Segmentation fault (exit code 139) when using pthread_join

Question: I'm doing some first steps with threads on Linux systems, and i have this error which occures on the base of a program that gets some n argument and creates n number of threads.
Here is the important part of the code:
The function the threads should run:
void* function(void* arg){
    int id = (long)arg;

    printf("Thread #%ld created!\n",id);

    pthread_exit(0);
}

Important part of code in the main function
int main(int argc, char **argv){

    if(argc != 3){
        printf("Usage: %s <num> <exp>\n",argv[0]);
        exit(-1);
    }

    int num = atoi(argv[1]), exp = atoi(argv[2]);
    long i;
    pthread_t threads[num];
    pthread_attr_t attr;

    printf("Creating %d threads \n",num);

    pthread_attr_init(&attr);
    pthread_attr_setdetachstate(&attr,PTHREAD_CREATE_JOINABLE);

    for (i = 0; i < num; i++) {
        pthread_create(&threads[i],&attr,function,(void*)i);
    }

    pthread_attr_destroy(&attr);

    for (i = 0; i < num; i++) {
        printf("Thread #%d is %ld\n", i, threads[i]);
    }

    for (i = 0; i < num; i++) {
        pthread_join(threads[num], NULL);
    }

}

Notice the last for loop with the pthread_join function, when i comment it out the program ends fine (exit code 0), but the output is obviously wrong since not all of the threads runs function before the main process exits.
When i don't comment it out i get segmentation fault (core dumped) when trying to run using the terminal in my Linux OS and Process finished with exit code 139 when running in my IDE (CLion).
I couldn't find anything i've done wrong as it's a very basic program that shouldn't have anything hard to find, what is the problem that causes the error?
Comment: Tip: "segmentation fault" and "Process finished with exit code 139" are synonymous. 139 = 0x80 | 11, which is what the shell returns as exit code when the program it executes is killed by signal 11, segmentation fault.
Answer: You should have used pthread_join(threads[i], NULL); instead of pthread_join(threads[num], NULL);. Suppose, the num is set to 4 via argument. Then threads[num] points to 5th element of array which does not exist as you have allocated an array of only 4 elements.
Comment: well kind of embarassing... Didn't notice that, stupid me... Thanks!


How to apply Panels layouts for CiviCRM pages

