Is there a way to find out how many numbers are at the end of a string without knowing the exact index?

Question: I have a method that extracts a certain substring from a string. This substring consists of the numbers in the string. Then this is parsed to an integer.
Method:
protected int startIndex() throws Exception {
    String str = getWorkBook().getDefinedName("XYZ");
    String sStr = str.substring(10,13);

    return Integer.parseInt(sStr) - 1;
}

Example:
String :

'0 DB'!$B$460

subString :

460

Well, I manually entered the index range for the substring. But I would like to automate it.
My approach:
String str = getWorkBook().getDefinedName("XYZ");
int length = str.length();
String sStr = str.substring(length - 3, length);

This works well for this example.
Now there is the problem that the numbers at the end of the string can also be 4 or 5 digits. If that is the case, I naturally get a NullPointerException.
Is there a way or another approach to find out how many numbers are at the end of the string?
Answer: You can use the regex, (?<=\D)\d+$ which means one or more digits (i.e. \d+) from the end of the string, preceded by non-digits (i.e. \D).
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {
    public static void main(String[] args) {
        // Test
        System.out.println(getNumber("'0 DB'!$B$460"));
    }

    static String getNumber(String str) {
        Matcher matcher = Pattern.compile("(?<=\\D)\\d+$").matcher(str);
        if (matcher.find()) {
            return matcher.group();
        }

        // If no match is found, return the string itself
        return str;
    }
}

Answer: In your case I would recommend to use regex with replaceAll like this:
String sStr = str.replaceAll(".*?([0-9]+)$", "$1");

This will extract the all the digits in the end or your String or any length.
Also I think you are missing the case when there are no digit in your String, for that I would recommend to check your string before you convert it to an Integer.
String sStr = str.replaceAll(".*?([0-9]+)$", "$1");
if (!sStr.isEmpty()) {
    return Integer.parseInt(sStr) - 1;
}
return 0; // or any default value

