Logging out issue

Question: How can i prevent users who have logged out from accessing their account when they try to access their account by clicking the browser previous-page button?
Currently, users can access their previous session by simply clicking the previous page button. how can i prevent this, thus, they get redirected to the log in form/page?
Comment: I found an open [drupal core issue](http://drupal.org/node/197786) for D6 that seems to be related. Comment #193 explains that it may be a hosting issue (which would mean that it applies to any version of Drupal) and there are various suggestions for fixes.
Comment: Are users actually able to access their session or are they just able to view a version of their profile page that has been cached by their web browser?
Comment: Hi, I've just checked and it seems they are just cached pages. is there a way of preventing this?
Comment: btw, I'm currently hosting my site on my localhost. So am not sure whether its a hosting issue in my case. thanks for the link though, was quite informative.
Answer: There's nothing that can be done to correct this, it's a browser caching issue. When you hit the back button, it loads the original HTML from the cache, not the modified HTML.
Answer: Others have already mentioned that this is a caching issue, not a Drupal issue. Two thoughts:

Blocking the 'back' viewing of previous pages  would conceptually be
possible if the cached page (The one you clicked 'logout' on)
contains Javascript that checks if the back button was pressed to
arrive at that page. If 'Yes', then force a refresh or check for
active credentials before allowing the display.
If you set appropriate Cache-Control headers and always generate an EXPIRED time in
the past (example here) on all pages that display the 'logout'
link, you can control this behavior in browsers that choose to
comply.

Method #1 seems complex and could be impossible. #2 might be a 'best fit' but certainly not bulletproof. I would weigh the effort that is required to continue down this road against the overall concern you have of client machines storing cached pages.

Logging out issue


GCSFuse - Fusermount: mountpoint is not empty

Question: Using gcsfuse to mount a point locally on a server within a script. Running on an Ubuntu 14 LTS server.
I have two fuse mount points and the script transfers data from other mount points into them.
This script is working for one of the mountpoints, but is not working for the second.
gcsfuse --debug_fuse bucket /mnt/gcloud-bucket
Using mount point: /mnt/gcloud-bucket
Opening GCS connection...
Opening bucket...
Mounting file system...
daemonize.Run: readFromProcess: sub-process: mountWithArgs: mountWithConn: Mount: mount: running fusermount: exit status 1

stderr:
fusermount: mountpoint is not empty
fusermount: if you are sure this is safe, use the 'nonempty' mount option

I checked my script for syntax errors, and its identical to the working one, and I tried running the command in the shell, and it continues to return the error.
I also tried rebooting to clear the mounts, but that did not resolve.
If I go to the /mnt/gcloud-bucket the data from the cloud is all there and mounted, and I can browse it, but it does not appear in the mount -l output.
I also tried doing a umount but the mount is not found.
Thanks,
Cam
Answer: If your mount command output shows that there is nothing mounted on the path, it means the files are stored on the parent filesystem.
So, in order to fix this, you need to remove the files from the directory before running the script again.
Comment: Alternatively, you can pass the `nonempty` option when invoking the command to have the local files removed automatically: `gcsfuse -o nonempty bucket /mnt/gcloud-bucket`
Comment: And that was it, I mv'd the folder and recreated the mnt folder, and my script is running like a charm.


Conflito ao carregar jQuery na página

Question: Creio que esteja com algum conflito de jQuery.
Tenho nesta página, entre outros, o link

Quando eu comento esta linha, a página aparece, conforme esta imagem. Quero que fique assim,

mas o menu acordion e faq acordion não funcionam.
Se eu descomentar este link do Ajax o menu e faq acordion voltam a funcionar, mas o cabeçalho fica como esta imagem.

Como descobrir onde esta o erro? Como consertar isto?
OBS.: Não entendo nada de jQuery
Comment: Olá, Rico, você é livre para [edit] sua pergunta e acrescentar novas informações. Não pode converter a pergunta em outra coisa, mas não tem problema nenhum em fazer updates quando alguém faz um comentário pedindo mais informação. Como pode ver, aqui nos comentários o código fica ilegível...
Comment: Eu não entendi sua dúvida, mas poste seu código fonte aqui, que com certeza conseguiremos te ajudar melhor.
Comment: Consegue postar o código?
O que esta acontecendo é que sem o jquery ele não converte os itens (tipo a lista de seleção) e quando você usa ele, é gerado os componentes. Você vai ter que fazer as correções de layout no CSS
Comment: O que você não quer que apareça na imagem ? não ficou claro
Comment: O código completo é longo, como sou novato, não sei se é permito postar script longo
Comment: O código quase completo é de 388 linhas, como posso enviar se o limite aqui é pequeno?
Comment: Se você abrir a página no chrome e apertar `F-12`, aparece algum erro no `console` ou na aba `Network`? Caso a `Network` esteja vazia, recarregue a página com o console aberto.
Comment: @RicoGaucho dá uma olhada nesse artigo http://imasters.com.br/artigo/13871/jquery/evitando-conflitos-com-jquerynoconflict/
Comment: no chrome não aparece erro.
quanto ao artigo, eu já havia lido algo parecido, mas não sei onde exatamente é o conflito.
Comment: Pode postar o HTML. Pelo menos o trecho do select que está mudando quando ativa a jquery...
Answer: Você pode tentar usar a tag de retirar conflito https://api.jquery.com/jquery.noconflict/ como no link do jQuery.
Mas creio que seja alguma classe do seu AJAX que está usando essa classe. É melhor se publicar algumas linhas do código para nos ajudar a resolver o problema...
Comment: Olá, Dom. Aqui as assinaturas são proibidas, preencha seu perfil que seu avatar vai aparecer em todas suas respostas e perguntas. Essa é nossa assinatura. Valeu!
Comment: Retirado de todos.. Vou mudar Obrigado.

Conflito ao carregar jQuery na página


Prove $\lim\limits_{x \to \pm\infty}\dfrac{x^3+1}{x^2+1}=\infty$ by the definition.

Question: Problem
Prove $\lim\limits_{x \to \pm\infty}\dfrac{x^3+1}{x^2+1}=\infty$ by the definition.
Note:
The problem asks us to prove that, no matter $x \to +\infty$ or $x \to -\infty$, the limit is $\infty$,which may be $+\infty$ or $-\infty.$
Proof
$\forall M>0$,$\exists X=\max(1,M+1)>0, \forall|x|>X$:
\begin{align*}
\left|\frac{x^3+1}{x^2+1}\right|&=\left|x-\frac{x-1}{x^2+1}\right|\\&\geq |x|-\left|\frac{x-1}{x^2+1}\right|\\&\geq |x|-\frac{|x|+1}{x^2+1}\\&\geq |x|-\frac{x^2+1}{x^2+1}\\&=|x|-1\\&>X-1\\&\geq M.
\end{align*}
Please verify the proof above.
Comment: It's basically correct, but I dislike how you've written it.
Comment: The default meaning, in all sources that I know (and in how I teach) is that $\lim_{x \to \infty}$ is like $\lim_{x \to 1}$ in that we suppress writing the $+$ sign, *even though* our intention is $\lim_{x \to +\infty}$ or $\lim_{x \to +1}$.
Comment: @mengdie1982 That's a fun communication barrier I wouldn't have expected. Thank you for the clarification. Since many users (the bulk of users probably -- given the answers you've already received) of this site have an alternate interpretation of that notation, would you mind adding that detail to your question? I think it'll prevent a lot of responses like the non-applicable answers you've seen.
Comment: Your inequalities look fine, but, your setup is fishy. For example, there should be no absolute value signs around the $x$. Also, the expression with the existential quantifier $\exists X$ is part of the *statement you are proving*, whereas the assigned value $X = \text{Max}(1,M+1)$ is part of the *proof that $X$ exists*. Mixing up the statement and the proof, as you have done, is a bad idea.
Comment: @LeeMosher We should consider $|x|$,not $x$, because the limit is under the process $x \to \infty$ not $x \to +\infty.$
Comment: @LeeMosher I have seen that usage in complex variables courses before, or something like it. If it's tagged `real-analysis`, maybe they're using something closer to the one-point compactification of the reals for their infinity? Dunno which author does that though, and I agree that it's super non-standard.
Comment: In China's teaching for calculus, especially in Chinese textbooks,$x \to \infty$ implies $x \to +\infty$ AND $x \to -\infty.$ But $n \to \infty$ only implies $n \to +\infty$, because that notation is for sequence limit only.
Comment: @HansMusgrave OK! I accept your advice. THX.
Answer: Your proof is correct.
You may consider shorter proofs by using some simplifications.
Since $x\to \infty $ we assume $x>1$
$$ \frac {x^3+1}{x^2+1} \ge\frac {x^3}{2x^2}=x/2$$
Comment: Your inequality goes in the wrong direction for the statement being proved.
Comment: Thanks, I fixed it to the right direction
Comment: Wait! $|x|\geq1$ does not imply $|x^3+1| \geq |x^3|.$ You may have $|x^3+1|\geq |x^3|-1.$
Comment: But,thus,you also need to consider $x<0$...
Comment: Thanks. I had positive $x$ values in mind.
Answer: Your proof looks ok to me.
An option:
$x^3+1=(x+1)(x^2-x+1);$
$x^2+1<x^2+x =x(x+1)$, for $x >1$.
$\dfrac{(x+1)(x^2-x+1)}{x^2+1}>$
$\dfrac{(x+1)(x^2-x+1)}{x(x+1)}=$
$x-1+1/x >x-1.$
Answer: Possibly correct but unreadable.
Consider
$$
\frac{x^3+1}{x^2+1}=x-\frac{x-1}{x^2+1}>x
$$
whenever $x>1$.
Comment: but you should consider the absolute value...
Comment: @mengdie1982 And so? For $x>0$, $\frac{x^3+1}{x^2+1}>0$.
Comment: but what if $x<0$?
Comment: @mengdie1982 You have to compute the limit at $\infty$, so it is not restrictive to assume $x>0$.


Select Records based on Count of Child Records Matching Specified Criteria

Question: I have two Tables in an SQL 08 database:

Clients
Balances

ClientID (foreign key to clients)
isStartingBalance (bit)

Using SQL, I need to locate and update all Balance Records where the Client the Balance Record belongs to has only one balance record, and that balance record has isStartingBalance=0. I need to update those records so that isStartingBalance=1.
How might I go about doing this?
Thanks in advance.
Answer: You can use a subquery to find clients with only one balance row:
update  Balances
set     isStartingBalance = 1
where   isStartingBalance = 0
        and ClientID in
        (
        select  ClientID
        from    Balances
        group by
                ClientID
        having  count(*) = 1
        )

Or more sensibly, you can update the oldest balance row for each customer:
update  bal
set     isStartingBalance = 1
from    (
        select  row_number() over (
                    partition by ClientID
                    order by dt) as rn
        ,       *
        from    Balance
        ) bal
where   rn = 1
        and isStartingBalance = 0

Example at SQL Fiddle.
An even more sensible solution would be to remove the isStartingBalance column entirely, and query for it when you need it:
select  ClientID
,       dt
,       case when rn = 1 then 1 else 0 end as isStartingBalance
from    (
        select  ClientID
        ,       dt
        ,       row_number() over (
                    partition by ClientID
                    order by dt) as rn
        from    Balance
        ) SubQueryAlias

Comment: Thanks Andomar. I think your first example will work for my case.


SQL Server : can we find out who has renamed database?

Question: Is there any way in SQL Server 2012 to identify who has changed the database name? Is there any audit log or some thing that would help?
Comment: @variable perhaps you should be looking at *why* this happened. *Why* doesn't every developer have his own server installation for coding? SQL Server Dev is free. *Express* has all programability features of Enterprise nowadays. Keeping changes in sync doesn't justify using a single database. If you do so, it means you have a version control problem easily solved by using SSDT, Database Projects and any kind of version control, like Git
Comment: try [this](http://stackoverflow.com/questions/5299669/how-to-see-query-history-in-sql-server-management-studio)
Comment: The rename can be done via UI and also via SQL script. Do you know if there is any sort of audit log?
Comment: SQL Server can be configured to audit a lot of things https://learn.microsoft.com/en-us/sql/relational-databases/security/auditing/sql-server-audit-database-engine
Answer: The rename operation will be written to TLOG no matter how you do it.
I did a small test and renamed a database. This rename operation is written to the TLOG as you can see in below screenshot:

You can read the log and know the name using this query:
<code>select
    suser_sname([transaction sid]) as username,*
from
    fn_dblog(null,null)
</code>
This is subject to below clauses

Your master db is in full recovery model
Even if your master db is not in full recovery model, you may get that data, if that is not truncated

Also note reading log on live production database is not recommended, so I advise taking backups of TLOG and reading them seperately


ScrollView in both directions android

Question: I have a layout with scrollview:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fillViewport="true"
    android:fadingEdge="none"
    android:overScrollMode="never"
    >
<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:weightSum="100"
    android:background="@color/antiquewhite">
        <LinearLayout
        android:id="@+id/top_layou"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:orientation="vertical"
        android:layout_weight="15"
        android:layout_marginLeft="40dp"
        android:layout_marginRight="40dp"
        android:layout_marginTop="25dp"
        android:background="@color/bisque">

        <TextView
            android:id="@+id/title_text_view"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="70dp"
            android:layout_marginTop="15dp"
            android:text="@string/user_information_text"
            android:textSize="26dp"
            android:textStyle="bold"
            android:textColor="@color/black" />

        <TextView
            android:id="@+id/subtitle_text_view"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="70dp"
            android:layout_marginTop="5dp"
            android:text="@string/user_information_subtitle_text"
            android:textSize="20dp"
            android:textStyle="bold"
            android:textColor="@color/black"/>

    </LinearLayout>

        <LinearLayout
            android:id="@+id/body_view"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="85"
            android:orientation="horizontal"
            android:layout_marginLeft="40dp"
            android:layout_marginRight="40dp"
            android:weightSum="100"
            >

            <LinearLayout
                android:id="@+id/left_part"
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:orientation="vertical"
                android:layout_weight="50"
                android:weightSum="100"
                android:background="@color/antiquewhiter">

                <TextView
                    android:id="@+id/first_name_text_view"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginLeft="70dp"
                    android:layout_marginTop="30dp"
                    android:text="@string/first_name_text"
                    style="@style/bold_text18"
                    />

                <LinearLayout
                    android:id="@+id/first_name_edit_layout"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:weightSum="100">

        <EditText
            android:id="@+id/first_name_edit_text"
            style="@style/editTextsvCard"
            android:layout_marginLeft="70dp"
            android:layout_marginTop="5dp"
            android:layout_weight="90"
            android:ems="10"

            >

        </EditText>

                </LinearLayout>

                <TextView
                    android:id="@+id/company_text_view"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginLeft="70dp"
                    android:layout_marginTop="30dp"
                    android:text="@string/company_text"
                    style="@style/bold_text18" />
                <LinearLayout
                    android:id="@+id/company_edit_layout"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:weightSum="100">

        <EditText
            android:id="@+id/company_edit_text"
            style="@style/editTextsvCard"
            android:layout_marginLeft="70dp"
            android:layout_marginTop="5dp"
            android:layout_weight="90"
            android:ems="10"
             >

        </EditText>

                </LinearLayout>
                               <TextView
                    android:id="@+id/phone_text_view"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginLeft="70dp"
                    android:layout_marginTop="30dp"
                    android:text="@string/phone_text"
                    style="@style/bold_text18"/>
                <LinearLayout
                    android:id="@+id/phone_edit_layout"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:weightSum="100">

        <EditText
            android:id="@+id/phone_edit_text"
            style="@style/editTextsvCard"
            android:layout_marginLeft="70dp"
            android:layout_marginTop="5dp"
            android:layout_weight="90"
            android:ems="10"
            android:inputType="phone"
            >

        </EditText>

                </LinearLayout>

                           <TextView
                    android:id="@+id/e_mail_text_view"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginLeft="70dp"
                    android:layout_marginTop="30dp"
                    android:text="@string/e_mail_text"
                    style="@style/bold_text18" />
                <LinearLayout
                    android:id="@+id/e_mail_edit_layout"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:weightSum="100">

        <EditText
            android:id="@+id/e_mail_edit_text"
            style="@style/editTextsvCard"
            android:layout_marginLeft="70dp"
            android:layout_marginTop="5dp"
            android:layout_weight="90"
            android:ems="10"
            android:inputType="textEmailAddress"
            >

        </EditText>

                </LinearLayout>

                             <TextView
                    android:id="@+id/mobile_text_view"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginLeft="70dp"
                    android:layout_marginTop="30dp"
                    android:text="@string/mobile_text"
                    style="@style/bold_text18"/>
                <LinearLayout
                    android:id="@+id/mobile_edit_layout"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:weightSum="100">

        <EditText
            android:id="@+id/mobile_edit_text"
            android:layout_marginLeft="70dp"
            android:layout_marginTop="5dp"
            style="@style/editTextsvCard"
            android:layout_weight="90"
            android:ems="10"

             >

        </EditText>

                </LinearLayout>
            </LinearLayout>

            <LinearLayout
                android:id="@+id/right_part"
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_weight="50"
                android:paddingRight="40dp"
                android:orientation="vertical"
                android:weightSum="100"
                android:background="@color/antiquewhiter">

                <TextView
                    android:id="@+id/last_name_text_view"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginLeft="70dp"
                    android:layout_marginTop="30dp"
                    android:text="@string/last_name_text"
                    style="@style/bold_text18" />
                   <LinearLayout
                    android:id="@+id/last_name_edit_layout"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:weightSum="100">

        <EditText
            android:id="@+id/last_name_edit_text"
            android:layout_marginLeft="70dp"
            android:layout_marginTop="5dp"
            android:layout_weight="100"
            android:ems="10"
            style="@style/editTextsvCard"
            >

        </EditText>

                </LinearLayout>

                <TextView
                    android:id="@+id/position_text_view"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginLeft="70dp"
                    android:layout_marginTop="30dp"
                    android:text="@string/position_text"
                    style="@style/bold_text18"/>
                   <LinearLayout
                    android:id="@+id/position_edit_layout"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:weightSum="100">

        <EditText
            android:id="@+id/position_edit_text"
            android:layout_marginLeft="70dp"
            android:layout_marginTop="5dp"
            android:layout_weight="100"
            android:ems="10"
            style="@style/editTextsvCard"
           >

        </EditText>

                </LinearLayout>

                   <TextView
                    android:id="@+id/fax_text_view"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginLeft="70dp"
                    android:layout_marginTop="30dp"
                    android:text="@string/fax_text"
                    style="@style/bold_text18"/>
                   <LinearLayout
                    android:id="@+id/fax_edit_layout"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:weightSum="100">

        <EditText
            android:id="@+id/fax_edit_text"
            android:layout_marginLeft="70dp"
            android:layout_marginTop="5dp"
            android:layout_weight="100"
            android:ems="10"
            android:inputType="phone"
            style="@style/editTextsvCard"
             >

        </EditText>

                </LinearLayout>

                   <TextView
                    android:id="@+id/internet_text_view"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginLeft="70dp"
                    android:layout_marginTop="30dp"
                    android:text="@string/internet_text"
                    style="@style/bold_text18"/>
                   <LinearLayout
                    android:id="@+id/internet_edit_layout"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:weightSum="100">

        <EditText
            android:id="@+id/internet_edit_text"
            android:layout_marginLeft="70dp"
            android:layout_marginTop="5dp"
            android:layout_weight="100"
            android:ems="10"
            style="@style/editTextsvCard"
             >

        </EditText>

                </LinearLayout>
                                   <TextView
                    android:id="@+id/b_text_view"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginLeft="70dp"
                    android:layout_marginTop="30dp"
                    android:text="@string/internet_text"
                    style="@style/bold_text18"
                    android:visibility="invisible"
                    />

                   <LinearLayout
                    android:id="@+id/button_edit_layout"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:weightSum="100"
                    android:layout_gravity="right"
                    android:gravity="right">

        <Button
            android:id="@+id/speichern_button"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginTop="5dp"
            android:layout_marginLeft="70dp"
            android:layout_weight="40"
            android:text="@string/speichern_text"
            >

        </Button>

                </LinearLayout>

            </LinearLayout>

        </LinearLayout>

</LinearLayout>
</ScrollView>

Vertical view work perfect but I would like to know if I can add horizontal scroll to this layout because when I have horizontal orientation layout looks good but when I change orientation I don't want to reduce size some elements in layout. I think about add horizontal scrool. This is possible?
Comment: A solution with Appbarlayout in a CoordinatorLayout: https://stackoverflow.com/questions/1399605/how-can-i-make-my-layout-scroll-both-horizontally-and-vertically/78001428#78001428
Answer: I add:
<HorizontalScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true"
>

as child my scroll view and this solution works great.
Comment: It works, but only one of the ScrollView operates in the same time. I mean you can't scroll diagonally.

ScrollView in both directions android


How can I pass the fragment context to the adapter?

Question: I am working on a project and stuck on this for 3 days now. The project reads a json, using an adapter, and fragments.
json: https://opendata.visitflanders.org/accessibility/activities/sport_v2.json
fragment_list_of_sports.xml:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".ListOfSportsFragment">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="List of sports and locations"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.022" />

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/rvSportList"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"/>

    <Button
        android:id="@+id/btnBack"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Back"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.049"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.976" />
</androidx.constraintlayout.widget.ConstraintLayout>

ListOfSportsFragment.kt:
package vives.be.bedoerikproject

import SportsAdapter
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.view.get
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import kotlinx.android.synthetic.main.fragment_list_of_sports.*
import kotlinx.android.synthetic.main.fragment_list_of_sports.view.*
import org.json.JSONException
import org.json.JSONObject

class ListOfSportsFragment : Fragment() {

     override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        val view = inflater.inflate(R.layout.fragment_list_of_sports, container, false)

        val sportList: ArrayList<SportModelClass> = ArrayList()

        try {
            // As we have JSON object, so we are getting the object
            //Here we are calling a Method which is returning the JSON object
            val obj = JSONObject("Sports.json")
            // fetch JSONArray named users by using getJSONArray
            val sportsArray = obj.getJSONArray("sports")
            // Get the users data using for loop i.e. id, name, email and so on

            for (i in 0 until sportsArray.length()) {
                // Create a JSONObject for fetching single User's Data
                val sport = sportsArray.getJSONObject(i)
                // Fetch id store it in variable
                val id = sport.getInt("business_product_id")
                val name = sport.getString("name")
                val city_name = sport.getString("city_name")
                val postal_code = sport.getInt("postal_code")
                val website = sport.getString("website")
                val phone = sport.getString("phone1")
                val email = sport.getString("email")

                // Now add all the variables to the data model class and the data model class to the array list.
                val sportDetails =
                    SportModelClass(id, name, postal_code, city_name, phone, email, website)

                // add the details in the list
                sportList.add(sportDetails)
            }
        } catch (e: JSONException) {
            //exception
            e.printStackTrace()
        }

       // Set the LayoutManager that this RecyclerView will use.
        rvSportList.layoutManager = LinearLayoutManager(activity) //rv = reciycleview
        // Adapter class is initialized and list is passed in the param.
        val itemAdapter = SportsAdapter(requireContext(), sportList)
        // adapter instance is set to the recyclerview to inflate the items.
        rvSportList.adapter = itemAdapter

        return view
    }
}

SportsAdapter:
import vives.be.bedoerikproject.SportModelClass
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import vives.be.bedoerikproject.R
import kotlinx.android.synthetic.main.sport_model_layout.view.*

class SportsAdapter(val context: Context, val items: ArrayList<SportModelClass>) :
    RecyclerView.Adapter<SportsAdapter.ViewHolder>() {
    /**
     * Inflates the item views which is designed in xml layout file
     *
     * create a new
     * {@link ViewHolder} and initializes some private fields to be used by RecyclerView.
     */
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        return ViewHolder(
            LayoutInflater.from(context).inflate(
                R.layout.sport_model_layout,
                parent,
                false
            )
        )
    }

    /**
     * Binds each item in the ArrayList to a view
     *
     * Called when RecyclerView needs a new {@link ViewHolder} of the given type to represent
     * an item.
     *
     * This new ViewHolder should be constructed with a new View that can represent the items
     * of the given type. You can either create a new View manually or inflate it from an XML
     * layout file.
     */
    override fun onBindViewHolder(holder: ViewHolder, position: Int) {

        val item = items.get(position)
        holder.name.text = item.name
        holder.city_name.text = item.city_name
        holder.postal_code.text = item.postal_code.toString()
        holder.website.text = item.website
        holder.phone1.text = item.phone1
        holder.email.text = item.email
    }

    /**
     * Gets the number of items in the list
     */
    override fun getItemCount(): Int {
        return items.size
    }

    /**
     * A ViewHolder describes an item view and metadata about its place within the RecyclerView.
     */
    class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        // Holds the TextView that will add each item to
        val name = view.name
        val city_name = view.city_name
        val postal_code = view.postal_code
        val website = view.website
        val phone1 = view.phone1
        val email = view.email
    }
}