Question: For CiviCRM pages Events and Contributions that has paths of e.g.
<code>www.site.com/civicrm/contribute/transact?reset=1&id=1
www.site.com/civicrm/event/register?id=23&reset=1
</code>
And so on.
Problem is that you need to copy paste custom .php files and folders in themes dir for each form to apply custom styling, e.g. have right side and left side columns and display custom content. E.g. left side column texts and infos, descriptions and right side column contains the registration form/payments.
I can't figure out how to do that without copying multiple folders for each form and editing it each time to match the page ID.
I'm looking at the Panels and it doesn't have CiviCRM content as nodes content type to be applied and filtered out in the panels variant and etc.
Or not possible?
Comment: If you haven't already done so, it would be great to see you supporting the proposal for the new CiviCRM StackExchange site: http://area51.stackexchange.com/proposals/77367/civicrm?referrer=sZxmfwEWAHDXeNHrjdyxXQ2
Answer: Most CiviCRM forms can be accessed with the Webform CiviCRM Integration module: https://www.drupal.org/project/webform_civicrm
Though the integration currently only handles on-site payment methods for contribution forms.
You can build a webform using fields from the CiviCRM form and then use panels to arrange the page, or use Webform Layout module (https://www.drupal.org/project/webform_layout) to arrange the form elements
Comment: If you haven't already done so, it would be great to see you supporting the proposal for a new CiviCRM StackExchange site: http://area51.stackexchange.com/proposals/77367/civicrm?referrer=sZxmfwEWAHDXeNHrjdyxXQ2
Answer: Might also be worth your while taking a look at the CiviCRM Entity module (https://www.drupal.org/project/civicrm_entity). Not straightforward to use but might get you at least some of the way.
I think Webform and webform_civicrm modules might be the way to go for standard contributions.


How do I get the logged user ID?

Question: I am developing a module with a form to ask for the email frequency; when users choose a value, and save it, I store it in the users table, but it doesn't work. It works only when I hard code the user ID.
global $user;
$uuid = $user->uid;

function emailf_form_submit($form, &$form_state) {
  $bb = $form_state['values']['emailf'];
  $query = db_update('users')
    ->fields(array('email_f' => $bb))
    ->condition('uid', $uuid, '=')
    ->execute();

  drupal_set_message('Email frequency successfully changed');
}

Comment: Did you try moving the lines setting `$uuid` inside the function?
Comment: Without the `global $uuid;` line, that code doesn't work. That variable should then be initialized from a function. Anyway, this is a plain PHP question. Drupal doesn't change how global variables work.
Comment: nop that's it when i set it inside the function it's working ...thanks...
Answer: It works when $uuid is initialized inside the function.
function emailf_form_submit($form, &$form_state) {
  global $user;
  $uuid = $user->uid;

  $bb = $form_state['values']['emailf'];
  $query = db_update('users')
    ->fields(array('email_f' => $bb))
    ->condition('uid', $uuid, '=')
    ->execute();

  drupal_set_message('Email frequency successfully changed');
}

How do I get the logged user ID?


MySQL - Inner join into same table with WHERE clause

Question: I have a MySQL table called campaigns like the following
ID    integer
Name  text
isBalanced  boolean
redirects  tinyint

I am trying to achieve a SELECT query so that I get ALL the rows where isBalanced is false PLUS only a DEFINED number of rows where isBalanced is true. After I get this result I need to get the single one with the lowest number of redirects.
I know that there are ways to do it but I am having an hard time to figure out how. This is what I got until know
SELECT campaigns.id, campaigns.name, campaigns.isBalanced, campaigns.redirects
FROM campaigns AS c
INNER JOIN campaigns_2 AS c2
WHERE c.isBalanced = 0

However I am not able to select just some of them from the c2 set and then regroup all the filter to get the single one with lowest number of redirects.
Any help would be greatly appreciated.
Comment: show some sample data and the expected result.it is not clear what you need.
Comment: What is your "defined" number of rows? Are these IDs in a table? Some criteria? Also, don't think in terms of "I want these rows, then I want to get this one from those". SQL is set-based and you need to teach yourself to think in those terms and not in sequential processing terms.
Comment: @TomH yes and no, SQL is also kind of sequential. E.g. when you select from a sub query you can look at it as a 2-step process. Also things like IN or EXISTS (or even WHERE itself) can be viewed as a sequential step.
Answer: It sounds like you want union all, perhaps with order by and limit:
select c.*
from campaigns c
where c.isBalanced = 0
union all
(select c.*
 from campaigns c
 where c.isBalanced = 1
 limit ??
)
order by redirects
limit 1;

The "defined number" goes where the ?? is.
Comment: you don't need `UNION ALL` here, just `UNION`
Comment: @Stan . . . `UNION ALL` is always preferable to `UNION`, unless you specifically want to incur the overhead of removing duplicate values.
Comment: This is it, @GordonLinoff. Thank you very much.


Extending PHP Class in Namespace

Question: I have a PHP class-- a generic ODBC database interface. While the methods will never change (because it uses PDO), the connection string will. To avoid having the user pass in an entire connection string manually or specify an ODBC driver to be placed into a connection string, I extend the class and create a SQL Server specific version.
Generic PDO ODBC Driver
class PDO_ODBC implements DBDriver{
    private $driver;
    private $connection_string;

    public function connect(){
        if(!$this->driver || !$this->connection_string){
            throw new \Exception("Invalid connection string or database driver.");
        }
    }
}

SQL Server Specific Version
class PDO_ODBC_SQL_Server extends PDO_ODBC{
    public function __construct(){
        $this->driver = 'SQL Server';
        $this->connection_string = 'odbc:Driver={[Driver]};Server=[Host];Database=[DBName];Uid=[Username];Pwd=[Password]';
    }
}

The problem is, when I create a new PDO_ODBC_SQL_Server object and call connect(), the exception is thrown because $this->driver and $this->connection_string doesn't exist. But how can this be? If I use print_r, I see both of those properties. One thing to note is that print_r also shows the namespace of the class for all properties except the driver and connection string, as shown here: http://pastebin.com/qh40eDpa. In fact, there are separate variables of connection string and driver under the namespace.
How can I fix this and prevent the exception from being thrown, while still being able to use a similar design pattern by extending the base ODBC class? If not, then the alternative is to allow for the developer to pass in a driver and connection string...
Note, I've omitted most of the private variables in the code sample above for brevity. Both of these classes are located in separate files and are under the namespace Lib\Database
Answer: Make the class properties protected or make getters and setters if you want to keep them private. Private properties can only be accessed from the class in which they are declared, not derived classes.
class PDO_ODBC implements DBDriver{
    protected $driver;
    protected $connection_string;

    public function connect(){
        if(!$this->driver || !$this->connection_string){
            throw new \Exception("Invalid connection string or database driver.");
        }
    }
}

http://php.net/manual/en/language.oop5.visibility.php#language.oop5.visibility-members

Extending PHP Class in Namespace


Queries on munkres lemma 41.3

Question: In Munkres Topology chapter 6 lemma 41.3(page 254)
Lemma 41.3:
Let $X$ be regular. Then the following conditions on $X$ are equivalent:
Every open covering of $X$ has a refinement that is:

An open covering of $X$ and countably locally finite
A covering of $X$ and locally finite
A closed covering of $X$ and locally finite
An open covering of $X$ and locally finite

In the proof of (2)$\Rightarrow$(3) (and (3)$\Rightarrow$(4)), Munkres constructs a covering $\mathscr{C}$ and seems to assume that it is countably locally finite as it uses (2) (and (3))

(2)$\Rightarrow$(3):
Let $\mathscr{A}$ be an open covering of $X$. Let $\mathscr{B}$ be the collection of all open sets $U$ of $X$ such that $\overline{U}$ is contained in an element of $A$. By regularity, $B$ covers $X$. Using (2), we can find a refinement $\mathscr{C}$ of $\mathscr{B}$ that covers $X$ and is locally finite.

In order to use (2) it seems like $\mathscr{B}$ is assumed to be countably locally finite. But suppose we let $\mathscr{B}$ be the collections of open sets in the lower limit topology that is contained in $[0,1)$, it doesn't seem like this collection is countably locally finite.
Similarly,

(3)$\Rightarrow$(4):
For each point $x$ of $X$, there is a neighborhood of $x$ that intersects only finitely many elements of $\mathscr{B}$. The collection of all open sets that intersect only finitely many elements of $\mathscr{B}$ is thus an open covering of $X$. Using (3) again, let $\mathscr{C}$ be a closed refinement of this covering that covers $X$ and is locally finite.

Which also assumes $\mathscr{B}$ is countably locally finite
My doubt is how is $\mathscr{B}$ is countably locally finite in both cases, since it doesn't seem to be in the specific case mentioned above.
Edit 1: The structure of the proof is pretty clear, it's just that using (2) or (3) assumes (1), which states that the covering have a refinement that is countably locally finite, not all coverings in regular spaces are countably locally finite, for instance $R_\ell^2$ is regular but not paracompact
Edit 2: So the assumption at first was that every open covering, not just a single open covering, so $\mathscr{B}$ by assumption is countably locally finite
Comment: Using (2) does not assume (1) at all. The 4 statements are all of the form "for every open cover of $X$ there is a refinement cover" which has possibly some extra condition. Munkres, as a shorthand, only mentions the extra condition without repeating the common part.
Comment: No $\mathcal{B}$ is *not* by assumption countably locally finite; you still misunderstand the structure of the statements and thus the structure of the proof.
Answer: The structure of the proof is a classical "round trip" of implications: so we assume $(2)$ holds ("every open cover has a locally finite refinement"; where this refinement is just any cover of $X$, the elements can be any type of set) and show $(3)$: "every open cover has a locally finite closed refinement".
So to show $(3)$, we start with an open cover $\mathcal{A}$ (and we can assume $(2)$ as a fact), but first we define an other related cover (not locally finite, in general ) $$\mathcal{B}=\{U: \text{ open }: \exists A \in \mathcal{A}: \overline{U}\subseteq A\}$$
This is a cover indeed: let $x\in  X$, as $\mathcal{A}$ is an open cover there is some $A_x \in \mathcal{A} $ with $x \in A_x$. By regularity there is an open subset $U$ of $X$ such that $x \in U \subseteq \overline{U} \subseteq A_x$. Then $U \in \mathcal{B}$ as witnessed by $A_x$ and $x \in U$.
Now apply $(2)$ to this cover $\mathcal{B}$, and we get a locally finite $\mathcal{C}$ that is a cover of $X$ and refines $\mathcal{B}$. Then he probably goes on to show that
$$\mathcal{C}'=\{\overline{C}: C \in \mathcal{C}\}$$
is a closed locally finite cover of $X$, where we can maybe rely on some old fact that when a family of set is locally finite, so is the set of its closures.
That it is indeed a cover and refines the original $\mathcal{A}$ is easy to check from definitions.
$(3)$ to $(4)$ is similar: we start with an open cover, define a related open cover, and apply $(3)$ to that related cover, and "manipulate" the (locally finite) result to show $(4)$, and get a refinement of the right type for the original open cover.
Comment: Also see my note [here](http://at.yorku.ca/p/a/c/a/03.pdf) for the same proof.
Comment: the cover $\mathscr{B}$ may not be countably locally finite tho, and to use (2) you need it to be countably locally finite
Comment: @Ariana you misunderstand what $(2)$ says. It says: "every open cover of $X$ has  a locally finite refinement". We apply it to the open cover $\mathcal{B}$.
Comment: oh right yea i think i misunderstood it, thanks!
Answer: For any conditional statement, $P \Rightarrow Q$, the statement evaluates to true for all possible truth values of $P,Q$ except $T \Rightarrow F = F$, but $F \Rightarrow Q = T, T\Rightarrow T = T$. So, the assumption is warranted to prove the conditional statement. You need only consider the case when $P$ is true and prove the implication is that $Q$ is also true.
In your example, if you want to prove that (2) implies (3), then assume (2) is true, and use its truth to prove that (3) is also true.
Comment: yea but it is now constructing a new covering and it uses (2) to get a locally finite covering, but that assumes it is countably locally finite in the first place(since (1)$\Rightarrow$(2))
Comment: The new covering is not assumed to be countably locally finite. It is declared to be locally finite, with countable local finiteness not required. The idea is $X \Rightarrow (1) \Rightarrow (2) \Rightarrow (3) \Rightarrow (4) \Rightarrow (1)$ shows equivalence. So, if you want to get back to see how it is countably locally finite, get all the way to 4 and follow the book's proof to return to (1).
Comment: yea but like you can just declare a arbitrary covering as locally finite
Comment: You are assuming that an arbitrary covering can be refined to a locally finite covering by the assumption of (2).
Comment: Yea realized that the assumption was all open coverings not just for a single open covering

Queries on munkres lemma 41.3


What is the best form (Gaussian, Multinomial) of Naive Bayes to use with categorical (one-hot encoded) features?

Question: I've been asked to use the Naive Bayes classifier to classify a couple of samples.
My dataset had categorical features so I had to first encode them using a one-hot encoder, but then I was at a loss as for which statistical model to use (e.g. Gaussian NB, Multinomial NB).
I ended up using the multinomial version because I read somewhere that it worked well in NLP and IR tasks due to documents being represented as term-count vectors or TF-IDF weights.
I would like to know if that was correct and, if possible, a quick explanation on why that is so.
PS There is this somewhat similar question, but I'm not sure whether that also applies to strictly binary (0 or 1) feature vectors.
Comment: Naive Bayes seems like a strange choice to me because it assumes independence between features. But, the features of a one-hot encoding are heavily dependent because only one of them can be nonzero. In this sense, one-hot encodings are different than word count vectors.
Comment: @user20160 I agree, but how else would you encode categorical (i.e. words) features in order to use them in a Naive Bayes classifier, supposing you need to use that classifier?
Answer: As others mentioned, there isn't a "right" model. However, since you used one-hot encoding, you are basically dealing with boolean features now. In other words each term/feature is following a Bernoulli distribution. That being said, I would use a multivariate Bernoulli NB or a multinomial NB with boolean features (which you already have). Gaussian NB seems a bit off here since you don't deal with real-valued features.
This excellent paper has a lot of information on different NB variants and when to use which.
Answer: Your choice of statistical model in classification (Gaussian NB, Multinomial NB, etc) depends on the distribution of your input variables.  You should plot the histogram of each input parameter in order to determine their distribution.
You can use Pandas to do this by creating a dataframe on your input matrix and running .hist() on it, as follows:
X_frame = pd.DataFrame(X, index=natural_index(dataset))
X_frame.hist()

Answer: If you're using real-world data, it's very unlikely that any model will be "right," so rather than try to find a model that is "right," you should try to find a model that is accurate. To decide between those two models, you can use cross validation to get an estimate of the accuracy of each model and choose the better one. At the end of the day, you can't be be confident about which model will perform best on your data without actually running the models on your data in some capacity, even if one model is used in similar applications.
I would also suggest a third Naive Bayes model that you could try. Instead of using a one-hot encoder, let the class-conditional density of each feature be a categorical distribution.
More precisely, suppose $Y_i \in \{1, ..., C\}$ is the label for data point $i$. Suppose $X_i$ is the data for data point $i$ and suppose that each feature is $X_{ij} \in \{1, ..., K\}$. In other words, suppose that each feature is categorical with $K$ values. You could use the model $P(X_{ij} = k|Y_{i} = c, \theta) = \theta_{cjk}$ where $\forall c \forall j$, $\sum_{k=1}^K \theta_{cjk} = 1$.
Answer: I would suggest to plot a histogram. For a quick histogram you can do this:
Load data into a pandas dataframe:

df = pandas.Dataframe( data, optional parameters)
df.hist()

If most of your features are following a  bernoulli distribution , you should be good to use  Multinomial (Bernoulli) NB  and if they are following a  Gaussian (Normal) distribution, Gaussian Bayes  should be good.
In case your distributions of features seems to be  complex (a mixture of different distributions), it would be good to  consider dimensionality reduction  to make sure you have most, though not all, features to have similar distribution.


Prove series is unbounded on any interval

Question: Let $f(x) =  x^{-1/2}$ for $ x \in (0,1)$ and zero otherwise.
Let $F(x) =  \sum 2^{-n} f(x - r_{n})$ where $ {r_{n}} $ is an enumeration of rationals.
1) Prove that $F(x)$ is integrable and thus its series is convergent almost everywhere.
(I did this part)
2) Prove that any function $G$, where $G$ agrees with $F$ almost everywhere, is unbounded in any interval.
I'm stuck on part 2.
Thank you for any help
Comment: Does this mean (1) pick any interval and any function $G$ that agrees with $F$ almost everywhere, and prove that $G$ is unbounded in that interval, or (2) prove that no matter which interval it is (it could be _any_ interval) and no matter which function $G$ you pick, that agrees with $F$ almost everywhere (it could be _any_ of them), that function is unbounded on that interval?  The word "any" is in some contexts ambiguous, and usually the ambiguity can be avoided by saying "every" instead of "any".  I think it's really only mathematicians who habitually use "any" as a synonym of "every".
Answer: Well, fix any interval $I$, pick any $r_n$ in the interior of $I$ and use the fact that $F\geqslant2^{-n}f_n$ everywhere, with $f_n:x\mapsto f(x-r_n)$. If one shows that $f_n$ is unbounded on $I$, the proof is over. Can you?


$G$ be a group of order $p^n$ and $H$ be any subgroup of $G$; then does there exist $x \in G\setminus H$ , such that $xH=Hx$?

Question: Let $G$ be a group of order $p^n$ , where $p$ is a prime and $n \in\mathbb N$ and $H$ be any subgroup of $G$; then does there exist $x \in G\setminus H$ , such that $xH=Hx$ ?
Comment: Every finite $p$-group is nilpotent. In particular, in nilpotent groups "normalizers grow". This means that
$$N_G(H) \supsetneq H$$ So the answer to your question is yes.
Answer: Yes.
If $Z(G)\not\subseteq H$, then letting $x\in Z(G)$ will satisfy the problem.
If $Z(G)\subseteq H$, then we take quotient by $Z(G)$ and apply induction. Suppose $x\mapsto \bar{x}$ denotes the quotient map. Then, by the induction hypothesis, there is $\bar{x}\in\bar{G}\backslash\bar{H}$ such that $\overline{xH}=\overline{Hx}$. It is easy to conclude $xH=Hx$ from here.
Comment: ADD: You should verify that the center of a p-group is nontrivial, so that you can actually apply the induction hypothesis.


Declare values of array of structures in POU using PLC ST

Question: I have structure declared like this:
TYPE board:
STRUCT
   number: INT;
   color: DWORD;
END_STRUCT
END_TYPE

And i want to declare array of these structures with starting values in POU. I do it like this:
Program PLC_PRG
VAR
   arr1: ARRAY[1..61] OF board;
   board: board;
   arr1[1].color := 16#FF0000;
END_VAR

But i get an error which say: "Error 4024: PLC_PRG(10): Expecting ':' before '['".
Do anybody know how to solve this problem?
Answer: You didn't specify a platform but I'll assume TwinCAT. To initialize an array of structures, you have to do it all in the variable declaration line.
arr1: ARRAY[1..61] OF board := [(number:=7, color:=16#FF0000), (number:=5, color:=16#FF0001)];

This example will initialize elements 1 and 2 of the array. To my knowledge you can't selectively initialize individual array elements as you are maybe wanting to do. You could use statements like arr1[17].color := 16#FF0000 of course but it would have to be outside of your variable declaration block.
Comment: I am using Codesys so just removed square brackets. Do you know is there way to declare couple of elements the same time like this:
arr2 : ARRAY [1..2,3..4] OF INT := [1,3(7)]; (* short for 1,7,7,7 *)
but with array of structs? Because this don't work:
arr1 : ARRAY[1..61] OF board := 6(number:=1, color:= 16#FF0000);
Comment: Square brackets are required in Codesys 3.5. This means you use CoDeSys 2.3.

To give answer for multilevel array in a comment is hard. Create new question so that we can give you answer with examples.
Comment: I don't know about CODESYS 2.3, but in 3.5 you should be able to initialize several identical objects with brackets. Alternatively, you may define a `init` variable and initialize your array once at the beginning of your program. This is especially useful if the array is big but can easily be initialized through a `FOR` loop!


Since we use Bootsrap to approximate the SE, can we use Bootstrap to find prediction errors?

Question: Instead of using Cross-validation, or K-fold Cross-validation, can we use Bootstrap to generate random samples and use one of them as test set, and others as training set?
Comment: Two bootstrap samples will include many observations in common, which leaves you with the problem of mostly testing on your training data
Comment: Do you mean that since we use our initial data set to obtain bootstrap sample, we have overlaps in data. Hence, our model would essentially use the fraction of data that we used for training, right?
Answer: As @Glen_b said, training on one bootstrap set and testing the other will have substantial overlap ($\approx 40\,\%$ of the cases will be in both sets), thus the error will have an optimistic bias.
But you can train on bootstrap sets and then test the left out cases ($\approx \frac{n}{e} \approx 37\,\%$ of the cases), this is called out-of-bootstrap error.
Comment: @ZamirAkimbekov: probability that a particular case is drawn into one bootstrap sample has limit ($n \to \infty$) $1 - \frac{1}{e}$. Both draws are independent, so probability to draw any particular case into both sets is $\approx (1 - \frac{1}{e})^2 \approx 0.4$.
Comment: How did you calculate the overlap percentage?


Antiderivative of $e^x/(1+2e^x)$

Question: I know the solution is $$\dfrac{\ln\left(2\mathrm{e}^x+1\right)}{2}+C$$ However, the result I got was $$\dfrac{\ln\left(\mathrm{e}^x+0.5\right)}{2}+C$$ What I did was:
$$ \begin{align}
\int \frac {e^x}{1+2e^x}dx &= \int \frac {e^x}{2*(0.5+e^x)}dx \\
&= 0.5 \cdot \int \frac{e^x}{0.5 + e^x} dx \\
&= 0.5 \cdot (\ln|0.5 + e^x| + C). \end{align}$$
I know there are antiderivative calculators online that show the correct method step by step, but I can't understand what I did wrong. What's the mistake?
Comment: I think OP choice's of presentation on a line was better than the actual edit, symbols get all packet in a small area now. Why override OP's style when the original LaTeX is ok ?
Comment: I split the lines because it accidentally carried over to a second line, which is distinctly unoptimal. The choice to make three lines instead of two was made on the fly.
Comment: @zwim Also (I'm not taking sides) multiple lines are better for viewing on mobile.
Answer: These answers are the same. Namely,
$$ \ln(2e^x + 1) = \ln(2(e^x + 0.5)) = \ln(2) + \ln(e^x + 0.5).$$
The added $\ln 2$ is absorbed by the $+ C$, and so we see that the two answers are the same up to an additive constant. There is no error.
Answer: Let $C = \ln 2$, a constant. Then they're equivalent.
What you did is correct; you just have a different value of $C$. This is why the "$+C$" is so important!
Answer: You can tell your answer is right by differentiating it and seeing what you get back. Indeed,
$$
\frac{d}{dx}\left(\frac{\ln(e^x+0.5)}{2}\right)
=\frac{1}{2}\frac{e^x}{e^x+0.5}
=\frac{e^x}{2e^x+1}.
$$
So you are correct. As the other answers point out, the two answers are the same up to a constant.
Answer: The others have answered your question. Note that one runs into this often also when dealing with trig functions.For example $\int sinx cosx dx= sin^2(x)/2 + C$ if one chooses to make the substitution $u= sinx$, and  $\int sin(x)cosx dx= -cos^2(x)/2 + C$, if one chooses $u=cosx$. Both answers are correct, as of course their difference is a constant, since $sin^2(x)+cos^2(x) = 1.$

Antiderivative of $e^x/(1+2e^x)$


Reading emails from my own server

Question: I am using PHPMailer for PHP on my site.
How can I read my own emails, by PHPMailer?
I have looked at: https://code.google.com/a/apache-extras.org/p/phpmailer/wiki/PHPMailer, but I didn't see any good example for PHPMailer using POP3.
I would be glade having a little code that explain the use of PHPMailer with pop3.
Thanks :)
Comment: I have changed a bit of my original question (So my question will be cleared). I looked at google, but didn't see any good example specifically for PHPMailer working with POP3 to receiving my emails. Need help about. Thanks :)
Answer: If your working with Yii Framework, then you easily can doing with EIMAP Yii Extension, for more help try this link - https://www.php.net/manual/en/book.imap.php
Comment: As my question, I would like sample for PHPMailer working with POP3 in order receiving emails. Thanks :)
Comment: regarding to your sound it's not possible through POP3, try this link - [link](http://in1.php.net/manual/en/book.imap.php), you will get the idea.
Comment: I have tried this link - what shall I do? For first test, I want to loop all of my emails, and read them. I need a code sample please. I didn't find any in google. Thanks :)
Comment: just download the zip file from this url - [http://www.yiiframework.com/extension/eimap/](http://www.yiiframework.com/extension/eimap/), check these source code. whole code written in php, so you will get the idea.

Reading emails from my own server


What's the successor of $\emptyset$? Do we need to assume that $\emptyset \in \emptyset$ for the successor to exist?

Question: I'm reading Guerino Mazzolla's Comprehensive Mathematics for Computer Scientists 1:

Axiom 3 (Axiom of Union) If $a$ is a set, then there is a set
$$\{x| \text{ there exists an element } b \in a \text{ such that } x\in b \}$$
This set is denoted by $\cup a$ and is called the union of $a$.

$ $

Lemma 1 For any set $a$, there is the set $a^+=a\cup \{a\}$. It's called the successor of $a$.

$\emptyset^+=\emptyset \cup \{ \emptyset \}$ can be rewritten as  $\bigcup \{\emptyset, \{\emptyset \}  \}$, then applying the axiom of union, there are two elements $b\in a$:

$\emptyset$ and $\{\emptyset \}$

And then when applying $x\in b$, I'm having trouble because the book states that the empty set is the set with no elements inside it. But somehow it seems reasonable that $\emptyset \in \emptyset$, then I could proceed:

$\emptyset^+=\{\emptyset,\{\emptyset \} \}$

$\{\emptyset,\{\emptyset \} \}^+= \bigcup \{\{\emptyset,\{\emptyset \} \},\{\{\emptyset,\{\emptyset \} \} \} \}= \{\emptyset,\{\emptyset \},\{\emptyset,\{\emptyset \} \} \}$

I've also made an experiment with Mathematica that seems to confirm my hypothesis:
<code>a = {}
a \[Union] {a}
(a \[Union] {a}) \[Union] {a \[Union] {a}}
((a \[Union] {a}) \[Union] {a \[Union] {a}}) \[Union] {(a \[Union] {a}) \[Union] {a \[Union] {a}}}
</code>
Which yields:
<code>{}
{{}}
{{}, {{}}}
{{}, {{}}, {{}, {{}}}}
</code>
Comment: Your experiment disagrees with your hypothesis, since it (correctly) determines that $\{\}^+ = \{\{\}\}$, not $\{\{\}, \{\{\}\}\}$ as you hypothesized.
Comment: "But somehow it seems reasonable that $\emptyset\in\emptyset$": this should not seem reasonable at all; try to formulate why you think it should be. Anyway see [this answer](http://math.stackexchange.com/a/302067/18880), and more generally several questions that should show up on "Related" links on the right margin of this question.
Comment: Yes. Sorry, my mind was too burned for me to notice the difference.
Comment: Commenting on the text: I would think that a successor function defined along the lines of Peano's axioms would be more fruitful in a CS text. It would also avoid wonky results like $2\subset 5$.
Comment: @DanChristensen The book has the Peano Axioms, but at this elementary level (in the book), the natural numbers still don't exist. The author is in the process of construction.
Answer: What is wrong with $\emptyset$ having no elements? It means that $\emptyset \cup \{\emptyset\} = \{\emptyset\} = \{\{\}\}$, which is not what you wrote, because $\{\emptyset,\{\emptyset\}\} = \{\{\},\{\{\}\}\}$.
Comment: You probably should avoid thinking of it as "picking one", because there could be none. Rather, think of it as "for any set in the union (there could be no set at all), its members (there could be none) are in the union, and for any element (possibly none) in the union, it is a member of some (at least one) set in the union."
Comment: Thanks. Yes, now I see. I was afraid of doing the operation and having no element to put in there. I thought that the doing the operation and picking $x\in b$ would give me an indefinite expression such as divison by $0$.


Derivation of expected value in REINFORCE policy gradient

Question: This is a derivation in the book "Reinforcement Learning, an Introduction, 2ed" for the REINFORCE algorithm.

By definition $q_\pi(s,a)=\mathbb{E}[G_t|S_t=s,A_t=a]$. I don't understand how the inner expectation vanish when going from line 2 to line 3. Why the following is true?
$$\mathbb{E}\left[\mathbb{E}[G_t|S,A]\frac{\nabla\pi(A_t|S_t)}{\pi(A_t|S_t)}\right]=
\mathbb{E}\left[G_t\frac{\nabla\pi(A_t|S_t)}{\pi(A_t|S_t)}\right]$$
This question was made in another stack but in one step of the accepted answer it is assumed that the conditional expectation is wrt $S_t=s$ (a specific value of $S_t$) and not $S_t$ which is a random variable.
Derivation of Monte Carlo Policy Gradient for REINFORCE
Answer: I came across this very interesting website with lots of properties for conditional expected values: https://randomservices.org/random/expect/Conditional.html
One of the formulas is this:
$$r(X)\mathbb{E}[Y|X]=\mathbb{E}[r(X)Y|X]$$
That is, if you are conditioning on a random variable $X$, deterministic functions of $X$ may be brought inside the expected value operator. I suspect this may be done also when you condition on multiple random variables:
$$\pi(A,S)\mathbb{E}[G|S,A]=\mathbb{E}[\pi(A,S)G|S,A]$$
If this holds and $\nabla\log\pi(A|S)$ is a deterministic function of state and action then:
$$\mathbb{E}[\mathbb{E}[G|S,A]\nabla\log\pi(A,S)]=\mathbb{E}[\mathbb{E}[\nabla\log\pi(A,S)G|S,A]]$$
And by the law of iterated expectations this is:
$$\mathbb{E}[\nabla\log\pi(A,S)G]$$


On convex subgroups of totally ordered groups.

Question: I am trying to find an example of a totally ordered abelian group $(\Gamma,+)$ such that the set of its convex subgroups is $\textbf{not}$ totally ordered.
I think there should be such an example, but something tells me it is not so trivial. Any help or reference would be deeply appreciated.
Answer: It is totally ordered.
Indeed, let $A,B$ be convex subgroups, and suppose $b\in B-A$, and $a\in A-B$. Up to invert, we can suppose $a,b\ge 0$. Up to switch, we can suppose $a\le b$. So $0\le a\le b$. By convexity, $a\in B$, contradiction.
Note that I used very little of the axioms: I only need a set $G$ with a total order and a basepoint $0$, and an involution $i$ exchanging $G_{\ge 0}$ and $G_{\le 0}$: then the set of $i$-invariant convex subsets is totally ordered.
Comment: +1. You didn't use and didn't need "Abelian".   The lexicographic (dictionary) order on $\Bbb R^2$ with group operation $(x,y)*(x',y')=(x+x',y+y'e^x)$ is an example of a non-Abelian fully-ordered group.
Comment: @DanielWainfleet Yes. For non-abelian groups, one distinguishes left/right/bi-ordered/orderable groups. (Of course left-orderable is equivalent to right-orderable.) Your example (which I know as 2-dimensional affine group) is actually bi-orderable. The above applies to both left-ordered and right-ordered groups.


how to exhaust ASP.NET worker threads to show importance of async await pattern

Question: I am trying to demonstrate to a junior the importance of asynchronous programming, using async and await. For the purpose I have created an ASP.NET Web API project with one controller and two GET actions. One GET action is synchronous and the other is asynchronous.
I want to demonstrate that, in case of synchronous blocking i/o call, all of the available ASP.NET worker threads are waiting and doing nothing useful and in the meantime when some more requests arrive they will time out as all the available threads are waiting for i/o threads to complete.
The problem is that that my below code snippet partly conveys the point. it works as intended in case of asynchronous calls but not for synchronous calls. If I uncomment the commented out code lines, it doesn't happen and ASP.NET runtime can cope with many more threads. The code snippet is below:
public class TestController : ApiController
{
    // -> Uncommenting the below method proves my point of scalability <-
    //public async Task<string> Get()
    //{
    //    CodeHolder obj = new CodeHolder();
    //    return await obj.AsyncData();
    //}
    // -> Uncommenting the below method doesn't enforce time outs, rather waits <-
    public string Get()
    {
        CodeHolder obj = new CodeHolder();
        return obj.SyncData();
    }
}
class CodeHolder
{
    public string SyncData()
    {
        Task.Delay(10000).Wait();
        return $"I am returned from Sync after waiting for 10 second at {DateTime.Now.ToString("HH:mm:ss:fffffff")}";
    }
    public async Task<string> AsyncData()
    {
        await System.Threading.Tasks.Task.Delay(10000);
        return $"I am returned from Async after semi-waiting for 10 second at {DateTime.Now.ToString("HH:mm:ss:fffffff")}";
    }
}

Although the point I was trying to propose, gets conveyed as the synchronous calls take ages to complete but I am wondering why the requests are being kept in queue instead of time outs. I am using JMeter for sending 250 concurrent HTTP requests to my Web API service but they never time out rather they keep waiting and complete, although a very large delay (~250 seconds).
By the way, in async version, all of the responses are returned in around 10 seconds.
Comment: The whole point of 'timing out a request' is that some X cannot wait for N seconds that Y needs and throws timeout error. In our case X is client that is using the api. In Asp.Net request won't be timed out automatically, it'll be put in a queue and wait for first available thread to serve it. But the fact that all threads are blocked for N seconds already proves the inefficiency of using sync calls for blocking operations
Comment: Just a reminder that "ASP.NET worker threads" are plain thread pool threads.
Comment: first this is quite trick to show due to knowing how many threads the machine is capable of this is machine hardware and os dependent, in terms of identifying max through-put. I would say you have chosen one of the hardest ways to show this as you making it specific about web end point which means you have to test from this prospective. To do this you need to construct a benchmark which hits an endpoint with x request per second, you would need to variances an async and sync version both doing x request per second, you would then need two build something to monitor threads and cpu time.
Comment: read this to help with building a suitable test https://labs.criteo.com/2018/10/net-threadpool-starvation-and-how-queuing-makes-it-worse/ and look at this  https://stackoverflow.com/questions/20109849/how-to-track-net-thread-pool-usage
Comment: this is also a gd read https://stackoverflow.com/questions/28690815/iocp-threads-clarification
Comment: Does this answer your question? [Shouldn't lesser number of threads be used if I use async?](https://stackoverflow.com/questions/23259763/shouldnt-lesser-number-of-threads-be-used-if-i-use-async)
Comment: https://stackoverflow.com/questions/23259763/shouldnt-lesser-number-of-threads-be-used-if-i-use-async found the perfect example...
Answer: You could show that the sync version uses more threads from the threadpool than the async one.
This is what I came up with to demonstrate, the web controller:
[Route("api/v1/[controller]")]
public class ThreadController : Controller
{
    private static readonly object locker = new object();

    private static HashSet<int> syncIds = new HashSet<int>();

    [HttpGet("sync")]
    public ActionResult<string> GetSync()
    {
        var id = Thread.CurrentThread.ManagedThreadId;

        lock (locker)
        {
            syncIds.Add(id);
        }

        Task.Delay(10000).Wait();

        return $"I am returned from Sync after waiting for 10 second at {DateTime.Now.ToString("HH:mm:ss:fffffff")}";
    }

    [HttpGet("sync/count")]
    public ActionResult<int> CountSync()
    {
        lock (locker)
        {
            int count = syncIds.Count;

            syncIds.Clear();

            return count;
        }
    }

    private static HashSet<int> asyncIds = new HashSet<int>();

    [HttpGet("async")]
    public async Task<ActionResult<string>> GetAsync()
    {
        var id = Thread.CurrentThread.ManagedThreadId;

        lock (locker)
        {
            asyncIds.Add(id);
        }

        await Task.Delay(10000);

        return $"I am returned from Async after waiting for 10 second at {DateTime.Now.ToString("HH:mm:ss:fffffff")}";
    }

    [HttpGet("async/count")]
    public ActionResult<int> CountAsync()
    {
        lock (locker)
        {
            int count = asyncIds.Count;

            asyncIds.Clear();

            return count;
        }
    }
}

A console application to simulate the requests (I gave 150ms delay to let some time to reach the await block):
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;

namespace ConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            using (var http = new HttpClient() )
            {
                var stopwatch = Stopwatch.StartNew();

                var sync = new List<Task>();

                for (int i = 0; i < 20; i++)
                {
                    sync.Add(http.GetAsync("http://localhost:5000/api/v1/thread/sync") );

                    Thread.Sleep(150);
                }

                Task.WaitAll(sync.ToArray() );

                stopwatch.Stop();

                Console.WriteLine("Sync used " + http.GetAsync("http://localhost:5000/api/v1/thread/sync/count").Result.Content.ReadAsStringAsync().Result + " threads in " + stopwatch.ElapsedMilliseconds + "ms");

                stopwatch.Restart();

                var async = new List<Task>();

                for (int i = 0; i < 20; i++)
                {
                    async.Add(http.GetAsync("http://localhost:5000/api/v1/thread/async") );

                    Thread.Sleep(150);
                }

                Task.WaitAll(async.ToArray() );

                stopwatch.Stop();

                Console.WriteLine("Async used " + http.GetAsync("http://localhost:5000/api/v1/thread/async/count").Result.Content.ReadAsStringAsync().Result + " threads in " + stopwatch.ElapsedMilliseconds + "ms");
            }

            Console.ReadLine();
        }
    }
}

The results I got:
first run:
Sync used 19 threads in 22412ms
Async used 8 threads in 12911ms

second run:
Sync used 18 threads in 21083ms
Async used 10 threads in 12921ms

third run:
Sync used 20 threads in 13578ms
Async used 10 threads in 12899ms

fourth run:
Sync used 18 threads in 21018ms
Async used 5 threads in 12889ms

Answer: Here they do a gd job at exampling and its a good example.
Shouldn't lesser number of threads be used if I use async?


SQL1024N when using DB2 in Cygwin

Question: I have DB2 version 188.8.131.527 on Windows 10
and Cygwin version 3.2.0(0.340/5/3)
I am trying to use DB2 from within Cygwin but it is not holding onto the db2 connection after successfully connecting.
Anyone have any suggestions?
How to reproduce:
(1) Start a Windows cmd window as Administrator
(2) Start a "DB2 Command Window - Administrator" :
"C:\Program Files\IBM\SQLLIB\BIN\db2cwadmin.bat"
(3) Start Cygwin inside the DB2 Command Window :
C:\cygwin64\bin\mintty.exe -i /Cygwin-Terminal.ico -
(4) Manually connect to the database(successfully) :
GMX+I10030754@DESKTOP-I1IQG9H ~
$ db2 connect to DB3270GA user db2admin using password
Database Connection Information
Database server        = DB2/NT64 11.1.0
SQL authorization ID   = DB2ADMIN
Local database alias   = DB3270GA
(5) Running any sql statement returns SQL1024N
GMX+I10030754@DESKTOP-I1IQG9H ~
$ db2 select * from myschema.application
SQL1024N  A database connection does not exist.  SQLSTATE=08003
Comment: in your bash (or whichever shell you are using) startup file, is the DB2CLP environment variable exported?  Example: `export DB2CLP=**$$** `  ?
Comment: @mao Thanks for that suggestion. When I added that export - it then failed to connect to DB2 at step(4) with DB21018E. I replaced that export statement with "export DB2CLP=DB20FADE" as recommended elsewhere and the original issue returned - failed at step (5) with SQL1024N.
Comment: after exporting the variable, kill any previously existing db2bp.exe started from cygwin.  Ensure to exit from and restart bash, then retry. It is the `db2bp.exe` that keeps the database-connection, so that process needs to continue to exist and have communications from db2.exe (clp) when it runs.  If db2.exe cannot contact or identify the db2bp.exe background task you get the SQL1024N I believe.
Comment: @mao That appears to be the issue. I can see a db2dp.exe process start up in the Task Manager when i issue the DB2 connect command. However it disappears after a few seconds. The question now is : how can we keep that background task(db2dp.exe) alive?
Comment: Does the same symptom if you use ksh (pdksh) instead of bash as the shell (still need to export the DB2CLP variable in the .profile or .kshrc for shell). ?
Answer: Try the following in a cygwin session:
<code>export DB2CLP=**$$**
# a connection will be closed after 5 seconds of inactivity otherwise
export DB2RQTIME=3600
db2 connect ...
sleep 10
db2 "select ..."
</code>
Comment: @mao and Mark, thank you both very much for spending time on this. I have tried various exports as suggested(and others) but the problem remains the same. Due to time pressures, I have to abandon this Cygwin approach.
Comment: The commands in this answer worked for me with Cygwin 3.4.6 and Db2 v11.5.8000.317 on Windows 10 v22H2. It also appears that Cygwin is the only command shell on Windows that needs the DB2CLP environment variable set to the pid of the current shell via `export DB2CLP=**$$**` in order for the Db2 CLP to work properly. The Db2 CLP evidently works fine in CMD.EXE and PowerShell no matter what value is assigned to DB2CLP, so long as it contains something.
Comment: It may help to point out that I needed to save the above commands into my `~/.bash_profile`
Answer: Older versions of Cygwin (e.g. 1.7.3) expand $$ to the Windows PID, newer versions (e.g. 3.3.4) to the Cygwin PID.
So you have to use:
export DB2CLP="**$(cat /proc/$$/winpid)**"
...and everything works fine.

SQL1024N when using DB2 in Cygwin


How to send JSON string from arduino to android device in terms of response and then decode the string on the android application?

Question: I am currently working on a project whereby i need to send a request from an android application to my Arduino mega which in turns response back with the states of LEDs connnected to the Arduino. I have already implemented the GET request. However i need to know how to read the response back and how to send the string from the Arduino to the Android app.
Here is the code for the response:
<code>client.println("HTTP/1.1 200 OK");
client.println("Content-Type: application/json");
client.println("Connection: close");
client.println();
client.println("{\"status\":\"ok\"}"); // <--- how to create the string?
</code>
and also how to decode it from the android application. I have seen tutorials on the internet about using InputStream to do so but am unable to understand the code. Could you please help me on this.
Comment: Would recommend using `Retrofit` (and `gson`) for something like this.
Comment: I have never used retrofit. I have already written the cod in an Async task class. The issue is that how can i read send the string from the arduino and then how i read the response back in the doInBackground method in the Async Task
Comment: As the Arduino is usually very restricted I recommend not to use HTTP if you only want to send one string. A simple string can be send directly via socket.
Answer: You have to implement a Webserver on Arduino side and use a HTTP library (i.e. OkHTTTP) to connect to the Webserver.
I used OkHTTP on Android side but you could use other libraries too.
This link is something like you are looking for. It is from my blog.
Otherwise you can use aRest. It is very simple to use. If you want to know more give a look at this link from my blog.


Is $\displaystyle\lim_{x\to a}\text{sgn}(f(x))$ always equal to $\text{sgn}\left(\displaystyle\lim_{x\to a}f(x)\right)$?

Question: Take this limit for example:$$\lim_{x\to0^+}\text{sgn}(x^{-\ln x})\\\text{sgn}(x):=
\begin{cases}
-1\quad&x\lt0\\
0\quad&x=0\\
1\quad&x\gt0
\end{cases}$$
Now, it can be shown that this limit has a value of $0$, however, this makes the assumption that$$\lim_{x\to a}\text{sgn}(f(x))=\text{sgn}(\lim_{x\to a}f(x))$$and my question is, is this always true, or when is this false?
For context, I was finding limits such as $\displaystyle\lim_{x\to0^+}\text{sgn}(x^{-\ln x})$,  $\displaystyle\lim_{x\to1^+}\text{sgn}(\ln(x)^{-\ln\ln x})$, and $\displaystyle\lim_{x\to0^+}\text{sgn}\left(\frac{x^2+4x-45}{e^x\ln x}\right)$ and was confused by what I was finding.
Comment: Consider $f(x)=x$ and $x\to 0$.
Answer: We have
\begin{align*}
\lim_{x\to0^+}\text{sgn}(x^{-\ln x}) = 1
\end{align*}
Not $0$. Because $x^{-\ln x} > 0$ for all $x > 0$. I will prove it by definition of right limit. If $\varepsilon > 0$, let
$\delta = \varepsilon$. If $0 < x - 0 < \delta$, then $x^{-\ln x} >0$, hence
\begin{align*}
\left\vert \text{sgn}(x^{-\ln x}) - 1 \right\vert = 0 < \varepsilon
\end{align*}
Although
\begin{align*}
\text{sgn}\left(\lim_{x\to0^+} x^{-\ln x}\right) = 0
\end{align*}
because is true that $\lim_{x\to0^+} x^{-\ln x} = 0$.
So the answer is no, it's not equal.


C# / SQL Error: There was an error parsing the query. [ Token line number = 1,Token line offset = 26,Token in error = user ]

Question: I can't my mind around this error. The server error point out towards this line:
<select name="selectUserName">
        @foreach(var row in db.Query(selectQueryString)) {
          <option>@row.username</option>
        }
      </select>

where selectQueryString is defined as:
var selectQueryString = "SELECT ID, username FROM user";

Answer: User is a reserved word in SQL Server.  Try:
FROM [User]

Answer: USER is a reserved keyword in SQL Server.
You should use it with squared brackets []
Like;
var selectQueryString = "SELECT ID, username FROM [USER]";


Cast automático com TypeScript?

Question: Direto ao ponto:
Existe uma maneira de realizar cast automático utilizando uma interface como modelo no Ionic (TypeScript + Angular 5)?
Se não, é possível fazer o Lint reconhecer que um objeto vindo do servidor não está dentro do contrato de interface esperado?
Cenário:
Estou utilizando Ionic (Angular versão 5) e um backend em PHP. Meu problema é na hora de tratar os dados vindos do servidor usando uma interface que criei.
Eu tenho duas interfaces que trabalham juntas:
export interface QuestionInterface {
    id_question: string,
    answers: Array<AnswerInterface>,
    question_text: string
}

export interface AnswerInterface {
    answer_text: string,
    is_correct: boolean
}

Dentro da aplicação, tudo funciona perfeitamente e recebo os alertas quando tento usar tipos que não estão no contrato. O problema é quando os dados chegam do servidor.
http.get('xxx')
.toPromise()
.then(result=> {

})

A requisição retorna um objeto que contém, em result.data, dados de uma tabela. Porém, como a coluna is_correct é do tipo tinyint(1), esses dados chegam pra mim como "0" ou "1".
Não queria ter que fazer o cast manualmente, porque acho muita gambiarra. Alguém consegue pensar em alguma forma de realizar uma conversão "automágica"?
Caso contrário, como fazer o objeto que vem do servidor passar por uma verificação de contrato com a interface?
Answer: Pode usar:
result.data.is_correct == "1"

var x = "1";
console.log(x == "1");
x = "0";
console.log(x == "1");

Coloquei no GitHub para referência futura.
Comment: Acho que aí você quer mágica.
Comment: Dois problemas: vou ter que varrer todos os objetos e não queria ter que fazer isso; os tipos são string, não number e esse teste sempre vai ser true. Eu entendo que posso fazer esse casting manualmente, mas queria evitar, se houvesse um meio de realizar esse cast.
Comment: Ah, sim. Resolve o segundo problema mas,ainda assim, preciso varrer os elementos todos. Se der pra evitar...
Answer: Voce pode criar uma propriedade a mais na sua interface assim
is_correct:number;
is_correct_bool: boolean;

Ai depois pode usar o
this.QuestionInterface.answers.forEach(element => {
        element.is_correct_bool = element.is_correct == "1" : true ? false;
});

Nesse exemplo o "QuestionInterface" seria a sua variável desse tipo ... depois de receber o retorno em JSON.
Assim ia ser feito de uma vez sem precisar passar manualmente 1 a 1.

Cast automático com TypeScript?


Well ordering on sequences over well-ordered sets

Question: I'm trying to solve problem 4.4.8 of Hrbacek & Jech's Introduction to Set Theory.  The problem reads in part,

Let $(A,<)$ be linearly ordered.  Define $\prec$ on $\operatorname{Seq}(A)$ by: $\langle a_0, \dots, a_{m-1} \rangle \prec \langle b_0, \dots, b_{n-1} \rangle$ if and only if there is $k < n$ such that $a_i = b_i$ for all $i < k$ and either $a_k < b_k$ or $a_k$ is undefined (i.e. $k = m < n$)... If $(A, <)$ is well-ordered, $(\operatorname{Seq}(A), \prec)$ is also well-ordered.

This looks to me like the lexicographic ordering of dictionary words, where a finite sequence that extends a shorter sequence comes after in the ordering.  But then the sequence of strings $ab > aab > aaab > \cdots$ is an infinite decreasing sequence of words in $\operatorname{Seq}(A)$, which I think proves that $\operatorname{Seq}(A)$ cannot be a well ordering.
I must be making a simple mistake here, but in two days I haven't managed to find it!  Can someone point out where I am going wrong?
Answer: You are correct, and there is an error in the definition of $\prec$ that you have written.  The definition of $\prec$ should instead require $a_i=b_i$ for all $i\color{red}>k$ (meaning that for each $i>k$, either $a_i$ and $b_i$ are both defined and equal or they are both undefined).  That is, you should use the reverse lexicographic order, where you start from the end of the sequence instead of the beginning.  (Note in particular that if $n>m$ then always $\langle a_0, \dots, a_{m-1} \rangle \prec \langle b_0, \dots, b_{n-1} \rangle$ by taking $k=n-1$.)


Configuring samba to provide subdomains on a local network

Question: I need to setup an ubuntu VM as a local webserver. I want to use samba to provide some DNS support. The box is accessable from the browser using the NET-BIOS name 'my.box'.
However when  I try a subdomain 'something.my.box' no ip is resolved.
I don't have a clue about windows networking. I used this sample smb.conf to configure samba on ubuntu 9.10:
    [global]
    ; General server settings
    netbios name = YOUR_HOSTNAME
    server string =
    workgroup = YOUR_WORKGROUP
    announce version = 5.0
    socket options = TCP_NODELAY IPTOS_LOWDELAY SO_KEEPALIVE SO_RCVBUF=8192 SO_SNDBUF=8192

    passdb backend = tdbsam
    security = user
    null passwords = true
    username map = /etc/samba/smbusers
    name resolve order = hosts wins bcast

    wins support = yes

    printing = CUPS
    printcap name = CUPS

    syslog = 1
    syslog only = yes

; NOTE: If you need access to the user home directories uncomment the
; lines below and adjust the settings to your hearts content.
;[homes]
    ;valid users = %S
    ;create mode = 0600
    ;directory mode = 0755
    ;browseable = no
    ;read only = no
    ;veto files = /*.{*}/.*/mail/bin/

; NOTE: Only needed if you run samba as a primary domain controller.
; Not needed as this config doesn't cover that matter.
;[netlogon]
    ;path = /var/lib/samba/netlogon
    ;admin users = Administrator
    ;valid users = %U
    ;read only = no

; NOTE: Again - only needed if you're running a primary domain controller.
;[Profiles]
    ;path = /var/lib/samba/profiles
    ;valid users = %U
    ;create mode = 0600
    ;directory mode = 0700
    ;writeable = yes
    ;browseable = no

; NOTE: Inside this place you may build a printer driver repository for
; Windows - I'll cover this topic in another HOWTO.
[print$]
    path = /var/lib/samba/printers
    browseable = yes
    guest ok = yes
    read only = yes
    write list = root
    create mask = 0664
    directory mask = 0775

[printers]
    path = /tmp
    printable = yes
    guest ok = yes
    browseable = no

; Uncomment if you need to share your CD-/DVD-ROM Drive
;[DVD-ROM Drive]
    ;path = /media/cdrom
    ;browseable = yes
    ;read only = yes
    ;guest ok = yes

[MyFiles]
    path = /media/samba/
    browseable = yes
    read only = no
    guest ok = no
    create mask = 0644
    directory mask = 0755
    force user = YOUR_USERNAME
    force group = YOUR_USERGROUP

Answer: Use netbios aliases = to add more NetBIOS names which your Samba server should advertise.  This assumes that something.my.box should resolve the same IP as my.box.  (Otherwise, you should use DNS.)


How are the different events classified according to tiers on the Women's Tennis circuit?

Question: On the Men's side, it's fairly simple & unambiguous. Men's tennis events for the season are classified into 3 tiers. ATP Masters 1000, ATP 500 & ATP 250 in decreasing order of importance based on points.
However, on the Women's side, there seems to be 3 tiers but the events are classified as WTA Premier & WTA international in decreasing order of importance based on points. But at this point it gets ambiguous. Taking into account the recent tournaments, WTA Tokyo(concluded today) & WTA Wuhan(starting today) are listed as WTA Premier events. But WTA Tokyo awards 470 points while WTA Wuhan awards 900 points.
So how can I unambiguously classify WTA events based on tiers? Also please list all the WTA events in a season which are Tier 1(900 points events)
Answer: In 2009 WTA has reformed categories for tournaments (source).
Since 2009 tournaments are splitted in:

4 Premier Mandatory (1000 points each)
5 Premier 5 (900 points)
12 Premier (470 points)
several international tournaments (280 points)

Obiovously the most important tournaments are:

4 Grand Slam (2000 points each)
WTA finals (1500 points)

Befor 2009 the tournaments could be: Tier I, Tier II, Tier III, Tier IV
Comment: It seems WTA, changes the category of events faster than comprehension. They downgraded Tokyo & brought in Wuhan in 2014. They did it with Qatar in 2015


Proving a subgroup generated by a subset is a normal subgroup using universal properties

Question: I have the following (from Aluffi II.7.7):

Theorem: Let $G$ be a group and $H \leq G$ be generated by all elements of a fixed order $N$. Then $H$ is a normal subgroup of $G$.

I came up with a fairly simple proof using the concrete description for "the subgroup generated by a subset": the subgroup consists of exactly the products of elements of the subset.

Proof: Using the concrete description for $H$, any element $h \in H$ can be written as:
$$ h = \prod_{1 \leq i < k} a_i,$$
where each $a_i$ has order $N$. But for any $g \in G$, we know each $g a_i g^{-1}$ has order $N$ as well, so:
$$ \prod_{1 \leq i < k} ga_ig^{-1} \in H,$$
but this product is just $ghg^{-1}$. Therefore, $H$ is normal in $G$.

However, I was wondering if there's a proof that uses the following definition of "the subgroup generated by a subset":

Definition:
For any $A \subseteq G$ with the natural map $\iota: A \to G$, the universal property for free groups implies that there exists a unique $\varphi: F(A) \to G$ such that the following diagram commutes:

The subgroup generated by $A$ is then the image of $\varphi$.

One of my attempts is as follows:

Let $G$ be a group, and let $A$ be the elements of order $N$ in $G$. For any $g \in G$, let $\gamma_g$ denote conjugation by $g$; consider the following diagram:

The universal property for free groups guarantees that $\varphi_g$ exists and is unique. However, we also have $\varphi: F(A) \to G$ from the definition of the subgroup generated by $A$:

...

I'm convinced that $??? = \gamma_g$ makes the diagram commute, in which case for any $h \in \text{img }\varphi$, then $h = \varphi(a)$ for some $a \in F(A)$ and $$ghg^{-1} = \gamma_g(\varphi(a)) = \varphi(\varphi_g(a)).$$
Thus, $ghg^{-1} \in \text{img } \varphi$. I'm stuck on how to prove that $??? = \gamma_g$ with just universal properties. I tried invoking the universal property with $\varphi \, j \, \gamma_g : A \to G$ but couldn't seem to get anywhere. Does anyone have suggestions on how to proceed from here?
Comment: The map ??? is not unique though. Certainly $???=\gamma_g$ works, but so does $???=\gamma_h$, whenever $gh^{-1}$ (or $g^{-1}h$ if you act on the other side) centralizes all elements of order $N$. This can happen, most obviously in a direct product of groups of coprime order. You will probably need to assume that $G$ is generated by $A$ first, and then you have ruined your result.
Answer: As David pointed out in the comments, "proving that ??? $= \gamma_g$" is the wrong way to think about it.  In fact, there can be other endomorphisms of $G$ that make your diagram commute; for example, in the silly case $N = 1$, any endomorphism of $G$ makes the diagram commute.
Instead, I would go back to the definition of the morphism $\gamma_g:  A \to A$.  By definition, this is the restriction of $\gamma_g:  G \to G$ to the subset $A$.  It follows that the outer rectangle of your diagram commutes, with ??? = $\gamma_g$.  The problem then is to prove that the upper square commutes as well.  That is, we must show that $\gamma_g \varphi = \varphi \varphi_g:  F(A) \to G$.  By (the uniqueness part of) the universal property of free groups, it suffices to prove that $\gamma_g \varphi j = \varphi \varphi_g j:  A \to G$.  This follows from the commutativity of the bottom square and the outer rectangle.
Comment: Yes.  The universal property says that there is exactly one map $F(A) \to G$ factoring the given map $A \to G$.  Both $\gamma_g \varphi$ and $\varphi \varphi_g$ factor this map, so they must be equal.
Comment: Do you mean $\varphi \varphi_g j: A \to G$, not $\varphi_g \varphi j$?
Comment: Yes, fixed.  Thanks for pointing it out.
Comment: Hmm, I'm not sure I follow why $\gamma_g \varphi j = \varphi \varphi_g j$ implies $\gamma_g \varphi = \varphi \varphi_g$. Are we applying the universal property to $\varphi \varphi_g j: A \to G$?
Comment: I see: the uniqueness in the universal property tells us $\alpha j = \alpha' j = \varphi j \gamma_g \implies \alpha = \alpha'$. Then we take $\alpha = \gamma_g \varphi$ and $\alpha' = \varphi \varphi_g$. Thanks for the help!


Usar Campo tipo Date no Java com MySQL

Question: Estou com um pequeno problema, estou fazendo um teste usando o campo data(Date) no Java, e estou tendo problemas na execução. Segue abaixo os códigos que estou usando:
1º o Código para criar a tabela no MySQL
Create table clientes (
cli_id Integer NOT NULL AUTO_INCREMENT,
cli_nome Varchar(200),
cli_dt_inclusao Date,
cli_endereco Varchar(200),
cli_bairro Varchar(80),
cli_email Varchar(200),
cli_tel Varchar(15),
cli_cidade Varchar(200),
cli_uf Varchar(2), Primary Key (cli_id)) ENGINE = MyISAM;

2º Classe clienteDAL
public class clienteDAL extends conexaoMySQL {
public void incluirCliente(clienteDTO cliente) throws Exception
{
    //Prepara a conexão com o MySQL
    abrirBD();
    sql = "INSERT INTO clientes (cli_id, cli_nome, cli_dt_inclusao, cli_endereco, cli_bairro, cli_email, cli_tel, cli_cidade, cli_uf) VALUES (null, ?, ?, ?, ?, ?, ?, ?, ?)";
    ps = con.prepareStatement(sql);
    //Busca os valores da classe clientesDTO
    ps.setLong(1, cliente.getCli_id());
    ps.setString(2, cliente.getCli_nome());
    ps.setDate(3, (java.sql.Date) cliente.getCli_dt_inclusao());
    ps.setString(4, cliente.getCli_endereco());
    ps.setString(5, cliente.getCli_bairro());
    ps.setString(6, cliente.getCli_email());
    ps.setString(7, cliente.getCli_tel());
    ps.setString(8, cliente.getCli_cidade());
    ps.setString(8, cliente.getCli_uf());
    ps.execute();
    fecharBD();
}

3º Classe clienteDTO
public class clienteDTO {
    private long cli_id;
    private String cli_nome;
    private Date cli_dt_inclusao;
    private String cli_endereco;
    private String cli_bairro;
    private String cli_email;
    private String cli_tel;
    private String cli_cidade;
    private String cli_uf;

    public long getCli_id()
    {
        return cli_id;
    }
    public void setCli_id(int cli_id)
    {
        this.cli_id = cli_id;
    }

    public String getCli_nome()
    {
        return cli_nome;
    }
    public void setCli_nome(String cli_nome)
    {
        this.cli_nome = cli_nome;
    }

    public Date getCli_dt_inclusao()
    {
        return this.cli_dt_inclusao;
    }
    public void setCli_dt_inclusao(Date cli_dt_inclusao)
    {
        this.cli_dt_inclusao = cli_dt_inclusao;
    }

    public String getCli_endereco()
    {
        return cli_endereco;
    }
    public void setCli_endereco(String cli_endereco)
    {
        this.cli_endereco = cli_endereco;
    }

    public String getCli_bairro()
    {
        return cli_bairro;
    }
    public void setCli_bairro(String cli_bairro)
    {
        this.cli_bairro = cli_bairro;
    }

    public String getCli_email()
    {
        return cli_email;
    }
    public void setCli_email(String cli_email)
    {
        this.cli_email = cli_email;
    }

    public String getCli_tel()
    {
        return cli_tel;
    }
    public void setCli_tel(String cli_tel)
    {
        this.cli_tel = cli_tel;
    }

    public String getCli_cidade()
    {
        return cli_cidade;
    }
    public void setCli_cidade(String cli_cidade)
    {
        this.cli_cidade = cli_cidade;
    }

    public String getCli_uf()
    {
        return cli_uf;
    }
    public void setCli_uf(String cli_uf)
    {
        this.cli_uf = cli_uf;
    }

}

4º Classe de teste para Incluir
public class TesteIncluir {
    public static void main(String[] args) throws Exception
    {
        clienteDTO cliente = new clienteDTO();
        cliente.setCli_nome("Teste");
        cliente.setCli_dt_inclusao(new java.sql.Date(System.currentTimeMillis()));
        cliente.setCli_endereco("Rua Teste, 15");
        cliente.setCli_bairro("Java Norte");
        cliente.setCli_email("firstname.lastname@example.com");
        cliente.setCli_tel("77777777");
        cliente.setCli_cidade("Java");
        cliente.setCli_uf("JV");
        clienteDAL dal = new clienteDAL();
        dal.incluirCliente(cliente);
        System.out.print("Cliente "+cliente.getCli_nome()+" Cadastrado com sucesso!");
    }

}

Quando mando executar a classe de teste, no NetBeans, Retorna o seguinte erro:
Exception in thread "main" com.mysql.jdbc.MysqlDataTruncation: Data truncation: Incorrect date value: 'Teste' for column 'cli_dt_inclusao' at row 1
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4118)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4052)
    at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2503)
    at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2664)
    at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2794)
    at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2155)
    at com.mysql.jdbc.PreparedStatement.execute(PreparedStatement.java:1379)
    at br.uniplan.DAL.clienteDAL.incluirCliente(clienteDAL.java:33)
    at br.uniplan.Testes.TesteIncluir.main(TesteIncluir.java:28)
