Is a multigroup confirmatory factor analysis appropriate for comparing the measurement model across two groups?

Question: Background: Before commencing treatment 180 participants completed a baseline 17-item Hamilton depression rating scale (HDRS), which is a likert scale. Because of the treatment, half developed depression and the other half did not. So i have two groups; depressed and non-depressed.
Analysis: I want to know whether the factor structure of baseline HDRS differs between the two groups. Thus, I performed multiple group confirmatory factor analysis (CFA).
I used a theoretically validated and relevant HDRS factor model as the basis of the MGCFA to compare goodness of fit measures and determine measurement invariances between the groups. However, my initial CFA indicated a poor model fit for both my groups. I am mindful that my sample sizes may be too small for this.
Questions

Is multigroup CFA appropriate for comparing the measurement model of my two groups?
What should I do given the poor model fit of the CFA in both groups?
Is a total sample size of 180 too small for this multiple group CFA?
Answer: In general, multiple group CFA is a good tool for comparing the equivalence of a measurement model across two groups.
However, you first need to show that the measurement model makes sense in at least one group.
First, analyse the entire sample
There are many different ways of tackling factor exploration. Here are some thoughts

Consider analysing the factor structure of the entire sample of 180.
If the confirmatory CFA is giving poor fit, you might want to run an exploratory factor analysis to see what is going on in the data. Are there items loading on factors other than theorised? Do the number of factors theorised seem reasonable relative to factor structures you get with a few more or a few less factors?
Also, it is not uncommon for item-level CFAs with large numbers of items per factor to yield relatively poor fit. This can be explained both in terms of how we think about fit statistics in such contexts, and also in terms of the simplicity of many measurement models. For example, it is quite common for there to be a number of systematic deviations from the idealised structure (e.g., items with common words correlating more highly; items close together correlating more highly; items that both negatively worded correlating more highly; etc.). Without incorporating these, dare I say, nuisance characteristics, fit will often be poor even when the theorised structure is a reasonable approximation.
Some people adopt an item parcelling approach to CFA that often smooths out some of these low-level item characteristic effects. Note that there is some controversy over the appropriateness of this approach. Item parcelling is often appealing to researchers, perhaps wrongly, because it can improve fit statistics to satisfy conventional criteria and therefore increase the ability to get published. A more reasonable justification for item-parcelling is in situations where you are not interested in the item-level and are only interested in more general characteristics of the scale. Anyway, in your case, you might want to examine item parcelling as it also reduces the number of parameters that need to be estimated.
With regards to sample size, I agree that more would be better, but my sense is that you'll still be able to get interesting results with 180. You can use fit statistics with confidence intervals to quantify associated uncertainty due to the smaller sample size.

Multiple group CFA
So, if, and only if, you can get a good model at the overall level would I proceed to multilple group CFA.
Comment: Hi Jeremy, thanks! I ran an EFA on the overall group and came up with a good fitting, theoretically sound, 2 factor model (4 items and 9 items). However, when conducting a CFA at the group level, the depressed group (n=95) fits well, whilst non-depressed group (n=85) fails to converge through floor effects of three of the items, all of which loaded onto the second factor. I rescoped the CFA dropping these three items, again getting a good fit overall and for the depressed group, but low fit metrics in the non-depressed group, which produces errors when I do a MGCFA. Any advice how to proceed?


How to refresh new migrations in Drupal 8 migration module?

Question: When writing Drupal 8 migrate processes I only can refresh new migration processes if I reinstall the custom migration module. drush cr doesn't work.
Explanation:
I have one module, ie: cm_migrations, which have 2 migrations:

cm_users
cm_tags

With drush ms I see:
Group: beer     Status  Total  Imported  Unprocessed  Last imported
 cm_users        Idle    3      3         0            2016-02-09 16:56:25
 cm_tags         Idle    4      0         4

I write a new migrate process:

cm_beers

I execute drush cr; drush ms and I see the same table as previous.
Only when I uninstall and install cm_migrations I can see the three migration processes:
Group: beer     Status  Total  Imported  Unprocessed  Last imported
 cm_users        Idle    3      3         0            2016-02-09 16:56:25
 cm_tags         Idle    4      0         4
 cm_beers        Idle    4      0         4

Any clue about  how can I refresh the migration processes without reinstall the module?
Thanks
Comment: In addition, I can say that if I execute the migration process, delete the content of `migrate.migration.cm_beers.yml` and execute again the process, the migration doesn't fail.

It seems to be cached the content of the yaml file somewhere.
Answer: I found this worked for me

drush config-import --partial --source=modules/custom/migrate_module/config/install/
Comment: @harshal had the same error when i had a preceding '/' in front source path while executing it from drupal project root. Without preceding '/' it is working fine
Comment: Hi, the above gives the following error :  The source directory does not exist. The source is not a directory.
Comment: Thanks @makkus, noted it
Answer: Migrations should be in the MODULENAME/migrations subdirectory.
After modifying a migration config a simple drush cr suffices to apply the changes.
A config deriver will turn a migration config back into a migration plugin.
See this change record: Migrations are plugins instead of configuration entities
Answer: There is a module for that.
Since normally the yml files are only loaded upon install.
This module lets you can define what module config files are automaticly imported.
https://www.drupal.org/project/config_devel
Also see this blog post:
https://blog.liip.ch/archive/2016/05/04/using-the-new-drupal-8-migration-api-module.html

Developing your own Drupal 8 migrate modules and fighting caching issues