SportModelClass.kt:
package vives.be.bedoerikproject

class SportModelClass (
    val business_product_id : Int,
    val name : String,
    val postal_code : Int,
    val city_name : String,
    val phone1 : String,
    val email : String,
    val website : String
    )

And I get an error in ListOfSportsFragment in line 60, this one:
E/AndroidRuntime: FATAL EXCEPTION: main Process: vives.be.bedoerikproject, PID: 7302 java.lang.NullPointerException: Attempt to invoke virtual method 'androidx.recyclerview.widget.RecyclerView$LayoutManager androidx.recyclerview.widget.RecyclerView.getLayoutManager()' on a null object reference at vives.be.bedoerikproject.ListOfSportsFragment.onCreateView(ListOfSportsFragment.kt:60) at androidx.fragment.app.Fragment.performCreateView(Fragment.java:2995) at androidx.fragment.app.FragmentStateManager.createView(FragmentStateManager.java:523) at androidx.fragment.app.FragmentStateManager.moveToExpectedState(FragmentStateManager.java:261) at androidx.fragment.app.FragmentManager.executeOpsTogether(FragmentManager.java:1840) at androidx.fragment.app.FragmentManager.removeRedundantOperationsAndExecute(FragmentManager.java:1764) at androidx.fragment.app.FragmentManager.execPendingActions(FragmentManager.java:1701) at androidx.fragment.app.FragmentManager$4.run(FragmentManager.java:488) at android.os.Handler.handleCallback(Handler.java:938) at android.os.Handler.dispatchMessage(Handler.java:99) at android.os.Looper.loop(Looper.java:223) at android.app.ActivityThread.main(ActivityThread.java:7656) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947) Disconnected from the target VM, address: 'localhost:52495', transport: 'socket'
Answer: You can set your layout manager in xml file.
...
<androidx.recyclerview.widget.RecyclerView
    android:id="@+id/rvSportList"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent"/>
