jQuery click target selector

Question: I have the following HTML in a page:

and I have the following javascript that attempts to handle the click event:
function InitProgressionSelectors() {
$(".move-next").click(function() {
    moveNext(this);
});

$(".move-previous").click(function() {
    movePrevious(this);
});
}

function moveNext(target) {
    var sourceContainer = target.parent("td");
    var targetContainer = sourceContainer.next("td");
}

I'm obviously missing something, because "target" in the moveNext function is returning an HTMLAnchorElement, but when I try to wrap that, or access it somehow as a jQuery object, so I can try to get a handle to it's parent container, I get errors.
A reference to $(target) returns null. How do I get a reference to target as a jQuery object so I can work with it in that context? What am I missing?
Thanks.
Comment: idon't remeber whether parent and next belongs to jquery api or regular javascript , right now you are just passing this and using this.parent , if you want to use jquery , you need to use $(this).parent ///
Comment: Could you perhaps post a demo that reproduces your problem at [JS Fiddle](http://jsfiddle.net/) or [JS Bin](http://jsbin.com/)?
Comment: Wow...I'm an idiot. @gov - You were right, I needed to be passing $(this), not just "this". That got me where I needed to be. Thanks.
Comment: you can give a vote , if you like my answer...
Answer: You need pass the jquery object
$(".move-previous").click(function() {
    movePrevious($(this));
});

Answer: As I mentioned in the comments below, using $(target) didn't work. However, as can be seen in the comments on the original question above, the solution was to actually pass $(this) as the argument. Once I did that, target.parent resolved to the expected node, and worked.

bob can you try using dollor
$(target)
var sourceContainer = $(target).parent("td");

Comment: "A reference to $(target) returns null" ...so, $(target).parent("td") returns an error.
Comment: @bob can you do a alert before calling the function do a alert(this) , it should print object object///otherwise you have to post the html in jsfiddle
Answer: Another alternative is to pass the function in by reference:
$(".move-next").click(moveNext);

You can then use the selector as expected:
function moveNext() {
    var sourceContainer = $(this).parent("td");
    var targetContainer = sourceContainer.next("td");
}

Please note the lack of parentheses when passing the function to the click handler.

jQuery click target selector


Modeling length of stay with (Cox) regression with censored observations

Question: I'm attempting to model length of stay (LOS) in a psychiatric child/adolescent setting. My LOS is censored for a few patients because they are required to leave the facility when they turn 18.
I was pointed to Cox regression because the time to event model, and because it might deal with the censored data. During the modelling I wondered whether the age at admission might be used as a predictor. However, because this age is directly related to the censoring I'm feeling a little unsure about it. It kind of seems like it would introduce some data leakage?
I'd love some intuition or pointers on how to approach this problem.
Comment: Do you have complete data on entry and arrival ages/times for all those who left before they turned 18?
Comment: How many patients are censored at the age of 18?
Comment: Only around 10. But I'd also be curious what to do if a larger proportion of cases met that condition.
Answer: In my opinion, the mandatory discharge of 18-year-olds will create an inaccurate assessment of the association between age and time-to-discharge. Age results in removal from the dataset either as an event of interest or as a nonevent. The former is acceptable if discharge from aging is of interest under your research hypothesis. The latter prevents observation of the event of interest and is a form of dependent censoring, which must be addressed to test your hypothesis or to obtain meaningful associations.
Options:

Exclude patients who will age-out. If there are few exclusions and you have examples of patients who are nearly 18 with complete hospitalizations, you can obtain accurate estimates of time-to-discharge by excluding patients who will age-out.

Weight the analysis for patients who do not age-out. See: https://journals.sagepub.com/doi/pdf/10.1177/0962280216628900


Obtaining easy-to-interpret decision tree

Question: I am trying to create a decision-tree out of a number of attributes, where there are only two final classes and the classes are highly unbalanced (Class 1: 95.5%; Class 2: 4.5%).
The idea is to profile the members of Class 2. For example, Class 2 members have attribute 1 >= 8, attribute 2 < 6, attribute 3 between 1/1/2013 and 12/31/2013.
A profile would be successful if:

it is easily understandable by the business
it shows an improvement in predicting Class 2 over the trivial classifier; i.e.: those classified using the profile should have a > 4.5% probability of actually being in Class 2.

Using WEKA's J48 algorithm along with its CostSensitiveClassifier on one attribute alone (treading carefully here) gives me the following tree:

Accuracy is 36.615%, which I can live with. 75% of Class 2 records were correctly classified, which is great. Most importantly, those classified as Class 2 had a 5.4% chance of actually being in Class 2, which meets goal (2) above.
Here's the problem: that tree is awfully complicated for just one attribute.
I am ideally looking for a single rule of the type: attr >= x: Y; attr < x: N.
I have tried many different weights in the cost matrix.
My questions are:

What techniques (different algorithms; different options in J48) can I try to obtain a simpler tree?
Perhaps the data just doesn't admit a simpler tree. Can people speak of their experiences interpreting complex trees for non-technical audiences?

I am really new to data mining, so if I've missed relevant information or asked the wrong question, please do let me know and I will correct.
Thanks in advance!
Answer:
Trees aren't great classifiers, so you might not get great results with this approach. The improvement with the classifier doesn't seem that good.
I don't use WEKA, but you can usually set the complexity of the tree fairly easily and reduce it to the number of branches/leaves desired. Sometimes this can be done crudely, by increasing the minimum number of observations in each leaf.
You can change the tree into another graphical representation. With two predictors people sometimes create a grid with blue and red squares for yes/no. With a single predictor you can similarly color a line to indicate yes/no.
Comment: Thanks for your answers! I chose decision trees because they are (theoretically) easy to understand. Do you have any recommendations for classifiers that will do better and still be easy to interpret?
Comment: Don't have any better recommendations. Would consider trying a more complex classifier (logistic or RF) to quantify loss in prediction from using a tree. May not be much, may just be a difficult problem. Depends on your situation, but can sometimes turn a model into simple graphic representation. Point systems, nomograms, and above mentioned grids (for 2 variables) have been used to make models easier to use (?interpretable).


Why do we need the $S \otimes L^{1/2}$ bundle product to determine a $Spin_c$ structure?

Question: I am reading Marino's book on topological field theory and 4-manifolds and I am very confused in the construction of the $Spin_c$ structures for manifolds that do not admit a $Spin$ structure. In the following all manifolds are 4 dimensional.
I will assume I understand that manifolds where the second Stiefel-Whitney class $w_2 \neq 0$ do not admit a $Spin$ structure (although not clear to me). Let us consider therefore such a 4-manifold. In order to construct something like a $Spin$ structure we need the "square root" of a line bundle $L$ which apparently does not exist (or is not well-defined).
Question 1: If $w_2=0$ is it well defined? Why do we only care about $L^{1/2}$ now?
Additionally the spinor bundle $S$ is also not globally defined (and I assume this has to do with $\pm 1$ ambiguities.
Question 2: Am I right? Is there a nice example where going from one chart to another $S$ (or sections of it) changes signs?
But then, magically, the structure $S \otimes L^{1/2}$ is well defined (because negative signs cancel to each other naively). So now we have this $Spin_c$ structure.
Question 3:What do sections of this spin bundle look now? In the case of spin manifolds we only had the spin bundle $S=S_+ \oplus S_{-}$. What is the case now?
I would really like to understand what section of this bundle look like. Finally this yields the final question which is
Question 4: How is the above related to the fact that $Spin_c(n) = Spin(n) \times U(1)?$
Answer: There is a ridiculously well written introduction to Seiberg-Witten theory by Moore here. In particular, I think it answers all your questions. Though everything is in the book, let me just summarize a bit.
Definition:
Basically you can take the following as definitions:
$$Spin (4) = SU(2) \times SU(2) = \left\{ B=\begin{bmatrix} A_+& 0 \\ 0 &A_- \end{bmatrix} : A_\pm \in SU(2)\right\}$$
and
$$Spin^c(4) = \left\{B^c= \begin{bmatrix} \lambda A_+& 0 \\ 0 &\lambda A_- \end{bmatrix} : A_\pm \in SU(2), \lambda \in U(1)\right\}$$
Note that in particular $Spin^c(4)$ is not the direct product $Spin (4) \times U(1)$ (understanding this is quite crucial in knowing why $L^{1/2}$ might not exists).
Note also that there is an inclusion $I : Spin(4) \to Spin^c(4)$.
Homomorphism, actions:
The $Spin(4)$ has natural projections $\rho_\pm : Spin(4) \to SU(2)$, sending $B$ to $A_\pm$. Also $Spin(4)$ has the following double covering to $SO(4)$: (here we think of $\mathbb R^4$ as the space of $2\times 2$ matrices)
$$\rho : Spin (4) \to SO(4), \ \ \ \rho(B) Q = A_- Q (A_+)^{-1}.$$
Similarly, $Spin^c(4)$ admits two homomorphisms $\rho_{\pm}^c$ to $U(2)$, sending $B^c$ to $\lambda A_\pm$ respectively. Also it has the following double covering
$$ \rho^c : Spin^c(4) \to SO(4) \times U(1), \ \ \ \rho^c (B^c) = (\rho (B^c), \lambda ^2).$$
here by $\rho(B^c)$ it means we use the same formula as in the Spin group $Spin(4)$, that is,
$$\rho(B^c) Q = (\lambda A_-) Q (\lambda A_+)^{-1}.$$
Note $B^c \mapsto \lambda$ itself is not well-defined, while $B^c \mapsto \lambda^2$ is: indeed $\lambda^2 = \det (\lambda A_\pm)$. In particular, one has the following homomorphism
$$ \det : Spin_c \to U(1)$$
All these homomorphisms of course induces actions on vector space: $\rho_\pm(B), \rho^c _{\pm } (B^c)$ acts on $\mathbb C^2$, $\det (B^c)$ acts on $\mathbb C$ etc....
Spin structure, associated bundles:
A Riemannian $4$-manifold $(M, g)$ can be understood as the following information: there is an open covering $\{U_\alpha\}$ of $M$ and a family of smooth mappings
$$ s_{\alpha\beta} : U_\alpha \cap U_\beta \to SO(4)$$
with some compatibility conditions. A spin$^c$ structure on $M$ is a lifting of $s_{\alpha\beta}$: that is, a family of smooth mapping (with some compatability conditions)
$$\widetilde{s _{\alpha\beta} }:U_\alpha \cap U_\beta \to Spin^c (4)$$
so that $\rho\circ \widetilde{s _{\alpha\beta} } = s_{\alpha\beta}$. Note that this immediately induces to the following:
$$\rho^c_\pm \circ \widetilde{s _{\alpha\beta} }:U_\alpha \cap U_\beta \to U(2)$$
and
$$\det \circ \widetilde{s _{\alpha\beta} }:U_\alpha \cap U_\beta \to U(1).$$
The first one induces two complex vector bundles of rank $2$ on $M$ while and the second induces a complex line bundle (called $L$) on $M$.
The two complex vector bundles are denoted $S_\pm\otimes L^{1/2}$ respectively. The reason is obvious: they are defined by the transition matrix $\lambda A^\pm$ respectively, and $\lambda^2$ defines $L$. So it is important to understand that $S_\pm\otimes L^{1/2}$ are really mere notations, there aren't vector bundles $S_\pm$ and there isn't a line bundle $L^{1/2}$ on $M$.
Although an oriented four manifold does not admit a Spin structure, it always admit a spin$^c$ structure (the dimension is important here).
Comment: You write $\rho_\pm^c(B^c) = \lambda A_\pm$, but $\det(\lambda A_\pm) = \lambda^2$, but we need it to be 1 (since the result must be in $SU(2)$). Am I missing something?
Comment: Thanks, @Appliqué It should be $U(2)$.


How to execute a CGI on my server?

Question: I want to execute a CGI on my server, but I have this issue:
run-detectors: unable to find an interpreter for /media/FTP/outils/cgi-bin/monitorCGI.cgi, >refererer: http://outils.mynd/backburner.
Premature end of scripts header: monitorCGI.cgi, referer: >http://outils.mynd/backburner.

My apache2.conf looks like so:
<location /media/FTP/racine/cgi-bin/>
Options +ExecCGI
AddHandler cgi-script .cgi
</Location>

My Vhost looks like so:
>VirtualHost *:80>
    ServerAdmin webmaster@localhost
    ServerName SERV-FTP
    DocumentRoot /media/FTP

    Directory /media/FTP/racine/cgi-bin>
        Options +Indexes FollowSymLinks MultiViews +ExecCGI
        AddHandler cgi-script cgi
        Order allow,deny
        allow from all
    /Directory>

    ErrorLog ${APACHE_LOG_DIR}/error.log

    # Possible values include: debug, info, notice, warn, error, crit,
    # alert, emerg.
    LogLevel warn

    CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>

Should I link wine to execute this CGI ?
Comment: What kind of cgi script is it? A perl script?
Comment: Hi ! don't know what is it really & my reseller can't give me an answer about that. He said me i need wine. So i guess it's an exe ... ?
Comment: OK, it looks like a windows executable if running it in Wine makes it execute enough to give an actual error message. You could 1) Look for a better monitoring tool that can run natively in your hosting environment or 2) Write a wrapper script that calls wine with your binary, then call that wrapper script as a CGI. Also see [this question](http://stackoverflow.com/questions/2338111/is-there-a-way-to-execute-a-exe-cgi-application-on-linux-apache) for a similar situation.
Comment: If it is an actual script and not some unsupported binary executable then "unable to find an interpreter" probably means the interpretor path in the [shebang](http://en.wikipedia.org/wiki/Shebang_(Unix)) is wrong - check the first line of the script and make sure the intepreter is being called with the correct path. Also execute the script manually and see if you get the same error. Finally the "file" command may be of use e.g. "file /media/FTP/outils/cgi-bin/monitorCGI.cgi" if you have shell access.
Comment: shebang ? I can't see the first line cause it's a compiled CGI (or i don't know how i can read the first line ...)
If i execute "wine monitorCGI.cgi" i have an other error "ERROR login procedure could not be completed". It's normal cause i didn't use the .auth file.
Comment: a wrapper like this ? test.php contains  ?
Comment: Error.log Application tried to create a window, but no driver could be loaded.Make sure that your X server is running and that $DISPLAY is set correctly. err:systray:initialize_systrayCould not create tray window [error] [client 192.168.0.235] File does not exist: /media/FTP/outils/favicon.ico
Note that '(null)/.local/share' is not in the search path
set by the XDG_DATA_HOME and XDG_DATA_DIRS environment variables,so applications may not be able to find it until you set them. The
directories currently searched are: - /var/www/.local/share - /usr/local/share/ - /usr/share/
Comment: Try and use the "wineconsole" command instead. But if it is a GUI (not command line/console) windows app then you're out of luck. Also see [this wine help page](http://www.winehq.org/docs/wineusr-guide/cui-programs).
Comment: Wineconsole don't help me.
Comment: Wineconsole don't help me. monitorCGI can be executed on a windows machine. I'm sure i just need to force wine to execute this CGI, or force apache to execute correctly this CGI...
Comment: My reseller said me monitorCGI is able to run on a linux distrib .. but don't tell me how ... :(
Comment: Then you should look for a different reseller (or a different script).
Comment: He said, i just configure apache to execute monitorCGI.cgi ... if u have an idea how configure it ...
Answer: The Apache webserver is unable to run the monitorCGI.cgi script because it is unable to find an interpreter to use.
This means that it does not recognise monitorCGI.cgi as a compiled binary, and so is treating it as a script, and therefore wants the first line to be #! /path/to/interpreter for some interpreter.
Since you claim the script is a compiled binary, but Apache does not recognise it as such, it is likely compiled for the wrong architecture.
Try the command file monitorCGI.cgi to see what type of file your OS claims it to be.  Possibly it is compiled for 64bit when you're running a 32bit system, or it is a Windows executable when you're running a Linux server.  In any case, you need to find a compatible binary for it to work.  Try running the script directly form the command line, to verify that it can execute, before running via Apache.
Comment: file monitorCGI.cgi : PE32 executable (console) Intel 80386, for MS Windows.
Comment: Under windows, a PE32 executable is a binary file, so MUST have a .exe extension, otherwise Apache will use the cgi-script handler, thinks it is a script and looks for an interpreter.
Rename monitorCGI.cgi to be monitorCGI.exe and it should work (though you'll likely need to change whatever it was that linked to it)
Comment: I'm using Debian :s

How to execute a CGI on my server?


I'm not sure if basic auth on my server is being secured

Question: This may be a really dumb question but I had to make sure that i'm fine with this.
I setup an HTTPS server with basic auth, but the browser informs me that the connection is not secured when i connect to the auth page, and tells me that the connection is secured after i sign in. I want to know whether this is safe, and if not, how can i make it  secured?
Config(NGINX):
<code>server {
    listen 80;
    server_name sub.example.com;

    return 301 https://$server_name$request_uri;
}

server {
    listen 443 ssl http2;
    server_name sub.example.com;

    ssl_ceerificate (certpath);
    ssl_certificate_key (certkeypath);
    ssl_trusted_certificate (anotherpath);
    ssl_dhparam (dhparam);

    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_prefer_server_ciphers on;
    ssl_ciphers TLS_AES_256_GCM_SHA384:TLS_CHACHA20_POLY1305_SHA256:TLS_AES_128_GCM_SHA256:ECDHE-RSA-AES256-GCM-SHA384:DHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-AES128-GCM-SHA25$
    ssl_ecdh_curve secp384r1;
    ssl_session_timeout 10m;
    ssl_session_cache shared:SSL:10m;
    ssl_session_tickets off;
    ssl_stapling on;
    ssl_stapling_verify on;

    add_header X-Content-Type-Options "nosniff" always;
    add_header X-Frame-Options "SAMEORIGIN" always;
    add_header X-XSS-Protection "1; mode=block"

    location / {
        auth_basic 'Nothing to see here';

        proxy_pass http://localhost:4000/;
    }
}
</code>
Screenshot
Comment: Do you have proper certificates installed?
Comment: @TeroKilkanen yes I have a letsencrypt cert installed and chrome recognizes it too after i sign in
Comment: Have you added the basic authentication to the encrypted host or to the unencrypted (port 80)? Please share your config file(s).
Comment: @digijay every http request is redirected to https, thus basic auth is on https server, i'll share the config asap
Comment: What is the real hostname?
Comment: Yes, we _prefer_ posting real information whenever possible as it makes diagnosis much easier in many cases.
Comment: For example: `curl: (7) Failed to connect to omv.jungroy.codes port 443: Connection refused` Is your web server up? Did you delete the https configuration?
Comment: @MichaelHampton Oh i denyed all except my ip, ill allow that
Comment: @MichaelHampton you can curl it now
Comment: Everything seems to be working fine.
Comment: Oh thank you for checking it out!
Answer: Your configuration appears fine; it's the browser that is misbehaving.
Your site correctly redirected to https, and the basic auth request was sent to you over https. But the browser did not update the address bar before popping up the dialog. Interestingly, I was able to see this behavior both on Chrome and Firefox. Perhaps this is because the browser asked for the credentials before (from its perspective) the page load was complete? It's a question for the browser developers.


Expiring content creates 404s with Nginx?

Question: I have a virtual host that includes the following location block:
server {
  listen      80;
  server_name ~^(?<username>[^.]+)\.project*/\.client\.com$;
  root        /home/$username/project/app/webroot;
  index       index.php;

  access_log /var/log/nginx/project.sandbox.access.log;
  error_log  /var/log/nginx/project.sandbox.error.log;

  location / {
    try_files $uri $uri/ /index.php?url=$uri;
  }

  location ~ \.php$ {
    include /etc/nginx/includes/php;
  }

  location ~* \.(js|css|png|jpg|jpeg|gif|ico)$ {
    expires max;
    log_not_found off;
  }
  include /etc/nginx/includes/ignore;
}

I've never had problems before, but I just added a feature that allows users to upload & store files. If the user uploads pdfs, txt files, etc. all is well and I can load the upload just fine via its URL. Images, on the other hand, not so much. 404s everywhere.
I've narrowed it down to this block, but I don't understand it. Other image assets load fine. The only difference, which may make all the difference, is that uploaded assets aren't loaded into the webroot as defined by the server block's root directive. Uploads are stored in /opt/www/app/plugins/.... Is there any reason that should matter? My front controller handles the routing for uploaded assets.
I'd like to cache/expire content, but I need to fix the 404s first.
Comment: Please include the rest of the relevant `server` block.
Comment: That can't possibly be the entire `server` block.
Comment: It wasn't. Now it is.
Answer: Your .(js|css|png|jpg|jpeg|gif|ico) location block catches requests for uploaded assets ending with those file extensions. Since nginx only executes a single location block at each level, your PHP script is not executed for these requests. nginx tries to serve the file directly from disk, but it can't find the uploaded asset.
You need to make this location block match stricter so that it does not match uploaded assets. For example:
location ~* ^/static/.*\.(js|css|png|jpg|jpeg|gif|ico)$

Edit: When I say "level" I mean nesting level. For example:
location / {
    location /foo {}
}

location /bar {}

location /baz {
    location /baz/quaz {}
    location ~ \.php$ {}
}

The /, /bar and /baz location blocks are at level 1. The /foo, /baz/quaz and \.php$ location blocks are at level 2, because they're nested within a level 1 location block. Let's say that the request is for /baz/quaz/index.php. nginx will select the most specific level 1 location block, in this case /baz. No other level 1 location blocks will be processed, so the / block will have no effect for this request. If there are level 2 location blocks it will do the same, in this case choosing \.php$ and ignoring /baz/quaz.
Comment: Thanks. Can you provide some detail (or point me to a URL) about "nginx only executes a single location block at each level"? I'm not I understand that. What is a "level" in this context?
Comment: Since I understand better through examples, maybe the better quetion is...how would my config need to change if I want to cache both the runtime assets located somewhere in the webroot _and_ the uploaded assets in my plugin directory (`/polyclip/assets/`)?
Comment: @RobWilkerson See my edit.
Comment: Final question: When processing the level 2 block for `/baz/quaz/index.php` what makes \.php$ get executed? Would `/baz/quaz` get "expanded" to `/baz/baz/quaz` (and hence not match) or is there a specificity rule in play that the "~" triggers? Thanks again for your help.
Comment: @RobWilkerson Yup, `~` blocks have a higher priority than plain paths. The documentation explains [how location blocks are chosen](http://wiki.nginx.org/HttpCoreModule#location).


Voice trills unintentionally when singing high-pitched notes

Question: I'm not an experienced singer, so I suppose I've got plenty of knowledge missing when it comes to keeping my voice in shape. Whenever I try to sing a high-pitched note, my voice inadvertently starts to trill. Here's a short clip of this:
A quick recording.
It sounds horrible, but if I keep trying to sing that note for a while, the trilling disappears. At least for some ten minutes. Is there something wrong with my voice or my technique?
Comment: Are you warming up properly?
Answer: I'm not sure what your level of experience is or whether you have had instruction, but there are some basic things you should be doing anytime that you sing, and especially when singing notes at or near the top of your range:

Smile the entire time.  Or don't smile, grimace.  Either way, raise your upper lip towards your nose in a bit of a sneer and take some breaths, so you learn the way that it feels when your soft palate is raised.
Breathe as though your mouth were at the small of your back.  This is easier if you are sitting, and almost unavoidable if you are lying on your back.  You're still smiling, right?  :)
Once you are doing both of these things, make sound, and use your diaphragm to support as well as push the sound up and out of you.  Try to imagine that the sound is coming out of your nose instead of your mouth.
Try not to think too much or at all about the fact that you want to sing a high note.  These thoughts will shake your confidence, lower your facial muscles and thus your soft palate, and choke your sound.

I really hope this helps you at least a little bit.
EDIT:  I wanted to suggest that in trying to hit these notes that you work first with wordlessness, such as the backing vocals in "Little GTO" by Ronnie and the Daytonas.  It is far easier to concentrate on hitting difficult notes if you aren't also worrying too much about forming syllables.
Answer: There is not enough information here to answer the question.
You need a vocal instructor.  Get one, because you run the risk of damaging your voice.


In a UFD, lcm = product for coprimes: $\,(a,b)=1,\ a,b\mid c\Rightarrow ab\mid c$

Question: Let $R$ be a $\text{UFD}$, and let $a,b,c \in R$ such that $1=\text{gcd}(a,b).$ Suppose $a |c, \ b|c.$ Could anyone advise me on how to prove $ab |c \ ?$ How do I use the fact that every nonzero non unit $r \in R$ can be expressed as finite product of irreducible elements in $R\ ?$
Hints will suffice.
Comment: Let $P$ be a set of representatives of the classes of associated primes. Then use that every $x\in R$ has a unique decomposition $$x = \varepsilon\cdot \prod_{p\in P} p^{v_p(x)}.$$ $\gcd(a,b) = 1$ means that for every prime at least one of $v_p(a)$ and $v_p(b)$ is $0$.
Answer: A UFD (or gcd domain) satisfies Euclid's Lemma: $\ (a,b)=1,\,\ a\mid bd\,\color{#c00}{\Rightarrow}\,a\mid d.\,$ In particular
$$ a,b\mid c,\,\ (a,b)=1\,\Rightarrow\, a\mid b(c/b)\,\color{#c00}{\Rightarrow}\,a\mid c/b\,\Rightarrow\, ab\mid c$$
Remark $\, $ In particular this holds true for any domain with a Euclidean algorithm, since this implies all gcds exist, e.g. it is true for $\Bbb Z$ or $\,F[x],\,$ for $F$ a field. Follow the above link for proofs.
See here for the straightforward inductive extension to $n$ arguments.
More conceptually gcd, lcm duality shows $\,{\rm lcm}(a,b) = ab/\gcd(a,b).\,$ OP is case $\,(a,b)=1$
Answer: @Daniel Fischer
Thanks for the reply.
Let $R$ be $\text{UFD}$ and $T$ be a complete set of representatives of associate classes of irreducible elements of $R$ *(so that for each irreducible $r\in R,$ there exists unique $t_r \in T$ such that $r$ is associate to $t_r)$
Then, for each $r \in R^*,$ there exists unique $u_r \in U(R)=$ set of units of $R$ and $n_{r,t} \in \mathbb{Z}_{\geq 0}$ for $t \in T $ such that $r = u_r\cdot \prod_{t\in T} t^{n_{r,t}}.$
Furthermore, if $s=u_s\cdot \prod_{t\in T} t^{n_{s,t}},$ with $u_s \in U(R) $ and $n_{s,t}\in \mathbb{Z}_{\geq 0}$ for all $t\in T,$ then $r|s$ iff $n_{s,t} \leq n_{r,t} $ for all $t \in T.$
Why $t$ is a prime? And if $\text{gcd}(r,s)=1,$ this means $1=\prod_{t\in T} t^{\text{min}(n_{r,t},n_{s,t})}.$ So why there exists $t \in T$ such that $\text{min}(n_{r,t},n_{s,t})=0?$
Comment: In a UFD, we have "irreducible = prime". If $\gcd(r,s) = 1$, then $\min (n_{r,t},n_{s,t}) = 0$ for **all** $t\in T$, for if we had $\min (n_{r,t},n_{s,t}) > 0$ for some $t$, then that $t$ would be a common divisor of $r$ and $s$, i.e. $t\mid \gcd(r,s)$. And thus we have $n_{r,t} + n_{s,t} = \max(n_{r,t},n_{s,t})$ for all $t$. Oh, and you forgot a 'c' in my name.


How do I fix the fact that Pip3 not working for Linux Mint?

Question: when i type in pip3 install ctypes it says:
ERROR: Could not find a version that satisfies the requirement ctypes (from versions: none)
ERROR: No matching distribution found for ctypes
i've already tried upgrading pip but that did nothing and i'm very annoyed
Comment: `ctypes` is a built-in no? Shouldn't that come with the install without having to add an additional dependency?
Comment: `ctypes` should be a builtin package, so pip is unecessary
Comment: Does this answer your question? [How to install ctypes on Mac with Python 2.7](https://stackoverflow.com/questions/36457439/how-to-install-ctypes-on-mac-with-python-2-7)
Answer: ctypes is a built-in module in Python and does not need to be installed using pip. It is possible that the error you are encountering is due to a typo or a misunderstanding of the purpose of the ctypes module.
If you are trying to use the ctypes module, you can simply import it into your Python script without needing to install it. Here is an example of how you can use ctypes:
import ctypes
Define a function pointer type
AddFunc = ctypes.CFUNCTYPE(ctypes.c_int, ctypes.c_int, ctypes.c_int)
Define a simple function
def add(x, y):
return x + y
Create a function pointer to the add function
add_func_ptr = AddFunc(add)
Call the add function through the function pointer
result = add_func_ptr(3, 4)
print(result) # Output: 7
If you are trying to install a package that depends on the ctypes module, it is possible that the package is not compatible with your version of Python or your operating system. In this case, you may need to look for alternative packages or solutions that meet your needs.
In any case, the ctypes module does not need to be installed separately using pip.
Comment: please format your answer in readable way.


Small confusion regarding singular homology

Question: This is the proof of Theorem 4.19. in Joseph J. Rotman "An Introduction to Algebraic Topology". We want to show that $H_n(X)=0$ for all $n>0$ and $X$ convex bounded in some euclidean space. I refer to a similar question Homology group of convex sets - boundedness condition for used notation, in short, $\gamma=\partial c\gamma+ c\partial\gamma$ for a chain $\gamma\in S_n(X)$. He then says that if $\gamma$ is a cycle, we have $\gamma =\partial c\gamma$, a boundary, so homology is trivial. But this I don't understand: is the cone over $0$ again $0$? In my eyes, I would see that the cone over $0$ is a boundary, which of course wouldn't change the conclusion, but the argument confuses me a little.
Thanks in advance for any sort of clarification!
Answer: I came to realise my mistake... the $0$-chain is not the zero simplex (which doesn't make any sense anyway, right?) but the neutral element in the group $S_n(X)$. I first deleted the question, but now I think one needs to stand by such wrong thoughts.
Comment: Rather than standing by "wrong thoughts", think of it as providing help for the next person who has the same question.


R: Insert a column at a specific place in R data table

Question: I have following data table
      user_id user_system_days event total_pics
[1,] 21196680             0     0         124
[2,] 21197699             0     0           4
[3,] 21197861             0     0          14
[4,] 21198820             1     0          21
[5,] 21199601             0     0           3
[6,] 21203847             0     0           1

Based on a value in column event I want to insert a column to the data table, My approach was by writing a function, and use that function to return a value.
opposite_event  <- function(x) {
  y <- 1
  if (x == 1)
    y <- 0
  return (y)
}

I called function as follows:
dt[,op_event:=opposite_event(dt$event)]

This actually added the column but values were wrong:
      user_id user_system_days event total_pics op_event
[1,] 21196680             0     0         124      0
[2,] 21197699             0     0           4      0
[3,] 21197861             0     0          14      0
[4,] 21198820             1     0          21      0
[5,] 21199601             0     0           3      0
[6,] 21203847             0     0           1      0

Based on my function if value of the dt$event is 1 then return value should be 0 and if dt$event is 0 then return value should 1 Plus I wasn't sure how to insert the column into a specific location like right after event column.
Answer: if is not vectorized, Replace it with y <- ifelse(x == 0, 1, 0).
You don't really need a custom function in my opinion:
dt[,op_event := ifelse(event == 0, 1, 0)]

Comment: Update on another way: `dt[, op_event := as.integer(!event)]`
Comment: the idiomatic way to rearrange columns is to use `setcolorder`. That'll rearrange by reference (no copies). Doing `dt[, list(.)]` is a column subset which'll create a copy.
Comment: @Null-Hypothesis yup.
Comment: should work such that if event == 1 then value of op_event is 1 and if event == 0 then op_event should be 1
Comment: @SeñorO whats the best way to re-arrange the column order such as getting the column op_event after event column?
Comment: You must do that after you create the column. The default way is just to list the names in order with data.table. You can also use numbers if you include `with=FALSE`. So like `dt[,list(uder_id, user_system_days....)]` or `dt[,list(1, 2, 3, 5, 4), with=FALSE]`


Does carrying capacity have the ability to act at a distance?

Question: This question concerns the generalized logistic function, discussed in Wikipedia here:
http://en.wikipedia.org/wiki/Generalised_logistic_function
If we take the lower asymptote to be 0, then the upper asymptote is called the carrying capacity. Fine, and for sake of this question, let's take the lower asymptote to be 0 (not that it matters for the mathematics of this question, but that gives us the convenient handle of "carrying capacity" to use in this question.) The problem is that in the differential form (Y'(t) = …), it appears that the rate of population growth can be increased simply by increasing the carrying capacity. In other words, the distance of the boundary of the constraint is somehow being "telegraphed" to the population. This seems counter-intuitive to me. Until the population starts to feel the effects of the constraint, a relaxing of the constraint should be imperceptible to the population. Obviously, I'm missing something, but what is it?
Comment: The logistics model is an approximation. For values of $y$ far from the carrying capacity, the growth is *close to* exponential, but it is not *exactly* exponential; there are extra terms. While those terms don't matter *much*, they do matter somewhat. The further away you are, the less they matter.
Comment: In the logistic model, the growth rate is modeled to be proportional to the "room left for growth". This room left for growth is the difference between the carrying capacity and the population. So the model inherently "telegraphs" the carrying capacity down to the population. As Arturo explains, the effect is small though when the room left for growth is large.
Answer:
the rate of population growth can be increased simply by increasing the carrying capacity.

Changing the capacity $K$ changes the growth process for the population $P(t)$, not only the rate at which the process takes place.  In other words, the differential equation for $P$ is not independent of $K$.
Comment: >changes the growth process...not only the rate...: excellent point


Quando crio duas tabelas no SQLite Android, somente uma funciona

Question: Estou tentando desenvolver um aplicativo de teste que requer duas tabelas (aluno e disciplina) na classe DataHelper. Crio duas tabelas, porém na hora de fazer testes, somente a tabela Aluno funciona. Em resumo: a aplicação tem algumas funcionalidades (inserir aluno, inserir disciplina, apagar aluno, apagar disciplina, entre outras) e todos os métodos funcionam para a tabela do aluno, porém nenhum método funciona pra tabela da disciplina. O que isso pode ser?
Abaixo, a classe em que as tabelas são criadas (DataHelper) seguidas das classes que manipulam cada tabela, são essas tabelas aluno (AlunoDao) e disciplina (DisciplinaDao) respectivamente e uma classe que abre e fecha o banco de dados (Dao):
public class DataHelper extends SQLiteOpenHelper {

    public DataHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
        super(context, name, factory, version);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
      try{
            StringBuilder sbAluno = new StringBuilder();
            StringBuilder sbDisciplina = new StringBuilder();
            sbAluno.append( "CREATE TABLE IF NOT EXISTS [disciplina](\n" +
                    "    [iddisciplina] INT PRIMARY KEY NOT NULL, \n" +
                    "    [nomedisc] TEXT NOT NULL, \n" +
                    "    [tutor] TEXT NOT NULL);");
            db.execSQL(String.valueOf(sbAluno));

            sbDisciplina.append("CREATE TABLE IF NOT EXISTS [aluno](\n" +
                    "    [idaluno] INT PRIMARY KEY NOT NULL, \n" +
                    "    [nome] TEXT NOT NULL, \n" +
                    "    [curso] TEXT NOT NULL);" );
            db.execSQL(String.valueOf(sbDisciplina));

        }catch (Exception e){

        }

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        try{

            StringBuilder sb= new StringBuilder();

            sb.append("DROP TABLE IF EXISTS [aluno];" + "DROP TABLE IF EXISTS [disciplina];" );

            String [] comando = sb.toString().split(";");

            for (int i = 0; i < comando.length ; i++) {
                db.execSQL(comando[i].toLowerCase()); //toLowerCase torna todas as letras minusculas
            }
        }catch (Exception e){
        }

        onCreate(db);

    }

public class DisciplinaDao extends Dao {

    private static final String TABELA = "disciplina";
    private static final String IDDISCIPLINA = "iddisciplina";
    private static final String NOMEDISC = "nomedisc";
    private static final String TUTOR = "tutor";

    public DisciplinaDao(Context context) {
        super(context);
    }

    public void inserirDisciplina(Disciplina disciplina){
        AbrirBanco();
        //
        ContentValues cv = new ContentValues();
        cv.put(IDDISCIPLINA, disciplina.getIddisciplina());
        cv.put(NOMEDISC, disciplina.getNomedisc());
        cv.put(TUTOR, disciplina.getTutor());
        //
        db.insert(TABELA, null, cv);
        //
        FecharBanco();

    }

    public void atualizarDisciplina(Disciplina disciplina){
        AbrirBanco();
        //
        ContentValues cv = new ContentValues();
        //
        String Filtro = "iddisciplina = ?";
        String [] argumentos = { String.valueOf(disciplina.getIddisciplina()) };
        //
        cv.put(NOMEDISC, disciplina.getNomedisc());
        cv.put(TUTOR, disciplina.getTutor());
        //
        db.update(TABELA, cv, Filtro, argumentos);
        //
        FecharBanco();
    }

    public void apagarDisciplina(int iddisciplina){
        AbrirBanco();
        //
        String Filtro = "iddisciplina = ?";
        String [] argumentos = { String.valueOf(iddisciplina) };
        //
        db.delete(TABELA, Filtro, argumentos);
        //
        FecharBanco();
    }

    public Disciplina obterContatoByID(int iddisciplina){
        Disciplina cAux = null;
        //
        AbrirBanco();
        //
        Cursor cursor = null;
        //
        try{
            String [] argumentos = { String.valueOf(iddisciplina) };

            StringBuilder comando = new StringBuilder();
            comando.append(" select * from disciplina where iddisciplina = ? ");

            cursor = db.rawQuery(comando.toString(), argumentos);

            //avançar os dados se nao conseguir passar pro proximo ele sai do while
            while (cursor.moveToNext()){
                cAux = new Disciplina();

                cAux.setIddisciplina(cursor.getInt(cursor.getColumnIndex(IDDISCIPLINA)));
                cAux.setNomedisc(cursor.getString(cursor.getColumnIndex(NOMEDISC)));
                cAux.setTutor(cursor.getString(cursor.getColumnIndex(TUTOR)));
            }

        }catch (Exception e){

        }finally {
            if (cursor != null){
                cursor.close();
                cursor = null;
            }
        }
        //
        FecharBanco();
        //
        return cAux;
    }

    public ArrayList<HMAux> obterListaDisciplina(){
        ArrayList<HMAux> dados = new ArrayList<>();
        //
        AbrirBanco();
        //

        Cursor cursor = null;
        //
        try{

            StringBuilder comando = new StringBuilder();
            comando.append(" select iddisciplina, nomedisc from disciplina order by nomedisc ");

            cursor = db.rawQuery(comando.toString(), null);

            //avançar os dados se nao conseguir passar pro proximo ele sai do while
            while (cursor.moveToNext()){
                HMAux hmAux = new HMAux();

                hmAux.put(HMAux.id_disciplina, String.valueOf(cursor.getLong(cursor.getColumnIndex(IDDISCIPLINA))));
                hmAux.put(HMAux.TEXTO_02, cursor.getString(cursor.getColumnIndex(NOMEDISC)));

                dados.add(hmAux);

                }

        }catch (Exception e){

        }finally {
            if (cursor != null){
                cursor.close();
                cursor = null;
            }
        }
        //
        FecharBanco();
        //
        return dados;
    }

    public int proximoID(){
        int proId = 0;
        //
        AbrirBanco();
        //
        Cursor cursor = null;
        //
        try{

            StringBuilder comando = new StringBuilder();
            comando.append("select max(iddisciplina)+1 as id from disciplina");

            cursor = db.rawQuery(comando.toString(), null);
            int x = 10;
            //avançar os dados se nao conseguir passar pro proximo ele sai do while
            while (cursor.moveToNext()){
                proId = cursor.getInt(cursor.getColumnIndex("id"));
            }
            if(proId == 0){
                proId = 1 ;
            }

        }catch (Exception e){

        }finally {
            if (cursor != null){
                cursor.close();
                cursor = null;
            }
        }

        //
        FecharBanco();
        //
        return proId;
    }

}

public class AlunoDao extends Dao {

    private static final String TABELA = "aluno";
    private static final String IDALUNO = "idaluno";
    private static final String NOME = "nome";
    private static final String CURSO = "curso";

    public AlunoDao(Context context) {
        super(context);
    }

    public void inserirAluno(Aluno aluno){
        AbrirBanco();
        //
        ContentValues cv = new ContentValues();
        cv.put(IDALUNO, aluno.getIdaluno());
        cv.put(NOME, aluno.getNome());
        cv.put(CURSO, aluno.getCurso());
        //
        db.insert(TABELA, null, cv);
        //
        FecharBanco();
    }

    public void atualizarAluno(Aluno aluno){
        AbrirBanco();
        //
        ContentValues cv = new ContentValues();
        //
        String Filtro = "idaluno = ?";
        String [] argumentos = { String.valueOf(aluno.getIdaluno()) };
        //
        //cv.put(IDCONTATO, contato.getIdcontato());
        cv.put(NOME, aluno.getNome());
        cv.put(CURSO, aluno.getCurso());
        //
        db.update(TABELA, cv, Filtro, argumentos);
        //
        FecharBanco();
    }

    public void apagarAluno(int idaluno){
        AbrirBanco();
        //
        String Filtro = "idaluno = ?";
        String [] argumentos = { String.valueOf(idaluno) };
        //
        db.delete(TABELA, Filtro, argumentos);
        //
        FecharBanco();
    }

    public Aluno obterAlunoByID(long idaluno){
        Aluno cAux = null;
        //
        AbrirBanco();
        //
        Cursor cursor = null;
        //
        try{
            String [] argumentos = { String.valueOf(idaluno) };

            StringBuilder comando = new StringBuilder();
            comando.append(" select * from aluno where idaluno = ? ");

            cursor = db.rawQuery(comando.toString(), argumentos);

            //avançar os dados se nao conseguir passar pro proximo ele sai do while
            while (cursor.moveToNext()){
                cAux = new Aluno();

                cAux.setIdaluno(cursor.getInt(cursor.getColumnIndex(IDALUNO)));
                cAux.setNome(cursor.getString(cursor.getColumnIndex(NOME)));
                cAux.setCurso(cursor.getString(cursor.getColumnIndex(CURSO)));

            }

        }catch (Exception e){

        }finally {
            if (cursor != null){
                cursor.close();
                cursor = null;
            }
        }
        //
        FecharBanco();
        //
        return cAux;
    }

    public ArrayList<HMAux> obterListaAluno(){
        ArrayList<HMAux> dados = new ArrayList<>();
        //
        AbrirBanco();
        //

        Cursor cursor = null;
        //
        try{

            StringBuilder comando = new StringBuilder();
            comando.append(" select idaluno, nome from aluno order by nome ");

            cursor = db.rawQuery(comando.toString(), null);

            //avançar os dados se nao conseguir passar pro proximo ele sai do while
            while (cursor.moveToNext()){
                HMAux hmAux = new HMAux();

                hmAux.put(HMAux.id, String.valueOf(cursor.getLong(cursor.getColumnIndex(IDALUNO))));
                hmAux.put(HMAux.TEXTO_01, cursor.getString(cursor.getColumnIndex(NOME)));

                dados.add(hmAux);

                }

        }catch (Exception e){

        }finally {
            if (cursor != null){
                cursor.close();
                cursor = null;
            }
        }
        //
        FecharBanco();
        //
        return dados;
    }

    public int proximoID(){
        int proId = 0;
        //
        AbrirBanco();
        //
        Cursor cursor = null;
        //
        try{

            StringBuilder comando = new StringBuilder();
            comando.append(" select max(idaluno)+1 as id from aluno ");

            cursor = db.rawQuery(comando.toString(), null);

            //avançar os dados se nao conseguir passar pro proximo ele sai do while
            while (cursor.moveToNext()){
                proId = cursor.getInt(cursor.getColumnIndex("id"));
            }
            if(proId == 0){
                proId = 1 ;
            }

        }catch (Exception e){

        }finally {
            if (cursor != null){
                cursor.close();
                cursor = null;
            }
        }

        //
        FecharBanco();
        //
        return proId;
    }

}

public class Dao {

    private Context context;
    protected SQLiteDatabase db;

    public Dao(Context context) {
        this.context = context;
    }

    public void AbrirBanco(){
        DataHelper dataHelper = new DataHelper(
            context,
            Constantes.BANCO,
            null,
            Constantes.VERSAO
        );

        this.db = dataHelper.getWritableDatabase();

    }

    public void FecharBanco(){
        if (db != null){
            db.close();
        }
    }
}

Ao utilizar os métodos da classe AlunoDao ocorre tudo normal. Porém, ao utilizar os métodos da classe DisciplinaDao, não funcionam, mas também não dá erro. Criei os dois da mesma forma e com os mesmos métodos. Não sei o que pode ser feito. Desde já agradeço.
Comment: Dá algum erro? Ponha o código de um dos métodos que não funcionam.
Comment: tenta fazer assim ó, adicone essa linha em ambas as tabelas: `db.execSQL("commit");` que pode ser isso
Comment: Você criou as duas tabelas ao mesmo tempo ou adicionou a tabela "disciplina" depois?
Comment: Não entendi a sua pergunta. As duas  estão sendo criadas ou apenas a de Alunos? Se as duas tabelas estão sendo criadas o problema não está com a sua classe DataHelper, mas sim com as classes que manipulam os dados delas.
Comment: As duas são criadas porém só uma funciona. Editei a pergunta e coloquei todos os detalhes do meu projeto, obrigado
Comment: Não coloque [resolvido] no título. Ao invés disso, marque como aceita a resposta que resolveu o seu problema. Se nenhuma das respostas tiver resolvido o seu problema e você mesmo tiver encontrado a solução sozinho, poste você mesmo a resposta.
Comment: Aqui vai o seu comentário que você postou na pergunta: "**Pelo que pesquisei o problema está na versão do banco de dados, a solução que encontrei foi desinstalar e instalar o apk, isso resolveu meu problema. Link de onde a solução foi encontrada:_ < http://stackoverflow.com/questions/21069532/android-database-sqlite-sqliteexception-no-such-table-admin-while-compiling-i >**"
Answer: O problema está na versão do banco de dados, a solução foi desinstalar e instalar o apk, isso resolveu meu problema. Link de onde a solução foi encontrada: stackoverflow.com/questions/21069532/…
Answer: Olhando as suas classes AlunoDao e DisciplinaDao, as mesmas são bem equivalentes. As pouquíssimas diferenças de algo que há em uma e não na outra não devem fazer efeito (linhas comentadas, linhas em branco, um int x = 10; que nunca é usado e o nome do método obterContatoByID ao invés de obterDisciplinaByID).
Entretanto, há um ponto diferente que vale uma investigação mais a fundo:
                hmAux.put(HMAux.id, String.valueOf(cursor.getLong(cursor.getColumnIndex(IDALUNO))));
                hmAux.put(HMAux.TEXTO_01, cursor.getString(cursor.getColumnIndex(NOME)));

                hmAux.put(HMAux.id_disciplina, String.valueOf(cursor.getLong(cursor.getColumnIndex(IDDISCIPLINA))));
                hmAux.put(HMAux.TEXTO_02, cursor.getString(cursor.getColumnIndex(NOMEDISC)));

Será que não há algo errado em relação a esse TEXTO_01 e TEXTO_02? Ou talvez quanto ao fato de um usar id e o outro id_disciplina?
Aliás, por que você devolve List<HMAux> nos dois casos ao invés de List<Aluno> e List<Disciplina>? Vou assumir que isso é um erro e que deveria ser esses dois últimos.
Quanto mais, o seu código tem sérios problemas de qualidade. O primeiro deles é que você devia usar o try-with-resources (veja nesse link como e por quê).
Se não puder usar o try-with-resources, ao menos certifique-se de fechar tudo em um bloco finally. Porém, uma vez que você já está usando a sintaxe de diamante (<> no construtor), então você já está usando pelo menos o Java 7, logo pode usar o try-with-resources.
Outro problema é que você usa StringBuilders sem necessidade. Por exemplo:
            StringBuilder comando = new StringBuilder();
            comando.append(" select * from disciplina where iddisciplina = ? ");

            cursor = db.rawQuery(comando.toString(), argumentos);

Poxa, seria bem mais fácil, mais simples, mais óbvio, mais direto e mais lógico se você fizesse isso:
            String comando = " select * from disciplina where iddisciplina = ? ";
            cursor = db.rawQuery(comando, argumentos);

Isso fica ainda pior na sua classe DataHelper, onde você concatena as strings para então separá-las de novo e até mesmo usa um for sem necessidade alguma.
Uma outra coisa que noto, é que todos os seus métodos dos DAOs começam com AbrirBanco() e terminam com FecharBanco(). Isso é esperado, mas isso também significa que a referência db não tem serventia nenhuma fora da execução de algum desses métodos. Mais do que isso, o db que é usado por um dos métodos dos DAOs tem um escopo que nasce, vive e morre inteiramente dentro de um único método de cada vez. Isso é um forte indício de que o uso de variáveis locais seria mais apropriado.
E por favor, se atente às regras de nomenclatura da linguagem Java. Ou seja, a menos que você tenha uma razão muito forte e muito bem justificada para fazer diferente, nomes de métodos e de variáveis locais DEVEM começar com letras minúsculas.
Comer exceções (capturar e e não fazer nada com ela depois) é uma péssima prática de programação. NUNCA faça isso:
        }catch (Exception e){

        }

Uma vez que a exceção android.database.SQLException herda de java.lang.RuntimeException, você não precisa tratá-la aqui. Entretanto, o código que for fazer uso dos seus DAOs deveria ser capaz de tratar isso.
Além disso, em uma classe chamada Aluno, um método getIdaluno() tem um nome um tanto redundante. O nome ser getId() já é suficiente. Afinal, se estou na classe Aluno, um método getId() obviamente só vai poder se referir ao id do aluno, e portanto ele não precisa se chamar getIdaluno(). O mesmo pode ser dito acerca de outros métodos e também de colunas no banco de dados tais como nomedisc e iddisciplina por exemplo.
Há também um princípio de programação orientada a objetos que diz que você deve depender de abstrações, e não de implementações. Um efeito direto disso é que você deve sempre preferir, se possível, referenciar interfaces ao invés de classes que implementam essas interfaces. Assim sendo, evite definir tipos que seja ArrayList<AlgumaCoisa> quando List<AlgumaCoisa> já serve.
Um outro princípio de prgramação diz que composição é melhor que herança. Podemos eliminar a sua herança nos DAOs ao separar o conteúdo da superclasse em uma nova classse que é usada pelos DAOs ao invés de ser herdada por eles. Essa abordagem provê um acoplamento mais fraco, um melhor encapsulamento e uma melhor organização do código. Coloquei o comportaneto da sua superclasse Dao em uma classe ConnectionFactory.
Simplificando todo o seu código, fica assim:
public class DataHelper extends SQLiteOpenHelper {

    private static final String CREATE_ALUNO = ""
            + "CREATE TABLE IF NOT EXISTS [aluno] (\n" +
            + "    [id] INT PRIMARY KEY NOT NULL, \n" +
            + "    [nome] TEXT NOT NULL, \n" +
            + "    [curso] TEXT NOT NULL);";

    private static final String CREATE_DISCIPLINA = ""
            + "CREATE TABLE IF NOT EXISTS [disciplina] (\n" +
            + "    [id] INT PRIMARY KEY NOT NULL, \n" +
            + "    [nome] TEXT NOT NULL, \n" +
            + "    [tutor] TEXT NOT NULL);";

    private static final String DROP_ALUNO =
            "DROP TABLE IF EXISTS [aluno];";

    private static final String DROP_DISCIPLINA =
            "DROP TABLE IF EXISTS [disciplina];";

    public DataHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
        super(context, name, factory, version);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(CREATE_ALUNO);
        db.execSQL(CREATE_DISCIPLINA);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL(DROP_ALUNO);
        db.execSQL(DROP_DISCIPLINA);
        onCreate(db);
    }
}

public final class ConnectionFactory {

    private final DataHelper dataHelper;

    public ConnectionFactory(Context context) {
        this.dataHelper = new DataHelper(context, Constantes.BANCO, null, Constantes.VERSAO);
    }

    public SQLiteDatabase conectar() throws SQLiteException {
        return dataHelper.getWritableDatabase();
    }
}

public class AlunoDao {

    private static final String TABELA = "aluno";
    private static final String ID = "id";
    private static final String NOME = "nome";
    private static final String CURSO = "curso";

    private static final String FILTRO_ID = "id = ?";

    private static final String SELECT_BY_ID_SQL =
            "SELECT * FROM aluno WHERE id = ?";

    private static final String SELECT_LIST_SQL =
            "SELECT id, nome FROM aluno ORDER BY nome";

    private static final String SELECT_PROXIMO_ID_SQL =
            "SELECT MAX(id) + 1 AS max_id FROM aluno";

    private final ConnectionFactory factory;

    public AlunoDao(ConnectionFactory factory) {
        this.factory = factory;
    }

    public void inserirAluno(Aluno aluno) {
        try (SQLiteDatabase db = factory.conectar()) {
            ContentValues cv = new ContentValues();
            cv.put(IDALUNO, aluno.getId());
            cv.put(NOME, aluno.getNome());
            cv.put(CURSO, aluno.getCurso());
            db.insert(TABELA, null, cv);
        }
    }

    public void atualizarAluno(Aluno aluno) {
        try (SQLiteDatabase db = factory.conectar()) {
            String[] argumentos = { String.valueOf(aluno.getId()) };
            ContentValues cv = new ContentValues();
            cv.put(NOME, aluno.getNome());
            cv.put(CURSO, aluno.getCurso());
            db.update(TABELA, cv, FILTRO_ID, argumentos);
        }
    }

    public void apagarAluno(int idAluno) {
        try (SQLiteDatabase db = factory.conectar()) {
            String[] argumentos = { String.valueOf(idAluno) };
            db.delete(TABELA, FILTRO_ID, argumentos);
        }
    }

    public Aluno obterAlunoByID(long idAluno) {
        String[] argumentos = { String.valueOf(idAluno) };

        try (
            SQLiteDatabase db = factory.conectar();
            Cursor cursor = db.rawQuery(SELECT_BY_ID_SQL, argumentos);
        ) {
            if (!cursor.moveToNext()) return null;
            Aluno aux = new Aluno();
            aux.setId(cursor.getInt(cursor.getColumnIndex(ID)));
            aux.setNome(cursor.getString(cursor.getColumnIndex(NOME)));
            aux.setCurso(cursor.getString(cursor.getColumnIndex(CURSO)));
            return aux;
        }
    }

    public List<Aluno> obterListaAluno() {
        try (
            SQLiteDatabase db = factory.conectar();
            Cursor cursor = db.rawQuery(SELECT_LIST_SQL, null);
        ) {
            List<Aluno> lista = new ArrayList<>();

            while (cursor.moveToNext()) {
                Aluno aux = new Aluno();
                aux.setId(cursor.getInt(cursor.getColumnIndex(ID)));
                aux.setNome(cursor.getString(cursor.getColumnIndex(NOME)));
                aux.setCurso(cursor.getString(cursor.getColumnIndex(CURSO)));
                lista.add(aux);
            }

            return lista;
        }
    }

    public int proximoID() {
        try (
            SQLiteDatabase db = factory.conectar();
            Cursor cursor = db.rawQuery(SELECT_PROXIMO_ID_SQL, null);
        ) {
            if (!cursor.moveToNext()) return 1;
            return cursor.getInt(cursor.getColumnIndex("id_max"));
        }
    }
}

public class DisciplinaDao {

    private static final String TABELA = "disciplina";
    private static final String ID = "id";
    private static final String NOME = "nome";
    private static final String TUTOR = "tutor";

    private static final String FILTRO_ID = "id = ?";

    private static final String SELECT_BY_ID_SQL =
            "SELECT * FROM disciplina WHERE id = ?";

    private static final String SELECT_LIST_HMAUX_SQL =
            "SELECT id, nome FROM disciplina ORDER BY nome";

    private static final String SELECT_PROXIMO_ID_SQL =
            "SELECT MAX(id) + 1 AS max_id FROM disciplina";

    private final ConnectionFactory factory;

    public AlunoDao(ConnectionFactory factory) {
        this.factory = factory;
    }

    public void inserirDisciplina(Disciplina disciplina) {
        try (SQLiteDatabase db = factory.conectar()) {
            ContentValues cv = new ContentValues();
            cv.put(ID, disciplina.getId());
            cv.put(NOME, disciplina.getNome());
            cv.put(TUTOR, disciplina.getTutor());
            db.insert(TABELA, null, cv);
        }
    }

    public void atualizarDisciplina(Disciplina disciplina) {
        try (SQLiteDatabase db = factory.conectar()) {
            String[] argumentos = { String.valueOf(disciplina.getId()) };
            ContentValues cv = new ContentValues();
            cv.put(NOME, disciplina.getNome());
            cv.put(TUTOR, disciplina.getTutor());
            db.update(TABELA, cv, FILTRO_ID, argumentos);
        }
    }

    public void apagarDisciplina(int idDisciplina) {
        try (SQLiteDatabase db = factory.conectar()) {
            String[] argumentos = { String.valueOf(idDisciplina) };
            db.delete(TABELA, FILTRO_ID, argumentos);
        }
    }

    public Disciplina obterDisciplinaByID(long idDisciplina) {
        String[] argumentos = { String.valueOf(idDisciplina) };

        try (
            SQLiteDatabase db = factory.conectar();
            Cursor cursor = db.rawQuery(SELECT_BY_ID_SQL, argumentos);
        ) {
            if (!cursor.moveToNext()) return null;
            Disciplina aux = new Disciplina();
            aux.setId(cursor.getInt(cursor.getColumnIndex(ID)));
            aux.setNome(cursor.getString(cursor.getColumnIndex(NOME)));
            aux.setTutor(cursor.getString(cursor.getColumnIndex(TUTOR)));
            return aux;
        }
    }

    public List<Disciplina> obterListaDisciplina() {
        try (
            SQLiteDatabase db = factory.conectar();
            Cursor cursor = db.rawQuery(SELECT_LIST_SQL, null);
        ) {
            List<Disciplina> lista = new ArrayList<>();

            while (cursor.moveToNext()) {
                Disciplina aux = new Disciplina();
                aux.setId(cursor.getInt(cursor.getColumnIndex(ID)));
                aux.setNome(cursor.getString(cursor.getColumnIndex(NOME)));
                aux.setTutor(cursor.getString(cursor.getColumnIndex(TUTOR)));
                lista.add(aux);
            }

            return lista;
        }
    }

    public int proximoID() {
        try (
            SQLiteDatabase db = factory.conectar();
            Cursor cursor = db.rawQuery(SELECT_PROXIMO_ID_SQL, null);
        ) {
            if (!cursor.moveToNext()) return 1;
            return cursor.getInt(cursor.getColumnIndex("id_max"));
        }
    }
}

Você não especificou onde você está usando os seus DAOs, mas suspeito que esse possa ser o seu grande problema. Do jeito que você usava, cada vez que você abria uma conexão, um nova instância de DataHelper e uma nova instância de SQLiteDatabase era criada. Do jeito que eu fiz, se você usar a mesma instância de ConnectionFactory e (re)utilizá-la para instanciar todos os DAOs, este problema será resolvido, uma vez que um único DataHelper será criado. Note que essa solução não seria possível sem a eliminação da herança.
Comment: Muito obrigado pelos esclarecimento e dicas, certamente me atentarei mais a esses "detalhes"! A solução de fato não foi oque você sugeriu, mas toda sua explicação foi de grande ajuda. :)


Computing the hyperbolic distance between two points

Question: In http://users.monash.edu/~jpurcell/papers/hyp-knot-theory.pdf, p. 22, it was left as an exercise that

The hyperbolic distance between the endpoints of the perpendiculars on the line from 0 to $\infty$ is $|\ln|z||$ (exercise).

However I was unable to show this result: what I tried was
$$ds^2=\dfrac{dx^2+dy^2+dt^2}{t^2} = \dfrac{\left|\dfrac{d(\frac{z+1}2 + \frac{z-1}2\cos u)}{du}\right|^2+\left|\dfrac{d(\frac{|z-1|}2\sin u)}{du}\right|^2}{\left(\frac{|z-1|}2\sin u\right)^2}=\dfrac{1}{\sin^2u}du^2$$
where $u$ ranges from $0$ to $\pi$. In this case $\sin u>0$, so we have
$$\int ds = \int_0^\pi \csc udu =  -[\ln|\csc u + \cot u|]_0^\pi $$
for which whatever the value is, is independent of $z$.
What is wrong?
Answer: The vertical line in question is the $t$-axis $\{(0,0,t) \mid 0 < t < +\infty\}$.
The two points in question on that line are:

$P=(0,0,1)$, which is the endpoint of the geodesic from $1 \in \mathbb C$ to the $t$-axis, meeting the $t$-axis at a right angle.
$Q=(0,0,|z|)$, which is the endpoint of the geodesic from $z \in \mathbb C$ to the $t$-axis, meeting the $t$-axis at a right angle.

Since the $t$-axis is a geodesic, the distance between $P$ and $Q$ is the absolute value of integral of $ds$ along the $z$-axis segment between $P$ to $Q$, which is
$$\left|\int_1^{|z|} ds\right| = \left|\int_1^{|z|} \frac{dt}{t}\right| = \left|\ln|z|\right|
$$


CSS transition on background-color

Question: I have a div with a background color and css transitions
#foo {
    background-color:rgba(255,0,0,0.9);
    -webkit-transition: all 3000ms ease;
    -moz-transition: all 3000ms ease;
    -o-transition: all 3000ms ease;
    transition: all 3000ms ease;
}

I also have a button. When the button is clicked, I would like to

immediately switch the div to transparent background and a final height
create a fade-in effect on background-color property only

To accomplish this, I've created some classes for the div
#foo.transparent {
    background-color:transparent;
}

#foo.final {
    background-color:rgba(255,0,0,0.9);
    height:400px;
}

and apply them to the div with jQuery on click
$('#start').click(function() {
    $('#foo').addClass('transparent').addClass('final');
});

Unfortunately, height switches immediately to the final value (this is correct), but the background color doesn't perform the required transition from transparent to final value. What am I missing?
(fiddle)
Comment: I am a bit lost. You are adding both classes on click at the same time and so I don't think your background is even changing. If you are looking to change it to transparent immediately and then slowly fade-in you may need to add a delay.
Comment: You are looking for something like this: [DEMO](https://jsfiddle.net/lmgonzalves/aqw4cbss/7/)?
Answer: I think an easier solution might be to use jQuery's fadeIn() effect, like this:
Html:
<button id="start">start animation</button>

some content

CSS:
#foo {
background-color:rgba(255,0,0,0.9);
}

#foo.final {
    height:400px
}