Comment: Look at the example input `'0 DB'!$B$460` in the question. Your code returns `0460` instead of `460`. In this case because the first number is a `0` the parsed number will be the same, but if there is a number(s) different to 0 your code fails.
Comment: @Robert correct, I missed to add the `$` in the regex `.*?([0-9]+)$`, fix it.
Comment: So this works fine. Thanks for this new approach.
Comment: regex yes, but replaceAll may apply the regex multiple times on the search string (if there are multiple (blocks) of numbers present and in the end all numbers will be merged to one large number block.
Comment: @Robert honestly I don't get you, can you explain with an example please!
Answer: If I were going to do this I just search from the end.  This is quite efficient. It returns -1 if no positive number is found.  Other return options and the use of an OptionalInt could also be used.
String s = "'0 DB'!$B$460";
int i;
for (i = s.length(); i > 0 && Character.isDigit(s.charAt(i-1)); i--);
int vv = (i < s.length()) ? Integer.valueOf(s.substring(i)) : -1;
System.out.println(vv);

Prints
460

If you know that there will always be a number at the end you can forget the ternary (?:) above and just do the following:
int vv = Integer.valueOf(s.substring(i));

Answer: If you just want to get the last number, you can go through the entire string on revert and get the start index:
protected static int startIndex() {
    String str = getWorkBook().getDefinedName("XYZ");

    if(Character.isDigit(str.charAt(str.length() - 1))) {
        for(int i = str.length() - 1; i >= 0; i--){
            if(!Character.isDigit(str.charAt(i)))
                return i+1;
        }
    }
    return -1;
}

and then print it:
public static void main(String[] args)  {
    int start = startIndex();
    if(start != -1)
       System.out.println(getWorkBook().getDefinedName("XYZ").substring(start));
   else
      System.out.println("No Number found");
}

You will have to add the
Answer: Simple and fast solution without RegEx:
public class Main
{
    public static int getLastNumber(String str) {
        int index = str.length() - 1;
        while (index > 0 && Character.isDigit(str.charAt(index)))
            index--;

        return Integer.parseInt(str.substring(index + 1));
    }

    public static void main(String[] args) {
        final String text = "'0 DB'!$B$460";
        System.out.println(getLastNumber(text));
    }
}

The output will be:
460


Group proof with Modular arithmetic

Question: Let $G=\{1,2,3,4,5,6\}$ and we define an operation $*$ on $G$ by $a*b=ab$, the
remainder of $ab\bmod 7$.
For instance, $$2*4=8=1$$  $$5*6=30=2$$
I want to show that $(G, *)$ is a group.
I know how to show that is has a binary operation, so every result of the operation is inside $G$.
I also know how to prove the inverse. However, how to show that it is associative and has an identity element?
Comment: Chelivery : firstly it's $(\mathbb{Z}_7 ^*, \cdot)$ that's a group, and secondly, do you think that if OP knew that it was, he would be asking this question ? He obviously has just begun studying groups, and so it's a good exercise trying to prove precisely what you're telling him to use
Comment: For the identity, you need $a*e=e*a=a$ for all $a$ in $G$.  Can you think of which element of $G$ would satisfy that requirement?
Comment: For the associative property, you can use that ($\mathbb{Z}_7, \cdot)$ is a group in itself, so $(a \cdot b) \cdot c = a \cdot (b  \cdot c)$, ($mod \ 7$)
Comment: @chelivery what are you talking about? The element $0\in\Bbb Z_7$ doesn't have an inverse, so it's not a group under multiplication
Comment: Alex: you're right, I meant without the $0$ as Max corrected (I was thinking of the field). Also I guessed he already knew some examples of groups that he could use such as those.
Comment: would the identity element be just 1?
Comment: Right, very good.
Comment: I'm curious how you are happy to prove the inverse without knowing the identity.
Answer: To prove associativity, consider the fact that you are multiplying integers together and then reducing modulo 7 (in your words - finding the remainder).
The remainder will not change if you change the order of multiplication, because multiplication of integers is associative.
I believe your problem with the identity is solved in the comments.
EDIT: Your group is NOT a field. $\mathbb{Z}_7$ is different to the group which you describe.
Answer: This answer was incorrect, see the answer below
Comment: This answer is not correct. The group he describes is not what you say it is and it is definitely not a field.
Comment: It should form a field if we include the typical notion of addition, right? I made that change.
Comment: @TylerKharazi It needs the additive identity as well
Comment: Absolutely not right. It is simple enough to check the axioms of a field, and check that what OP describes does not satisfy all of them. You should remove your answer.
Comment: You're right. I can't delete the answer if it has been accepted though. I can edit out the field bit.

Group proof with Modular arithmetic


Problem with strong law of large numbers and sequence

Question: Show that ${X_n}$ is i.i.d and $E(X_1) = 1$ and $c_n$ is bounded real numbers
then $\frac{c_1 + ... + c_n}{n} \rightarrow 1$ if and only if $\frac{c_1X_1 + ... + c_nX_n}{n} \rightarrow 1$.
In the K.L. Chung A course in probability theory(3rd edition), there is hint s.t. truncate Xn at n and proceed as in Theorem 5.4.2(the Strong law of Large numbers).
But by separating integrals with the area of $j-1<|c_nX_n|<j$, since c_n can be 0 and cn is not same, applying the process of the proof of SLLN is not easy. Is there any another way to prove this?
--
Thank you for your answer. I solved it using another way.
As in the K.L.chung, define Yn = XnI(|xn| <= n), not Yn = anXn* I(|xn| <= n)
Then, the infinite sum of Var(anYn/n) converges similar to the proof of SLLN.
Answer: It is a consequence of the (usual) law of large numbers, that is, $S_n/n\to\mathbb E\left[X_1\right]$, where $S_n=\sum_{i=1}^nX_i$. Indeed,
\begin{align}
\frac 1n\sum_{i=1}^nc_iX_i  &=\frac{c_n}nS_n+\frac 1n\sum_{j=1}^{n-1}j\left(c_j-c_{j+1}\right)\frac{S_j}j\\
&=\frac{c_n}nS_n+\frac 1n\sum_{j=1}^{n-1}j\left(c_j-c_{j+1}\right)\left(\frac{S_j}j-1\right)+\frac 1n\sum_{j=1}^{n-1}j\left(c_j-c_{j+1}\right)\\
&=\frac{c_n}nS_n+\frac 1n\sum_{j=1}^{n-1}j\left(c_j-c_{j+1}\right)\left(\frac{S_j}j-1\right)+\frac 1n\sum_{j=1}^{n-1}j c_j -\frac 1n\sum_{j=2}^n\left(j-1\right)c_j   \\
&=\color{blue}{\frac{c_n}nS_n-\frac{n-1}nc_n   } +\frac 1n\sum_{j=1}^nc_j +\frac 1n\sum_{j=1}^{n-1}j\left(c_j-c_{j+1}\right)\left(\frac{S_j}j-1\right).
\end{align}
Now, the conclusion follows if we manage to show that

the blue term goes to zero and
if $\varepsilon_n\to 0$, then $\frac 1n\sum_{j=1}^{n-1}j\left(c_j-c_{j+1}\right)\varepsilon_n\to 0$.
Comment: Thank you for the answer! For the last term, I think that e_n should be replaced to e_ j. And I think this makes it hard. If it is a e_n for every j in the summation, the problem is quite easy because $\frac{c_1 + ... + c_n }{n}$ converges. But it is e_j, so, showing the last term converges to 0 is little bit hard( I tried $\frac 1n\sum_{j=1}^{n-1}j\left(c_j-c_{j+1}\right)\varepsilon_j$ <= $\frac 1n\sum_{j=1}^{n-1}|j|\left(|c_j-c_{j+1}|\right)|\varepsilon_j|$ ), but the existence of j makes it hard(changing the sum with $e_j-e_{j+1}$ doesn't help). Could you please explain a little bit more??


Use polar coordinates to compute volumes, via the change of variables theorem

Question: So there is a question in my Anaylis book (with 3 subquestions) that I think understand, but I can not seem to understand the approach used in the solution. I've tried all subquestions, and for each of them I seem to make a mistake somewhere. When I then look at the solution they approach it differently, and I don't understand why. The question goes:
Use polar coordinates to compute

the volume of the region enclosed by the $x y$ -plane and the paraboloid $z=25-x^{2}-y^{2}$;
$\int_{0}^{1} \int_{0}^{\sqrt{1-y^{2}}} \frac{1}{1+x^{2}+y^{2}} d x d y$;
the volume of $R=\left\{(x, y, z): 0 \leq z \leq \sqrt{4-x^{2}-y^{2}},(x-1)^{2}+y^{2} \leq 1\right\}$.

To solve this I take the following steps. I sketch the volumes to get an idea of the problem. I then create my new region in polar coordinates by transforming the constraints via $x=rcos\phi$ and $y=rsin\phi$ (for $\mathbb{R^2}$, for $\mathbb{R^3}$ they're different but I won't mention them). This transforming is hard (for me) and this always seems to give me incorrect boundaries for my integrals. Then once I have the right boundaries I rewrite my integral over the new region and multiply it by the absolute Jacobian of my polar coordinate functions, which in case of polar coordinates (in $\mathbb{R^2}$) is $r$. This is because of the change of variable theorem. Then I can integrate over $\phi$ and over $r$ one by one and compute my result.
These are the provided solutions:
1: approach 1
$$
\begin{aligned}
A &=\int_{0}^{2 \pi} d \varphi \int_{0}^{5} rdr\left(25-r^{2}\right) \\
&=\int_{0}^{2 \pi} 2 \varphi\left[\frac{25}{2} r^{2}-\frac{1}{4} r^{4}\right]_{0}^{5} \\
&=2 \pi\left(\frac{5^{4}-5^{4}}{4}\right)=\frac{1}{2} \pi 5^{4} \\
&=\frac{625}{2} \pi
\end{aligned}
$$

approach 2:
$$
\begin{array}{l}
x^{2}+y^{2}=r^{2} \\
\int_{0}^{25} d z\left(\int_{x^{2}+y^{2} \leq 25-z}d x d y\right)= \\
\int_{0}^{25} d z(\pi \cdot(25-z))= \\
\pi \cdot\left[25 z-\frac{1}{2} z^{2}\right]_{0}^{25}= \\
\pi \cdot\left(25^{2}-\frac{1}{2} 25^{2}\right)=\frac{1}{2}(25)^{2} \cdot \pi \\
=312\frac{1}{2} \pi
\end{array}
$$

\begin{aligned}
& \int_{0}^{\pi / 2} d \varphi \int_{0}^{1} rdr\left(\frac{1}{1+r^{2}}\right) \\
=& \int_{0}^{\pi / 2} d \varphi\left[\ln \left(1+r^{2}\right)\right]_{0}^{1} \\
=& \frac{\pi}{2} \cdot \ln (2)
\end{aligned}
3.
\begin{array}{l}
\sqrt{4 x^{2}-y^{2}}=\sqrt{4-r^{2}} \\
(x-1)^{2}+y^{2} \leq 1 \Leftrightarrow \\
x^{2}-2 x+1+y^{2} \leq 1 \\
x^{2}+y^{2} \leq 2 x \\
r^{2} \leq 2+\cos \varphi \\
r \leq 2 \cos \varphi
\end{array}
\begin{array}{l}
\text { So Vol}(R)= \\
\int_{-\pi / 2}^{+\pi / 2} \int_{r=0}^{2 \cos \varphi} r d r(\sqrt{4-r^{2}})=
\end{array}
\begin{array}{l}
=\int_{-\pi / 2}^{\pi / 2} d \varphi\left[-\frac{1}{3}(4-r^2)^{3 / 2}\right]_{0}^{2 \cos \varphi} \\
=\int_{-\pi / 2}^{\pi / 2} d \varphi\left(4 / 3-\frac{8}{3}\left(1-\cos ^{2} \varphi\right)^{3 / 2}\right) \\
=\int_{-\pi / 2}^{\pi / 2} d \varphi\left(4 / 3-\frac{8}{3}|\sin \varphi|^{3}\right) \\
=2 \cdot \int_{0}^{\pi / 2} d \varphi\left(4 / 3-\frac{8}{3} \sin ^{3} \varphi\right) \\
=2 \cdot\left(\frac{4}{6} \pi-8 / 3-8 / 9\right)=\frac{4}{3} \pi-\frac{32}{9}
\end{array}
I hope I scanned/typed the solutions correctly.
My question goes:

Can anyone explain the steps taken to get to the boundaries in parts 1, 2 and 3?
Where does the $r$ go in part 2 which states $rdr$ right before it is integrated?

I hope I have explained everything clearly. Cheers!
Answer: I would usually get the bounds for polar coordinates by sketching the shape of the region of integration and looking for a polar equation.
In case 1 the region is a disk centered at the origin and in case 2 it's a quarter of a disk centered at the origin;
so the limits for $r$ run from $0$ (at the origin) to the radius of the disk,
and the limits for $\phi$ run all the way round the disk in case 1
and just one-quarter of the way around in case 2.
In case 3 you have a disk with the origin on the circumference.
You might happen to recall that the polar equation of the circle bounding that disk is $r = 2\cos\phi.$
To "cover" the area of the disk, you need to integrate along the radials in all directions to the right of the origin: everything between $-\frac\pi2$ and $0$ to cover the region below the $x$ axis,
and $0$ to $\frac\pi2$ to cover the region above the $x$ axis.
In part 2, the $r$ didn't "go" anywhere, or you might say it "went" to the same place as the $1/(1+r^2)$.
The solution requires evaluating an integral in $r,$
$$
\int r \,dr\left(\frac1{1+r^2}\right)
= \int \left(\frac r{1+r^2}\right) dr
= \frac12\ln(1+r^2).
$$
Note that the given "solution" omitted the factor $\frac12.$
The "solution" provided is therefore twice as large as the correct answer.
Comment: This was very helpful, thank you!
I now see that $\frac{d}{dr}(\frac{1}{2}ln(1+r^2)) = \frac{r}{1+r^2}$, thanks! It seems that the $\frac{1}{2}$ was indeed forgotten. The book also mentions $\frac{\pi}{4} ln(2)$ as the correct solution. Thank you!


c# what takes processing time?

Question: I'm doing a program for video processing in which the time is very critical. I'm not having any difficulties in the program, but I would like to know from you, what things in coding takes most processing time? loops? if statements? goto statements ? functions? writing/reading text files ? other things? my program contains alot of each on of the above, and i would like to know which things take the most time so that I can try to minimize the time ( even 1 second matter in my application )
Comment: This is not the right way to figure out where performance issues will arise.  Use a profiler instead.
Comment: All of those take time.  Get a good performance profiler, see what the slowest spots are, then tackle those.
Comment: You may find this interesting: http://www.eecs.berkeley.edu/~rcs/research/interactive_latency.html
Answer: It is impossible to give a precise answer using the data above. It most likely will be in some library calls to the video processing library, but this is just guesswork.
The only sensible answer is therefore: Use a profiler to find out where exactly your program spents it's time.
A profiler is a program that analyzes your program and determines where it spends its time.
Comment: The redgate profiler is easy to use and has a 30 day trial. Link: http://www.red-gate.com/products/dotnet-development/ants-performance-profiler/
Comment: would you tell me what a profiler is ? if you would provide me with some usefull links, it is really my first time to hear about that
Comment: Another good indicator of potential performance bottleneck are subroutines with high growth rates. Look into [Big O Notation](http://stackoverflow.com/questions/487258/plain-english-explanation-of-big-o).
Answer: I agree about using the profiler. In some cases using the profiler might slow the program too much or take too much memory. in such cases an informed use of time measurment using:  StopWatch
might do the trick.

c# what takes processing time?


AS2 - terminate interval on main stage frame from movie clip on stage

Question: Hi,
I have an interval running within a function on the main stage, frame 1.  Where "foo" calls "bar" every 1ms using interval "timerCollapse" like so-
function foo() : Void {
var timerCollapse :Number= setInterval(bar, 1);
}

function bar() : Void {
trace("test");
}

Also tried using an undeclared method for the above like so-
timerCollapse = setInterval(bar, 1);

Then I have a clip on the stage that I would like to tell that interval to stop.  Below are the various methods tried but I cannot figure out how to stop the interval from another clip.
clearInterval(timerCollapse);       //does nothing
clearInterval(_root.timerCollapse); //does nothing
_root.clearInterval(timerCollapse); //does nothing

Any thoughts on how to kill that interval?
Many thanks :)
Comment: You have a scope issue, see a similar thread: http://stackoverflow.com/questions/1261977/how-does-one-break-out-of-a-set-interval-in-action-script-2
Answer: The easiest would be to do somethign like the following:
framescript:
var myInterval;

function startMyInterval() {
    myInterval = setInterval(update, 1000);
}

function update() {
    trace('hi');
}

button in a movie clip
on(release) {
    clearInterval(_root.myInterval);
}

call startMyInterval from wherever.
Comment: @cheeseomelete (great handle btw) did you get the above integrated successfully?
Comment: hah thanks, all the good names were taken :)  I adapted the button code you have there to do it directly when it hit that specific frame and that did it!  Thanks!
Comment: also by declaring the interval ID properly as you have here so it knew what to clobber.


Finding a source for the definition of "clustering accuracy"

Question: In papers about unsupervised clustering I see a lot of references to a metric "clustering accuracy" or "unsupervised clustering accuracy" (ACC) which is usually defined as something like:
$$
ACC(x,y) = \frac{1}{N} \max_{m}\sum^{N}_{i=1}1(m(x_i) = y_i)
$$
where m is all possible permutations of the x and y. I think the 1 is something like the dirac-delta function but I'm not sure. Most papers I have seen also mention that the mapping can be solved using the Kuhn–Munkres algorithm.
But I can't find an original source for the definition of this metric. Most papers I read reference other recent papers which are using ACC but are not the source defining it. Others don't reference the formula at all (while they do reference the formula for NMI for example).  I saw one paper that referenced a book "Matching Theory" but I couldn't find this mentioned in that either (though I searched for it through the PDF).
When I google it or search for it here I get results about clustering accuracy in general. It doesn't even appear to have a Wikipedia article which like other metrics do.
What I'm looking for is a source about about this metric, whether it has some other name which is why I can't find it, and an explanation of it and how it differs from other metrics.
Comment: Easy.  Many clustering methods will find clusters even when the data represent pure noise.  When such raw data have wide distributions, the found clusters are often extremely large and virtually meaningless.  The fact that something is labeled as a cluster by an algorithm does not make it a cluster.
Comment: I don't see how data used to develop clusters can be used to assess cluster "accuracy".  Instead I'd spend time verifying that the clusters are really clusters, i.e., that they are compact sets and satisfy (1) distance from cluster centers are not informative once cluster labels are defined and (2) no observation in a cluster is closer to an observation in another cluster than it is to the observations in its "own" cluster.  People frequently build clusters that are not compact and they turn out to not be so useful, and to hide heterogeneity.
Comment: Are you sure this is "unsupervised"? Is $y$ not a cluster label? You might need to provide some more details here.
Comment: Instead of answering the question, I would suggest to you to read a short overview of the external cluster validity indices. https://stats.stackexchange.com/q/586470/3277
Comment: @FrankHarrell With a finite number of points, how can there be a lack of compactness?
Comment: Thank you all for your discussion so far. @Eoin is correct that the $y$ is the true cluster label, or another clustering that we are comparing to. However this is called "unsupervised clustering accuracy" or "clustering accuracy" in the papers I have read, so I'm looking for a source of where it comes from. Other metrics like ARI which are common to clustering also need the cluster labels to be available, the different is that they are agnostic to what class elements are put in as long as elements of each true cluster are put in the same together.
Comment: @ttnphns Thanks for your comment. I'm aware of external cluster validity indices, I'm looking for the source of this particular one that I see often reference.
Answer: Given your definition (and the clarification in the comments), $\text{ACC}(x, y)$ is just the proportion of cases where the predicted cluster label, $m(x)$, matches the ground truth label $y$, with the added twist that you take the maximum over possible cluster label permutations to account for the possibility you've ended up with the labels the wrong way around. This is a pretty elementary idea, so I wouldn't expect a source or reference for it.


Buscando dados em outro Schema do banco usando o createQuery

Question: No postgres, podemos buscar dados em vários schemas através do sql mesmo.
Fazendo assim:
SELECT * FROM meu_schema.minha_tabela

É possível fazer isso utilizando o createQuery?
Por padrão, minha aplicação está utilizando o schema public, mas queria fazer uma busca em outro schema em determinado método.
Algo parecido como:
Query query = entityManager.createQuery("SELECT s FROM schema2.Simulacao s");

Answer: Você deve criar um EntityManagerFactory e EntityManager  para cada esquema.
Ex.
javax.persistence.Persistence.createEntityManagerFactory esquema1 = javax.persistence.Persistence.createEntityManagerFactory("Esquema_1");
javax.persistence.Persistence.createEntityManagerFactory esquema2 = javax.persistence.Persistence.createEntityManagerFactory("Esquema_2");

EntityManager em1 = esquema1.createEntityManager();
EntityManager em2 = esquema2.createEntityManager();

Query query1 = em1.createQuery("SELECT s FROM Simulacao s");
Query query2 = em2.createQuery("SELECT s FROM Simulacao s");


Performing a biserial correlation on SPSS v21

Question: I have a set of data in which the response variable is continuous and the other independent variables are dichotomous (not naturally occurring).
I think I have to perform Biserial correlation (I an aware of the difference between point biserial and biserial correlation).
How can I do this on SPSS or any other statistical software?
Comment: Please visit my web-page. In "Various proximities" you will find computation of biserial as well as point-biserial correlations.
Comment: If you have a dependent and an independent variable, then why not use regression?
Answer: If you are looking for "Point-Biserial" correlation coefficient, just find the Pearson correlation coefficient. In SPSS, click Analyze -> Correlate -> Bivariate. The rest is pretty easy to follow. Computationally the point biserial correlation and the Pearson correlation are the same.
Comment: _Are you sure_ the biserial correlation was introduced in version 21?
Comment: I stand corrected. What I meant was the "Point-Bieserial" correlation coefficient.


periodically check value of UITextField

Question: I have a scanner that is reading text into a UITextField, looks like it is one character at a time.  So every 1/2 second or so I want to check the value of that UITextField so I can grab the value.
Comment: I ended up using a combination, once text editing was started I kicked off a timer that fired in 1 second.  That one second gave my scanner plenty of time to read in the data.  Once the timer fired I set it to nil and cleared the text field that the scanner populated.  If editing started again the whole process started over - works like a charm.
Answer: Two options:
1) Set the text field's delegate, then catch the changes as they happen in the shouldChangeCharactersInRange method of said delegate.
2) Use an NSTimer object.
In most situations, the first method is superior, but if you want to check every so often rather than catching the changes as they happen, you will need the NSTimer.
Answer: I think there is a better method than the ones William stated, although both will work.
The best option would be to set the UIControlEventEditingChanged event to an action. For example:
<code>[textField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
</code>
This will call the method:
<code>- (void)textFieldDidChange:(id)sender { }
</code>
everytime that the text field changes. Make sure you also declare the method in your interface. The statements that you put in between the { } (curly brackets) will be performed for every change in text.
If however you do really want to check the value of the text box periodically and not just on change, you can use the following code:
<code>[NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(textFieldDidChange) userInfo:nil repeats:YES];
</code>
-Dan

periodically check value of UITextField


Serviço sendo carregando null no controller

Question: Ao realizar um post para o meu controller, ao debugar, vi que o serviço o qual carrego no meu construtor, está vindo o tipo null.
Controller:
public class UserController : ApiController
{
    private static IUserService _userService;

    public UserController(IUserService userService)
    {
        _userService = userService;
    }

    [System.Web.Http.HttpGet]
    public IHttpActionResult GetUserById(long id)
    {
        var user = _userService.GetById(id);
        return Ok(user);
    }

    [HttpPost]
    [Route("api/User/Insert")]
    public IHttpActionResult Insert(User user)
    {
        user.StartDate = DateTime.Now;
        _userService.Register(user);

        return Ok();
    }
}

Retorno de erro do debbug:

Controller' não tem um construtor padrão","Exception Type":"System.ArgumentException","StackTrace"
Comment: Qual a estratégia de injeção de dependência que você usa?
Comment: Você inicializa o `UserController` em algum momento?
Comment: @DiegoRafaelSouza Estava tentando injetar na WebApiConfig.cs, mas foi sem sucesso. Então, é nenhuma.
Comment: Então, sem jeito de dar certo a menos que você declare o tal construtor padrão, tipo assim: `public UserController() : this(new UserServiceImplementation()) { }`
Comment: Dessa forma não funciona.
Answer: Você pode inicializar seu serviço no construtor default do seu Controller:
public class UserController : ApiController
{
    private IUserService _userService;

    public UserController()
    {
        _userService =  new UserService();
    }

    public UserController(IUserService userService)
    {
        _userService = userService;
    }

    [System.Web.Http.HttpGet]
    public IHttpActionResult GetUserById(long id)
    {
        var user = _userService.GetById(id);
        return Ok(user);
    }

    [HttpPost]
    [Route("api/User/Insert")]
    public IHttpActionResult Insert(User user)
    {
        user.StartDate = DateTime.Now;
        _userService.Register(user);

        return Ok();
    }
}

Caso você tenha interesse em utilizar alguma estratégia de injeção de dependência, existem alguns container's muito úteis atualmente. Entre eles existem o Unity e Ninject. Abaixo um exemplo de alguém que teve o mesmo problema que você e o caso dele é tratado com Ninject. Segue link: Ninject para Injeção de Dependência


Outlier Detection using OutlierTest

Question: I found an outlier using the outlierTest function in the car package. However, I can see from the results that the Externally Studentized Residual and p-values. This is a result for the full model.
    rstudent unadjusted p-value Bonferroni p
348 5.872682         7.9377e-09   3.9689e-06

Cooks D Bar Plot:

I have performed normality test on residuals using the following code:
shapiro.test(resid(housing.lm))

R Console:
Shapiro-Wilk normality test

data:  resid(housing.lm)
W = 0.97068, p-value = 1.876e-08

The p-value is less than 0.05 indicating that the residuals may not be normally distributed. However, I assume it  is not critical for linear regression as long as the other assumptions are met.
I have also performed heteroscedasticity test using the following code:
ncvTest(housing.lm)

R console:
Non-constant Variance Score Test
Variance formula: ~ fitted.values
Chisquare = 0.3243994, Df = 1, p = 0.56898

When I fit the regression using the coded:
lm(price~ bath + sqft, data=data)

My diagnostic plots looks as follows;

When try to remove observation 348 based on the p-value sqft variable becomes insignificant.
Is it better to keep it since it seems an influential point?
Comment: Well, at least it's telling you that that one data point has a big influence on your conclusions.
Comment: @SalMangiafico yeah but how I can I figure out if it is in a good or bad way? :)
Comment: Thank you for adding the residual plots.
Answer: In general, you shouldn't remove outliers unless you know that the data point is wrong or impossible or otherwise objectionable in reality.
Using methods to detect outliers is useful to find data that may require some double-checking or additional scrutiny.
However, in this case, that one data point appears to be so far out from the rest of the data set (with n > 300).
One approach is to use a robust method that won't be as affected by this one point.
In this case, your model is simple enough that I'm sure you can see what effect that one point has on the results. I mean by examining simple plots of the dependent variable vs. each independent variable.
I can't make a conclusion without seeing all the data, and understanding what it is that you are trying to model (and why !). But I think if your conclusion is that this one point should be removed so as not to bias the results (in the colloquial sense), that may be a reasonable approach. One large, expensive house in the data set may influence the results to suggest that sqft has a large effect on price, when it doesn't for the rest of the 300 + data points.
If you choose to remove this point, be sure to state this in your results and explain why. It may simply be that you remove the one observation with sqft > X because it's not representative of the rest of the rest of the population.

