SetEmptyView doesn't fit inside his parent (list view)

Question: This is what happen when i set a 'view' for my empty view. (the empty view fit inside the whole screen instead listview's size.
issue
i want to fit my empty view inside the blue area (see the image) :
enter image description here
empty_items
<RelativeLayout  xmlns:android="http://schemas.android.com/apk/res/android"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="#bdbdbd">

<ImageView
    android:id="@+id/image1"
    android:layout_width="150dp"
    android:layout_height="150dp"
    android:layout_gravity="center"
    android:background="@mipmap/ic_inf"
    android:layout_centerVertical="true"
    android:layout_centerHorizontal="true"
    android:contentDescription="information">
</ImageView>

<TextView
    android:layout_width="wrap_content"
    android:layout_height="168dp"
    android:textAppearance="?android:attr/textAppearanceLarge"
    android:text="SIN NADA POR MOSTRAR"
    android:textAlignment="center"
    android:textSize="32sp"
    android:textStyle="bold"
    android:textColor="#757575"
    android:id="@+id/infoMsgTextView"
    android:layout_gravity="center_horizontal|bottom"
    android:layout_alignParentTop="false"
    android:layout_alignParentLeft="false"
    android:layout_alignParentStart="true"
    android:layout_marginTop="224dp"
    android:layout_alignParentEnd="false"
    android:layout_alignParentBottom="true"/>

sales_fragment.xml - a fragment with the listview  that i want to set empty view.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
            xmlns:fbutton="http://schemas.android.com/apk/res-auto"
            xmlns:tools="http://schemas.android.com/tools"
            xmlns:htext="http://schemas.android.com/apk/res-auto"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            xmlns:fab="http://schemas.android.com/apk/res-auto"
            tools:context=".controler.SalesFragment"
            android:visibility="visible"
>

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="165dp"
    android:layout_gravity="center"
    android:background="#144257"
    android:id="@+id/relativeLayout"
    android:layout_below="@+id/tvClient"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true">

    <EditText
        android:layout_width="100dp"
        android:layout_height="wrap_content"
        android:inputType="numberDecimal"
        android:background="@drawable/roundedshadow_et"
        android:ems="10"
        android:id="@+id/discountEditText"
        android:elegantTextHeight="false"
        android:hint="@string/discountHint"
        android:textColorHint="#FFFF"
        android:textColor="#FFFF"
        android:textAlignment="center"
        android:layout_alignTop="@+id/etPrice"
        android:layout_toLeftOf="@+id/etPrice"
        android:layout_toStartOf="@+id/etPrice"/>

    <AutoCompleteTextView
        android:layout_width="300dp"
        android:background="@drawable/roundedshadow_et"
        android:layout_height="60dp"
        android:singleLine="true"
        android:scrollHorizontally="true"
        android:id="@+id/productAutoCompleteTextView"
        android:hint="@string/product"
        android:textColorHint="#FFFF"
        android:layout_gravity="center"
        android:textAlignment="center"
        android:textColor="#ffff"
        android:visibility="visible"
        android:layout_alignParentTop="true"
            android:layout_centerHorizontal="true"/>

    <EditText
        android:layout_width="100dp"
        android:layout_height="wrap_content"
        android:inputType="numberDecimal"
        android:background="@drawable/roundedshadow_et"
        android:ems="10"
        android:id="@+id/amountEditText"
        android:elegantTextHeight="false"
        android:textAlignment="center"
        android:textColor="#FFFF"
        android:textColorHint="#FFFF"
        android:hint="@string/amountHint"
        android:layout_alignTop="@+id/discountEditText"
        android:layout_alignLeft="@+id/productAutoCompleteTextView"
        android:layout_alignStart="@+id/productAutoCompleteTextView"/>

    <info.hoang8f.widget.FButton

        android:layout_width="70dp"
        android:layout_height="wrap_content"
        fbutton:buttonColor="#144257"
        fbutton:shadowColor="#0e2e3c"
        fbutton:shadowEnabled="true"
        fbutton:shadowHeight="5dp"
        fbutton:cornerRadius="5dp"
        android:textColor="#ffff"
        android:textAlignment="center"
        android:text="@string/addProduct"
        android:id="@+id/addProductBtn"
        android:layout_below="@+id/discountEditText"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="5dp"/>

    <EditText
        android:layout_width="100dp"
        android:layout_height="wrap_content"
        android:inputType="numberDecimal"
        android:background="@drawable/roundedshadow_et"
        android:ems="10"
        android:id="@+id/etPrice"
        android:elegantTextHeight="false"
        android:textAlignment="center"
        android:textColor="#FFFF"
        android:textColorHint="#FFFF"
        android:hint="@string/priceHint"
        android:layout_centerVertical="true"
        android:layout_alignRight="@+id/productAutoCompleteTextView"
        android:layout_alignEnd="@+id/productAutoCompleteTextView"/>

</RelativeLayout>

<com.hanks.htextview.HTextView
    android:id="@+id/tvClient"
    android:layout_width="fill_parent"
    android:layout_height="20dp"
    android:background="#144257"
    android:gravity="center"
    android:textColor="#FFFFFF"
    android:textSize="15sp"
    htext:animateType="anvil"
    android:layout_alignParentTop="true"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:textAlignment="center"/>

<com.hanks.htextview.HTextView
    android:id="@+id/tvPrice"
    android:layout_width="fill_parent"
    android:layout_height="20dp"
    android:background="#144257"
    android:gravity="center"
    android:textColor="#FFFFFF"
    android:textSize="15sp"
    htext:animateType="anvil"
    android:textAlignment="center"
    android:layout_below="@+id/relativeLayout"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"/>

<com.github.clans.fab.FloatingActionMenu
    android:id="@+id/sale_floating_menu"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    fab:menu_animationDelayPerItem="55"
    fab:menu_backgroundColor="@color/fbutton_color_transparent"
    fab:menu_buttonSpacing="0dp"
    fab:menu_colorNormal="#e040fb"
    fab:menu_colorPressed="#4d0359"
    fab:menu_colorRipple="#99d4d4d4"
    fab:menu_fab_label="Opciones de venta"
    fab:menu_fab_size="normal"
    fab:menu_icon="@mipmap/shopping_cart"
    fab:menu_labels_colorNormal="#333"
    fab:menu_labels_colorPressed="#444"
    fab:menu_labels_colorRipple="#66efecec"
    fab:menu_labels_cornerRadius="3dp"
    fab:menu_labels_ellipsize="none"
    fab:menu_labels_hideAnimation="@anim/fab_slide_out_to_right"
    fab:menu_labels_margin="0dp"
    fab:menu_labels_maxLines="-1"
    fab:menu_labels_padding="8dp"
    fab:menu_labels_position="left"
    fab:menu_labels_showAnimation="@anim/fab_slide_in_from_right"
    fab:menu_labels_showShadow="true"
    fab:menu_labels_singleLine="false"
    fab:menu_labels_textColor="#f2f1f1"
    fab:menu_labels_textSize="15sp"
    fab:menu_openDirection="up"
    fab:menu_shadowColor="#66aff198"
    fab:menu_shadowRadius="4dp"
    fab:menu_shadowXOffset="1dp"
    fab:menu_shadowYOffset="4dp"
    fab:menu_showShadow="true"
    android:layout_alignParentRight="true"
    android:layout_alignParentEnd="true"
    >

    <com.github.clans.fab.FloatingActionButton
        android:id="@+id/floating_add"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@mipmap/add_tag"
        fab:fab_size="mini" />

    <com.github.clans.fab.FloatingActionButton
        android:id="@+id/floating_checkout"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@mipmap/checkout"
        fab:fab_size="mini" />

</com.github.clans.fab.FloatingActionMenu>

<RelativeLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/tvPrice">

    <ListView
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:longClickable="true"
        android:id="@+id/lvCart"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="false"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true"
        android:layout_alignParentBottom="true"/>
</RelativeLayout>

SalesFragment.java
    @Override
    public View onCreateView(LayoutInflater inflater, final ViewGroup container,
                             Bundle savedInstanceState)
    {
        // Inflate the layout for this fragment
    View view = inflater.inflate(R.layout.fragment_sales, container, false);
        neverEmptyListView = (ListView) view.findViewById(R.id.lvCart);
    ViewGroup headerView = (ViewGroup) getActivity().getLayoutInflater().inflate(R.layout.header_row_layout, neverEmptyListView, false);
    neverEmptyListView.addHeaderView(headerView);

    View emptyView = getActivity().getLayoutInflater().inflate(R.layout.empty_items, null);
    emptyMsg = (TextView) emptyView.findViewById(R.id.infoMsgTextView);
    emptyMsg.setText("Agregue productos para la venta");

     getActivity().addContentView(emptyView, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
    neverEmptyListView.setEmptyView(emptyView);

    items = new ArrayList<String>();
    lvAdapter = new ListViewAdapter
            (getContext(), R.layout.row_layout, R.id.description, items);
    neverEmptyListView.setAdapter(lvAdapter);

Comment: remove this line and then check: getActivity().addContentView(emptyView, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
Comment: when i remove that line the empty view dissapear from my listview even if there aren't items.
Answer: i solve my problem this way:
        ((ViewGroup)neverEmptyListView.getParent()).addView(emptyView);
    neverEmptyListView.setEmptyView(emptyView);


How many times batsmen have managed to get more than 7 runs on a single ball in an international cricket match?

Question: Australia's Andrew Symonds managed to score eight runs off one ball while playing in Brisbane facing New Zealand bowler Iain O'Brien in November 2008. He ran four runs before the ball was thrown back over the wicket keeper's head for a boundary.
How many times has this happened in an international cricket match?
Answer: According to ESPNCricinfo, it happened four times in Test cricket in total including the feat of Andrew Symonds. Other instances are given below.

Patsy Hedren facing Percy Hornibrook in 1928-29, Melbourne.

This rare feat happened for the first time when Patsy Hedren collected four overthrows after an all-run four off the Australian debutant Percy Hornibrook.

Here is another trivia bit. This was the first series of Sir Donald Bradman.
John Wright facing Lenny Pascoe in 1980-81, Melbourne

This time it was New Zealand's John Wright who benefited from four overthrows (by Rod Marsh, who collected a fielder's return and hurled it at the stumps) after an all-run four off an unamused Lenny Pascoe.

Brian Lara facing Nicky Boje in 2004-05, Port of Spain.

When Brian Lara glanced a ball from the South African slow left-armer Nicky Boje for three. The wicketkeeper, Mark Boucher, ran after the ball and threw it back in, but his return hit a fielder's helmet on the ground, so he incurred five penalty runs, making eight in all off that delivery.

However, these five penalty runs have been deducted from Brian Lara 's total runs after a recent rule change. These five runs were converted into extra penalties.

Occurences in ODI cricket are unknown. There are no occurences in T20 cricket.
Answer: To add to the accepted answer, 8 runs scored off the bat has also happened in a Namibia Under-19s v North West Under-19s match at Port Elizabeth on Dec 17, 2015.
Source: Over 15.6

Davin to Senokwane, 8 runs,
Comment: Try to use proper formatting, [Markdown Help](https://sports.stackexchange.com/editing-help)


Evaluating quality of sources using factor analysis

Question: Assume I have entities $e_i$ (let's say, persons) and am trying to approximate their numerical attribute $q_i$ (let's say, their age). For this, I'm using imperfect data from $3$ sources $S_1, S_2, S_3$. Source $S_i$ is defined on a domain $D_i\subseteq \{e_1,\ldots, e_N\}$ and gives me an approximation of the real value for any $e\in D_i$. Assume that $D_i\cap D_j$ is nonempty for each $i,j$.
Without having much other information, how can I evaluate the quality of my sources?
One idea I have in mind is to construct a "correlation matrix" $C$ having

$1$ on the diagonal, and
a Pearson correlation of sources $S_i$ and $S_j$ on the intersection $D_i\cap D_j$ where both sources are defined, on positions $(i,j)$ and $(j, i)$.

Then the C-eigenvector corresponding to the largest eigenvalue should correspond -- I guess -- to something like an "approximation of the true value", assuming that factors in the factor analysis are interpretable.
If this first factor is, let's say, $0.8\times S_1 + 0.3\times S_2 + 0.6\times S_3$, can I interpret it so that source $S_1$ is "better" and source $S_2$ is the worst?
Any feedback or references to this idea? -- does it make sense?
Answer: Yes. But you should probably use principal components analysis
A similar approach is used in intelligence testing - general intelligence (g) is defined as the first unrotated principal component from a PCA of a bunch of intelligence tests. The higher the loading, the more the test is assumed to represent general intelligence, and this is called its 'g-loading'.
There's information on the wikipedia page: https://en.wikipedia.org/wiki/G_factor_(psychometrics)
You can find more papers with your favorite search engine. Here's one: https://www.sciencedirect.com/science/article/abs/pii/0160289686900097
Comment: Ok -- I will study that, thank you!
Comment: Thanks for your comment. However, regarding PCA -- note that I don't really have the full data from all the sources -- my correlations are computed each one on a different set (intersection of the domains $D_i$ and $D_j$), I'm not sure what else I can do then get this pseudo-correlation matrix...
Comment: Not sure I understand. If you just have a correlation matrix, you can do PCA or EFA, can't you?
Comment: It's not a correlation matrix in the usual sense that I have full data, $N$ rows and $k$ columns ($k$ would be 3 in my example, with 3 sources). I only have limited data from each source. So, the correlation between source 1 and source 2 is computed on a subset {John, Peter, Pavel} and the correlation between source 1 and source 3 is computed on a different subset {Maria, Eva, Paul}. I'm putting all these correlations into one matrix and am calling it "correlation matrix". However, I'm not sure how to mimic PCA with such incomplete data...
Comment: Maybe I'm just not educated enough, but don't you need the actual full data to do PCA? If I only have a symmetric matrix (let's call it correlation matrix), can I do anything else than compute eigenvectors?
Comment: In R, the main PCA functions take either a data frame or a correlation matrix. http://www.sthda.com/english/articles/31-principal-component-methods-in-r-practical-guide/118-principal-component-analysis-in-r-prcomp-vs-princomp/


htaccess - redirect user from index.php to another file if url is more than root

Question: I have a need where I have 2 files located within the same directory
index.php and room.php
What I want to be able to do it if a user goes to www.example.com it will direct them to index.php
If a user types in the url www.example.com/whateverelse/ it will redirect them to room.php
Also I would like to capture the extra part of the URL into a variable for instance whateverelse
Is this even possible?
Answer: Yes it is very much possible. Use this code in your root .htaccess:
# load index.php by default
DirectoryIndex index.php

RewriteEngine On
RewriteBase /

# remove trailing slash
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.+)/$ /$1 [NE,R=301,L]

# for all other requests load room.php
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^((?!(index|room)\.php).+)$ room.php [L,NC]

Comment: This pattern `^((?!(index|room)\.php).+)$` is already capturing URI in `$1` back reference. That you can use as a query parameter e.g. `room.php?u=$1`
Comment: does not seem to be working, it messes up all my css and image paths.
Comment: how do I capture the extra part of the url as a variable? For isntance `RewriteRule ^((?!(index|room)\.php).+)$ room.php$1 [L,NC]`
Comment: Hey thanks so much for the solution BTW, I have another question since you seem to know what you are talking about :). Is there a way with this solution to ensure that a trailing `/` (slash) is never present in the url at the end of it?
Comment: Yes sure trailing slash can be removed for all non directories in request, see my updated rule.


Unknown User Registered into my system

Question: I'm currently doing recruitment system by using drupal 7.. In my system, the user (anonymous) need to register before they can log in into the system. For log in and registration, i use LoginToboggan module. i also use the captcha module to avoid from spam.
However, when i look at the people..there is a lot of unknown user.. and it seems like spam.
what should i do?
Comment: Related: http://drupal.stackexchange.com/questions/68630/a-better-anti-spam-solution-for-drupal-7
Comment: Are you sure that you protect the registration form with CAPTCHA?
Comment: yes i am sure..what should i check to ensure my captcha is working?
Comment: I would also recommend you to set the user registrations to be approved by administrator. You can find this setting under `admin/config/people/accounts`
Comment: Did you go to the modules settings page (/admin/config/people/captcha) and enable the captcha for user registration form?
Comment: Maybe it's just my impression, but it looks like the captcha string is attached to the end of the username
Comment: @Astrayus Very unlikely...even if the bot cracked the Captcha, it'd be weird for it to re-submit the form with a different username than it had already submitted with
Comment: i set the user need to require a verification e-mail, but let users set their password directly on the registration form. am i choose the option for this?
Answer: These are robot spam registrations. To my eye, they look like they originate from XRumer.  XRumer knows how to complete the registration process of LoginToboggan and knows how to solve simple CAPTCHAs, so these measures will not stop XRumer from registering.
The modules I've found to be most effective against robot spam registrations are MotherMayI and CAPTCHA Riddler.
Both these are based upon the same idea: To register, the registrant should be able to answer a simple question where the answer is obvious to a human, but not to a robot.
If you site's language is not English, almost any question will work, since robots do not have multi-language skills.
CAPTCHA Riddler lets you set up a "pool" of questions (so a returning robot will face a different question on each visit).  MotherMayI only allows one question, but let you set up an RegExp for the answer and also has allows for a longer text to "hint" to a human what is expected.  I currently prefer MotherMayI, but check out both.
PS: So far, no spam robot has managed to register at any of my 20 sites (all that accepts registrations by the public are protected by MotherMayI).
Comment: so that's mean, the xrumer know how to complete the logintoboggan registration  module even there is a CAPTCHA?
Comment: @Izzwan Captcha has been broken for ages, probably best to move on to other prevention methods these days (or at least look at adding other methods alongside)
Comment: @Izzwan, CAPTCHA just means "Completely Automated Public Turing Test To Tell Computers and Humans Apart". There are different *types* of CAPTCHA you can use. However, XRumer knows how to complete the LoginToboggan registration module when there is a simple CAPTCHA of the type that distorts characters or poses math questions.  *Other* types of CAPTCHA (like those riddle based CAPTCHAs I suggest) still works on my sites.
Answer: If Captcha isn't working (and you definitely have it turned on, obviously), I'd recommend using something like Botcha instead:

BOTCHA is a highly configurable non-CAPTCHA spam protection framework.
In CAPTCHA, user has to prove he/she is human. Unfortunately, spambots learned
  to bypass CAPTCHA really well, and real users are frustrated with increasing
  complexity and burden of CAPTCHA.
In BOTCHA, we don't abuse our human users - BOTCHA protection is completely
  transparent to them and non-intrusive.
BOTCHA lets spambots to prove they are bots, and let real users zip by.

Works a lot better than Captcha in my experience, and less intrusive to the user. Bear in mind this is just one spam-prevention tool, depending on how hard your site gets hit you might have to take more drastic measures.
Answer: You can also consider using Honeypot or Mollom.

Honeypot uses both the honeypot and timestamp methods of deterring spam bots from completing forms on your Drupal site. These methods are effective against many spam bots, and are not as intrusive as CAPTCHAs or other methods which punish the user.

So, Honeypot has the same philosophy as Botcha (spam bot centered).
Mollom has Acquia / Dries Buytaert experience of Drupal behind and provides combined features: text analysis, spam database, then CAPTCHA if there is a doubt about the content + hidden honeypot feature. Several plans are proposed (free / paying), depending on the amount of spams and service wished.

Unknown User Registered into my system


Is fail2ban working without firewalld?

Question: do i need firewalld for fail2ban to work?
Can fail2ban block IP's with iptables only?
I've installed iptables-service on a CentOS 8 vps. I use nftables v0.9.3 (Topsy) to restrict/grant access. Firewalld is stopped and not running, but I guess fail2ban needs firewalld to block ip's?
Thanks for any hint or idea about this question.
Comment: Fail2ban works with iptables by default. However, installing fail2ban on CentOS 8 also installs fail2ban-firewalld (which changes that default) Even with a properly configured fail2ban jail, you won't see the expected results. fail2ban will log events as expected, but no traffic will be banned. I would suggest using fail2ban with iptables, but while you can find many articles on using iptables with failban to ban, there is little to no information on using firewalld with fail2ban and related configuration issues.
Comment: By default, fail2ban uses the [iptables interface](https://www.digitalocean.com/community/tutorials/how-fail2ban-works-to-protect-services-on-a-linux-server) to block IP addresses.
Answer: You can configure your fail2ban instance to specify which banning action it would use, thereby native net-filters are recommended (so firewalld is not advisable).
Which actions are available is depending on your fail2ban version, e. g. latest 0.10/0.11 have besides to several iptables also nftables action.
If you use nftables, it is also better to ban using nftables action (mostly iptables will just emulate nftables).
Also if your version is older (still does not have it), you can try to copy the latest version of action to /etc/fail2ban/action.d and try it.
To overwrite your defaults, simply set both banaction in default section of your jail.local:
[DEFAULT]
# default type of nftables is multiport: banaction = nftables[type=multiport]
banaction = nftables
banaction_allports = nftables[type=allports]

Comment: thank you so much. since fail2ban is new to me, i was not aware, that firewalld gets installed with fail2ban. I really would prefer workin with nftables only. I've set a couple of rules in my jail.local. Can I place the [DEFAULT] on top so every rule like [SSHD] or [apache] will use nftables?
Comment: thanks for pointing me at "banaction". I think that's the missing part in my config.
Answer: In addition to what serbes said, I must warn you.
It is true that fail2ban prefers raw iptables rather than ufw or firewalld or another higher-layer helper. But, if you have some rule saving/restoring mechanism (like netfilter-persistent in the Debian; I don't know how such thing is called in CentOS, sorry), there will be annoying catch. On restart, it will save fail2ban-added rules on the stop and restore them during startup, and fail2ban at the start will also add them again. So you'll end up with two identical fail2ban rule sets. On the next restart they will be multiplied again. And again.
This will not break things, but this somewhat obscures direct use of iptables. To conquer this you need to customise fail2ban actions. You need it to not install any firewall rules during jail startup, and then install these rules by hand and rely on your rule saving/restoring service. Also it's better to, say, set fail2ban to use ipset, and don't save ipsets by the rule saving service. This way everything will be clean.
Or, don't use rule saving/restoring service together with fail2ban.
Comment: One can surely filter f2b-* chains. It is also possible to create own chain or table like F2B (in nftables it is already the case), add it to input, prerouting or whethever chain you may need, and adjust configuration of fail2ban to set `chain=F2B` in local-conf as well as config of *-persistent services to ignore F2B (chain or table), or to filter it somehow. No idea how it is possible in netfilter-persistent, but it is definitely the issue of this service(s) and not of fail2ban.
Comment: nftables v0.9.3 is not netfilter right? I thought nftables replaces iptables in CentOS 8. I really would like to work with nftables, but I don't see any chains from f2b in nftables. That's why I installed iptables again, but the chains don't show up. Neither in nftables nor in iptables. So that's why I tried firewalld (which really is an overkill).
nftables uses a very simple set of rules on start. after that a script adds some more chains and rules to block some countries. so ideally, f2b creates a chain in nftables and blocks them on all ports. So I have to figure out the "banaction"
Comment: As for "but the chains don't show up" - fail2ban does it on demand (by first ban), see https://github.com/fail2ban/fail2ban/issues/1755#issuecomment-295286513 (and you can specify `actionstart_on_demand = false` in action config or supply it as parameter to banaction in order to do this on start)

Is fail2ban working without firewalld?


Henkin-style proof of first-order compactness

Question: In the comments to my answer to this post Noah Schweber mentioned a Henkin-style proof of the compactness theorem for first-order logic, based on a finitary satisfaction relation.  At his suggestion, I'm posting to ask to see the proof.  I'm particularly interested to see how this proof of compactness can help you engineer a sound and complete proof system.
Comment: Maybe you are interested in this semantic (and very elegant) [proof](https://mathoverflow.net/a/45498/102446).
Comment: @Taroccoesbrocco That one's not quite the same thing, but [Joel's answer](https://mathoverflow.net/a/45501/8133) to that question (of which I was unaware) does mention the argument I give below.
Comment: Thanks for the link to the MO post.
Answer: EDIT: An old MO answer of Joel David Hamkins mentions this argument briefly, and that question and its answers are quite interesting. Also I should clarify that this argument is very much not due to me - it seems to be folklore.

Let $\models_f$ be the finitary companion of the usual entailment relation $\models$: that is, $\Gamma\models_f\varphi$ iff $\Gamma'\models\varphi$ for some finite $\Gamma'\subseteq\Gamma$. This consequence relation is trivially compact, and we want to show that it coincides with $\models$.
As in the proof of the completeness theorem, we're going to set up a notion of term structure $Term(\Gamma;\models_f)$ assigned to an arbitrary finitely satisfiable theory $\Gamma$; we'll then argue that every theory $\Gamma$ is contained in a larger theory $\Gamma'$ such that $Term(\Gamma';\models_f)\models\Gamma'$ (and hence $\Gamma$).
Our term structures are defined in the obvious way:

The underlying set of $Term(\Gamma;\models_f)$ is the set of equivalence classes of closed terms in our language, under the equivalence relation $$t\approx_\Gamma^f s\iff \Gamma\models_ft=s.$$
The interpretation is given in the obvious way (e.g. for a term $t$ and a unary predicate $U$ we set $Term(\Gamma;\models_f)\models U([t])$ iff $\Gamma\models_fU(t)$), with well-definedness being straightforward to prove.

(Why closed terms? I just prefer to avoid free variables. This is purely a matter of taste. Note that we can always add a new constant symbol into our language, so WLOG there actually are closed terms in the language of our theory and so we get a nonempty term structure, or we could just allow structures to be empty in general.)
As in the proof of the completeness theorem, there's no reason to have $Term(\Gamma;\models_f)\models\Gamma$. So we need to fix this.
As before we'll look at two particular ways to "improve" a theory:

Every finitely satisfiable theory $\Gamma$ has a "$\models_f$-complete" extension - that is, a finitely satisfiable extension $\Gamma'\supseteq\Gamma$ such that for each $\varphi$ we have $\Gamma\models_f\varphi$ or $\Gamma\models_f\neg\varphi$. This is proved exactly as for $\vdash$ - just do a "greedy algorithm." The key point is that the result is in fact finitely satisfiable, and this holds since every finite stage was finitely satisfiable and finite satisfiability of a theory is determined by its finite fragments.
We can also Henkinize exactly as usual. If $\Gamma\models_f\forall x\exists y\varphi(x,y)$, we can add a function symbol $p_\varphi$ and pass to $\Gamma\cup\{\forall x\varphi(x, p(x))\}$, which is finitely satisfiable if $\Gamma$ itself is.

These two transformations together let us build, for $\Gamma$ an arbitrary finitely satisfiable theory, an extension $\Gamma'\supseteq\Gamma$ which is finitely satisfiable and $\models_f$-complete. We now prove that

$(*)$ for each $\psi\in\Gamma'$ we have $Term(\Gamma';\models_f)\models\psi$

by (a purely semantic) induction on complexity of $\psi$, and finish the proof by passing to the reduct to the original language of $\Gamma$.
Going through this argument with a fine-toothed comb, we can enumerate the properties $\models_f$ needs to satisfy in order for things to work out. For example, we need to have rules like "If $\Gamma\models_f\psi$ and $\Gamma\models_f\theta$ then $\Gamma\models_f\psi\wedge\theta$" in order to run the inductive proof of $(*)$. The consequence relation generated by all these rules is then trivially complete, and was "discovered organically" - there was never a worry that we might not find all the rules since we were literally just ripping them from an argument we already knew worked.
(This isn't quite fair - it's important to note that in addition to finitary closure properties, the argument above needed $\models_f$ to be finitary in order to construct $\models_f$-completions. But finitarity of our consequence relation is trivial, since it's generated by definition from finitary rules.)

Afterthought: One thing I really like about this argument is that it motivates the idea of taking a purely semantic consequence relation and studying its various "cousins," especially its perhaps-better-behaved fragments. This becomes a really important perspective in the study of infinitary logic, introduced by Barwise (see e.g. section $3$ of Keisler/Knight's wonderful survey). Perhaps more valuably it builds (at least, it did for me) an "aesthetic bridge" between the syntactic and semantic perspectives on consequence relations, which (again, at least for me) helps motivate their algebraic study which somehow falls (yet again, at least for me) in between the two
Comment: Thank you!  This is a very nice argument, especially for the reasons you describe in the "afterthought".  I always felt like it was sort of a stroke of good luck that someone happened to come up with an adequate proof system, but this argument makes it clear to me that one could have come up with the proof system along the way to proving the completeness theorem (I doubt that's the real history, but I always like feeling like things could be discovered by non-geniuses - of course, thinking to look at the finite consequence relation is clever too!).


Easiest Fetch request for getting just the 'latest' Single entity - core data

Question: I have a Parent <-->> Child relationship (to-many).
And the relationship is when i need to fetch all child(s), Parent.children = (NSSet *) child(s)
There are times when I just need only one, latest entity based on a timeStamp attribute of the Child entity.
I was wandering what would be the easiest way to fetch it, easier than say creating a fetch request and setting fetch limit One and using a sort descriptor to order it based on timeStamp.
Is there an easier way? just calling maybe :
[Parent.children firstObject];

The reason is I'm gonna need to fetch it many times, through out the life of the app. In some cases, i though i'd have to fetch the latest Child entity in the -(void)awakeFromFetch() of a Parent Entity.. and thats why i wanted to have a way thats more easier than anything else specially in terms of memory.

When Fetching Child entities, i kinda fetch a  bunch of them that are child to 2 or more Parent entities using this predicate :
NSPredicate *pred = [NSPredicate predicateWithFormat:@"forParent IN %@", [Array of Parents]];

From the resultant NSSet, since i'd get all the required Child entities for the said object,  it would be very convenient if  I could allot a pointer to a latest child in according to its timeStamp attribute (NSDate).
Obviously after I'd get the NSSet result i could iterate over each child and allot a pointer to the latest entity i find in the NSSet, but it looks pretty painstaking, though i'd have to allot just one pointer to the latest entity of a particular Parent , iterating an NSSet which potentially could have more than a hundred  entities seems bad programming.
Any ideas?
Comment: Instead of limit 1 and sort, I've used for similiar problem NSExpression with `max:` function. Other solution is to create in model on parent entity a latestChild property and set it when creating every new child. It's not ideal, but works and it's fastest solution.
Comment: could you elaborate a bit man? i didn't quite get 'creating in model on parent entity'
Comment: Let me explain :) you have two entities - Parent and Child. Add new property named latestChild to Parent entity in your model (MOM defined by xcode) and set this latestChild to child recently added to Parent.childrens. So, finally latestChild is direct relation to Child instead of calculated relation through predicates or iterations.
Comment: ups… not MOM but xcdatamodel :)
Comment: @thom_ek i did exactly that :) Instead of a property, I added another One-on-One relationship between Parent and Child, called it latestChild, in any case, i do have to iterate throw other child entities, and if i reach the last index count of the array, i just add it to the single latestChild relationship.
Answer: You have several options.  The fetch request, with fetchLimit = 1, sorted by time is actually not a bad option.  You can even make the timestamp field an INDEX in the model GUI, and the lookup will be super fast.
If the database will be constantly changing, and you always want access to the most recent item, consider registering for the DidSave notification on the NSManagedObjectContext.
You can get called when the context is saved (or even when there are changes to any object).  In the notification method, just look at the inserted items, and update to take the most recent value.
You can search the inserted objects, and grab the matching entity with the biggest timestamp.
The notifications for save and object change are:
NSManagedObjectContextDidSaveNotification
NSManagedObjectContextObjectsDidChangeNotification


WorldPay integration

Question: I am currently working a system whereby my users can pay for items that they have added to an order.
The payment will be using Worldpay.
I have a Worldpay account, but I am a little confused as to what steps I need to do next.
I am using symfony and I have an order, with products associated to it. I have then created a 'Pay Now' link, which links to a executePayment action.
What I'd really like, is for this to then take me to the hosted payment pages on Worldpay, pay for the order and then takes me back to my site to an order success page.
Has anyone implemented WorldPay using symfony before?
Thanks
EDIT:
So It seems, that I can have a form on the page where the Pay Now button is, but change it to a <input type="submit" /> and then post the details to https://secure-test.wp3.rbsworldpay.com/wcc/purchase
Is there some kind of callback functioanlity, to redirect me to a confirmation/failure page if the transaction was completed?
Thanks
Answer: WorldPay works like this...
1) You have a form on your website that collects your customer details. You then POST this data to https://secure-test.wp3.rbsworldpay.com/wcc/purchase
2) The customer will add their payment details in to WorldPay
3) Next, (depending on if the payment was successful or not) the user will be either directed to your resultY.html or resultC.html page that you can upload to your file management section within the WorldPay admin.
Alternatively you can supply a URL to a callback file on your server that is pinged when the customer clicks pay. This allows you to get information about the transaction and add it to your database.
With the callback page on your server, you can output a confirmation of payment, but you then have to include a link to physically get the user to come back to your site. I think automatically redirecting from this page is against Worldpay's T&Cs.
Hope this helps.
Philip
Answer: I user RBSWorldPay with Symfony - its very simple to setup - yes there is a callback function that you setup within the Settings of your RBSWorldPay account - you can also test by adding a test field - again check the RBS Documentation for testing.

WorldPay integration


How long would it take to bruteforce?

Question: I'm trying to reduce the solution space by excluding the wrong cases.
The original problem:
4851 choose 693 = 1.70E+862
Right now the possible combinations are (with n choose k):
1680 choose 420 = 4.36E+408
I'd attempt the bruteforce with a notebook, so it is not a powerhouse. I wonder if it is possible to find the solution now or should I try and reduce the available options further.
Update:
The problem is the following: I've got a set of graph nodes and some constraints. The goal is to connect the most nodes without violating the conditions.
Comment: What is your problem?
Comment: Updated the question.
Comment: How many of the combinations are valid solutions? If it's just a few like $10^{100} $ among the $\approx 10^{400} $ then forget about brute force.
Comment: My current theory is that there will be only one valid solution.
Comment: What are the constraints?
Comment: Working with strongly regular graphs. So there are 3 conditions: the count of edges, neighbours and non neighbours.
Comment: What are those counts?  Is there a constraint on the number of nodes?
Answer:
How long would it take

Assume it takes 1 nano second to construct a candidate and to check whether it is the solution. Then divide the number of all candidates by $2.25 \cdot10^{27}$ to get the time it takes to check all of them, where the unit is "age of the universe". Thus it takes around $$2 \cdot 10^{381} \text{ times the age of our universe}$$to brute-force check all possibilities.

How long would it take to bruteforce?


Specifying contrasts for lme in 3x3 repeated-measures design

Question: I would like to test the effects of two categorical variables, each with 3 levels, on some continuous data. Three groups of participants completed the same task for 3 types of stimuli, so it's a 3x3 repeated measures design. I'm using lme. The fixed-effects part of the model is the interaction between participant group ("play") and stimuli ("ins"), and the random-effects part is subject grouped within stimulus category.
contrasts(iqr$ins) <- contr.sum(3)
contrasts(iqr$play) <- contr.sum(3)
iqr.lme <- lme(iqr ~ play*ins, random = ~1|subject/ins, data = iqr)

I'm using sum contrasts and would like to see comparisons between each level of the "play" and "ins" variables. In other words, I would like to use a contrast matrix for each variable that looks like the one below. If I understand correctly, -1 is the reference level and 1 is the level compared to it. Specifying contr.sum only results in contrasts for the first two columns being given, however.
          [,1]  [,2]  [,3]
clarinet    1     0     1
piano       0     1    -1
violin     -1    -1     0

Here is the fixed effects part of the summary output:
Fixed effects: iqr ~ play + ins + play * ins
                 Value  Std.Error DF   t-value p-value
(Intercept)  2.9768519 0.11599299 66 25.664066  0.0000
play1       -0.0185185 0.16403886 33 -0.112891  0.9108
play2        0.2037037 0.16403886 33  1.241801  0.2231
ins1         0.1342593 0.09005357 66  1.490882  0.1408
ins2        -0.3240741 0.09005357 66 -3.598681  0.0006
play1:ins1  -0.3009259 0.12735498 66 -2.362891  0.0211
play2:ins1   0.0601852 0.12735498 66  0.472578  0.6381
play1:ins2   0.1574074 0.12735498 66  1.235974  0.2208
play2:ins2  -0.1481481 0.12735498 66 -1.163269  0.2489

If I understand correctly, ins1 is the contrast for clarinet vs. violin (using the contrast matrix above), and ins2 is the contrast for piano vs. violin. The problem is that I would also like to see a contrast for clarinet vs. piano.
My solution was to run a second model using a contrast matrix that I specified myself. I thought this would give me the missing contrast and replicate the clarinet vs. violin values from the original output.
cst1 <- cbind(c(-1,1,0), c(-1,0,1))
contrasts(iqr$ins) <- cst1
contrasts(iqr$play) <- cst1
iqr.lme <- lme(iqr ~ play*ins, random = ~1|subject/ins, data = iqr)
contrasts(iqr$ins)

          [,1]  [,2]
clarinet   -1    -1
piano       1     0
violin      0     1

Here, ins1 should correspond to clarinet vs. piano, right? But the values are the same as the ins2 contrast in my original output, indicating that the contrast matrix I specified was blatantly ignored and ins1 instead corresponds to piano vs. violin. The values for play2 and ins2 are new, and I could just assume that they indicate the contrast that was missing from the original output, but I would really rather understand what is going on than base my results on dubious assumptions!
Fixed effects: iqr ~ play * ins
                 Value  Std.Error DF   t-value p-value
(Intercept)  2.9768519 0.11599299 66 25.664066  0.0000
play1        0.2037037 0.16403886 33  1.241801  0.2231
play2       -0.1851852 0.16403886 33 -1.128910  0.2671
ins1        -0.3240741 0.09005357 66 -3.598681  0.0006
ins2         0.1898148 0.09005357 66  2.107799  0.0389
play1:ins1  -0.1481481 0.12735498 66 -1.163269  0.2489
play2:ins1  -0.0092593 0.12735498 66 -0.072704  0.9423
play1:ins2   0.0879630 0.12735498 66  0.690691  0.4922
play2:ins2  -0.2314815 0.12735498 66 -1.817608  0.0737

Am I misunderstanding how contrast matrices are read or specified? Or is there actually a way to get all the contrasts I want listed at once? I am fairly new to R and very new to nlme, so I could very well be missing something obvious. I hope this is enough information for someone to be able to help. Thanks a lot!
Answer: If you have a factor with $n$ levels, you can test $n - 1$ effects (at maximum) associated with this factor in one model.
Have a look at the sum contrasts. The function contr.sum(3) returns the following matrix:
  [,1] [,2]
1    1    0
2    0    1
3   -1   -1

The columns denote the contrasts. For a factor with $3$ levels, you obtain $2$ contrasts. Your interpretation of the contrasts is not correct. The first one tests the first level of the factor against levels 2 and 3. The second contrasts tests the second levels against levels 1 and 3.
You manually specified a contrast matrix with cbind(c(-1,1,0), c(-1,0,1)):
     [,1] [,2]
[1,]   -1   -1
[2,]    1    0
[3,]    0    1

This matrix also allows two tests. You test level 2 against levels 1 and 3. This is identical to the second test in the first matrix. Hence, you obtain the identical coefficient in both models. The second test of this contrast matrix is level 3 against levels 1 and 2.
If you want to compare levels against each other, there are two possibilities:

Treatment contrasts:
contr.treatment(3)

  2 3
1 0 0
2 1 0
3 0 1

Here, you test the first level against (a) the second and (b) the third one.
Repeated contrasts (sliding differences):
library(MASS)
contr.sdif(3)

         2-1        3-2
1 -0.6666667 -0.3333333
2  0.3333333 -0.3333333
3  0.3333333  0.6666667

Here, you test (a) the first level against the second one and (b) the second level against the third one. This matches the column names.

Please note that no contrast matrix will allow you to have more than $2$ contrasts for a factor with $3$ levels.
If you want to manually create an appropriate contrast matrix based on specific tests, you can use the ginv function from the MASS package:
cst1 <- cbind(c(-1,1,0), c(-1,0,1)) # your contrast matrix

library(MASS)
t(ginv(cst1))

       [,1]       [,2]
[1,] -0.3333333 -0.3333333
[2,]  0.6666667 -0.3333333
[3,] -0.3333333  0.6666667

The resulting matrix allows the tests you are looking for, i.e., level 2 against level 1 and level 3 against level 1.
For more details on how you can create a contrast matrix based on manually defined comparisons, have a look at this answer.


Factoring $x^{3}-6\in \mathbb{F}_{p}[x]$ when $p\equiv 1$ mod $3$.

Question: If $p\equiv 1$ mod $3$, I know that $x^{3}-6$ has any solution in $\mathbb{F}_{p}$ if and only if there exist $A,B\in\mathbb{Z}$ such that $p=A^{2}+3B^{2}$ and $9|B$ or $9|(2B+A)$ or $9|(2B-A)$ (This is one of the many conjectures of Euler). I have to show that, if this happens, then $x^{3}-6$ factors into different linear factors in $\mathbb{F}_{p}[x]$.
Answer: The answer doesn't have anything to do with $A$ and $B$. It's just that the multiplicative group of $\mathbb F_p$ is cyclic of order divisible by $3$, thus has three cube roots of unity. If there's one cube root of $6$, then there are three.


Is it possible to delete 15 ad groups in one second without PS?

Question: I deleted 2 user accounts in AD running on Windows 2016 (pdc), time stamp is around 1:05:00 pm, then the users report cannot access the share drive on a domain member file server.
Then I found in event log shows I deleted over 10 groups in ONE SECOND at 15:05:16, I haven't done such things and never use script.

I was test GPO (add and delete) at that time, is this caused such error ?
Apart from operation error, any other possibilities will cause over 10 groups deleted in 1 second which looks not like a human's action?
What reason should use in incident report?

I Googled, only use PS may cause such action, is this true? Maybe a bug?
Comment: How can we answer what happened without having access to logs?
Comment: Incident report: Im not sure why my rights have been misused. There is no way I can explain what happened. And I'm not sure why I have so many rights, that I can do this.' aslong as you dont overcome with [ask] its at current sate offtopic - and `yes it is possible to wipe an entire AD within milliseconds.`
Answer:
NO, If you used the default "User and computers" interface? and deleted them one at the time
YES, if you accidentally did a multi-select and have forgotten you had the groups selected

If the eventlog show you deleted the groups, there is little left for debate :)
You could include that the deletions "were unintended" and it led to "unanticipated problems"
Comment: So much effort into this post and its responses - a simple "I goofed" in the incident report with a 30 second "Restore-ADObject" is much more efficient.
Answer: It could be a system glitch or even an undetected script running amok. In your incident report, maybe chalk it up to an unidentified system anomaly while testing GPOs. Definitely keep digging, maybe even check with the Microsoft community or support
Comment: Highly unlikely.