JQuery:
$('#start').click(function() {
    console.log('click');
    $('#foo').addClass('final').hide().fadeIn();
});

And your updated fiddle: https://jsfiddle.net/aqw4cbss/3/
Comment: This may be a solution, even if I preferred to use CSS transitions instead of jQuery. Thanks anyway.
Answer: height is not animatiable. use min-height && max-height instead.
plus the backgrounds in your initial state and final state are the same, so how can it be transitioned from 2 equals state.
jsfiddle
Comment: This is why i first add the transparent class: my goal is to cause a transition from transparent to non transparent background
Answer: I think you should look into JQuery .animate and .css functions.
$('#foo').css("opacity", "0");
$('#foo').animate({backgroundColor: "green"}, 500);

note: you should specify a default background-color and opacity in the css to transition from.
EDIT: You'll need the JQuery Color plugin in order to make this work (it's very small.)
https://github.com/jquery/jquery-color

CSS transition on background-color


sorttable.js - How to disable sorting on a column that has had sorting enabled on pageload?

Question: Using sorttable.js - how can I disable sorting of a column or an entire after after sorting has been enabled on that table?
More information can be found here:
https://github.com/stuartlangridge/sorttable
http://www.kryogenix.org/code/browser/sorttable/
Any information on another table sorting plugin that works well with recent jquery releases would be appreciated as well.
Comment: https://kryogenix.org/code/browser/sorttable/#nosortcolumn.  According to the Kryogenix site, you can add `class="sorttable_nosort"` to the `` to make a column unsorttable.
Answer: here's a quick hack. do this after you loaded/sorted your table. assuming you have jquery. you might want to be more specific so it doesn't disable all your tables though.
<code>$('th').css('pointer-events','none');
</code>