Outlier Detection using OutlierTest


How to extract news content from a web page using Boilerpipe?

Question: I need to extract main news content from a web page.I searched on internet and found an api named Boilerpipe freely available for that purpose http://boilerpipe-web.appspot.com/ But I'm not abled to find any implementations in java that make use of Boilerpipe.Can anyone tell me how can I use Boilerpipe in Java to extract the news content or give me some links to implementations in java which make use of Boilerpipe to extract content from a news web page?
Comment: Have you considered using a library like Jsoup?  http://jsoup.org/  Do you have a specific website you are trying to scrape?
Answer: may be my answer is too late. But it's pretty simple.
<code> URL url = new URL("http://www.nydailynews.com/sports/baseball");
 ArticleExtractor ae = new ArticleExtractor();
 String content = ae.getText(url);  // this contains the final text
</code>
Answer: simple huh,
suppose you need to extract this URL
just use my BoilerPipe Alternative Web API HERE,
my service is based on boilerpipe,i have developed this because of getting overquota error in the original application..you have the option to get back the result in JSON,just consume it in your application..
Best Regards


is there a way to hide a "custom field" in edit mode Drupal 8?

Question: I have a form with 5 custom fields. I would like to hide a couple of fields based on the view mode in the back-end while the user is editing the form.  Right now you can easily hide the field in the front end, but i am looking for way to not confuse the editors and hide the form fields while they are making changes.
Disable fields still show up in the back-end.
My goal is simple: if your view mode has the field disable it should not show up in the back-end and in the front end.
is there a setting or a hook that can allow me to accomplish that.
Comment: Would setting field permissions work?
Answer: Making this based if it's printed on a view mode, makes things quite complex. You'll have to write a custom module.
Try using the Fields Permissions which is based on Roles. So just check mark the Roles that should be able to see the field in the front.


Replace certain values in pandas dataframe with mode of that row

Question: I have a DataFrame like this:
ColA      ColB  ColC  ColD  ColE

Male       1     0     ?     1
Female     1     1     ?     1
Male       0     0     0     1
Female     1     0     0     ?
Female     1     1     1     ?

It has a number of ? throughout. I'd like to replace these with the mode (most common value of each row) - excluding the first column.
I've done something like this, but doesn't return what I want:
df.replace("?", np.nan, inplace = True)
df_new = df.apply(lambda row: row.fillna(row[1:].mode()), axis = 1)

Answer: For fillna we can only fillna with column with series, so we need T, and for the mode we can do outside the apply
df_new = df.T.fillna(df.iloc[:,1:].astype(float).mode(axis=1)[0]).T
df_new
     ColA ColB ColC ColD ColE
0    Male    1    0  1.0    1
1  Female    1    1  1.0    1
2    Male    0    0    0    1
3  Female    1    0    0  0.0
4  Female    1    1    1  1.0


Area under the curve (Integration)

Question: For this question:

I have found the limits to be $(-k)^{\frac{1}{2}} , 0 , k^{\frac{1}{2}}$
but the trouble I'm having is how do I know what graph I should minus from each other. So for area a , do I do $f(x) - g(x)$ , or $g(x) - f(x)$.
Is there a trick$?$
Comment: If your geometric reasoning fails you, you could try both and see which gives you a positive number.
Comment: Is there a trick tho , from just looking at the graph?
Answer: The area bound by two curves, $f(x),g(x)$ on $[a,b]$ is $$Area=\int_a^b|f(x)-g(x)|dx$$ In order to evaluate this integral, you need to do something to get rid of the absolute values (usually) and so the way we accomplish this is by using the piecewise definition of $|\cdot|$. We break this integral up into sub-integrals based on the points at which $|\cdot|$ changes sign. After identifying the points $\{c_1,\cdots,c_n\}$ at which $|f(x)-g(x)|$ changes sign, we can write $$\int_a^{c_1}|f(x)-g(x)|dx+\int_{c_1}^{c_2}|f(x)-g(x)|dx+\cdots+\int_{c_n}^b|f(x)-g(x)|dx$$
Now, when we look at these integrals, we know that the sign of $f(x)-g(x)$ is constant for each integral, so we can drop the $|\cdot|$ by simply making sure the functions are being subtracted in the right order, i.e. the order that makes the difference positive. You've already broken it up correctly, so you just need to identify which function is larger on which interval and subtract the smaller function from the larger one. From just looking at the graph, you simply pick the one higher up on the y-axis.
Comment: It should also be mentioned that you can tell which line is which by by noting the difference in appearance between quadratics and cubics (the quadratic has one hump, the cubic has two)
Answer: Notice that
$$
g(x)=x^3-kx+f(x),
$$
therefore the equation
$$
f(x)=g(x)\tag{1}
$$
is equivalent to
$$
x^3-kx=0 \tag{2}
$$
The solutions of (2) are
$$
-\sqrt{k},0,\sqrt{k}.
$$
Because $f(x)\ge g(x)$ for $-\sqrt{k}\le x\le 0$, and $g(x)\ge f(x)$ for $0\le x\le \sqrt{x}$, we have
$$
A=\int_{-\sqrt{k}}^{0}[g(x)-f(x)]\,dx,\quad B=\int_{0}^{\sqrt{k}}[f(x)-g(x)]\,dx.
$$
Since $g(x)-f(x)=x^3-kx$ is an odd function, we have
\begin{eqnarray}
0&=&\int_{-\sqrt{k}}^{\sqrt{k}}[g(x)-f(x)]\,dx\\
 &=&\int_{-\sqrt{k}}^{\sqrt{k}}[g(x)-f(x)]\,dx\\