How to make a slide in UIViewTableCell

Question: I am trying to create a UITableView so that When the user touches my normal UIViewTableCell another UIViewTableCell slides in from the right side with a new cell format. This new UIViewTableCell does not leave the UITableView.
The UIViewTableCells are 2 different custom Cells.
I was wondering if there is a way to swap one UITableViewCell that is of X type for another UITableViewCell that is of Y type with an animated sliding effect?
I've looked at the following code but I do not understand where do I place my Cell information.
[tableView beginUpdates];
[tableView deleteRowsAtIndexPaths:myIndexPaths
                 withRowAnimation:UITableViewCellRowAnimationRight];
[tableView endUpdates];
[tableView beginUpdates];
[tableView insertRowsAtIndexPaths:myNewIndexPaths
                 withRowAnimation:UITableViewCellRowAnimationLeft];
[tableView endUpdates];

Any guidance on how to do this is highly appreciate it.
PS: I am not looking for a repo. I would like to understand how this is done.
Comment: Unless I misunderstood the question, I would have all the data in one custom cell. That custom cell has a UIScrollView just large enough to carry the content of two cells. And then just put initialize it appropriately and have it scrolled in. That can be done even withtout the scroll view of course, but I think using a scroll view is much easier for you.
Comment: The alternative without: Put all your stuff in a container. Just a UIView. That serves as your content view. You could have one UIView subclass for each custom table view cell subclass that you currently have, but you would go on with only one custom talble view cell subclass that does not do mutch itself but carrying this very container (or subclasses of it respectively). Before you change the content, create a new container right off screen to the left. Then have both containers animated to the right by the width of the cell. After that release (nil) the old content container. Done.
Comment: @HermannKlecker I though about `UIScrollView` but I would prefer using `UITableViewCells` as they are easy to style and know for future projects
Comment: UITableViewCells as they are cannot do the trick. You could try creating a new UITableViewCell and then "transfer" the content view from the new cell to the old one and then release the new cell. After that do the animation get rid of the old content view. As you cannot easily re-link the new text view to the old cell etc (the related properties are readonly) you may have to move the labels and uiimage from the old content view to the new one and discard the subviews of the new content view after copying the data over. But that does not sound too easy as you are using custom cells anyway ...
Answer: Basically the way table view cell animation works is you update your data source (usually an array that you reference when providing cells to the table view), then call the animation methods. The table view calls numberOfRowsInSection and cellForRowAtIndexPath when you insert a cell, so it's important that they return the correct values.
In this situation, however, the number of cells remains the same so you can't use insertion and deletion. You can use cell reloading, however. Theoretically, every time didSelectRowAtIndexPath is called you would add to a list of tapped index paths that should display the new kind of cell. Alternatively, if you only want one of these special cells present at a time, you would use a single NSIndexPath variable. Then you would call
[tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationRight]; //or left

