Latin Square Design ANOVA in R

Question: I have been searching online for an appropriate way to analyse data obtained using a 4x4 latin-square design (and more specifically how to do this in R).
I have some sources online that say the data should be analysed using a repeated measures ANOVA. I have tried this, but want to make sure that I have entered the error term correctly or whether there is a better method.
The design is repeated-measures: I have my treatment factor (correction) with 4 levels, and another factor (narrative) which also have 4 levels. Correction and narrative have 4 different combinations or orders.
Any help at all would be much appreciated!
Comment: what are two blocking variables to make your design to make this latin square.
Comment: Hi there - Narrative is the Column blocking variable and I have Order (which corresponds to the combination of Narrative with the treatment variable Correction) as the Row blocking variable. So each subject is allocated to one of four orders which are combinations of Narrative and Correction. I am analyzing the data in R and I know that there are some issues with unbalanced designs for aov and ezANOVA in R so I'm not sure this is the best approach.
Comment: I think there issues with 'lmer' because of the design
Comment: To make things even more complicated the qualtrics algorithm didn't allocate subjects to the different orders equally so there are more observations for some conditions than others
Answer: This is complete answer but more than just comment.
Probably you have looked the bloggers article:
https://www.r-bloggers.com/latin-squares-design-in-r/
I think using mixed model analysis is more powerful. You can treat them as row-column design.
The following question may be useful:
lme4 or other open source R package code equivalent to asreml-R
Comment: Thanks so much. I had initially intended on using mixed model analysis but I spoke to someone who knew more about this analysis and they said that design means that LMM might not be appropriate. I also couldn't find any resources online to for using LMM in this way.
Comment: The other thing I find a little confusing is that some of the resources I have found online suggest using a linear model but this ignores the repeated measures nature of the data.

Latin Square Design ANOVA in R


Excel VBA Macro MsgBox auto converts number to Scientific notation, how do I stop this?

Question: I am trying to get the current date into milliseconds so I can compare it to the AD "LastLogon" time stamp. The problem is that the current date automatically becomes scientific notation instead of the 18 digit number I am in need of. How do I force it to display all digits?
Dim currentDate
currentDate = Now * (8.64 * 10 ^ 11) + 109205
'MsgBox (DateAdd("d", -90, Now))
MsgBox (currentDate)

Comment: `I am trying to get the current date into milliseconds` Do you any any chance want to get the current time to show in miliseconds(with ms formatted as 6 digits)?
Answer:  MsgBox( Format(currentDate, "#0"))

or other format you prefer
Answer: Dim currentDate
currentDate = Now * (8.64 * 10 ^ 11) + 109205
'MsgBox (DateAdd("d", -90, Now))
MsgBox (Format(currentDate(), "MM dd, yyy"))
MsgBox (Format(Now(), "MM dd, yyy"))

Now() displays a date
currentDate is an over flow.
How to format date in VBA?


How to create component inside other component in Angular2

Question: I need to split one complicated component into two or more simplier using directives in template.
Answer: Here is the way how to implement this.
MainComponent.ts
import { Component } from '@angular/core';
import { MyService1 } from '../../providers/myService1/myService1';
import { MyCmp1 } from '../../components/myCmp1/myCmp1';

@Component({
   templateUrl: 'build/pages/mainComponent/mainComponent.html',
   providers: [
      MyService1
   ],
   directives: [
      MyCmp1
   ],
   //pipes: [ ... ] // Pipes which you are using
})
export class MainComponent {
   main: any;

   constructor() {
      this.load();
   }

   load(): void {
       MyService1.loadData()
          .then((response) => {
               main.data1 = response;
          });
   }

   onShowMe(data): void {
       alert(data);
   }
}

MainComponent.html

Main Component

   <my-cmp-1 [data1]="main?.data1" (onShowMe)="onShowMe($event)"></my-cmp-1>

MyCmp1.ts
import { Component, EventEmitter } from '@angular/core';
import { Input, Output } from '@angular/core';

@Component({
   selector: 'my-cmp-1',
   templateUrl: 'build/components/myCmp1/myCmp1.html'
})

export class MyCmp1 {
   @Input() data1: any;
   @Output() onShowMe = new EventEmitter();

   showMe(event: Event, data: any): void {
      event.preventDefault(); // If you are using  or etc.
      this.onShowMe.emit(data);
   }
}

MyCmp1.html

My Component 1

Show Me


Bayesian Network or Logistic regression?

Question: The Bayesian Networks and Logistic regression can be used to predict events or give to each customer the propensity to have a behavior.
Which are the advantages or disadvantages of these 2 methods? When is better use the first and when is better use the other?
Answer: A Bayesian network is a graphical representation of an arbitrary probabilistic model.   Logistic regression is one very specific kind of probabilistic model, and it can be represented by a Bayesian network.  So you can't really say that one is better than another at prediction.


Is it true that a metric over $\mathbb{R}^n$ (or $\mathbb{C}^n$) always makes a complete metric space?

Question: I'm studying for my calculus II exam and I was thinking about the statement in the title.
My "sloppy" proof is something like: Over $\mathbb{R}^n$ (or $\mathbb{C}^n$) the Bolzano-Weierstrass theorem is always true so the completeness of the metric space should be independent of the specific metric that I define.
I couldn't come up with a better proof nor did I find a similar statement on my book.
Could you please help me clarify this problem?
Answer: No, it is not true. Consider, for instance, the following metric on $\Bbb R$:$$d(x,y)=\bigl|\arctan(x)-\arctan(y)\bigr|.$$With respect to this metric, the sequence $1,2,3,4,\ldots$ is a Cauchy sequence. But it doesn't converge.
Comment: https://math.meta.stackexchange.com/questions/33508/enforcement-of-quality-standards?cb=1


Find the limit with floor sequence or prove that it doesn't exist

Question: I need to find the limits of these 2 sequences or prove that they don't exist.
$$\lim_{x\to\infty}\left(x-5\left\lfloor\frac x5\right\rfloor\right)$$
$$\lim_{x\to\infty}\frac{x-5\left\lfloor \frac x5\right\rfloor}x$$
But I don't know how to get rid of the floor here.
I know I should use somehow this inequality. $\frac{x}{5} -1 \leq \left \lfloor \frac{x}{5} \right \rfloor \leq \frac{x}{5}$
But I'm not sure how to do it right.
And how to define in any sequence if the limit exist or not?
Thank you!
Comment: Hint: The second limit exists and is equal to 0, the first doesn't. To show that the first doesn't exist, consider $x=5n$ and $x=5n+1$ for $n\in\mathbb N$. To show that the second is 0, use your inequalities and estimate the fraction from above and below. Then let $x\to\infty$ on these bounds.
Comment: Thank you very much! I just have a question about the 1st one. So if I consider x=5n, the limit of the sequence will be equal to 0 in this case. And if I take x=5n+1, the limit will be equal to 1. So these limits are not the same, and it proves that the limit does not exist, right?
Comment: Exactly. Well done :)
Answer: Here is an answer of the first part. We  use the fractional part $\{x\}$ of a real number $x$.
$$\{x\}=x-\lfloor x\rfloor\qquad\qquad 0\leq \{x\}<1$$

We obtain
  \begin{align*}
\lim_{x\to\infty}\left(x-5\left\lfloor\frac x5\right\rfloor\right)
&=\lim_{x\to\infty}\left(x-5\left(\frac{x}{5}-\left\{\frac{x}{5}\right\}\right)\right)\\
&=\lim_{x\to\infty}\left(5\cdot\left\{\frac{x}{5}\right\}\right)\\
&=5\cdot\lim_{x\to\infty}\left\{\frac{x}{5}\right\}\quad\not\exists\tag{1}\\
\end{align*}

From the representation (1) we see, the values oscillate in $[0,5)$ when $x$ increases, so that the limit does not exist. In other words: Since the limits of the subsequences
\begin{align*}
5\cdot\lim_{{x\to\infty}\atop{x\in 5\mathbb{Z}}}\left\{\frac{x}{5}\right\}=0
\qquad\qquad\text{and}\qquad\qquad
5\cdot\lim_{{x\to\infty}\atop{x\in \frac{5}{2}\mathbb{Z}}}\left\{\frac{x}{5}\right\}=\frac{5}{2}\\
\end{align*}
are different, the limit (1) does not exist.


How to df.groupby(cols).apply(my_func) for some columns, while leave a few columns not tackled?

Question: Suppose I have a Pandas dataframe df has columns a,b,c,d...z . And I want to: df.groupby('a').apply(my_func()) for columns d-z, while leave column 'b' & 'c' unchanged . How to do that ?
I notice Pandas can apply different function to different column by passing a dict . But I have a long column list and just want parameters to set or tip to simply tell Pandas to bypass some columns and apply my_func() to rest of columns ? (Otherwise I have to build a long dict)
Answer: One simple (and general) approach is to create a view of the dataframe with the subset you are interested in (or, stated for your case, a view with all columns except the ones you want to ignore), and then use APPLY for that view.
In [116]: df
Out[116]:
     a  b         c  d        f
0  one  3  0.493808  a      bob
1  two  8  0.150585  b    alice
2  one  6  0.641816  c  michael
3  two  5  0.935653  d      joe
4  one  1  0.521159  e     kate

Use your favorite methods to create the view you need. You could select a range of columns like so df_view = df.ix[:,'b':'d'], but the following might be more useful for your scenario:
#I want all columns except two
cols = df.columns.tolist()
mycols = [x for x in cols if not x in ['a','f']]
df_view = df[mycols]