C:\Users\profe\AppData\Local\NetBeans\Cache\8.1\executor-snippets\run.xml:53: Java returned: 1
FALHA NA CONSTRUÇÃO (tempo total: 0 segundos)

Onde estou errando?
Olá, consegui resolver o incluir, meu problema agora é no item alterar, segue abaixo meu método alterar na classe DAL:
public void alterarCliente(clienteDTO cliente) throws Exception
 {
     abrirBD();
     sql = "UPDATE clientes SET cli_nome = ?, cli_dt_inclusao = ?, cli_endereco = ?, cli_bairro = ?, cli_email = ?, cli_tel = ?, cli_cidade = ?, cli_uf = ? WHERE cli_id = ?";
     ps = con.prepareStatement(sql);
     ps.setLong(1, cliente.getCli_id());
     ps.setString(2, cliente.getCli_nome());
     ps.setDate(3, new java.sql.Date(cliente.getCli_dt_inclusao().getTime()));
     ps.setString(4, cliente.getCli_endereco());
     ps.setString(5, cliente.getCli_bairro());
     ps.setString(6, cliente.getCli_email());
     ps.setString(7, cliente.getCli_tel());
     ps.setString(8, cliente.getCli_cidade());
     ps.setString(9, cliente.getCli_uf());
     ps.execute();
     fecharBD();
 }