For example. go to that page you gave us.
http://www.kryogenix.org/code/browser/sorttable/
go to developer console in your web browser (right click and hit 'inspect') choose the console. copy & paste this, to inject jquery (since he hasn't loaded it on his webpage)
<code>javascript:(function(){function l(u,i){
    var d=document;if(!d.getElementById(i)){var s=d.createElement('script');s.src=u;s.id=i;d.body.appendChild(s);}}l('http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js','jquery')})();
</code>
now type this statement.
<code>$('th').css('pointer-events','none');
</code>
you'll see that his sorting doesn't work anymore.


Finding a cluster of size $k$ with minimum intra-distance

Question: I've been looking for an algorithm for the following problem: given a set of $N$ points $x_1, \ldots, x_N$ in $\mathbb{R}^d$ and an integer $k \leq N$, find a set of $k$ points that minimizes its intra-distance, i.e., a set $S \subseteq [N]$ of size $k$ such that $\sum_{i, j \in S} d(x_i,x_j) $ is minimal among all sets of this size.
This looks closely related to clustering, with the difference that the goal is to obtain a single tightly-packed subset of points rather than a partition of the entire set of points. However, I wasn't able to find any algorithms well-suited for this task; all the variants I managed to find either try to find a partition with prescribed sizes (such as this) or try to find a single subset, but with unconstrained size.
While iterating over all $k$-subsets yields an $O(N^k)$ time algorithm, I imagine there is a more efficient way to go about this (algorithms without proven runtime bounds would be fine, too). Is a solution to this problem known?
Comment: Are you sure that you want to minimize $\sum_{i\in S} x_i$?  I would have expected something more like $\sum_{i\in S, j \in S: i < j} d(x_i,x_j)$, where $d()$ is Euclidean distance.
Comment: That's right, thanks! I just edited the question.
Answer: You can solve the problem via integer linear programming as follows.  Let binary decision variable $y_i$ indicate whether $i \in S$.  The problem is to minimize $$\sum_{i<j} d(x_i,x_j) y_i y_j \tag1$$ subject to
$$\sum_i y_i = k \tag2$$
You can linearize the objective $(1)$ by introducing binary (or just nonnegative) variables $z_{i,j}$ and minimizing $$\sum_{i<j} d(x_i,x_j) z_{i,j}$$ subject to $(2)$ and
$$z_{i,j} \ge y_i + y_j - 1 \quad\text{for all $i<j$} \tag3$$
Constraint $(3)$ enforces the logical implication $y_i \land y_j \implies z_{i,j}$.
Comment: I see, thanks. Though that may not be faster than the trivial $O(N^k)$ time algorithm that enumerates over all subsets, right? Or is this in a class of efficiently solvable ILPs?
Comment: Even if not better in terms of computational complexity, in practice this should perform much better than brute-force enumeration.
Answer: Another strategy that is asymptotically $O(N^k)$ but will probably perform much faster in practice is $A^*$ search. One admissible heuristic is the number of points left to add times the cost of adding the greedily least expensive point. Even tighter heuristics probably also exist.


Jquery Hide/Show Div based on data-x-toggleable

Question: I have two buttons and I want to hide/show some other divs based on whether the user clicks each button.
<button id="tab-572-10" class="e572-10" role="tab" aria-selected="false" aria-controls="panel-572-10" data-x-toggle="tab" data-x-toggleable="tab-item-572-10" data-x-toggle-group="tab-group-e572-9" style="outline: none;">Tab 1</button>

<button id="tab-572-11" class="e572-11 x-active" role="tab" aria-selected="true" aria-controls="panel-572-11" data-x-toggle="tab" data-x-toggleable="tab-item-572-11" data-x-toggle-group="tab-group-e572-9" style="outline: none;">Tab 2</button>

I am trying to target the class of each button to identify which button the user has clicked
jQuery('button[data-x-toggleable]').on('click', function() {
  if (this.hasClass("e572-10")) {
    jQuery('div[id^=pr-mem]').show();
    jQuery('div[id^=co-mem]').hide();
  }
});

However I get error: Uncaught TypeError: this.hasClass is not a function
Answer: Because it is
$(this).hasClass("..."); // jQuery

or
this.classList.contains("...."); // DOM


Chi Square Test for QC Samples

Question: An analytical procedure is run for 112 consecutive days. Each day, the analyses are run in four batches in order -- Batch-1, Batch-2, etc. In each batch is a QC sample, labeled QC1, QC2, etc. The following R code generates a contingency table for the data, showing the number of times each QC sample was a particular rank. For example, QC1 had the highest result 43 days out of 112 and QC4 had the lowest result 28 days out of 112. The analyst has the feeling that the first batch of the day tends to have the highest results. What statistical test should I use to check out whether or not the ranks of the QC samples are random from day to day? I understand that I should not use a chi-square test of independence between the QC sample and the ranks, but why not?
<code>count <- c(43,26,26,17,24,33,28,27,18,27,27,40,27,26,31,28)
mat.obs <- matrix(count,nrow=4,byrow=TRUE)
rownames(mat.obs) <- c("QC1","QC2","QC3","QC4")
colnames(mat.obs) <- c("1","2","3","4")
mat.obs
</code>
Comment: I think that this feeling comes from the fact that given the way your 4×4 matrix is generated, all rows and all columns sum to 112. This is definitely not a classical contingency table.
Comment: I think the table is fine. I just point out what makes it special... I'll try to propose an answer later.
Comment: The table was generated after the analyst expressed the gut feeling about the QC samples, and if nothing else it is a concise way of presenting the results for discussion.
Answer: I think you probably want a Friedman test.  This is designed for just this case.  It is a non-parametric equivalent of an ANOVA  for where the data are rankings.
You can implement this in R using friedman.test() which comes with the base distribution.  However, you need some additional information not contained in your summary table.  You will need to present the data with 112 rows and 4 columns (one for each QC sample), with the cell being the rank from one to four of each sample for that day.

Chi Square Test for QC Samples


Solving a non-linear equation of 3 unknowns

Question: I have the following set of equation which comes from a free boundary problem. I have seen a paper which had complicated expression for the solution for even more variables. I would like to know how to solve these explicitly. The first two equations comes from a smooth fit condition, the last equation comes from continuity condition. I have tried solving it, but I have failed. but are there any standard methods?
$C_1x_*^{\beta_1}+C_2x_*^{\beta_2}=K-x_*$
$C_1\beta_1x_*^{\beta_1}+\beta_2C_2x_*^{\beta_2}=-x_*$
$C_1x_1^{\beta_1}+C_2x_1^{\beta_2}=C$
Here $x_*$, $C_1$ and $C_2$ are unkown, but $x_1$, $C$, $\beta_1$ and $\beta_2$ are known.
$\beta_1<0<\beta_2$. $C$ is fixed such that a solution exists for $x_1<x_*<K$
Comment: It seems that the second equation is redundant because it can be obtained by differentiating the first one with respect to $-x^*$.
Comment: @mne__povezlo no it is not, because the first equation cannot hold for every $x$. this type of thing arises from smooth fit condition for pricing of american type options in optimal stopping and my girlfriend made the identical comment, so you are not the only one thinking that!
Comment: excuse my incompetence. So is the true then that the first two equations describe the point of tangency of two curves since we'd like the values and the slopes at that point to be the same?
Comment: @mne__povezlo yes we are trying to patch up 2 equations at a point so that it is continuous at that point and their first derivative agrees
Answer: The 3rd equation gives $$C_2=a+bC_1$$ where $a$ and $b$ can be expressed in terms of known quantities.
Then the 1st equation becomes $$C_1x_*^{\beta_1}+(a+bC_1)x_*^{\beta_2}=K-x_*$$ which we can solve for $C_1$: $$C_1={K-x_*-ax_*^{\beta_2}\over x_*^{\beta_1}+bx_*^{\beta_2}}$$ Now we can dump all this into the 2nd equation to get something where $x_*$ is the only unknown: $${K-x_*-ax_*^{\beta_2}\over x_*^{\beta_1}+bx_*^{\beta_2}}\beta_1x_*^{\beta_1}+\beta_2\left(a+b{K-x_*-ax_*^{\beta_2}\over x_*^{\beta_1}+bx_*^{\beta_2}}\right)x_*^{\beta_2}=-x_*$$ Clearing fractions, this is $$(K-x_*-ax_*^{\beta_2})\beta_1x_*^{\beta_1}+\beta_2(a(x_*^{\beta_1}+bx_*^{\beta_2})+b(K-x_*-ax_*^{\beta_2}))x_*^{\beta_2}=-x_*(x_*^{\beta_1}+bx_*^{\beta_2})$$ Now you can multiply everything out and combine like terms. It looks like you'll get an equation involving $x_*$ to the powers $0,1+\beta_1,\beta_1+\beta_2,2\beta_2$, and $1+\beta_2$.
It will probably be hopeless to solve such an equation, other than numerically.
Comment: Thanks a lot, here is a slightly harder question, and a lot more vague, so my apologies. how would you go about proving  $x_1<x_*<K$ if I have a lower and upper bound of value of C? (I stated this as an assumption and from intuition and sketches, it is pretty clear, but there is no way of knowing)
Comment: If it helps in fact I want to show $x_1<x_*<x_0<K$ where $x_0$ is a point which satifies $K-x_0= Dx_0^{\beta_1}$ and $-x_0= D\beta_1x_0^{\beta_1}$, so $Dx^{\beta_1}$ is a touches the line $K-x$ at $x_0$. In fact, $K-x$ is its tangent at $x_0$. The condition on $C$ is that $C<(K-x_0)(x_1/x_0)^{\beta_1}$. I know that if $C=(K-x_0)(x_1/x_0)^{\beta_1}$, the solution is precisely $D\beta_1x_0^{\beta_1}$ and $x_*=x_0$. If it helps, $D=(K-x_0)(1/x_0)^{\beta_1}$
Comment: And don't worry if you do not want to help me with this. any sort of comment on theorems which might be useful is greatly appreciated.


Unity3D: Extract Textures from FBX via C# script

Question: I am struggling to find a way to extract textures from an FBX model in Unity via script. Unity has a hidden method to extract materials here, but cannot find a method to extract textures even in their own github.
i even tried to use the same approach to load Texture2D-s from the asset file like so:
    IEnumerable<Object> enumerable = from x in AssetDatabase.LoadAllAssetsAtPath(assetPath)
                                                 where x.GetType() == typeof(Texture2D)
                                                 select x;

but to no avail.
Can anyone help? thank you!
Answer: You can achieve this using ModelImporter:
var tex = AssetImporter.GetAtPath(pathToFbx) as ModelImporter;
tex.ExtractTextures(destinationPath);


Create a dynamic Mongo query in Java

Question: I'm migrating MongoDB with Hibernate OGM & ORM to 'pure' Java MongoDB (org.mongodb:mongodb-driver-core:4.4.0.
As: "Hibernate OGM is not going to work with ORM 5.5 (the latest version requires ORM 5.3)".
How to use Hibernate ORM 5.5.x.Final with Jakarta 9 on wildfly-preview-25.0.0.Final
I now want to create a 'dynamic' version say x -> 99 (FindIterable Document). As I did similar with Hibernate OGM & ORM:
if (MotorcycleController.motorcycleManufacturers.length > MotorcyclesEJB.ZERO) {
    stringBuilderSQL.append(WHERE);
    stringBuilderSQL.append(OPEN_BRACKET);

    for (int x = MotorcyclesEJB.ZERO; x < MotorcycleController.motorcycleManufacturers.length; x++) {
        stringBuilderSQL.append(MotorcyclesEJB.MANUFACTURER);
        stringBuilderSQL.append(MotorcyclesEJB.EQUALS);
        stringBuilderSQL.append(MotorcyclesEJB.SINGLE_QUOTE);
        stringBuilderSQL.append(MotorcycleController.motorcycleManufacturers[x]);
        stringBuilderSQL.append(MotorcyclesEJB.SINGLE_QUOTE);

        if ((x + ONE) < MotorcycleController.motorcycleManufacturers.length) {
            stringBuilderSQL.append(MotorcyclesEJB.OR);
        }

        stringBuilderSQL.append(CLOSE_BRACKET);
    }
}

I can create (a static) multiple persion of MongoDB 'Collection' using:
FindIterable<Document> motorcycleApriliaMotoGuzzi = mongoCollectionMotorcycleManufacturer.find(or(eq("manufacturer", "Aprilia"), eq("manufacturer", "Moto Guzzi")));

Which can show results (example of one):
INFO  [com.gostophandle.ejb.MongoDBEJB] (ServerService Thread Pool -- 97) >>>>> motorcycleApriliaMotoGuzzi = Document{{_id=61d70d6a8c9e88075702af3e, manufacturer=Aprilia, model=RS 660, modelType=E5, typesOf=Sport, dateProductionStarted=Fri Jan 01 00:00:00 GMT 2021, dateProductionEnded=Fri Jan 01 00:00:00 GMT 2021, engine=Document{{type=Four-Stroke, displacement=659.0, cylinder=2.0, capacityUnit=cc, carburation=, bore=0.0, boreMeasurement=mm, stroke=0.0, strokeMeasurement=mm, distribution=, maxiumPowerHp=0.0, maxiumPowerKilowatt=0.0, maxiumPowerRpm=0.0, maximumTorque=0.0, maximumTorqueUnit=Nm, maximumTorqueRpm=0.0}}, performance=Document{{topSpeedMph=105.0, topSpeedKph=0.0, accelleration30Mph=0.0, accelleration60Mph=0.0, accelleration100Mph=0.0, accelleration30Kph=0.0, accelleration60Kph=0.0, accelleration100Kph=0.0}}, dimensionsWeights=Document{{batteryCapacity=, casterAngleDegrees=0.0, dimensionsL=0.0, dimensionsW=0.0, dimensionsH=0.0, frameType=, fuelTankCapacityLitres=0.0, fuelConsumption=0.0, groundClearance=0.0, kerbWeight=0.0, seatHeight=0.0, trail=0.0, wheelbase=0.0}}, chassisBrakesSuspensionWheels=Document{{frame=1, swingarm=2, absSystem=3, frontBrakes=4, rearBrakes=5, frontSuspension=6, rearSuspension=7, tyresFront=8, tyresRear=9, frontTyre=10, rearTyre=11, frontWheel=12, rearWheel=13, instrumentDisplayFunctions=14}}, transmission=Document{{clutch=1, clutchOperation=2, finalDrive=3, gearbox=4, transmissionType=5, primaryReduction=0.0, gearRatios1st=0.0, greaRatios2nd=0.0, gearRatios3rd=0.0, gearRatios4th=0.0, gearRatios5th=0.0, gearRatios6th=0.0}}, instruments=Document{{headlights=1, socket=2, ignitionSystem=3, instruments=4, tailLight=5, usbSocket=6}}, electrics=Document{{}}, colours=[Document{{colour=Acid Gold}}, Document{{colour=Lava Red}}, Document{{colour=Apex Black}}], accessories=[], image=Document{{file=/Users/NOTiFY/IdeaProjects/GoStopHandle/images, url=/Aprilia/2021/, png=ap6115200ebm03-01-m.webp, dimensionsWidth=1500, dimensionsHeight=1000}}}}

I can't get it to create a dynamic version using 'find', 'or' & 'eq' etc.
Any suggestions? TIA.
Comment: Your original code looks like it is prone to SQL injection.
Comment: There is some help [here](https://stackoverflow.com/q/57488543/102937), although that `eval` call gives me pause.  The second method described in the answer there might work.
Answer: There are two Filters methods for constructing the Bson for OR:
Filters.or(Bson...)
Filters.or(Iterable<Bson>)

Using the latter, you can construct Bson for each of your conditions that you want to OR together, collect them in a List, and then pass that list to that method to construct the Bson for the OR.  I guess this is really an IN operation because these are all the same field but for demonstration purposes:
public Bson or(String field, List<String> values) {
  return Filters.or(
      values.stream()
        .map(v -> Filters.eq(field, v))
        .collect(Collectors.toList()));
}

Answer: @vsfDawg - Perfect
 List<String> stringList = new ArrayList<>();
 stringList.add("Aprilia");
 stringList.add("Moto Guzzi");

 Bson bson = or("manufacturer", stringList);

 MongoCursor<Document> cursor = mongoCollectionMotorcycles.find(or("manufacturer", stringList)).iterator();;
 try {
     while (cursor.hasNext()) {
         LOGGER.info(">>>>> 6.4 motorcycleApriliaMotoGuzzi = {}", cursor.next());
     }
 } finally {
     cursor.close();
 }

public Bson or(String field, List<String> values) {
    return Filters.or(
        values.stream()
           .map(v -> Filters.eq(field, v))
           .collect(Collectors.toList()));
    }
}

Displays data:
INFO  [com.gostophandle.ejb.MotorcyclesEJB] (default task-1) >>>>> 6.4 motorcycleApriliaMotoGuzzi = Document{{_id=61d70d6a8c9e88075702af3e, manufacturer=Aprilia, model=RS 660, modelType=E5, typesOf=Sport, dateProductionStarted=Fri Jan 01 00:00:00 GMT 2021, dateProductionEnded=Fri Jan 01 00:00:00 GMT 2021, engine=Document{{type=Four-Stroke, displacement=659.0, cylinder=2.0, capacityUnit=cc, carburation=, bore=0.0, boreMeasurement=mm, stroke=0.0, strokeMeasurement=mm, distribution=, maxiumPowerHp=0.0, maxiumPowerKilowatt=0.0, maxiumPowerRpm=0.0, maximumTorque=0.0, maximumTorqueUnit=Nm, maximumTorqueRpm=0.0}}, performance=Document{{topSpeedMph=105.0, topSpeedKph=0.0, accelleration30Mph=0.0, accelleration60Mph=0.0, accelleration100Mph=0.0, accelleration30Kph=0.0, accelleration60Kph=0.0, accelleration100Kph=0.0}}, dimensionsWeights=Document{{batteryCapacity=, casterAngleDegrees=0.0, dimensionsL=0.0, dimensionsW=0.0, dimensionsH=0.0, frameType=, fuelTankCapacityLitres=0.0, fuelConsumption=0.0, groundClearance=0.0, kerbWeight=0.0, seatHeight=0.0, trail=0.0, wheelbase=0.0}}, chassisBrakesSuspensionWheels=Document{{frame=1, swingarm=2, absSystem=3, frontBrakes=4, rearBrakes=5, frontSuspension=6, rearSuspension=7, tyresFront=8, tyresRear=9, frontTyre=10, rearTyre=11, frontWheel=12, rearWheel=13, instrumentDisplayFunctions=14}}, transmission=Document{{clutch=1, clutchOperation=2, finalDrive=3, gearbox=4, transmissionType=5, primaryReduction=0.0, gearRatios1st=0.0, greaRatios2nd=0.0, gearRatios3rd=0.0, gearRatios4th=0.0, gearRatios5th=0.0, gearRatios6th=0.0}}, instruments=Document{{headlights=1, socket=2, ignitionSystem=3, instruments=4, tailLight=5, usbSocket=6}}, electrics=Document{{}}, colours=[Document{{colour=Acid Gold}}, Document{{colour=Lava Red}}, Document{{colour=Apex Black}}], accessories=[], image=Document{{file=/Users/NOTiFY/IdeaProjects/GoStopHandle/images, url=/Aprilia/2021/, png=ap6115200ebm03-01-m.webp, dimensionsWidth=1500, dimensionsHeight=1000}}}}
12:42:59,335 INFO  [com.gostophandle.ejb.MotorcyclesEJB] (default task-1) >>>>> 6.4 motorcycleApriliaMotoGuzzi = Document{{_id=61d70d6a8c9e88075702af58, manufacturer=Moto Guzzi, model=Le Mans, modelType=I, typesOf=Sport, dateProductionStarted=Thu Jan 01 00:00:00 GMT 1976, dateProductionEnded=Sat Jan 01 00:00:00 GMT 1977, engine=Document{{type=Four-Stroke, displacement=850.0, cylinder=2.0, capacityUnit=cc, carburation=null, bore=80.0, boreMeasurement=mm, stroke=74.0, strokeMeasurement=mm, distribution=null, maxiumPowerHp=85.0, maxiumPowerKilowatt=38.0, maxiumPowerRpm=6200.0, maximumTorque=60.0, maximumTorqueUnit=Nm, maximumTorqueRpm=4900.0}}, electrics=Document{{}}, colours=[Document{{colour=Red}}, Document{{colour=Silver Blue}}], accessories=[Document{{productNumber=MG0123456789, productName=Product 1}}, Document{{productNumber=MG0123456789, productName=Product 2}}], image=Document{{file=/Users/NOTiFY/IdeaProjects/GoStopHandle/images, url=/MotoGuzzi/1976/, png=motorcycle.png, dimensionsWidth=900, dimensionsHeight=440}}}}

Create a dynamic Mongo query in Java


ARCore Augmented Image how to create a new Object Renderer at runtime

Question: I'm expanding the "Augmented Image" Arcore project in Android Studio using Java, and i would like to create at runtime new Objects Renderer in order to spawn new objects on the augmented Image. I saw the "Hello AR" project, but in that example it creates more instances of the same object, and therefore use the same Object Renderer. I need to create different objects and so I think I need to create different Objects Renderers.
I tried to create all of the Object Renderers I need in the "createOnGlThread" method but it takes time, while i'd prefer to create them at runtime. The problem it gives me is in the shader tho. It can't create them outside the "createOnGlThread" method as the "GLES20.glCreateShader(type)" method in the ShaderUtil always returns 0, and "GLES20.glGetShaderiv(shader, GLES20.GL_COMPILE_STATUS, compileStatus, 0);" returns 0 in the compileStatus too and it launches the RuntimeException("Error creating shader.").
How can I create an Object Renderer outside the "createOnGlThread" method?
Answer: What you can do is instead of creating all you Object Renderers at first try to create them when for example a model has been selected.
let's say you have a button on the screen and when you click on the button you want to create a new Object Renderers and change the model and texture. here is how you can handle this.
myNewModel.setOnClickListener {
            objectName = "newModelFromAssets"
            objectTexture ="newTextureFromAssets"
            objectRenderer = ObjectRenderer()
            isModelSelected = true
    }

Then in onDrawFrame do this:
if (isModelSelected) {
            isModelSelected = false
            try {
                objectRenderer.createOnGlThread(
                    this,
                    objectName,
                    objectTexture
                )
               objectRenderer.setDepthTexture(
                    depthTexture.depthTexture,
                    depthTexture.depthWidth,
                    depthTexture.depthHeight
                )
               objectRenderer.setMaterialProperties(
                    0.0f,
                    2.0f,
                    0.5f,
                    6.0f
                )
            } catch (e: Exception) {
                Log.e("onSurfaceCreated", "Failed to read plane texture")
            }
        }

That's all.
And an easier solution is to use 'queueEvent' to interact with OPENGL from main thread like this :
surfaceView.queueEvent {
//render your object
}


Leitura de registro para inferir contador

Question: Tenho um modelo chamado Request e esse modelo tem uma coluna chamada Number.
Esse Number tem a seguinte estrutura: ANO + CONTADOR.
Acontece que sempre que vou criar uma nova request eu pego a última request adicionada no banco de dados e a partir dela posso inferir o Number da nova request.
Por exemplo, se minha última request inserida tem number = 20140001 então a próxima request terá number = 20140002.
O problema ocorre quando duas requests são geradas simultaneamente. Acontece que dois ou mais processos podem criar requests. Logo em cada processo desse o banco é acessado, eu verifico qual é a ultima request e gero uma nova. Acontece que de modo simultâneo os processos pegam a mesma request e consequentemente geram Numbers iguais.
Estou usando Entity Framework 5 e MVC 4. Como resolver isso?
Comment: Qual e' a base de dados?
Comment: Junior, você já resolveu este problema? Ainda precisa de ajuda?
Comment: é Sql server dcastro! Ainda não resolvi Andre. A resposta do dcastro não acho que está correta. Não quero um contador para a minha key.
Comment: Você precisa do número ANTES do insert no banco de dados, é isso?
Comment: Sim @iuristona.
Answer:
Tens que actualizar o esquema da BD, e alterar o campo number da tabela Requests para

chave primaria
auto increment - isto depende da BD. Em SQL Server, usa-se a keyword Identity

Adicionar o atributo [DatabaseGenerated(DatabaseGeneratedOption.Identity) a' propriedade Number no codigo.
public class Request
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)
    public int Number {get; set;}
}