Apply your function to that view. (Note this doesn't yet change anything in df.)
In [158]: df_view.apply(lambda x: x /2)
Out[158]:
   b         c   d
0  1  0.246904  20
1  4  0.075293  25
2  3  0.320908  28
3  2  0.467827  28
4  0  0.260579  24

Update the df using update()
In [156]: df.update(df_view.apply(lambda x: x/2))

In [157]: df
Out[157]:
     a  b         c   d        f
0  one  1  0.246904  20      bob
1  two  4  0.075293  25    alice
2  one  3  0.320908  28  michael
3  two  2  0.467827  28      joe
4  one  0  0.260579  24     kate


User Profile Disks with RemoteApp 2012 R2 Locked

Question: We have a RemoteApp deployment (Web, Gateway, High Available Connection Brokers, ...). We use profile disks stored on a file share.  We publish most of our applications, but from time to time, a user needs a full fletched desktop.
That's why we also published mstsc with the path to the original .rdp-file from when there were no applications published.
This all works fine, unless a user has an application open when they open the desktop.
The server fails to mount their profile disk (because it's already mounted by the session providing the application and thus locked).
This causes the session host to load a temporary profile.
Is there any way around this, while still using User Profile Disks?
Is it possible to get the session that is providing the apps when opening the desktop somehow?
Answer: This question has come up previously (Windows 2012 RDS Temporary profile for Administrator) with no workaround. UPD was only designed to support a single session per user.
Even if you could get the RemoteApp session, which I don't believe you can, the screen resolution would end up being very screwy, since it's based on the size of the single application window.
Your best bet is simple user education, or write some kind of script that's launched when they try to enter a full-desktop session to kick any other sessions off first.
Answer: To expand on @tfrederick74656,

UPD was only designed to support a single session per user, per session collection

Best I've come up with is to provide users two session collections, both with their own UPD's. Use identical syspreps of Session Hosts across farm so the user experience is the same:

Collection 1: RemoteApp's, published to RDWeb
Collection 2: "Full Desktop", published to RDWeb

The full desktop can only be published if you don't create any Published Applications in the collection. It's an either-or scenario.
Only down side is twice as many UPD's and Session Hosts.


Why mutate applied only to first row and repeats its result to the rest

Question: I have a data frame which consists of several columns. One of them is date_created column in the unified format. I want to split it into year, month, day and add these columns to the same data frame.
input:
id      date_created
1       02-20-2014
2       01-15-2015

result:
id      date_created     year    month    day
1       02-20-2014       2014    2        20
2       01-15-2015       2015    1        15

I have a sample code which works incorrect
displays <- displays %>%
        mutate(month = as.integer(unlist(strsplit(date, '-')))[1],
               day   = as.integer(unlist(strsplit(date, '-')))[2],
               year  = as.integer(unlist(strsplit(date, '-')))[3]
              )

it produces the following:
id      date_created     year    month    day
1       02-20-2014       2014    2        20
2       01-15-2015       2014    2        20

I guess that the function is not called for each row, but cannot understand why. Explain, please, how it works and provide the sample code to achieve desired result. Thanks
Comment: In the `mutate`, you are just calling the 1st, 2nd and 3rd element from the entire date column that got split up
Answer: You can use separate or extract from tidyr
library(tidyr)
separate(d1, date_created, c('month', 'day', 'year'), remove=FALSE)

Or
extract(d1, date_created, c('month', 'day', 'year'),
              '([^-]+)-([^-]+)-([^-]+)', remove=FALSE)

Or cSplit from splitstackshape
library(splitstackshape)
cSplit(d1, 'date_created', sep="-", drop=FALSE)

Or using tstrsplit from the devel version of data.table
library(data.table)#v1.9.5
setDT(d1)[, c('month', 'day', 'year') := tstrsplit(date_created, '-')]

Regarding the problem in your code, it is just selecting 1st, 2nd and 3rd element from the entire 'date_created' column.  Just use rowwise
  library(dplyr)
  d1 %>%
     rowwise() %>%
     mutate(month= as.integer(unlist(strsplit(date_created, '-')))[1],
            day= as.integer(unlist(strsplit(date_created, '-')))[2],
            year=as.integer(unlist(strsplit(date_created, '-')))[3])

Or another option would be to convert to date class and then extract 'day', 'month' and 'year'
  library(lubridate)
  d1 %>%
     mutate(date=mdy(date_created), year=year(date),
            month=month(date), day=day(date)) %>%
     select(-date)

Comment: works, thanks, just needed to add separator `-`. Can you explain why `mutate` didn't work?
Comment: @AskhatOmarov I didn't had to add the `sep='-'` for `separate`.  May be it is the version difference.  I used `tidyr_0.2.0`
Comment: @AskhatOmarov Updated with post by correcting your code


Adding elements to top and bottom of UITable View Controller

Question: I am new to objective C. I have a small app where I have used a UITableviewcontroller(TVC). I need to add four elements.,label and button above TVC and a label and button below TVC. But it is allowing only to add 2 elements., one above TVC and other below TVC. Also added element is occupying the entire width of screen. Can I overcome this restriction???
Answer: Customize the table view cell – instead of using the default style of table view cell.
this link is helpful you with sample project
http://www.appcoda.com/customize-table-view-cells-for-uitableview/
Answer: These two are tableview properties.
tableHeaderView
tableFooterView

By using the above properties you can show your own custom view on top / bottom of table view.
sample code
[self.tableView setTableHeaderView:yourHeaderView];
[self.tableView setTableFooterView:yourFooterView];

Write this code in viewDidLoad.
Comment: Hello Ram., So every thing we need to do is Programmatical here., and nothing to do in utilities right?
Comment: how u r creating the uivew using xibs or coding.
Comment: By Dragging the controllers from the object library in utilities Section ( Xcode-5).
Comment: Do you have any knowledge on custom uiview creating using xib (Dragging).
Answer: UITableViewController is kind of a screwed up class, in my opinion. A UITableViewController can only manage a table view, and nothing else. If you want a more complex layout where you have a table view on part of the screen, and then other view objects elsewhere, you can't do that with a UITableViewController.
However, with iOS 6 and later, there is a pretty easy solution.
You can embed a UITableViewController as a child view controller of another view controller.
What you do is to create a parent view controller with everything you need. Then you create a container view on your parent view controller and size it to contain your table view. Then you create a separate scene in your storyboard that defines a table view controller. Finally, you control-drag from your container view to your UITableViewController, and create an embed segue.
I have a project on github that demonstrates this technique:
Demo project using UITableViewControllers as child view controllers


maven deploy to nexus

Question: My project contains the following pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.onestopspot</groupId>
    <artifactId>api_library</artifactId>
    <version>5.0.0-SNAPSHOT</version>
    <packaging>apk</packaging>
    <name>One Stop Spot</name>
    <distributionManagement>
        <repository>
            <id>confiz-repo</id>
            <url>http://10.10.10.230:8081/nexus/content/groups/public</url>
            <releases>
                <enabled>true</enabled>
            </releases>
            <snapshots>
                <enabled>true</enabled>
                <updatePolicy>always</updatePolicy>
            </snapshots>
        </repository>
     </distributionManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.android</groupId>
            <artifactId>spring-android-rest-template</artifactId>
            <version>1.0.0.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.codehaus.jackson</groupId>
            <artifactId>jackson-mapper-asl</artifactId>
            <version>1.9.8</version>
        </dependency>
        <dependency>
            <groupId>com.google.android</groupId>
            <artifactId>android</artifactId>
            <version>22.214.171.124</version>
            <scope>provided</scope>
        </dependency>
    </dependencies>

    <build>
        <finalName>${project.artifactId}</finalName>
        <sourceDirectory>src/main/java</sourceDirectory>
        <pluginManagement>
            <plugins>
                <plugin>
                    <groupId>com.jayway.maven.plugins.android.generation2</groupId>
                    <artifactId>android-maven-plugin</artifactId>
                    <version>3.4.0</version>
                    <extensions>true</extensions>
                </plugin>
            </plugins>
        </pluginManagement>
        <plugins>
            <plugin>
                <groupId>com.jayway.maven.plugins.android.generation2</groupId>
                <artifactId>android-maven-plugin</artifactId>
                <configuration>
                    <sdk>
                        <platform>16</platform>
                    </sdk>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

and my settings.xml file in my maven conf folder contains the following information
<?xml version="1.0" encoding="UTF-8"?>

<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0 http://maven.apache.org/xsd/settings-1.0.0.xsd">
  <pluginGroups>
  </pluginGroups>

  <proxies>
  </proxies>

  <servers>
    <server>
      <id>confiz-repo</id>
      <username>admin</username>
      <password>admin123</password>
    </server>
  </servers>

  <mirrors>
    <mirror>

      <id>confiz-repo</id>
      <mirrorOf>*</mirrorOf>
      <url> http://10.10.10.230:8081/nexus/content/groups/public/</url>
    </mirror>
  </mirrors>

  <profiles>
    <profile>
      <id>nexus</id>

      <repositories>
        <repository>
          <id>confiz-repo</id>
          <url>http://central</url>
          <releases>
        <enabled>true</enabled>
      </releases>
          <snapshots>
        <enabled>true</enabled>
        <updatePolicy>always</updatePolicy>
      </snapshots>
        </repository>
      </repositories>
      <pluginRepositories>
        <pluginRepository>
          <id>confiz-repo</id>
          <url>http://central</url>
          <releases>
        <enabled>true</enabled>
      </releases>
          <snapshots>
        <enabled>true</enabled>
      </snapshots>
        </pluginRepository>
      </pluginRepositories>
    </profile>
  </profiles>

  <activeProfiles>
    <activeProfile>nexus</activeProfile>
  </activeProfiles>

</settings>

now when i do a mvn deploy on my projects pom.xml file i get the following error
Failed to execute goal org.apache.maven.plugins:maven-deploy-plugin:2.7:deploy (default-deploy) on project api_library: Failed to deploy artifacts: Could not transfer artifact com.onestopspot:api_library:apk:5.0.0-20130318.070710-1 from/to confiz-repo (http://10.10.10.230:8081/nexus/content/groups/public): Failed to transfer file: http://10.10.10.230:8081/nexus/content/groups/public/com/onestopspot/api_library/5.0.0-SNAPSHOT/api_library-5.0.0-20130318.070710-1.apk. Return code is: 400

My nexus repo is working properly, and i can log in using the above username and password. What am i doing wrong ?
Kind Regards
Answer: You can't deploy to /content/groups/public - on a default Nexus installation, that's a group of repositories. Nexus wouldn't know which underlying repository to put the artifact it. Try /content/repositories/snapshots/.
Comment: I think it makes more sense in the pom file because it's specific to the project
Comment: ok thanks. That worked for me. Now the distributionManagement tag do i have to place it on my pom file, or can i place it in the settings.xml file ?

maven deploy to nexus


input não está puxando valor certo do banco

Question: Preciso de uma ajuda.
Em meu sistema, eu tenho um input que trás uma data do banco de dados.

Como podem ver na foto acima a data informada está 06/09/2017 00:00, só que a real data deste campo é 05/09/2017 22:03.
O formato que esta no meu banco está assim 2017-09-05 22:03:03.757 e logo abaixo está o meu input que puxa está data.
<input type="text" class="form-control" style="text-align: center;" value="@(Model.DataRandomizacao?.ToString("dd/MM/yyyy HH:mm") ?? "Não randomizado")" disabled>

alguém poderia me ajudar?
eu consegui resolver desta forma.
 @{ DateTime RandomizacaoData = Convert.ToDateTime(ViewBag.Randomizacao.RandomizacaoData); }
                                    <input type="text" class="form-control" style="margin-left:0; text-align: center;" value="@RandomizacaoData.ToString("dd/MM/yyyy HH:mm")" disabled>

só que preciso que caso não haja uma data ele apareça "Não Randomizado" como o exemplo antigo.
Comment: Qual o valor do DataRandomizacao sem  o ToString()?
Comment: Sem o ToString da erro e não consigo visualizar a data
Comment: Coloca o breakpoint nessa linha do seu cshtml -> CTRL+ALT+I para abrir o intermediate windows -> digite seu Model.DataRandomizacao.
Comment: o breakPoint não funciona nesta linha da data
Comment: Você esta em modo debug? Vai na sua Controller, onde possui a Action que chama essa View e veja o Model que você retorna para a View.
Comment: A variavel DataRandomização vem deste model @model Basics.Domain.Entities.ViewModel.Detalhes dentro deste model está a variavel public DateTime? DataRandomizacao { get; set; }
Comment: @GabrielColetta Eu consegui resolver de uma outra maneira, só que estou com um outro problema, caso não haja uma data, ele aparece "Não randomizado" vou editar o codigo e mostrar como fiz
Answer: Consegui resolver pessoal.
Obrigado a quem ajudou.
@if (Model.DataRandomizacao == null)
{
    Data da randomização:
    <input type="text" class="form-control" style="margin-left:0; text-align: center;" value="Não Randomizado" disabled>
}
else
{
    Data da randomização:
    DateTime RandomizacaoData = Convert.ToDateTime(ViewBag.Randomizacao.RandomizacaoData);
    <input type="text" class="form-control" style="margin-left:0; text-align: center;" value="@RandomizacaoData.ToString("dd/MM/yyyy HH:mm")" disabled>
}


Various Intersections of Sylow p-subgroups.

Question: I was told yesterday that in a system of Sylow $p$-subgroups of a finite group $G$, if, $\{S_1,S_2, \cdots, S_n\}$ make up the system, it can happen that, say, the intersection of $S_1$ and $S_2$ has order $p^k$, while the intersection of $S_3$ and $S_4$ has size $p^j$, with $k \neq j$.
1) My first question is if some examples are available of this. I think I can't find examples in the alternating groups and symmetric groups, due to multiple transitivity.
2a) If $j = k$ in the above, must the intersections $S_1 \cap S_2$ and $S_3 \cap S_4$ be isomorphic?
2b) If those two intersections in 2a) above are isomorphic, then must there be an inner automorphism mapping $S_1$ to $S_3$ and $S_2$ to $S_4$? That is, must Sylow systems have as much conjugacy as "possible", in addition to simple transitivity?
Thanks.
Comment: You should be able to find counterexamples for all claims by choosing the right groups $G$ and $H$ and looking at $G\times H$. The Sylow subgroups of $G\times H$ are the direct products of the Sylows of $G$ with those of $H$, so just pick the latter ones for your needs. For 1) and 2b) you can take $p=2$ and $G=H=S_3$. For 2a) $p=2$, $G=Z_5\rtimes Aut(Z_5)$ and $H=A_5$ (or another group with 2-Sylows isomorphic to $Z_2\times Z_2$ and two 2-Sylows intersecting trivially).
Comment: In the alternating group $A_7$ the $3$-Sylow subgroups $S_1=S_3=\langle (123), (456)\rangle$, $S_2=\langle (123), (457)\rangle$ and $S_4=\langle (124), (356)\rangle$ answer 1). For 2) the examples would become biggish, but should exist.
Answer: Let $C_3$ be the cyclic group of order $3$ and $D_8$ the dihedral group of order $8$, and let $G$ be the regular wreath product $C_3 \wr D_8$, which has order $3^8 \cdot 8$.
There are $3^7 = 2187$ Sylow $2$-subgroups of $G$, and all subgroups of $P$ arise as intersections of two of these. Since $P$ has non-isomorphic subgroups of order $4$, this answers Questions 1 and 2a) in the negative.
I found examples of Sylow $2$-subgroups $P_1,P_2,P_3$ with $|P_1 \cap P_2| = |P_1 \cap P_3| = 2$, such that $P_2$ and $P_3$ are not conuugate in $N_G(P_1)$, so the answer to 2b) is also no.