...

and you don't have to pass context into your adapter, you can reach context in onCreateViewHolder like this
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
    return ViewHolder(
        LayoutInflater.from(parent.context).inflate(
            R.layout.sport_model_layout,
            parent,
            false
        )
    )
}

Answer: Could you try move your codes from onCreateView to onViewCreated fun on your fragment and use 'context' instead of 'requireContext()'. Hope it hepls.
Comment: This is solved my problem, but I had to add one more modification:
I created this onViewCreated, took everythin inside this, and then my problem was that I couldn't read the json, so I wrote a function that reads the json like this: context?.assets?.open("filename.json").
Answer: Use requireActivity() like this:
 rvSportList.layoutManager = LinearLayoutManager(requireActivity())

Comment: It's not working for me, I'm getting the same error.
Comment: Then I think the issue is not related to Context. Maybe it is related to Kotlin synthetics. I suggest migrating to Android View Binding
Answer: You can use synthetic view binding like this only after your fragment onCreateView() has returned.
Move the view setup code using synthetics such as rvSportList.layoutManager = LinearLayoutManager(activity) //rv = reciycleview to e.g. onViewCreated().
Also worth noting that the kotlin-android-extensions plugin that provides synthetic view binding is deprecated. Consider using view binding instead.
Answer: This is your error:
java.lang.NullPointerException: Attempt to invoke virtual method
'androidx.recyclerview.widget.RecyclerView$LayoutManager
androidx.recyclerview.widget.RecyclerView.getLayoutManager()'
on a null object reference at
vives.be.bedoerikproject.ListOfSportsFragment.onCreateView(ListOfSportsFragment.kt:60)

It's trying to call a method (getLayoutManager()) on something that's supposed to be a RecyclerView, but it's not - it's null. Can't call a method on a null object, so you get the NullPointerException
This is line 60, where the log tells you the error is happening:
rvSportList.layoutManager = LinearLayoutManager(activity) //rv = reciycleview

So if the problem is calling methods on a null RecyclerView, and it's happening on that line, then rvSportList isn't a RecyclerView, it's null.

You're getting that magic rvSportList variable from the Kotlin synthetic extensions you're using, which have been deprecated for a long time. You should use View Binding instead - but in the meantime, try this - the basic way to find a view:
val rvSportList = view.findViewById<RecyclerView>(R.id.rvSportList)
rvSportList.layoutManager = LinearLayoutManager(requireContext())
// etc


Quasi compact topological space.