Assim, a BD vai tratar de auto-incrementar o campo. E gracas as propriedades ACID, nao havera problemas de concurrencias.

Se nao quiseres/poderes usar autoincrement, acho que vais ter de implementar o teu proprio mecanismo, e isso nao é tarefa simples...
Ora bem, ja nao trabalho com bases de dados ha algum tempo, mas eu recomendo o seguinte:

Criar uma tabela (ex: "NumberCounter") com uma só linha e uma só coluna (ex: "Count")
╔═══════╗
║ Count ║
╠═══════╣
║  2010 ║
╚═══════╝

Quando quiseres incrementar & obter o próximo number, usa uma stored procedure que:

Incrementa o valor de Count. Exemplo em "pseudo-codigo"/"pseudo-query": INSERT INTO NumberCounter(Count) values((Select Count from NumberCounter) + 1);
Usa um lock na tabela, para impedir que outros increments sejam feitos em paralelo
Retorna o valor actual de Count.

Espero que ajude.
Ler mais:
 Understanding Locking in SQL Server
Comment: Não quero um autoincrement...
Comment: @Junior posso perguntar porquê? Parece ser o ideal para essa situação..
Comment: @Junior, editei a minha resposta e forneci um rascunho de uma solução alternativa. Espero que ajude.
Answer: Se você está utilizando SQL Server 2012 você deveria utilizar uma sequence. O valor deve ser recuperado no momento em que o form é carregado.
Se seu banco não for SQL Server 2012, uma opção pra simular uma sequence está nesse artigo.
Answer: Para lidar com esse problema de concorrência, eu crio a entidade em questão e uma outra entidade de controle. Assim:
1- crio a entidade principal, neste caso: Request
public class Request
{
    public Guid RequestId { get; set; } = Guid.NewGuid();