By considering expressions of the form $Y(t) = e^{tw}V$, find the general solution to $\frac{d^2Y}{dt^2} = AY$.

Question: By considering expressions of the form $Y(t) = e^{tw}V$, find the general solution to $\frac{d^2Y}{dt^2} = AY$.
We were given a matrix: $$A = \begin{bmatrix}
    2       & -1 & -1  \\
    -1       & 2 & -1  \\
    -1       & -1 & 2 &
\end{bmatrix}$$
The eigenvalues are 3 and 0.  The corresponding eigenvectors I found are:
For $\lambda = 3$: $$\begin{bmatrix}
           1 \\
           0 \\
           -1
         \end{bmatrix}, \begin{bmatrix}
          0 \\
          1 \\
           -1
         \end{bmatrix}. $$
For $\lambda = 0$: $$\begin{bmatrix}
           1 \\
           1\\
           1
         \end{bmatrix}$$
How do I find the general solution?
Thank you!
P.S. $V$ is the eigenvectors.
Comment: I think it would be something like $$Y=A\cdot e^{t\sqrt3}V_{\lambda=3\text{ (first one)}}+B\cdot e^{t\sqrt3}V_{\lambda=3\text{ (second one)}}+C\cdot V_{\lambda=0}$$but that has 3 constants, so I am not sure exactly why that's wrong (hence why I am not putting it as an answer). Perhaps someone can correct it
Answer: Plug $Y(t)$ into the differential equation. You'll get $w^2e^{tw}V=Ae^{tw}V$, which can be rewritten as
$$e^{tw}(A-w^2I)V=0.$$
It follows that $w^2=\lambda$ and $V$ is the corresponding eigenvector of $A$.
Comment: But how does this allow for a general solution to be written? As a linear combination of the three factors? If so, wouldn't this have 3 arbitrary constants?
Comment: I think I see where you are going, but how does this lead to a general solution/
Comment: @M.Byrne: See John Doe's comment under your question.
Comment: @AlexR. ahh OK this makes sense.


Achar atalho do Atom

Question: Hoje, enquanto eu estava trabalhando em um CSS com o Atom, eu abri uma sugestão de emotes para usar através de um atalho acidentalmente, porém eu não sei qual atalho eu usei e gostaria de saber. Alguém sabe?
Eu não utilizo nenhum package de emotes.
Comment: Caso utilize *Windows 10*, basta utilizar as teclas `Windows` + `.` (Ponto)
Comment: BOA! É isso mesmo que eu abri, muito obrigado.
Comment: Se o seu sistema operacional for Windows 10+ e o seu teclado for PT-BR aperte `⊞ Win + ç` que vai abrir a janela de emojis
Answer: Para ver a lista de emotes é só utilizar ⊞ Win + ..

Achar atalho do Atom


Two matrices having the same norm

Question: Let $V$ be a real finite dimensional vector space with inner product. A set of $k$ vectors $y_1,...,y_k\in V$, defines the linear operator $A: V\rightarrow V$ by $$Ax=\sum_{j=1}^k\langle y_j,x\rangle y_j$$. Define $k\times k$ matrix, $M$ with $M_{ij}=\langle y_i,y_j\rangle$. The norm of $A$ is the operator norm coming from the vector norm $\|x\|^2=\langle x,x\rangle$. The norm of $M$ is the matrix norm coming from $\mathbb{R}^k$: $\|z\|^2=\sum_{j=1}^kz_j^2$. Show that $\|A\|=\|M\|$.
So how do we start this? A direct computation seems difficult and heady
Answer: For convenience define $Y:V\to\mathbb R^k$ by
$$ Y(x) = \begin{bmatrix} \langle y_1, x \rangle \\ \vdots \\ \langle y_k, x \rangle \end{bmatrix}. $$
Then, the adjoint ("transpose") $Y^*:\mathbb R^k\to V$ of $Y$ is given by
$$ Y^*(u) = \sum_{i=1}^k u_i y_i. $$
Thus, we have $A = Y^*Y$ and $M=YY^*$.
It is easy to check that $A$ is self-adjoint, (that is $\langle Ax, z \rangle = \langle x, A z \rangle $) and $M$ is symmetric. Thus, the operator norm is given by the largest eigenvalue in modulus.
If $\lambda$ is an eigenvalue of $A$ with eigenvector $x$, then it follows
$$ M Yx = YY^* Y x = Y Ax = \lambda Yx. $$
Thus, if $\lambda\ne 0$, then $\lambda$ is also an eigenvalue of $M$ with eigenvector $Yx$. (Why is $Yx\ne 0$?)
We can show in a similar way that a nonzero eigenvalue of $M$ is also an eigenvalue of $A$.
Thus, the nonzero eigenvalues of $A$ and $M$ agree, and so do their operator norms.

Two matrices having the same norm


prove that for any $(s,t)$ there is a pair $(x,y)$ that is not good

Question:
Let $s$ and $t$ be nonzero integers and let $(x,y)$ be any ordered pair of integers. A move changes $(x,y)$ to $(x-t, y-s)$. The pair $(x,y)$ is good if after some number of moves it becomes a pair of integers that are not relatively prime. Prove that for any $s,t,$ there is a pair $(x,y)$ that is not good.

Working towards a proof by contradiction, suppose there is a pair $(s,t)$ of nonzero integers for which every pair $(x,y)$ of integers is good. Let $g = sx-ty$ for some integers $x,y,$ where $g = \gcd(s,t)$. Then $x$ and $y$ are coprime, since $1 = (s/g) x - (t/g) y$. By assumption, there is some $k$ so that after $k$ moves, $(x -kt, y-ks)$ become not relatively prime. Let $p$ be a prime divisor of the two integers $x-kt$ and $y-ks$. Then $p$ divides $s(x-kt)$ and $t(y-ks)$ so it divides $sx-yt = g.$ Hence $p$ divides $s$ and $t$. But I'm not sure how to get the contradiction from here. For instance, if $s = 4, t = 6, g = 2, x = 2, y= -1,$ then $p=2$ in this case but $p\nmid y$.
Comment: Might be easier to just construct a bad pair $(x,y)$ explicitly.
Comment: @lulu thanks. So could you provide a hint as to how to construct such a pair from (s,t)?
Comment: It's easy in this case, since the moves only go one way.  If, say, you picked $(0,0)$ then the first move gets you to $(-t, -s)$ which may or may not be relatively prime.  But look what happens after that...
Comment: Sorry, I misread the question.  My construction gives you a starting point for which *every* move gives you a pair with a common factor.  I still think explicit construction is probably your best bet, but my specific suggestion is not relevant.
Comment: As a better suggestion, let's work an example:  say $(t,s)=(2,3)$.  Then, starting with $(1,1)$ we see that $\gcd(1-2n, 1-3n)=1$ for all $n$ (why?)  So $(1,1)$ works in this case.  Try to generalize this.
Answer: Let's start with an example.  Say $(t,s)=(2,3)$.  Then I claim that $(1,1)$ works.
Pf:  We need to show that $\gcd(1-2n,1-3n)=1$ $\forall n\in \mathbb N$. But suppose it was $d$.  Then of course $d$ divides $(1-2n)-(1-3n)=n$.  But if $d$ divides $n$ then $d$ can't divide $1-2n$ so we are done.
Now we seek to generalize this.  So let $(t,s)$ be arbitrary. Suppose first that they are relatively prime.  In that case, we know from Euclid that there exist integers $(a,b)$ with $at+bs=1$.  We claim that the pair $(a, -b)$ is not good.
Pf:  We need to consider $d_n=\gcd (a-tn, -b-sn)$  As before, we remark that $d_n$ divides $b(a-tn)+a(-b-ns)=n(-bt-as)=-n$.  But, as before, if $d_n\,|\,n$ then that would imply that $d_n$ divided both $a$ and $b$, a contradiction (if $d_n>1$).  And we are done.
Now suppose that $\gcd(t,s)=d>1$.  Repeat the argument using integers $(a,b)$ with $bt+as=d$  Again consider the pair $(a,-b)$ noting that at least it is a relatively prime pair.  As before, let $d_n=\gcd (a-tn, -b-sn)$ and deduce that $d_n\,|\,d\times n$.  Now $\gcd (d_n, d)=1$ since, if a prime $p$ divided both $d_n$ and $d$ it would have to divide both $a$ and $b$.  Thus $d_n\,|\,n$ and we are done, as before.
Comment: You are right.  I should have had $bt+as=d$.  I will edit accordingly.  Thanks for spotting that.


Como calcular números perfeitos de forma rápida?

Question: Estou tentando realizar um exercício para mostrar os números perfeitos presentes dentro de um determinado range, porém eu só consigo realizar tal feito até o quarto número perfeito. Se eu aumentar o range, ele acaba demorando muito tempo e não responde:
def perfeito(n_max):
    lista = []
    for n in range(1, n_max + 1):
        soma = 0
        for div in range(1, n):
            if n % div == 0:
                soma += div
        if n == soma:
            lista.append(n)
    return lista

Aqui definimos o range, neste caso 500, e ele retornará os 3 primeiros:
print(perfeito(500))

Conjunto números perfeitos: {6, 28, 496, 8128, 33550336, 8589869056, …}
Após o 4º número. não consigo mais exibir. Alguma dica de otimização para meu código?
Answer: Existe uma relação direta entre os números perfeitos e os números primos de Mersenne. Um número primo de Mersenne nada mais é que um número primo que pode ser escrito na forma Mn = 2n – 1, para dado n inteiro, e a relação dele com os números perfeitos é uma potência de 2. Vale ressaltar na resposta que os conceitos aplicados aqui valem para, apenas, números perfeitos pares, porém a solução se mantém válida dado o fato que ainda não é conhecido pela matemática nenhum número perfeito ímpar - no dia que descobrirem eu edito a solução, prometo.
Assim, dado um número primo de Mersenne Mn = 2n – 1, podemos obter o respectivo número perfeito fazendo Pn = (2n-1) (2n – 1).

Pn=1 = (21-1) (21 – 1) = 1
Pn=2 = (22-1) (22 – 1) = 6
Pn=3 = (23-1) (23 – 1) = 28
Pn=4 = (24-1) (24 – 1) = 120
Pn=5 = (25-1) (25 – 1) = 496
...

Perceba que quando 2n – 1 não é primo, nos casos de n=1 e n=4, o resultado não será um número perfeito. Então o primeiro desafio desta abordagem é garantir que tenhamos como 2n – 1 um número primo.
E esse desafio é muito fácil resolver. Matematicamente, podemos definir que 2n – 1 é um número primo e, pronto, resolvemos o nosso problema. Porém, resolvendo um, aparece outro: mas 2n – 1 é um primo de Mersenne?
Para garantir que o número primo Pn = 2n – 1 seja um primo de Mersenne deve existir um valor inteiro n que valide a expressão. Ou seja, se existir um valor n tal que n = log2(Pn+1) seja inteiro, então Pn será um primo de Mersenne.
A abordagem consistirá, então, de percorrer a lista de números primos, verificar se é um primo de Mersenne e, quando for, calcular o respectivo número perfeito. Com sorte, nós já sabemos calcular os números primos de uma forma eficiente