Question: A topological space $(X,T)$ is said to be quasi compact if every open covering has a finite refinement. Let f be a fuction from $(X,T)$ to another topological space $(Y,T')$ then f is said to be quasi compact if inverse image of every quasi compact open subset of Y is a quasi compact subset of X.
Recently I saw another definition of quasi compactness in the research paper On Door Spaces by Julian Dontchev which says that a function f from a topological space $(X,T)$ to another topological space $(Y,T')$ is called quasi compact if it satisfies the following condition:
Let $U$ be an open subset of $X$ such that inverse image of $f(U)$ is $U$ itself then $f(U)$ is open in $Y$.
My doubt is whether this two definitions are equivalent. If yes kindly post the proof.
Answer: These certainly are not equivalent.  For instance, let both spaces be $\mathbb{R}$ with the usual topology.  The only quasicompact open subset of $\mathbb{R}$ is the empty set, so trivially any map $f:\mathbb{R}\to\mathbb{R}$ is quasicompact by the first definition.  But it's certainly not true that every map $f:\mathbb{R}\to\mathbb{R}$ is quasicompact by the second definition.  For instance, $f(x)=x^2$ fails the definition for $U=\mathbb{R}$.

Quasi compact topological space.


POST of large file is timing out, when running through ARR

Question: When POST'ing a large file through ARR, the request times out after 120 seconds. The client recieves error code 502 Bad Gateway. I have configured the "proxy timeout" of the web farm to be 600 seconds. I have also configured the Connection time-out of Default Web Site to be 600 seconds. The ARR server has been restarted.
The following is from the log file on the ARR server:
2015-05-07 13:25:16 192.168.87.155 POST /Redacted/Import/RedactedImport20150507_152313.csv X-ARR-CACHE-HIT=0&X-ARR-LOG-ID=253daa4a-8372-405a-8efd-21ebbc38353f 80 - 192.168.87.198 - redacted.local 502 3 64 120436

from applicationHost.config:
    <webFarm name="redacted.local" enabled="true">
        <server address="redacted.local" enabled="true" />
        <applicationRequestRouting>
            <healthCheck url="http://redacted.local/redacted.svc" liveTrafficFailureCodes="400-" />
            <protocol timeout="00:10:00" />
        </applicationRequestRouting>
    </webFarm>

Background:
I'm building a PoC for using ARR to achieve load balancing and high availability for our backend services, which are mostly WCF (Basic HTTP) and REST.
One of the (REST) services is used to recieve a large(ish) file a couple of times each day, from a batch job. The REST service does not return until the processing of the file is complete (which could take 5 minutes), since the client application needs to know when the processing is complete (more steps follows, which are dependent on the first).
Answer: In my case I resolved the problem by changing the proxy time-out

Go to IIS manager
Application requests routing
Under "actions" go to server proxy settings
Change the time-out to your desired value.

These steps are for IIS v7
Comment: On my install of IIS 10/ WS2016 Step "2" here is called "Application Request Routing Cache", which is a bit confusing.
Answer: For iis10

Go to Application Request Routing Cache
Right click and choose Server Proxy Settings
Under the Proxy Settings section change the Time-out(seconds) value
Answer: Answering my own question, as I finally figured it out.
I added this to applicationHost.config under configuration/system.applicationHost:
<webLimits connectionTimeout="00:10:00" minBytesPerSecond="0" />

But even after saving and pressing Restart under Manage Server in IIS Manager, it still responded with 502 after two minutes.
However, today when I installed some IIS features (Failed Request Tracing) I restarted the IIS service W3SVC and the Web Management Service WMSvc, and suddenly the 502 stopped.
Answer: We had a similar issue which was to do with the default MTU setting on the network card, it was set to 1514 instead of 1500 which was only causing problems with larger posts.
https://blogs.technet.microsoft.com/askpfeplat/2014/12/01/psa-incorrect-mtu-size-causes-connectivity-issues-with-windows-server-2012-and-windows-server-2012-r2/


Box Cox transformation in R

Question: I understand how to use the box cox transformation in R and how to get the graph and lambda.
These are the things that are confusing me. For simplicity assume this example:
<code> Weight = Gender + Height + Age + Income
</code>
gender = categorical variable 1 = male, 0 = female
continuous variables - weight, height, age, income.
I've done:
<code>model = lm(weight ~ gender + height + age + income)
</code>
and applied box-cox to this model which is about 1 so no transformation is needed for weight.
The questions are:

How do I apply Box-Cox to the 'x' variables to see if they need to be transformed (I read  they can be applied to all x variables, the only disadvantage is its time consuming, but this isn't an issue for me).
How do I know if they need a transformation for sure e.g. if lambda is 0.4 should I use a square root transformation or does it 'have' to be 0.5? what is lambda is 2?
If one or two or all variables need a transformation then how do I adjust the main model formula?
Comment: Your first two questions are answered in the duplicate thread at http://stats.stackexchange.com/questions/35711/box-cox-like-transformation-for-independent-variables, so please focus on the third question here.
Comment: Why do you need to use Box-Cox to check your IVs? Usually Box-Cox is used to check for an optimal transformation for the DV to help with the assumption of normally distributed residuals (that is, a normally distributed DV \emph{conditional} on the IVs).
Answer: When referring to Box-Cox transformations there are really 2 concepts that look like they are being mixed up.  The first is what the original paper was about, the methodology of finding a transformation within a family of transformations that gives the "best" transformation assuming the truth results in normal residuals with equal variance and a linear relationship.  This is what you already did with the response (dependent) variable.
In the paper Box and Cox presented a family of transformations (actually the paper has more than 1, but variations on the main one are what people mainly refer to), this family of transformations (or variations on it) is also often called the Box-Cox transformations.  If you want to apply one of this family of transformations to a predictor variable, then just plug the variable into the formula.
To determine what types of transformations to apply to predictor variables, the most important thing to use is knowledge about your data and the science behind it.  How do you expect weight to change with age, height, or income?  (I would be surprised if a Box-Cox transform is the best for any of these).
There are tools like spline fits, ACE, AVAS, and others that can suggest transformations, but you need to use knowledge and common sense to convert these into meaningful transformations.
Comment: Thanks for this. Would LASSO (and coding it to include a polynomial) tell you which factors are relevant? Does the Box-Cox of the entire linear model (weight ~ age + gender etc) tell you whether or not to transform the y variable 'only'. I'm still a bit confused about this. In R there is a formula to apply box-cox to each 'x' variable but i get complete different results (sapply(df[-24],BoxCoxTrans)) where 24 is the column with the y variable of the data frame (df). Why is this?
Comment: I looked up AVAS and it looks like thats what I need. However, I'm a little stuck on implementing it. I took x = matrix with height, age etc, y = weight and a = avas(x,y). however, only plot(a$x, a$tx) and plot(a$y, a$ty) work i.e. not plot(a$tx, a$ty). Also I'm unsure of how to interpret the charts and determine if a transformation is needed as my graphs do not look anything like the graphs presented in the example. Can you help me please?

Box Cox transformation in R


Parsing information out of the center of a String in Java

Question: Let's say I have the following string of text:
"first:center:last"
I want to extract only "center" from this string. However, I do not know what will be in the beginning, the end, or the center of the string. All I know is that colons will separate the three pieces of the string and the part I need from the string is the piece in-between the colons.
Using Java, what is the cleanest way that I could accomplish this task?
Thank you very much in advance for your time.
Answer: Since you only want the center you can perform a substring using the appropriate indices. This will be more efficient than the split() approach as you'll create fewer string and array instances.
public class Main {

    public static void main(String[] args) {
        String fullStr = "first:center:last";
        int firstColonIndex = fullStr.indexOf(':');
        int secondColonIndex = fullStr.indexOf(':', firstColonIndex + 1);
        String centerStr = fullStr.substring(firstColonIndex + 1, secondColonIndex);
        System.out.println("centerStr = " + centerStr);
    }
}

Comment: That's 3 liner of what I did in 2 lines...heck...could do it in 1 line too...lol
Comment: yeah, but it avoids using split() ;)
Answer: A non-RegEx based solution which I believe is the fastest:
String string = "left:center:right";
String center = string.substring(string.indexOf(':') + 1, string.lastIndexOf(':'))

Answer: Logically, I would have gone (of this effect):
String[] splits = string.split(":");
String centerStr = splits[1];

Answer: Use String.split() and take the second item in the array.
http://www.rgagnon.com/javadetails/java-0438.html
Answer: try{
    String str="first:center:last";
    String result = str.split(":")[1];
}catch(ArrayIndexOutOfBounds aex){
    //handle this scenario in your way
}


Fender hot rod deluxe connected to speaker simulator diagram

Question: I am trying to connect my Fender hot rod deluxe tube amp to a speaker simulator. My speaker simulator is the Iron Cab which has a "link out", and the manual description says:

Attention! When using IRon Cab with a guitar amp, be sure that the guitar cabinet/load emulation is connected to the LINK jack. Otherwise IRon Cab and the amp will be damaged.

I know I can go from speaker out to cab sim and then from LINK back to speaker, but I am wondering if I do the following connections without using the link, but the speaker is connected to my amp, am I damaging my amp?
Answer: The configuration in the diagram is not safe for your amp. All speaker jacks used on a tube amp must be connected to an appropriate load or the amp may be damaged from over-current.
You can either connect a single jack to a load (speaker or load box) and leave the external jack unused, or you can connect both the normal and external speaker jacks to two separate loads, but you can't connect one jack to a load and then connect the other jack to something that does not present the appropriate load.


How can I add 'text/jsx' type to a script tag via libraries.yml?

Question: I want to add some react js files to a theme's libraries.yml and I don't know how I can do this in drupal 8.

or

I can't figure it out hot to make the type="text/jsx" appear when the file is added to the page.
Any ideas on how I can achieve this in Drupal 8?
Answer: I took a wild guess because I couldn't find absolutely nothing. Apparently this works:
my-libary:
  version: 1.x
  js:
    js/node.js: { attributes: {type: text/babel} }


Can you use a Marshall single channel footswitch with a MG102FX 4-channel amp?

Question: I have a four-channel MG102FX amp. Will a single-channel pedal work with it? Both are Marshall. Help, please! I just want to be able to go from clean to distortion.
Comment: Looking at [the user manual](http://www.marshallamps.com/wp-content/uploads/2013/08/mg15cfx-mg100hcfx-hbk3.pdf), it's hard to say what a single footswitch would do; it has a standard-looking 1/4" jack input, but the pedal pictures has four switches and a tuner.
Answer: It will at least do something. One of the 4 channels will be triggered. Just test it out...
Comment: this assumes they have the same type of input to the amp. I used to have a four-button foot switch for a Gallien Krueger amp that used a five-pin-din connection.


Xcode 9 stuck on Swift 4 migration

Question: I'm trying to migrate my Swift 3 project to Swift 4 in Xcode 9. After selecting target and choosing either of @obcj inference options, Xcode stuck on Generating preview spinning wheel forever. How can I migrate my project?
Answer: On the same conversion dialog uncheck Remind me checkbox and click Convert Later. Now go to Build Settings and change Swift Language Version to Swift 4.0. Most likely this will produce a lot of warnings or errors. Unfortunately you have to fix them manually.
Comment: Why did i even think that the automatic migration would work. It didn't from 2 to 3 either.

Xcode 9 stuck on Swift 4 migration


Find the smallest $x$ for $9x \equiv 3 \pmod {23}$

Question: $9x \equiv 3 \pmod {23}$
How to derive the smallest $x$. I understand I can use the extended euclidean algorithm for eg $19x = 1 \pmod {35}$.
However, I not too sure how to work on it when it is $3 \pmod {23}$.
I am able to reach the step of $1 = -5(9) + 2(23$) after going thru the euclidean algorithm.
Comment: As $3$ is relatively prime to $23$, $9x\equiv 3\iff 3x\equiv 1$. Guessing shows that $23+1=24=3\cdot 8$ is a multiple of $3$. Indeed, $9\cdot 8=72=3\cdot 23+3$.
Answer: Ah, great, but this already means that $-5$ is the multiplicative inverse of $9$ modulo $23$, as $(-5)\cdot 9\equiv 1 \pmod{23}$. So you have
$$x\equiv (-5)\cdot 9x\equiv (-5)\cdot 3=-15\equiv 8 \pmod{23}$$
Among these, $8$ is the smallest positive number.
Answer: As you computed, $9(-5)\equiv 1\pmod {23}\implies 9(-5)3\equiv 3\pmod {23}\implies 9(-15)\equiv 3\pmod{23}$ $\implies 9(8)\equiv3\pmod{23}$
Answer: Hint $\rm\,\ mod\ 23\!:\,\ 9x\equiv 3\iff x\equiv \dfrac{3}{9}\equiv \dfrac{1}3\equiv \dfrac{8}{24}\equiv \dfrac{8}1$
Remark $\ $ We used Gauss's algorithm for computing inverses $\rm\:mod\ p\:$ prime.
Beware $\ $ One can employ fractions $\rm\ x\equiv b/a\ $ in modular arithmetic (as above) only when the fractions have denominator $ $ coprime $ $ to the modulus $ $ (else the fraction may not uniquely exist, $ $  i.e. the equation $\rm\: ax\equiv b\,\ (mod\ m)\:$ might have no solutions, or more than one solution). The reason why such fraction arithmetic works here (and in analogous contexts) will become clearer when one learns about the universal properties of fraction rings (localizations).
Answer: $ _{_{_{x}}}$
(This is certainly a smaller $x$ than any other solution has)
(From reading "Littlewood's Miscellany" - highly recommended)
Answer: We employ an algorithm that was discussed here.
$\alpha-$Solve:
$\;9x \equiv 3 \pmod{23}, \text{ and } \; 23 = 9 \cdot 2 + 5,\quad -3 + 1 \cdot 9 = 6$
$\alpha-$Solve:
$\;5x \equiv 6 \pmod{9}, \text{ and } \; 9 = 5 \cdot 1 + 4,\quad -6 + 2\cdot 5 = 4$
$\alpha-$Solve:
$\;4x \equiv 4 \pmod{5},  \text{ ANS: } \; x = 1 \text{ is the least residue solution}.$
Propagating backward,
Solve $5x = 6 + 1 \cdot 9, \text{ ANS: } \; x = 3$
Solve $9x = 3 + 3 \cdot 23, \text{ ANS: } \; x = 8$
$\text{ANSWER: }  x = 8 \text{ is the least natural number satisfying }$
$\quad 9x \equiv 3 \pmod{23}$


How can I paste above the default email signature?

Question: Private Sub CommandButton1_Click()

Dim ol As Object 'Outlook.Application
Dim olEmail As Object 'Outlook.MailItem
Dim olInsp As Object 'Outlook.Inspector
Dim wd As Object 'Word.Document
Dim rCol As Collection, r As Range, i As Integer

'if outlook is running use GO, create otherwise
Set ol = GetObject(Class:="Outlook.Application")
Set olEmail = ol.CreateItem(0) 'olMailItem

Set rCol = New Collection
With rCol
    .Add Sheet1.Range("B6:C23") '/\* add your ranges the same sequence \*/
End With

With olEmail
.To = "email@example.com"
.CC = "email@example.com"
.Subject = "Useful subject"
Set olInsp = .GetInspector
If olInsp.EditorType = 4 Then 'olEditorWord
Set wd = olInsp.WordEditor
For i = 1 To rCol.Count '/\* iterate all ranges \*/
Set r = rCol.Item(i): r.Copy
wd.Range.InsertParagraphAfter wd.Paragraphs(wd.Paragraphs.Count).Range.PasteAndFormat 16 '16 - wdFormatOriginalFormatting
Next
End If

wd.Range.InsertParagraphAfter
.Display
End With

End Sub

This code copies and pastes into new Outlook email under the default signature.
The selection needs pasting before the signature, in the logical place of the beginning of the email.
Comment: did you want to paste each cell into each line in the email body?
Comment: @k1dr0ck I'm not quite sure. What happens now is it pastes the two columns directly under the signature. It looks exactly like it does in Excel, which is what I wanted. So just need something that says "do exactly what you're doing but starting above the email signature".
Answer: Move the cursor above the signature before pasting.
Option Explicit

Private Sub CommandButton1_Click2()

Dim ol As Object        'Outlook.Application
Dim olEmail As Object   'Outlook.MailItem
Dim olInsp As Object    'Outlook.Inspector

Dim wd As Object        'Word.Document
Dim wdRng As Object     'Word.Range

Dim r As Range

' No need to differentiate CreateObject and GetObject for Outlook
' The result of either is the one allowed instance of Outlook
Set ol = CreateObject(Class:="Outlook.Application")
Set olEmail = ol.CreateItem(0) 'olMailItem

Set r = Sheet1.Range("B6:C23")

With olEmail
    .To = "firstname.lastname@example.com"
    .CC = "email@example.com"
    .Subject = "Useful subject"
    Set olInsp = .GetInspector

    If olInsp.EditorType = 4 Then 'olEditorWord - True since 2007
        Set wd = olInsp.WordEditor
        Set wdRng = wd.Range(0, 0)  ' Move the cursor to the start

        r.Copy
        wdRng.Paste ' Paste should not overwrite signature
    End If

    .Display
End With

End Sub

Comment: Thank you very much. That does precisely what I need now and my project is back on track.
Answer: try
Sub SendEmailWithRange()
    Dim MyRange As Range
    Dim doc As Object,x

    Set MyRange = Sheet1.Range("B6:C23")

    With CreateObject("outlook.application").CreateItem(0)
        .Display  'Change to .Send to send the email immediately

        .Body = "This is the body:"
        Set doc = .GetInspector.WordEditor

        x = doc.Range.End - 1
        MyRange.Copy
        doc.Range(x).Paste

        .To = "email@example.com"
        .CC = "firstname.lastname@example.com"
        .Subject = "Useful subject"

        Application.CutCopyMode = 0
    End With

End Sub

Comment: Thank you. That is much better, but removes the signature altogether. Is there a way to get the signature to appear underneath the content?


How to Segue-Push after using UISearchBar in a TableView, project with storyboard

Question: I have a UITableView with a UISearchBar in a project that uses storyboard.
The search function without problem.
I have the cell linked to a Seague Push to the next view.
If I select a cell, the next view is loaded and everything works perfect.
Everything was perfect until I use UISearchBar, then stops working Segue Push and I can not go to the next view when I select the filtered cell.
What to do? Force segue.
A model of a project at this links:
http://uploaded.to/file/ooohrxnf
//Code for search
- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString
{

[searchData removeAllObjects];

NSArray *group;

for(group in arraynumbers)
{
    NSMutableArray *newGroup = [[NSMutableArray alloc] init];
    NSString *element;

    for(element in group)
    {
        NSRange range = [element rangeOfString:searchString options:NSCaseInsensitiveSearch];

        if (range.length > 0) {
            [newGroup addObject:element];
        }
    }

    if ([newGroup count] > 0) {
        [searchData addObject:newGroup];
    }
}

onTableData = searchData;

return YES;
}

// Force Segue when UISearchBar isActive
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
if (self.searchDisplayController.isActive) {

    NSMutableArray *mutablerray = [searchData objectAtIndex:indexPath.section];
    number = [mutablerray objectAtIndex:indexPath.row];
    [self performSegueWithIdentifier:@"detail" sender:self];
    searchBar.text = @"";
}

}

// pickup number when UISearchBar isNotActive and reloadData after Segue
- (void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([segue.identifier isEqualToString:@"detail"])
{
    if (!self.searchDisplayController.isActive)
    {

        number = [[onTableData objectAtIndex:[[self.tableView indexPathForSelectedRow] section]] objectAtIndex:[[self.tableView indexPathForSelectedRow] row]];
    }

    NSLog(@"number: %@", number);
    [segue.destinationViewController setNumber:number];

    [self.tableView reloadData];
}
}

Answer: I ran into the exact same issue, and ended up trying a variety of things since the UISearchDisplayController was very new to me. I ended up setting the tableView as the searchResultsDelegate for the searchDisplayController:
searchDisplayController.searchResultsDelegate = self;

I'm not quite sure why this took care of it though. Anyone with an explanation?
Comment: Please add ' or four spaces when you add code to your answer. '' or four spaces .


ul is not inside div container

Question: Why my container is not background color red and ul is not inside div container ??
STYLE:
#container {
            width:1000px
            }

#categoryorder {
            float:left;
            width:500px;
            margin:0 0 0 50px;
            display:inline;
            list-style-type:none
}