Classe de teste para Alterar, conforme abaixo:
package br.uniplan.Testes;

public class TesteAlterarCliente {
    public static void main(String[] args) throws Exception
    {
        clienteDTO cliente = new clienteDTO();
        cliente.setCli_id(2);
        cliente.setCli_nome("Teste");
        cliente.setCli_dt_inclusao(new java.sql.Date(System.currentTimeMillis()));
        cliente.setCli_endereco("Rua Teste, 77");
        cliente.setCli_bairro("Java Sul");
        cliente.setCli_email("email@example.com");
        cliente.setCli_tel("88888888");
        cliente.setCli_cidade("Java 8");
        cliente.setCli_uf("J8");
        clienteDAL dal = new clienteDAL();
        dal.alterarCliente(cliente);
        System.out.println("Cliente " + cliente.getCli_nome() + " Alterado com sucesso!");
    }
}
Quando mando executar não dá erro, mas não faz a alteração na tabela. Onde posso estar errando?
Comment: A resposta te ajudou a resolver o problema? É possível aceitá-la?
Answer: Você está errando nos parametros da Query SQL, cada "interrogação" representa um parametro a ser setado no Statement, como não tem ? para o id do Cliente logo ele não precisa ser setado no seu Statement o correto ficaria assim:
Query
INSERT INTO clientes (
cli_nome,
cli_dt_inclusao,
cli_endereco,
cli_bairro,
cli_email,
cli_tel,
cli_cidade,
cli_uf
VALUES (?, ?, ?, ?, ?, ?, ?, ?);

Statement
ps.setString(1, cliente.getCli_nome());
ps.setObject(2, cliente.getCli_dt_inclusao());
ps.setString(3, cliente.getCli_endereco());
ps.setString(4, cliente.getCli_bairro());
ps.setString(5, cliente.getCli_email());
ps.setString(6, cliente.getCli_tel());
ps.setString(7, cliente.getCli_cidade());
ps.setString(8, cliente.getCli_uf());

Comment: Bom dia, caro José Anderson, muito grato, era isto mesmo, resolvido o problema.

Usar Campo tipo Date no Java com MySQL


Conditional mutual information and Markov chain.

Question: If we have the Markov chain $X \to Y \to Z$, or equivalently
$$I(X;Z| Y)=0, \tag{1}$$
where $I(\cdot)$ denotes the mutual information.
Does the Markov chain $X \to (Y,W) \to Z$ also hold?
Or
$$I(X;Z|Y,W)=0~~? \tag{2}$$
Intuitively, I think (2) is true. But how to prove? Thanks in advance.
Another simple question about probabilities,
$$P(Z=z|X=x,Y=y)\cdot P(Y=y)=P(Z=z,Y=y|X=x) \tag{3}$$
Is (3) right? I am confused. Thanks again.
Answer: The answer to your first question is actually no, the second one Markov chain need not be correct. To see this, take a trivial case where $X$ and $Z$ are independent variables and $Y$ is a trivial variable (only one element in its range with probability $1$). Trivially $X$-$Y$-$Z$ form a Markov chain. Now take $W=X \oplus Z$ (i.e. sum modulo $2$), so that it holds the parity of $X$ and $Z$. Now, clearly, knowing $W$ correlates $X$ and $Z$ (if $W=0$, then $X=Z$; if $W=1$, then $X \ne Z$), so that $I(X:Z|W) \ne 0$ (or equivalently $I(X:Z|WY) \ne 0$, as $Y$ is a trivial random variable and including it doesn't harm anything). In other words $X$-$WY$-$Z$ is no longer a Markov chain.
Your second question is regarding the extension of the chain rule to conditional probabilities:
$$P(A_n,\dots,A_1 \mid B) = P(A_n \mid A_{n-1},\dots,A_1,B) \cdot P(A_{n-1},\dots,A_1 \mid B) \ ,$$
so the correct form is:
$$P(Z=z \mid Y=y, X=x) \cdot P(Y=y \mid X=x) = P(Z=z, Y=y \mid X=x) \ .$$
Comment: It's always nice to see long-standing inaccuracies on MSE corrected, and it looks like this question has had an incorrect answer to it for nearly $4$ years. Good job!
Answer: The first is practically trivial, once we understand that the random variables $X$, $Y$... are not necessarily one-dimensional (scalars). So you can just define $S=(Y,W)$ (a multivariate variable) and with that notation you get the first case.
Regarding the second, simplifying/abusing notation:
$$P(Z | X Y ) P(Y) = \frac{P(Z X Y)}{P(XY)} P(Y)$$
and
$$ P(Z Y |X)=\frac{P(Z X Y)}{P(X)}$$
These would be equal iff $\frac{P(Y)}{P(XY)}=\frac{1}{P(Y)}$, or $P(XY)=P(X)P(Y)$, i.e. iff $X,Y$ are independent.
Comment: I could not get your idea. You mean (2) is true?
Comment: @MIMIGA : Yes. Just replace $(Y,W)$ by (say) $S$ and you get (1).


If $A$ is a complex full row rank matrix, why is $A A^T$ necessarily invertible?

Question: There are standard proofs of $ A A^* $ being invertible, but what about $ A A^T $? I am asking this because I want to understand a theorem from wikipedia that states that for a full row rank matrix $A$ it holds that $ A^T (A A^T)^{-1} $ is a right inverse.
Comment: one way to prove is by using [SVD](https://en.wikipedia.org/wiki/Singular_value_decomposition)
Comment: Try $A=(1, \mathrm{i})$.
Answer: It is not true for complex matrices. Take $A=\begin{pmatrix}i & 1\end{pmatrix}$ as a counterexample.


continuity of $f(t,u(t))$ with respect to $t$

Question: My question relates to definition of continuity from calculus.
Let $y=f(t,u(t))$. What does it mean $f$ is continuous with respect to $t$ at $t_{0}$?
Answer: It seems that the definition $y=f(t,u(t))$ is not related to your question. And it seems that $t$ is the first parameter of the function $f$.
The function $f$ is continuous with respect to $t$ at $t_0$ if
$$\lim_{t\to t_0} f(t,x) = f(t_0, x)$$
for any $x$ such that there is a neighborhood of $(t_0,x)$ where $f$ is defined.
Comment: shouldn't the fact that $u$ is a function of $t$ be somehow reflected in this definition?
Comment: $u$ is not part of the definition of $f$ is it @ZviadKhukhunashvili? It would be different if we want to know about the continuity of $y$ with respect to $t$. Then $u$ would be involved.
Comment: what do you mean by "not part of the definition of $f$"?  $u$ is unknown function, $f$ is known.
Comment: @ZviadKhukhunashvili, we could have for instance $f(t,x)=t+x$ and $u(t)=\sqrt t$. Note that the definition of $f$ does not contain any reference to $u$, nor does its continuity depend on it. However, we have $y(t)=f(t,u(t))=t+\sqrt t$, so the continuity of $y$ does depend on $u$.
Comment: then I say $f(t,u(t))$ is the right hand side of an ODE with unknown $u(t)$ and I need to check whether it satisfies conditions of the existence and uniqueness theorem, in particular, continuity of $f$ in $t$.  Should I go with the first way or the second way?
Comment: @ZviadKhukhunashvili, if you have $u'(t)=f(t,u(t))$, then there exists a unique solution around $t_0$ if $f$ is uniformly Lipschitz continuous in its second parameter (let's call it $x$), and continuous in its first parameter $t$.
Comment: that is what I am trying to check.  So do I treat $u(t)$ as fixed and consider the limit above to check for continuity in $t$?
Comment: @ZviadKhukhunashvili, yes, that is half of the check you need to make. For the other half we treat $t$ as fixed, and check uniform Lipschitz continuity with respect to the second parameter $x$.


how to split a continuous variable in linear model

Question: I wonder to know what is the better way to split-up a continuous variable in order to avoid slopes in residuals
require(tidyverse)

data <- mtcars %>% select (disp, hp)
data_splitted <- mtcars %>% select (disp, hp) %>%
mutate(
    disp170 = ifelse(disp  < 170, disp, 0)
  , disp500 = ifelse(disp  < 170, 0, disp - 170)
  , disp = NULL
)
data_capped <- mtcars %>% select (disp, hp) %>%
mutate(
    disp170 = ifelse(disp  < 170, disp, 0)
  , disp500 = ifelse(disp  < 170, 0, disp)
  , disp = NULL
)

lm <- lm(hp ~ disp , data = data)
lm_splitted <- lm (hp ~ disp170 + disp500 , data = data_splitted)
lm_capped <- lm (hp ~ disp170 + disp500 , data = data_capped)

summary(lm)
plot(lm$residuals ~ data$disp)
summary(lm_splitted)
plot(lm_splitted$residuals ~ data_splitted$disp500)
summary(lm_capped)
plot(lm_capped$residuals ~ data_capped$disp500)

Comment: Are you trying to reinvent segmented regression? See https://www.rdocumentation.org/packages/segmented/versions/0.5-3.0/topics/segmented
Answer: My own view is that we should formulate models which answer the question(s) we are interested in, rather than torture the predictor variables until they confess.
When you fit a model like lm(hp ~ disp, data=...), you are essentially assuming that horsepower (hp) tends to either increase or decrease linearly as displacement (disp) increases and you are interested in estimating the rate of increase/decrease from the data. (In this model, you are treating disp as a continuous variable). The model answers questions such as: Does hp tend to increase/decrease with disp and if so, at what rate?
Let's say now that instead of working with the continuous version of the predictor displacement, you are going to work with a binary version of this predictor, defined like this:
disp.binary = 1 if disp > observed mean value of disp in the data
disp.binary = 0 otherwise

In other words, disp.binary keeps track of whether or not displacement is bigger than average.
We can now fit the model lm(hp ~ disp.binary, data = ...) to the data but this model will answer a different question: Do cars with a displacement which is bigger than average tend to have a larger/smaller horsepower than cars with a displacement which is not bigger than average?
Of course, in practice people discretize predictor variables all the time, sometimes not realizing that not only does this lead to a loss of information but also to answering different questions based on their models.
If you have to discretize a predictor variable, you should at least do so in a way which ensures that you are still answering relevant questions. Some people discretize variables using cut-offs pulled out from the literature or inspired by other subject-matter considerations. Others use data-driven cut-offs like the observed mean of the variable to be discretized or the observed quantiles. The problem with data-driven cut-offs is that they are not portable across similar studies, since they reflect the idiosyncrasies of the data collected in the study at hand.
If you are contemplating discretization of a predictor variable simply because some of the assumptions underlying your current model are violated by the data, there are better options available to you. For example, consider a more flexible model which allows the effect of the predictor to be nonlinear rather than linear or perhaps consider transforming the predictor before including it in your model.


Faild to settext in textview.Error:-android.content.res.Resources$NotFoundException: String resource ID #0x0

Question: First of all, I am a beginner at android. I am actually trying to build a quiz app. but I am getting stuck with an error that is unexpected.when I clickNext button, I found an error. I was searching for the same question in StackOverflow but I could not find an expected solution. here is my code:-
MainActivity.java
package com.example.hellowandroid;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private Button falsebutton;
    private Button truebutton;
    private TextView questionTextView;
    private ImageButton nextButton;

    private int currentQuestionIndex = 0;

    private Question[] questionBank = new Question[]
            {       new Question(R.string.question_amendments, false),
                    new Question(R.string.question_constitution, true),
                    new Question(R.string.question_declaration, true),
                    new Question(R.string.question_independence_rights, true),
                    new Question(R.string.question_religion, true),
                    new Question(R.string.question_government, false),
                    new Question(R.string.question_government_feds, false),
                    new Question(R.string.question_government_senators, true),
            };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        falsebutton = findViewById(R.id.false_button);
        truebutton = findViewById(R.id.true_button);
        questionTextView = findViewById(R.id.answer_text_view);
        nextButton = findViewById (R.id.next_button);

        falsebutton.setOnClickListener(this);
        truebutton.setOnClickListener(this);
        nextButton.setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {

        switch (v.getId())

        {
            case R.id.false_button:
                Toast.makeText(MainActivity.this,"false",Toast.LENGTH_SHORT).show();
                break;
            case R.id.true_button:
                Toast.makeText(MainActivity.this,"true",Toast.LENGTH_SHORT).show();
                break;

            case R.id.next_button:

                //go to next question
                currentQuestionIndex = (currentQuestionIndex + 1) % questionBank.length;

                Log.d("Current Index","onClick"+currentQuestionIndex);

                questionTextView.setText((questionBank[currentQuestionIndex].getAnswerResId()));

        }

    }
}

maybe this line questionTextView.setText((questionBank[currentQuestionIndex].getAnswerResId())); has a problem, I am not sure.
Question.java
package com.example.hellowandroid;

public class Question {
    private int answerResId;
    private boolean answerTrue;

    public Question (int answerResId,boolean answerTrue)
    {
        answerResId=this.answerResId;
        answerTrue=this.answerTrue;

    }

    public int getAnswerResId() {
        return answerResId;
    }

    public void setAnswerResId(int answerResId) {
        this.answerResId = answerResId;
    }

    public boolean isAnswerTrue() {
        return answerTrue;
    }

    public void setAnswerTrue(boolean answerTrue) {
        this.answerTrue = answerTrue;
    }
}

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:gravity="center"
    android:background="@color/design_default_color_primary_dark"
    tools:context=".MainActivity">

    <ImageView
        android:src="@android:drawable/ic_dialog_dialer"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

    <TextView
        android:id="@+id/answer_text_view"
        android:text="@string/question_declaration"
        android:padding="10dp"
        android:textColor="@android:color/background_light"
        android:textSize="16sp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

    <LinearLayout
        android:orientation="horizontal"
        android:layout_marginTop="64dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">

        <Button
            android:id="@+id/true_button"
            android:text="@string/true_text"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"/>

        <Button
            android:id="@+id/false_button"
            android:text="@string/false_text"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"/>

    </LinearLayout>

    <ImageButton
        android:contentDescription="@string/next_text"
        android:id="@+id/next_button"
        android:src="@android:drawable/ic_media_next"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

</LinearLayout>

strings.xml
<resources>
    <string name="app_name">HellowAndroid</string>

    <string name="true_text">true</string>
    <string name="false_text">false</string>
    <string name="question_declaration">General Knowledge Of US Students.</string>
    <string name="correct_answer">That\'s correct</string>
    <string name="wrong_answer">That\'s incorrect</string>
    <string name="question_constitution">The Supreme law of the land is the Constitution.</string>
    <string name="question_amendments">The (U.S.) Constitution has 26 Amendments.</string>
    <string name="question_independence_rights">The two rights in the Declaration of Independence are:
        \n \t life \n  \t pursuit of happiness.</string>
    <string name="question_religion">Freedom of religion means:
        \n \t You can practice any religion, or not practice a religion.</string>
    <string name="question_government">Journalists is one branch or part of the government.</string>
    <string name="question_government_feds">Congress does not make federal laws.</string>
    <string name="question_government_senators">There are one hundred (100) U.S. Senators.</string>
    <string name="next_text">next</string>

</resources>

Here is the error:-
E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.hellowandroid, PID: 27079
    android.content.res.Resources$NotFoundException: String resource ID #0x0
        at android.content.res.Resources.getText(Resources.java:1184)
        at android.widget.TextView.setText(TextView.java:5218)
        at com.example.hellowandroid.MainActivity.onClick(MainActivity.java:81)
        at android.view.View.performClick(View.java:6312)
        at android.view.View$PerformClick.run(View.java:23985)
        at android.os.Handler.handleCallback(Handler.java:751)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:154)
        at android.app.ActivityThread.main(ActivityThread.java:6816)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1563)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1451)