&=&\int_{-\sqrt{k}}^{0}[g(x)-f(x)]\,dx+\int_{0}^{\sqrt{k}}[g(x)-f(x)]\,dx\\
&=&\int_{-\sqrt{k}}^{0}[g(x)-f(x)]\,dx-\int_{0}^{\sqrt{k}}[f(x)-g(x)]\,dx\\
&=&A-B
\end{eqnarray}
It follows that
$$
A=B=\int_{0}^{\sqrt{k}}(kx-x^3)\,dx=\frac{1}{2}kx^2-\frac{1}{4}x^4\Big|_{0}^{\sqrt{k}}=\frac{1}{4}k^2
$$

Area under the curve (Integration)


Find all maximal ideals of the ring $\mathbb Z[i]$ containing the ideal $I=(4-2i) \mathbb Z[i] + (9+3i) \mathbb Z[i]$

Question:
Find all maximal ideals of the ring $\mathbb Z[i]$ containing the ideal $I=(4-2i) \mathbb Z[i] + (9+3i) \mathbb Z[i]$

I think that in this task I need to find gcd first:
$$4-2i=2(2-i)=(1-i)(1+i)(2-i)$$
$$9+3i=3(3+i)=3(1+i)(2-i)$$
$$\text{gcd}(4-2i,9+3i) ∼ (1+i)(2-i)=3+i$$
However, I don't know what I can do next.
Answer: Hint: $\mathbb Z[i]$ is a PID. In a PID, to divide is to contain. Thus $(1+i)(2-i)=3+i$ gives
$$
\langle 1+i \rangle \supseteq \langle 3+i \rangle,
\quad
\langle 2-i \rangle \supseteq \langle 3+i \rangle
$$
Comment: @timofiej8384, yes, exactly. But you must argue that $\langle 1+i \rangle$ and $\langle 2-i \rangle$ are maximal ideals. Not hard, since you know all the divisors of $ 3+i$.
Comment: Ok, so to sum up - the full procedure in this task is as follows: 1) we are looking for $\text{gcd}(4-2i,9+3i)$ and geting $3+i$ 2) thanks to $\text{gcd}$ we know that $I$ is generated by $3+i$: $I=\langle 3+i \rangle$ 3) using the fact the $\mathbb Z[i]$ is PID we know that: a is irreducible element in PID $\Leftrightarrow aR$ maximal ideal in PID 4) knowing that $\langle 1+i \rangle \supseteq \langle 3+i \rangle,
\quad
\langle 2-i \rangle \supseteq \langle 3+i \rangle$ and using 3) we have that solution are $I_1=\langle 2-i \rangle, I_2= \langle 1+i \rangle$.
Comment: Is it correct? Did I understand everything correctly?


Validação de um campo em um formulario REGEX

Question: Bom dia,
Estou com o seguinte problema:
Possuo um regex que valida as seguintes situações:
Não conter ponto, espaço, acentos e/ou letras maiúsculas
"^[a-z0-9]*$"
Queria incluir também para que não permitisse numeros apenas como primeiro caractere, como poderia fazer isso?
Answer: Pode montar a regex em duas parte, a primeira que especifica que o primeiro caracter deve ser uma letra minúscula (<code>^[a-z]+</code>) e a segunda que o demais podem ser tanto números quanto letras.
<code>^[a-z]+[0-9a-z]*$
</code>
Comment: Show, era exatamente isso que precisava, muito obrigado!


Add flag counter in views Module(Search API index)

Question: I want to add flag counter of content in views field. Authenticated users can flag(bookmark) contents. I want to know how many users flaged a content, And I want to add this in views field(display the number of times a node is flagged by a certain flag by Users).
Notice; I'm using "Search API Index" in content part of views
How can I do it?

UPDATE Question after using Vicky8888 method;
I added below code in global php field of views
   <?php
   $flag = flag_get_flag('bookmarks');
   if ($flag) {
  print "Number of Flags:";
  print $flag->get_count($node->nid);
      }
    ?>

this code work in tpl.php file of content type, But It's showing "0" in views.
I got several errors in picture too.

after that I using JS code of Vicky8888.
Drupal.behaviors.your-theme = {

 attach: function (context, settings) {

 //add your available class below
    jQuery('.view-id-top_users.view-display-id-page .views-field-php .flag-link-toggle').click(function(){

        jQuery(document).ajaxComplete(function() {
         location.reload();
        });
       });
      }
       };

I cleared "your-theme" and added "adaptivetheme", and cleared classes and added
".view-content .views-field.views-field-php .field-content .flag-link-toggle".
after that I using this code in separate file and added
scripts[]=scripts/extracode.js

in adaptivetheme.info file.
I cleared cache and run cron too.
but It didn't work too.
Answer: Use these two modules drupal like and flag simultaneously
Go to /admin/structure/flags create flag ,and  configure it properly.
Go to your view add  Global: PHP field
 <?php
print flag_create_link('bookmarks',$node->nid);

 $counts = flag_get_counts('node', $node->nid);
if(isset($counts['bookmarks'])){
 echo $counts['bookmarks'] .' Likes';
 }else{
      echo"no user flaged a content";
     }

 ?>

And at last put this code in your themes js file
Drupal.behaviors.your-theme = {

 attach: function (context, settings) {

 //add your available class below
    jQuery('.view-id-top_users.view-display-id-page .views-field-php .flag-link-toggle').click(function(){

        jQuery(document).ajaxComplete(function() {
         location.reload();
        });
       });
      }
       };

To add the flag link in your content type use code:
   <?php
    global $user ,$base_url;
    if(!$user->uid) {
   $flag_link = flag_flag_link($flag, $action, $content_id);

   $flag_url = $flag_link['href'];
    if(isset($flag_link['query']['token'])) {

    $flag_url .= '?'.$flag_link['query']['token'];
}

?>

  <a href="<?php echo $base_url;?>/user/login?destination=<?php echo      current_path();?>">MY-LINK

Comment: unfortunately It's didn't work for me. but when I'm using below code, It's work but always shows "0" flag.   get_count($node->nid);
}
?>   . This Code work when I using It in tpl.php file of content type but It didn't work in Views. I mean this code in tpl.php file shows number of flags but in views only shows "0".
Comment: i have the solution and i knows why its showing 0
Comment: Dear @vicky8888 I edited my question
Comment: use the exact code whatever i editted and then let me know,forget your code whatever you written for some time
Comment: if still it dont work then it may b issue of search api or it may be doing some mistake while configuring modules
Comment: I'm using your codes without any change. Exactly your codes. It doesn't work unfortunately. am I need to change Some values of your codes? please tell me about js code. how can i use it? where I should use it? Thank You.


non linear codes

Question: hello everybody im taking a course in nonlinear codes next semester and in order to be prepared as best as i can im trying to solve an home exercise given to us to be done by the semesters opening. Im writing here the questions i didn't succeed, these exercises are about constant weight codes, linear cyclic codes and a bit of combinatorics
1.Let $\Phi={(C_1,C_2,...)}$ be a set of linear codes over a finite field  $F_q$, all of length $n$ and dimension $k$. assume every non zero vector $v \in F_q^n $ is contained in the same number of codes from $\Phi$. Prove that if $$\sum_{i=1}^{d-1} {{n \choose i}(q-1)^i} < \frac{q^n-1}{q^k-1}$$
then $\Phi$ contains a code with minimum distance at least $d$.

$n$ and $q$ are positive integers such that $\gcd(n,q)=1 $. Fix a polonymial $g(x)$, wich we shall use as a generator polynomial to constuct a cyclic code over $F_q$ of length $n$. Prove that we can pick $n$ such that the resulting cyclic code has a minimum distance at most 2, regardless of the choice of $g(x)$.

for the second question i tried to use the fact that $g(x)$ have only simple roots in their splitting field but im not sure how to connect it to a upper bound for the code
ill appreciate any help, clues or guidance
thanks
Comment: the left side is the size of a ball of radius d-1 over F_q correct? for the right side i tried to look at it as portion of two field sizes but didnt succeed to advance with that
Comment: The "geometric" interpretation of the inequality is as follows. If $B$ is some set, another set $A$ is called a *packing* if $a+B \cap a'+B= \emptyset$ for all $a,a'\in A$, or equivalently $|A+B| = |A||B|$, where $+$ here is the minkowski sum/sumset. Your inequality can therefore be written as $|\mathbb{F}_q^k\setminus \{0\}| |B_0(d-1)| < |\mathbb{F}_q^n\setminus\{0\}|$ where $B_0(d-1)$ is the Hamming ball you describe. Can you rewrite this in terms of packings? And what can you say about the minimum distance of a packing of Hamming balls?
Comment: For the first problem, do you have any geometric intuition for what either of the quantities in the inequality correspond to? At least the quantity on the left-hand side has a geometrically simple meaning that I encourage you to try to think about.
Comment: i tried to go in this way but didnt succeed to advance further than you described, i tried also to use the code anticode bound but im really not sure about what i wrote, also i tried to use the hamming ball to describe an anticode with $d_max<2(d-1)$. can you please expand your answer? also im nut sure how to use the analogy of packing wich set is $A$ and wich is $B$? in order to use it i need to define them such that the intersection will be empty
Comment: Looking more carefully, it seems that I misread the upper summation index to be $(d-1)/2$. If this were the case, the proof would follow exactly the same proof as the Hamming bound, which is what I was alluding to. Without this condition, you probably instead need to leverage the condition that "every non-zero vector is contained in the same number of codes...".
Comment: The standard argument (at least for the case of Euclidean lattices, which should be similar) is to look at fixed $v\in\mathbb{F}_q^n\setminus\{0\}$, look at $\Pr_{C_i\gets \Phi}[v\in C_i]$ where the choice of $C_i$ is uniform, and then union bound over $v$ in a suitable Hamming ball and take complements to lower bound the probability that some $C_i$ doesn't contain a "short" $v$ (which is precisely lower bounding the minimum distance). Hopefully the inequality you are given is such that this argument works, but I haven't checked.
Comment: thank you very much for your answers, i didnt understand what probability you are meaning and what it means union bound over $v$ and what complements to take in order to lower the bound' i also tried to describe the problem as a steiner system bu i dont think this is the way
Answer: Writing up a slightly more complete (but still not complete) sketch of an answer I mentioned in the comments.
A key question you should ask yourself (and a hint towards this kind of solution) is

Why am I given a collection $\Phi = (C_1,\dots, C_\ell)$ of codes, rather than a single one?

Generally, this is because you are expected to use some "probabilistic argument", meaning prove some statement of the form
$$\Pr_{C_i \gets \Phi}[C_i\text{ has minimum distance }\geq d] > 0$$
If the probability is strictly positive, at least one $C_i$ must have the property, even if you don't know which.
It's also worth mentioning the precise distribution on $\Phi$ you choose doesn't matter provided you can get the above argument to work, but when $\Phi$ is finite the uniform distribution is of course the "most obvious" choice.
Now, a key perspective in (a similar argument to this in the world of Euclidean lattices) is noticing that

A code $C_i$ has minimum distance $\geq d$ iff $\forall v\in B_0(d-1)\setminus\{0\}$, $v\not\in C_i$.