    public int Number { get; set; }

    // demais propriedades necessárias
}

2- crio uma entidade de controle do número, tipo: RequestCounter
public class RequestCounter
{
    public Guid RequestCounterId { get; set; } = Guid.NewGuid();

    public int Number { get; set; } // no banco este campo será autoincrement

    public DateTime Dth { get; set; } = DateTime.Now;
}

3- Na Action do Controller, eu chamo ObterRequestCounter() para obtenção do número.
public ActionResult Create(Request request)
{
    if (ModelState.IsValid)
    {
        request.Number = ObterRequestCounter();

        _repository.Adicionar(request);

        return RedirectToAction("Index");
    }

    return View(request);
}

4- Crio o método privado onde adiciono um RequestCounter com o RequestCounterId gerado por mim (quando instancio) e depois faço a consulta utilizando-o para recuperar Number.
private int ObterRequestCounter()
{
    var requestCounter = new RequestCounter();

    _repository.AdicionarRequestCounter(requestCounter);

    var newNumber = _repository.ObterRequestCounterPorId
                                (requestCounter.RequestCounterId).Number;

    // concateno o ano com o novo número e depois retorno para número.
    return Convert.ToInt32(DateTime.Now.Year + newNumber.ToString());
}

Por causa do passo 4, não importa quantos usuário farão uma adição do Request ao mesmo tempo. Com o RequestCounterId do RequestCounter gerado no código (antes de ir para o banco), eu consigo recuperar qual foi o Number gerado automaticamente pelo banco sem concorrência.
No meu caso, a tabela do RequestCounter fica como histórico, mas se meu cliente em algum momento futuro decidir que registros antigos devam ser apagados, eu posso fazê-lo utilizando a propriedade Dth para isso.
É isso.