also i tried questionTextView.setText(""+ questionBank[currentQuestionIndex]. getAnswerResId()); but same error. it's main is mainly happend when i click next button.how i resolve this issue.
Answer: You have set these variables the wrong way.
public Question (int answerResId, boolean answerTrue)
{
  answerResId = this.answerResId;
  answerTrue = this.answerTrue;
}

It should have been like this:
public Question (int answerResId, boolean answerTrue)
{
  this.answerResId = answerResId;
  this.answerTrue = answerTrue;
}

Answer: The value of currentQuestionIndex must be smaller than the value of questionBank.size():
if (currentQuestionIndex >= questionBank.size()) {
   throw new IndexOutOfBoundsException(
       "no item exists at index " + currentQuestionIndex
   );
}

And I really do not understand the purpose of this % modulo operation here:
currentQuestionIndex = (currentQuestionIndex + 1) % questionBank.length;

The common way of writing that might rather be:
currentQuestionIndex ++;

Comment: Now i found an error now ```can not find symbol method size()```
Comment: I am use ```currentQuestionIndex = (currentQuestionIndex + 1) % questionBank.length;``` instead ```currentQuestionIndex ++;``` because when my questionindex>questionSize then automaticly currentQuestion start from 0.
Comment: With an array, that may be `.lenght()` (just use an ArrayList, as anybody else and the code would work). And your business logic provides no sense, as the error clearly shows. It's almost funny how you point out one minor typo, while presenting code that just doesn't work. Do you want to tell me, that your code is correct?
Comment: Thanks, problem solved.