#categoryorder li {
            color:#003366;
            font-size:20px;
            float:left;
            width:196px;
            background-color:#fcfcfc;
            border: 2px solid #dddddd;
            margin:0 50px 50px 0;
            line-height:50px;
            text-align:center;
            display:inline;
            cursor:move
}

HTML:

1

2

3

4

5

6

7

8

Comment: http://jsfiddle.net/vrVAP/84/
Answer: Because you are floating all of the elements within, without clearing them. Create a clear class and then add an element at the bottom:
HTML

1

2

3

4

5

6

7

8

CSS
.clr{
    clear:both;
    font-size:0;
}

JSFiddle
Comment: This is the correct answer - however you should use the clearfix techniques as defined in this article http://css-tricks.com/snippets/css/clear-fix/ as adding empty `div` elements just for the sake of clearing floats is a bad practice.
Comment: @ninty9notout - Why is it the correct answer? An extra div is completely unnecessary.
Comment: @j08691 that was how you used to do clearfix in the good old days, before pseudo elements, therefore it's a valid answer. I've also mentioned that it is a bad practice, which takes care of the unnecessary argument, and given a link to a resource that provides ways clearfix is achieved in modern browsers.
Comment: @ninty9notout - valid sure, I won't dispute that, but as you point out it was an old way of doing things that requires extra, non-semantic markup.
Answer: When you float the children you essentially remove them from the flow of the document and the container element's height shrinks to nothing. Add overflow:auto; to your #container div to restore the behavior you seek.
#container {
    width:1000px;
    overflow:auto;
}