Swagger Try it out button not working (Swashbuckle issue)

Question: I added Swashbuckle.AspNetCore 2.4.0 to my VS2017 project
following along on Pluralsight's Play by Play course.
When I navigate to http://localhost:51806/swagger/  I have the swagger UI.
When I click on the "Try it out" button the button changes to "Cancel" but nothing else happens.
I have tried each response content type
Swagger support forum indicates this is a Swashbuckle issue.
[Update]
I just did not realise that the Execute was a link
Comment: Are there any errors in the browser console?
Comment: no errors in the browser console
Comment: Is there button  "Execute"? Did you try other browsers?
Comment: Does this prove that , UI design of Swagger is not appropriate (think) ?
Comment: Ah it just shows the design was not intuitive for a particular newbie (me)
Answer: But after pressing the button "Try it out", nothing should happen, only display "Execute" button
Comment: Glad to have been of help
Comment: Thank you, oh dear, lol, I updated the question to show my ignorance!


Error Running composer.phar update

Question: This worked about 3 months ago, which was the last time I edited this JSON file. The change at the time was to add the reference to ThirdEngine/DotNetIntegration which is a library I wrote. Running php composer.phar update gives me the following error.
Problem 1

Installation request for doctrine/migrations dev-master -> satisfiable
  by doctrine/migrations[dev-master].