Safe PDF view in ASP.NET MVC

Question: I have a PDF file and I want to allow users to view it online, but I want to prevent this document from being downloaded. Does know any solution to achieve that ?
Comment: see these http://stackoverflow.com/questions/4930914/prevent-pdf-file-from-downloading-and-printing, http://stackoverflow.com/questions/4043801/how-to-prevent-pdf-document-from-being-download-to-users-pc
Answer: This is fundamentally impossible.
The only way to view a PDF is to download it to a temp folder.  (the browser does this automatically)
On a deeper level (for any type of document), it is fundamentally impossible for you to tell what is sending an HTTP request.
Answer: You could convert those PDFs to an ePaper solution.
This is one option... but there are lots.
Comment: This answers the wording of the question... but the end user still has the "ePaper" file. It is trivially more complex to use it, but still...
Comment: @AndrewBarber, yep... it is more an alternative that a solution :)

Safe PDF view in ASP.NET MVC


Is $f(X)=-tr(AXBX^T)$ convex?

Question: Given $A,B \in \mathbb{R}^{N \times N}$ and they are non-negative matrix.
Is $f(X)=-tr(AXBX^T)$ convex when $X$ is also non-negative?
If yes, how can I show that?
Comment: Is there any condition on $A$ and $B$?
Comment: @Raskolnikov No, just squared real matrices
Comment: Well, suppose for some choice of $A$ and $B$, your function is convex, then change $B$ with $-B$ and your function is concave.
Comment: @Raskolnikov Thanks for pointing this out. I think I have to add one more thing: $A$ and $B$ are non-negative.
Comment: Then the answer is trivially "no" since when $N=1$, one is looking at the function $f:x\mapsto-abx^2$, which is concave when $ab\gt0$.
Comment: This seems to have some relation with Lieb's concavity theorem. See the Wikipedia article on trace inequalites: http://en.wikipedia.org/wiki/Trace_inequalities. But do you really have a minus sign?
Answer: When applied to matrices (instead of operators), "nonnegative" usually means entrywise nonnegative. I am not sure if you are considering nonnegative matrices or positive semidefinite matrices, but the answer is "no" in both cases.
If $A$ and $B$ are nonnegative, the answer is no in general. For examples, when $A=B=\pmatrix{0&1\\ 1&0}$ and $X=\pmatrix{x&z\\ y&w}$, $-\mathrm{trace}(AXBX^T)=-2(wx+yz)$ is neither convex nor concave: put $w=x=0$ and observe that $yz$ is not midpoint concave if we consider $y=z$, and it is not midpoint convex if we consider $(y_1,z_1)=(1,3)$ and $(y_2,z_2)=(3,1)$. Note that the $X$ in this counterexample is nonnegative too.
If $A$ and $B$ are positive semidefinite, then
$$
-\mathrm{trace}(AXBX^T)=-\mathrm{trace}(A^{1/2}XB^{1/2}B^{1/2}X^TA^{1/2})=-\mathrm{trace}\left((A^{1/2}XB^{1/2})(A^{1/2}XB^{1/2})^T\right),
$$
which is a concave function of $X$. Again, this is not convex in general.