jsFiddle example
Note that this answer doesn't require any extra (non-semantic) divs to get the desired result.
Answer: You are floating your elements and need to add overflow: hidden to your PARENT container to restore the height. Use this and you wont need to add an extra div to your flow.
#container {
            width:1000px; overflow: hidden;
            }

http://jsfiddle.net/saUp7/1/
Comment: in this case they both act similar and just clear the floats, overflow hidden will hide extra content but only if there is a set height fixed
Comment: Finally I understood why my floated content made the containing DIV shrink... :-) But what is the difference between using overflow: hidden or auto? It also works with auto as per @j08691 answer.
Answer: Change your float:left to display:inline-block;
Css:
#categoryorder {
     width:500px;
     margin:0 0 0 50px;
     display:inline-block;    /*from float:left; to display:inline-block; */
     list-style-type:none;
}

DEMO
Answer: Just use display:inline-block instead (and add vertical-align: top for better look).
Float is designed for cutting block from flow, so it is normal behaviour for that: you have no no-floated blocks inside, so flow is near nothing.
Inline-blocks are in flow, so it will work.
And just one trick for inline-blocks: remember the spaces! If they are in source, there will be small margins within blocks, so just comment your indents

somethinganother
  (look up to source)

ul is not inside div container


backup maze for a small IT group