Returning to the probability we want to lower-bound, we have that
\begin{align*}
\Pr_{C_i \gets \Phi}[C_i\text{ has minimum distance }\geq d] &= \Pr_{C_i \gets \Phi}[\forall v\in B_0(d-1)\setminus\{0\}, v\not\in C_i]\\
&= 1 - \Pr_{C_i \gets \Phi}[\exists v\in B_0(d-1)\setminus\{0\}, v\in C_i]\\
&\geq 1 - \mathsf{vol}(B_0(d-1)\setminus\{0\})\max_{v\in B_0(d-1)\setminus\{0\}}\Pr_{C_i \gets \Phi}[ v\in C_i].
\end{align*}
Here, in the first equality, we simply apply the above characterization of minimum distance.
In the second inequality, we take complements, and in the third inequality, we apply the "union bound"
$$\Pr[\exists x\in A : T(x)] \leq \sum_{x\in A}\Pr[T(x)] \leq |A|\max_{x\in A}\Pr[T(x)]$$
where $T(x)$ is an arbitrary predicate.
Technically the first inequality is the union bound, but I use the second as well so I describe it anyway.
Anyway, we are trying to lower bound our probability by $>0$ strictly.
It therefore suffices to show that
$$\frac{1}{\mathsf{vol}(B_0(d-1)\setminus\{0\})} > \max_{v\in B_0(d-1)\setminus\{0\}}\Pr_{C_i \gets \Phi}[ v\in C_i].$$
Establishing this bound on $\Pr_{C_i \gets \Phi}[ v\in C_i]$ is what I meant by bounding the probability that $v\in C_i$.
From the inequality you are given, it suffices to show that
$$\max_{v\in B_0(d-1)\setminus\{0\}}\Pr_{C_i \gets \Phi}[ v\in C_i] \leq \frac{q^k-1}{q^n-1} = \frac{|\mathbb{F}_q^k\setminus\{0\}|}{|\mathbb{F}_q^n\setminus\{0\}|}.$$
In particular, you have to show that the codes you have are "uniformly random" in a certain sense --- the probability they contain any non-zero point is precisely the cardinality of their non-zero points (as they are rank $k$), divided by the total number of $n$-dimensional non-zero points.
It would be quite easy to give you a collection of codes $\Phi$ for which this is false for.
Therefore, you need to show that the condition

assume every non zero vector $v\in\mathbb{F}_q^n$ is contained in the same number of codes from $\Phi$.

implies the above "uniformly random" bound on the probability $\Pr_{C_i}[v\in C_i]$.
I haven't thought about doing this, but hopefully this gives you a foothold for the problem (as well as exposes you to the above "standard" argument to show that a code/lattice of a certain minimum distance exists).
Comment: WOW. thank you very much for your answer i really appericiate it, i would not figure it by meslf, thanks!!

non linear codes


Does this logically follow?

Question: Suppose it is given to be true that if $p_i | q_i$, then $p_i \nmid q_j$ for any $j\neq i$. Suppose it is also known that if $p_i \nmid q_i$, then $p_i | q_j$ for some $j\neq i$ is false whenever $p_i\nmid q_i$. Since any $p_i$ either divides $q_i$ or does not, there exists no scenario where $p_i|q_j$ when $j\neq i$. Is this correct?
Comment: Yes, that's correct.  Basically you have for any $p_i$ either $p_i\mid q_i$ or $p_i$ does not divind any $q_i$ in the second set.
Comment: @fleablood, thank you. One concern I have is that since the contrapositive of a statement is equivalent in truth value, wouldn't taking the contrapositive of both statements show that the $p_i$ can never divide any $q_i$, producing a contradiction?
Answer: The first proposition can be put as
$$P_i \;\; \implies\;\; Q_{i,j}$$
the second is of the form,
$$not \; P_i \;\; \implies \;\; not \; Q_{i,j}$$
is false  so its negation
$$P_i \wedge Q_{i,j}$$
is true.
therefore, we cannot have $ not \;Q_{i,j}$.

Does this logically follow?


D3 Json to Hardcoded variables

Question: I want to turn the fetching of data from JSON to a hardcoded variable. This is the link to the d3 treemap chart: Zoomable Treemap Template.
Comment: could you post any code you may have written up to this point.
Comment: I have not started anything yet I am basing on the template on the link. I am just thinking of how can I use hard coded data instead of a json
Answer: If you mean you want to put JSON data into a variable, then you would represent this:
<code>[
  {
    "key": "Asia",
    "values": [
    {
      "key": "India",
      "value": 1236670000
    },
    {
      "key": "China",
      "value": 1361170000
    }]
  },
  {
    "key": "Africa",
    "values": [
    {
      "key": "Nigeria",
      "value": 173615000
    },
    {
      "key": "Egypt",
      "value": 83661000
    }]
  }
]
</code>
like this:
<code>var x = [
  {
    "key": "Asia",
    "values": [
    {
      "key": "India",
      "value": 1236670000
    },
    {
      "key": "China",
      "value": 1361170000
    }]
  },
  {
    "key": "Africa",
    "values": [
    {
      "key": "Nigeria",
      "value": 173615000
    },
    {
      "key": "Egypt",
      "value": 83661000
    }]
  }
];
</code>
Comment: How can I call the variable to the d3

D3 Json to Hardcoded variables


how to set the condition in AnyLogic?

Question: Each ticket office is allowed a queue.
Its maximum length is QueueCapacity1 and QueueCapacity2 installed 10 people.
When a new application is received, its processing is performed
order:

if a client of the first type arrives and the queue to the first cash desk is not complete, then the customer is put into this queue, otherwise, if the queue is not full to the 2 ticket offices, it goes to the queue to the cashier №2;
if both queues are full, then the client proceeds to the ticket machine;
if a second type client arrives and the queue to the second ticket office is not complete, the client "Placed" there, otherwise it goes to the vending machine to purchase a ticket.
Comment: You haven't actually specified what your question is, how your screenshot relates to what you have attempted (and how the Services / Delays / SelectOutputs relate to your 'specification', and how you currently setup your SelectOutputs), and where you have problems. As Felipe says in his answer we can make sensible guesses on this, but it would be better if you update your question to make it clearer.
Answer: What about this? Not sure if I understood your question, but this is how I would set a condition using selectOutput5 to solver your problem.
Comment: Can you help with these tasks, please?
1. if both queues are full, then the client proceeds to the ticket machine;
2.if a second type client arrives and the queue to the second ticket office is not complete, the client "Placed" there, otherwise it goes to the vending machine to purchase a ticket.
Comment: I am very grateful to you. You helped me a lot))))
Comment: I still have a question. In the picture above, Type1, is this?
Comment: Type1 is your agent type coming from source1, your agent coming from source2 should be of a different type... at least that is what I got from your question

how to set the condition in AnyLogic?


Django ManyToManyField post not working in drf

Question: model
class DesignerProduct(models.Model):
    title      = models.CharField(max_length=500, default=None)
    descripton = models.CharField(max_length=500, default=None)
    price      = models.CharField(max_length=500, default=None)
    editions   = models.CharField(max_length=500, default=None)
    verified   = models.BooleanField(default=False)
    created_at = models.DateTimeField(auto_now_add=True, null=True, blank=True)
    user       = models.ForeignKey(
        to=Login, on_delete=models.CASCADE, related_name="designerproduct", null=True, blank=True
    )
    collection = models.ForeignKey(
        to=DesignerCollection, on_delete=models.CASCADE, related_name="designerproduct", null=True, blank=True
    )
    categories = models.ManyToManyField(DesignerCategories, related_name='designerproduct', blank=True)

serializers
class DesignerProductSeriali
    designerproductmedia = DesignerProductMediaSerializer(many=True, read_only=True)
    user = serializers.PrimaryKeyRelatedField(queryset=Login.objects.all(), many=False)
    collection = serializers.PrimaryKeyRelatedField(queryset=DesignerCollection.objects.all(), many=False)

    user_name = serializers.CharField(source='user.name', read_only=True)
    user_photo = serializers.CharField(source='user.display_photo', read_only=True)
    class Meta:
        model = DesignerProduct
        fields = ('id', "user", "categories", "collection", 'created_at', 'designerproductmedia', 'title', 'descripton', 'price', 'editions', 'verified', 'user_name', 'user_photo')
        depth = 1

data after upload
    {
        "id": 11,
        "user": 9,
        "categories": [],
        "collection": 6,
        "created_at": "2021-06-05T17:03:52.807755Z",
        "designerproductmedia": [
            {
                "file": "designer/products/74647.jpg",
                "id": "38",
                "firework": null
            }
        ],
        "title": "hello there",
        "descripton": "hello there",
        "price": "10",
        "editions": "10",
        "verified": false,
        "user_name": "soubhagya pradhan",
        "user_photo": "profile/52319.jpg"
    }

Here i am omplmenting django manyToMany relation
and sending categories like [1, 2, 3]
But, after successfull post category list comes empty .
How to fix that ?
Please take a look

In drf also not showing please check this image
Answer: You can simply write a method get_categories by defining categories as SerializerMethodField to fetch the categories related to each instance of DesignerProduct.
Make these changes to your serializer -
class DesignerProductSerializer(serializers.ModelSerializer):

    categories = serializers.SerializerMethodField()
    designerproductmedia = DesignerProductMediaSerializer(many=True, read_only=True)
    user = serializers.PrimaryKeyRelatedField(queryset=Login.objects.all(), many=False)
    collection = serializers.PrimaryKeyRelatedField(queryset=DesignerCollection.objects.all(), many=False)

    user_name = serializers.CharField(source='user.name', read_only=True)
    user_photo = serializers.CharField(source='user.display_photo', read_only=True)
    class Meta:
        model = DesignerProduct
        fields = ('id', "user", "categories", "collection", 'created_at', 'designerproductmedia', 'title', 'descripton', 'price', 'editions', 'verified', 'user_name', 'user_photo')
        depth = 1

    def get_categories(self, obj):
       category_list = []
       category_list.append(category.id) [for category in obj.categories.all()]
       return category_list

Answer: In order to successfully send POST requests, you must add the categories field to your serializer as per below:
categories = serializers.PrimaryKeyRelatedField(
    queryset=DesignerCategories.objects.all(), many=True
)


Userscript to Click a "Refresh" button every minute except when there is input?

Question: I'm trying to create a Tampermonkey script that would click the page's "Refresh" button every so often, preferably every minute.
It would be even better if it could pause while you are performing other actions on the site like typing but that's more optional.
Reason for this is that we are using a website at work that needs us to keep track of incoming customer requests in a timely manner but the site only has an integrated refresh button that needs to be clicked manually and doesn't refresh automatically.
There are browser plugins which kinda do what I need but they refresh the whole webpage which causes it to loose important information or settings that have been done before. (this does not happen with the refresh button on the site).
So what i have found was the setInterval and the .click function.
What i setup was the following which sometimes worked and sometimes didn't.
But every time it did work it wouldn't stop even when disabling Tampermonkey.
// ==UserScript==
// @name         Ticket System - Auto Refresh
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  try to take over the world!
// @author       You
// @match        https://my*******.***.****mand.com/*
// @grant        none
// ==/UserScript==

setInterval(function () {document.getElementById("buttonOcLMZKwM8KoKda967hf2B0_11").click();}, 10000);

//end

I probably have some significant flaws in what i did above but as i said i have no experience with javascript. Also the time used was to test in order to quickly see if it works or not.
As you probably can see i already got stuck at the refresh part, so the stopping part when typing isn't even remotely done.
I also used
document.getElementById("buttonOcLMZKwM8KoKda967hf2B0_11")

and it is very likely target to fail as the website tends to change this ID when you login again. So i tried to do it by using instead:
document.querySelector('[title="Refresh"]');