Como gerar 200.000 primos o mais rápido possível em Python?

Então basta percorrer esses valores e verificar quais são primos de Mersenne, calculando o número perfeito:
# Percorre a lista de números primos menores que N:
for prime in sieve_of_eratosthene(N):

    # Calcula o valor de n que define o Pn:
    n = math.log2(prime+1)

    # Verifica se n é inteiro, sendo um primo de Mersenne:
    is_mersenne = n.is_integer()

    # Se for um primo de Mersenne, calcula o número perfeito:
    if is_mersenne:
        print(2**(n-1) * prime)

Veja funcionando no Repl.it | Ideone | GitHub GIST
Assim, testando aqui, ele levou cerca de 34 segundos para calcular até o número perfeito 137438691328. Acima disso comecei a ter problemas com memória, que buscarei resolver em breve.
Referências adicionais
Dois vídeos que recomendo assistir sobre o assunto são:

Perfect Numbers and Mersenne Primes - Numberphile
Perfect Number Proof - Numberphile

Buscando otimizar o código, consegui fazer sem utilizar o Sieve. Basicamente o que o código faz é definir um gerador que retorna todos os números primos de Mersenne verificando se o número é primo e utilizando o teste de primalidade de Lucas-Lehmer.
def is_prime(number):
    # Condição para number=2 ignorada propositalmente, visto que a menor entrada será 3
    i = 3
    while i**2 <= number:
        if number % i == 0:
            return False
        i += 2
    return True

def lucas_lehmer(p):
    s = 4
    M = 2**p - 1

    for _ in range(p - 2):
        s = ((s * s) - 2) % M
    return s == 0

def mersenne_primes():
    p = 3
    while True:
        if is_prime(p) and lucas_lehmer(p):
            yield (p, 2**p - 1)
        p += 2

Para utilizá-lo, por exemplo, buscando os 10 primeiros números perfeitos, basta fazer:
numbers = mersenne_primes()

for _ in range(10):
    p, mersenne = next(numbers)
    perfect = 2**(p-1) * mersenne
    print(perfect)

Veja funcionando no Repl.it | Ideone | GitHub GIST
Alguns resultados que obtive:

Para os 10 primeiros números perfeitos: 0.0003993511199951172s
Para os 15 primeiros números perfeitos: 1.9178969860076904s
Para os 16 primeiros números perfeitos: 6.957615613937378s
Para os 17 primeiros números perfeitos: 28.416791677474976s
Para os 18 primeiros números perfeitos: 78.89492082595825s
Para os 19 primeiros números perfeitos: 93.7487268447876s

Para 20 eu fiquei com preguiça de esperar.
Comment: "*ainda não é conhecido pela matemática nenhum número perfeito ímpar - no dia que descobrirem eu edito a solução, prometo*" - Você acha que isso é antes ou depois de resolverem o problema P=NP? Será que até semana que vem já acham algum número perfeito ímpar?
Comment: "*Euclides demonstrou que o número 2**(p-1)*(2**p-1) é um número perfeito par se p for um número primo*" - Isso é um "*se*", ou é um "*se, e somente se*"?
Comment: @VictorStafusa bom ponto - e com isso percebi que faltaram as referências ali
Comment: E para o caso de números perfeitos ímpares? Ninguém nunca conseguiu descobrir um, mas também ninguém nunca conseguiu provar que não existem. Esse teorema de Euclides serve para os números perfeitos pares apenas.
Comment: Basta inserir o laço for abaixo do : yield perfect_number e pedir para ir printando?
Comment: Só para lembrar, não basta, ser número primo para gerar números perfeitos, tem que ser os Primos Mersenne --> https://pt.m.wikipedia.org/wiki/Primo_de_Mersenne
Comment: @weltonvaz sim, isso está comentado bem no início da resposta, na nota.
Comment: @anderson-carlos-woss Só foi citado a fórmula, NÃO o tipo de Números Primos! Por senão pode pensar que qualquer número primo geraria número perfeito!
Comment: @weltonvaz resposta reformulada, veja se ficou mais claro assim :D
Comment: @anderson-carlos-woss valeu cara, ficou muito, muito melhor. Desculpe se fui inconveniente, mas sou obstinado(ou melhor louco mesmo) para achar um fórmula, para Números Primos de Mersenne. Que podesse ser resolver em tempo polinomial por uma Máquina de Turing não determinística!
Comment: @weltonvaz inconveniente nenhum, qualquer coisa que seja para colaborar com a qualidade sempre é bem-vinda. Se quiser, temos o [chat](https://chat.stackexchange.com/rooms/11910/estouro-de-pilha) para conversas mais diretas.
Comment: Acredito que quando Vc falou isso, fez como brincadeira. Mas como a matemática é sempre surpreendente, olha esse materia que acabei de ler:
Matemático afirma que resolveu problema de 160 anos que vale US$ 1 milhão - Revista -Galileu - A teoria afirma que a distribuição de números primos não é aleatória (como é classificada), mas pode seguir um padrão descrito por uma equação. https://revistagalileu.globo.com/Ciencia/noticia/2018/09/matematico-afirma-que-resolveu-problema-de-160-anos-que-vale-us-1-milhao.htm
Comment: https://revistagalileu.globo.com/Ciencia/noticia/2018/09/matematico-afirma-que-resolveu-problema-de-160-anos-que-vale-us-1-milhao.html
Answer: O seu programa apenas está levando um tempo muuuuuuito longo para calcular.
Observe que você tem um for dentro do outro. O laço de fora vai rodar mais de 33 milhões de vezes para achar o 5º número. O laço de dentro vai percorrer em cada iteração o mesmo valor do número do laço externo menos 1.
Se o laço externo roda n_max vezes, isso significa que o laço de dentro vai acabar executando um número de vezes igual n_max * (n_max - 1). Se n_max for 33550336, então o laço interno vai ter que rodar 1.125.625.012.162.560 de vezes até que o quinto número seja encontrado. Para chegar a esse número de mais de um quadrilhão de iterações, é possível que o programa leve alguns dias.
Já para encontrar o 8589869056, ele provavelmente levaria anos.
É possível fazer algumas simplificações:

Cortar o laço interno quando soma ultrapassar n.
Quando você encontra que n % div == 0, você encontra dois divisores, e não apenas um. Um deles é div e o outro é n / div. Com isso, você consegue diminuir o limite superior da iteração e só precisa ir até a raiz quadrada de n.
Já fazer soma começar com 1 e começar a testar a partir do 2. Pode parecer bobo, mas sem isso as duas otimizações anteriores não funciona porque ao achar o 1, ele também acharia o n e cortaria o laço imediatamente.

Com isso, é possível otimizar o laço interno mais ou menos assim:
soma = 1
for div in range(2, math.ceil(math.sqrt(n))):
    if n % div == 0:
        soma += div
        div2 = int(n / div)
        if (div != div2):
            soma += div2
        if soma > n:
            break

Você também pode acrescentar um parâmetro n_min e ao invés de percorrer de 1 até n_max, percorrer de n_min até n_max. Com essas mudanças, ao pesquisar os números perfeitos no intervalo 33550337 e 33550338, ele acha o 33550336 num piscar de olhos.
O código completo fica assim:
import math

def perfeito(n_min, n_max):
    lista = []
    for n in range(n_min, n_max + 1):
        soma = 1
        for div in range(2, math.ceil(math.sqrt(n))):
            if n % div == 0:
                soma += div
                div2 = int(n / div)
                if (div != div2):
                    soma += div2
                if soma > n:
                    break
        if n == soma:
            lista.append(n)
    return lista

print(perfeito(33550335, 33550337))

Veja aqui funcionando no ideone.
Tentei usando print(perfeito(2, 33550337)). Os números 6, 28, 496 e 8128 surgiram em milisegundos (coloquei um print antes do append para ver isso). No entanto, ainda demora várias horas para o 33550336 aparecer.
Answer: Somando às resposta já publicadas, um ponto a ser notado é que todo o número perfeito é um número hexagonal. Então, ao invés de testar um por um dos números, você pode percorrer apenas os números hexagonais. Ex:
def gen_hexagonal():
    n = 1
    while True:
        yield (2 * n * (2 * n - 1)) // 2
        n += 1

for i, num in gen_hexagonal():
    print(num)

# 1, 6, 15, 28, 45, 66, 91, 120, 153, 190, 231, 276, 325, 378, 435, ...

Exemplo funcionando


guardar um tipo de dados em ficheiro em linguagem c

Question: Tenho esta estrutura de dados:
typedef struct
{
    ListaCartao tabelaCartao[HASHSIZE];
    ListaArtigos tabelaArtigos[HASHSIZE];
    char localidade[MAXLOCALIZACAO];
}tCelulaSuperdume, *SuperDume;

SuperDume superMercadoLocal[CONJUNTOSUPERDUME];
char localSuperDume[MAXLOCALIZACAO];
int indiceLocalSuperDume = 0;

Dentro de SuperDume tenho duas tabelas de Hash. Depois tento guardar um SuperDume em ficheiro e não consigo:
void EscreveFicheiro(char nomeFich[])
{
    FILE* f;
    if (fopen_s(&f, nomeFich, "wb") == NULL)
        printf("Erro");

    else
    {
        SuperDume aux;
        for (i = 0; i < CONJUNTOSUPERDUME; i++)
        {
            aux = superMercadoLocal[indiceLocalSuperDume];
            fwrite(&aux, sizeof(SuperDume) * CONJUNTOSUPERDUME,1,f);
        }
        fclose(f);

    }
}

O ficheiro abre, só que não consegue fazer o fwrite, retornando-me o seguinte erro:

Editado.
Tenho o seguinte código
void EscreveFicheiroCartoes(char nomeFich[])
{
    FILE* f;

    if (fopen_s(&f, nomeFich, "wb") == NULL)
        printf("Erro");

    ListaCartao aux;
    for (i = 0; i < HASHSIZE; i++)
    {
        aux = superMercadoLocal[indiceLocalSuperDume]->tabelaCartao[i];

        if (aux == NULL)
            continue;

        else
        {
            while (aux != NULL)
            {
                fwrite(&(aux), sizeof(ListaCartao), 1, f);
                aux = aux->proximo;
            }
        }
    }
    fclose(f);
}

Answer: Eu não consigo achar a descrição de fopen_s no Standard de C; deves estar a usar um compilador não Standard :-)
A descrição de fopen_s fornecida pela Microsoft e a maneira como usas o valor devolvido pela função não são coerentes ... por isso deduzo que também não seja essa a versão que estás a usar.
Vê no manual do teu compilador como funciona o teu fopen_s.
Ou usa a função do Standard que já tem dado provas ao longo de tantos anos
f = fopen(nomefich, "wb");
if (f == NULL) {
    perror(nomefich);
    exit(EXIT_FAILURE);
}

Edit: encontrei o fopen_s no Standard C11, no apendice K, como facultativo.
A descrição no Standard é coerente com a descrição da Microsoft.

Returns
The fopen_s function returns zero if it opened the file. If it did not open the file or if there was a runtime-constraint violation, fopen_s returns a nonzero value.

Ou seja, quando a função devolve 0 é porque "funcionou"
// NULL é automaticamente convertido para 0
if (fopen_s(&f, nomeFich, "wb") == NULL)
    /* fopen_s funcionou */
else
{
    /* fopen_s não funcionou */
}

Nota: a meu ver fica melhor usar 0 na comparação; não há vantagem em "meter NULL ao barulho"
Comment: obrigado , pensei que a forma segura do fopen funciona-se de igual forma que o fopen. Mas mesmo assim , não consigo escrever a estrutura em ficheiro, apenas me escreve um caracter : 'è' , nada mais
Answer: aux é um ponteiro.
fwrite(&aux, sizeof(SuperDume) * CONJUNTOSUPERDUME,1,f);
//     |     ^^^^^^^^^^^^^^^^^ tamanho dum ponteiro
//     \--> endereço dum ponteiro