doctrine/migrations dev-master requires symfony/console ~2.3 -> no
  matching package found.

Problem 2

doctrine/migrations 1.0.x-dev requires symfony/console ~2.3 -> no
  matching package found.
doctrine/doctrine-migrations-bundle dev-master requires
  doctrine/migrations ~1.0 -> satisfiable by
  doctrine/migrations[1.0.x-dev].
Installation request for doctrine/doctrine-migrations-bundle
  dev-master -> satisfiable by
  doctrine/doctrine-migrations-bundle[dev-master].

{
  "name": "latent-codex/estimator",
  "description": "",
  "autoload": {
    "psr-0": { "": "src/" }
  },
  "require": {
    "php": ">=5.3.3",
    "symfony/symfony": "2.2.*",
    "propel/propel-bundle": "1.1.*",
    "doctrine/orm": "~2.2,>=2.2.3",
    "doctrine/doctrine-bundle": "1.2.*",
    "doctrine/doctrine-fixtures-bundle": "dev-master",
    "doctrine/doctrine-migrations-bundle": "dev-master",
    "doctrine/migrations": "dev-master",
    "doctrine/data-fixtures": "dev-master",
    "twig/extensions": "1.0.*",
    "symfony/assetic-bundle": "2.1.*",
    "symfony/swiftmailer-bundle": "2.2.*",
    "symfony/monolog-bundle": "2.2.*",
    "symfony/console": "2.2.*",
    "sensio/distribution-bundle": "2.2.*",
    "sensio/framework-extra-bundle": "2.2.*",
    "sensio/generator-bundle": "2.2.*",
    "jms/security-extra-bundle": "1.4.*",
    "jms/di-extra-bundle": "1.3.*",
    "braintree/braintree_php" : "2.27.0",
    "mikehaertl/phpwkhtmltopdf": "1.2.*",
    "h4cc/wkhtmltopdf-amd64": "0.12.*",
    "intervention/image": "2.*",
    "robmorgan/phinx": "*",
    "phpunit/phpunit": "4.3.*",
    "ThirdEngine/DotNetIntegration": "dev-master",
    "symfony/process": "2.2.*"
  },
  "scripts": {
    "post-install-cmd": [
      "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::buildBootstrap",
      "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::clearCache",
      "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::installAssets",
      "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::installRequirementsFile"
    ],
    "post-update-cmd": [
      "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::buildBootstrap",
      "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::clearCache",
      "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::installAssets",
      "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::installRequirementsFile"
    ]
  },
  "config": {
    "bin-dir": "bin",
    "github-oauth": {
        "github.com": "3d9b33f82636944b2cf643e5bf4011c2a89af6b4"
    }
  },
  "minimum-stability": "alpha",
  "extra": {
    "symfony-app-dir": "app",
    "symfony-web-dir": "web",
    "branch-alias": {
      "dev-master": "2.2-dev"
    }
  },
  "repositories": [
    {
      "type": "vcs",
      "url": "git://github.com/ThirdEngine/DotNetIntegration.git"
    }
  ]
}
Comment: Since you are only adding a new lib you can use `php composer.phar update ThirdEngine/DotNetIntegration`. Symfony 2.2 is EOL and you are trying to update all the packages set to dev master so you may encounter dependency issues
Answer: I ended up just upgrading the frameworks to newer versions and setting the versions in the composer.json to fixed version properly like it should have been done originally.

Error Running composer.phar update