but that didn't seem to work at all even though the title of the button is Refresh.
This is the full button HTML on the site:
<button type="button" id="buttonOcLMZKwM8KoKda967hf2B0_11" data-sap-ui="buttonOcLMZKwM8KoKda967hf2B0_11"
data-sap-automation-id="OcLMZKwM8KoKda967hf2B0" title="Refresh" role="button"
aria-disabled="false" tabindex="0" class="sapUiBtn sapUiBtnIconOnly sapUiBtnLite sapUiBtnS width-button-form sapUiBtnStd">
</button>

I would really appreciate any help i can get.
Comment: Rather than hitting the refresh button and reloading the entire page you should find a way to refresh a particular section of the page using AJAX or other means
Comment: Can you use `window.location.reload()` inside tampermonkey? Or doesn't it have a window object? In the optimal world, you'd get a push message from the server every time a request arrives. But as wouvik suggests, check if there's a http call delivering the data you can refresh instead of the entire page.
Comment: @SouvikGhosh - I am not sure if that will be possible, the site is build very complicated. But if you have any info for me where i can read more about that AJAX stuff i will have a look into that.

@Shilly How can i identify which id or class i can use for the `window.location.reload()` function? i do not understand on how i can tell it to just reload that specific window or part of the page.
Answer: To start and stop polling, or interval clicking, etc.; merely:

Store the value of the setInterval() call.
EG: var myTimer = setInterval (someFunction, 1000);
Pass that value to clearInterval() to stop the loop.
EG: clearInterval (myTimer);

Of course, the user interface is the hardest part.  I like to:

Put a status and control button in the upper-right of the screen.
Bind a keyboard shortcut to be able to toggle the loop without needing the mouse.

The following userscript does all of the above, plus:

Clicks the "Refresh" button on every iteration of the loop.
Stops/Restarts the loop when the control button is clicked.
Stops/Restarts when F9 is pressed (depending on where the focus is).
Stops the loop when one of the form controls is selected or typed into.
Restarts the loop when the "Refresh" button is clicked.