Question: I am the sole sysadmin for a small software development company, and occasionally I get help from either my boss or one of the engineers.  So its sort of a 1.5 person scenario.
We are currently using backupexec 9, and its definitely showing its age.  We have a sql2005 & sharepoint box it basically cant touch, and are considering some virtualized solutions that it wont be able to service either.
Ive looked at somewhere near 6 solutions at this point, and they all appear to do what we probably want.  So far ive given a cursory review to CA ARCServe, Barracuda Yosemite, BackupExec, BackupExpress, and Acronis.  I was recently recommended to check out tivoli, although i havent gotten around to it.
BackupExec is very expensive.  With all the features we would be wanting out of it, it came to more than 12k.
I spoke with the CA rep, and he put me in with the features i wanted for somewhere around 4k, which is better but still not great.
So finally, the question:  Are any of these packages "avoid at all costs"?  Anyone using CA right now?  Love/Hate it?
Comment: I have it on good authority that CA doesn't use their own software. Draw your own conclusion from that.
Comment: I assume you are looking at list prices for things?  Don't do that.  Contact a reseller and get an upgrade quote for Backup Exec.  Use two resellers if you need to get the pricing down further.  Oh, and avoid CA.
Comment: "Backup maze"? Maze?
Comment: What features are you looking at in Backup Exec, anyway? $12K is a _lot_ of Backup Exec. I wouldn't spend any money for "Continuous Protection" or "Intelligent Disaster Recovery" (or whatever they're calling these "features" these days...)
Comment: @Scott: Surely they're using some kind of helpdesk automation software they wrote themselves, though. Every time I ever called it seemed like my ticket number was invalid or the wrong notes came up.  *smile*
Comment: @Evan: The primary license, 4 or 5 agent licenses, Exchange, SQL2005, 2 active directory agents (though i think i need only one of these), VMWare ESX.  This pricing was from the symantec website, so you may be right that i can get better pricing elsewhere.
Answer: I wouldn't use CA ARCServe if you paid me to use it. A lot. Lots and lots. If terrorists asked me for a recommendation on a backup solution I wouldn't even recommend ARCServe to them. Backup Exec has never caused a server of mine to "blue screen"-- ARCServe did it all the time 4 - 5 years ago. Symantec's support isn't wonderful, but CA's was down right hostile (again, 4 - 5 years ago). Perhaps I'm holding a grudge, but the last time I looked at the ARCServe product, about 2 years ago, I was still fantastically unimpressed.
Backup Exec is expensive, but does generally work fairly well. My company is using it almost exclusively with our Customers (except for a little bit of NetBackup). I'm not very happy about the pricing, nor with Symantec following the long-held Veritas traditions of (a) not selling licenses for agents for older versions (forcing you to upgrade), and (b) making sure that older versions cannot handle backups of newer versions of software (SQL Server 2005 / 2008, Exchange 2007, etc).
We haven't been able to find anything better.
Microsoft Data Protection Manager looks interesting, but I hear it's pretty pricey, too.
A former co-worker of mine, now working at a Fortune 500 company, mentioned Atempo LiveBackup (http://www.atempo.com/products/liveBackup/default.asp) a few months ago, but I haven't had a chance to look at it. Apparently they were thinking pretty strongly about replacing Backup Exec with it. That seemed like fairly high praise, but he wasn't a heavy Backup Exec user so he couldn't really comment on its similarities / differences. If you happen to give it a look, drop me a line. I'd love to hear what somebody used to Backup Exec thinks about it.
Comment: "ARCServe ate my baby."
Comment: So how do you feel about ARCServe? *grin*
Comment: The only time "Arcserve" should appear in a question about backup is when the question is something like "Help, I installed arcserve by mistake, how do I do a disaster recovery with *my real backup program* to correct this terrible error in judgement?" -- as for pricing, it might be $12k to buy the solution you (probably need) and that might seem expensive. What's the cost of NOT having reliable backups? More or less than $12k? That's your answer right there.
Comment: I can't agree more with Evan's evaluation of Ca's product.  I was forced to use it at a client, I should have just let them shoot me. DPM isn't that pricey when used in a virtual environment see: http://www.microsoft.com/systemcenter/en/us/management-suites.aspx
Comment: If you thought that was bad, try it under NetWare.
Comment: You know, I actually thought it sucked less under NetWare than under Windows. I don't recall having the jobs that hang forever, destabilization of the server operating system, and general crappiness. Then again, I may be repressing general NetWare memories too. That time in my life is a haze.
Comment: "not selling licenses for agents for older versions" - We're using a v11 agent license in a v10d system with no problems. Don't know if that's just because the versions are so close together, though...
Comment: @Ben: Hmm... perhaps I needed to push on the sales gerbil a little harder, then. In at least once case that I can recall I was told that I could not purchase an Exchange agent for a Customer who was runing v10d and that I'd have to upgrade to (then) 12 in order to get the ability to backup their newly-installed Exchange 2003 environment. Hmmm...
Comment: I've had both ARCserve and BackupExec be nightmares and I've had them both run perfectly.  To me it just seems like backups are like a pool of water any time you toss a rock in(make changes) it takes time for the ripples to dissapaite, and calm down again.  When I say I've used both I mean across multiple versions going back 10 years on mutlitple OS's(Windows,Linux,NetWare).
Answer: I am lone geek at a 10 person marketing and sales division, and I am using EMC Retrospect.
I like it, and here's what I like:

Under $1k for their Multi-Server version (backs up servers, PCs and Macs)
They charge extra for special add-ons for SQL Server and Exchange backups, if you want them.
Backs up to plain old hard drives, I use 2 on an A/B schedule, where Retrospect handles "grooming" - where it drops out older versions as space runs out (totally configurable) - I take one off-site every night.
Easy to setup (I am a programmer first, and IT guy second, so I don't have extensive training in backup technologies).
Disks keep getting cheaper and larger.
I've been using it for about 4 years, and their support is great, and I have yet to lose anything or have any problems retrieving files.

I also use this in conjunction with TrueCrypt - I keep my drives encrypted to protect against theft.  (Note, you need a dual-core or better to handle the encryption).
ps: I have no relationship with EMC/Retrospect except as happy customer.
They are here: http://www.retrospect.com/products/software/retroforwin/
Comment: So, the backups are easy to set up.  Have you (had to, and been able to) successfully **Restore**?  A backup solution is only as good as your ability to restore...
Answer: My motto here is "all backup software sucks".  Having said that, since you're used to the quirks and foibles of BE, I'd recommend sticking to that route rather than switching to an alternative product and giving yourself a whole new set of quirks and foibles to get used to.
You can get VERY cheap BE licensing, by the way, if you approach resellers in the right way, as mentioned above.  An added bonus, if you're in a position where Symantec view you as a customer they might want to piggy-back on for more business elsewhere, is that they actually are prepared to turn a blind eye to their normal support policies every now and then (but don't tell anyone I said that... ;)
Comment: All Windows backup software, at least. I've found rsync/cron to be a a rock solid setup on the Linux servers I have to work on.
Comment: @Dentrasi - copies are not backups, unless you're also doing something to get those backups versioned and offline.
Answer: Bakbone Netvault may fit your budget.  I use it for my "small workgroup" and it hasn't let me down yet.
Answer: I was suprised to find myself really liking HP's dataprotector.  I've used all the usual suspects (BE, tivoli, networker etc) and HP's got a solid product. It's relativly simple to use. My only real gripe is that if you're required to do any sort of non-standard reporting the reporting tools that come with it are almost worthless and the reporting tool add in for their storage product is laughably expensive.
The pricing is great (essentially it's per backup device not client, and any extra integrations span the enterprise), the support has been great, and most importantly it's been trouble free (relatively speaking)
Answer: I tried the HP Dataprotector briefly and, well, Evan's rant against ARCServe covers my sentiments nicely.  ;)  The interface was terrible (admittedly, I'm used to Backup Exec), and HP support had a ball passing me around between departments for weeks on end.
My experience with Retrospect was as a backup to the Backup Guy, so I wasn't as arms-deep as I would've preferred, but aside from a slightly cryptic interface, it was able to do everything asked of it, and is very, very hands-off once you have everything configured.
If I were replacing the backup right now (it's a nice dream), I'd think seriously about Retrospect.
Answer: I'd like to see more people comment on their ability to do Restores.  Setting it up is important, as is your ability to monitor success/failure and to remediate defects.
But the proof is in the restore.
Answer: We use BackupExec, and are reasonably satisfied with it.  I second the suggestions to shop around on pricing.
That said, you may wish to consider an online backup solution such as Iron Mountain.  Given the expense of a server, software, tape drives and tape, the monthly expense might make sense.
Note: Iron Mountain bought LiveVault, remember the John Cleese video?
Answer: Since no other open source solutions have been brought up yet, have you considered looking at Bacula at all? I haven't played around with it much yet, but I need to get myself around to testing it in a few VMs. It has a nice modular design, and has supports backing up the usual Windows / Linux / FreeBSD.
Answer: Have you taken a look at Zmanda?  I haven't used it, but it might fit the bill.
Answer: I used ArcServe for about 8 years and never had a problem until about 18 months ago, when there were compatibility issues with then recent Microsoft updates. Hardly a surprise, as at that time there were compatibility issues even between updates issued at the same time. Unfortunately, CA was distinctly less than helpful, telling me the only possible solution was to purchase the latest version of ArcServe. In the past they would have supplied a patch.
I now use Backup Exec. The main reason for the change is not the problem described above but the need to backup Windows, Linux and Mac, all from a central Windows machine. There are also a range of services, such a SQL Server and Exchange that need to be catered for. BE is horrendously expensive but it does have considerable flexibility and numerous options to cater for a very diverse range of situations. On the down-side, I really hate the unintuitive interface where everything is harder to do than it needs to be because what I want is usually not where I would expect to find it. Of course once it's properly configured there should be little need to use said interface. Emailed alerts keep me well informed, so I only connect when performing random test restores.
When looking for an alternative I did consider Bacula but I've never been able to actually get it to do what others seem to have no trouble in achieving. Perhaps it's just because Linux is not my native language. ;)
Answer: We use Data Protection Manager from Microsoft and we like it. Its not the most easy thing to manage at times (some tasks have to be done by scripts/powershell) but it does a great job at protecting the Microsoft workloads (SQL/Hyper-V/Exchange/etc).
Pricing will be about 10-15% cheaper then what you find on this page: http://www.microsoft.com/systemcenter/en/us/data-protection-manager/dpm-pricing-licensing.aspx
Basically:
$400/server to backup workloads/everything else (workloads can be SQL/Exchange/etc)
$150/server to just backup sys state/files (can't back up workloads)
$30/pc to backup a PC
Edit: I will add that we used Backup exec before switching to DPM. We went from two backup exec installs on two separate servers to one centralized backup server with added drives for disk to disk.
Answer: Haven't seen anyone recommend CommVault? I've played with it briefly for an old client, so I don't have a lot of personal experience, but I know a lot of people that like it. Including my current company, which is migrating to it.
Most of my experience is with BE 9/10 (decent for my use of them, although kind of annoying) and Legato Networker 7.2-7.3, which was damned spiffy but not that easy to learn.
Answer: At my small development company, we threw out all our backup hardware & software recently and switched to the cloud with Carbonite Pro.
Everything is instantly stored off-site, it's cheap, and it's easy to restore.
For SQL databases, just set up a SQL task to back up the database to a folder, and have your backup software use that folder instead.

backup maze for a small IT group


java bufferreader read elements equal to another array elements

Question: I read a file by using bufferreader and also have another array(array_to_compare_with). So, I want to compare these two data.
How can I get over this ? Anybody has a clue ?
String[] array_to_compare_with = { "str1","str2","str3","str4" }

FileInputStream fstream = new FileInputStream("filename");

DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;

while ((strLine = br.readLine()) != null)   {
// strLine and array_to_compare_with comparison needed to be done
}

Comment: what do you mean by compare? do you want to check if its in the array?
Comment: i mean that if strLine has "str1" element or not. If it has than str1 element is found will be printed.
Answer: Maybe you want something like this:
    String[] array_to_compare_with = { "str1","str2","str3","str4" };

    FileInputStream fstream = new FileInputStream("filename");

    DataInputStream in = new DataInputStream(fstream);
    BufferedReader br = new BufferedReader(new InputStreamReader(in));
    String strLine;

    while ((strLine = br.readLine()) != null)   {
        boolean found = false;
        for(String str : array_to_compare_with){
            if(str.equalsIgnoreCase(strLine.trim())){
                found = true;
                break;
            }
        }
        if(found){
            //DO WHAT YOU WHANT
        }
    }

Answer: String[] array_to_compare_with = { "str1","str2","str3","str4" }

FileInputStream fstream = new FileInputStream("filename");

DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;

while ((strLine = br.readLine()) != null)   {
    for(String s: array_to_compare_with){
        if(strLine.contains(s)){
            System.out.println(strLine);
            break;
        }
    }
}


Part of a sorted array is reversed

Question: Given a sorted array, a part of which is reversed. We are required to completely sort it.
eg :
ip - 2 4 5 7 13 11 9 14 19
op - 2 4 5 7 9 11 13 14 19

It's easy to solve when we know whether the given array is sorted in ascending or descending order.If we don't know the order, how to solve it?
eg:
ip - 19 17 2 6 8 10 1
op - 19 17 10 8 6 2 1

also ambiguity occurs when 1st part of input is in ascending order and remaining is in descending order.In that case any order can be considered for output.
Answer:
Assume the final result should be ascending. Run your algorithm once.
Check whether the output is really ascending. If yes, we are done; if no, go to 3.
Roll back to original input, assume the final result should be descending, run your algorithm once.
Check whether the output is really descending. If yes, we are done; if no, the input is illegal.

Part of a sorted array is reversed


Old user accounts generated on new instances

Question: When I generate a new VM instance, I notice that if I go the the /home directory, I see the home directories of past user accounts I've created.  I find this odd since I'm creating a new instance from scratch.  Can anyone please advise why this might be happening.  I made sure to delete all old instances and disks.
Answer: Google Compute Engine creates the accounts based on your instance metadata or in your project metadata if you don't have instance metadata.
In this case it's using the project's metadata. To see your project's metadata go to Compute->Compute Engine->Metadata in the Developers Console and click on 'SSH keys' on the top of the page. There, you can find a list with two columns:

On the left you can see the username that will be generated every time you create an instance.
On the right you can see the SSH key that will be stored in <username>/.ssh/authorized_keys for that user.

There can be more than one SSH key per user. Therefore, if you want to remove all old users from there, you just need to click on 'Edit' and remove all the lines where appears those users in the left column.
Note:  Be aware that if you remove some users, their home directories will remain in the instances and they won't be able to SSH into any instance unless they set their SSH keys manually for some specific instances.
If you want to deepen and know why everything is working as intended, you can see that the instance is running with runlevel 2 via sudo runlevel.
As you may know, once the system boots up, it will execute all the scripts in the /etc/rc2.d/ folder and there is one responsible of manage all the project accounts for the instance. You can find it at /etc/rc2.d/S03google-accounts-manager which is a soft link to /etc/init.d/google-accounts-manager.
This one runs /usr/share/google/google_daemon/manage_accounts.py which is in a github repository as well with the files it uses. This script orchestrates everything related with the accounts using desiredaccounts.py and accountsmanager.py among other.
The desiredaccounts.py is used to get all the users and its SSH keys for the instance and project looking at two URLs. You can check the instance metadata with the command:
`curl http://169.254.169.254/computeMetadata/v1/instance/attributes/sshKeys?%s -H "Metadata-Flavor: Google"`

And the project metadata with the following command:
`curl http://169.254.169.254/computeMetadata/v1/project/attributes/sshKeys?%s -H "Metadata-Flavor: Google"`

The script will use the project metadata only if the instance metadata it's empty.
Once the script has the desired accounts, it uses accountsmanager.py which calls the UpdateUser method
Finally in account.py, you can see how it calls the method UserAdd that belongs to utils.py to create the user, add the user to the sudoers file and put the SSH key in his ~/.ssh/authorized_keys file.
Hope it helps.


What is the baseline level in a factor-by-factor interaction?

Question: What is the baseline level for a factor-by-factor interaction term in multiple regression?
Consider this example from Fox 2003. In the regression below, these two variables are categorical: year={1997,..,2002} and colour={black,white}.
require(effects)
require(lmtest)
Arrests$year <- as.factor(Arrests$year)
arrests.mod <- glm(released ~ employed + citizen + checks
                         + colour*year + colour*age,
                         family=binomial, data=Arrests)

Which yields:
> coeftest(arrests.mod)

z test of coefficients:

                       Estimate Std. Error  z value  Pr(>|z|)
(Intercept)           0.3444334  0.3100749   1.1108 0.2666514
employedYes           0.7350645  0.0847701   8.6713 < 2.2e-16 ***
citizenYes            0.5859841  0.1137717   5.1505 2.598e-07 ***
checks               -0.3666425  0.0260322 -14.0842 < 2.2e-16 ***
colourWhite           1.2125167  0.3497751   3.4666 0.0005272 ***
year1998             -0.4311794  0.2603589  -1.6561 0.0977023 .
year1999             -0.0944343  0.2615447  -0.3611 0.7180519
year2000             -0.0108975  0.2592073  -0.0420 0.9664655
year2001              0.2430630  0.2630151   0.9241 0.3554129
year2002              0.2129549  0.3532786   0.6028 0.5466444
age                   0.0287279  0.0086191   3.3330 0.0008590 ***
colourWhite:year1998  0.6519565  0.3134898   2.0797 0.0375555 *
colourWhite:year1999  0.1559504  0.3070430   0.5079 0.6115161
colourWhite:year2000  0.2957537  0.3062034   0.9659 0.3341076
colourWhite:year2001 -0.3805413  0.3040538  -1.2516 0.2107305
colourWhite:year2002 -0.6173178  0.4192551  -1.4724 0.1409086
colourWhite:age      -0.0373729  0.0102003  -3.6639 0.0002484 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

In the table above, I interested in identifying the baseline level for the factor by factor interaction term... For instance, group colourWhite:year1998 is compared to which other group?
Is colourWhite:year1997 the baseline level, or perhaps colourBlack:year1997?
Comment: See also: http://stats.stackexchange.com/questions/122246/interpretation-of-interaction-term?rq=1
Answer: The reference category is the combination of first levels of the factors in the model:
> with(Arrests, levels(colour))
[1] "Black" "White"
> with(Arrests, levels(year))
[1] "1997" "1998" "1999" "2000" "2001" "2002"

So the Intercept is for colourBlack:year1997 and the default contrasts specify differences in means with is class and the other combinations of factors involved in your model specification, hence colourWhite reflects the difference in $E(y)$ for the combination colourWhite:year1997. you can think of this really as
colourBlack:year1997 + colourWhite

as colourWhite represents the difference in 1997 for colour White.
The other interaction terms in the model are the additional differences for colour White in the other years, whilst the year main effects are the differences in $E(y)$ between the reference year and the other years for colourBlack`.
Looking at the model matrix can often help in deciphering these things:
> head(model.matrix(~ colour * year + colour * age, data = Arrests))
  (Intercept) colourWhite year1998 year1999 year2000 year2001 year2002 age
1           1           1        0        0        0        0        1  21
2           1           0        0        1        0        0        0  17
3           1           1        0        0        1        0        0  24
4           1           0        0        0        1        0        0  46
5           1           0        0        1        0        0        0  27
6           1           0        1        0        0        0        0  16
  colourWhite:year1998 colourWhite:year1999 colourWhite:year2000
1                    0                    0                    0
2                    0                    0                    0
3                    0                    0                    1
4                    0                    0                    0
5                    0                    0                    0
6                    0                    0                    0
  colourWhite:year2001 colourWhite:year2002 colourWhite:age
1                    0                    1              21
2                    0                    0               0
3                    0                    0              24
4                    0                    0               0
5                    0                    0               0
6                    0                    0               0

The look at the first few rows of the data to see how the dummy variables indicate the various groupings indicated by the combinations of factors and their interactions.
Comment: "What about comparisons not directly shown in the regression table?" That table just shows the parameters of the particular model parameterisation you have used. To get the comparison you want, you need *post hoc* comparisons. The **multcomp** package is particularly strong on this. **effects** is good too and whilst it generates the effects displays it does also provide the statistics behind the plots.
Comment: For your second comment, yes; if you are `colourWhite` in 1997 then you take the intercept plus `colourWhite` coefs. If you are `colourWhite` in 1998 you want intercept, `colourWhite`, `year1998`, & `colourWhite:year1998` coefficients to get the mean for that combination.
Comment: Yes, `year1998` is the modification you need to make if you are in 1998; all samples in 1998 take this modification. The `colourWhite:year1998` is an *extra* modification that you take *only* if you are that specific combination. If you look at the model matrix (a shown in my Answer) the parametrisation is essentially a set of indicator variables. If you look closely at rows in the model matrix that correspond to rows in the data with `colour == "White" & year == "1998"` you'll see that all such entries have a `1` in the `year1988` column.
Comment: Thank you so much for this exhaustive explanation! What about comparisons not directly displayed in the regression table? For instance, `colourWhite:year2000` vs `colourWhite:year2002`. Aside from the option of changing the reference level and re-estimating the regression, is it OK to use the `effects` package to graphically display the *effects* of all possible groups, and then draw conclusions from the graphs? This is very much related to this question: http://stats.stackexchange.com/questions/146715/how-to-interpret-factor-by-factor-interactions
Comment: *The other interaction terms in the model are the additional differences for colour White in the other years* By this do you mean that `colourWhite:year1998` is contrasted with `colourWhite` (which effectively represents `colourWhite:year1997`)? Thanks!
Comment: *"If you are `colourWhite` in 1998 you want `intercept`, `colourWhite`, `year1998`, & `colourWhite:year1998`"* Are you sure about including `year1998` for `colourWhite` in 1998? From your answer my understanding was that (1) for **`colourWhite` in 1998** we would take `intercept`, `colourWhite` & `colourWhite:year1998`, whereas (2) for **`colourBlack` in 1998** we would take `intercept` & `year1998`. Did I get that wrong?
Comment: Very interesting. So after the intercept, all remaining terms related to an interaction (both main-term and interaction-term regressors) are merely sequential additional differences. But then what do the statistical significances actually represent? For instance, coefficient for `year1998` (`-0.4311794`) shows that Blacks in 1998 have a lower $E(y)$ than Blacks in 1997, correct? Whereas coefficient for `colourWhite:year1998` (`colourWhite:year1998`) has no literal interpretation from what I see... Am I getting any closer?
Comment: Thank you for all the helpful explanations and pointers. `multcomp` does indeed multiple comparisons (in some respects better than `effects`), as does `lsmeans`. All three packages overlap in scope, but differ somewhat in implementation...


How do I get the raw URL as a field in Views?

Question: In views I need to return the raw url that is provided as the href value to the title field (when as a link) or the Content: link value.  I thought originally I could choose Content:link and strip the HTML in a rewrite, but no go.
I need the full URL so that I can pass it as a parameter in a field rewrite. Thoughts on how to get this only?
Comment: The url to node based content can always be accessed as node/NID, so, you should be able to have Node: Nid as a field and then use it in a rewrite later on as node/[nid] or something similar.
Answer: As per the comment here http://drupal.org/node/458316#comment-6236984
In views 3.x you can use "Path" field with option "Use absolute link (begins with "http://")" in Rewrite results section.
Comment: Problem I find with this solution is you get URLS that look like http://example.com//content/new-article
Comment: This solution works perfectly for me
Answer: Yes, we can use the path field. This also support multilingual content. Please find attached screenshot to see what it looks like.
Answer: Adding to rakesh.flake comment, we have a option to add the absolute URL as well in the settings.
Answer: There is number of ways you can do this but the following is fairly easy.
In your view add NID as a field.
Create a 'row style' template that loops through the $fields object.
In your template file, before the loop assign a variable with the NID value from the field.
$nid = strip_tags($fields['nid']->content);

Then use the node_load() function to load a node object.
$node = node_load($nid);

You should be able to access anything you want including the path from this node object.
To see whats in it use Devel if you have this installed or just use the PHP var_dump() function.
Even better check whether you have a 'path' field the you can add.
Comment: Please do not do this. There's no reason for a full node_load; it will slow down your views considerably.


How to make this bet fair?

Question: A person bets $1$ dollar to $b$ dollars that he can draw two cards from an ordinary deck of cards without replacement and that they will be of the same suit. How to find the value of $b$ so that the bet will be fair?
My effort:
There are a total number of ${52 \choose 2} = 26 \cdot 51$ ways of drawing two cards oout of a deck of $52$.
And, there are ${13 \choose 2} = 13 \cdot 6 $ ways of drawing two cards of any given suit, say, hearts.
Now since there are four distinct suits, the number of ways of drawing two cards of the same suit is $13 \cdot 6 \cdot 4$.
So the probability of drawing two cards of the same suit (assuming that the deck is well-shuffled  so that each card is equilikely to be drawn) is $$ \frac{13 \cdot 6 \cdot 4}{26 \cdot 51} = \frac{4}{17}.$$
Is it correct? And if so, then what next?
Answer: It is correct.
So the probability of getting different suits is $\dfrac{13}{17}$.
So the odds should be $\dfrac{4}{17} : \dfrac{13}{17}$ or $4 : 13$ or $1:3.25$.
There are other ways of getting the same result.
For example, given the first card, there are $12$ other cards of the same suit and $39$ cards of other suits, making the odds $12:39$.

How to make this bet fair?


List error after second click

Question: in my app I have a views that retrieve a list of a certain content type which links to the specific node.
When I click for the first time it's ok, app brings me to the page that shows the content but when I go back and I click on another item in the list, the page that shoud shows content goes blank.
Any idea?
Thank you,
Cris.

UPDATED ON 2017-08-18

Page that shows the list:
function list_articles_list_row(view, row, variables) {
  try {

      var title_html = "
" + row.nome+" "+row.cognome.charAt(0)+". -  "+" "+row.title+"
";
       var image_html = "
"+theme('image', { path: row.img.src })+"
";

      var link = l('' + image_html + title_html, 'singlegiftapp/' + row.nid);
      return link;

   }
  catch (error) { console.log('list_articles_list_row - ' + error); }
}

Single page item:
    function single_page(nid) {
     var content = {};
      content['ite'] = {
        theme: 'jqm_item_list',
        title: '',
        items: [],
        attributes: { id: 'ite' + nid }
      };
      return content;
     }

function single_pageshow(nid) {
  var path_to_view = 'singlegiftapp/'+nid;
  views_datasource_get_view_result(path_to_view, {
    'success':function(data){

    if (data.nodes.length > 0) {
        var items = [];

        $.each(data.nodes, function(index, object){
              var row = object.node;

             var image_html = theme('image', { path: row.img.src });

               var description =
                '
' + row.title + '
' +
                '
Price suggested:  ' + row.Prezzo + '
' ;
               var dato = t(description+image_html);
              items.push(dato);

        });
         drupalgap_item_list_populate("#ite" + nid, items);
      }
    }

  });

}

Thank you so much Tyler for your help!
Comment: Please share your code that you are using to build the page/view/etc. Most likely you need to append a unique id to the end of your View since DrupalGap 7 is a multi-page app.
Answer: I'm also interested in your page_callback implementation, but I am guessing you just need to make your id for your item list be dynamic:
var itemListId = 'ite' + nid;

Then in your pageshow, do something like this:
drupalgap_item_list_populate("#ite" + nid, items);

DrupalGap 7 is a multi-page application, so as you navigate around previously visited pages remain in the DOM, so any id that you add to elements should be unique for that page. Which means typically you just need to append an entity type/id to the element's id, and you should be good to go.

List error after second click


Menu on mobile phone - How to directly show second level of menu?

Question: Following configuration: Drupal 7, tb corpal theme, superfish menu
For mobile phones I get a menu as shown in the image. If I press the menu icon (1, red on image) I get first the "Main menu" level (2, red on image). After pressing "Main menu" the menu expands and one gets to the desired next level.

What do I have to change to get directly to the "second level" after "Main menu" level?
Answer: You can force the desired behavior via CSS or via Javascript (jQuery). For instance, check with jQuery if main menu is displayed on mobile. If so, then display its children, too. The CSS way would work if "main menu" is displayed by adding a class. If so, then you can, from CSS, display the second level when that class is present.