Then, in cellForRowAtIndexPath, you would check to see if the particular row requires a different type of cell, and you would return that new type there. That way, the code you need to present the new type of cell is insulated from the initializing of the new cell.
Hope this works for you!

How to make a slide in UIViewTableCell


Proof of $M$ Noetherian if and only if all submodules are finitely generated

Question: Is my proof of proposition 6.2 on page 75 correct? (it's different from what they do in the book)
Proposition 6.2.: $M$ is a Noetherian $A$ module $\iff$ every submodule of $M$ is finitely generated.
My proof:
$\implies$ Assume $M$ has a submodule $N$ that is not finitely generated. Say, $N = \langle \bigcup_{i=1}^\infty \{ n_i \} \rangle$. Then the following is an increasing chain that is not stationary: $\langle n_1 \rangle \subset \langle n_1, n_2 \rangle \subset \langle n_1, n_2, n_3 \rangle \subset \dots$
Hence $M$ is not Noetherian.
$\Longleftarrow$ Assume $M$ is not Noetherian. Then there is a non-stationary increasing chain of submodules $N_1 \subset N_2 \subset \dots$. Then $N = \bigcup_{k=1}^\infty N_k$ is a submodule. If $N$ was finitely generated, $N_k$ would be stationary. Hence $N$ is a submodule that is not finitely generated.
Comment: You might consider doing [this](http://meta.math.stackexchange.com/a/3590/2614).
Comment: @BrunoStonek So I should post this as an answer?
Comment: @BrunoStonek Usually, people manage to write more than just "yes" to my questions.
Comment: I did not express any views on the subject, I just directed you to a meta question that is very related, and to the (only) answer, which was quite well received by the community. If you're worrying about preventing good answers by others by doing what is suggested in that post, then don't worry! There can be multiple answers to one question, no? If someone has something interesting to add, they can always do it, no matter if you posted your intended solution in the question or in an answer.
Comment: @BrunoStonek Ok : )
Answer: The first part is not quite correct: you have assumed $N$ is countably generated.
The second part looks good, though you should make sure you know why the fact that $N$ is finitely generated implies that the sequence is stationary.
Comment: But if $N$ is generated by an uncountable set, couldn't you just pick out a countable set and make the exact same argument? I would think you would also have to make some statement about the non-redundancy of generators too, or minimality of the generating set.
Comment: I agree with Colin.  If feels strange to me to write down a generating set when you are assuming $N$ is not finitely generated.  After all, why not just write $N = \langle \cup_{n \in N} n \rangle$.  You are right to be worried about redundancies, though that is an issue in your proof as well.  Try this:  choose elements $n_i \in N$ inductively so that $n_i \not\in \langle n_1, \ldots, n_{i-1}\rangle$...
Comment: I did indeed assume that it's countably generated, of course without intending to. Thank you!
Comment: But what do you think of unit3000-21's suggestion to fix my proof?
Comment: @ClarkKent Take a look at Benjamin's answer below this one.  I think that ties up any loose ends.
Comment: @unit3000-21 Yes, thanks. I did and I understand it now.
Answer: Your first part is strange. I would rephrase the argument as follows: Suppose that $M$ is a Noetherian $A$ - module and there exists a submodule $N$ that is not finitely generated. Now choose $f_1 \in N$. Since $N$ is not finitely generated, $\langle f_1 \rangle \subsetneqq N$ and so we can choose $f_2$ such that $f_2 \in N - \langle f_1 \rangle$. By the same argument as before, we can choose $f_3 \in N - \langle f_1,f_2\rangle$ such that $\langle f_1,f_2,f_3 \rangle \subsetneqq N.$ We now have a chain of submodules of $N$ (and hence of $M$) such that
$$\langle f_1 \rangle \subsetneqq \langle f_1,f_2 \rangle \subsetneqq \ldots \subsetneqq \langle f_1,f_2,f_3 \rangle $$
contradicting the ACC.
Comment: You may want to formalise the choosing process using the axiom of choice though.


Probability of rolling 3 mutually exclusive dice

Question: Suppose I have 3 dice. Each has some mechanism that can prevent other dice being in the same number as itself when they are rolled together. Now I roll the 3 dice at the same time. Then what is the probability of having a 2 appear?
Is the answer 1/6 + 1/6 + 1/6 = 1/2 since the event are mutually exclusive and each has a probability of 1/6? But 1/2 seems to be too high?
Comment: What do you mean "at least"??? According to your description, there cannot be more than a single occurrence of each value.
Comment: This question has generated a kilometre of LaTeX! But the answer is obvious: If exactly three different numbers are rolled, the probability of a specific number belonging to those three is $\frac36$.
Comment: thank you, it should be there is a 2 appear
Comment: @TonyK: Nice! That's actually a cleaner explanation than the "traditional" combinatorics type of answers (such as my own answer in this case).
Comment: ADD: If the 3 dice can only prevent 2 from from appearing in other dice if itself is 2 but not other number. Should the probability change? Is the event of 2 appearing in each of three dice still mutually exclusive.
Comment: The metaphor of dice is not a good one here, it makes it unclear what the distributions are.  Better to say "Suppose I have six cards with values 1 to 6.  If I randomly draw three of them, what is the probability that I draw a 2?"
Comment: Or, "I roll 3 dice until each die has a different number.  What is the probability of having a 2 appear at the end?"  This makes it clear that each of the ${6 \choose 3}$ combinations occurs with equal probability.
Answer: Because a dice prevents the same number from appearing on another dies means that you can roll only those combinations which contain distinct numbers. The number of such combinations is $^6\mathrm{C}_3 \times 3!$
Number of such combinations with $2$ in them are $^5\mathrm{C}_2 \times 3!$
So the probability that $2$ appears on one of the dies is $\dfrac{^5\mathrm{C}_2 \times 3!}{^6\mathrm{C}_3 \times 3!} = \dfrac{1}{2}$
Yes the answer is $\frac{1}{2}$
Answer: Think of it as selecting 3 items in the set $\{1,2,3,4,5,6\}$ which can be done in $6\choose3$$=20$ ways.
Convince yourself that this is the sample space (and not $6^3$)
Now, at least one 2, means that there is ONLY one 2 and 2 always appears (since these magical die makes sure 2 doesnt appear in the other two)
That would leave us with choosing 2 out of $\{1,3,4,5,6\}$ which is $5\choose2$$ = 10$
The probability is $\frac{10}{20} = \frac{1}{2}$
$1/2$ is most definitely very high, but you are thinking about the sample space $6^3$. Out of 20 possibilities 2 appears 1/2 the time, which makes sense because, each number either appears or does not (because of the mutual-exclusiveness) and if you calculate for other numbers (1,3,...) you'll notice that the answer is 1/2 as well.
Note: Im assuming the order of the die don't matter. If they do, multiply and divide by $3!$
Answer: The total number of combinations is $\dbinom{6}{3}\cdot3!=120$
The number of combinations with 2 in them is $\dbinom{5}{2}\cdot3!=60$
So the probability of getting a combination with 2 in it is $\dfrac{60}{120}=\dfrac{1}{2}$


How to use SQL Server table hints while using LINQ?

Question: What is the way to use Sql Server's table hints like "NOLOCK" while using LINQ?
For example I can write "SELECT * from employee(NOLOCK)" in SQL.
How can we write the same using LINQ?
Answer: Here's how you can apply NOLOCK: http://www.hanselman.com/blog/GettingLINQToSQLAndLINQToEntitiesToUseNOLOCK.aspx
(Quote for posterity, all rights reserved by mr scott):
ProductsNewViewData viewData = new ProductsNewViewData();
using (var t = new TransactionScope(TransactionScopeOption.Required,
    new TransactionOptions {
        IsolationLevel = System.Transactions.IsolationLevel.ReadUncommitted
    }))
{
   viewData.Suppliers = northwind.Suppliers.ToList();
   viewData.Categories = northwind.Categories.ToList();
}

Answer: I STRONGLY recommend reading about SQL Server transaction isolation modes before using ReadUncommitted.
Here's a very good read
http://blogs.msdn.com/b/davidlean/archive/2009/04/06/sql-server-nolock-hint-other-poor-ideas.aspx
In many cases level ReadSnapshot should suffice. Also you if You really need it You can set default transaction isolation level for Your database by using
Set Transaction Isolation Level --levelHere

Other good ideas include packaging Your context in a wrapper that encapsulates each call using demanded isolation level. (maybe You need nolock 95% of the time and serializable 5% of the time). It can be done using using extension methods, or normal methods by code like:
viewData.Categories = northwind.Categories.AsReadCommited().ToList();

Which takes your IQueryable and does the trick mentioned by Rob.
Hope it helps
Luke


If X and Y are perfectly correlated, what is the correlation of X+Y and X-Y?

Question: I've started with thinking that if X and Y are perfectly correlated, then it is the same as looking at the correlation of Y and -Y (since the X provides no new information) and thus the correlation is -1.
Is this correct?
Comment: Your reasoning is flawed.
Comment: If $X$ and $Y$ have a correlation coefficient  of $\rho$ then $X$ and $Y$ have a correlation coefficient  of $-\rho$.  If  $X$ and $Y$ are "perfectly correlated" (i.e. knowing $X=x$ you can be almost sure $Y=a+bx$ for some fixed $a,b$) then $\rho=+1$ or $-1$ but without more information you cannot tell which
Comment: No reason why it can't be 1. Perfect correlation only says that Y=aX+b. If a is positive the correlation is 1 and it is -1 if a is negative. So what you need to do is find the correlation between (1+a)X+b with (1-a)X-b.
Comment: If a=1 the correlation is 0. But if a is not 1 it can be determined using my argument..
Answer: Hint: In general, \begin{align}
\rho_{A,B} &= \frac{\operatorname{cov}(A,B)}{\sqrt{\operatorname{var}(A)\operatorname{var}(B)}},\\
\operatorname{var}(X\pm Y)&= \operatorname{var}(X)+\operatorname{var}(Y)
\pm 2\operatorname{cov}(X,Y),\\
\text{and}\qquad\operatorname{cov}(X+Y,X-Y)&=\operatorname{var}(X)-\operatorname{var}(Y)\end{align} So, work out what $\rho_{X+Y,X-Y}$ is in general, and in the special case when $Y = aX+b$. You might be surprised at the result.
Comment: @JPMSpoof :  You would only get a denominator of zero from assuming equal variance.  Perfectly correlated is not the same as equal variance.  For instance, $Y = 5X$ yields perfect correlation with unequal variance.
Comment: Using those properties, I came out to Var(X) - Var(Y) / 0? The denominator all cancelled out but that cannot be right as the denominator being 0 means that the correlation is undefined?
Comment: No, the denominator is $\sigma_{X+Y}\sigma_{X-Y}$ which in the special case $\rho_{X,Y}=1$ makes $\sigma_{X\pm Y}= \sigma_{X}\pm \sigma_Y$ leading to $$\rho_{X+Y,X-Y}=\frac{\sigma_X^2-\sigma_Y^2}{(\sigma_X+\sigma_Y)(\sigma_X-\sigma_Y)}=1.$$
Comment: @EricTowers The answer I provided might give some insight into the denominator of zero issue, perhaps?
Answer: I'll treat this as self-study, and I'd encourage you to read its wiki and add the tag.
Your argument is already very good. Here are a few pointers. Feel free to write a comment so we can discuss and work towards a good answer.

I assume you are looking at Pearson's correlation, right? (Does your argument work for other measures of correlation?)
What does a perfect correlation mean graphically?
What will $X+Y$ and $X-Y$ look like graphically if $X$ and $Y$ are perfectly Pearson-correlated?
Comment: @Stephan I don't think the argument in the question is good at all. Consider X,Y bivariate normal with zero mean and Var(X) = $10^4$ Var(Y). Then X+Y is approximately X and X-Y is approximately X, and the OP's answer of -1 is as wrong as could be. Now consider zero means and Var(X) = Var(Y), in which case X-Y is always 0 and the correlation is undefined.
Comment: Yes I am looking at Pearson's correlation. I know perfect correlation means the X-Y scatterplot follows a perfectly straight line, so now I imagine as X+Y increase, and X-Y decrease, the correlation will be negative
Comment: @Glen_b Please check your assertion that $X-Y$ is always $0$ when $X$ and $Y$ are perfectly correlated (cf. my comment to the OP in response to his comment on my answer).
Answer: I see this already has an accepted answer, but I've always liked simulations more than equations, and this seemed like a fun question. I generated a variable $x$ from a distribution $N(0, 1)$ whose sample size $n$ was drawn from $U(100, 10000)$. To make $y$, I simply added a constant—drawn from $U(1, 100)$—to $x$. I then calculated the correlation between $X + Y$ and $X - Y$. I did this 10,000 times:
set.seed(1839)
cors <- sapply(1:10000, function(placeholder) {
  n <- runif(1, 100, 10000)
  b0 <- runif(1, 1, 100)
  x <- rnorm(n)
  y <- b0 + x
  cor(x + y, x - y)
})

You'll get a ton of warnings. I run warnings()[1:5] to get the first five:
Warning messages:
1: In cor(x + y, x - y) : the standard deviation is zero
2: In cor(x + y, x - y) : the standard deviation is zero
3: In cor(x + y, x - y) : the standard deviation is zero
4: In cor(x + y, x - y) : the standard deviation is zero
5: In cor(x + y, x - y) : the standard deviation is zero

We can still look at the histogram of correlations that were defined, calling hist(cors[!is.na(cors)]):

We can also look at how many of those simulations had the $Var(X - Y) = 0$:
set.seed(1839)
sd_is_zero <- sapply(1:10000, function(placeholder) {
  n <- runif(1, 100, 10000)
  b0 <- runif(1, 1, 100)
  x <- rnorm(n)
  y <- b0 + x
  ifelse(var(x - y) == 0, TRUE, FALSE)
})

Then we can call prop.table(table(var_is_zero)) to see how many simulations generated $Var(X - Y) = 0$:
var_is_zero
 FALSE   TRUE
0.1698 0.8302

But why were some defined and some undefined? Was it related to the sample size or was it related to the constant?
set.seed(1839)
dat <- as.data.frame(matrix(nrow = 10000, ncol = 3))
colnames(dat) <- c("var_is_zero", "n", "b0")
for (i in 1:10000) {
  n <- runif(1, 100, 10000)
  b0 <- runif(1, 1, 100)
  x <- rnorm(n)
  y <- b0 + x
  dat$var_is_zero[i] = ifelse(var(x - y) == 0, TRUE, FALSE)
  dat$n[i] = n
  dat$b0[i] = b0
}

We can now predict whether or not the variance was zero from the sample size, the constant, and the interaction, looking at the result with summary(glm(var_is_zero ~ n * b0, data = dat, family = binomial())):
Call:
glm(formula = var_is_zero ~ n * b0, family = binomial(), data = dat)

Deviance Residuals:
    Min       1Q   Median       3Q      Max
-2.5154   0.1628   0.3039   0.5997   1.2894

Coefficients:
              Estimate Std. Error z value Pr(>|z|)
(Intercept) -2.613e-01  1.038e-01  -2.518   0.0118 *
n           -2.114e-05  1.785e-05  -1.184   0.2362
b0           5.323e-02  2.973e-03  17.907   <2e-16 ***
n:b0        -4.011e-07  4.968e-07  -0.807   0.4195
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

(Dispersion parameter for binomial family taken to be 1)

    Null deviance: 9111.4  on 9999  degrees of freedom
Residual deviance: 7148.0  on 9996  degrees of freedom
AIC: 7156

Number of Fisher Scoring iterations: 6

It looks like the larger the intercept, the more likely the correlation is to be undefined.
Comment: By `y <- b0 + x`, you implicitly set $\sigma_Y=\sigma_X$, which is not implied by the condition. The result will be well-defined if you use $\sigma_X\neq\sigma_Y$.
Answer: $X,Y$ perfectly correlate $\implies Cov(X,Y)=\sqrt{Var(X)Var(Y)}$
$Cov(X+Y,X-Y)=Cov(X,X)-Cov(X,Y)+Cov(Y,X)-Cov(Y,Y)=Var(X)-Var(Y)$
$Var(X+Y)Var(X-Y)=[Var(X)+Var(Y)+2Cov(X,Y)][Var(X)+Var(Y)-2Cov(X,Y)]=[Var(X)+Var(Y)]^2-4Cov(X,Y)Cov(X,Y)=_{\rho_{X,Y}=1}=[Var(X)+Var(Y)]^2-4Var(X)Var(Y)=[Var(X)-Var(Y)]^2$
Hence, $\rho_{X+Y,X-Y}=Cov(X+Y,X-Y)/\sqrt{Var(X+Y)Var(X-Y)}=\pm1$.
As @whuber pointed out, when $Var(X)=Var(Y)$, $\rho_{X+Y,X-Y}$ is undefined.
@Dilip Sarwate has provided the answer in the comment to his post. I added some details.
Actually, if $Var(X)=Var(Y)$, given they are perfectly correlated, $Y=\pm X+b$, hence either $X+Y\equiv0$ or $X-Y\equiv0$. Therefore, $\rho=0$.
Comment: @whuber You are right, I forgot to mention this special case.
Comment: When $\operatorname{Var}(X)=\operatorname{Var}(Y)$, the denominator is $0$, whence the correlation is undefined in that case.
Answer: If $X$ is a linear function of $Y$ (definition of perfect correlation), then both $X-Y$ and $X+Y$ will be linear functions of $Y$, and therefore are linear functions of each other.
So, $X-Y$ and $X+Y$ are perfectly correlated.
Comment: I still on't see why it can't be -1.
Comment: Obviously if one or both of $X-Y$, $X+Y$ are constant, the answer is undefined. I assumed that's not the case while writing this answer.
Comment: @MichaelChernick, I meant to say they were perfectly correlated. Thanks.


Tautology And Substitution

Question: Let $ \alpha $ be some proposition, and let $ A = \alpha $, and let $ B = \neg \alpha $.
Is the statement $ A \lor B $ a tautology?
Answer: Obviously, $α ∨ ¬α$ is a tautology.
But - in general - $A∨B$ is not a tautology.
The "rule" is:

every instance of a tautological schema will be a tautology.

In other words, given a tautological schema, like $\varphi \lor \lnot \varphi$, every formula obtained via substitution from it, like $p_1 \lor \lnot p_1$ or $\forall x Q(x) \lor \lnot \forall x Q(x)$, will be a tautology.
Comment: So letters (or symbols) have to be independent in a sense that they don't contradict?
Comment: @Joseph - we have to take care about the difference between formula of the (formal) language, made with connectives and propositional letters (or variables): $p_1,p_2,\ldots$ and schema of the meta-language, like e.g. $A \lor \lnot A$ where $A$ stay for a *formula*.

Tautology And Substitution


Android Studio 3.2.1 não localiza "Default Activity"

Question: Pessoal estou com esse problema desde o Android 3.2. Já fiz os seguintes procedimentos para tentar fixar o problema:
- Já fiz clean e rebuild do projeto
- Já limpei o cache e reiniciei o Android Studio
- Já fiz sync com o Gradle (esse funciona, mas só deixa instalar o app uma única vez, depois dá erro de novo)
- Já apaguei e recriei o projeto várias vezes (nunca adianta)

Podem me dar uma ajuda? Já nem sei mais o que fazer. Seguem os prints abaixo.
Comment: Dê preferencia a postar o código, não imagens... aqui no Sopt utilizamos seu proprio codigo para lhe ajudar
Answer: Você poderia fazer alguns testes?

No OnCreate() da sua BaseActivity setar o contentView.
setContentView(R.layout."SeuLayout")
Tentar setar na mão qual activity é seu launcher, seguindo o seu segundo screenshot, onde está "Default Activity" muda para "Specified Activity" e no campo abaixo seleciona sua base activity.
Answer: Tente zerar o Cache do Android Studio em:
File -> Invalidate Caches / Restart...
Caso não funcione, certifique-se que todos os caminhos de SDK, JRE e NDK, estão atualizados e apontando para os caminhos corretos de instalação. Em:
File > Project Structure > SDK Location
E os pacotes de versão do SDK em:
File > Settings > Apperance & Behavior > System Settings > Android SDK


I want to add the Bootstrap CONTAINER to WPBakery Page Builder and don't want to use the already available SECTION element instead

Question: I'd developed a wordpress plugin with addons for WPBakery Page Builder sometime back and over the time I was getting some suggestions from its users so decided to build some of those into my plugin...
You could please check more details regarding the purpose of that plugin at https://wordpress.org/plugins/using-visual-composer-support-for-twitter-bootstrap-themes/
I was trying to add a new element "Container" (https://getbootstrap.com/docs/4.3/layout/overview/#containers) which would almost work like the already existing "Section" element in WPBakery Page Builder but with somewhat less options.
You could please check the code I've written to achieve the above at the following link...
https://github.com/gitfaraz/WPBakery-Page-Builder-for-Twitter-Bootstrap-Themes/blob/master/bootstrap4/bs_container.php
Following is the code from that file...
add_action('init', 'bs_container');
function bs_container() {
    class WPBakeryShortCode_Bs_Container extends WPBakeryShortCodesContainer{

        // Element Init
        public function __construct(){
            add_action('vc_before_init', [$this, 'mapping']);
            add_shortcode('bs_container', [$this, 'output']);
        }

        public function mapping(){
            vc_map(array(
                'name' => esc_html__('Container', 'js_composer'),
                'base' => 'bs_container',
                'class' => 'vc_main-sortable-element',
                'show_settings_on_create' => false,
                'category' => esc_html__('Bootstrap', 'js_composer'),
                'icon' => 'vc_icon-vc-section',
                'description' => esc_html__('Group multiple rows in container', 'js_composer'),
                'is_container' => true,
                'js_view' => 'VcSectionView',
//              'as_parent' => array(
//                  'only' => '',
//              ),
//              'as_child' => array(
//                  'only' => '', // Only root
//              ),
                'params' => array(
                    array(
                        'type' => 'checkbox',
                        'heading' => esc_html__( 'Full height section?', 'js_composer' ),
                        'param_name' => 'full_height',
                        'description' => esc_html__( 'If checked section will be set to full height.', 'js_composer' ),
                        'value' => array( esc_html__( 'Yes', 'js_composer' ) => 'yes' ),
                    ),
                    array(
                        'type' => 'el_id',
                        'heading' => esc_html__( 'Section ID', 'js_composer' ),
                        'param_name' => 'el_id',
                        'description' => sprintf( esc_html__( 'Enter element ID (Note: make sure it is unique and valid according to %sw3c specification%s).', 'js_composer' ), '', '' ),
                    ),
                    array(
                        'type' => 'checkbox',
                        'heading' => esc_html__( 'Disable section', 'js_composer' ),
                        'param_name' => 'disable_element',
                        // Inner param name.
                        'description' => esc_html__( 'If checked the section won\'t be visible on the public side of your website. You can switch it back any time.', 'js_composer' ),
                        'value' => array( esc_html__( 'Yes', 'js_composer' ) => 'yes' ),
                    ),
                    array(
                        'type' => 'textfield',
                        'heading' => esc_html__( 'Extra class name', 'js_composer' ),
                        'param_name' => 'el_class',
                        'description' => esc_html__( 'Style particular content element differently - add a class name and refer to it in custom CSS.', 'js_composer' ),
                    ),
                    array(
                        'type' => 'css_editor',
                        'heading' => esc_html__( 'CSS box', 'js_composer' ),
                        'param_name' => 'css',
                        'group' => esc_html__( 'Design Options', 'js_composer' ),
                    )
                )
            ));
        }

        public function output($atts, $content = NULL ) {
            $output = ('
'.do_shortcode( shortcode_unautop( $content ) ).'
');
            return $output;
        }
    }

    new WPBakeryShortCode_Bs_Container();
}

The problem I am having is that its not adding in the backend as I want. When I try to add it to the backend, it adds wrapped within the ROW and COLUMN which I do not want to happen. I want it to add into the backend just like the WPBakery Page Builder's already available SECTION element...
If you could than please download and install the plugin files from https://github.com/gitfaraz/WPBakery-Page-Builder-for-Twitter-Bootstrap-Themes so that you could better understand the issue and so will be able to help me in a better way to achieve what I want.
I know there is someone out there who can help me with this in the best way possible and I will be happy to add his/her/their names to the list of Contributors & Developers section on my Wordpress Plugin page.
I could alter the already existing SECTION element with 'vc_map_update()' (https://kb.wpbakery.com/docs/inner-api/vc_map_update/) but that might be irritating for WPBakery Page Builder users so wanted to add a completely new and standalone CONTAINER element.
Please check the attached snap which I've created to help you better understand the issue...
Comment: Please let me know if you found the solution?
Comment: All the details are there in my question. Those offsite links are only to support what I've mentioned in my question so that the viewers could better understand the issue, please check.
Answer: When you unminify the code of "assets > js > dist > backend.min.js" in "js_composer" plugin directory and look into line 1408 you will find the following code with two occurences of "vc_section:
(e = e.closest("[data-preset]")) && (preset = e.data("preset"), presetType = e.data("element")), !1 === this.model ? (window.vc.storage.lock(), "vc_section" === tag ? (e = { […] && "vc_section" === presetType

You can change these lines and add your own element here. Example: If your Element is called "vc_carousel_father" you add an OR-condition. Just replace "vc_section" === tag with ("vc_section" === tag || "vc_carousel_father" === tag) and "vc_section" === presetType with ("vc_section" === presetType || "vc_carousel_father" === presetType)
After that your Element "vc_carousel_father" behaves like a root-container.
Important: To do this you have to modify a core-file of WPBakery. After an update your modifications might be gone or WPBakery stops working. I'm looking for a way to hook this instead of modifying corefiles and keep you posted.
I've also added more info to this task and about the status-quo of it in this thread here: Is a custom "Row" Element for WPBakery (Visual Composer) possible?

Another method you can try is this:
Write a watchscript for the variable "content" in backend. In this variable the content of the wysiwyg editor is stored dynamically. If the content changes and contains your element, you could write a regular expression that detects it, finds the wrapped-around [vc_row][vc_column] shortcodes and deletes it. This method produces a relatively high JS-load in the browser, but it works.
Some methods for observing variables can be found here: https://lage.us/Javascript-Watch-Variables-for-Change.html
Your script needs to be called via wordpress "admin_enqueue_scripts" hook in your theme's functions.php file


If I is an ideal of R (considering I as an additive subgroup of R), elements of the factor ring/group (R/I).

Question: If I is an ideal of R (considering I as an additive subgroup of R), how do the elements of the factor group (R/I) relate with the elements of the factor ring (R/I)?
I know that, If I is an ideal of R, then R/I has a well-defined multiplication: For r, s contained in R, define (r + I)(s + I) = rs + I.
My assumption is that the elements of the factor group (R/I) are equal to the elements of the factor ring (R/I) but I'm not too sure why. Any suggestions would help.
Comment: You are right. As a set both are same, I mean on the group $R/I$ you are giving some additional structure.
Answer: A good way to think about why this is, is that both the quotient group and quotient ring result from treating everything from the ideal like it's zero, so they should give you the same set.


Univariate cox regression hazard ratio in SPSS

Question: I'm currently doing some analysis for a retrospective cohort study of biomarkers in cancer patients. I've noticed that some papers have utilized univariate cox regression analysis to generate a hazard ratio with confidence intervals. However in some of these papers, they've generated a single hazard ratio with CI's for categorical variables with more than 2 categories.
reference: http://www.ncbi.nlm.nih.gov/pubmed/25575264
My questions:
(1) How does one even generate a single HR for a variable with more than 2 variables? This doesn't seem to make sense?
(2) How does univariate cox regression compare to cox-mantel/log rank? Are they very similar?
Comment: For a 3 category predictor in which no ordering of levels is assumed, you must have 2 hazard ratios.  And why would unadjusted (univariable) hazard ratios be of any interest?
Comment: The variables in question with more than 2 categories seem to be T, N, TNM stage, and the modified Glasgow Prognostic Score (mGPS). Most likely the authors treated all these as numeric rather than categorical variables in some of their tables, and the survival curves suggest that this use of numeric scores might have modeled the data fairly well in this case.
Comment: Taking TNM stage as an example, the issue is whether each unit increase of stage adds the same increase in hazard ratio, not whether stage is a continuous variable. Figs. 1A and 3A in the paper suggest that this might not be too bad a model for cancer-specific survival in this case, while Figs 1C and 3C might support your understanding that stages I and II have similar _overall_ survival, both better than stage III. I don't think you can know _a priori_ whether treating these variables as numeric is good or bad; that's a question to answer by examining how well the data are modeled.
Comment: Log-rank tests are score tests for the hazard ratios from a Cox regression model with a single categorical predictor. Perhaps referencing one of the papers would help someone answer your first question.
Comment: I've added the paper of interest. Traditionally in cohort studies in medical literature, univariate analysis is used to screen for variables to be used in multivariate analysis. Although there are pitfalls to this methodology, it remains the standard approach and therefore unavoidable if you want to be published.
Comment: This seems to be a rather strange choice as neither of those variables are meaningful as continuous variables. Indeed the increase from stage 1 to 2 and 2 to 3 have a drastically different meaning clinically.  From what I understand of numeric vs categorical variables - in numeric - the hazard ratio describes the increased risk with each increase of 1 unit. However as increased stage does not possess a linear or even exponential relationship in regards to survival - is the overall choice to utilize a numeric variable poor?
Answer: (1) One HR for multi-valued categorical variables
In the cited paper on colorectal cancer, some variables were listed as multi-valued categorical but only had single hazard ratios (HRs) presented in Cox proportional-hazards survival analysis. The variables in question were: T (tumor size), N (tumor spread to lymph nodes), TNM stage (a combined assessment of disease severity), and the modified Glasgow Prognostic Score (mGPS). These are ordered clinical classifications presented as integer values, following standard practice (although TNM stage is usually represented by Roman numerals and in some types of cancers there are subtypes a, b, etc, for certain classifications).
A single HR can be obtained for each of these classifications if they are treated as numeric values in the Cox regression. If each extra step along an ordered categorical scale contributes the same multiplicative change in hazard ratio, then there is no harm in treating that categorical variable as numeric.
Analysis as numeric variables is almost certainly why only a single HR is presented for each of these classifications; what is uncertain from my reading of the paper is whether this was a deliberate or an accidental choice. In a cursory reading of the paper I also did not find results of diagnostics or validations of the models that might have helped evaluate whether this was a good choice.
As you note, in colon cancer there is generally a large jump in mortality between TNM stage II and stage III, with much less of a jump between stage I and stage II. That would undercut the numeric analysis of stage. Figure 1C and 3C in the paper, on overall survival, seem to support your contention, but the figures on cancer-specific survival (1A and 3A) seem pretty well fit by an equal-step-per-class model.
Whether the numeric treatment of such an ordered classification is appropriate can best be addressed in light of how well it models the data. As models are all approximations to reality at best, it's possible that the errors introduced by such numeric treatment are balanced by other advantages, provided that the validity of the model is not adversely affected. For example, numeric treatment of such a variable has the advantage of only using one degree of freedom, rather than 2 or more if treated as a multi-level factor.
(2) Cox regression and log-rank tests
As @Scortchi put it simply in a comment: "Log-rank tests are score tests for the hazard ratios from a Cox regression model with a single categorical predictor." I find these lecture notes to be a short explanation directly on point, with useful extensions to different tests. The tests are asymptotically equivalent, although their results of course may differ in any particular data set.
Historical note: I discovered item (1) by accident when I was analyzing a data set to produce the unadjusted univariate hazard ratios that are still typically demanded by clinical journals despite their dubious usefulness. Having a large number of both categorical and numeric predictor variables, I wrote a script to automate the process, taking advantage of the ability of R to deal well with both types of variables. I was initially shocked to obtain only a single HR for each of T, N, and TNM stage. Of course these variables had been entered as numbers and, in my poorly designed script, R interpreted them as numeric variables even though I had been thinking of them as ordered categories. What was perhaps more surprising, until I thought about it, was that these numerically-treated categorical variables bore reasonable relations to outcome. Those HRs for the numeric treatment of the data made it into the final publication (carefully annotated as having been analyzed numerically, of course, along with reports on diagnostics and model validation).


Prove some statements about projective modules

Question: A module $_RU$ is projective module its annihilator in case $U$ is a projective $R/l_R(U)$ module.
Prove that these are equivalent:
(a) $_RU$ is projective module its annihilator;
(b) $U$ is a projective $R/I$ module for some ideal $I\subseteq{l_R(U)}$;
(c) $U$ is $U^A$-projective for every set $A$.
I have proved that $(a)\Rightarrow(b)$ and $(b)\Rightarrow(c)$, but I can't prove that $(c)\Rightarrow(a)$. Could any body give me some help? Thanks a lot!
Comment: It is a question in GTM13 page 13,the 15th question
Answer: Proof (1) To prove $(a)\Rightarrow(b)$, we just need to take $I=l_R(U)$.
$(b)\Rightarrow(c):$  $U$ is a projective $R/I$ module, so $U^A$ is a $R/I$ module. And by the definition of projective module,for any epimorphism $g: M\rightarrow N$ and each homomorphism $f:U\rightarrow N$, there is a homomorphism $h:M\rightarrow U$ such that $f=gh$.Since $g$ is epic, then $U^A/ker {\ g}$ is isomophic to $N$. Thus $N$ is an $R/I$ module.Therefor by $(b)$, we can get that for any epimorphism $g: {U^A}\rightarrow N$ and each homomorphism $f:U\rightarrow N$, there is a homomorphism $h:U\rightarrow U^A$ such that $f=gh$.Therefor $U$ is $U^A$-projective for any set $A$.
$(c)\Rightarrow(a):$ Since for any set $A$, $_RU$ is $U^A$-projective,then $_{R/l_R(U)}U$ is $U^A$-projective.
Because $_{R/l_R(U)}U$ is the generator of $_{R/l_R(U)}M$ and $_{R/l_R(U)}U$ is $U^A$-projective for any set $A$. Therefore $U$ is projective $_{R/l_R(U)}U$ module. Thus $_RU$ is projective modulo its annihilator.
(2) To prove these statements, we just need to reverse the arrows in (1).


List installed packages in channel

Question: With PHP's PEAR, how can I check whether package foo in channel bar is already installed?  (Assuming that the channel bar is available, and has already been "discovered".)  Something like pear list that displays installed packages in channel bar only would be ideal.
Answer: pear list -c bar

Comment: Use `pear list -a` to list installed packages in *all* channels.

List installed packages in channel


Generating Mini Text Dump LInux

Question: Following question describe for windows
How to create minidump for my process when it crashes?
But how can I create mini crash  text dump on linux ?
Answer: You need to write a signal handler.
Here is a slide deck on how to do it:
http://www.scribd.com/doc/3726406/Crash-N-Burn-Writing-Linux-application-fault-handlers
Here is the code form the slide deck:
https://github.com/gby/libcrash
Answer: I'm not sure you can get the exact same thing as a .NET MiniDump - but you will be able to produce a core dump on Linux that should get the information you are after. Make sure that core files are enabled by issuing a command such as:
ulimit -c unlimited

This will also set the maximum size of core dumps to be unlimited - you can tailor this as you wish to achieve the 'mini' aspect of your question. man ulimit is your friend here.
Then, run your process and while you it is running kill it. The signal I usually send is SIG_ABRT (Signal 6) as so:
kill -6 <pid>

If you don't know what the pid is, or how to get a pid, you probably need to read up some more on Linux.
Comment: Make sure your code is compiled with the `-g` flag (debug symbols) so you can make sense of the core dump. You can also use the signal's name (without the `SIG` prefix) to `kill` so you don't have to memorize the numbers: `kill -ABRT `
Comment: Thanks for the additions, Mike!
Comment: I am already generating core dump but I want to generate a small readable text dump

Generating Mini Text Dump LInux


Non-linear relationship among independent variables in linear model

Question: Assume that we have a linear model with 4 independent variables, and 2 of them have a strong non-linear relationship (between them). How this fact could affect my model ($R^2$, or implications on the robustness of the model)?
It is a question that popped up to my mind while working with linear regressions. Any tips?
Comment: Does this answer your question? https://stats.stackexchange.com/questions/63730/how-to-test-for-multicollinearity-among-non-linearly-related-independent-variabl
Comment: Partially; I would expect a non-linear relationship amongst some of the independent variables to have some effect on the model. But, that's just my assumption as no mathematical proof is involved.

Also, I said partially because the data that he created in the example exhibit high autocorrelation; which violates one of the regression principles for the residuals. Also, I think inflates R^2
Answer: When you refer to a "linear model" I take that to mean an ordinary least squares model with linear adjustment for four regressors. If the relationship with the predictors is in fact non-linear then there are a number of ways forward:
First solution: just leave them as-is. The resulting model gives biased predictions and has heteroscedastic errors, but so what? Maybe the model performance is good enough, and has the added benefit of being simple and easy to communicate. The R^2 is not interpreted as a fraction of variance "explained" but as the mean-squared error of predictions. The risk of doing this is that, when validating the model in independent data, there may be a shift in distribution of the regressors, and domains in which the heteroscedastic model performed poorly may be overrepresented.
Second solution: include higher order terms or breakpoints (splines). Splines are highly adept polynomial approximations that can capture most forms of non-linearity. The benefit is that they are easy to fit, and they are possible to interpret. They need not dramatically complicate the model. The problem is that they can be somewhat difficult to communicate. For instance, with a quadratic trend, there are many features of interest such as the location of the inflection point, and the magnitude of trend at various levels of the regressor(s). It is a subtle point to calculate these things and present their confidence intervals.
Comment: 'If the relationship with the predictors is in fact non-linear' do you mean the relationship AMONGST the predictors?
Or between the dependent variable and the predictors? Because I care for the first interpretation rather than the latter.


Button.Click event doesn't fire after TextBox.Leave event

Question: I use the below code to verify if the text into a TextBox was changed and ask for saving changes:
Private TBoxTxtBefore As String = String.Empty

Private Sub TextBox1_Enter(ByVal sender As Object, ByVal e As System.EventArgs) Handles TextBox1.Enter
    Try
        TBoxTxtBefore = CType(sender, TextBox).Text
    Catch ex As Exception
        MsgBox(ex.ToString)
    End Try
End Sub

Private Sub TextBox1_Leave(ByVal sender As Object, ByVal e As System.EventArgs) Handles TextBox1.Leave
    Try
        If CType(sender, TextBox).Text <> TBoxTxtBefore Then
            Dim SN As MsgBoxResult = MsgBox("Save changes?", vbYesNo, "Save Changes")
            If SN = vbYes Then Btn_SaveChanges.PerformClick()
        End If
    Catch ex As Exception
        MsgBox(ex.ToString)
    End Try
End Sub

But when I click a button (for example button1) while the cursor is inside TextBox1, only TextBox1.Leave event was raised.
How can I have Button?.click event raise after TextBox1.Leave event?
Comment: Edit this question and show the button1 click event as well as Btn_SaveChanges click event.
Answer:
How can I have button1.click event raise after TextBox1.Leave event?

If TextBox1 has the focus and you click a button the leave event will fire before the click event.  To test click in Texbox1, then click Button1.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Debug.WriteLine("B1C")
End Sub

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
    Debug.WriteLine("B2C")
End Sub

Private Sub TextBox1_Leave(sender As Object, e As EventArgs) Handles TextBox1.Leave
    Debug.WriteLine("TBL")
    Button2.PerformClick()
End Sub

Try to clarify your question please.
edit:  This recreates the problem I think you are having,
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Debug.WriteLine("B1C")
End Sub

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
    Debug.WriteLine("B2C")
End Sub

Private Sub TextBox1_Leave(sender As Object, e As EventArgs) Handles TextBox1.Leave
    MessageBox.Show("FOO")
    Debug.WriteLine("TBL")
    Button2.PerformClick()
End Sub

Did some searching and found that the Message box causes pending focus events to be lost.
Comment: button1.click event isn't fired
Comment: Edit your question and show the button1 click event as well as Btn_SaveChanges click event.
Comment: Button1.click is for example. Everywhere I click no event is raised after `TextBox1.Leave`
Comment: Did you try the example I posted?  Does it work?  You have to post at least one buttons code or we can't help.
Comment: Ok you found the issue (+1). I tried removing the msgboxes and the event was fired. Now is there any way to fire the event without removing the confirmation msgboxes?
Comment: I accepted your answer because you showed me the way to get the button clicked by referencing the focus and so the active control. ;)
Comment: @genespos - a solution would depend on how many other user events could be triggered with the user in the textbox.  How complicated is the form?
Comment: I solved using Me.Activecontrol at the top of leave event
Comment: @genespos - post your fix as an answer so that if others have the problem they will know how to fix it.
Answer: Thanks to dbasnett's hints I was able to get the name of the control that fired the Leave event, so to call it (if it's a button) after the Message Box was showed:
Private Sub TextBox1_Leave(ByVal sender As Object, ByVal e As System.EventArgs) Handles TextBox1.Leave
    Try
        Dim FiringCtrl As Control = Me.Activecontrol
        If CType(sender, TextBox).Text <> TBoxTxtBefore _
           AndAlso FiringCtrl.Name <> "Btn_SaveChanges" Then
            Dim SN As MsgBoxResult = MsgBox("Save changes?", vbYesNo, "Save Changes")
            If SN = vbYes Then Btn_SaveChanges.PerformClick()
            If TypeOf FiringCtrl Is Button Then
                DirectCast(FiringCtrl, Button).PerformClick()
            End If
        End If
    Catch ex As Exception
        MsgBox(ex.ToString)
    End Try
End Sub

Anyway Plutonix showed me a better solution here
Answer: You can call multiple events one after the another. Your TextBox1_Leave event could trigger Button1_click event.
Private Sub TextBox1_Leave(ByVal sender As Object, ByVal e As System.EventArgs) Handles TextBox1.Leave

  'Take the control to another sub. Pass the sender control and the event details as arguments
  Call Button1_Click(sender,e)

End Sub

Private Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
'Do your stuff here

End Sub

Hope this helps.
Comment: But I don't know what event I need to raise. It doesn't matter where I click, the only event raised is `TextBox1.Leave` and not the other I've clicked.
Comment: This isn't **firing the event**. This is just calling another method. Also this just doesn't address the OP's question.