Experimenta
if (fwrite(aux, sizeof *aux, CONJUNTOSUPERDUME, f) != CONJUNTOSUPERDUME) /* erro */;
//              \---------/  ^^^^^^^^^^^^^^^^^ numero de elementos
//                tamanho de cada elemento

Mas não ponhas o fwrite dentro dum ciclo; ou então mete, mas com a esrita de apenas 1 elemento de cada vez.
Comment: ja tentei escrever o SuperDume (tipo de dados constituido por duas hash tables e uma "string" )

Mas não consegui nada, perguntei a um professor de outra linguagem de programação e ele disseme para utilizar o serialize. Andei a procura mas não entendi nada daquilo.

Entao decidi comerçar a guardar em ficheiro apenas as listas ligadas.


Why kill [pid] does not work?

Question: I face a problem trying to kill a pid. I have a ruby pid that i try to kill but nothing happens.
lsof -i   (service list)

ruby      282 xxx    3u  IPv4 0xffffff80111f4c20      0t0  TCP localhost:49206 (LISTEN)
ruby      282 xxx    9u  IPv4 0xffffff800fa29c20      0t0  TCP *:hbci (LISTEN)
ruby      282 xxx   10u  IPv4 0xffffff80115406c0      0t0  TCP localhost:hbci->localhost:49400 (ESTABLISHED)
kill 282

The same things
ps -A | grep ruby

282 ??         0:24.54 /xxx/.rvm/gems/ruby-1.9.2-p320/gems/ruby-debug-ide-0.4.17.beta14/bin/rdebug-ide
  324 ttys000    0:00.00 grep ruby
kill 282

still nothing.
May be someone faced already this issue?
Comment: you can try kill -9 pid.
Answer: kill -9 pid should work. Kill neads a signal to send (-9 = SIGKILL).
Answer: See THIS for usage of the 'kill' command. You must send a signal to the PID ID to tell it why it is closing. Also, make sure that you are killing as root.

Why kill [pid] does not work?


Existe autoincrement no oracle?

Question: Tentei utilizar o autoincrement no Oracle e não consegui, existe isso no Oracle?
Segue código:
CREATE TABLE Pessoa
(
ID_PESSOA integer not null,
NOME varchar2(30),
ENDERECO varchar2(40),
CIDADE varchar2(20),
CONSTRAINT PK_ID_PESSOA PRIMARY KEY AUTOINCREMENT (ID_PESSOA)
);

Comment: https://stackoverflow.com/questions/11296361/how-to-create-id-with-auto-increment-on-oracle
Comment: como já comentado use `sequence`, aqui uma pergunta com um exemplo: https://pt.stackoverflow.com/questions/188883/duvida-utiliza%c3%a7%c3%a3o-do-sequence-oracle
Comment: O Oracle não possui um tipo de dado "auto-incremento", ele utiliza um objeto `SEQUENCE` para fazer `auto-incremento` de uma olhada [aqui](https://www.oracle.com/br/technical-resources/articles/addressing-use-sequences-oracle.html)
Comment: Sequence e Trigger , exemplos publicados
Answer: Não e Sim.
Como disse o colega  Zé Reis:
NÃO porque:
O oracle não tem uma característica que se possa setar AUTO_INCREMENT
SIM porque:
O oracle possui a opção de criar uma sequência [1]
CREATE SEQUENCE customers_seq
 START WITH     1000
 INCREMENT BY   1
 NOCACHE
 NOCYCLE;

Você cria sua tabela normal:
CREATE TABLE "db"."tabela"
    (
     id_campo NUMBER NOT NULL ENABLE,
     NOME VARCHAR2(4000 BYTE) NOT NULL ENABLE
     CONSTRAINT "id_campo_pk" PRIMARY KEY ("id_campo ")
   )

Ai quando você for fazer o insert você chama essa sequência que você criou
  INSERT INTO tabela
      (id_campo, nome)
    VALUES
      (customers_seq.nextval, 'texto1');

Para mais informações você pode dar uma olhada nessa resposta
Espereo ter ajudado

Existe autoincrement no oracle?


Calculus - Comparative Rates of Change

Question:
I am working on this problem but can't quite get the correct answer. My working:
The question asks for $\frac{dh}{dt}$ where $h = \frac{1}{2}a$ which can be caculated using $\frac{dh}{dt} = \frac{dV}{dh}/\frac{dV}{dt}$
if $ V = \frac{1}{3}\pi h^2 (3a-h)$, when $h=\frac{1}{2} a$
$V = \frac{5}{24}\pi a^3 $
$\frac{dV}{dh} = \frac{15}{24}\pi a^2$ (expressed in a)
$\frac{dV}{dh} / \frac{dV}{dt} $= $\frac{15}{24}\pi a^2/3 \pi a^3 = \frac{15}{72}a$ but the answer is $4a$
Answer:
You have $dh/dt=(dV/dh)/(dV/dt),$ which is upside-down.
Correct is $dh/dt=(dV/dt)/(dV/dh).$

$dV/dh=(\pi/3) \cdot d(3ah^2-h^3)/dh=$ $(\pi/3)\cdot(6ah-3h^2).$
When $h=a/2$ this is $(\pi/3)\cdot (3a^2-3a^2/4)=$ $(\pi)\cdot (a^2-a^2/4)=$ $3\pi a^2/4.$

So when $h=a/2$ we have $$(dh/dt)=(dV/dt)/(dV/dh)=(3\pi a^3)/(3\pi a^2/4)=4a.$$
Comment: Thanks a lot for highlighting the clarification, and corrections in a number of places during differentiation, much appreciated.
Comment: Could I ask for a quick clarification on the intuition behind point one? Going back to it I can see - a change in time leads to a change in volume ($\frac{dV}{dt}$) while a change in volume leads to a change in height ($\frac{dh}{dV}$). So $\frac{dV}{dt} * \frac{dh}{dV} = \frac{dh}{dt}$?Then to get it into a workable form the denominator is inverted and division used instead of multiplication?
Comment: In some calculations we can treat terms like $dh, dt,dV$ as if they were non-zero numbers For example, in this Q, as $V$ and $h$ are strictly monotonic functions of $t.$

Calculus - Comparative Rates of Change


Format array data in table

Question: The data are presented in the format:
tags_list = [
    ['foo'],
    ['foo', 'boo', 'goo'],
    ['boo', 'zoo']
]

I'm writing this data to table:
for tags in tags_list:
    cursor.execute("""INSERT INTO tags_table VALUES (%s);""", (tags,))

BUT this way data in table becomes to type tuple:
(['foo'],)
(['foo', 'boo', 'goo'],)
(['boo', 'zoo'],)

while I'm expecting:
{'foo'}
{'foo', 'boo', 'goo'}
{'boo', 'zoo'}

Is it possible to convert data to normal PostgreSQL's ARRAY view?
Comment: Pass `tags` instead of `(tags,)`.
Comment: Can you put your table structure here ~
Comment: @cᴏʟᴅsᴘᴇᴇᴅ then I'll get an exception `not all arguments converted during string formatting`
Comment: It doesn't make sense to me that you can vary the values inserted into the table. How does this even work? You don't even specify any columns names. I can't see how this would work.
Comment: @FrankAK table contains just one column TEXT[], for testing
Comment: Which `Python-API` for pg you have used?
Comment: @FrankAK psycopg2
Answer: I simple create a table by follow sql:
CREATE TABLE contacts (
 id serial PRIMARY KEY,
 name VARCHAR (100),
 phones TEXT []
);

I am assume you are use pydb and I have create a table like the below show
 id | name |    phones
----+------+--------------
  1 |      | {123,222,33}

My python code is just simple insert into one list .
import pgdb

conn = pgdb.connect(database='test')

cur = conn.cursor()

lst = ['123','222','33']
cur.execute('insert into contacts(phones) values (%s)', (lst,))
conn.commit()

It's work for me! I guess you did not commit your cursor or your field type is no right!
Back to your example, i have create a table like yours:
CREATE TABLE tags_table(tags TEXT[]);

Before run my python code, let check table .
test=# select * from tags_table;
 tags
------
(0 rows)

and my python code :
#import pgdb
#conn = pgdb.connect(database='test')
#if psycopg2 has used
#try this
import psycopg2
conn = psycopg2.connect(database='test')
cursor = conn.cursor()

tags_list = [
    ['foo'],
    ['foo', 'boo', 'goo'],
    ['boo', 'zoo']
]

for tags in tags_list:
    cursor.execute("""INSERT INTO tags_table(tags) VALUES (%s);""", (tags,))

conn.commit()

After run the above code, my table got those result:
test=# select * from tags_table;
     tags
---------------
 {foo}
 {foo,boo,goo}
 {boo,zoo}
(3 rows)

I don't really understand why you need to show the result as {} but there are a simple way to do this by declare your own List type.
class MyList(list):
    def __str__(self):
        items = ','.join(self)
        return '{' +'{}'.format(items if items else '') + '}'
    def __repr__(self):
        return self.__str__()

for i in d:
    j = MyList(i[0])
    print j

and you will got the result as below show!
{foo}
{foo,boo,goo}
{boo,zoo}
{foo}
{foo,boo,goo}
{boo,zoo}

Comment: when I'm checking table in python script, data type in table is `tuple`
Comment: Yes, python show list with `()` but pg show list with `{}`.
Comment: that's cool but problem is how to fix that behavior in python))
Comment: @AntoshaShmonoff hey,as you expect result ,your maybe expect to covert it to pg style with {},it is very easy to do it with python but you should know python will be use {}to set type
Comment: and you're right again, sets has no indexes, so they cannot be converted to postgres arrays
Comment: @AntoshaShmonoff hey guy! i have update the answer which maybe you want ~
Comment: it's all about perfectionism and curiosity
Answer: Here's some compromise solution:
cursor.execute("""SELECT * FROM tags_table;""")
rows = cursor.fetchall()
for row in rows:
    print(row[0])

¯ \ _ (ツ) _ / ¯

Format array data in table


How can I have a view  tag render markup correctly?

Question: Objective : show a link on the column heading of the table so that the user can reach an explanation page on the content of the column.
I am having trouble figuring out how to add a link to a  tag in my View, simply.
So I need a field label to contain HTML.
For example if I enter My field label in Field configuration label input, the resulting table header is not a link and the markup is visible (plain text).
Table Format settings : no sticky headers and no sortable columns.
Any tip here?
Views Field Configuration:

The result:
Comment: You can use a twig template and insert the link via twig.
Comment: What are your Table Format settings? Drupal can use sticky headers for tables, and it can set the table header cells as sorting links for their columns, so overriding table header cells with links is a lot more nuanced than simply changing the field label. Can you use a different Formatter than Default to get the link you want? Have you tried Rewrite options?
Comment: @prkos question edited. Default Formatter and Rewrite options are only working with Field value and not Label, if I'm not mistaken.
Comment: Yes, Formatter and Rewrite work on values, I must have been thought about the Style options, there is a separate Label option there. It does allow for the change in HTML element, but the anchor isn't on the list. The Label field is meant to be taking in only text, no HTML, so you might need to preprocess or twig that Label to allow HTML as input, then your link might work as you've written it. You'd still have to careful with setting table Format options (sorting etc).
Comment: I guess Patrick Kenny had the solution since the beginning then, as stated (and then erased later...). I suppose I need to create views-view-field--view-name--field-body.html.twig and write the appropriate output? Could anyone point me to the right direction with Twig syntax here?
Answer: with Views UI, in the HEADERsection, add a Global Text area with this Content in Text format = Full HTML:
Ajouter

and it gives something like:
Comment: Thanks for answering but this not in the View header I need a link, this is in table header (th).
Comment: @Toki – Screenshots in your question may help clarifying this.
Answer: maybe using hook_views_pre_view...
function hook_views_pre_view(ViewExecutable $view, $display_id, array &$args)
{
  switch ($view->id()) {
    case 'your_view_id':
      switch ($display_id) {
        case 'your_view_display_id':
          $fields = $view->display_handler->getOption('fields');
          foreach ($fields as $key => $value) {
            if ($key == something) {
              $newLabel = 'whatever';
              $view->setHandlerOption($view->current_display, 'field', $key, 'label', $newLabel);
            }
          }
          break;
        default:
      }
      break;
    default:
  }
}

I use it only to change the label of some fields but you may try to handle your link this way.


EPPlus Format Cell as "Accounting" Number

Question: In Excel you can format numbers in the following format:

I'd like to format a cell with this format in EPPlus, but I don't see that property available:

I've looked a number of other formats, , but none of them are the same. I also tried to set the "BuildIn" number(it has no setter, this didn't work). I'm trying to use the system format, vs roll my own custom format. Is it possible to use the "Accounting" format with EPPlus?
Comment: Why not make a dummy spreadsheet and set a cell to the format you want. Then read that cells formatting using EPP (or with VBA) and see what the actual format is. Then there should be no guessing.
Answer: EPPlus does not include the number formats built into Excel so you must set it manually.
All the built-in formats in Excel have an actual number format. For accounting, the format is:

-$* #,##0.00-;-$* #,##0.00_-;-$* "-"??-;-@-

The format above may differ depending on your region/settings. To see what the format is for any built-in formats:

Right-click a cell and select Format Cells
Click on your built-in format, in this case Accounting

Click on Custom to see the format of the previously selected
format

Apply the format to your cells:
ws.Cells["A1:A5"].Style.Numberformat.Format = "_-$* #,##0.00_-;-$* #,##0.00_-;_-$* \"-\"??_-;_-@_-";

Answer: I used this format is simulating same as "Accounting Number" in the Excel.
ws.Cells["A1:A5"].Style.Numberformat.Format = "_($* #,##0.00_);_($* (#,##0.00);_($* \"-\"??_);_(@_)"

Answer: I don't know what an accounting number format looks like, but if you want the dollar sign behind the number, you can do this.
ws.Cells["A1:A25"].Style.Numberformat.Format = "#,##0.00 $";

Comment: If you look at the question's image of the spreadsheet, the accounting format puts the dollar sign in front of the number, not behind it. Specifically, it places the dollar sign at the beginning of the cell.
Answer: In my testing, none of the answers to date are exactly correct. The cell contents look fine, but Excel doesn't recognize them as Accounting, so they show up as "Custom" in the format drop-down list. The following format string is recognized by Excel as "Accounting" and not "Custom":
const string AccountingFormat = @"_(""$""* #,##0.00_);_(""$""* \(#,##0.00\);_(""$""* ""-""??_);_(@_)";

ws.Cells["A1:A25"].Style.Numberformat.Format = AccountingFormat

(The differences with the other answers are the dollar signs are quoted here, and the inner parentheses are escaped.)


Given two transcendental numbers, is their difference algebraic?

Question: It is straightforward that a transcendental plus an algebraic is transcendental. I wonder if, given two transcendentals x and y we may find such algebraic a that x+a=y?
Comment: How about $x=\pi$ and $y=\pi+1$?
Comment: It depends on the two numbers. In principle, the difference of two transcendental numbers may be anything.
Comment: How about $x = e$ and $y = 2e$?
Comment: Hmm. If you are *given* $x$ and $y$, then of course $a=y-x$. This could be anything, depending on $x$ and $y$. For example, take $x=\pi$ and $y=1+\pi$. Or take $x=e$ and $y=e^2+e$.
Comment: I think we still don't know anything about $\pi-e$...
Answer: You answered yourself: if $x+a=y$, then $x,y$ are a pair of transcendentals that differ by an algebraic.
This is of course not the case for any pair $x,y$, because there are many more transcendentals (uncountable) than there are algebraics (countable).
Answer: You should be able to see the following:
Each transcendental belongs to a countable set of transcendentals which differ from itself and from each other by an algebraic number.
Since these sets of transcendentals are countable, and a countable collection of countable sets is countable, there must be an uncountable number of such sets to include all the transcendentals.


Amazon ec2 reserve instance

Question: We received the education credit (valid for 1 year) from Amazon to use, and just wondering if we can buy reserved instance (3years) using that credit?
Is there any way to reserve how much bandwidth we can use too ?
Thanks
Answer: The AWS education credit looks like it's a general usage credit, so just think of it as taking the credit amount off your AWS services bill.  You can use it towards a reserved instance, but since the credit is only valid for 1 year, you may not recoup the full amount; for example, if your credit is $500 and you pay $300 up front for a reserved instance and then incur $100 of instance costs in the first year, you'll lost the remaining $100 from your education credit unless you use it for something else within the first year.
You can't reserve bandwidth on AWS, you just pay as you go.
Comment: It is possible that the credit can be applied to related storage costs (i.e. S3 and/or EBS), bandwidth usage, etc.

Amazon ec2 reserve instance


Sort numbers with the format x.x.x.x in perl

Question: Say for example the numbers are in format :
1.1.10
184.108.40.206
188.8.131.52
1.1.11
1.1.12
1.1.13
126.96.36.199
1.1.3
1.1.4

And the wat I am looking for output is :
1.1.3
1.1.4
1.1.10
184.108.40.206
18.104.22.168
1.1.11
1.1.12
1.1.13
22.214.171.124