You have learned, that the whole migration mapping is now done in yaml files. But how about writing your own migration yaml files?
Unfortunately, there are some pitfalls for new Drupal 8 developers. Because of the Configuration Management Interface (https://www.drupal.org/documentation/administer/config) of Drupal 8, all yml files in the "config/install" directory are only imported when installing the module.
This is very impractical if you want to develop new configuration files. To address this, a module "Configuration Development" (https://www.drupal.org/project/config_devel) which resolves the caching issues can be installed. It is possible to import certain yml files on every request. But unfortunately drush commands are not supported yet. So we need to add all yaml files we want to import into a new section in our module.info.yml.
config_devel:
 install:
   - migrate_plus.migration.page_node
   - migrate_plus.migration.menu_item
   - migrate_plus.migration_group.liip

Then we can run the following commands after updating the yml file. This will import the new configuration file into Configuration Management Interface.
drush cdi <module_name>
drush cr

Comment: I can't get this to work, and the documentation is lacking. Can you give a bit more information?

https://www.drupal.org/node/2845304
Answer: I was struggling with the same issue: how to update migration config during development. Here is what I ended up with:
drush cdi1 path-to-config-dir-form-site-root/your-config.yml

config-devel-import-one, command (cdi1 for short) is intended to import single config into active configuration. It is the part of config_devel module mentioned above.
Answer: I didn't have success with FLY's solution. Had to uninstall migrate_tools also, to get yaml's refreshed. And no luck with devel_config.
I did find this refreshed configurations:
$ drush @site_alias pmu mymodule, migrate_tools, migrate_plus -y
$ drush @site_alias en mymodule, migrate_tools, migrate_plus -y

Answer: I have found that sometimes none of the above work. Even combining them all. However I could trick migrate_tools into giving me some insight.
Apparently there is a check if the yml file is valid before it gets listed. Try running the importer (yes, even if it doesn't show up with $ drush ms )
My migration was called products, so I did: $ drush mim products
Migration failed with source plugin exception: The "int" plugin does not exist.
Fixing this fault (changing int to integer in my case) and then following @FLY 's answer above made the migration show up. Shame the error did not show up and it just failed silently, but that's another topic. ;-)
P.S. I would have posted this as a comment, but I don't have enough points yet.
Answer: Following up on Peter J Lord's solution, you can also add a config directory (for new or updated ymls) to your settings.php file. e.g.:
$config_directories['fresh'] = 'sites/default/fresh';

Place new yml files in that directory and then import the fresh configuration settings with drush's config-import command:
drush cim fresh --partial

Answer: Following on from the config_devel solution explained by FLY.
config_devel now has a gui at admin/config/development/config_devel. In 'Auto import' you can list all the ymls you want importing. It doesn't take wildcards so you have to list them individually. When these files change, they will be automatically imported at the beginning of the next browser page request.
Answer: In the answer by FLY above, drush cdi <module_name> should now be drush cde <module_name>.
Comment: drush cde exports the config and overwrites what you have. That's not what we want. How is this accepted?


If $\frac{\sin^2 A + \sin^2 B + \sin^2 C}{\cos^2 A + \cos^2 B + \cos^2 C}=2$ , then $\triangle ABC$ is a right triangle

Question:
Show that the triangle whose angles satisfy the equality
  $$\frac{\sin^2 A + \sin^2 B + \sin^2 C}{\cos^2 A + \cos^2 B + \cos^2 C}=2$$
  is right-angled.

I've tried many times, but was unsuccessful.
Comment: Welcome to MSE.  Your questions will have more chances to be answered rather than downvoted if you show your work:  what have you tried?  And, instead of giving a link to a .jpg file, please use [MathJax](https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference)
Answer: Hint: Show that
\begin{eqnarray*}
1-\cos^2 A-\cos^2 B-\cos^2C+ 2\cos A \cos B \cos C =0
\end{eqnarray*}
for any triangle.
Answer: COMMENT.- First note that if $C=90^{\circ}$ then you have $\dfrac{1+1}{1+0}=2$. To verify that necessarily your equality implies $C=90^{\circ}$ you can consider that $\sin C=\sin (180^{\circ}-(A+B))=\sin(A+B)$ and $\cos C= \cos (180^{\circ}-(A+B))=-\cos(A+B)$ so you get
$$\sin^2 A+\sin^2 B+\sin^2 (A+B)=2(\cos^2A+\cos ^2 B+\cos^2(A+B))$$
You have to know simple formulas of trigonometry to finish.
EDITION.-Sorry, dear friend, your problem is not as simple as I had thought. But you can stay in the same direction as suggested. This way you get both $$\sin^2 A+\sin^2 B+\sin^2 (A+B) = 2\qquad (*)$$ and the similar with cosines what gives $1$ instead of $2$. Taking $(*)$ you can try to prove this equality is verified if and only if when $A + B =\dfrac{\pi}{2}$ (the "if" is obvious and we need the "only if"). So put $A + B = \dfrac{\pi}{2}\pm h$ with $h\ne 0$ and look at the functions
$$\sin^2(x)+\sin^2(\dfrac{\pi}{2}\pm h-x)+\sin^2(\dfrac{\pi}{2}\pm h),\quad0\lt x\lt\dfrac{\pi}{2}$$ which becomes for $h$ positive and $h$ negative respectively $$f_1(x)=\sin^2(x)+\cos^2(x-h)+\cos^2(h)\qquad (1)\\f_2(x)=\sin^2(x)+\cos^2(x+h)+\cos^2(h)\qquad (2)$$ Now you can prove that $$\begin{equation}f_1(x)\begin{cases}\lt2\text{ when } 0\lt x\lt h\\=2 \text { when }x=h \space\text {discarded because } B\ne\dfrac{\pi}{2} \\\gt 2\text { when }h\lt x\lt\dfrac{\pi}{2}\\ \end{cases}\end{equation}$$
and that $f_2(x)$ is   smaller than $2$ on $0\lt x\lt \dfrac{\pi}{2}$.
This requires elementary calculus that I guess you know how to handle.
Comment: I can't get it please elaborate.
Comment: Look at my edition later,please, where I reply your comment. Regards.
Answer: \begin{align}
\frac{\sin^2 A + \sin^2 B + \sin^2 C}{\cos^2 A + \cos^2 B + \cos^2 C}
&=2
.
\end{align}
There are known identities
for any $\triangle ABC$
with sides $a,b,c$, angles $A,B,C$
radius of inscribed circle $r$,
radius of circumscribed circle $R$
and semiperimeter $\rho=\tfrac12(a+b+c)$:
\begin{align}
a^2+b^2+c^2
&=
2\rho^2-8r\,R-2r^2
,\\
\cos A \cos B \cos C
&=\frac{\rho^2-(r+2R)^2}{4R^2}
.
\end{align}
\begin{align}
{\sin^2 A + \sin^2 B + \sin^2 C}
&=2(\cos^2 A + \cos^2 B + \cos^2 C)
,\\
{\sin^2 A + \sin^2 B + \sin^2 C}
&=2(1-\sin^2 A + 1-\sin^2 B + 1-\sin^2 C)
,\\
3(\sin^2 A + \sin^2 B + \sin^2 C)
&=6
,\\
\sin^2 A + \sin^2 B + \sin^2 C
&=2
,\\
4R^2\sin^2 A + 4R^2\sin^2 B + 4R^2\sin^2 C
&=2\cdot4R^2
,\\
a^2+b^2+c^2&=8R^2
,\\
2\rho^2-8r\,R-2r^2&=8R^2
,\\
\rho^2-(r+2R)^2&=0
,\\
\frac{\rho^2-(r+2R)^2}{4R^2}
=0
.
\end{align}
And since
\begin{align}
\cos A \cos B \cos C
&=\frac{\rho^2-(r+2R)^2}{4R^2}
,
\end{align}
one of
$\cos A,\cos B,\cos C$
must be 0,
hence, one of the angles must be $\tfrac\pi2$.
Answer: I know I am coming two years late, but I happened to find a rather nice geometric solution to this problem, so I am putting it here.
First off, reduce the problem to the more "user-friendly" equivalent
$$\Sigma \sin^2 A = 2$$
Using the law of sines, this becomes
$$a^2 + b^2 + c^2 = 8R^2$$
where $R$ is the circumradius of the triangle. By comparing this second equation to the law of cosines, we get
$$c^2 + 2ab \cos C = 4R^2$$
Since $c^2 \le 4R^2$, this means that the triangle must be acute. (This step may not actually be required -- I haven't checked.)
Now we perform the usual trick: inscribe $\triangle ABC$ in a circle of radius $\frac{1}{2}$ (this is purely for bookkeeping purposes -- the argument would be quite similar without this step), so that the statement becomes
$$AB^2 + BC^2 + CA^2 = 2$$
Now let (WLOG) $AB \ge$ other two sides.
Unfortunately, I am not fully familiar with methods of including diagrams, so this is going to be a little painful. Anyway, put $C'$ on the circle so that $CC'$ is a diameter (then, since $\triangle ABC$ is acute, $C'$ and $C$ will lie on opposite sides of $AB$).
Then we get a Pythagorean relation free (recall that the diameter is 1):
$$BC^2 + CC'^2 + C'B^2 = 2$$
$$\implies AB^2 + CA^2 = CC'^2 + C'B^2$$
But since $CC'^2 = CA^2 + AC'^2$, this becomes
$$AB^2 = AC'^2 + C'B^2$$
This is Pythagoras again, so $\angle AC'B = 90$, and since the quadrilateral $ACBC'$ is cyclic, that leads us straight to $\angle ACB = 90$ as desired.


In a multi-server environment, if a site has inactivity for more than 15 mn, the server loses connection to PostgreSQL database

Question: I get the following errors in airbrake if my staging (2 servers) or production (4 servers) servers have no activity for about 15 minutes. Here are the error messages:

ActiveRecord::StatementInvalid: PG::Error: could not receive data from
  server: Connection timed out

OR

PG::Error: could not connect to server: Connection timed out Is the
  server running on host "tci-db4.dev.prod" and accepting TCP/IP
  connections on port 5432?

I'm using PostgreSQL as my database. One of the servers also acts as the db server.
Environment:
Ruby 1.9.3 (This also happened under Ruby 1.8.7, but it is worse since upgrading since the ruby process on the server will go to 100% and stay at 100% until is killed when the server loses the db connection.
Rails 3.1.6
PG GEM 0.13.2
Postgres 9.1
Phusion Passenger
This problem has been happening for over a year, so I'm hoping someone has some insight on how to fix it. Thanks.
Comment: IS there anything unusual about your connection to PostgreSQL? Is it directly encrypted with SSL or going through an SSH or SSL tunnel?
Comment: No it is not going through SSH or SSL.
Comment: Is there a firewall in between? ;)
Answer: Check your TCP/IP socket timeout settings on all routers/switches between the application servers and the database servers.  Also turn on logging on the database side and watch the full life cycle of the connection and compare the timing to the errors in your application.  I suggest turning on the following settings in postgresql.conf until you get an idea of what to look for:
<code>log_connections = on
log_disconnections = on
log_statement = all
</code>
These can be activated with a SIGHUP of the postgres process (or run "SELECT pg_reload_conf();" as a database superuser.
I'll be that you have a "connection closed by remote host" or something similar as the last message before the actual disconnect is logged.
I've seen this before and it was the timeout settings on an intermediate switch causing it.
Answer: Maintaining a lot of keepalived connections from 4 application servers may be quite hard to do (it may represent a very high number of connections. You may check PgPool-II to maitain a reasonnable number of keepalived connections between pgpool and your postgres server. pgPool will also queue connection when too much process ask for a connection. After that check how the connections are managed in your application. Is there a pool of connections managed in the app server? Do you still need it? Do you have a need for long-standing connections or can you simply use short sessions connections?
If you still have disconnected sessions between PgPool and your postgreSQl server you will have to check for TCP/IP problems. Such problems can come from the OS TCP/IP settings, but can also be tweaked in postgreSQl configuration. Check for tcp_keepalive settings on that runtime configuration manual page. if you use pgpool, check for health_check settings.
Answer: You probably have a NAT router, connection tracking firewall, or an uppity "layer 3 switch" between the client and the server. These devices flush remembered connections from their tables after a timeout. You will need to enable keepalives.


Does MySQL 5.0 do IPv6 well?

Question: I'm using
mongrel + apache 2.2 + mod_proxy_balancer + mysql
apache2.2 is IPv6 well
http://httpd.apache.org/docs/2.2/en/bind.html#ipv6
Does MySQL 5.0 do IPv6 well?
Answer: MySQL did not gain full IPv6 support until version 5.5.3.
Answer: it looks like it may be a work in progress still. there's a bunch of patches and bug reports for "mysql ipv6" on Google.
on the plus side, you probably DONT want your MySQL DB exposed to the internet, so you could keep it on IPv4/localhost or use sockets.

Does MySQL 5.0 do IPv6 well?


Let $\int_0^2 f\left(x\right) dx = a+\frac{b}{\log 2}$. Find $a,b$

Question: Let $f$ be a real-valued continuous function on $\mathbb{R}$ such that $2^{f\left(x\right)}+f\left(x\right)=x+1$ for all $x\in \mathbb{R}$. Assume that $\int_0^2 f\left(x\right) dx = a+\dfrac{b}{\log 2}$ with $a,b$ are rational numbers . Find $a,b$.

I have no idea how to use the assumption $2^{f\left(x\right)}+f\left(x\right)=x+1$ for all $x\in \mathbb{R}$ except taking integral of the both sides:
$$\int_0^2 2^{f\left(x\right)}+f\left(x\right) dx=4 $$
Please help me an idea. Thank you.
Comment: Is $ f $ differentiable. if yes multiply by $ f'(x) $ and integrate.
Answer: The function $y+2^y$ is one-to-one (because of its strict monotonicity). Notice that
$$2^0 + 0 = 0 + 1$$
$$2^1 + 1 = 2 + 1$$
just by guessing, and the one-to-one property makes these solutions unique. Thus geometrically we have that:
$$\int_0^2 f(x)\:dx + \int_0^1f^{-1}(y)\:dy = 2\cdot 1 - 0\cdot 0 = 2$$
a rectangle of area $2$ minus a rectangle of area $0$ (with $x=f^{-1}(y) = 2^y+y-1$). Therefore the desired integral is given by
$$\int_0^2f(x)\:dx = 2-\int_0^12^y+y-1\:dy = 2-\left(\frac{2-1}{\log 2}+\frac{1}{2}-1\right) = \frac{5}{2}-\frac{1}{\log 2}$$
Comment: Thank you. I got it.
Answer: Let $\alpha = \log 2$, differenital $x + 1 = 2^f + f$ on both sides, we get
$$\begin{align}
1 &= (\alpha 2^f + 1)f'
= (\alpha(x + 1 - f) + 1)f'\\
&= \left[\alpha\left((x + 1)f - \frac{f^2}{2}\right) + f\right]' - \alpha f\\
\implies \alpha f &= \left[\alpha\left((x + 1)f - \frac{f^2}{2}\right) + f - x\right]'
\end{align}
$$
Integrate both sides for $x$ over $[0,2]$ and notice $f(0) = 0$ and $f(2) = 1$, we get
$$\begin{align}
\alpha\int_0^2 f dx
&= \left[\alpha\left((2 + 1)1 - \frac{1^2}{2}\right) + 1 - 2\right]
- \left[\alpha\left((0 + 1)0 - \frac{0^2}{2}\right) + 0 - 0\right]\\
&= \alpha\frac52 - 1
\end{align}
$$
This means $\displaystyle\;\int_0^2 fdx = \frac52 - \frac1{\log 2}$
Comment: If $f$ is differentiable.
Comment: @Vichakh $f$ is an implicit function defined by $F(x,f(x)) = 0 $ where $F(x,y) = 2^y + y - x - 1$. Since $\frac{\partial F(x,y)}{\partial y} = \alpha 2^y + 1 \ne 0$ for all $y$, you can apply [implicit function theorem](https://en.wikipedia.org/wiki/Implicit_function_theorem) to show $f$ is a unique solution of some initial value ODE problem and hence differentiable. Look at section
[Proof of 2D case](https://en.wikipedia.org/wiki/Implicit_function_theorem#Proof_for_2D_case) in above wiki.
Answer: My solution is here :
I hope this will help you!
(https://i.stack.imgur.com/uCEc3.jpg)
Comment: Thank you but we don't know if $f$ is differentiable or not.


Trigger views exposed filter on custom select box

Question: I have this view which contains an exposed filter to filter out a simple content type listing page.
The problem is about theming and keeping the view functional.
I succeeded in theming the view with a select filter, as provided to me in a static html file.
The filter is select box but the theming have it's proper tags that works similar to a select box model.
For example:
<code><!-- Basic select box in Drupal -->
<select data-drupal-selector="edit-filterone" id="edit-filterone" name="filterone" class="form-select">
  <option value="All" selected="selected">- Any -</option>
  <option value="13">term 1</option>
  <option value="15">term 2</option>
  <option value="16">term 3</option>
</select>

<!-- Our themer select box model -->
<custom-select label="Filter label" name="filterone">
  <custom-option label="- Any -" name="filterone" value="All" selected></custom-option>
  <custom-option label="term 1" name="filterone" value="13"></custom-option>
  <custom-option label="term 2" name="filterone" value="15"></custom-option>
  <custom-option label="term 3" name="filterone" value="16"></custom-option>
</custom-select>
</code>
Then the value selected get stored in a JS object.
In this view I use BEF (Better exposed forms) module and autosubmit is activated with a hidden apply button.
Using twig suggestions I can populate the select list with the filter values but there is no action trigged when I change the item.
The view is not applied and it act just like a static html. I need a way to keep the filter functional as normal.
I can get the values with js when a select list change but I don't know (or have a clue) how to send these values by ajax and alter the view and get back the results as normal views do.
My first thought is to keep the select boxes provided by drupal and just hide them from display and when the user changes value in the 'fake' select box, have them copied to the hidden one; and then just trigger the click on the (hidden) apply button.
Any suggestions please?
(I don't know if my explication is that clear but I can be more specific if needed, thank you)
Answer: I managed to achieve that result I had thought of. Adding same filter in hidden display and just assign new values to it when the fake select box changed; then trigger the apply button.
I had little problems with 'all' value because I was parsing the selected values before reassign them.


How does rsync --daemon know which way it is being run?

Question: I am wanting to run rsync over an SSL/TLS encrypted connection.  It does not do this directly so I am exploring options.  The stunnel program looks promising, although more complicated than designed due to the need to hop connections with the -r option.  However, I do find there is a -l option to run a program.  I am assuming this works by having two processes, one to carry out the SSL/TLS work, and one to be the worker which the client is communicating to.  These would then communicate by a pipe pair or two way socket between them.
What struck me as odd when I surveyed a number of web pages to see how to properly set this up is that whether running as a standalone daemon, or under a super daemon like inetd, the arguments for rsync are the same.  How does rsync --daemon know whether it should open a socket and listen on it for many connections, or just service one connection by communicating with the stdin/stdout descriptors is has when it starts up (which really would go through the extra process to handle the encryption, description, and SSL/TLS protocol layer)?
And then I need to find a way to wrap the client to have it do SSL/TLS in one simple command (as opposed to connection hopping that stunnel seems to favor).
Answer:
And then I need to find a way to wrap the client to have it do SSL/TLS in one simple command (as opposed to connection hopping that stunnel seems to favor).

rsync has an --rsh option to spawn stunnel and use stdin/stdout on the client side and stunnel has an exec option to spawn rsync on the server side - combining these two will get you what you want. See dozzie's rsync over SSL for some further information and readily available scripts to run this config (needs git to download).
Comment: OK, I think I have figured it out, now.  But the rsync-ssl-stunnel.sh script is making incomplete or incorrect assumptions about the arguments it gets from the rsync --rsh or -e option that references it.  I'll try some rewriting to see what I come up with.
Comment: If rsync is not getting the network socket, how does it know NOT to do its own network listen accept loop?  Or does it do this because stdin is a pipe?
Comment: @Skaperen Honestly, I don't know and never bothered to look it up in the source. I suppose you are right and the detection is based on something like [isatty](http://linux.die.net/man/3/isatty).
Comment: I cannot find the author's email address.  Some things are left out and/or not explained.  How do run stunnel in inetd-mode as a client (e.g. as an ssh substitute) is missing how to make it connect (not seen in stunnel man pages).
Comment: I think I need to ask this question in an entirely different way.
Comment: @Skaperen take a look at the rsync-ssl-package's scripts (as I wrote you would need `git` to download the code set), a whole lot should become clear then.
Comment: Sorry, a whole lot was not clear (I downloaded it).  Two scripts and they look like one calls the other.  It's not even clear what is for client and what is for server.  I can understand that one script would invoke something with the other script being referenced to run something in a certain way.  I'd expect 4 scripts, a pair to launch the server, and a pair to run the client (to access the server).  Or am I expecting too much?
Comment: Technically, the answer by Wil Tan was the answer to the question I asked, so I'm checking that as the answer.  However, this answer has good information (I'm just not sure, yet, how to use it).
Comment: @Skaperen the two shell scripts you mention are used as the client call - the main purpose of `rsync-ssl-stunnel.sh` is to parametrize certificate-based auth for the SSL connection. The config files `stunnel.conf` and `rsyncd.conf` are intended to reside on the server side (after modifications to match your environment). Running `stunnel` as a daemon to listen for connections at the server side and `rsync-ssl.sh` to invoke a transfer from the client side should provide you with the config you've asked for.
Comment: So what keeps the rsync --daemon from listening on port 873 for unencrypted connections?
Answer: From the section on --daemon in the rsync(1) man page:

If standard input is a socket then rsync will assume that it is being run via inetd, otherwise it will detach from the current terminal and become a background daemon.

You can see the command line arguments that apply to daemon mode by running:
rsync --daemon --help

Comment: So does this mean rsync won't work under stunnel -l since under that it would get a pipe, instead?
Comment: Maybe it will handle a pipe like a socket (they are similar).


How to check whether or not two regression curves from different datasets are different in R

Question: Here is an example code:
set.seed(3)

data1 = iris[sample(c(1:dim(iris)[1]), 30), ]
data2 = iris[sample(c(1:dim(iris)[1]), 50), ]

model1 = lm(Petal.Length ~ log(Petal.Width),
            data = data1)
model2 = lm(data2$Petal.Length ~ log(data2$Petal.Width))

par(mfrow = c(1, 4))
plot(data1$Petal.Width,
     data1$Petal.Length)
points(sort(data1$Petal.Width),
       predict(model1, newdata = data1[order(data1$Petal.Width), ]),
       col = "red",
       type = "l")

plot(data2$Petal.Width,
     data2$Petal.Length)
points(sort(data2$Petal.Width),
       predict(model1, newdata = data2[order(data2$Petal.Width), ]),
       col = "red",
       type = "l")

summary(model1)
summary(model2)

As in the code, I fitted two different curves from two different datasets using the simple regression method in which the explanatory variable is in logarithm form. Like in the code, the datasets have the same variables with different size.
I want to check that the two curves (model1 and model2) are statistically different or not.
How can I do it in R?
---- edited ----
I know that there are many questions about comparing regression lines, but my case is a different one from previous ones because I want to compare different models built from different data sets while other cases are to compare different models built from the same data set.
Let me state more about the context of my purpose to elaborate on the term "compare."
I made a model (the curve) for an experimental site and want to apply this model to many other sites (over the country). I acknowledge that it would not proper to apply the model to other sites where the model is not based on (the resulted curve of another site may be different from the previous one). So, I made one more curve for another study site and trying to compare the two models built from different sites.
This is why the two data sets have the same variable list. And the common points of the two data sets in the example can be ignored in term of my purpose.
Thank you!
Comment: This actually isn't a duplicate--it's a totally bizarre situation in which the same model is being fit to different data, rather than different models to the same data (where you can just do anova). I've been thinking about how to answer it, but I think it was closed prematurely.
Comment: You still have lines -- in log-petal-width. The previous posts you refer to that are about comparing lines apply directly.
Comment: @Glen_b Thank you for your reply. Can you provide example posts that are suitable for my case? What I found were all about comparing method applicable for the model fitting phase or for models from the same size of data sets.
Comment: Assuming comparison of curves means comparing the models (i.e. the Null would be all coefficients are statistically same), use [chow.test](https://www.rdocumentation.org/packages/gap/versions/1.2.1/topics/chow.test) in R. Only thing is that since you are taking sample from a dataset, there will be common data points. These data points will be repeated in the combined regression. This may give undue weight to these points. To handle this you can find out common set of data points in data1 and data2 and remove them from one of the dataset (say data1) and then use chow.test.
Comment: What about building a confidence interval for each estimation and check if the other estimation fits in it?
Comment: @SheridanGrant: You are right in pointing out that the question isn't exactly the duplicate. However, the situation here is not very different from anova. Chow test can be used here, which is essentially a form of anova (basically an F test) only.
Comment: Only difference here is that the common points need to be emitted from one of the datasets. Otherwise there would be an artificial equivalence between the two models due to common points and it's possible that Null may not be rejected when it should ideally be.
Comment: Right--which changes the problem, since you have to refit the model once you ensure the data sets don't overlap. Even then, the "already answered" question makes no mention of the Chow test. I would love to know what scientific problem, if any, led @HoonTaek to this question... I dunno how to get the mods to reopen this though.
Comment: I appreciate every reply. I have edited my question, which may lead to reopen the discussion.
Comment: @HoonTaek I think no overlapping in data makes it simpler. Just use Chow Test. It is specifically designed for this purpose only.
Comment: @Dayne Thank you for your answer. It is easy and seems suitable for my case.
Comment: Glad I can be help.
Answer: Your case is that of comparing two models with same variables but different set of data points. You can use chow.test from library gap. However, as mentioned in my comment above, you need to remove common data points from one of the data frames. Following is the code for this (and also the result I obtained):
set.seed(3)
data1 = iris[sample(c(1:dim(iris)[1]), 30), ]
data2 = iris[sample(c(1:dim(iris)[1]), 50), ]

data1_sno=as.numeric(rownames(data1))
data2_sno=as.numeric(rownames(data2))

# next line tells you which of the data points in data2 are also in data1.
new_index=data2_sno %in% data1_sno
data2_new=data2[!new_index,]
gap::chow.test(y1=data1$Petal.Length,x1=log(data1$Petal.Width),
           y2=data2_new$Petal.Length,x2=log(data2_new$Petal.Width))

   F value      d.f.1      d.f.2    P value
 0.8257495  2.0000000 64.0000000  0.4425175

So the null could not be rejected, i.e. it cannot be said that the curves are indeed different.
Answer: Why do a statistical test of this? Any test will have the usual problems of p values - that is, the result will depend partly on sample size.
When you have two data sets, you know that the same line doesn't fit both equally well (except perhaps for some constructed data sets and some very small data sets). So, graph both and look at them.
Are they different?
Then look at the predictions that each makes from the same IVs. Are they different?
And, by "different" I mean "different enough to matter to anyone".
Comment: Thank you for your reply. Surely, they will be likely to differ from each other. I think that you replied like this because I provided little information on the term "different."


Minimum of random exponential variable and time

Question: Let $U$ and $V$ be $\sim\mathrm{Exp}(\lambda)$.
Let $s \in [0, t)$.
Does this reasoning from left to hold:
$P(U + (V \wedge t) \leq s) = P(U + V \leq s; V < t) $ or is in this case enough to write (as our tutor did)
$P(U + V \leq s)$.
I do not think that the latter is correct, since random variable $V$ is defined on $(0,\infty)$.
Thanks in advance!
Comment: What does $\Longrightarrow$ mean in this context?
Comment: And what does $(V \mbox{ min }  t)$ mean?
Comment: Perhaps you mean $\{U + V \leq s \} \cap \{V < t\} \subseteq \{U + \min[V,t] \leq s\}$, which is true.  But then I do not see a question in what you write.
Comment: I have edited my question. $(V \min t)$ was supposed to be $\min(V,t)$
Answer: I'm going to hazard a guess that where you wrote $P(U + (V \min t) \leq s) \implies P(U + V \leq s; V < t)$, you meant "$=$".
If the two probabilities are indeed equal, it seems likely that it's because the two events $[U+\min\{V,t\}\le s]$ and $[U+V\le s\ \&\ V<t]$ are equal, or at least differ by an event whose probability is $0$.
There are two cases to consider:
$$
\begin{cases}
\cdots\cdots & \text{if }V<t, \\
\cdots\cdots & \text{if }V>t.
\end{cases}
$$
(We need not consider $V=t$ since the probability of that is $0$.)
$$
[U + \min\{V,t\}\le s] = \begin{cases} [U+V\le s] & \text{if }V<t, \\[6pt] [U + t \le s] & \text{if }V>t. \end{cases}
$$
But we have not yet used the fact that $s<t$, which was given at the outset.  Since $U>0$, the event $[U+t\le s]$ is impossible.  Hence if $V>t$, then the event whose probability we seek cannot happen.  Therefore it is equivalent to $[U+V\le s\ \&\ V<t]$.
Comment: I completely understand the explanation above for which I am really thankful. So the answer $[U + V \leq s]$ is in this case not correct?
Comment: Actually $[U+V\le s]$ would imply that $V<t$, so that appears to be correct. ${}\qquad{}$
Comment: If we would like to calculate the exact probability, are we integrating over the same area in both cases?
Comment: Yes.  (Except for possible boundaries whose measure is $0$, and those won't affect the value of the integral.) ${}\qquad{}$


How to show $1 +x + x^2/2! + \dots+ x^{2n}/(2n)!$ is positive for $x\in\Bbb{R}$?

Question:
How to show $1 + x + \frac{x^2}{2!} + \dots+ \frac{x^{2n}}{(2n)!}$ is positive for $x\in\Bbb{R}$?

I realize that it's a part of the Taylor Series expansion of $e^x$ but can't proceed with this knowledge? Also, I can't figure out the significance of $2n$ being the highest power.
Comment: If the degree is odd, the property is impossible as the leading term always dominates.
Comment: Try proving that it's always larger than $e^x$ for $x<0$
Comment: Have you tried multiplying $f(x)$ by $f(-x)$?
Answer: By induction, assume that
$$f_{2n}(x)=1+x+\frac{x^2}2+\cdots\frac{x^{2n}}{(2n)!}>0.$$
Then the antiderivative
$$f_{2n+1}(x)=1+x+\frac{x^2}2+\cdots\frac{x^{2n+1}}{(2n+1)!}$$ is a growing function and has a single root.
Then the antiderivative
$$f_{2n+2}(x)=1+x+\frac{x^2}2+\cdots\frac{x^{2n+2}}{(2n+2)!}$$ has a single minimum, which occurs at this root, let $r$.
The value at the minimum is easy to compute as
$$f_{2n+2}(r)=f_{2n+1}(r)+\frac{r^{2n+2}}{(2n+2)!}=0+\frac{r^{2n+2}}{(2n+2)!},$$
which is a positive number.
Answer: If we use Taylor's theorem with an integral remainder we get:
$$ 1+x+\frac{x}{2}+\ldots+\frac{x^{2n}}{(2n)!} = e^x-\frac{1}{(2n)!}\int_{0}^{x}t^{2n}e^{x-t}\,dt \tag{1}$$
hence in order to prove the non-negativity of the LHS it is enough to show that:
$$ \int_{0}^{x} t^{2n}e^{-t}\,dt \leq (2n)! \tag{2}$$
holds for any $x\in\mathbb{R}$. $(2)$ is trivial if $x\leq 0$, and if we assume $x>0$, since the integrand function is non-negative, we get:
$$ \int_{0}^{x}t^{2n}e^{-t}\,dt \leq \int_{0}^{+\infty}t^{2n}e^{-t}\,dt = \Gamma(2n+1)=(2n)!,\tag{3}$$
proving our claim.
Answer: Let $P_n(x)$ your polynomial. The Taylor-Lagrange formula gives for $x\in \mathbb{R}$ that there exists $c$ such that $\exp(x)=P_n(x)+\frac{x^{2n+1}}{(2n+1)!}\exp(c)$ for some $c$ depending on $x$. Now suppose that there exists $x\in \mathbb{R}$ such that $P_n(x)=0$. Obviously, we have $x<0$. Then $\exp(x)=\frac{x^{2n+1}}{(2n+1)!}\exp(c)$, and $\exp(x-c)=\frac{x^{2n+1}}{(2n+1)!}<0$, a contradiction. Hence $P_n(x)$ is never zero, and as a continuous function, it has a constant sign. As $P_n(0)=1$, we are done.


Aggregating coefficients in a meta-analysis

Question: I have a question about the treatment of data in a meta-analysis.
It is quite common in this particular field for researchers to essentially use data twice for analysis: once as a normal bivariate correlation between variable A and B and then again in a multiple-regression context where they model the relationship between A and B as a quadratic function, while also including a couple of other predictors. Theoretically it makes more sense to treat the relationship as non-linear, but some researchers treat the relationship as linear, while others treat it as non-linear, while some even just report both, as mentioned above.
What is the most appropriate way of dealing with this situation? Can I just aggregate the unstandardized coefficients, regardless of how the researchers treated the relationship?
Answer: If you are combining coefficients, you want those coefficients to be estimating, as far as possible, the same thing. If one study controls for some covariates, and another study does not, then it's possible that they are estimating very different effects. The relationship between height and weight in children, for example, is different to the relationship between height and weight in children, controlling for age.
Sometimes you might consider different sets of covariates to be attempts to estimate the same thing - but different covariates were relevant, or one study attempted to estimate an effect using a randomized trial, and a second attempted to use propensity scores.
The heterogeneity statistic might be useful if you do decide to combine studies, as might the use of study level moderators.
Comment: Thanks guys. I figured entering highly correlated outcomes separately can potentially wreck havoc on the summary effect size and bias estimates, hence my question about aggregating them. Seems like I'm stuck between a rock and a hard place here.
Answer: The main problem I foresee here apart from the issues of the comparability of the other covariates which Jeremy Miles has outlined in another answer is combining the linear and quadratic coefficients simultaneously. To do this you will need a multivariate meta-analysis which is not the main problem as that is available in standard statistical software like R and Stata. However you will also need the variance-covariance matrix of the coefficients (or at least the covariance for the linear and quadratic coefficients) and I suspect this will not have been published.


What do the symbols d/dx and dy/dx mean?

Question: Okay this may sound stupid but I need a little help...
What do $\Large \frac{d}{dx}$ and $\Large \frac{dy}{dx}$ mean?
I need a thorough explanation. Thanks.
Comment: This is not precalculus, it is calculus. These symbols are derivatives. Are you familiar with derivatives?\
Answer: The symbol
$$
\frac{dy}{dx}
$$
means the derivative of $y$ with respect to $x$. If $y = f(x)$ is a function of $x$, then the symbol is defined as
$$
\frac{dy}{dx} = \lim_{h\to 0}\frac{f(x+h) - f(x)}{h}.
$$
and this is is (again) called the derivative of $y$ or the derivative of $f$. Note that it again is a function of $x$ in this case. Note that we do not here define this as $dy$ divided by $dx$. On their own $dy$ and $dx$ don't have any meaning (here). We take $\frac{dy}{dx}$ as a symbol on its own that can't be slit up into parts.
The symbol
$$
\frac{d}{dx}
$$
you can consider as an operator. You can apply this operator to a (differentiable) function. And you get a new function. So if $f$ is a (differentiable) function that it makes sense to "apply" $\frac{d}{dx}$ to $f$ and write
$$
\frac{d}{dx}f
$$
If you write $y = f(x)$, then this is the same as
$$
\frac{d}{dx}y = \frac{dy}{dx}.
$$
Comment: The confusion often arises from the fact that many writers call $dy/dx$ a "symbol" as if it were atomic, but then later start doing algebra with it.  This leads to the question, "well, then what is $dy$ really?"
Comment: @Fixee: That is right. I often see this confusion which is why I always emphasize that $\frac{dy}{dx}$ is just a symbol. It is not a fraction.
Comment: @Thomas It's _kinda_ a fraction. It's the limit of a fraction.
Comment: (Or the "standard part" of a fraction, if you're doing nonstandard analysis...)
Comment: @Fixee See my answer. It is nevertheless CAN be defined as a fraction of two functions, rather than an atomic object.
Answer: $\frac{d}{dx}$ means differentiate with respect to $x$.
$\frac{dy}{dx}$ means differentiate $y$ with respect to $x$.
Do you have any concrete examples for which you need to calculate these two? It would probably make it more easy to grasp for you if I could explain it in a few examples.
Comment: Maybe calculating the flow rate of a tap based on how the container gets filled?
Answer: $d f$ means the differential of function $f$. By definition $(df)(x) = \lambda t\in\mathbb{R}:f'(x)\cdot t$. In other words, differential is the linear function (of an additional variable denoted $t$ here) whose tangent is the derivative of $f$.
$d$ alone means the differential operator (a function of argument $f$).
Exercise: Show that $\frac{df}{dx}=f'$.
Comment: Note that $\frac{F}{G}$ is defined for two functions $F$ and $G$ as $\frac{F}{G}(x)=\frac{F(x)}{G(x)}$. Thus $\frac{df}{dx}$ makes sense.
Comment: It is described in http://en.wikipedia.org/wiki/Differential_of_a_function
Answer: I like to look at it this way: $dx$ and $dy$ are just representations of change in accordance to either $x$ or $y$ axis.
If you take the the symbol for derivative $$\frac{dy}{dx}$$ and compare it to the formula for the slope: $$\frac{f(x_1) - f(x_2)}{x_1 - x_2}$$ we can clearly see that $dy$ and $dx$ depict change in $y$ and change in $x$ respectively.
Answer: If $y=f(x)$ i.e., where $y$ is the equation ( the dependent variable) and $x$ is the independent variable. Meaning $x$ changes $y$.
Now $\frac{dy}{dx}$ means differentiate the equation $y$ in respect to $x$.
$\frac{d}{dx}$ means differentiate in respect to $x$.
Same way $\log x$ means find the natural logarithm of $x$, $\frac{d}{dx} x$  means find the derivative of $x$.
N.B. In an equation $k= h²+5 $,
$\frac{dk}{dh}$ means differentiate the equation $k$ in respect to $h$. Its not always $\frac{dy}{dx}$.
I hope you understand
Comment: **Welcome to Mathematics Stack Exchange!** A quick [tour](https://math.stackexchange.com/tour) will enhance your experience. Here are helpful tips to [write a good question](https://math.meta.stackexchange.com/questions/9959/how-to-ask-a-good-question/9960#9960) and [write a good answer](https://stackoverflow.com/help/how-to-answer). For equations, use [MathJax](https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference).
Comment: See the answer given by Thomas


How to pass data back to the caller from the clickOnce applicationw

Question: I have an online ClickOnce application that launches from a web page. After the application is closed, I would like the user to return information to the page. Is this possible?
I haven't found anything online. Any tips? Something that could lead me in the right direct.
Answer: Can you just put an an action in the application's FormClose event?  If you know the application is only run from the ClickOnce webpage you could simply launch a web page on the application's FormClose event.
Launch on Form Close
Open a URL from Windows Forms


Trouble with bowling

Question: I am a medium fast bowler and was able to bowl with good line and length with some swing but due to gap in playing cricket I am not able to bowl and all of my balls are either going above the head of batsman or they are pitching short.
Not getting the reason for this? what am I missing? please help me to rectify the problem.
Comment: Nice question. Training in Cricket questions are [very rare](http://sports.stackexchange.com/questions/tagged/cricket+training).
Answer: For most players (specially non professional) this happens when they don't play cricket for some times. That's why professional players keep practising on off-days as well. The main reason is lack of confidence in throwing and losing the grip on the ball. Either they think they will bowl full toss or very short deliveries. That's why they bowl either very short or full toss respectively. To get back your confidence you may try this:

Start practising with throwing the ball to a good length area on the wicket without any run-up or moving your hand round (i.e. just normal throws). Don't care of the speed.
If you think you are able to throw in a good length area, try to grip the ball same as you do while bowling and keep throwing. Improve the speed upto your actual speed.
Now try to bowl the ball without run-up and maintain the speed. This is very important. If you are able to bowl in a good length area, you will able to bowl in the same area while bowing with run-up.
Now try to bowl with run-up. If you are not able to bowl in a good length, you may start with small run-up then improve it to your actual run-up.
You will probably be able to bowl in a good length with proper grip on the ball now.

Note: I am not a professional trainer. I too am not able to play regular cricket. And this is what I do when I lose my line, length and grip and mostly this works.

Trouble with bowling


Taxonomy & Views

Question: How can I take a "Content Type" with a "Taxonomy Term" field... and use views to generate a list of content with that term via URL?
I have a content type that has the basics (Title, Body) as well as Taxonomy Term for a Vocabulary & Weight. I want the user to be able to type:
http://myip.org/portals/safety

This would theoretically generate

HTML list of pages
"Menu" to be use in a block with a list of safety (or whatever) pages.

I can't seem to figure out where to get the taxonomy/term to work as variables in the View.
Views has the "Taxonomy Term" default view with
taxonomy/term/%
taxonomy/term/%/feed

I'd like to remove the /%,/%/feed and auto-magically make a taxonomy/term page/menu.
Answer: The key to views is to use the filter function to get the correct node relations out in the way you want. I had the same problem where I wanted a node of content type "application" with a taxonomy of "approved", "pending", and "denied". The view should get a with a filter of node: type = "applications", based on my example. That will find the right content. I added a base url of applications for the page view. The arguments section is where the taxonomy can be used to filter based on URL.
portals/safety
node type = safety
portals/safety/one
node type = safety
taxonomy: term = one
portals/safety/two
node type = safety
taxonomy: term = two
It might be easier if I just export the view and see if it helps point the way along.
$view = new view;
$view->name = 'Applications';
$view->description = 'List of all applications';
$view->tag = '';
$view->view_php = '';
$view->base_table = 'node';
$view->is_cacheable = FALSE;
$view->api_version = 2;
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */
$handler = $view->new_display('default', 'Application List', 'default');
$handler->override_option('fields', array(
  'title' => array(
    'label' => 'Application',
    'alter' => array(
      'alter_text' => 0,
      'text' => '',
      'make_link' => 0,
      'path' => '',
      'link_class' => '',
      'alt' => '',
      'prefix' => '',
      'suffix' => '',
      'target' => '',
      'help' => '',
      'trim' => 0,
      'max_length' => '',
      'word_boundary' => 1,
      'ellipsis' => 1,
      'html' => 0,
      'strip_tags' => 0,
    ),
    'empty' => '',
    'hide_empty' => 0,
    'empty_zero' => 0,
    'link_to_node' => 1,
    'exclude' => 0,
    'id' => 'title',
    'table' => 'node',
    'field' => 'title',
    'relationship' => 'none',
    'override' => array(
      'button' => 'Override',
    ),
  ),
  'name' => array(
    'id' => 'name',
    'table' => 'term_data',
    'field' => 'name',
  ),
));
$handler->override_option('arguments', array(
  'name' => array(
    'default_action' => 'ignore',
    'style_plugin' => 'default_summary',
    'style_options' => array(),
    'wildcard' => 'all',
    'wildcard_substitution' => 'All',
    'title' => '%1 Status Application',
    'breadcrumb' => 'Applications',
    'default_argument_type' => 'fixed',
    'default_argument' => '',
    'validate_type' => 'none',
    'validate_fail' => 'not found',
    'glossary' => 0,
    'limit' => '0',
    'case' => 'none',
    'path_case' => 'none',
    'transform_dash' => 0,
    'add_table' => 0,
    'require_value' => 0,
    'id' => 'name',
    'table' => 'term_data',
    'field' => 'name',
    'validate_user_argument_type' => 'uid',
    'validate_user_roles' => array(
      '2' => 0,
      '3' => 0,
      '4' => 0,
    ),
    'relationship' => 'none',
    'default_options_div_prefix' => '',
    'default_argument_fixed' => '',
    'default_argument_user' => 0,
    'default_argument_php' => '',
    'validate_argument_node_type' => array(
      'blog' => 0,
      'poll' => 0,
      'faq' => 0,
      'forum' => 0,
      'application' => 0,
      'page' => 0,
      'story' => 0,
    ),
    'validate_argument_node_access' => 0,
    'validate_argument_nid_type' => 'nid',
    'validate_argument_vocabulary' => array(
      '1' => 0,
      '2' => 0,
      '3' => 0,
      '4' => 0,
    ),
    'validate_argument_type' => 'tid',
    'validate_argument_transform' => 0,
    'validate_user_restrict_roles' => 0,
    'validate_argument_php' => '',
  ),
));
$handler->override_option('filters', array(
  'status' => array(
    'operator' => '=',
    'value' => '1',
    'group' => '0',
    'exposed' => FALSE,
    'expose' => array(
      'operator' => FALSE,
      'label' => '',
    ),
    'id' => 'status',
    'table' => 'node',
    'field' => 'status',
    'relationship' => 'none',
  ),
  'type' => array(
    'operator' => 'in',
    'value' => array(
      'application' => 'application',
    ),
    'group' => '0',
    'exposed' => FALSE,
    'expose' => array(
      'operator' => FALSE,
      'label' => '',
    ),
    'id' => 'type',
    'table' => 'node',
    'field' => 'type',
    'relationship' => 'none',
  ),
));
$handler->override_option('access', array(
  'type' => 'none',
));
$handler->override_option('cache', array(
  'type' => 'time',
  'results_lifespan' => '3600',
  'output_lifespan' => '3600',
));
$handler->override_option('title', 'Applications');
$handler->override_option('style_plugin', 'list');
$handler = $view->new_display('page', 'Page', 'page_1');
$handler->override_option('path', 'applications');
$handler->override_option('menu', array(
  'type' => 'tab',
  'title' => 'Applications',
  'description' => 'Applications',
  'weight' => '0',
  'name' => 'navigation',
));
$handler->override_option('tab_options', array(
  'type' => 'none',
  'title' => '',
  'description' => '',
  'weight' => 0,
  'name' => 'navigation',
));
$handler = $view->new_display('block', 'Block', 'block_1');
$handler->override_option('block_description', 'Applications');
$handler->override_option('block_caching', -1);

Comment: I've adjusted this to my "Portals"... and in the test area, when using "safety" contextual it works. The three pages I have as safety pages show up in a list... but when I go to myip.org/portals/safety it just shows a blank page.
Comment: Not sure what I changed... but i got it working! vonderball... follow-up question coming shortly.
Comment: The issue I have atm... is the page version works, but it doesn't work as a block.
Comment: It wouldn't work in blocks because contextual filters rely on the page URL.

Taxonomy & Views


why my print doesn't work?

Question: In this below program i am printing the contents of the div when i click the print button i am receiving an alert message printer error not available why it is so

    This will be printed. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque a quam at nibh adipiscing interdum. Nulla vitae accumsan ante.

<input type="button" value="Print Div" onclick="PrintElem('#mydiv')" />

Answer: Because your physical printer is not physically plugged in or not correctly installed. The code is not wrong.

why my print doesn't work?


Where can I find jQuery or Ext plugins for creating organization charts?

Question: I know we can create an organization chart with Google Chart Tools.
But my client's server doesn't have an Internet connection.
Are there any jQuery or Ext plugins for creating an organization chart?
Answer: I have successfully used JavaScript InfoVis Toolkit to create a graph that looks very similar to that.  As implied by the name, it is only Javascript and you can host it internally.  Since it is very customizable, there is a bit of a learning curve to getting your data in the correct format and the interface the way you'd like.  Look at this demo for a tree-like structure which could be used for an organization.
Comment: This is the answer, tsurahman.  InfoVis looks nice!
Comment: best JS visualization library, hands down
Comment: jit is so heavy though. is it possible to lode the code just for that org chart piece?
Comment: @jellyfishtree - it is certainly possible, but also highly impractical
Answer: Yeah, there is. See http://thejit.org/static/v20/Jit/Examples/Spacetree/example2.html
Answer: jQuery OrgChart is a plugin that allows you to render structures with nested elements in a easy-to-read tree structure:

You can view a demo of this here: http://dl.dropbox.com/u/4151695/html/jOrgChart/example/example.html
you can view the github repository here: https://github.com/wesnolte/jOrgChart
Answer: Seriously.. the JavaScript InfoVis Toolkit is superb. Just extend as necessary
Answer: I have forked jOrgChart for the Ext JS users and created ExtJSOrgChart. Please check it out and provide your feedback.
https://github.com/shaikhmshariq/ExtJSOrgChart
Answer: I like http://www.highcharts.com/
HighCharts extension for ExtJS 4
joekuan.wordpress.com/2012/01/27/highcharts-extension-for-extjs-4/?relatedposts_exclude=4038


Game about placing pennies on table follow-up

Question: This is inspired by the question at Game about placing pennies on table
"Consider the following two player game. Each player takes turns placing a penny on the surface of a rectangular table. No penny can touch a penny which is already on the table. The table starts out with no pennies. The last player who makes a legal move wins. Does the first player have a winning strategy?"
The first player will win by placing a penny in the centre of the table, then can always symmetrically match the opponent's moves reflecting across the central point (assuming equivalent dexterity), until the second player has no remaining move.
However, suppose we are playing as the second player, and we observe that the first player does not know this strategy - it appears that the first player has played in a 'random' (edit: leaving a central play possible) position on the board.
Can the second player use this bad first move to create a winning strategy? Even if the first player then returns to playing 'perfectly'? How?
If not, what is the second player's best option for a chance to win?
Further to discussion:
If the first player can return to play in the centre later on (or, even if the second player plays directly in the centre), the first player will take back their winning strategy.
Can the second player partially cover the centre enough in order to prevent this/gain the "central play" advantage? Can we be specific about what the second player should do in each case?
Comment: It is not obvious that if the first player can play the center later on, he has a guaranteed win.  The strategy relies on symmetry and the symmetry may be broken by the plays so far.  It may be a winning move, but it may also not be.
Comment: A quick (and somewhat boring) counter-example: if the table can only fit one penny (say, if its side length is $2R(1+\epsilon)$, $R$ being the penny's radius) then the first player wins anyway.
Comment: in that case we might say the first player played in the centre of the table ;)
Comment: @yohBS I edited the question, thanks :)
Comment: We might say that, but **we don't have to**. That is exactly my point. I don't know what the answer is, but you see immediately that it might depend on the the table size. So this might turn out to be ugly...
Comment: good point, thanks. i had assumed that the first player could ultimately recapture the symmetry, but it's apparent that the second player has enough freedom to break it.
Comment: Note: I will try to award the bounty to the most insightful of these answers before the time elapses, but really I would prefer a more complete answer.
Answer: Considering similar games, I don't think that the second player necessarily will have a winning strategy.  Either the first or the second player will have a winning strategy, but which player will depend on the dimensions of the board.
The "gold standard" of a strategy for impartial games like this involves a Grundy function $G$, which always exists (Sprague-Grundy theorem) but can be hard to find.  It takes a board position as input and returns a non-negative integer.  It returns a positive number for first player wins and zero for second player wins.
With $G$, the problem of perfect play is solved:  Consider all the board positions $P_i$ that you could move to.  If there's a position such that $G(P_i)=0$, then move there... and your opponent has no hope.
$G$ has these properties:

During the endgame, there will be a few "islands" in the sea of pennies where one can still play.  Each island is a mini-board with its own Grundy value.  The Grundy value of the entire board is the bitwise XOR, a.k.a. nim-sum, of the Grundy values of the islands.
If you are at board position $P$, and can move to any one of the board positions $P_i'$, then $G(P) = mex(G(P_i'))$, where "mex" means the minimum excluded value.  That is, the least non-negative integer not in the set $\{G(P_i')\}$.

To train myself to play against other people, I would study the Grundy values of small board positions.  I would write a computer program to draw bunches of them grouped by their Grundy values, then look for patterns.  My strategy would be to avoid symmetry and place the pennies to create islands with known Grundy values.  Then play perfectly just in the end-game.
In the game Cram, players place 1x2 dominoes on a square grid.  The last player who makes a legal move wins. From the table of Grundy values in Wikipedia's page on Cram, you can see that:

4x4, 5x5, and 4x6 islands are first-player wins.
4x5 and 5x7 islands are second player wins.
There's not much else known about who wins despite a lot of searching by computer.
Answer: If the distance between the center of the first penny and the center of the table (which I'll call the origin) is between $R$ and $\sqrt 3 R$, where $R$ is radius of the pennies, mirroring the first player's moves is a winning strategy for the second player. This is because it is always possible to mirror a penny that does not cover the origin, and two opposite pennies placed as above leave no room on either side to sneak in a penny that does cover the origin.
Comment: Because if the first penny is at slightly under $2R$, and the second penny mirrors the first, there is still room to fit in another penny -- not directly between them, but a little off to the side -- that does cover the origin.
Comment: ok... so if the first penny is sufficiently close to the centre that a mirror coin doesn't leave space for a central coin, the second player can 'steal' the first player's mirroring strategy.
Comment: Why $\sqrt{3}R$ rather than $2R$?
Comment: suggestion: if the first penny doesn't have this condition, then the second player has the opportunity to place a penny which does follow this condition.
Comment: Like! but this creates a curious asymmetry which might affect the strategic advantage of playing at the origin?
Answer: Assume the player must place the penny on a lattice-point:
If the table contains an even number of lattice-points, the second player always wins.  An odd number of points and the first player always wins.
If the player can place the penny on a lattice-line, thus blocking two lattice-points, then the above still holds (the evenness-oddness of the count does not change).
Edit: I misspoke: the evenness-oddness does change for the player!
If player two, on an even turn, blocks two lattice-points, it becomes an even turn for player one.  It's a lot like the "picking up the matches" game.
Strategy to guarantee the win when only one lattice-line remains playable:
If even-oddness is in player's favor: play a lattice-point, else play the lattice-line.
Comment: still not sure that this is a complete answer.
Even if player 2 can (choose to) change the even-oddness, then player 1 can change it right back?
Comment: @Ronald: a play on a lattice-point blocks three lattice-lines (assuming hex grid,) so opportunities to change even-oddness diminish as the game proceeds.
Comment: Misspoke again: up to six lattice-lines will be blocked on one play on a lattice-point.
Comment: If the play is in the center of a small triangle, three of each are blocked, parity does not change,and for this reason, I must agree with @TonyK: play anywhere you like.
Comment: so, player 2 has no strategy to win, no matter how badly player 1 plays? this seems highly unlikely.
Comment: At the point in the game when there is one open lattice-line and only single lattice-points open elsewhere, you can use the strategy in the last two lines of my answer.
Answer: If you were only allowed to place the pennies on the points of a hexagonal lattice (with the lattice points far enough apart so that pennies can't overlap), then the first player would still win: play opposite the second player, treating the two 'critical points' (the centre of the table, and the point opposite the first move) as opposite.
As Rahul's answer shows, the lattice-point condition is necessary.
Updated to add: After Rudy Toody's answer, I realise that this strategy is overkill. Equally effective is the strategy "play anywhere you like".
Comment: agreed, if you are placing on discrete points.
Comment: Further: if the lattice points are far enough apart so that the pennies don't overlap, then Player 2 can never win (no matter the strategy) because there should be an odd number of points.


Create a singleton class with react native

Question: I found different topics explain how to create a singleton, but none of them worked for me. This is an example taken from this post
export default class Credentials {

    static myInstance = null;

    _userID = "";

    static getInstance() {
        if (myInstance == null) {
            myInstance = new Credentials();
        }

        return myInstance;
    }

    getUserID() {
        return this._userID;
    }

    setUserID(id) {
        this._userID = id;
    }
}

when I call Credentials.getInstance() I get a warning

Can't find variable myInstance
Answer: JS has no implicit field lookup like statically-compiled languages. You need to lookup variables on the class explicitly:
class Credentials {

    static myInstance = null;

    static getInstance() {
      if (Credentials.myInstance == null) {
        Credentials.myInstance = new Credentials();
      }

      return Credentials.myInstance;
    }
}

Be careful with this approach since it's not truly a singleton because JS doesn't have proper class encapsulation.
You could change the instance directly easily:
Credentials.myInstance = 'something else';

Proper singleton with encapsulation should be implemented via a closure:
const Credentials = (() => {
  let myInstance = null;
  return class Credentials {
    static getInstance() {
      if (myInstance == null) {
        myInstance = new Credentials();
      }
      return myInstance;
    }
  }
})()

Answer: I think the most clean and easy solution would be the "ES6 singleton pattern" (not sure if there is an official name for this pattern).
You export the instance as default and everywhere you import it you get the same instance. This relies on the fact that module require is cached.
You would create your class and export the like so:
class Credentials {

    constructor() {
        this._userID = "";
    }

    get userID() {
        return this._userID;
    }

    set userID(userID) {
        this._userID = userID;
    }

}

export default new Credentials();

Wherever you import it you get the same instance:
import credentials from './credentials';

Comment: @Nicodemuz what doesn't work for you exactly? I've used this pattern many times in RN projects without any issues
Comment: I keep getting a new instance instead of the same.
Comment: interesting... if this indeed doesn't work I would want to know :) how are you testing it?

I tried to require it twice in the same block of code and compare - they are equal which means the same instance as far as I understand.

I also tried to add a static counter which is incremented in the constructor, then log it in several places in the app - always get a count of one.
Answer: This should be enough for any kind of single ton instance in JS.
Now, wherever you import this the same instance will be used. You can cross check by adding a date inside the class and accessing it at various places where you imported this.
import { SomeClass } from 'some-class'

let singletonInstance;

if (!singletonInstance) {
  singletonInstance = new SomeClass();
  // singletonInstance.time = new Date();
}

export default singletonInstance;

Then import it using
import singletonInstance from './above-code-file'


How to play these notes?

Question:
This is basically a G minor chord with a G in the bass.
Should I use my left hand to play the bass G and right hand to play the G minor triad?
Or should I play the bottom 2 notes with my left hand and top 2 notes with my right hand? Like strictly left hand for bass clef and right hand for treble clef.
Not sure what the convention is
Answer: As with so many things in music, it depends on the context. You can play this either way: with three voices in the right hand and one in the left hand, or with two voices in either hand.
Your decision would likely be up to what chords occur before and after this one. If all of the surrounding chords are easier to play with three voices in the right hand and only one in the left, then you'd probably want to play this chord that way, also.
Answer: You could do either.  The preferred method is going to depend on what comes next - there's no particular rule.
In some scores the upper three notes will be on a single stem (even when divided between staves) - in that case you can assume they're all played by the right hand.  The same is true when the two lower staff notes are on a single stem.  But in what you posted you're basically looking at four separately notated voices, and you'll do whatever is most comfortable in context.
Answer: There is no convention. This seems to be a choral setting and the beams are referring to the 4 voices SATB. But you can play it the way you want. As other say: it depends of the context (what comes next?)

How to play these notes?


Java equals() and hashcode() during automatic code generation

Question: I am working on a project where code gets automatically generated based upon an MySQL library. It is somewhat like JPA, but not quite.
This is an example bean:
public class TemplateBean implements Bean {
    private Integer templateId;
    private Integer businessPartnerId;

    public TemplateBean(final Integer businessPartnerId) {
        this.businessPartnerId = businessPartnerId;
    }

    private TemplateBean(final Object nullObject, final Integer templateId, final Integer businessPartnerId) {
        this.templateId = templateId;
        this.businessPartnerId = businessPartnerId;
    }

    public TemplateBean(final ResultSet rs) throws SQLException {
        this(null, rs.getInt(1), rs.getInt(2));
    }

    public Integer getTemplateId() {
        return templateId;
    }

    public void setTemplateId(final Integer templateId) {
        this.templateId = templateId;
    }

    public Integer getBusinessPartnerId() {
        return businessPartnerId;
    }

    public void setBusinessPartnerId(final Integer businessPartnerId) {
        this.businessPartnerId = businessPartnerId;
    }

    @Override
    public String toString() {
        return "Template(" + templateId + ", " + businessPartnerId + ")";
    }
}

Now I need it to implement equals() and hashCode(). I of course have access to all data that is available from SQL, so I think implementing equals() should be doable, but how am I going to create a good hashCode()?
Any tips will be appreciated.
Comment: If you are using Eclipse IDE, you can let Eclipse to generate `equals()` and `hashCode()` for you. Source > Generate Hashcodes and Equals then click the fields where you want to base your object's equality.
Comment: No. The reason is probably that it exists only since Java 7. It's probably also marginally faster because it doesn't need to box primitive fields and to create an array, but it's much less readable and maintainable.
Comment: you should have a look on http://commons.apache.org/proper/commons-lang/javadocs/api-3.1/org/apache/commons/lang3/builder/HashCodeBuilder.html and http://commons.apache.org/proper/commons-lang/javadocs/api-3.1/org/apache/commons/lang3/builder/EqualsBuilder.html - simply append your fields to the builders to dynamically generate `equals()` and `hashcode()`
Comment: And if you use Netbeans: ALT+INSERT > equals&hashcode.
Comment: Or in Guava, [`Objects.hashCode`](http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/base/Objects.html#hashCode%28java.lang.Object...%29)
Comment: @onepotato ,assylias Please read the question, I am talking about auto generated code, not human-typed code.
Comment: Or in plain Java 7: `Objects.hash(filed1, field2, field3)`
Comment: @JBNizet Netbeans does add prime numbers though in the generation. Maybe that's the reason why it is used above Objects.hash(Object...)?
Answer: I would like to suggest to use EqualsBuilder
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;

public class Person {
    private String id;
    private String name;
    private String address;
    private String phone;
    private String version;

    @Override
    public boolean equals(Object object) {
        return EqualsBuilder.reflectionEquals(this, object,);
    }

    @Override
    public int hashCode() {
        return HashCodeBuilder.reflectionHashCode(this);
    }

    or

    /*
     * equal() method with exclude fields.
     * it will neglect id and version fields.
     *
     * */
    @Override
    public boolean equals(Object object) {
        return EqualsBuilder.reflectionEquals(this, object, "id", "version");
    }
}

Comment: Beware of using all fields in a bean to compute `hashCode()` and `equals()`, specially when the bean represents database data. For example, comparing primary keys is generally undesirable (because you would be checking identity, not equality). Also, you could do potentially expensive comparisons, for example two blobs. My advice is to choose the fields used to compute the `equals()` carefully, not rely on reflection.
Comment: This seems a nice option, such that I don't have to build the functions myself in my generator, and moreover I am more confident that the commons' `hashCode()` is correct.
Comment: After more thinking I realised that it does add reflection in every single call of `equals()` resp. `hashcode()`, so aren't `HashMap`s and `Set`s, etc. getting very expensive to work with then?
Comment: @skiwi You could use HashCode/EqualsBuilder without reflection and append the desired fields to the builders. just look at the documentatation and keep in mind what EmirCalabuch mentioned
Answer: One very convenient way is to use the @EqualsAndHashCode annotation provided by Groovy. Using this is as simple as
@EqualsAndHashCode
public class TemplateBean implements Bean {
  // implementation omitted
}

This will generate equals() and hashCode() methods based on the class' properties using an algorithm similar to the one outlined in the book Effective Java.
Because the annotation is implemented via an AST transformation, it can be used in Java or Groovy classes, though you will of course need the Groovy library on your classpath to use it.


Reflexive transitive closure in Propositional Dynamic Logic

Question: Would anyone care to explain how can we dualize the Reflexive Transitive Closure in PDL from :
$$\frac{(\phi\vee\langle\alpha\rangle\psi)\rightarrow\psi}{\langle\alpha^*\rangle\phi\rightarrow\psi}$$
to: $$\frac{\psi\rightarrow (\phi\vee [\alpha]\psi)}{\psi\rightarrow [\alpha^*]\phi}$$?
Where $\alpha$ is a program, $\phi,\psi$ are formulas and $\langle\alpha\rangle$ is the diamond from PDL.
Comment: Are you sure it's not $(\phi \wedge [\alpha]\psi)$?
Answer: $\def\<#1>{\langle#1\rangle}$We start from the relation between box and diamond:
$$ \<\alpha>p \equiv \neg [\alpha] \neg p \enspace. $$
Substitution in the reflexive transitive closure rule yields
$$ \frac{(\phi \vee \neg[\alpha]\neg \psi) \rightarrow \psi}{\neg[\alpha^*]\neg\phi \rightarrow \psi} \enspace. $$
Taking the contrapositive of both premise and conclusion,
$$ \frac{\neg \psi \rightarrow (\neg\phi \wedge [\alpha]\neg \psi)}{\neg\psi \rightarrow [\alpha^*]\neg\phi} \enspace. $$
We now rename, so that $\neg\phi$ is replaced by $\phi$ and $\neg\psi$ is replaced by $\psi$:
$$ \frac{\psi \rightarrow (\phi \wedge [\alpha]\psi)}{\psi \rightarrow [\alpha^*]\phi} \enspace. $$
Finally, if we wish to obtain the loop invariance rule, we substitute $\psi$ for $\phi$ and simplify:
$$ \frac{\psi \rightarrow [\alpha]\psi}{\psi \rightarrow [\alpha^*]\psi} \enspace, $$
having noted that $\psi \rightarrow (\psi \wedge [\alpha]\psi) \equiv \psi \rightarrow [\alpha]\psi$.


Superfish Menu: looking for specific css value

Question: Using Drupal 7.19 and Superfish 7.x-1.8
I was able to override most of the CSS and we are working towards a menu that we would like. However, I would like the parent menu item that is looked at to show a certain color. But it goes transparent once the mouse if off if it is unactive.
I am looking to make the unactive parentmenu item go a certain color if the child is hovered. I can't find the id/class via firebug, but am still looking.
If you look at the image provided, we want "Nuestro Institución" to show #fec24a (yellow) when it is expanded and unactive.
The site is in Spanish and these are the institutional colours.
I had an image attached, but I can't post it as a new user, so I will include the site I am working on.
Please remember that it is a work in progress.
http://devel.idl.org.pe/
Answer: The HTML element for "Our Institution" is:

Nuestro Institución

You want the :hover value of this li item when you're on a child item. This is:

Nuestro Institución

In my opinion this always gets ugly in CSS, for just that 1 menu item you could do (depending on your rules already in CSS):
#menu-679-1.sfHover {background-color: yellow;}
or if that doesnt work:
#menu-679-1.middle.even.sf-item-2.sf-depth-1.sf-total-children-5.sf-parent-children-0.sf-single-children-5.menuparent.sfHover { background-color: yellow; }

I would just write 1 css class per menu ID you want to target. If you use LESS CSS preprocessor you can use a small template to apply the hover color. You might be able to use a descendant selector but I always run in problems selecting all child
s when I do that ....
Answer: Normally, you should start by chosing a style from the superfish block administration and see if the background changes for hovered  menu parent elements. (It should - only the default style - that you are using now has no background). If it is, copy the stylesheet to a new one (let's say newstyle.css) and rename(use a find/replace all tool) all occurances of old stylesheet name in the classes names with the "newstyle". Then edit the colors or other formatting as you like in the new stylesheet.
If not, which is again your case, you should remove or edit the .sf-menu classes from yoour sites/devel.idl.org.pe/themes/corolla/css/navigation.css
the background for your main parent elements is given in the corrola navigation stylesheet  by :
.sf-menu li.sfHover

and by(line42) :
.sf-menu.sf-style-space-orange li.sfHover

in the orange-space.css(as an example) file - that you should have it in the sites/all/libraries/superfish/style
Also you should look in sites/devel.idl.org.pe/themes/footheme/css/footheme.css and i guess the generated css of footheme sites/devel.idl.org.pe/files/color/footheme-9c3b33ed/colors.css for conflicts on the lines that start with #menu-bar


Hibernate JPA difference in remove between find() and merge()

Question: I want to ask what is the difference between removing using find() and merge() method. I get the same results after compiling. User class and UserDetails are classes in OneToOne relation (parent and child).
using find()
<code>@Transactional
@Override
public void delete(User user) {
    User temp = entityManager.find(User.class,user.getId());
    entityManager.remove(temp.getUserDetails());
    entityManager.remove(temp);
}
</code>
using merge()
<code>@Transactional
@Override
public void delete(User user) {
    User temp = entityManager.merge(user);
    entityManager.remove(temp.getUserDetails());
    entityManager.remove(temp);
}
</code>
Answer: The merge() method is used to perform an update on an entity passed as a parameter, after the update is done it returns the result of the update/merge, this is why you was able to use it as a "find()" method.
The find() method only takes an ID as a parameter so it's not possible to perform an update with this one.
I would says that the merge() method is less effective because it will perform the update first then return the result, maybe there's also some logic to check if the entity is dirty or not before performing the update which can result in an additional cost. On the other hand, there shouldn't be a huge difference between the two methods in most scenarios.
Comment: Yes, I know it, but I rather wanted to know what are the pros/cons of using them and which one is better to use :)


Java: Separate Time Digits

Question: I'm trying to separate each number in an hh:mm type of setup into individual digits. So if the time was 8:24, I would have [0, 8, 2, 4]. How would I do that?
Answer: Once you get the hour and minute from your Date object, you can use the mod and % operators to calculate the individual digits. http://mindprod.com/jgloss/modulus.html
Answer: You need to format your input text with HH:mm date pattern, remove all non-numeric characters and finally split string into characters.
String inputTime = "8:24";
DateFormat df = new SimpleDateFormat("HH:mm");
String formattedInputTime = df.format(df.parse(inputTime));

String timeDigits = formattedInputTime.replaceAll("[^\\d]", "");

char[] timeDigitTokens = timeDigits.toCharArray();
for (char timeDigitToken : timeDigitTokens) {
    System.out.println(timeDigitToken);
}

Compile and run working code here.
Answer: No need to remove non-numeric characters as suggested above, just don't put them in the formatted date to begin with.  Also, there's no need for the toCharArray to be called, as you can get at each character directly via String.charAt method:
String s = new SimpleDateFormat("mmss").format(new Date());
System.out.println(s.charAt(0));
System.out.println(s.charAt(1));
System.out.println(s.charAt(2));
System.out.println(s.charAt(3));

Comment: Well, question owner didn't specify, what are per-conditions, is it a Date or a String and should the date be hh(12h-based) or HH(24h-based). And charAt(idx) method checks for bounds in String's internal array, takes 4 dirty hardcoded lines of code while toCharArray() method just delegates its copy work of its internal's char array to System.arraycopy(..) and takes only one clean universal line of code.
But +1 for 'hhmm' format instead of 'hh:mm'.
Answer: Based on Chris Nava's idea (upvote his answer first) and assuming you want int digits instead of char:
public class TimeSplit {

  public static void main(String[] args) throws ParseException {
    printSplit("8:24"); // [0, 8, 2, 4]
    printSplit("10:22"); // [1, 0, 2, 2]
    printSplit("13:57"); // [0, 1, 5, 7] because of 12h
  }

  private static void printSplit(String time) throws ParseException {
    System.out.println(time + " -> " + Arrays.toString(split(time)));
  }

  private static int[] split(String time) throws ParseException {
    DateFormat fmt = new SimpleDateFormat("hh:mm"); // 12h, use HH for 24h
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(fmt.parse(time));
    return split(calendar);
  }

  private static int[] split(Calendar time) {
    int hours = time.get(Calendar.HOUR); // 12h, use HOUR_OF_DAY for 24h
    int minutes = time.get(Calendar.MINUTE);

    int[] digits = new int[4];
    digits[0] = hours / 10;
    digits[1] = hours % 10;
    digits[2] = minutes / 10;
    digits[3] = minutes % 10;
    return digits;
  }
}

Output:
8:24 -> [0, 8, 2, 4]
10:22 -> [1, 0, 2, 2]
13:57 -> [0, 1, 5, 7]

Java: Separate Time Digits


7- Disable a block or edit it without access to the admin interface

Question: I activated php code in a block in the header, and I put "echo $user;" instead of "echo $user->name;".
Now I get an error on page load and can't edit the block to correct the mistake.
If I could change the active admin theme back to bartik, that would also solve the problem.
Any ideas welcome. Thanks
Edit: ok I think I solved by deleting my custom theme folder. Good that the block was only enabled for the custom theme.
Answer: If you have devel installed, you can edit the default theme by editing theme_default variable.
http://yoursite.com/devel/variable/edit/theme_default
Or deactivate the block in your database
update blocks set status = 0 where delta = 'block';


content-rich button collapsed into icon and show nav tab content

Question: I'm trying to achieve this "effect" or whatever its called.
Where I have a content-rich vertically aligned buttons (with an icon, header text, and normal text).
Then when a button gets pressed, A new set of vertically aligned buttons (with an icon and normal text) appeared as new options.
Then when a "sub-button" gets pressed, A content area appears.
I tried "vertically aligned tabs with bootstrap 4" but I'm stuck with:

showing ONLY the main buttons with full content
showing ONLY the icon for the main button (where the rest of the button content gets hidden after the click) +and+ the sub-buttons
return to normal, where only the main buttons appear with full content

as the picture below

I'm using: Bootstrap 4 + I know a little of JS
Please help me with this, or guide me to where I could get an answer for it. Thanks
~ update: here is a link for a very basic "vertical navs pills" I'm working on https://codepen.io/bixet/pen/yxGrLO

      Main
Home
      Main
Profile
      Main
Messages
      Main
Settings

      SubHome
      SubProfile

1) Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque at ex viverra, maximus ante nec, porta turpis. Fusce eu velit nec sem blandit aliquet. Curabitur vitae ultrices leo. Fusce risus mauris, iaculis vitae viverra in, lacinia quis lacus.

2) Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque at ex viverra, maximus ante nec, porta turpis. Fusce eu velit nec sem blandit aliquet. Curabitur vitae ultrices leo. Fusce risus mauris, iaculis vitae viverra in, lacinia quis lacus.

      SubHome
      SubProfile

1) Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque at ex viverra, maximus ante nec, porta turpis. Fusce eu velit nec sem blandit aliquet. Curabitur vitae ultrices leo. Fusce risus mauris, iaculis vitae viverra in, lacinia quis lacus.

2) Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque at ex viverra, maximus ante nec, porta turpis. Fusce eu velit nec sem blandit aliquet. Curabitur vitae ultrices leo. Fusce risus mauris, iaculis vitae viverra in, lacinia quis lacus.

3) Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque at ex viverra, maximus ante nec, porta turpis. Fusce eu velit nec sem blandit aliquet. Curabitur vitae ultrices leo. Fusce risus mauris, iaculis vitae viverra in, lacinia quis lacus.

4) Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque at ex viverra, maximus ante nec, porta turpis. Fusce eu velit nec sem blandit aliquet. Curabitur vitae ultrices leo. Fusce risus mauris, iaculis vitae viverra in, lacinia quis lacus.

Comment: Can you edit to include the solutions you've tried so far?
Comment: done, I just did the sub-level. Still can't know how to do the auto-show or auto-hide or what is called so I could look for it.
Answer: i have the following solution that uses pure CSS and some Javascript code :
(See this fiddle) for a good preview

let menuItems =document.querySelectorAll(".y-menu-item");
menuItems.forEach((item)=>{
    item.addEventListener("click", function(event){
        document.querySelectorAll(".y-texts-wrapper,.y-menu-sublevel-1").forEach((txtw)=>{
            txtw.style.display='none';
        });

        item.children[2].style.display='block'

    })
})

/********************** */

let subMenuItems=document.querySelectorAll('.y-menu-item-sublevel-1');

subMenuItems.forEach((subItem)=>{
    subItem.addEventListener("click",function(){

        document.querySelectorAll(".y-sub-l1-ht,.y-content").forEach((ht)=>{
            ht.style.display='none';
        });
        subItem.children[2].style.display='block'

    });
})
body{
    height: 100vh;
    width: 100vw;
    margin: 0;
    font-family: Montserrat,sans-serif;
    color:#333;
}
p{
    font-size: 10pt;
}
.y-menu{
    padding: 20px;
    height: 80%;
    display: flex;
    flex-direction: column;

    justify-content: space-between;
    align-items: flex-start;

}

.y-menu-item{
    display: flex;
    flex-direction:row;
    align-items: center;
    padding: 20px;
    margin: 5px 0;
    border-radius:5px;
    /* background: #eee; */
    cursor: pointer;

}

.y-icon{
    width: 70px;
    height: 70px;
    border-radius: 15px;
    background: #4E0BEF;
}

.y-s-icon{
    width: 40px;
    height: 40px;
    border-radius: 5px;

}
.y-texts-wrapper{
    margin-left: 20px;
    /* display: none; */
}

.y-normaltxt{
    width: 200px;

}
.y-menu-sublevel-1{
    display: none;
    position: absolute;
    margin-left: 84px;
    margin-top: 47px;
}

.y-menu-item-sublevel-1{
    display: flex;
    flex-direction:row;
    align-items: center;
    margin:0 0 10px 10px ;
}

@keyframes anim1{
    0% {width: 0;height: 0;opacity: 0;}
    50% {width: 250px;height: 250px;opacity: .5;}
    100% {width: 500px;height: 500px;opacity: 1;}

}

.y-content{
    width: 500px;
    height: 500px;
    top:20px;
    left:180px;
    padding:20px;
    color: #fff;
    background: #4E0BEF;
    position: fixed;
    display:none;
    text-align: center;
    animation: anim1 .1s ;
}
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Menu</title>

    <link rel="stylesheet" href="style.css">

Some head text

Lorem ipsum dolor sit amet consectetur adipisicing elit

Some head text 1

Lorem ipsum dolor, sit amet consectetur adipisicing elit. Sed mollitia et labore sunt distinctio laboriosam numquam laborum doloribus ex animi at amet maiores, quaerat temporibus, exercitationem minima repellat quos eligendi!

Some head text 1

The main content

Some head text 1

The main content

Some head text

Lorem ipsum dolor sit amet consectetur adipisicing elit

Some head text 1

The main content

Some head text 1

The main content

Some head text 1

The main content

Some head text

Lorem ipsum dolor sit amet consectetur adipisicing elit

Some head text 1

The main content

Some head text 1

The main content

Some head text 1

The main content

Some head text

Lorem ipsum dolor sit amet consectetur adipisicing elit

Some head text 1

The main content

Some head text 1

The main content

Some head text 1

The main content

Comment: Thanks a lot, bro, your solution is very good for going forward. But the only thing wrong with it is when I try to switch or go to another group. I mean the text should appear back if I want to see a different element. but thanks though :)


Expressing english in logic

Question: The sentence:
The difference of two positive numbers is not necessarily positive,
Is expressed as:
$$ (\forall x\in\Bbb Z)((x>0)\land(y>0)\rightarrow(x+y >0))$$
Is this statement correctly expressed? If so, please give a brief(or detailed) explanation.
This statement implies that if  x > 0 and y > 0  then, x + y > 0, where's the necessarily part?
If the necessarily part comes from, the fact that if the R.H.S
is False then the statement is false. Then, I'm confused in the contraction with the simple analogy of another statement:
"The product of two negative numbers is always positive", expressed as:
  $$ (\forall x\forall y\in\Bbb Z)((x<0) \land (y<0)\rightarrow (x*y) > 0)$$
Which is always true, so, there's no necessarily part in this at all. What I mean is, if the first statement is stated correcly, means that there's a necessarily part in this first statement, in which case, there should also be a necessarily part in the second statement(by comparison), which should not be the case, because the statement is always true.
Of course, if the first statement expressed with logic and quantifiers was wrong, everything is solved.(Note, the example the taken from Rosen's book of discrete mathematics.)
Comment: I think that you have misunderstood the locution "not necessarily". It must be read: "it is not true that, if $x$ and $y$ are both positive, then their difference is positive".
Comment: To say that "the difference of two positive numbers is not necessarily positive" is the same as "there are two positive numbers whose difference is not positive".
Comment: Consider the case with $2$ and $3$: $((2>0) ∧ (3>0) \land (2-3 \le 0))$. Now quantify it accordingly.
Comment: Here are some fun pop-culture examples of translating assertions from English to first-order logic: http://jdh.hamkins.org/famous-quotations-in-their-original-language/.
Comment: The first formula says that the sum of $x$ and $y$ **is** positive
Comment: I would say 'not necessarily positive ' to mean 'possibly not positive', i.e. that for *some* positive numbers, the difference is not positive ... so you should probably have an existsntial in there ... *or* use the negation of the sentence that says that the difference is always positive
Comment: @MauroALLEGRANZA, do you mean that the quantification of the first statement is wrong. Please say so explicitly, because, the remarks are just as vague.
Comment: Exactly: the correct transaltion is obtained writing is symbols: "there are positive numbers $x$ and $y$ whose difference is not positive".
Comment: $\exists n \ \exists m \ [(n >0) \land (m > 0) \land (n-m \le 0)]$.
Answer: There are two issues here. One is that the logic statement you offer does not match the English statement. The logic statement you offer (when you add $\forall y$ as Mauro Allegranza suggested in the comments) would be best translated to English as: The sum of any two positive numbers is (necessarily) positive.
For the English statement "The difference of two positive numbers is not necessarily positive", you would want something like:
$$\neg \forall x \forall y (x>0 \land y>0 \rightarrow x-y>0)$$
or, equivalently,
$$\exists x,y \text{ such that } (x>0 \land y>0 \land x-y <0)$$
The second issue is the question you raise about how "necessarily" figures in these statements. "Necessity" is a phrase used in many ways, often unclearly. For your purposes, in your original English sentences, "necessarily" almost certainly means simply that some positive numbers have negative difference.
In other words, the only reason "necessarily" is there in your English statement is because if it weren't there, many readers might erroneously understand the statement to be claiming that all positive numbers have negative differences. But the statement is not claiming that; it is instead claiming that positive numbers sometimes have negative differences. So "necessarily" is added to make this clear.
The reason why "necessarily" does not occur in your second example is that there is no such danger of ambiguity, so there is no reason to include "necessarily" to prevent misunderstanding.
It is worth adding that some "modal" logical systems -- almost certainly not related to what you are working with -- do incorporate operators for necessity. In such a logic, there is a distinction between truth and necessary truth. (E.g., it is true that my tea is hot, but it is not a necessary truth; my tea can easily become cold. By contrast, it is a necessary truth that 1<2.) In such modal logical languages, necessity is typically denoted by "$\square$". So, we have:
\begin{align*}
A \text{ implies }B& & \phantom{\square (}A\rightarrow B\phantom{)}\\
A \text{ necessarily implies }B& &\square (A\rightarrow B)
\end{align*}
Comment: @BeshalJaenal I see now. In my version of the statement, the negation applies to the whole following statement. That is, the statement I wrote is equivalent to: $\neg \left( \forall x \forall y (x>0 \land y>0 \rightarrow x-y>0)\right)$. So in my original version of the statement, the negation doesn't have any particular connection to $x$ rather than $y$. The statement $\forall x \neg \forall y ( x>0\land y>0 \rightarrow x-y>0)$ would be an awkward way of expressing the original -- but yes, it would have the same meaning as my version.
Comment: I came to this a little bit later, but could you tell me why the negation is not done in y instead or why not in both?
Comment: @BeshalJaenal Sorry, I don't understand what you mean. Can you rephrase your question?
Comment: below the line:  "The difference of two positive numbers is not necessarily positive", you would want something like:, you have given ¬∀x∀y(x>0∧y>0→x−y>0 statement, why is ¬∀x done? Is ¬∀y also OK? How does this alter the meaning?
Answer: I think the book uses 'necessarily' and 'always' interchangeably. So, that second second could be expressed as 'the product of two negative numbers is always positive', but it can also be expressed as 'the product of two negative numbers is necessarily positive'.
As such, the sentence 'the difference of two positive numbers is not necessarily positive' can be understood as 'the difference of two positive numbers is not always positive'.
To symbolise that first sentence in logic, we can do one of two things:
A first strategy is to symbolise the sentence 'the difference of two positive numbers is always positive', and just negate that. That gives us:
$$\neg \forall x,y \in \mathbb{Z} ((x >0 \land y >0) \rightarrow x-y >0)$$
A second strategy is to rephrase the sentence as 'it is possible for the difference of two positive numbers to not be positive' or what is the same thing, 'there exists two positive numbers such that their difference is not positive'. In logic, that would be:
$$\exists x,y \in \mathbb{Z} (x>0 \land y >0 \land \neg \ x-y >0)$$

Expressing english in logic