Here is a complete working userscript (It's just the part above the ****** block.).
To see it in action, Run the code snippet.

// ==UserScript==
// @name     _Click button regularly, with start/stop controls
// @match    *://YOUR_SERVER.COM/YOUR_PATH/*
// @require  https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js
// @grant    GM_addStyle
// ==/UserScript==

//--- Initialize the refresh button loop and controls.
var rfrshBtnSel = 'button[title="Refresh"]';  //  jQuery selector for the refresh
var rfrshTmr    = LoopManager (clickRefreshButton, 1000);  //  1000 ms == 1 second.
var loopStBtn   = LoopButtonManager (rfrshTmr.toggle);

rfrshTmr.setCallbacks (loopStBtn.start, loopStBtn.stop, loopStBtn.error);
rfrshTmr.start ();  //  Start looping the refresh btn click.

$(window).keydown (keyboardShortcutHandler);

//--- On use of certain form controls, stop the refresh timer:
$("body").on (
    "click keydown focus paste scroll", "input, textarea, select", rfrshTmr.stop
);
//--- On click of the refresh button, (re)start the refresh timer:
$("body").on ("click", rfrshBtnSel, rfrshTmr.start);

function clickRefreshButton () {
    var refreshBtn = $(rfrshBtnSel);
    if (refreshBtn.length === 1)  clickNode (refreshBtn);
    else loopStBtn.error ("Refresh button not found!");
}
function keyboardShortcutHandler (zEvent) {
    if (zEvent.which == 120) {  //  On F9, Toggle the Loop state.
        rfrshTmr.toggle ();
        return false;
    }
    return true;
}
function clickNode (jNode) {
    var clickEvent  = document.createEvent ('MouseEvents');
    clickEvent.initEvent ('click', true, true);
    jNode[0].dispatchEvent (clickEvent);
}

function LoopManager (callbackFnc, intrvlMillisec, bAutoStart, ...optParams) {
    var _thisInterval = null;
    var _startCB = null, _stopCB = null, _errorCB = null;
    if (bAutoStart)  _start ();

    function _start () {
        if ( ! _thisInterval) {
            _thisInterval = setInterval (callbackFnc, intrvlMillisec, ...optParams);
        }
        if (_startCB)  _startCB ();
    }
    function _stop () {
        clearInterval (_thisInterval);
        _thisInterval = null;
        if (_stopCB)  _stopCB ();
    }
    function _toggle () {
        if (_thisInterval)  _stop ();
        else                _start ();
    }
    function _setCallbacks (startCB, stopCB, errorCB) {
        _startCB = startCB; _stopCB = stopCB; _errorCB = errorCB;
    }
    return {
        start: _start,  stop: _stop,  setCallbacks: _setCallbacks,  toggle: _toggle
    };
}
function LoopButtonManager (clickCB) {
    var _btnNode = $('#tmStartStopBtn');
    if (_btnNode.length === 0) {
        _btnNode = $( `
            <button id="tmStartStopBtn" type="button" class="tmRefreshRunning">
                TBD (F9)
            </button>
        ` ).appendTo ("body");
    }
    var _spanNode = _btnNode.find ("span");

    _btnNode.click (clickCB);

    function _start () {
        setButtonDisplay ("Running", "tmRefreshRunning");
    }
    function _stop () {
        setButtonDisplay ("Stopped", "tmRefreshStopped");
    }
    function _error (errMess) {
        console.error ("TM: " + errMess);
        setButtonDisplay ("See console!", "tmError");
    }
    function setButtonDisplay (btnText, btnClass) {
        _spanNode.text (btnText);
        _btnNode.removeClass ();
        if (btnClass)  _btnNode.addClass (btnClass);
    }
    return { start: _start,  stop: _stop,  error: _error };
}
GM_addStyle ( `
    #tmStartStopBtn {
        position:           absolute;
        top:                0;
        right:              0;
        font-size:          18px;
        margin:             5px;
        opacity:            0.9;
        z-index:            1100;
        padding:            5px 20px;
        color:              black;
        cursor:             pointer;
    }
    .tmRefreshRunning { background: orange; }
    .tmRefreshStopped { background: lime; }
    .tmError { background: red; }
` );

/********************************************************************
******* Everything below this block is simulated target page. *******
******* It's NOT part of the userscript.                      *******
********************************************************************/
$('button[title="Refresh"]').click ( function () {
    $(this).attr ("id", 'spelunk' + Math.random () );
    $("#StatusNd").text ("Refreshed: " + (new Date() + '').replace (/\s*\(.+\)/, "") );
} );
div {
    margin: 0 0 1ex 1em;
    width: 20em;
    padding: 0.5ex 1em 0 1em;
    border: 1px solid darkgreen;
    border-radius: 1ex;
}
label { margin: 0 0 0 2em; }
label[for="Bar"] { display: inline-block;  vertical-align: top; }
button, #StatusNd { margin: 0 0 1ex 2em; }

This userscript will click the "Refresh" button every second,
 unless typing in an input.

Some inputs:

    Foo: <input type="text" id="Foo">

<button type="button" id="some_random_ID" title="Refresh">Refresh</button>

Comment: I can't thank you enough this is what i was looking for.
It pretty much does what i was trying to accomplish.
I managed to get it to work only thing that i don't seem to be able to get going is the button itself. The script can be started and stopped using F9. That works.
The button however seems not to want to become visible. I'm trying to figure out why.
Again Thank you sooo much. This is really amazing!
Comment: Managed to the the button work too.
had `grant none` on the top which canceled the `grant GM_addStyle`.
Again Thank you!


Migration taking increasingly long periods of time

Question: I have a migration and I've noticed that the code, through each batch operation, seems to process less and less items.
For example, the first few cycles, it'll say, "processed 600", and 600 or around there will be processed. However about 5-10 cycles in, and it will still say "processed 600", and it actually processes perhaps 100 or 200. This eventually stops the migration from happening, as it essentially grinds to a halt.
It was completing on my local machine and not the stage environment, which I initially thought to be due to some sort of environmental condition. Now I think that the cycles on my local were just large enough to allow everything to process before it grinded to a halt.
I'm not sure what is causing this, and if it's in this migration, or the migration that this migration is extending. I'll include the former, and if anyone needs the latter, let me know.
Note, there may be occasional instances where the words Company or Type are capitalized when they should not be - I just did a quick find/replace for sensitive data.
<code>class CompanyTypeUserDataMigration extends CompanyCertBaseMigration {

public function __construct($arguments) {
    parent::__construct($arguments);

    $this->machineName = "CompanyTypeUserData";
    $this->systemOfRecord = Migration::DESTINATION;
    $this->group = MigrateGroup::getInstance("Company");
    $query = Database::getConnection('default', 'Type')
        ->select('Type')
        ->fields('Type', array('Name', 'Username', 'Address', 'City', 'State', 'Zipcode', 'Country', 'Phone', 'Notes', 'Email'));
    $query->addExpression('`Company Name`', 'Company');
    $query->addExpression('`Supervisor Email`', "supervisor_email");
    $query->addExpression('`Declined Recert Renewal`', "declined_recert");
    $query->isNotNull('Username');
    $this->source = new MigrateSourceSQL($query, array('status' => 'Status calculated based on various fields'));
    $this->destination = new MigrateDestinationUser();
    $this->map = new MigrateSQLMap($this->machineName, array(
            'Username' => array('type' => 'varchar',
                'length' => 50,
                'unsigned' => FALSE,
                'not null' => FALSE,
            ),
            'Email' => array('type' => 'varchar',
                'length' => 50,
                'not null' => FALSE,
            )
        ), MigrateDestinationUser::getKeySchema()
    );

    $this->addFieldMapping('name', 'Username');
    $this->addFieldMapping('field_company', 'Company');
    $this->addFieldMapping('field_supervisor_email', 'supervisor_email');
    $this->addFieldMapping('field_notes', 'Notes');
    $this->addFieldMapping('field_status', 'status');
    $this->addFieldMapping('field_full_name', 'Name');
    $this->addFieldMapping('uid', 'user_id');
}

public function prepareRow($row) {
    // Always include this fragment at the beginning of every prepareRow()
    // implementation, so parent classes can ignore rows.
    if (parent::prepareRow($row) === FALSE) {
        return FALSE;
    }
    if (empty($row->Username)) {
        return FALSE;
    }

    $uid = $this->find_user_id($row);
    if($uid === FALSE){
        return false;
    } else {
        $row->user_id = $uid;
        $user = user_load($uid);
        if(isset($user->name)){
            $row->Username = $user->name; //so we don't try to overwrite username permutations
        }
    }
}

}
</code>
Answer: What's the total number of nodes you're importing? I've hit this issue before using the D2D Migration module. I've found that D2D starts to slow down on consecutive batches when I'm importing in more than ~5K nodes. In scenarios where I've needed to import 10K-100K nodes, batches eventually slow down to where nothing is ever imported.
Using XHProf & XDebug, I traced down the issue to database objects consuming tons of memory & CPU to the point of stopping PHP execution. I've never been able solve the issue for importing over 10K nodes using D2D. Searches all over the internet have produced nothing. In many instances I've had to rely on custom PHP import code as since I could not use D2D.
Comment: I found the same thing. I developed a workaround which I can post as an answer later.


Check if referenced field exists in commerce product display

Question: I have to render different types of product (with different fields combinations) in a generic product display tpl file.
I created an array with all possible field names (they all are referenced product:field_name) which passes through a
if ($content[$my_field]){
  //some code
}

that is supposed to check if the field exists and then do things...
The problem is that it actually checks the existence of the field but shouts out a notice: undefined index warning for every field that is not present.
Is there a way to execute this check in a cleaner way?
Thanks!
Comment: Thanks @aram-boyajyan for improving formatting of the question!
I don't know if it's better to ask another question or maybe integrate this one... actually after checking if the field exists I need to check if it's empty too and I can't understand how to do it
Answer: If I understood your question correctly, you should check if that element exists; here's how:
if (isset($content[$my_field])) {
  //
}

This way if the field is not set, you won't get the undefined index error.
Comment: Yes, actually that is not throwing out the error anymore. thanks!


Checking choice correspondence satisfy Weak Axiom of Revealed Preferences

Question: I have a question whether the below choice correspondence satisfies WARP or not. I know how to check a choice satisfies WARP when set X is in he form of X={x,y,z} however i cannot figure out when it is in the form given below. Can you help me?
By the way question is coming from Rubinstein's Lecture Notes in Microeconomic Theory book pg.44 Q3.)
C(A) = {x ∈ A | the number of y ∈ X for which V (x) ≥ V (y) is at least |X|/2}, and if the set is empty, then C(A) = A.
Is C(A) satisfy WARP?
Answer: HINT: Let $X=\{a,b,c,d\}$, with utility function $V:X\to\Bbb R$ given by $V(a)=B(b)=1$ and $V(c)=V(d)=2$. Find distinct $3$-element subsets $A$ and $B$ of $X$ and distinct $x,y\in A\cap B$ such that $x\in C(A)$, $y\in C(B)$, and $x\notin C(B)$. Note that since $X$ has $4$ elements, for any $x\in A\subseteq X$ we have $x\in C(A)$ if and only if there are at least $2$ elements $z\in A$ such that $V(x)\ge V(z)$.
Comment: Thank you! Then I guess if I define b,d ∈ A∩B , A={a,b,d} and B={b,c,d} then it would be b ∈ C(A), d∈C(B) and b ∉C(B).
Comment: @D.Sahin: Yes, that works. You're welcome!


Setting up Multiple Databases on a current site

Question: I'm having issues with my current shared hosting provider due to my core database exploding upwards of 1GB due to cache_form. I've been looking at trying to offload the cache and revisions databases into different databases entirely and set them away in order to hold down the load. I think my understanding of how is ok but I want to be sure as this is a current live site.
I declare the default database then declare where each table is explicitly in the prefix array. If this is accurate then I will just do it that way, if not then I'd like to know where I'm going wrong. Do I need to explicitly declare ALL my databases first in settings.php or do I need to declare just my default and let it work that way?
Comment: at some point "shared hosting" goes out the window and you should pay more for a dedicated server -- it sounds like you've reached that point.
Comment: I can't afford the kind of cash a vps requires right now.
Comment: As an aside, do you have cron running?
Comment: I have cron running. I have OptimizeDB module set to flush out the cache every time cron runs on Drupal. I'm not sure how to configure a cron job in cpanel for it to do it there, but that is what I have right now.
Answer: I think I figured out what to do in order to pull this off. The issue was that the documentation in default.settings.php was rather lacking but I managed to piece it together. You do have to set your tables up explicitly and your databases as well. It has not helped the issue at all, and frankly it concerns me due to the issues with Drupal 8 coming that frankly might not be usable. So I'm going to pursue a different course of action on this.


how cancellation token stop continue with?

Question: I have a Thread with this code:
foreach (string file in allDirectoriesFiles)
{
    if (cancellationToken.IsCancellationRequested)
    {
        return;
    }

    // ... some operation...
}

// ... some operation 2...

notice that I use return instead of break, because if I stop the thread the some operation 2 must not be executed.
I also notice that in this manner the .ContinueWith it is not executed.
Well, but that is just a "return" function. How can C# know that I'm returning due to the tokenSource.Cancel() instead of a usual return?
Answer: You should not create the continuation with the same cancellation token or else the continuation will also be cancelled, even before it is executed. Create the continuation with a different cancellation token (from a different cancellation source) or simply create it without a cancellation token if you always want the cancellation to execute.
Comment: Well! So: if current thread is executed, I can only stop it checking the cancellation token inside of it (it in fact won't force the exit of the thread. In other words: It will continue till the end if I don't check that token. Instead, if the continue function is not started, it won't if cancellation token is called (without I check manually). Right?
Comment: Yes that is correct. Even 'normal' tasks do not get executed if the cancellation token (with which it was created) was cancelled before the task is processed by the task scheduler. You only check the token in your own task so that you can cancel a long running loop, etc. O, and just a note: ending a task does not necessarily mean the thread (on which ot runs) exits, even if an exception is thrown.
Answer: A CancellationToken is meant to propagate the cancelling to the whole set of actions at once. Once you Cancel() its source, the other continuations won't be called.


Is there a well-known type of differential equation consisting of $y$, $y'$, and $y''$ multiplied together?

Question: Is there some sort of well known type of differential equation consisting of first and second derivatives multiplied together? For example (I just made this up):
$$y''(y')^2-y-x^2=0$$
Edit: Are there any applications of these sort of differential equations?
Comment: Consider anything of the form $$ (y^\prime)^k = F(y,x)$$ for some $F$ and integer $k \geq 2$; and differentiate to obtain a new differential equation of the form you seem to seek.
Comment: i don't think there is an explicit solution
Answer: The height profile of a viscous gravity currents on horizontal surfaces can be described using a similarity solution as
$$ (y^3y')' + 1/5(3\alpha+1)xy' - 1/5(2\alpha-1)y = 0, $$
on the domain $ 0 \leq x \leq 1$.  Analytic solutions exist for $\alpha = 0$.
Is this similar enough to what you're looking for?
Comment: Thank you! This is what I was looking for.
Comment: @Tdonut cool. Why are you interested in such an equation?
Comment: I was just wondering if any type like this existed.


Inheritance security rules violated while overriding member: 'System.Data.Entity.Utilities.TaskExtensions

Question: Previously, my website was working, but then I changed the GoDaddy ASP.NET Settings from vb to c#.  I don't recall changing anything else.  Now I am getting this error:
Server Error in '/' Application.

Inheritance security rules violated while overriding member: 'System.Data.Entity.Utilities.TaskExtensions+CultureAwaiter`1<T>.UnsafeOnCompleted(System.Action)'. Security accessibility of the overriding method must match the security accessibility of the method being overriden.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.TypeLoadException: Inheritance security rules violated while overriding member: 'System.Data.Entity.Utilities.TaskExtensions+CultureAwaiter`1<T>.UnsafeOnCompleted(System.Action)'. Security accessibility of the overriding method must match the security accessibility of the method being overriden.

Source Error:

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Stack Trace:

[TypeLoadException: Inheritance security rules violated while overriding member: 'System.Data.Entity.Utilities.TaskExtensions+CultureAwaiter`1<T>.UnsafeOnCompleted(System.Action)'. Security accessibility of the overriding method must match the security accessibility of the method being overriden.]
   System.Reflection.RuntimeAssembly.GetExportedTypes(RuntimeAssembly assembly, ObjectHandleOnStack retTypes) +0
   System.Reflection.RuntimeAssembly.GetExportedTypes() +21
   Heroic.AutoMapper.HeroicAutoMapperConfigurator.<LoadMapsFromAssemblies>b__4(Assembly a) +10
   System.Linq.<SelectManyIterator>d__16`2.MoveNext() +188
   System.Linq.Buffer`1..ctor(IEnumerable`1 source) +191
   System.Linq.Enumerable.ToArray(IEnumerable`1 source) +77
   Heroic.AutoMapper.HeroicAutoMapperConfigurator.LoadMapsFromAssemblies(Assembly[] assemblies) +110
   Heroic.AutoMapper.HeroicAutoMapperConfigurator.LoadMapsFromCallerAndReferencedAssemblies(Func`2 assemblyFilter) +225
   HeroicCRM.Web.AutoMapperConfig.Configure() in AutoMapperConfig.cs:14

[TargetInvocationException: Exception has been thrown by the target of an invocation.]
   System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor) +0
   System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments) +192
   System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) +101
   WebActivatorEx.BaseActivationMethodAttribute.InvokeMethod() +73
   WebActivatorEx.ActivationManager.RunActivationMethods(Boolean designerMode) +350
   WebActivatorEx.ActivationManager.Run() +78

[InvalidOperationException: The pre-application start initialization method Run on type WebActivatorEx.ActivationManager threw an exception with the following error message: Exception has been thrown by the target of an invocation..]
   System.Web.Compilation.BuildManager.InvokePreStartInitMethodsCore(ICollection`1 methods, Func`1 setHostingEnvironmentCultures) +613
   System.Web.Compilation.BuildManager.InvokePreStartInitMethods(ICollection`1 methods) +141
   System.Web.Compilation.BuildManager.CallPreStartInitMethods(String preStartInitListPath, Boolean& isRefAssemblyLoaded) +102
   System.Web.Compilation.BuildManager.ExecutePreAppStart() +157
   System.Web.Hosting.HostingEnvironment.Initialize(ApplicationManager appManager, IApplicationHost appHost, IConfigMapPathFactory configMapPathFactory, HostingEnvironmentParameters hostingParameters, PolicyLevel policyLevel, Exception appDomainCreationException) +531

[HttpException (0x80004005): The pre-application start initialization method Run on type WebActivatorEx.ActivationManager threw an exception with the following error message: Exception has been thrown by the target of an invocation..]
   System.Web.HttpRuntime.FirstRequestInit(HttpContext context) +9946024
   System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context) +90
   System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest wr, HttpContext context) +261

Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.6.1069.1

Here is the code where the error occurs, where line 14 is "HeroicAutoMapperConfigurator":
[assembly: WebActivatorEx.PreApplicationStartMethod(typeof(HeroicCRM.Web.AutoMapperConfig), "Configure")]
namespace HeroicCRM.Web
{
    public static class AutoMapperConfig
    {
        public static void Configure()
        {
            //HeroicAutoMapperConfigurator.LoadMapsFromCallerAndReferencedAssemblies(x => x.Name.StartsWith("YourPrefix"));
            HeroicAutoMapperConfigurator.LoadMapsFromCallerAndReferencedAssemblies();
        }
    }
}

The code is from this project:
https://github.com/MattHoneycutt/HeroicCRM
I haven't changed any code in my application.  Does anyone have any suggestions?
Answer: At GoDaddy, they said that totally rebuilt my account from the ground up, though I'm not sure exactly what that means.  Also, I re-published my website from Visual Studio to the production web hosting account, which together these things fixed the issue.
Answer: Issue is related to trust level. Most of the shared hosting doesnt provide full trust hosting.If you are using Microsoft.Owin.Security even if you turn it own at start up, It will not work.
<appSettings>
    <add key="owin:AutomaticAppStartup" value="false" />

So better change a hosting, otherwise you will be modifying your code.


Does returning an address find any useful application over returning a pointer?

Question: C/C++ allows the return of pointers:
int* returnpointer() {
    int c = 1;
    int *d = &c;
    return d;
}

so that it may be used in the caller function:
int* p = returnpointer();

This is the style I am most accustomed to as it makes the most natural sense.
Why then, would C/C++ provide a language feature to return an address if the above suffices in normal conditions? i.e.:
int& returnpointer() {
    int c = 1;
    int *d = &c;
    return *d;
}

called through the caller:
int* p = &returnpointer();

Given that I am more versed in the former, are there any features of the latter that the former isn't as well suited to do?
PS: I am aware that such code is dangerous because it can involve pointers pointing to variables that no longer exist as functions exit the stack. However that is not the scope of this question.
Comment: @AlexChamberlain .. and an unnecessary `d` along for the ride.
Comment: Returning a reference guarantees you'll get something - i.e. there's no way to pass NULL, as you could with a pointer. Also, a pointer could be cast to a different type - a reference cannot.
Comment: The first `returnpointer()` has a lovely side effect of **undefined behavior**, so its a pretty bad example; the second is just plain wrong.
Comment: @WhozCraig They both have undefined behviour!
Answer: You are confusing returning an address with returning a reference:
int& returnpointer() { ... }

Here, returnpointer() returns a reference to an int. A reference is an alias for an object of a certain type. References have different semantics to pointers, so they tend to serve different purposes.
A couple of differences that are very important are that references cannot be default constructed (there is nothing to construct), and they cannot be reset. They need to be initialized to refer to an existing object and they refer to that same object during their lifetime.
Pointers on the other hand hold values (representing addresses), and these values can be changed during their lifetime. A pointer can be made to point to a different object, be a nullptr, or point somewhere completely random (potentially leading to undefined behaviour if de-referenced).
Note that both your examples are wrong: the first returns a pointer to a variable that is local to the function. The second does the same, this time with a reference.
Answer: int& is not address-of operator.  int a = 0; int *ptr = &a;  that is the address-of operator.
int& returnpointer() {
    int c = 1;
    int *d = &c;
    return *d;
}

This does not return an address, but a reference to an int.  Think of a reference as an alias to another variable.
int a = 15;
int& ref = a;
ref is now just another name for a.
The difference between references and pointers is that a reference can never be NULL, it always must refer to something.
A little note:
int* returnpointer() {
    int c = 1;
    int *d = &c;
    return d;
}

You are returning a pointer to a local function variable c here, which is undefined behaviour, because that variable is destroyed when the function exits.  In order to return a pointer you  need to create it on the heap like so int * f = new int; *f = 5; return f;.  Now you can return f and use it outside the function.
Answer: C++ allows the return of pointers and references because it's entirely legal.
Consider this (and I do not advocate this, because returning memory allocated within a function in a naked sense is mostly discouraged due to a question of ownership):
MyObject* create() {
    return new MyObject();
}; // eo create

All fine.  We're returning a pointer, and we allocated the object dynamically.  Logically nothing wrong (other than allocating and returning a pointer without ownership... booo!).  And yet, some functions are going to have to do this:
void* operator new(std::size_t size) {
    return malloc(size);
};

References (as you seem to have got a little confused), are also utterly viable, even on pointer allocated things.  If we have a manager that maintains the instances, they can return a reference quite simply:
class Manager {
private:
    std::list<MyClass*> objects_;

public:
    Manager() {
    };
    ~Manager() {
        for(auto& o : objects_) {
            delete o;
        };
    };

    Myclass& create() {
        o = new MyClass();
        objects_.push_back(o);
        return *o;
    };
};

The above is perfectly fine, as the manager manages the lifetime of the objects.


Does $\sum\limits_{k=1}^\infty |\sin(ak)/k|$ converge?

Question: Does $\sum_{k=1}^\infty |\sin(ak)/k|$ converge for all $0<a<\pi$? I do not think so since for $a=\pi
/2$:
$$\sum_{k=1}^\infty\left\vert\frac{\sin(ak)}{k}\right\vert=\sum_{k=0}^\infty (2k+1)^{-1}=\infty.$$
But is this true for all $a$?
Comment: Since it not true for $a=\pi/2$ then abviously it's not true for all $a\in(0,\pi)$
Comment: I am interested if it is not converging for any a! :-)
Comment: Then why don't you correct your question in the post ?
Comment: Careful. If $a=\frac\pi2$, then $\sin(ak)=0$ whenever $k$ is even, but if $k=2j+1$, we have $\sin(ak)=(-1)^j$. Hence the series converges by the alternating series test.
Comment: It probably diverges for all $a$ in that interval. The reason is that the number of terms with $|\sin(ak)|\geq1/10$ is too high for the series to converge. This needs to be done rigidly to be a full proof, of course.
Comment: @Jason Did you miss the absolute value signs?
Comment: @Arthur Yes, I suppose I did!
Answer:
The series diverges if and only if $\sin(a)\ne0$, that is, if and only if $a/\pi$ is not an integer.

For every $k$, let $N_k^\varepsilon=\{n\leqslant k\mid|\sin(an)|\geqslant\varepsilon\}$, then the sum of the series is at least $$\sum_{k\geqslant1}\frac{\varepsilon}k\mathbf 1_{|\sin(ak)|\geqslant\varepsilon}=\varepsilon\sum_{k\geqslant1}\frac1k(N_k^\varepsilon-N_{k-1}^\varepsilon)=\varepsilon\sum_{k\geqslant1}\frac{N_k^\varepsilon}{k(k+1)},$$ hence it suffices to show that, for some positive $\varepsilon$, there exists some positive $\alpha$ and some finite $n$ such that, for every $k\geqslant n$, $$N_k^\varepsilon\geqslant\alpha k,$$ to conclude that the series diverges.
Assume without loss of generality that $0\leqslant a\leqslant2\pi$. If $a=0$ or $a=\pi$ or $a=2\pi$, then every term is zero hence the series converges. Otherwise, let us show that two successive terms $|\sin(ak+a)|$ and $|\sin(ak)|$ cannot both be small.
To wit, assume that $|\sin(ak)|\leqslant\varepsilon$ for some $\varepsilon$ in $(0,1)$, then $$\sin(ak+a)=\sin(ak)\cos(a)+\cos(ak)\sin(a),$$ and $\sin(a)\ne0$ hence $$|\sin(ak+a)|\geqslant|\cos(ak)|\cdot|\sin(a)|-|\sin(ak)|\cdot|\cos(a)|\geqslant\sqrt{1-\varepsilon^2}\cdot|\sin(a)|-\varepsilon.$$ For every $\varepsilon\leqslant\frac13|\sin(a)|$, the RHS is at least $\varepsilon$. For such value of $\varepsilon$, this proves our claim that $|\sin(ak+a)|$ and $|\sin(ak)|$ cannot both be less than $\varepsilon$, hence $N_k^\varepsilon$ is at least of order $\frac12k$ and the result follows.


Criando objeto PHP a partir de HTML

Question: Imagino que os frameworks normalmente fazem o seguinte para criar um campo de texto simples:
$campoTexto = new CampoTexto("nomeDoCampo", "valorDoCampo");
$campoTexto->gera();

O resultado seria:
<input type="text" name="nomeDoCampo" value="valorDoCampo">

Minha dúvida é a seguinte, existe alguma classe/função que faça uma engenharia reversa do código acima? Imagino algo mais ou menos assim:
$tag = new ObjetoMilagroso("<input type=\"text\" name=\"nomeDoCampo\" value=\"valorDoCampo\">");
print $tag->type . " - " . $tag->name . " - " .$tag->value;

O resultado:

input - nomeDoCampo - valorDoCampo
Comment: Isso é possível com um *parser* de HTML (como [`DOMDocument`](http://www.php.net/manual/en/class.domdocument.php)), mas tem certeza de que precisa disso? Não tem como evitar?
Comment: De uma olhada em processadores de xml, afinal html é um "xml", com sua tags e atributos
Comment: Muito interessante você poderia criar uma biblioteca com funções deste tipo para baixar NET.
Comment: Existe algum objetivou ou é só curiosidade mesmo? Até é possível montar um framework de domínio específico, mas daria um certo trabalho.
Answer: Com a sugestão do Fernando cheguei a seguinte conclusão:
<?php
    $t = "<input type=\"text\" name=\"nomeDoCampo\" value=\"valorDoCampo\" peterson=\"bonito\" />";
    $html = simplexml_load_string(html_entity_decode($t));
    $arrAtributos = $html[0]->attributes();
    $nome = $html[0]->getName();
    print "Nome da tag: ".$nome."
";
    print "Atributos:
";
    foreach ($arrAtributos as $key => $value) {
        print $key." => ".$value."
";
    }

É uma sugestão simples ainda e precisa de ajustes, tipo:
A tag obrigatoriamente tem que ter fechamento como no XML (de novo, sugestão do Fernando):
<input> =  erro
<input /> = ok
<button></button> = ok

Não estou tratando erros.
Mas achei interessante pois acabou ficando "genérico" e soluciona meu problema.
Comment: Faltou a implementação da classe Milagre :)
Comment: kkkk, "de novo, sugestão do Fernando", nossa parece ser minha a culpa. Mas não sei no que você quer utilizar isso, mas é bem interessante, e para uma pesquisa posterior, (não conheço muito bem) mas acredito que validadores de html utilizam algo nesse sentido. Não sei se essa é sua implementação. Mas pode pesquisar para entender melhor como pode ser a sua implementação.

Criando objeto PHP a partir de HTML


Troca de XML entre service e cliente

Question: Estou estudando WCF e todo o material inicial que encontro tudo se resume a coisas muito básicas, expondo métodos que recebem alguns parâmetros e devolvem algum valor.
Preciso criar um web service que será a interface entre o banco de dados e aplicações externas. As aplicações externas poderão fazer inserções, exclusões e alterações em registros.
Penso que isso deve ser feito via troca de arquivos XML, ou seja, para a aplicação externa inserir um registro de um novo cliente por exemplo, ela deverá enviar ao Web Service um XML com todos os dados necessários para o cadastro do referido cliente.
Como eu implemento isso?
Comment: Só pra esclarecer. Este procedimento é feito com envio e recebimento de XML por baixo dos panos. Essa simplificação, se eu não me engano, se chama RPC (Remote procedure call), parece que você está consumindo um método local, mas na verdade, é feita uma chamada pro seu webservice enviando estes dados e tecendo o resultado via XML.
Comment: Eu não consegui entender a sua pergunta.
Comment: Mas se está interessado em criar webservices que trabalham com você pode procurar por topicos como SOAP,WSDL e REST.
Comment: Eu só encontro exemplos tolos como por exemplo um web servisse que expõe um método chamado `soma` que recebe dois inteiros e devolve o resultado.
Assim uma aplicação que consome o serviço chama o método, passa dos dois inteiros e recebe o resultado da soma.
Como seria por exemplo o método responsável por fazer a inserção de um cliente, cujo o cadastro contem 30 campos? Criar um método com 30 parâmetros um para cada campo?
Answer: A resposta é mais curta é: você não implementa. O framework faz tudo isso por você.
Esse "simplificação", que faz parecer com que você esteja chamando métodos locais, se chama RPC (remote procedure call) - que, na minha opinião, é um dos pontos mais interessantes do WCF e ASMX.
Por "baixo dos panos" o que acontece é um envio e recebimento de XML's. Porém, tudo isso é extremamente regrado, com tipagem, e todas as outras vantagens de se fazer uma chamada local. Esta "regra" é definida por meio de um arquivo WSDL, todos os webservices desenvolvidos em WFC, por padrão terão este arquivo.
O WSDL também se encarrega de levar os tipos (classes) criados no webservice para aplicação cliente. Então, se existir uma classe Cliente no webservice, no momento que você criar a referência para o mesmo (isso geralmente é feito pelo Visual Studio) este tipo também passa a existir no projeto cliente.
A partir daí é só mandar o objeto para o método remoto que o framework fará todo o "trabalho sujo" por você. Obviamente que você pode configurar tudo, mudar algumas coisas, até mesmo escolher o formato dos dados (JSON, XML, etc.).

WCF é um framework para construção de aplicações orientadas a serviços (SOA), você pode ler algumas coisas bem interessantes em Diferenças de tipos de Web Service: SOAP, REST, XML.
Comment: @MatheusSaraiva Isso mesmo. Perceba que geralmente o próprio Visual Studio vai criar as classes responsáveis pelo contrato no seu projeto cliente.
Comment: Então o método exposto pode receber um objeto `Cliente` normalmente? Nesse caso o programa externo também deve ter uma classe do tipo cliente e passar esse objeto "preenchido" para o método do Web Server.
Seria isso?
Comment: As demais dúvidas estou sanando com  essa sequência de [vídeos](https://www.youtube.com/channel/UCYW01fOF5WFtnzdt78sqkUg/videos) sobre WCF do Israel Aece.

Troca de XML entre service e cliente