Is $f(X)=-tr(AXBX^T)$ convex?


Prove that every $G$-invariant subspace of $V \otimes U$ has the form $V \otimes U_{0}$.

Question: Knowing the following theorem:

Theorem 4. Let $T$ be an irreducible complex representation of the group $G$ in the space $V$, and let $I$ be the trivial representation of $G$ in the space $U$. Then every minimal subspace $W \subset V \otimes U$ invariant under the representation $TI$ has the form $V \otimes u_0$, where $u_0 \in U$.

How can I prove that:

Every $G$-invariant subspace of $V \otimes U$ has the form  $V \otimes U_{0}$, where $U_{0}$ is a  subspace of $U$.

Could anyone help me please?
Comment: It is related in that you already know what minimal invariant subspaces look like, and I just told you how to relate any invariant subspace to minimal ones
Comment: A $G$-invariant subspace is a sum of minimal $G$-invariant subspaces.
Comment: $G$ is not finite dimensional, it's finite, or the space is finite dimensional, don't mix the two. I agree that it need not be true if $G$ is infinite (though that's not an iff). I was assuming that $G$ was finite in my comment. If it's not it might require a bit more work, but then again so must the theorem. I'll write an answer when I have the time
Comment: What is the relation between your hint and the theorem mentioned above Max, the question says under the assumptions of theorem 4 prove that ..... Could you please clarify more ?
Comment: @Max this question from the book of Vinberg section 4
Comment: @Max my professor said that your first comment is generally incorrect ..... it is correct iff $G$ is finite dimensional ...... so why $G$ is finite dimensional in our case?
Comment: Thank you so much ...... I appreciate this @Max
Comment: Actually I realized the proof I had in mind still used that either $V$ is finite dimensional (no assumptions on $U$ or $G$ though). I'll think about it
Answer: The following works whenever $V$ has dimension $< |\mathbb{C}|=\mathfrak{c}$, so it is not a complete answer.
I will use the Jacobson density theorem, as stated for instance on the wikipedia page with the same name (I will use left modules instead of right modules but that doesn't matter of course):

The Jacobson Density Theorem. Let $U$ be a simple left $R$-module, $D = \operatorname{End}\left(_R U\right)$, and $X \subset U$ a finite and $D$-linearly independent set. If $A$ is a $D$-linear transformation on $U$ then there exists $r \in R$ such that $A\left(x\right) = rx$ for all $x \in X$. (Isaacs, Theorem 13.14, p. 185.)

Indeed $V$ is an irreducible representation of $G$, hence a simple $\mathbb{C}G$-module.
Now by Schur's lemma, with our hypothesis on the dimension of $V$, $End_{\mathbb{C}G}(V) = \mathbb{C}Id$ (the usual form of Schur's lemma assumes finite dimensions, but actually you can make it work if the dimension is strictly smaller than the size of the field - if you don't know about that I can add a few words for that).
Therefore, using the notations of wikipedia, that is $D=End_{\mathbb{C}G}(V) = \mathbb{C}Id$, a subset $X$ of $V$ is $D$-linearly independent if and only if it is $\mathbb{C}$-linearly independent, and a $D$-linear map is simply a linear map: we will use this.
Let $(e_i)_{i\in I}$ be a basis for $V$.
Let's now get to the proof : let $W\subset V\otimes U$ be a $G$-invariant subspace, and let $\displaystyle\sum_{i\in J}e_i\otimes u_i\in W$, with $J$ a finite subset of $I$, $u_i\in U\setminus\{0\}$ for $i\in J$.
Then for all $\alpha\in \mathbb{C}G$ as $W$ is $G$-invariant and $U$ has a trivial $G$-action, we get that $\displaystyle\sum_{i\in J}(\alpha e_i)\otimes u_i \in W$.
Let $i\in J$ and $j \in I$, and let $f_{ij}:V\to V$ be defined by sending every $e_k$ to $0$ except for $e_i$, which it sends to $e_j$. Then $f_{ij}$ is linear, hence $D$ linear. Hence, by the Jacobson density theorem, since $X=\{e_j, j\in J\}$ is linearly independent, hence $D$-linearly independent, we get that there is $\alpha \in \mathbb{C}G$ such that $f_{ij}(x)= \alpha x$ for $x\in X$. In particular $e_j\otimes u_i =\displaystyle\sum_{k\in J}\alpha e_k\otimes u_k\in W$.
Therefore $V\otimes u_i\subset W$ for all $i$. So now if you take $U_0 = \{u\in U\mid \exists i\in I, e_i\otimes u \in W\}$.
By the Jacobson density theorem again, it follows that $U_0$ is a subspace of $U$, moreover by the above proof it's clear that $V\otimes U_0 = W$.
I don't know if the result is true when $V$ has arbitrary dimension, and if it is I don't know how to prove it (yet). I do suspect that the result you were expected to prove had some kind of finiteness assumptions. If you have some finiteness assumptions ($G$ finite, or more generally $V$ finite dimensional), the proof becomes much easier
Comment: I am not sure about your definition of $U_0$, but there is an easier way to complete your proof: For each $i \in I$, let $f_i : V \otimes U \to U$ be the map sending each $e_k \otimes u$ to $0$ if $k \neq i$ and to $u$ if $k = i$. (This is an example of tensor contraction.) Now, set $U_0 = \sum_{i \in I} f_i\left(W\right)$. The argument made earlier proves that $e_k \otimes f_i\left(u\right) \in W$ for each $k \in I$ and $i \in I$; thus, $e_k \otimes U_0 \subset W$ for each $k \in I$; thus, $V \otimes U_0 \subset W$. And of course, the opposite inclusion holds.
Comment: @darijgrinberg : I don't know if it's easier, but of course what's easier depends on people. About my definition of $U_0$ : what I proved earlier was that if $\sum_i e_i\otimes u_i \in W$, then for all $j,i$, $e_j\otimes u_i \in W$, therefore $U_0$ is a good candidate for being a "tensor complement". That it is a subspace is clear because if $e_i\otimes u, e_j \otimes v \in W$, then by the result I just stated, $e_i\otimes v\in W$ as well, so we can just sum them.


$W^{1,\infty}$ function that cannot be approximated by Smooth Functions

Question: I am trying to find a function $u \in W^{1,\infty}$ that cannot be approximated by smooth functions. It seems like it should be an easy construction but I am blanking. Thanks.
Answer: Any Lipschitz function that is not $C^1$ will do, since convergence in the $W^{1,\infty}$ norm implies uniform convergence (for the function and its derivatives) in $C^1$.
Answer: For example take $u(x):=|x|$ on $\mathbb{R}$. I assume that you can prove that $u\in W^{1,\infty}(\mathbb{R})$ (more generally, it is not so difficult to see that $W^{1,\infty}(\mathbb{R})$ consists exactly of the Lipschitz functions).
The weak derivative of $u$ is $v(x)=\text{sgn}(x)$ (which equals $1$ on $\mathbb{R}^+$ and $-1$ on $\mathbb{R}^-$).
Now take any smooth $f\in C^{\infty}(\mathbb{R})\cap W^{1,\infty}(\mathbb{R})$: if $f'(0)\ge 0$ then
$$\lim_{x\to 0^-}|f'(x)-v(x)|=|f'(0)-(-1)|\ge 1,$$
so $\|f'-v\|_\infty\ge 1$; if instead $f'(0)\le 0$ then
$$\lim_{x\to 0^+}|f'(x)-v(x)|=|f'(0)-1|\ge 1,$$
so again $\|f'-v\|_\infty\ge 1$.
In any case you get $\|f-u\|_{W^{1,\infty}}\ge 1$.
But if you weaken your requirement the situation improves: there is always a sequence of smooth functions $f_n$ such that $f_n\to u$ in $L^\infty$ and $f_n'\rightharpoonup u'$ in the weak-$*$  topology of $L^\infty$.
Answer: $u(x)=|x|$ for $-1<x<1$? (Weak) $u'(x)=H(x)=1[x>0]+0[x<0]$ (where $[]$ is Iverson bracket), that's discontinuous, so no uniform ($L^\infty$) convergence of continuous (let alone smooth) function sequence.
Comment: I think you mean $-1[x<0]$ in the definition of $H$?
Comment: Yep. Anyway Mizar's answer has the same idea, it is much more detailed and was posted a couple of minutes before mine.