Comment: Quick hack: `sort { eval $a cmp eval $b } @numbers`
Comment: @Cupidvogel http://stackoverflow.com/a/7142844/725418 In the comments there, tchrist elaborates on this particular "trick". Basically it does what ikegami said, it turns the quasi-numerical string into a proper string, after which we can "safely" use it with the `cmp` operator. I named it a quick hack, because it is probably not a good way to solve this particular problem.
Comment: @Cupidvogel, `126.96.36.199` is the same as `v126.96.36.199`, which stringifies to `chr(1).chr(1).chr(1).chr(10)`. In other words, `eval "22.214.171.124"` is an expensive and risky way to do `pack "W*", split /\./, "184.108.40.206"`. Yes, you can change the "`C`" in the pack templates in my solutions to "`W`". Does numbers up to 4 billion on 32-bit Perls, and 2**64-1 on 64-bit machines.
Comment: Duplicates:  http://stackoverflow.com/questions/6917314/how-can-i-sort-a-list-of-ip-addresses-in-perl
Comment: Not a duplicate of 6917314. iDev's strings don't have exactly 4 parts, and he didn't say anything about them being limited to 255.
Comment: These look remarkably like version numbers and thus [Sort::Versions](http://search.cpan.org/~edavis/Sort-Versions-1.5/Versions.pm) might be in consideration.
Comment: @TLP, that was just awesome! Can you explain how it works? Doing `print eval('184.108.40.206')` prints out some garbage value. What is the basis of comparison here?
Answer: use Sort::Key::Natural qw( natsort );
my @sorted = natsort @data;

or (no modules)
my @sorted =
   map $_->[0],
   sort { $a->[1] cmp $b->[1] }
   map [ $_, pack('C*', split /\./) ],
   @data;

or (no modules, faster, but requires an array rather than a list for input)
 my @sorted =
   map $data[unpack('N', $_)],
   sort
   map pack('NC*', $_, split /\./, $data[$_]),
   0..$#data;

In the pack templates, you can change C to n or N. C allows numbers up to 255. n allows numbers up to 65,535. N allows numbers up to 4 billion.
Comment: cant figure out how the sort works when it gets the pack(...) data,pack in this case just creates a single octet value out of each version number... isnt comparing each number with 'cmp' will do the same?
Comment: @soulSurfer2010, `"1.2.1" cmp "1.16.1"` fails because the numbers have a variable width. Using `pack C`, makes them all the same width. It boils down to `"\x01\x02\x01" cmp "\x01\x10\x01"` which sorts correctly because of the padding added.
Answer: Try the following:
use Modern::Perl;
use Sort::Naturally  qw{nsort};

my @numbers = nsort(qw{1.1.10 22.214.171.124 184.108.40.206 1.1.11 1.1.12 1.1.13 126.96.36.199 1.1.3});
say for @numbers;

Output:
1.1.3
1.1.10
22.214.171.124
188.8.131.52
1.1.11
1.1.12
1.1.13
184.108.40.206

Hope this helps!
Answer: This may be easier for you to comprehend:
sub min { $_[0] <= $_[1] ? $_[0] : $_[1] }
sub comp
  {
  ($a1,$a2) = @_;
  @a1 = @{$a1};
  @a2 = @{$a2};
  for (0..min(scalar @a1,scalar @a2))
     {
     return 1 if $a1[$_] > $a2[$_];
     return -1 if $a2[$_] > $a1[$_];  #exit early if an inequality is found
     }
  return 0 if @a1 == @a2; #both array are equal, thus both numbers are equal
  return @a1 > @a2 ? 1 : -1; #arrays are equal upto a certain point, thus longer array is 'greater'
  }
@sourcearray = ('1.1.10','126.96.36.199','184.108.40.206','1.1.11','1.1.12','1.1.13','188.8.131.52','1.1.3','1.1.4');
@individual = map { [split /\./] } @sourcearray; #splits each number into arrays consisting of individual numbers
@sorted = sort {comp($a,$b)} @individual; #sort algo decides which of these two arrays are 'greater'
{
local $" = ".";
print "@{$sorted[$_]}\n" for 0..$#sorted;
}


What happens if the result of match was found wrong after the match day?

Question: Consider a situation where Team A and Team B are playing a cricket match,
Team A scored some odd runs (lets assume 250 runs).
Team B is chasing the score, while chasing they require 2 runs from a ball. Bowler bowls the ball Umpire somehow declare it as a NO ball and batsman is able to take only single run from that ball in this case the Team B wins the match because of that NO ball.
Now my question is after a day of the match Team A checks the replays and finds it was not a NO ball or it was not appropriate to say that ball was not legal to be bowled and if that is considered the result should have been tie instead of Team B winning the match, will the result can be changed on the appeal from Team A?
Does they have any right to ask for or report for the same?
If yes then is there any team who have done like this in Cricket History?
Answer: No. The result stands. Law 21.10 (Result not to be changed) is very clear:

Once the umpires have agreed with the scorers the correctness of the scores at the conclusion of the match - see Laws 3.15 (Correctness of scores) and 4.2 (Correctness of scores) - the result cannot thereafter be changed.

In a controversial Test match at The Oval in 2006, the umpires held that Pakistan had forfeited the match due to refusing to take the field, and that England had therefore won. This result was then controversially overturned by the ICC, who declared that the result should be considered a draw. However, the ICC later changed the result back to the original decision, a forfeit, after the MCC - the custodians of the Laws - declared that this would set a "dangerous precedent," and that the ICC had no power to change the result. All this underlined the fact that the umpires' decision must stand.
Answer: As per Law 3 (The umpires)

7. Fair and unfair play
The umpires shall be the sole judges of fair and unfair play.

So umpire's decision is considered as the last decision. No matter whether it found wrong on the next day. So in the given scenario Team-B remains winner.
Comment: True, but I don't think this query relates to fair and unfair play (which covers matters such as intimidatory bowling, stealing runs, etc.); section 15 of Law 3 may be more relevant (Correctness of scores).


How can I use Mangopollo's IconicTileData to update the main tile of my application?

Question: I write an app for Windows Phone 7/8. I want my default tile to look like WP8's one, so I use Mangopollo in such manner:
var tile = new IconicTileData
{
      Title = "WP Day",
      Count = 8,
      BackgroundColor = Colors.Transparent,
      IconImage = new Uri("/ApplicationIcon.png", UriKind.Relative),
      SmallIconImage = new Uri("/ApplicationIcon.png", UriKind.Relative),
      WideContent1 = "WP Developer Day",
      WideContent2 = "use Windows Phone 8 features",
      WideContent3 = "on Windows Phone 7 apps"
}.ToShellTileData();;

var tile2 = new StandardTileData
{
    Title = "E",
    Count = 9
};

ShellTile.ActiveTiles.FirstOrDefault().Update(tile);

But it does not effect. When I want to update "first" tile with tile object (IconicTileData) does not any effect. But when I use tile2 object the tile is updating. Any ideas?
I saw thats possible in a few apps, for example TinyDO.
Answer: Tried this code after modification from link : http://wp.qmatteoq.com/tag/mangopollo/
and it works.. it is this line which does the trick:
Uri navigationUri = new Uri("/MainPage.xaml?Id=5", UriKind.Relative);
private void OnCreateWideTileClick(object sender, RoutedEventArgs e)
{
    if (true)
    {
        var tile = new IconicTileData
        {
            Title = "WP Day",
            Count = 8,
            BackgroundColor = Colors.Transparent,
            IconImage = new Uri("/Assets/Tiles/IconicTileMediumLarge.png", UriKind.Relative),
            SmallIconImage = new Uri("/Assets/Tiles/IconicTileSmall.png", UriKind.Relative),
            WideContent1 = "WP Developer Day",
            WideContent2 = "use Windows Phone 8 features",
            WideContent3 = "on Windows Phone 7 apps"
        }.ToShellTileData();

        ShellTileExt.Create(new Uri("/MainPage.xaml?Id=5", UriKind.Relative), tile, true);
    }
    else
    {
        MessageBox.Show("This is Windows Phone 7");
    }
}

private void OnUpdateTileClick(object sender, RoutedEventArgs e)
{
    if (Utils.IsWP8)
    {
        IconicTileData tile = new IconicTileData
        {
            WideContent1 = "This is the new content",
            WideContent2 = "The tile has been updated",
            WideContent3 = "with success"
        };

        Uri navigationUri = new Uri("/MainPage.xaml?Id=5", UriKind.Relative);
        ShellTile.ActiveTiles.FirstOrDefault(x => x.NavigationUri == navigationUri).Update(tile);
    }
}


Can updateInterval be set for a design document?

Question: In Couchbase 2.2, I have set the updateInterval parameter both globally (for the view update daemon) and for an individual design document. It appears that only the global setting is always taking effect. On the other hand, if I set updateMinChanges for a design document, it takes effect just fine.
Curiously, the documentation example does not show updateInterval being set for a design document:
<code>{
   "_id": "_design/myddoc",
   "views": {
      "view1": {
          "map": "function(doc, meta) { if (doc.value) { emit(doc.value, meta.id);} }"
      }
   },
   "options": {
       "updateMinChanges": 1000,
       "replicaUpdateMinChanges": 20000
   }
}
</code>
Can updateInterval be set for a design document?
Answer: it is not currently possible to set an updateInterval at the design document level.  A feature request has been added to provide this function @ https://www.couchbase.com/issues/browse/MB-11594


What are steps to clear sendmail queue without rebooting?

Question:                     Begin Note

I believe this is a similar but not duplicate question to another server fault question, because the bounced message is to a legitimate email address that I can send to currently with the bounced message remaining in the queue. That other Server Fault question links me to an answer, rather than provides it within the answer itself, which is something I've been marked down for in the past.
                    End Note

My question is how to I clear a locked sendmail system without rebooting. Here is some background:
I have a Linux Red Hat Enterprise WS 5 server that is solely dedicated to transferring and receiving meter configuration and meter reads information. The server sends a small to moderate amount of email using sendmail.
Linux h2oamr.Somewhereton1.local
2.6.18-348.el5 #1 SMP
Wed Nov 28 21:22:00 EST 2012
x86_64 x86_64 x86_64 GNU/Linux

Once a month this little shell script runs as root, and this month, some content came back showing a message was in the queue.
#!/bin/bash
#
# sendmail_alive.sh
# Change History:
# Charles M. Norton 12/13/2010
# Fix header, and add su -l -c to send as amr.

/usr/bin/mailq -v > /tmp/mailq.txt
su -l amr -c \
"mail -s 'sendmail status' firstname.lastname@example.com < /tmp/mailq.txt"

Here is what my bot sent me:
        /var/spool/mqueue (1 request)
-----Q-ID----- --Size-- -Priority- ---Q-Time--- --------Sender/Recipient--------
r3E822QG016051*    1208      31671 Apr 14 04:02 <firstname.lastname@example.com>
                        <firstname.lastname@example.com>
        Total requests: 1

I tried sending email out to the same recipient as that mail stuck in the queue, and it got to that use almost immediately. However, the original stuck message remained in the sendmail queue.
Then, I tried these commands:
sendmail -bm
sendmail -OTimeout.hoststatus=0m -q -v

but kept getting a locked pid message. Unfortunately, I did not preserve the locked .pid message.
Rebooting cleared the problem.
Is it possible to accomplish clearing the queue without rebooting, and, if so, how?
Comment: Could you post the relevant sendmail process state as reported by ps? Version for linux-debian: `ps auxw | grep sendmail`. IMHO you should try to locate which delivery timeout should be reduced.
Comment: Don't have it anymore, but you've answered what I need to look at.
Answer: Try to find out "why is the message locked?"
Could you post the relevant sendmail process state as reported by ps? Version for linux-debian: ps auxw | grep sendmail. IMHO you should try to locate which delivery timeout should be reduced.
The most likely suspects: Timeout.connect, Timeout.iconnect.
Comment: The message wasn't locked. The pid was locked. I've edited the OP to include the message the bot sends me. root sends the message. An account named dbadmin gets the message. While that message sits in the queue, root can send as many emails as it likes to dbadmin, and they go through.
Comment: man `mailq`: `The status characters are either * to indicate the job is being processed;`. I call messages with `*` locked. Add `ps` report to your `mailq` report. [Sendmail processes change their ps visible data]


How do I prevent CKEditor 4 from stripping Google AdSense asynchronous tags?

Question: For whatever reason, CKEditor 4 is stripping Google AdSense asynchronous tags from my Full HTML text format.
What starts as this (placeholders substituted for IDs):

Ends up as this:

Again, this is in the Full HTML text format and I'm able to get the ins tag through without attributes, but not with attributes, even though other tags have no problems getting their attributes through to save.
For what it's worth, I do have the following set on the CKEditor profile:
config.allowedContent = true;

UPDATE
CKEditor is only stripping the ins tag (and attributes) when it's an empty tag as given by AdSense. If I add anything – a non-breaking space, even – CKEditor is preserving the ins tag and attributes.
Per tenken's suggestion, I added the following line to my config, but it didn't help.
config.protectedSource.push( /<\/ins\>/g );

Comment: Are you sure this behavior does not happen with just a filter format of `FULL_HTML` and no WYSIWYG editor?
Comment: Good question. The snippet is getting through using a textarea without CKEditor.
Answer: Have you read this blogpost (not by me) Drupal WYSYWG Module Custom CkEditor Configuration by Philip Norton.
Your


Why do Italian football teams tend to be so different to teams in other countries?

Question: In particular I've noted two features about Italian teams that are fairly uncommon (not unknown, but uncommon) elsewhere, especially in other major football nations:

Stadium shares are very common even with world class teams. See the Milans for instance, two of the biggest teams in Europe, but they share a stadium.

I understand this is because they don't own the stadium, rather its owned by the city. But how did this state of affairs come to be in Italy?

Teams often aren't named after where they're located. Of course, the teams often have very good reasons for being named what they are. But it is very common in Italy that teams are not named after their hometown; Juventus, Sampdoria, Lazio (named after the province), Atalanta, etc...

It strikes me that football in Italy must have evolved in a significantly different way to England, Spain, or Germany. Just what is the explanation here?
Comment: Lazio & Roma also share a stadium, the Stadio Olimpico
Answer: The naming thing isn't so odd. Often a club needs a name to distinguish it from other clubs in the same area, and just giving a more specific neighborhood doesn't cut it, because the club didn't start off wanting to represent a specific location as much as to embody some sort of ideal.
Many are named after some sort of classic ideal, like Atalanta. You'll find a Young Boys in Switzerland, which is basically what Juventus means. Ajax is another classical reference. Sparta (Rotterdam) as well. The classical civilizations were into their sports, hence the nod from 19th and early 20th century club founders. I think you might find a number of lower league teams in other countries named like this.
Sampdoria is a contraction of two merging clubs.
Lazio I think we can give a pass, because it's common to name clubs after smaller or larger regions like Bavaria or St Pauli, or even all of Spain.
In Denmark some of the clubs are called B1909 or B93, which is literally "football club of {year}".
In Sweden you'll find AIK, the "general or public football club".


Debian Jessie NS LOOKUP ip

Question: When i use command
nslookup 192.168.1.1 or (my real ip address)

back this:
126.96.36.199.in-addr.arpa   name = 18.104.22.168-my-net.net

I want to change name with my website example
220.127.116.11.in-addr.arpa    name = www.example.com

How to do this? Thank you!
Answer: in-addr.arpa is special domain name to get full qualified domain name of host from ip address. This is called
 reverse DNS lookup.
You need to assign new DNS zone 1.168.192.in-addr.arpa on your DNS server. Then you can add PTR record 1  PTR  full.your.host.name in file of this zone.
You can see an example of such zone at  https://serverfault.com/questions/462474/how-do-i-set-up-a-reverse-zone-file
Also another way exists. Add string 192.168.1.1 full.your.host.name to file /etc/hosts on your workstation.
Comment: i have add  my.real.ip.addr mydomain.com, in /etc/hosts but name it's not change for the ip address
Comment: Your ip address isn't real, add it as real with same hostname.
Comment: The ip address in post (192.168.1.1) it's example, not ip address who i use. I have bind9 dns server. Do you tell me particularly how to add ptr record?  Thank you!
Comment: I updated my answer.
Answer: Why do you want to do that? If it is for a 192.168.x.y it means a private IP on your network so it will depend on how you run your local recursive nameservers (and you will need to do basically what is in Mikhail answer).
If it is for a public IP (what you call the real ip ?) you will need to ask the owner of the IP block in which your IP is, so that he will either, do the reverse resolution for you, or delegate this handling to your nameservers if you have more than one IP address from them and you want to handle the reverse resolution yourself. Hard to help you more without knowing the real IP we are speaking about.
Comment: I want to do this, because this host my.real.ip.my-net.net it's confuse my mail server.

Debian Jessie NS LOOKUP ip


sum of multiplication of two binomial coefficients

Question: Is there any formula for calculating
$\sum_{k=0}^n {n\choose k} {2n\choose 2k}$ ?
One possible way is to use Stirling's approximation, but couldn't reach a reasonable answer.
Comment: @labbhattacharjee Didn't get your meaning. Can you be more specific?
Comment: $$(1+x^2)^n(x+1)^{2n}=\sum_{k=0}^n\binom nk(x^2)^k\cdot\sum_{k=0}^{2n}\binom{2n}k x^{2n-k}$$

Compare the coefficients of $x^{2n}$
Answer: This is probably not the most pleasant result.
$$S_n=\sum_{k=0}^n {n\choose k} {2n\choose 2k}=\, _3F_2\left(\frac{1}{2}-n,-n,-n;\frac{1}{2},1;-1\right)$$ where appears the generalized hypergeometric function.
However, plotting $\log(S_n)$ as a function of $n$ reveals almost a straight line and a simple linear regression gives $$\log(S_n)\approx 2.06597 n-2.27715$$ ($R^2=0.999998$) which gives at least the order of magnitude.


$(a+b+c+d)^{10}$ expansion such that the powers are different from 2

Question: We can rewrite the question as $x+y+z+w=10$ and $x,y,z,w \not=2$, how many integer values fulfill the condition ?
i know how to solve the question when the constrain is $>$ and not $\not=$.
Comment: I think is confusing to use the same labelings for variables and exponents, maybe you can change it to $(x+y+z+w)^{10}$?
Comment: Usually this problems with the restriction $\neq$ are better solved with inclusion-exclusion,
Answer: Instead of finding
$$A=\{(x,y,z,w)\geq 0\hbox{ such that }x+y+z+w=10, x,y,z,w\neq 2\}$$
 Let's find the complement
$$A^c=\{(x,y,z,w)\geq 0 \hbox{ such that }x+y+z+w=10, x=2 \hbox{ or }y=2 \hbox{ or }z=2 \hbox{ or }w=2\}$$
This complement can be expressed as a union of the sets
$$A^c=\bigcup_i\{(x_1,x_2,x_3,x_4)\geq 0\hbox{ such that }x_1+x_2+x_3+x_4=10, x_i=2\}$$
To get cardinality of the union of sets you can use inclusion-exclusion method. At the end you will get
$$|A^c|={4\choose 1} |B_3(8)|-{4\choose 2}|B_2(6)|+{4\choose 3}|B_1(4)|$$
Where
$$B_k(n)=\{(x_1,\dots,x_k)\geq 0:x_1+\dots+x_k=n\}$$
We know that $|B_k(n)|={n+k-1\choose k-1}$.


Set delay so the played notes appear to be "doubled"

Question: I guess many of you are familiar with the dotted 8 delay, so when you play plain 8th notes, you hear 1/16 notes.
Little illustration to show what I mean:
<code>         1 - - - 2 - - - 3 - - - 4 - - -
Played:  x   x   x   x   x   x   x   x
Delay:         x   x   x   x   x   x   x
Result:  x   x x x x x x x x x x x x x x
</code>
Example I can think of (and love): Frusciante when playing don't forget me.
So to the question itself: I have a lot of trouble setting the delay to that required dotted 8s when playing live (I use tap tempo) to set the delaytime. Often it ends up not being perfect, which kinf of ruins the effect. Also not keeping the tempo of the song perfectly is a problem. Are there any tips on how to set the delaytime more easily?
Also, when I'm here already, can anyone tell me how Frusciante has his delay set up in this song exactly?
Answer: To get the dotted eighth delay in time in the first place, the easiest way (of course) is to use a delay that has a mode that will give you dotted eighths when you tap quarter notes. If you don't have that facility, the easiest way is probably to count three sixteenths in your head and tap to that beat.
As for staying in time, the first requirement is for your own playing to stay in time with the delay, so that the effect turns out nice and precise. It can help to focus mentally on a slower pulse, from quarter notes to full bars, rather than get distracted by each individual note - don't worry about missing a note here or there, but keep the notes you do play in time.
Secondly, if you're not using a delay that's 'clocked' from an external source, it's important for other players to realise that the delay has to act as the 'master clock' for the band - so the drummer in your band has to follow your delayed part. This may take a bit of practice - it might be worth taking 10 minutes here or there to practice one on one with them.
The more egalitarian solution is to use a master clock source that can drive a click track for the drummer to listen to, and that your delay can also sync to (e.g. via MIDI), but this might be overkill for many situations (and not all delays can do this).
In either of those cases, you have to realise that you're not the boss of the timing any more - let the delay (or click) be the boss, and you stay in time with it, rather than make it stay in time with you. A good practice routine is set the delay time roughly and then get into the habit of syncing your playing to the delay.
If you want to be able to vary the tempo and still keep the synced dotted 8th effect, it helps to be able to re-tap with a minimum of audible artefacts - some delay pedals are better able to do this than others.
If you have enough spare pocket money, a product currently available on the market is the Free The Tone flight time delay - this has a microphone and BPM analyser that will listen to the performance and adjust the delay time automatically...

Though I'm not sure if that would be able to deal with the example you linked to!


Question of ultrafilters/prime ideals in finite Boolean algebras

Question: Let $U$ be an ultrafilter in a finite Boolean algebra $A$. Does $U$ necessarily contains an atom of $A$?
Let $I$ be a prime ideal in the same finite Boolean algebra $A$. Does $I$ necessarily contains the complement of an atom of $A$?
If these two statements are correct. Does this mean that there are as many ultrafilters (prime ideals) in a finite Boolean algebra as there are atoms (complements of atoms)?
Comment: hint: every ultrafilter in a finite set is principal
Answer: Every ultrafilter on a finite Boolean algebra is fixed (principal) and therefore contains an atom; there is exactly one ultrafilter for each atom. The ultrafilters on a Boolean algebra are precisely the prime filters, so the prime ideals are the complements of the ultrafilters. Thus, both statements are correct.
Comment: Thank you very much. I suppose this is why ultrafilters are considered as a generalisation of atoms.
Comment: @student: You're very welcome.


How can I get a direct link on behalf of a client?

Question: I know I can use the following command to get a direct link to the video audio by using:
<code>youtube-dl -f 139 --get-url https://www.youtube.com/watch?v=dQw4w9WgXcQ
</code>
Which will give me the URL
However, this link is only accessible on the machine that the command ran on. I tried changing out the IP with the client's IP, but it still does not work. The client cannot run the command themselves, so it has to be done somewhere else.
Is there a way to generate a direct link that can be used by clients?
Answer: This is answered in the youtube-dl FAQ in detail.
For some of the websites youtube-dl supports, you can simply give the link to the client. For others, it may be possible to change something. For instance, there was a time when you could send requests to YouTube via IPv6 and you'd be given an IP-unrestricted download URL.
Since all the links YouTube hands out are limited to the IP address of the client which requested the link, there is no way to get a link that works on a machine with a different IP address.


Approximate $\int_0^x e^{f^{-1}(t)} \; dt$ from an approximation of $f$

Question: I am wondering if it is possible to have an approximation of this integral
$\int_0^x e^{f^{-1}(t)} \; dt$
I have only an approximation of $f$: $f(\frac{i}{n}),\; i=0, \dots, n$?
Many thanks, Peter.
Answer: By the substitution $t=f(u)$ and integrating by parts, it can be shown that the integral equals
$$xe^{f^{-1}(x)}-\int^{f^{-1}(x)}_{f^{-1}(0)}f(u)e^udu$$
Assume $f$ is monotonically increasing (the decreasing case is similar). Since the domain of $f$ is $[0,1]$, we have $0\le f^{-1}\le 1$.
By assuming $f^{-1} (x)\approx 1, f^{-1}(0)\approx 0$, we can approximate the integral by Riemann sum
$$\frac1n\sum^n_{i=1}f\left(\frac in\right)e^{i/n}$$
In conclusion,
$$\int^x_0 e^{f^{-1}(t)}dt
\approx xe^{f^{-1}(x)}-\frac1n\sum^n_{i=1}f\left(\frac in\right)e^{i/n}
$$

Error term bound
The error term $\epsilon :=\text{actual}-\text{approximation}$ can be bounded by
$$\epsilon\le e\cdot f(1)(1-f^{-1}(x))+O\left(\frac1n\right)$$
$$\epsilon \ge xe^{f^{-1}(x)}(1-f^{-1}(x))+f^{-1}(0)f(0)-O\left(\frac 1n\right)$$
Comment: Thanks for the answer, is it possible to get an approximation of the term $xe^{f^{-1}(x)}$?
Comment: @Clifford Do we know the range of $f$?
Comment: Sadly:  $f:[0, +\infty) \rightarrow [0, +\infty)$ and $ \lim_{x \rightarrow +\infty} f(x) = +\infty$


SQL Server Creating complicated SQL Query for 3 tables

Question: Please help me creating this SQL query for SQL Server 2008.
I've wasted 1 day thinking of this but I cannot find the solution:
I have 3 [tables] with respective (columns):

[table_users] TB1 (Id, Name)
[table_schedule] TB2 (Id, userId, dateScheduled)
[table_schedule_confirmation] TB3 (Id, scheduleId, confirmationStatus)
confirmationStatus -> 0 = cancelled, 1 = confirmed

I must filter [TB1] by selecting a day, it must list only user names that:

are not scheduled at all (userId doesn't exist in [TB2] for selected day)

or

if scheduled, there's a matching confirmation for (scheduleId) in [TB3] and
(confirmationStatus) must be 0 (cancelled)

Problems:

There can be more than one entries in TB2 and TB3 for a userId and date

Date Filter = 31/03/2013
Situation 1 (1 confirmed schedule):
Situation1 http://img255.imageshack.us/img255/1508/sqld.png
As you can see, I've scheduled 4 times for user 1, but he cancelled the 3 first, confirming only on the 4th time.
Situation 2 (1 pending schedule):
Situation1 http://img854.imageshack.us/img854/8116/sql2s.png
In this case, user hasn't confirmed the 4th (id=16) schedule yet.
Situation 3 (all schedules cancelled):
Situation1 http://img41.imageshack.us/img41/5720/sql3s.png
User cancelled all the 4 schedules.
Situation 4 (no schedules for user on that date):
Situation1 http://img255.imageshack.us/img255/9679/sql4.png
No schedules for selected day.
In resume:
Filtering by date, I must list only users that applies to Situations 3 and 4 and NOT applies to Situations 1 and 2 !
I must make this filter, to populate a dropdown with only users that are available for that day.
This is what I've tried so far:
DECLARE @dataAg datetime SET @dataAg = '2013/03/31 16:30'

SELECT T1.id, T1.name
FROM [tbl_users] T1
WHERE
    (NOT EXISTS
         (SELECT *
          FROM [tbl_schedule] T2
          WHERE T2.userId = T1.id
          AND CONVERT(date,T2.scheduledDate) = CONVERT(date, @dataAg))
    )
    OR
    (EXISTS
         (SELECT *
          FROM [tbl_schedule] T2, [tbl_scheduleConfirmation] T3
          WHERE T2.id = T3.idSchedule
            AND T2.userId = T1.id
            AND CONVERT(date,T2.scheduledDate) = CONVERT(date, @dataAg))
     AND
     NOT EXISTS
          (SELECT *
           FROM [tbl_schedule] T2, [tbl_scheduleConfirmation] T3
           WHERE T2.id = T3.idSchedule
             AND T3.confirmation = 1
             AND T2.idUser = T1.id
             AND CONVERT(date, T2.scheduledDate) = CONVERT(date, @dataAg))
          )

Comment: This question does not show any research effort. It is important to **do your homework**. Tell us what you found and ***why*** it didn't meet your needs. This demonstrates that you've taken the time to try to help yourself, it saves us from reiterating obvious answers, and most of all it helps you get a more specific and relevant answer. [FAQ](http://stackoverflow.com/questions/how-to-ask).
Answer: Assuming you want all the columns in TB1 this query should get you what you need.
SELECT *
FROM TB1
WHERE ID IN
      (SELECT ID
       FROM TB3
       WHERE confirmationStatus = 1
         AND scheduleID IN
             (SELECT ID
              FROM TB2
              WHERE DATE(dateScheduled) = 'YOUR_ENTERED_DATE'))

In the future, you may also want to include what exactly you are using (mySQL, SQL Server, etc.)
Comment: Thank you David, but i don't think this would do the job. Seems to be a little more complicated.
Comment: Help us understand what you are asking for by using pseudocode.  You want all the data in `TB1` where the `user` has a `confirmed scheduling` on a `date that you specify`?
Comment: I want to list all users (id + name) from TB1 that are "available" for a specified date...

By "available" i mean:
- There's no entry with this date + userId on TB2 at all
OR
- if there's one or more entries for this date + userId on TB2, all of these entries must have a corresponding row in TB3 (cancelling or confirming)
AND
- none of the corresponding entries in TB3 have "confirmation = 1"
Comment: in another words:

- This user was never scheduled for that day
OR
- If he was scheduled for that day, he must have confirmed or cancelled the schedule, if he didn't replied the scheduled yet then he must not be listed as we don't know if he will be available
AND
- There must not be any entry in TB3 for this date + user that is confirmed
Answer: Finally i got it.
DECLARE @dataAg datetime SET @dataAg = '2013/03/31 16:30'

SELECT T1.id, T1.name FROM [tbl_users] T1
WHERE
NOT EXISTS(
    SELECT * FROM [tbl_schedule] T2 WHERE T2.userId = T1.id AND CONVERT(date,T2.scheduledDate) = CONVERT(date,@dataAg)
    )
OR
(
NOT EXISTS
    (
        SELECT * FROM [tbl_schedule] T2 WHERE
        NOT EXISTS
        (
            SELECT * FROM [tbl_scheduleConfirmation] T3 WHERE T2.id = T3.idSchedule
        )
        AND T2.userId = T1.id AND CONVERT(date,T2.scheduledDate) = CONVERT(date,@dataAg)
    )
AND
NOT EXISTS(
    SELECT * FROM [tbl_schedule] T2, [tbl_scheduleConfirmation] T3 WHERE
    T2.id = T3.idSchedule AND T3.confirmation = 1 AND T2.userId = T1.id AND CONVERT(date,T2.scheduledDate) = CONVERT(date,@dataAg)
    )
)

Thank's anyway.