Erro ao tentar buscar dados

Question: Tenho uma aplicação que deve inserir dados em uma tela e na outra consultar no banco
O problema é que sempre que tento executar a consulta da erro:
Log
11-16 18:43:31.023: I/ActivityManager(26887): Timeline: Activity_launch_request     id:br.com.exercicio8 time:58351239
11-16 18:43:31.103: D/AndroidRuntime(26887): Shutting down VM
11-16 18:43:31.103: W/dalvikvm(26887): threadid=1: thread exiting with uncaught    exception (group=0x41996d88)
11-16 18:43:31.103: E/AndroidRuntime(26887): FATAL EXCEPTION: main
11-16 18:43:31.103: E/AndroidRuntime(26887): Process: br.com.exercicio8, PID: 26887
11-16 18:43:31.103: E/AndroidRuntime(26887): java.lang.RuntimeException: Unable to start activity ComponentInfo{br.com.exercicio8/br.com.exercicio8.LocalizacaoAtual}: android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0
11-16 18:43:31.103: E/AndroidRuntime(26887):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2237)
11-16 18:43:31.103: E/AndroidRuntime(26887):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2286)
11-16 18:43:31.103: E/AndroidRuntime(26887):    at android.app.ActivityThread.access$800(ActivityThread.java:144)
11-16 18:43:31.103: E/AndroidRuntime(26887):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1246)
11-16 18:43:31.103: E/AndroidRuntime(26887):    at android.os.Handler.dispatchMessage(Handler.java:102)
11-16 18:43:31.103: E/AndroidRuntime(26887):    at android.os.Looper.loop(Looper.java:212)
11-16 18:43:31.103: E/AndroidRuntime(26887):    at android.app.ActivityThread.main(ActivityThread.java:5135)
11-16 18:43:31.103: E/AndroidRuntime(26887):    at java.lang.reflect.Method.invokeNative(Native Method)
11-16 18:43:31.103: E/AndroidRuntime(26887):    at java.lang.reflect.Method.invoke(Method.java:515)
11-16 18:43:31.103: E/AndroidRuntime(26887):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:878)
11-16 18:43:31.103: E/AndroidRuntime(26887):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
11-16 18:43:31.103: E/AndroidRuntime(26887):    at dalvik.system.NativeStart.main(Native Method)
11-16 18:43:31.103: E/AndroidRuntime(26887): Caused by: android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0
11-16 18:43:31.103: E/AndroidRuntime(26887):    at android.database.AbstractCursor.checkPosition(AbstractCursor.java:426)
11-16 18:43:31.103: E/AndroidRuntime(26887):    at android.database.AbstractWindowedCursor.checkPosition(AbstractWindowedCursor.java:136)
11-16 18:43:31.103: E/AndroidRuntime(26887):    at android.database.AbstractWindowedCursor.getString(AbstractWindowedCursor.java:50)
11-16 18:43:31.103: E/AndroidRuntime(26887):    at br.com.exercicio8.LocalizacaoAtual.onLocationChanged(LocalizacaoAtual.java:85)
11-16 18:43:31.103: E/AndroidRuntime(26887):    at br.com.exercicio8.LocalizacaoAtual.onCreate(LocalizacaoAtual.java:46)
11-16 18:43:31.103: E/AndroidRuntime(26887):    at android.app.Activity.performCreate(Activity.java:5231)
11-16 18:43:31.103: E/AndroidRuntime(26887):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
11-16 18:43:31.103: E/AndroidRuntime(26887):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2201)
11-16 18:43:31.103: E/AndroidRuntime(26887):    ... 11 more

Código que é executado do SQLiteOpenHelper
public Cursor consult(int latiude, int longitude){
          SQLiteDatabase db = this.getReadableDatabase();
            String query = "select "+CADASTRO_COLUMN_NOMELOCAL+" from " + LOCATION_TABLE_NAME + " where + " + CADASTRO_COLUMN_LATITUDE + " = " + latiude + " AND "+ CADASTRO_COLUMN_LONGITUDE + " = " +longitude;
            Cursor registro = db.rawQuery(query, null); //objeto do sqllite que representa um objeto de qualquer tabela
            return registro;
       }

Código na classe
@Override
public void onLocationChanged(Location location) {
    double lat = location.getLatitude();
    double lon = location.getLongitude();
    campoLat = (int)lat;
    campoLong = (int)lon;

    BD dbm = new BD(getApplicationContext());
    Cursor seleciona = dbm.consult(campoLat,campoLong);
    seleciona.moveToFirst();
    String aux = seleciona.getString(seleciona.getColumnIndex(BD.CADASTRO_COLUMN_NOMELOCAL));
    /*
    if(aux != "" || aux != null)
    {
        local.setText(aux);
    }
    else
    {
        local.setText("Local desconhecido");
    }*/

Codigo do banco
 public class BD extends SQLiteOpenHelper {
   public static final String DATABASE_NAME = "location.db";
   public static final String LOCATION_TABLE_NAME = "cadastro";
   public static final String CADASTRO_COLUMN_NOMELOCAL = "nomeLocal";
   public static final String CADASTRO_COLUMN_LATITUDE = "latitude";
   public static final String CADASTRO_COLUMN_LONGITUDE = "longitude";

public BD(Context context) {

      super(context, DATABASE_NAME , null, 1);

}

@Override
public void onCreate(SQLiteDatabase db) {

     db.execSQL(
              "create table " + LOCATION_TABLE_NAME +
              "(" +
                CADASTRO_COLUMN_NOMELOCAL + " text primary key, " +
                CADASTRO_COLUMN_LATITUDE + " text,"+
                CADASTRO_COLUMN_LONGITUDE + " text" +
              ")"
              );

}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    String query = "drop table if exists "+ LOCATION_TABLE_NAME;
    db.execSQL(query);
    onCreate(db);
}

   @Override
public void onOpen(SQLiteDatabase db) {
        String query = "drop table if exists "+ LOCATION_TABLE_NAME;
        db.execSQL(query);
        onCreate(db);
}

public boolean insert (String nome, String latitude, String longitude)
   {
      SQLiteDatabase db = this.getWritableDatabase();
      ContentValues contentValues = new ContentValues();

      contentValues.put(CADASTRO_COLUMN_NOMELOCAL, nome);
      contentValues.put(CADASTRO_COLUMN_LATITUDE, latitude);
      contentValues.put(CADASTRO_COLUMN_LONGITUDE, longitude);

      db.insert(LOCATION_TABLE_NAME, null, contentValues);
      return true;
   }

   public Cursor consult(int latiude, int longitude){
          SQLiteDatabase db = this.getReadableDatabase();
            String query = "select * from " + LOCATION_TABLE_NAME + " where " + CADASTRO_COLUMN_LATITUDE + " = " + latiude + " AND "+ CADASTRO_COLUMN_LONGITUDE + " = " +longitude;
            Cursor registro = db.rawQuery(query, null); //objeto do sqllite que representa um objeto de qualquer tabela
            return registro;
       }

}
Ocorre o erro quando executo essa linha
 String aux = seleciona.getString(seleciona.getColumnIndex(BD.CADASTRO_COLUMN_NOMELOCAL));

Para apagar a tabela
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    String query = "delete table if exists "+ LOCATION_TABLE_NAME;
    db.execSQL(query);
    String queryy = "drop table if exists "+ LOCATION_TABLE_NAME;
    db.execSQL(queryy);
    onCreate(db);
}

Comment: O erro significa que o `Cursor` está vazio. Ao usar `moveToFirst` o cursor se posiciona uma posição antes da primeira linha, você deve executar um `moveToNext` para consultar (com o `getXYZ`) a primeira e as demais linhas em sequência, verificando se ele não retornou `false` ou verificar usando `isAfterLast`.
Comment: Obrigado pela ajuda Wakim, só tenho um pequeno problema, meu banco não esta sendo excluido quando no onUpgrade, alguem poderia me ajudar?
Comment: A sintaxe do `delete` esta errada, falta o `from`. Além disso ja que esta dropando a tabela, não precisa executar o `delete`.
Comment: Tentei apenas com o drop mas a tabela continua, sendo que para poder colocar um valor novo,quando inicio o app em meu smartphone tenho que ir em configurações -> Aplicativos -> app -> Limpar dados
Comment: Não está dando algum erro? Como está seu `onCreate`, pode incluir na pergunta?
Comment: Pior que não indica nenhum erro. Incluir a classe do banco toda
Comment: Está incrementando a versão sempre que atualiza o schema? Ele só executa o `onUpgrade` quando isso ocorre. Quando você quer apagar o banco? A cada deploy do aplicativo ou a cada abertura?
Comment: De preferência sempre que o app for abert0 (se não for possível pode ser no deploy mesmo)
Answer: Quando se está usando o Cursor, primeiramente deve usar o moveToFirst. Com isso o cursor irá apontar para antes da primeira linha.
Para acessar os dados, use moveToNext verificando se o retorno foi true. Por exemplo:
BD dbm = new BD(getApplicationContext());
Cursor seleciona = dbm.consult(campoLat,campoLong);

seleciona.moveToFirst();

if(seleciona.moveToNext()) {
    String aux = seleciona.getString(seleciona.getColumnIndex(BD.CADASTRO_COLUMN_NOMELOCAL));

    // Restante do código que dependa de aux
}

Caso queira iterar sobre os resultados:
BD dbm = new BD(getApplicationContext());
Cursor seleciona = dbm.consult(campoLat,campoLong);

seleciona.moveToFirst();

// Eh bom fazer o cache do índice, já que ele nunca muda e evitamos processamento desnecessário
int index = seleciona.getColumnIndex(BD.CADASTRO_COLUMN_NOMELOCAL);

while(seleciona.moveToNext()) {
    String aux = seleciona.getString(index);

    // Restante do codigo que dependa de aux
}

No caso do onUpgrade, a sintáxe do delete está incorreta. O correto seria:
delete from nome_tabela

Lembrando que o comando delete não suporta if exists.
Além disso já que esta dropando a tabela, não é necessário deletar os registros antes.
Edit:
Para limpar o banco na abertura do aplicativo, basta usar a classe Application.
Registrando uma classe Application você consegue ser notificado do início e o fim da sua aplicação. Com isso pode deletar os registros da tabela.
Basta criar uma subclasse de android.app.Application e registrá-la no AndroidManifest com o atributo name:
<application
    android:name="nome.do.seu.pacote.NomeDaApplication">

Na sua NomeDaApplication basta sobreescrever o método onCreate e limpar a tabela:
public NomeDaApplication extends android.app.Application {

    @Override
    public void onCreate() {
        // Recupera seu banco e apaga os dados
        SQLiteDataBase bd = openOrCreateDatabase("NOME_DO_BANCO", MODE_PRIVATE, null);

        // Usar o bd para apagar as linhas
    }
}

Só tenha um certo cuidado porque não tenho certeza da ordem de execução do SQLiteOpenHelper e a execução do onCreate. Imagino que poderá dar erro quando o banco é criado pela primeira vez.
Comment: Obrigado Wakim.

Erro ao tentar buscar dados


Find the rate of change in a given direction of two variable function

Question: The temperature of any given point on a plate is given by:
T(x,y)=180e^(−(x^2/4)−(y^2/3))
I need to find the rate of change in temperature along the direction from (2,1) to (-1,-3). I have tried taking the dot product of the gradient and unit vector, but this has not worked. I have correctly used the same technique to find the direction and magnitude of greatest increase in temperature. I have found the gradient of T to be <-180e^(-4/3), -120e^(-4/3). How do I find the rate of change from (2,1) to (-1, -3)?
Comment: It would be nice of you to show what exactly you have tried that hasn't worked, because if you did actually take the dot product of the gradient with the unit vector in the right direction, you would get the right answer. There must be some miscalculation or misunderstanding in the process of calculation.
Answer: Let $A = (2,1), B = (-1,-3)\implies \vec{u} = \dfrac{1}{|\vec{AB}|}\vec{AB}= \left(\dfrac{-4}{5}, \dfrac{-3}{5}\right)$ is the unit vector which is also the direction in which the derivative being taken along. Thus the directional derivative you are looking for is: $\nabla_{\vec{u}} f= \nabla f\cdot \vec{u}= (f_x,f_y)\cdot \vec{u}= \dfrac{-4}{5}f_x - \dfrac{3}{5}f_y$. You can find the partial derivatives, can't you ....? Also, you need to specify the point that the directional derivative is calculated at...
Comment: Wouldn't $\vec{AB}=\langle (-1-2), (-3-1) \rangle = \langle -3, -4 \rangle$?
Comment: Directional derivatives are located at (2,1), yielding Tx = -180e^(-4/3) and Ty = -120e^(-4/3). When plugging those in to the equation multiplying gradient by unit vector, I found the answer to be 36e^(-4/3), which was incorrect.
Comment: @Julia97 $\left\langle-\frac35,-\frac45\right\rangle\cdot\langle-180,-120\rangle\ne36$.
Answer: The directional derivative along a vector $\vec{v}$ is given by
$$\vec{\nabla}_v f( \vec{x} ) = \vec{\nabla} f( \vec{x} ) \cdot \vec{v} $$
But since the question asks merely in the direction of $\vec{v}$, you must instead dot with $\hat{v}=\frac{\vec{v}}{|\vec{v}|}$.
Since you were given $f(\vec{x})=T(x,y)$ and $\vec{v}$ (found through the two points), all there's left to do is compute
$$\vec{\nabla} f( \vec{x} ) \cdot \hat{v} = \vec{\nabla} T(x,y) \cdot \hat{v} =  \left< \frac{\partial T}{\partial x}, \frac{\partial T}{\partial y} \right> \cdot \hat{v}$$

Complete solution: We have $T(x,y)=180 e^{-\frac{x^2}{4} - \frac{y^2}{3}}$ thus
$$\vec{\nabla}T(x,y)= \left< -90 x e^{-\frac{-x^2}{4}-\frac{y^2}{3}}, -120 y e^{-\frac{x^2}{4} - \frac{y^2}{3}} \right>$$
and $\vec{v}= \left< -1-2, -3-1 \right> = \left<-3,-4 \right> \implies \hat{v}=\left< -\frac{3}{5}, -\frac{4}{5} \right>$. Thus
$$\begin{align*}
\left< \frac{\partial T}{\partial x}, \frac{\partial T}{\partial y} \right> \cdot \hat{v} &= \left< -90 x e^{-\frac{-x^2}{4}-\frac{y^2}{3}}, -120 y e^{-\frac{x^2}{4} - \frac{y^2}{3}} \right> \cdot \left< -\frac{3}{5}, -\frac{4}{5} \right> \\
&= 54 x e^{-\frac{-x^2}{4}-\frac{y^2}{3}} + 96y e^{-\frac{x^2}{4} - \frac{y^2}{3}}
\end{align*}$$


Average Time over a period of time in a SQL Query

Question: Hello how would i be able to get the AVG of the Minimum time across records?
Meaning, I have these records:
Id   Date    Time    Amount
1    7/1/14  9:00am  5.00
2    7/1/14  8:45am  6.00
3    7/1/14  9:30am  7.00
4    7/2/14  8:30am  4.50
5    7/2/14  9:15am  5.50
6    7/2/14  7:45am  4.75

now what i need is to get MIN of each day... so in this case it would be record 2, and 6.
but i want to some how average those times... meaning 8:45am and 7:45am ...
I want to know what is the average time first sale occurs over a time period.  Not sure how to average out the time. So to say, over a given period, generally first sale occurs around say 8:20 am (estimating)
tx very much for any assitance
Comment: What database are you using?
Comment: What data type is used to store Time?
Answer: You can try somthing like this:-
SELECT Id, Date, AVG(Time)
FROM (SELECT Id, Date, MIN(Time) AS Time
      FROM YOUR_TABLE
      GROUP BY Id, Date) AS TABLE1
GROUP BY Id, Date;

This might be helpful to you.
Answer: To get the average, convert the time to seconds, compute the average and convert it back to a time.
SELECT Id, Date, SEC_TO_TIME(AVG(sec))
FROM (SELECT Id, Date, MIN(TIME_TO_SEC(Time)) AS sec
      FROM YOUR_TABLE
      GROUP BY Id, Date) AS TABLE1
GROUP BY Id, Date;

Comment: Thanks for the reply! i see what is needed, bring down to sec from day offset, then avg, then redisplay!  i am using access so actually i needed to do this something a little different.
Answer: SELECT Format(( AVG(Table1.daTime) /86400),"hh:nn:ss") AS AvgTimeOfFirstTransaction
FROM (SELECT  date, (MIN(Time) *86400)  AS daTime
       FROM transactions
       WHERE (  (transactions.date)>=#7/1/2014# And (transactions.date)<#7/3/2014#)
       GROUP BY transactions.date
)  AS TABLE1

Comment: This is what i'd actually need for access.   ahh but i just noticed that the sec * and / is not needed, what was truely missing for my use was just the formatting back to time from both the solutions.   Tx to both of you.


Use of unresolved identifier 'GMSPlacesClient' after updating from GoogleMaps SDK for IOS to GooglePlaces SDK for IOS

Question: I am using the GoogleMaps SDK for places in my app (using essentialy the Autocomplete feature) & I saw that its now possible to use only GooglePlaces SDK.
(the GoogleMaps SDK has a big size -130MB in my .ipa file)
migration link here
I followed the instructions but I am now getting a lot of 'Use of unresolved identifier' like GMSPlaceClients ,CLLocationDegrees or  GMSAutocompleteResultsViewController  althought they suppose to be in the GooglePlaces SDK.
Any ideas what am I missing ?
Thanks for your help.
Edit: after pod install in terminal :
Comment: are you installing new versions ?
Comment: @HarshalBhavsar , Hi you can  see my edit
Answer: The class have changed.
Use : GoogleAPI.placeAutocomplete(...)
Comment: can u be more specific? Im working with the official doc [https://developers.google.com/places/ios-api/reference ]


Implicitly defined constructor deleted due to variant member, N3690/N4140 vs N4659/N4727

Question: My story starts off the same as this person's here:
Unions in C++11: default constructor seems to be deleted
The resolution here (now about three years old) is a bit unsatisfactory, because the "Digging into the standard" that the author did ended up with concluding that the behavior was as described in the standard, but unfortunately the quote is from a Note, and those are supposed to be non-normative (I've been told).  Anyways, there's a link to an old bug report on gcc that is claimed to be fixed, and they also claim that the code compiles in clang, however I'm having issues (with the same and similar code). The matter boils down to a whether or not a union-like class with a default initialized variant member should compile whether or not there is another variant member (in the same variant set) that has a non-trivial constructor.
struct X {
  X() {}        //non-trivial default constructor
};

struct U {
  union {
    X x;
    int i{0};   //default member initializer
  };
};

U u;            //error: default constructor deleted

These failed with -std=c++14 and -std=c++17 on gcc version 7.3.0 (Ubuntu 7.3.0-27ubuntu1~18.04) as well as clang version 6.0.0-1ubuntu2.
There seems to be a history of change in the standard, and so I'll put forth what I've found:

N3690/N4140:
  [12.1.4/Constructors]
  ...A defaulted default constructor for class X is defined as deleted if:

X is a union-like class that has a variant member with a non-trivial default constructor

[9.5.2/Unions]...
  [Note:
  If any non-static data member of a union has a non-trivial default
  constructor (12.1), copy constructor (12.8), move constructor (12.8), copy assignment operator (12.8), move
  assignment operator (12.8), or destructor (12.4), the corresponding member function of the union must be
  user-provided or it will be implicitly deleted (8.4.3) for the union.
  — end note]

N4659/N4727:
  [15.1.5/Constructors]
  ...A defaulted default constructor for class X is defined as deleted if:

X is a union that has a variant member with a non-trivial default constructor and no variant member of X has a default member initializer

[12.3.3/Unions]...
  [Note:
  Absent default member initializers, if any non-static data member of a union has a non-trivial default
  constructor (12.1), copy constructor (12.8), move constructor (12.8), copy assignment operator (12.8), move
  assignment operator (12.8), or destructor (12.4), the corresponding member function of the union must be
  user-provided or it will be implicitly deleted (8.4.3) for the union.
  — end note]

Anyways, it seems like at one point this code should have failed, but it was thought to be conforming and that gcc had a bug, and it was claimed to be fixed, but now it should succeed, and it doesn't compile (I may not have the chronology perfect here, it would be interesting to know the full story; figuring it out is one step further than I'd like to take) but I guess I'm just wondering what is the correct behavior?
Comment: Notes are indeed non-normative. That's a general principle for ISO standards; works the same in ISO C.
Comment: Related [Why does a struct, that has another struct wrapped in a union as a member not compile without an explicit default constructor?](https://stackoverflow.com/q/53143245/1708801)
Answer: I believe you are correct, this should be valid code now.
The original wording for the non-normative note that descirbes the old behavior comes from n2544: Unrestricted Unions (Revision 2).
That change you note in the normative section comes from Core defect report 2048: NSDMIs and deleted union default constructors which says:

According to 15.1 [class.ctor] paragraph 4 says,

A defaulted default constructor for class X is defined as deleted if:

X is a union-like class that has a variant member with a non-trivial default constructor,
...

This should make the following example ill-formed:
  struct S {
    S();
  };
  union U {
    S s{};
  } u;

because the default constructor of U is deleted. However, both clang
  and g++ accept this without error. Should the rule be relaxed for a
  union with an NSDMI?

and modified [class.default.ctor]p2 as you referenced from N4659/N4727. Additionally we can see that the case mentioned in the DR does indeed work for gcc and clang but not for MSVC see it live on godbolt.
This feels like a bug since [class.default.ctor]p2.1 should cover this case and make it will-formed since the member i has a default member initializer:

X is a union that has a variant member with a non-trivial default constructor and no variant member of X has a default member initializer,


In what sense is the sequence $(0,1,2,0,1,2,\ldots)$ convergent?

Question: In what sense is the sequence $(0,1,2,0,1,2,\ldots)$ convergent?
A problem I'm working on needs a concept of convergence which understands the fact that this sequence extended infinitely is convergent - at least in the sense that it is stable and orbits a fixed point.
The name may not be "convergence".
I can of course engineer something but I presume there is some accepted terminology I can use.
For example I want to describe that:
$$\lim_{n\to\infty}\left((1-2^{-n})+ (n\mod3)\right)$$ converges upon an orbit centred on the number $2$
Comment: There are three convergent subsequences. One converges to 0, the other converges to 1 and…
Comment: Aha. Sure there are infinitely many convergent subsequence there. For each n, make put n zeros there and make the tail to be all one… That lead me to think of this question: are there only countably many convergent subsequences?
Comment: @LiChunMin In a [sequential space](https://en.wikipedia.org/wiki/Sequential_space) like $\mathbb R$, the set of limits of subsequences is the same as the set of "accumulation points" of the sequence. See my answer for some relevant links.
Comment: Thanks @LiChunMin that's exactly the answer I need.  The problem's a little more complicated in that there are infinitely many subsequences... every one of which converges, but since there are infinitely many, there are new subsequences constantly appearing.
Answer: I would not use the word "convergent" in any sense!  This sequence is "periodic" with period 3.
Comment: The second sequence is not periodic, yet it has an important relationship to convergence since there is a finite set of limits of convergent subsequences.
Answer: You can take the already defined Cesàro summability, and sort of modify it to fit your needs. Let $(a_n)_{n=1}^\infty$ be your sequence. We can define a sequence to be Cesàro convergent if and only if
$$ \lim_{n\to \infty} \frac{1}{n}\sum_{i=1}^n a_i \in \mathbb R$$
That is, if the limit above exists, the sequence is Cesàro convergent.
Notice, in your case, the limit above converges to $1$, since that is the average value of your sequence. So, in this sense, the sequence is "Cesàro convergent around 1".
Answer: The set of "accumulation points" (sometimes "cluster points") of the first sequence is $\{0,1,2\}$ and that set for the second sequence is $\{1,2,3\}$. This is because every neighborhood of one of the numbers, say $1$, has infinitely many sequence entries in that neighborhood.
This idea of the accumulation points is closely related to other ideas of "limit set" like attractors and limit cycles.


how to split a very large database on sql server

Question: I have a 90 GB SQL Server database that I want to make more manageable.  It stores stock data from 50+ different stocks from 2009 and 2010, and each stock is a separate table.  Some tables have hundreds of millions of rows, and other have just a few million.
What I want to do is somehow split the database, so that I don't have a single database file that is 90 GB.
What I want is to be able to somehow magically split all the tables so that I can backup the 2009 data once and not have to keep on including it in the backup every time I backup the entire database, however, I would like the 2009 data to be included whenever I do a query.
Is partitioning the database the way to go?  Will it do the above for me, or will I need some other solution?  I research partitioning, but I wasn't sure if that would solve all my problems.  I wasn't able to find anything that would tell me whether or not it would migrate prexisting data, or whether it only worked for newly inserted data.
Any help or pointers would be much appreciated.
Thanks in advance,
Ken
Comment: What version of SQL Server?  Because only Enterprise provides table partitioning: http://blog.sqlauthority.com/2008/01/25/sql-server-2005-database-table-partitioning-tutorial-how-to-horizontal-partition-database-table/
Comment: Belongs on Serverfault and I have no more close votes.
Answer: Kimberly Tripp put out a great webcast series that answers questions just like these.  Instead of making a general recommendation fro your specific case, I think it would be better to check out this webcast.  I'm sure it will give you the guidance on partitioning and aging to make the right decision for your situation.
Answer: Partitioning should solve your problem of splitting the table while still having access to all the data in one query, but if you don't have Enterprise, you can still use partitioned views
To solve your backup issue once the table is split into multiple tables, then move your tables to separate filegroups and then you can backup the filegroups which aren't changing separately from the filegroups which are getting new data.
Is there any reason you have each stock in its own table?  (Because now you have 50 tables to manage the partitioning on)  If the stocks were in a single table, you could partition that one table by month, say.


Why is any(True for ... if cond) much faster than any(cond for ...)?

Question: Two similar ways to check whether a list contains an odd number:
any(x % 2 for x in a)
any(True for x in a if x % 2)

Timing results with a = [0] * 10000000 (five attempts each, times in seconds):
0.60  0.60  0.60  0.61  0.63  any(x % 2 for x in a)
0.36  0.36  0.36  0.37  0.37  any(True for x in a if x % 2)

Why is the second way almost twice as fast?
My testing code:
from timeit import repeat

setup = 'a = [0] * 10000000'

expressions = [
    'any(x % 2 for x in a)',
    'any(True for x in a if x % 2)',
]

for expression in expressions:
    times = sorted(repeat(expression, setup, number=1))
    print(*('%.2f ' % t for t in times), expression)

Try it online!
Comment: Another way to look at the filtering approach is `next((True for x in a if x % 2), False)`, which uses an explicit default to make it clear that the filtering generator doesn't yield any values that are false, even if `a` only contains even numbers.
Answer: The first method sends everything to any() whilst the second only sends to any() when there's an odd number, so any() has fewer elements to go through.
Comment: It should be noted that since it's is a generator, "everything" doesn't necessarily mean that it processes all the elements of `a`. Both versions stop when they get to the first odd number. But in the test case, there are no odd numbers, so the generator does have to go through the whole list.
Comment: The other answers have more details, but I think the brevity and clarity of this one makes it a nice top answer to read first.
Answer: (x % 2 for x in a)

This generator produces a series of falsey values until it produces a truthy value (if it does), at which point any will stop iterating the generator and return True.
(True for x in a if x % 2)

This generator will only produce exactly one True value (if it does), at which point any will stop the iteration and return True.
The additional back and forth of yielding back to any and then fetching the next value from the generator in the first case accounts for the overhead.
Comment: @don't That looks like a micro-optimisation to me, so you should only go for that if it actually makes a difference to you because it measurably speeds up your algorithm in actual practice. I wouldn't default to this style just because…
Comment: So the second way is always faster or equally fast? Is it preferable in general then? So far I've been using the first way.
Comment: In the given example all the numbers are even, so no `True` values are produced.
Comment: @deceze I have to agree, this is a serious case of micro-optimisation. We're talking about roughly 30ns extra time for running `any()` on a list of 10M elements. This question and the answers remain very interesting, but I'm going to stick to the more readable version, even if it's ever so slightly slower. With the faster version, I'd feel the need to write a comment saying why I'm using such a surprising line of code.
Answer: TL;DR The slow version has to iterate over a long sequence of false values before returning False. The fast version "iterates" over an empty sequence before doing the same. The difference is the time it takes to construct the long-false sequence vs the empty sequence.

Let's look at the byte code generate by each. I've omitted the first section for each, as they are identical for the both. It's only the code for the generators involved that we need to look at.
In [5]: dis.dis('any(x%2 for x in a)')
[...]

Disassembly of <code object <genexpr> at 0x105e860e0, file "<dis>", line 1>:
  1           0 LOAD_FAST                0 (.0)
        >>    2 FOR_ITER                14 (to 18)
              4 STORE_FAST               1 (x)
              6 LOAD_FAST                1 (x)
              8 LOAD_CONST               0 (2)
             10 BINARY_MODULO
             12 YIELD_VALUE
             14 POP_TOP
             16 JUMP_ABSOLUTE            2
        >>   18 LOAD_CONST               1 (None)
             20 RETURN_VALUE

In [6]: dis.dis('any(True for x in a if x % 2)')
[...]

Disassembly of <code object <genexpr> at 0x105d993a0, file "<dis>", line 1>:
  1           0 LOAD_FAST                0 (.0)
        >>    2 FOR_ITER                18 (to 22)
              4 STORE_FAST               1 (x)
              6 LOAD_FAST                1 (x)
              8 LOAD_CONST               0 (2)
             10 BINARY_MODULO
             12 POP_JUMP_IF_FALSE        2
             14 LOAD_CONST               1 (True)
             16 YIELD_VALUE
             18 POP_TOP
             20 JUMP_ABSOLUTE            2
        >>   22 LOAD_CONST               2 (None)
             24 RETURN_VALUE

Both are identical up to the BINARY_MODULO instruction. After that, the slower version has to yield the resulting value for any to consume before moving on, while the second code immediately moves on to the next value. So basically, the slower code has to consume a long list of false (i.e., non-zero) values to determine that there are no true values. The faster code only needs to consume an empty list.
Answer: The previous answers somewhat assume the reader is already familiar with the syntax and generators. I'd like to explain more for people who aren't.
The snippet
any(x % 2 for x in a)

is short syntax for:
any((x % 2 for x in a))

So what's happening is that (x % 2 for x in a) gets evaluated and the result value is then given to the any function. Just like print(21 * 2) computes the value 42, which is then given to the print function.
The expression (x % 2 for x in a) is a generator expression and its result is a generator iterator. That is an object that computes and hands out its values on demand. So in this case, when asked for a value, this iterator looks at the next value from a, computes its remainder modulo 2 (i.e., 0 for even and 1 for odd), and hands out that value. And then literally waits for possibly getting asked again for another value.
The any function is a second actor here. It gets the iterator as its argument, and then asks the iterator for more and more values, hoping for one that's true (note that 1 is true and 0 is false).
You can really think of it as two different persons interacting. The any-guy asking the iterator-guy for values. Again, note that the iterator-guy does not compute all values in advance. Only one at a time, whenever the any-guy asks for the next value. So it's really a back-and-forth between the two guys.
In the case of any(x % 2 for x in a), the iterator-guy, whenever asked by the any-guy for the next value, just computes one modulo value, hands it to the any-guy, and the any-guy has to judge it. Here the iterator-guy is like an incompetent junior developer, involving the manager for every single number, somewhat forcing them to hardcore micro-manage.
In the case of any(True for x in a if x % 2), the iterator-guy, whenever asked by the any-guy for the next value, doesn't mindlessly hand over just the modulo values. Instead, this iterator-guy judges the values himself, and only hands over something to the manager when there's something worthy to hand over. Namely only when he discovers an odd value (in which case he doesn't hand over 0 or 1, but True). Here the iterator-guy is like a competent senior developer doing all the work, and the manager can totally lay back and chill (and at the end of the day still take all the credit).
It should be clear that the second way is much more efficient, as they don't needlessly communicate for every ... single ... input number. Especially since your input a = [0] * 10000000 doesn't contain any odd numbers. The junior developer reports ten million zeros to the manager who has to judge all of them. With a constant back-and-forth between them for every zero. The senior developer judges all himself and reports nothing to his manager. Well, ok, both developers at the end additionally report that they're done, at which point the manager concludes False as the result of the whole any(...) expression).
Comment: I have read all three answers. This one was the most confusing one and I still have no idea what accounts for such discrepancy in performance between the two expressions in question. Isn't `True for x in a if x % 2` exactly what `any(x % 2 for x in a)` does?
Comment: Enclosed in `any(...)`, it means what I said. I have already told you what I *really mean*, and you're refusing to understand. Hence the downvote. Have a nice day.
Comment: @oguzismail I didn't want to know what "meaning" of the code you meant, I wanted to know what *code* you meant. Because I can't discuss code that I don't know. So did you mean `any(True for x in a if x % 2)`? And yes, both `any(x % 2 for x in a)` and `any(True for x in a if x % 2)` have the same meaning, pretty much the "return true if x % 2 is true for any element in a" that you said. But they achieve that in *different ways*, and one of them is faster. Just like `min(a)` and `sorted(a)[0]` mean the same thing ("minimum of `a`") but compute it in different ways that are differently fast.
Comment: Yes, it is. You're saying the same thing as the top voted answer using more words. Thanks
Comment: @oguzismail `True for x in a if x % 2` isn't even a valid expression, can you clarify what you mean?
Comment: @oguzismail No, `True for x in a if x % 2` literally means *nothing* in Python. That's [not valid syntax](https://tio.run/##K6gsycjPM7YoKPr/P6SoNFUhLb9IoUIhM08hUSEzDchSVTD6/x8A). Can you fix it and tell what you really mean?
Comment: @oguzismail The different ways that I described in the answer. Your *"first fetch the result of x % 2 and test whether it is True"* is unclear, as you're not saying which objects do those things. I see you're a bash guy, so let me try that. Compare `cat numbers.txt | print_modulo_2 | are_any_true` with `cat numbers.txt | print_true_only_if_odd | are_any_true`. The second way is faster because the lines with even numbers are discarded earlier, aren't sent through the pipe to `are_any_true`. Same in the Python code, where the generators play the `print_...` roles. . Is it clear now?
Comment: I mean, `True for x in a if x % 2` means *return true if `x % 2` is true for any element in `a`*, right? Isn't it what `any(x % 2 for x in a)` does? What does the latter do in between to achieve the same thing almost twice as slower? Without using workplace analogies and this-guy and that-guy terminology, please
Answer: Number of "checking for falsiness" is not the actual reason because in faster version we can see an if statement which intern calls bool(). That checking is done "in advance" in faster case. So in both cases python has to go through all values and check truthiness of all of them.
The procedure that showed in Chepner's answer is indeed the answer of the question. Let's find when the next item in for loop can be requested...:
In faster case, it is just after the BINARY_MODULO, but in POP_JUMP_IF_FALSE statement it has to do a little bit of work to check the truthiness(if calls bool()) while in slower version it doesn't check that there. Up until now (-1) point for faster version. BUT in slower version it has to do three steps to reach the point to request for next item, YIELD_VALUE, POP_TOP, JUMP_ABSOLUTE. So (-3) for slower version... Those three steps causes the overhead because they can not be skipped.
In other words, faster version only does "checking" to reach the point to request for next item but slower version has to do "checking + those steps".  Again both of them check for truthiness of all values.
The answer is the overhead of yielding.
Comment: @don'ttalkjustcode Since it's going to be way off topic, for last question, I said the `if obj:` statement does exactly what `if bool(obj) is True:` does, but you reject it and you said Something else calls `__bool__`. Could you tell how does this work? `if obj:` is also check for returning boolean value from `obj`'s `__bool__` method.
Comment: I think it's gotta be the `tp_as_number->nb_bool` option, maybe the `as_number` is just a misleading name.
Comment: Little nitpick: `if` doesn't call `bool()`.
Comment: @don'ttalkjustcode It does, check [this link](https://tio.run/##PY07DsMgEET7PcV0QJ0msuTCd0iPbAIO0QrQgoucnmBZ8uvmo5nya5@cHs8ivTtea8UyEQZvH2DtljNbq6vnYC7/pEhMTaszRKxwK3NMuzJ3QXw7JOElhyfK2xczFm2IYsBQ11AZZ73/AQ) please.
Comment: No, that's the object's `__bool__` method. The claim `'bool is calling'` is incorrect. Something else calls it.
Comment: @don'ttalkjustcode `if obj:` is implicitly changed to `if bool(obj) is True:` or as you said python calls `__bool__` of that object. I just intended to say the check for truthiness is done in "if statement" just like in `any()`. in both cases this `__bool__` gets called.
Comment: No, you can see [`POP_JUMP_IF_FALSE` directly uses `PyObject_IsTrue`](https://github.com/python/cpython/blob/5246dbc2a12bf8e64e18efee2fdce02a350bbf09/Python/ceval.c#L3962-L3976), bypassing `bool()`.
Comment: @don'ttalkjustcode good point Interesting, So why in every cases that `__bool__` gets called? I mean in `Any()` in `if` statement...  `[i for i in range(10) if A()]` prints that sentence 10 times, I thought this is what `bool()` does , bool() invokes `__bool__`.
Comment: `bool()` does (or rather might) invoke `__bool__`, it's just not the only thing that does.
Comment: You can disassemble that as well, should also use [`PyObject_IsTrue`](https://github.com/python/cpython/blob/044e8d866fdde3804bdb2282c7d23a8074de8f6f/Objects/object.c#L1433). Which then calls the object's `__bool__` method if none of the earlier options there apply. At least I think so. None of the options there sound like they apply.


Working with hibernate multiple Criteria with logical AND

Question: So far i've been working with only a case with 2 properties with and as logical operator so i use LogicalExpression like so
Criterion eqRef = Restrictions.eq("referenceID", referenceId);
Criterion eqType = Restrictions.eq("verificationType", type);
LogicalExpression and = Restrictions.and(eqRef, eqType);

this time along its more than 2 so i'm a bit confused.say this time i've added username property i can do the normal chaining with
session.createCriteria(this.getPersistentClass())
.add(Restrictions.eq("referenceID", referenceId))
.add(Restrictions.eq("verificationType", type))
.add(Restrictions.eq("username", username))
.list();

but now i don't know which kind of logical operator used between them.i'm also tempted to do this:
Criterion eqRef = Restrictions.eq("referenceID", referenceId);
Criterion eqType = Restrictions.eq("verificationType", type);
Criterion equsername = Restrictions.eq("username", username);
LogicalExpression and = Restrictions.and(eqRef, eqType);
LogicalExpression secondand = Restrictions.and(and, equsername);

i've see the eqAll too but i've never used it before.So do you have any idea about that?How do you do it, and thanks for reading this.
Answer: Since you're "AND"-ing all of your restrictions the grouping is irrelevant, so you can just continue on as in your second example, as there's nothing to be gained by subgrouping them, e.g.
.add(Restrictions.eq("referenceID", referenceId)).add(Restrictions.eq("verificationType", type)).add(Restrictions.eq("username", username))...

You do run into this problem where you need to group mixed "AND" and "OR" queries, if you want to group multiple "OR" values you can also add Criteria to a Disjunction
Answer: Adding these restrictions individually creates a relation of 'AND' between them. This is good enough for what you need.
Answer:
but now i don't know which kind of
  logical operator used between them.

Good answers already, but as an aside you can use the property hibernate.show_sql, set it to true, and you'll be able to see exactly what sql your criteria is producing.
Answer: just use this
criteria = session.createCriteria(Model.class).add(
                             Restrictions.between("ModelDate", dateMin, dateMax));

Comment: Can you explain what "ModelDate", "tglMin", and "tglMax" are?  I don't see them in the question and I have no idea why you would use them.
Comment: ModelDate is date column from model/entity, tglMin & tglMax I mean dateMin & dateMax in between restriction.


Show that $\int_a^bf(x)dx=0 \implies f= \hat{0}_{|[a,b]}$

Question: Let be f$:[a,b]\to \mathbb{R}$ a continuous function where $f(x)\geq 0$ for all $x\in[a,b]$.

Show that  $\int_a^bf(x)dx=0 \implies f= \hat{0}_{|[a,b]}$.

My approach via contraposition:
Let be $c\in (a,b)$ with $f(c)>0$. Then we know that due to continuity there exists a neighbourhood $U_{\delta}(c):=\{x\in[a,b]\mid |x-c|<\delta\}$ such that for all $x\in U_{\delta}(c)$ it holds $f(x)>0$.
We define a partition $P$ of $[a,b]$ as follows $P:=\{[a,c-\delta,c+\delta,b]\}$. If we now consider the lower Darboux sum we get:
$$
L(f,P)=0(c-\delta-a)+m\delta+0(b-c+\delta)=m\delta>0,\\
\text{where } m:=\inf\{f(x)\mid x\in[c-\delta,c+\delta]\}.
$$
We know that for every refinement of $P'$ of $P$ it holds: $L(f,P')\geq L(f,P)>0$ and hence $\sup\{L(f,P)\mid P \text{ is a partition of } [a,b]\}=\int_a^bf(x)dx>0$.
As $(A\implies B)\iff (\lnot B\implies \lnot A)$ the statement $\int_a^bf(x)dx=0 \implies f= \hat{0}_{|[a,b]}$ must be true. (Note if $c=a$ or $c=b$, then we can simply adjust the partition accordingly).
Why is this approach wrong? (my tutor said this)
Comment: ...I don't find something wrong in your approach...the only mistake might be what the answer said. But we always make $inf\{f(x)\}$ greater than zero without statement...
Answer: The idea is sound. I think there's a small point to fix. The infimum that defines $m$ might yield $m=0$ even though the function is positive on the neighborhood $U$. You can just redefine $U$ so the function is at least $f(c)/2$ there, rather than just positive.
Comment: As a general tip: in these kinds of problems, always try to bound below by something strictly greater than $0$. Often, bounding below by $0$ won't be good enough, even with strict inequality.


Calculate starting value of geometric progression

Question: I am trying to find a formula to calculate the staring value of a geometric progression.
Starting value $a$ and ratio $r$. The infinite sum of this sequence is $200$.
Ratio $r$ is calculated: $ 1-(a/200)$
If $a = 52$ then the sum of the first 10 terms: $ar^0 ... ar^9 = 190$ which is 95% of the infinite sum.
The formula for the sum of the first ten terms is: $a\left(\frac{1-r^{10}}{1-r}\right)$
What is the formula to calculate $a$ if I have the infinite sum, the formula for $r$ as above, and the percentage of the infinite sum that I want to arrive at by the 10th term?
Answer: I think you made a mistake in calculating $r$. You said $\displaystyle r=1-\frac{S_\infty}{a}$; it should be:
$$\begin{aligned}S_\infty&=\frac{a}{1-r}\\1-r&=\frac{a}{S_\infty}\\r&=1-\frac{a}{S_\infty}\end{aligned}$$
After that, say we want the partial sum of the first $n$ terms to make up proportion $p$ of the infinite series; then:
$$\begin{aligned}p&=\frac{S_{n}}{S_\infty}\\&=\frac{\frac{a\left(1-r^{n}\right)}{1-r}}{\frac{a}{1-r}}\\&=1-r^{n}\\&=1-\left(1-\frac{a}{S_\infty}\right)^{n}\end{aligned}$$
From here, we just need to solve for $a$:
$$\begin{aligned}\left(1-\frac{a}{S_\infty}\right)^{n}&=1-p\\1-\frac{a}{S_\infty}&=\sqrt[n]{1-p}\\a&=S_\infty\left(1-\sqrt[n]{1-p}\right)\end{aligned}$$
In your example, you have $S_\infty=200$, $n=10$ and $p=0.95(=95\%)$, which gives us $a\approx51.8$.
Comment: Yes, I did make a mistake on my formula for r, you are right I wrote that division backwards.  I corrected it in my question.  Thanks for your help!


How is Carmichael's function subgroup of Euler's Totient function?

Question: I've seen this question. I'm trying to find the connection between Euler's totient function and Carmichael's function.
Carmichael's function outputs smallest $k$ such that:
$a^k ≡ 1 \pmod n$
Euler's totient function outputs the order of numbers $h$ less than some number $n$ that are coprime to $n$:
$gcd(h, n) = 1$
There exists Fermat's little theorem, stating that if there is some prime number $p$:
$a^{p-1} ≡ 1 \pmod p$
I'm thinking that i found the purpose of Carmichael's function while proving this theorem using Lagrange's theorem.
As we know, according to number theory, the congruence classes coprime to $n$ form a multiplicative group of integers modulo n, thus $∃ G = (ℤ/pℤ)^*$. Let's say there also exists a monoid subgroup $H$ generated by some element $a$ (this makes $H$ a cyclic group). According to the group theory, the order of $H$ is smallest $k$ such that $a^k ≡ e \pmod p$, where $e$ is identity element (and we know, that for groups under multiplication, identity element is always equal to $1$), and thus: $|H|$ = $λ(n)$. Finally we can prove theorem by knowing that according to Lagrange's theorem, the order subgroup $H$ divides the order group $G$, and that there exists $m$ such that $|H|=p-1=k*m$, therefore:
$a^{p-1} ≡ (a^k)^m ≡ 1^m ≡ 1 \pmod p$
But what's interesting here, is that somehow Carmichael's function happens to be subgroup of Euler's totient function. Is this because every multiplicative group has $λ(n)$ as its order?
Euler's theorem is generalisation of Fermat's little theorem stating that:
$a^{\phi(n)} ≡ 1 \pmod n$
We also know that there is some specific relationship between Carmichael's function and Euler's totient function, and somehow if this relationship is satisfied, multiplicative group becomes cyclic. Is there any proof to this relationship?
Do all subgroups of groups have exponent of groups as their order?
Thus is this the main purpose for existence of $λ(n)$ in cryptography? Does Carmichael's function only work because Totient function is its multiple? Why is output Carmichael's of Carmichael's function different from the output of Totient Function sometimes?
Or just how is Carmichael's function connected to Euler's totient function?
Thank you!
Comment: We have equality if and only if the multiplicative group of $\mathbb Z_n^*$ is cyclic. This is the case, if and only if $n$ is an odd prime power (possibly an odd prime number) , twice an odd prime power (possibly twice an odd prime) or one of the numbers $1,2,4$.
Comment: Euler's function $\phi(n)$ gives the order of the multiplicative group $(\mathbb{\Z}/n\mathbb{\Z})^×$, whereas Carmichael's function gives the exponent of this group, see fifth and sixth sentence of https://en.wikipedia.org/wiki/Torsion_group .
Comment: The Carmichael function allows to generalize the Euler-theorem. It is a bit more complicated because we cannot always reduce modulo $\lambda(n)$. If the modulus is coprime to the base, this can be done. In this case, the numbers $1,a,a^2,\cdots,a^{\lambda(n)}$ actually form a subgroup of the group consisting of $1,a,a^2,\cdots,a^{\phi(n)}$
Comment: The Carmichael-function cannot exceed the totient-function because it determines the smallest exponent with the desired congruence, hence it must be a divisor of the totient-function with the same argument. In short, we have $\lambda(n)|\phi(n)$ for all $n$. Equality is possible.
Comment: An example is a number of the form $2^k$ with $k\ge 3$. We have $\phi(2^k)=2^{k-1}$, but $\lambda(2^k)=2^{k-2}$
Comment: Not sure whether there is a named theorem mentioning this relation. But Carmichael's theorem only is about the congruences and the cycle-argument.
Comment: @Peter Does this mean that Carmichael's function of $n$ may sometimes be larger than totient function of $n$ or just equal? Thank you!
Comment: @Peter Oh, of course, i was little confused. Could you be able to explain which are the cases where Carmichael's function is not equal to Totient function and why? If totient function outputs all numbers coprime and less to some $n$, shouldn't Carmichael's function always equate to it? considering that it is order of multiplicative groups. Apologies if i misunderstand something.
Comment: @Peter Thank you! I thought all multiplicative groups under mod n were cyclic groups (since they were generated by some element). Just my final question, in which theorem is this relationship mentioned? Is it Carmichael's theorem? Thank you again.
Answer: Let $U(n)$ be the group of units mod $n$.
Euler's totient function gives the order of $U(n)$.
Euler's theorem is Lagrange's theorem for $U(n)$.
Carmichael's function gives the exponent of $U(n)$, by definition.
Every finite abelian group $A$ contains a cyclic subgroup whose order is the exponent of $A$. This subgroup correspond to the largest invariant factor of $A$.
Comment: @ShellRox: The alternating group $A_5$ has exponent $30$, but no subgroup of this order.
Comment: Thank you, but does group have to be abelian to have a subgroup with order of exponent of group? In proof i pick G as a multiplicative group (and as i know, element operations there are not commutative, but associative).
Comment: @j.p Thank you! What about multiplicative group of integers modulo $n$, It seems to be monoid group (not abelian) but does have subgroup with the order of exponent of group. Does this mean that monoid groups can have these groups as well?
Comment: Apologies for misunderstanding, I've read your link completely and understood that every finite group has exponent. Finally, $\phi{(n)}$ is the order of all multiplicative groups under $\pmod n$ correct? or just generally all multiplicative groups?


Looping functions over dates - Python

Question: I am not the most proficient in Python so apologies for any hideous code.
I have a csv file containing daily spot rates of different libor curves of different tenors. I have two functions where the first takes the spot rates of one libor curve at one date, and the second takes those rates from the first function and calculates the forward rates:
def importdata (fileloc, date, name, max_maturity=None):
    'Imports data from a given location, date and name'
    data = pd.read_csv(fileloc) # file location
    data = data[ (data['date']) == date] # getting the date of the curve
    data =  data.loc[:, data.columns.str.startswith(name)] # getting the curve wanted at the date
    data = data.T # Transposing the data
    data = data.reset_index()
    data.columns = ['maturity','spot rate'] # renaming columns
    data['maturity'] = data.maturity.str.rsplit(n=1).str[-1]
    if max_maturity:
        data = data.iloc[:data.loc[data.maturity.str.contains(max_maturity,na=False)].index[0]+1]
    return data

def interpolate (dataframe, TENOR, freq):

    'Gets the forward rates from given tenors (X) and corresponding spot rates (Y)'

    terms= dataframe["maturity"].tolist()
    rates= dataframe['spot rate'].tolist()

    dc = ql.Actual360()
    settlement_days = 0
    if Curve =='3M USD' or Curve == '6M EUR' or Curve == '6M GBP':

        helpers = []

        for term, r in zip(terms, rates):
            if Curve == '3M USD':
                swapIndex = ql.UsdLiborSwapIsdaFixAm(ql.Period((term)))
                helpers.append(ql.SwapRateHelper(r/100, swapIndex))
            elif Curve == '6M EUR':
                swapIndex = ql.EuriborSwapIsdaFixB(ql.Period((term)))
                helpers.append(ql.SwapRateHelper(r/100, swapIndex))
            elif Curve == '6M GBP':
                #swapIndex = ql.SwapIndex('GBP Libor', ql.Period(term), settlement_days, ql.GBPCurrency(), ql.UnitedKingdom(), ql.Period('6M'), ql.Following, dc, ql.GBPLibor)
                swapIndex = ql.GbpLiborSwapIsdaFix(ql.Period((term)))
                helpers.append(ql.SwapRateHelper(r/100, swapIndex))

    elif Curve == 'EONIA' or Curve =='SONIA' or Curve =='FF':

        OIS_helpers = []

        if Curve == 'EONIA':
            calendar = ql.TARGET()
            EONIA = ql.OvernightIndex("EONIA", settlement_days, ql.EURCurrency(), calendar, dc)

            for i in range(len(terms)):
                tenor = ql.Period(terms[i])
                rate = rates[i]
                OIS_helpers.append(ql.OISRateHelper(settlement_days, tenor, ql.QuoteHandle(ql.SimpleQuote(rate/100)), EONIA))

        elif Curve =='SONIA':
            calendar = ql.UnitedKingdom()
            SONIA = ql.OvernightIndex("SONIA", settlement_days, ql.GBPCurrency(), calendar, dc)

            for i in range(len(terms)):
                tenor = ql.Period(terms[i])
                rate = rates[i]
                OIS_helpers.append(ql.OISRateHelper(settlement_days, tenor, ql.QuoteHandle(ql.SimpleQuote(rate/100)), SONIA))

        elif Curve == 'FF':
            calendar = ql.UnitedStates()
            FedF = ql.OvernightIndex("FedF", settlement_days, ql.USDCurrency(), calendar, dc)

            for i in range(len(terms)):
                tenor = ql.Period(terms[i])
                rate = rates[i]
                OIS_helpers.append(ql.OISRateHelper(settlement_days, tenor, ql.QuoteHandle(ql.SimpleQuote(rate/100)), FedF))

        helpers = OIS_helpers

    curve = ql.PiecewiseSplineCubicDiscount(0, ql.TARGET(), helpers, dc)
    curve.enableExtrapolation()

    days = ql.MakeSchedule(curve.referenceDate(), curve.maxDate() , ql.Period(freq)) #Frequency

    if Curve == '3M USD' or Curve =='FF':
        fwds = [
            curve.forwardRate(d, ql.UnitedStates().advance(d,ql.Period(TENOR)), dc, ql.Simple).rate()*100
            for d in days
        ]

    elif Curve =='6M EUR' or Curve == 'EONIA':
        fwds = [
            curve.forwardRate(d, ql.TARGET().advance(d,ql.Period(TENOR)), dc, ql.Simple).rate()*100
            for d in days
        ]

    elif Curve =='6M GBP' or Curve == 'SONIA':
        fwds = [
            curve.forwardRate(d, ql.UnitedKingdom().advance(d,ql.Period(TENOR)), dc, ql.Simple).rate()*100
            for d in days
        ]

    fwdsdic = {Date:fwds}
    fwdcomp = pd.DataFrame(fwdsdic)

    ALL_FWD = fwdcomp.to_csv('1y1y.csv', header = '1y1y')

    return fwdcomp;

An example of data which is used an input to interpolate:
    maturity    spot rate
0   1Y  0.105
1   18M 0.19
2   2Y  0.265
3   3Y  0.41100000000000003
4   4Y  0.542
5   5Y  0.655
6   6Y  0.7509999999999999
7   7Y  0.833
8   8Y  0.904
9   9Y  0.966
10  10Y 1.021
11  12Y 1.093
12  15Y 1.157
13  20Y 1.182
14  25Y 1.18
15  30Y 1.162
16  40Y 1.073
17  50Y 1.01

What I want to do is to calculate these forward rates for one curve, but for all the dates in the CSV file, and then save these rates to a new csv file. So far what I have done is import the entire CSV file into pandas and then create a for loop for all the dates:
AllDate = all_data['date']
for dt in AllDate.iteritems():
    data = importdata(locationAll, dt, Curve)
    interpolate(data, '1y', '1y')

I get this error:
ValueError: Length mismatch: Expected axis has 1 elements, new values have 2 elements

I'm unsure as to where I have gone wrong, any help is greatly appreciated.
Edit:
I have changed the for loop to this:
AllDate = all_data['date']
for dt in AllDate.iterrows():
    data = importdata(location, dt, Curve)
    interpolate(data, '1y', '1y')

I get this error message instead:

AttributeError: 'Series' object has no attribute 'iterrows'

Here is a picture of my input file if it helps:
enter image description here
Answer: The error you got says what's wrong. pandas.DataFrame.interitems() returns two values (label and content) but you gave it only one variable dt to write it to.
You can read the docs here for an example.
Comment: I edited my question, I realised interitems() is for columns whereas my dataset is in rows

Looping functions over dates - Python


How to know the template of the main page in prestashop

Question: I want to know where is the main template of a prestashop project.
I come from Laravel and this is something weird to me.
Thanks.
Answer: in Prestashop 1.7 its in themes/classic/templates/
page.tpl for the home page
catalog/product.tpl for the product page
catalog/listing/product-list.tpl for any product list page
checkout/cart.tpl for the detailed cart
checkout/checkout.tpl for the checkout process

in Prestashop 1.6 , there is no main.tpl like in twig.
you just have something like this
header.tpl
page_name.tpl
footer.tpl

in themes/default-bootstrap/


Integration Factor Constant Rule for Double Integral

Question: I know that for the situation where there is a constant c on a function I can factor it from the integrand. So,

$\int c f(x) dx$
    $c \int f(x) dx$

What about a double integral? Would it be like

$\iint c f(x,y) dx dy$
     $c \iint f(x,y) dx dy$

Is that correct?
Comment: In a word: yes.
Comment: To see that this is so, imagine that $f$ is constant so that the double integral is the volume of a rectangular prism. If the situation is clear there, next, think about the definition of the integral as a limit of Riemann sums (if you know this, learn it if you don't) and general case should become clear.
Answer: Yes, by definition $$ \iint f(x,y)dxdy =  \lim_{(\Delta x_i,\Delta y_j) \to (0,0)} \sum\sum f(\xi_i,\psi_j)\Delta x_i \Delta y_j$$
Now $$\iint cf(x,y)dxdy = \lim_{(\Delta x_i,\Delta y_j) \to (0,0)} \sum\sum cf(\xi_i,\psi_j)\Delta x_i \Delta y_j $$
Now, use the properties of Sums and limits to obtain:
$$\lim_{(\Delta x_i,\Delta y_j) \to (0,0)} \sum\sum cf(\xi_i,\psi_j)\Delta x_i \Delta y_j = c\left(\lim_{(\Delta x_i,\Delta y_j) \to (0,0)} \sum\sum f(\xi_i,\psi_j)\Delta x_i \Delta y_j\right) $$
Therefore,
$$\iint cf(x,y)dxdy = c\iint f(x,y)dxdy$$


Minimum number of subsets of combinations so all combinations in a subset differ by one

Question: Consider all ${n \choose k}$ subsets of size $k$ from a larger set of size $n$.  I would like to split the set of subsets into parts so that in each part, the intersection of all the subsets is at least of size $k-1$.

What is the minimum number of parts that you are guaranteed to be able
  to split the set of subsets into?

The maximum number of subsets in a part is $n$ so this at least gives us a lower bound of $\frac{{n \choose k}}{n}$ for the number of parts. But this is not tight.
When $k=1$ the minimum number of parts is $1$. When $k=2$ the minimum number of parts is $n-1$. I don't know how to solve the problem for $k=3$.
Edit
Smylic points out you can slightly raise the lower bound as each  part has at most $n  - (k-1)$ subsets. So this makes a new lower bound of $\frac{{n \choose k}}{n  - (k-1)}$.
Comment: Could you show us an example where the number of elements in the partition exceeds n, the lower bound? I almost suspect you can show n is the correct answer by pigeonhole, but am probably wrong.
Comment: @barrycarter I updated what I wrote. Is it clearer now?
Comment: I wasn't requesting clarification. I meant: can you show us a case where the number of parts exceeds the minimum bound? Or are you saying you suspect the minimum bound may also be the actual value?
Comment: @barrycarter I added $k=2$ which shows that the lower bound is not tight.
Comment: OK, I'll stop being lazy and work out n=4, k=2 or something myself. I may not be "getting this". You're saying the 6 subsets of 4 elements that have 2 elements can be partitioned into 3 groups such that, in each group, 1 element is shared?
Comment: @barrycarter Try these three parts, {{0,1}, {0,2}, {0,3}}, {{1,2}, {1,3}}, {{2,3}}. The intersection sizes are 1, 1, and 2.
Comment: Nice! For some reason, I thought the parts would be the same size.
Comment: You can slightly raise lower bound, because each part has at most $n - (k - 1)$ subsets.
Comment: @Smylic Thanks. A non-trivial upper bound would be great too.
Answer: This is not a complete answer, just an upper bound.
A trivial upper bound is $\binom{n}{k - 1}$, because each part has its specific subset of size $k - 1$ that is subset of each element of part (even is a part has only one subset of size $k$ it can be assigned some subset of size $k - 1$).
I'm going to show that $\binom{n - 1}{k - 1}$ for $k \ge 1$ is a better upper bound (and $k = 0$ is a trivial case with the only part of one empty subset). Let $f(n, k)$ be the desired minimum number of parts. Then $f(n, 1) = 1$ and $f(n, n) = 1$. Suppose $f(m, k) \le \binom{m - 1}{k - 1}$ for all $m < n$ and $1 \le k \le m$. We have $f(n, k) \le f(n - 1, k - 1) + f(n - 1, k)$ since we can firstly divide all subsets with element $n$ into $f(n - 1, k - 1)$ parts and then divide all subsets without element $n$ into $f(n - 1, k)$ parts. So
$$f(n, k) \le f(n - 1, k - 1) + f(n - 1, k) \le \binom{n - 2}{k - 2} + \binom{n - 2}{k - 1} = \binom{n - 1}{k - 1}$$
for $2 \le k \le n$ and $f(n, 1) = 1 \le 1 = \binom{n - 1}{0}$. Thus we have proven an induction step and the basis is $n = 2$.
This upper bound is less than $k$ times greater than the lower bound achieved before:
$$\frac{\binom{n - 1}{k - 1}}{\frac{\binom{n}{k}}{n - (k - 1)}} = \frac{(n - k + 1)}{n}k.$$
However $f(6, 3) = 6$ shows that both of them are not tight.
Answer: I have a solution for $k=3$; when $k>3$, the question is a well-known open problem.
When $k=3$, instead of dividing the $\binom{n}{3}$ subsets into parts, it's equivalent to choose some number of pairs $\{x,y\} \subset \{1,2,\dots,n\}$ to serve as their intersections. (In most cases, a part will have intersection of size exactly $2$; if a part consists of only one subset $\{x,y,z\}$, we may arbitrarily choose any of $\{x,y\}$, $\{x,z\}$, or $\{y,z\}$ to be its assigned pair.) Conversely, if we specify some pairs such that every $3$-subset contains at least one pair, we have specified the partition, up to some flexibility when a $3$-subset contains more than one pair, and can fit in more than one part.
We can think of choosing these pairs as choosing a graph $G$ on vertex set $\{1,2, \dots, n\}$. The condition that every $3$-subset is assigned a part is now saying that for any $\{x,y,z\}$, one of $xy$, $xz$, or $yz$ must be an edge of $G$. Equivalently, the complement $G^c$ is a triangle-free graph.
By the $r=2$ case of Turán's theorem, a triangle-free graph on $n$ vertices can have at most $\left\lfloor\frac{n^2}{4}\right\rfloor$ edges, and this is tight: the bipartite graph $K_{\lfloor n/2\rfloor, \lceil n/2\rceil}$ has that many edges and is triangle-free. Therefore $G$ has at least $\binom{n}{2}-\left\lfloor\frac{n^2}{4}\right\rfloor$ edges, and any partition of the $3$-subsets of $\{1,2,\dots,n\}$ of the kind we're looking for has at least $$f(n,3) = \binom{n}{2} - \left\lfloor\frac{n^2}{4}\right\rfloor = \left\lfloor\frac{(n-1)^2}{4}\right\rfloor$$ parts.
Similarly, for $k>3$, we can interpret the problem as a hypergraph Turán problem. Instead of the graph $G$, we have a $(k-1)$-uniform hypergraph $H$, whose complement $H^c$ contains no $k$-clique $K_k^{k-1}$. The Turán number $\DeclareMathOperator{\ex}{ex}\ex(n,K_k^{k-1})$ is the maximum number of edges $H^c$ can have. The answer $f(n,k)$ we're looking for is the minimum number of edges $H$ can have, so $$f(n,k) = \binom{n}{k-1} - \ex(n,K_k^{k-1}).$$ This value is also often denoted $f(n,k) = T(n, k, k-1)$.
It's known that as $n \to \infty$, $$T(n, k, k-1) \sim t(k,k-1) \binom{n}{k-1}$$ for some constant $0<t(k,k-1)<1$ independent of $n$. As far as I know, $$(1+o(1))\frac1{k} \le t(k,k-1) \le (1+o(1))\frac{\log k}{2k}$$ are asymptotically (as $k \to \infty$) the best bounds known, which I got from this survey, but there may have been new, better results in the past five-six years. (The value of $t(4,3)$ is known to be somewhere between $0.438334$ and $\frac49$, which is also elaborated on in the survey.)
Comment: It does; to the best of my knowledge, an exact answer to $f(n,4)$ for all $n$ would be worth $\$1000$ from Erdős. (We do have a construction that's asymptotically within $2\%$ of the right answer, and possibly actually optimal, but hard to prove to be optimal.)
Comment: Does the question become open at $k=4$?
Comment: Does the situation change much if we allow repetitions (so we get multi-subsets rather than subsets)? That is for $k=3$ we would have (0,0,0), (0,0,1), (0,0,2) etc.
Comment: It changes enough that I don't know what to say about the multiset version off the top of my head. It seems harder to analyze because it has less symmetry.


Is there any algebraic structure on Dyck words of length $2n$ or full binary trees of $n+1$ leaves?

Question: Just out of curiosity, I wonder if there are researches about algebraic structures on Dyck words of length $2n$ or (equivalently) full binary trees of $n+1$ leaves (with fixed $n \in \mathbb{Z}^+$).
As a matter of fact, that two sets have the same number of elements: the $n^{th}$ Catalan number $C_n$.
I've googled but got no result.
Thanks in advance.
Comment: http://www.sciencedirect.com/science/article/pii/S0001870898917595
Comment: @Phicar: There is the fixed length $n$, whereas the paper mostly talks about planar binary trees of any number of leaves, which is equivalent to the Dyck language. There are already some algebraic researches about the Dyck language as a whole.
Answer: There is actually a huge literature on this topic. See Chapter 11, Words and trees, in [2] and Lemma 9.3.1 in
[4] for your specific question. See the notes of Chapter 9 in [3] for (many) relevant references. Reference [3] doesn't address your question but is still a good reference on algebra over words. For an algebraic theory of context-free languages, see [2] and Chapter 2 in [1]
[1] Berstel, Jean. Transductions and context-free languages. Leitfäden der Angewandten Mathematik und Mechanik [Guides to Applied Mathematics and Mechanics], 38. B. G. Teubner, Stuttgart, 1979. 278 pp. ISBN: 3-519-02340-7
[1] Berstel, J.; Boasson, L. Towards an algebraic theory of context-free languages, Fund. Inform. 25 (1996), no. 3-4, 217--239
[2] Lothaire, M. Combinatorics on words. With a foreword by Roger Lyndon and a preface by Dominique Perrin. Corrected reprint of the 1983 original, with a new preface by Perrin. Cambridge Mathematical Library. Cambridge University Press, Cambridge, 1997. xviii+238 pp. ISBN: 0-521-59924-5
[3] Lothaire, M. Algebraic combinatorics on words. A collective work by Jean Berstel, Dominique Perrin, Patrice Seebold, Julien Cassaigne, Aldo De Luca, Steffano Varricchio, Alain Lascoux, Bernard Leclerc, Jean-Yves Thibon, Veronique Bruyere, Christiane Frougny, Filippo Mignosi, Antonio Restivo, Christophe Reutenauer, Dominique Foata, Guo-Niu Han, Jacques Desarmenien, Volker Diekert, Tero Harju, Juhani Karhumaki and Wojciech Plandowski. With a preface by Berstel and Perrin. Encyclopedia of Mathematics and its Applications, 90. Cambridge University Press, Cambridge, 2002. xiv+504 pp. ISBN: 0-521-81220-8 MR1905123
[4] Lothaire, M. Applied combinatorics on words. A collective work by Jean Berstel, Dominique Perrin, Maxime Crochemore, Eric Laporte, Mehryar Mohri, Nadia Pisanti, Marie-France Sagot, Gesine Reinert, Sophie Schbath, Michael Waterman, Philippe Jacquet, Wojciech Szpankowski, Dominique Poulalhon, Gilles Schaeffer, Roman Kolpakov, Gregory Koucherov, Jean-Paul Allouche and Valérie Berthé. With a preface by Berstel and Perrin. Encyclopedia of Mathematics and its Applications, 105. Cambridge University Press, Cambridge, 2005. xvi+610 pp. ISBN: 978-0-521-84802-2; 0-521-84802-4


How do I consume REST data with an external service?

Question: I want to integrate RESTful API with drupal 8.
What I want to achieve is my a project which is built in drupal 8 is the consumer and RESTful API is integrated into another website using CodeIgniter.
I want to create a page in drupal using routing and all data will be coming from another website.
Example:
http://mywebsite.com/products [drupal 8]
http://webservice.com/products/list.json [CI]

My website will consume web service of webservice.com and will display the products on my website.
What is the better way or structure to achieve it?
Answer: I actually have implemented a similar thing in my project.
I created a module structure like as follow.
 my_module [directory]
        products [directory]
          products.info.yml
          products.module
          products.routing.yml
          src[directory]
            Controller[directory]
              - ProductsController.php
          templates[directory]
              - products-list.html.twig
        my_module.info.yml
        my_module.module
        my_module.routing.yml

products.routing.yml
 products.list:
    path: '/products'
    defaults:
      _controller: '\Drupal\products\Controller\ProductsController::getList'
      _title: 'Get List'
    requirements:
      _permission: 'access content'

src/Controller/ProductsController.php
    /**
     * @file
     * Contains \Drupal\products\Controller\ProductsController.
     */
    namespace Drupal\products\Controller;

    use Drupal\Core\Controller\ControllerBase;

    /**
     * Controller routines for products routes.
     */
    class ProductsController extends ControllerBase {

      /**
       * Callback function to get the data from REST API
       */
      public function getList() {

        $data = array();
        $response = $data = $result = null;

        if (function_exists('my_module_reponse')) {
          $response = my_module_reponse('http://webservice.com/products/list', 'GET');
        }

        if ($response) {

          $result = json_decode($response);
          $data = array();

          // # add all the data in one multiple dim array
          $data['title'] = 'products to consume REST API';
          $data['users'] = $result;

          // display the content in the middle section of the page
          $build = array(
            '#theme' => 'products_list', // assign the theme [products-list.html.twig]
            '#title' => 'products to consume REST API', // assign the page title
            '#pagehtml' => 'data is coming from : products/list ', // assign the string message like this
            '#data' => $data
          ); // assign the array like this to access in twig file
        }
        return $build;
      }
    }

templates/products-list.html.twig

 {{ data.title }}

 {{ pagehtml }}

  {% for item in data.users %}

{{ item.yourproductnamekey}}

  {% endfor %}

my_module.module
      /**
       * @file
       * Test API module.
       */
      function my_module_reponse($url, $method = 'GET', $params = array()) {
        $methods = [
          'POST',
          'GET',
          'PUT',
          'DELETE'
        ];
        $result = array();

        try {
          if (empty($url)) {
            throw new Exception("Invalid url");
          }
          if (in_array(strtoupper($method), $methods) === FALSE) {
            throw new Exception("Invalid method");
          }
          else {
            // will need a request call for GET, POST, PUT
            switch (strtoupper($method)) {
              case 'GET':
              case 'POST':
              case 'PUT':
              case 'DELETE':
                if (function_exists('my_module_call_request')) {
                  $result = my_module_call_request($url, $method, $params);
                }
                break;
              default:
                throw new Exception("Invalid method");
                break;
            }
          }
        }
        catch (Exception $e) {
          echo $e->getMessage();
        }

        return $result;
      }

      function my_module_call_request($requesturl, $method, $params = array()) {

        // request url
        $url = $requesturl;

        try {

          // initialized curl
          $ch = curl_init();

          // set header for curl request
          $headers = array(
            "Cache-Control: no-cache",
            "Pragma: no-cache"
          );

          // set required setting with curl configuration
          curl_setopt($ch, CURLOPT_URL, $url);
          curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
          curl_setopt($ch, CURLOPT_FRESH_CONNECT, TRUE);
          curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
          curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
          curl_setopt($ch, CURLOPT_FORBID_REUSE, 1);

          // pass the additional values
          curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($params));

          // close the curl connection
          $result = curl_exec($ch);
          curl_close($ch);

          return $result;
        }
        catch (Exception $e) {
          echo $e->getMessage();
        }
      }

products.module
    /**
     * implements hook_theme();
     * description: create the file as per below
     * eg : products-list.html.twig  for "products_list"
     */
    function example_theme($existing, $type, $theme, $path) {
      return array(
        'products_list' => array(
          'variables' => array(
            'pagehtml' => NULL,
            'data' => NULL
          )
        ),
      );
    }

Each submodule will contain the individual routing file and function related to each page. It will make easy for you to maintain the code as well.
Comment: thanks for your solution. and happy with yor explaination
Answer: There's a contrib module which can be used for this purpose too. The name is External Entities
Module itself will take care of caching and other things. And you will be able to create twig template for theming purpose.


Can anyone explain the steps to calculate the time complexity of this code and what it would be?"

Question: I have a code snippet that I would like to analyze for time complexity. The code is as follows:
<code>for (i=1; i<=n; i++) {
    for (j=1; j<=n; j=j+i) {
        printf("x");
    }
}
</code>
I would like to know the time complexity of this code
Comment: What do _you_ think the time complexity of this is? Is `n` a constant, or a user input?
Comment: @EricPostpischil I believe Chris was trying to let OP think through the question again and try and get the solution. If n is fixed, ie 5, then the program will not be a function of n. Just thoughts though
Comment: Minor stylistic suggestion as an aside: `j = j + i` == `j += i`
Comment: Does this answer your question? [Finding Big O of the Harmonic Series](https://stackoverflow.com/questions/25905118/finding-big-o-of-the-harmonic-series)
Answer: The complexity is proportional to the number of Xs you get, which is roughly:
n + n/2 + n/3 + n/4 ... n/n
That is
n ( 1 + 1/2 + 1/3 + 1/4 ... 1/n)
The second term is the harmonic series.  It comes out to about loge n, so your total complexity is O(n log n)


How are theses functions called and what are their properties?

Question: We define a system of two equations with two variables and six parameters:
$\begin{cases}
a_1x+b_1y=c_1\\
a_2x+b_2y=c_2
\end{cases}$
We obtain a function $f:\mathbb{R^3\times\mathbb{R}^2\rightarrow\mathbb{R}^2}$,
$$\pmatrix{a_1 &  a_2 \\ b_1 & b_2 \\ c_1 & c_2}\mapsto \pmatrix{x \\ y} $$
If we fix the five parameters $a_1$, $a_2$, $b_1$, $b_2$, $c_1$ and we vary the value of $c_2$. We obtain a function $f_{c_2}: \mathbb{R}\rightarrow\mathbb{R}^2$,
$c_2\mapsto\left(x,y\right)$. In the same manner we obtain the five other functions $f_{a_1}$, $f_{a_2}$, $f_{b_1}$, $f_{b_2}$, $f_{c_1}$.
My question is how are theses functions called and what are their properties?
Answer: The functions in OP are defined by the system:
$$\begin{cases}
a_1x+b_1y=c_1\\
a_2x+b_2y=c_2
\end{cases}$$
so that:
$$
x=\dfrac {\Delta_x}{\Delta} \qquad y=\dfrac {\Delta_y}{\Delta}
$$
where:
$$
\Delta=a_1b_2-a_2b_1 \quad \Delta_x=b_1c_2-b_2c_1 \quad \Delta_y=a_1c_2-a_2c_1
$$
so that the functions $f_{c_1}:\mathbb{R}\to\mathbb{R}^2$ and $f_{c_2}:\mathbb{R}\to\mathbb{R}^2$ are:
$$
f_{c_1}(t)=
\begin{bmatrix}
\frac{-b_2}{\Delta}t+\frac{b_1c_2}{\Delta}\\
\frac{-a_2}{\Delta}t+\frac{a_1c_2}{\Delta}\\
\end{bmatrix}
$$
and
$$
f_{c_2}(t)=
\begin{bmatrix}
\frac{b_1}{\Delta}t-\frac{b_2c_1}{\Delta}\\
\frac{a_1}{\Delta}t-\frac{a_2c_1}{\Delta}\\
\end{bmatrix}
$$
so these functions represent straight lines on $\mathbb{R}^2$.
The functions $f_{a_i}$ and $f_{b_i}$ are different. As example the function $f_{a_1}:\mathbb{R} \to \mathbb{R}^2$ is:
$$
f_{a_1}(t)=
\begin{bmatrix}
\dfrac{b_1c_2-b_2c_1}{b_2t-a_2b_1}\\
\dfrac{c_2t-a_2c_1}{b_2t-a_2b_1}
\end{bmatrix}
$$
that represent an homographic function in $\mathbb{R}^2$ whose graph is an hyperbola.
I dont know if all these function have some collective name (I never see it).
1.


How does Mac OS X VPS work?

Question: How do folks like Xcloud for example provide Mac OS X VPS service? Do they run VMWare with Mac OS X guest instances, or is there a native(if that even makes sense) hypervisor that runs on something like Apple hardware?
Answer: As Apples terms of sale prohibit the virtualization of OS X on any other platform than OS X, they probably use Apple hardware - Apple discarded their XServe server series 2 years ago, so I guess, they are using Mac Pro's.
Comment: @Henrik ESXi can run Mac VMs, though the licensing restriction of running on Apple hardware still applies: http://kb.vmware.com/kb/2005793
Comment: So they run VMWare on Mac Pro with OSX being guest system? WOuldn't the performance be pretty bad on such setup?
Comment: I'm only guessing, but due to the lack of a bare metal hypervisor for mac, I think they'll use either VMWare or Parallels.
Comment: @Shane I already knew about this - even a lot more virtualisazion solution are able to do so (like Xen, Virtualbox) with more are less workarounds (for more information see http://www.tonymacx86.com/). Actually I'm virtualizing 10.6 with Virtualbox on Linux host system, because 10.6 is the last OS X where the TOS could be interpreted in this way, that virtualization is allowed on non-Apple Hardware. For 10.7 and later its impossible to do this legally :)

How does Mac OS X VPS work?


Como retornar uma coluna de uma query dentro de classe

Question: Estou atualizando meu projeto todo para PDO orientado a objeto, porém estou tendo algumas dificuldades pra retornar uma coluna de um fetch na query da classe User. Depois de várias tentativas, assim ficou meu código:
user.php
Class User {

    public $usr_idLogged = 1;

    public function selectUser() {

        try {

            $classConnection = new Connection();
            $openConn = $classConnection->openConn();

            $stmt = $openConn->prepare('SELECT * FROM tbl_users a JOIN tbl_users_picture b ON a.usr_id = b.usrPic_idUser WHERE usr_id = :usr_id;');
            $stmt->bindParam(':usr_id', $usr_idLogged);
            $stmt->execute();
            $usr_idLogged_f = $stmt->fetch();
        }
        catch (PDOException $e) {
            echo "There is some problem in connection: " . $e->getMessage();
        }
    }
}

E aqui está a página onde quero exibir um resultado por vez.
panel.php
              $classUser = new User();
              $classUser->selectUser();

              if ((!empty($classUser->usr_idLogged_f['usrPic_path'])) && (file_exists($classUser->usr_idLogged_f['usrPic_path']))) {
                  echo 'usr_idLogged_f['usrPic_path'].'" title="Open your profile">';
              }
              else {
                echo '';
              }

No caso eu quero exibir a coluna do fetch que dei, mas eu sempre acabo em um erro diferente relacionado à variavel, no caso usr_idLogged_f['usrPic_path']).
Answer: Existem algumas formas de você resolver esse problema.
Você pode declarar o seu método como estático e assim instanciar o obejto direto.
(Não rodei seu código, por isso minha dica vai no escuro)
Segue abaixo o mencionado:
<?php
class User {

    public $usr_idLogged = 1;

    public static function selectUser() {

        try {
            $classConnection = new Connection();
            $openConn = $classConnection->openConn();

            $stmt = $openConn->prepare('SELECT * FROM tbl_users a JOIN tbl_users_picture b ON a.usr_id = b.usrPic_idUser WHERE usr_id = :usr_id;');
            $stmt->bindParam(':usr_id', $usr_idLogged);
            $stmt->execute();
            $usr_idLogged_f = $stmt->fetch();
        }
        catch (PDOException $e) {
            echo "There is some problem in connection: " . $e->getMessage();
        }
      }
     }
    ?>

Porém, como você está fazendo em PDO, é ideal que você faça os Getters e Setteres, para depois criar os métodos e criaria uma class de conexão. Como eu não sei como a sua conexão está sendo feita, eu mandarei um exemplo e como ficariam os dois arquivos.
Class Conexão
<?php
class Connection extends PDO{
    private $conn;
    //Conexão automática ao banco de dados
    public function __construct()
    {
        $this->conn = new PDO("mysql:host=localhost;dbname=dbphp7", "root","");//Pode ser passado por paramêtros com bindParam caso exista mais de um servidor
    }
    //Associação de parâmetros passados
    private function setParams($statment, $parameters = array()){
        //Com este foreach, é possível passar quantos parâmetros necessários
        foreach ($parameters as $key => $value) {
            //O $this->setParam está chamando o método abaixo, no qual executa o bind de apenas um parâmetro, porém, devido ao foreach, este bind será executado quantas vezes for necessário
            $this->setParam($statment, $key, $value);
        }
    }
    //Ao contrário do método setParams, este executa o bind de apenas um parâmetros, por isso o nome Param, pois é apenas um
    private function setParam($statment, $key, $value){
        $statment->bindParam($key, $value);
    }
    //Execução de um comando ao banco
    public function query($rawQuery/*Query bruta que será tratada depois*/, $param = array())
    {
        //Comando de execução no banco
        $stmt = $this->conn->prepare($rawQuery);
        //Chamando o métododo setParams e associando os parâmetros statement = $stmt e parameter = $param.
        //A variável $stmt está chamando o comando de execução no banco.
        //A variável $param está recebendo o array
        //Cada variável passada refere-se a exigência do método setParams
        $this->setParams($stmt, $param);
        //Executando
        $stmt->execute();
        //Retornando a execução
        return $stmt;
    }
    //Método para o select
    public function select($rawQuery, $params = array()):array{
        //O $stmt é o que o método quey retorna
        $stmt = $this->query($rawQuery, $params);
        //Retorna o fetchAll com os dados associativos
        return $stmt->fetchAll(PDO::FETCH_ASSOC);
    }
}
?>

Class de métodos
<?php
class User {

    public $usrPic_path;

    public function setUsrPic_path($usrPic_path){
        $this->usrPic_path = $usrPic_path;
    }
    public function getUsrPic_path($usrPic_path){
        return $this->usrPic_path;
    }

    public function setData($data){
        //Envia os dados, por vetor e row, para os métodos setters
        $this->UsrPic_path($data["usrPic_path"]);
    }

    public function selectUser() {
        $openConn = new Connection();
        $resultado = $openConn->prepare('SELECT * FROM tbl_users a JOIN tbl_users_picture b ON a.usr_id = b.usrPic_idUser WHERE usr_id = :usr_id;', array(
            ':usr_id'=>$usrPic_path
        ));
        if(count($resultado)>0){
            $this->setData($resultado[0]);
        }
    }
}
?>

AutoLoad da conexão nas classes
<?php
//Auto load das classes
spl_autoload_register(function($class_name){
    //Passa o nome do arquivo
    $filename = "class". DIRECTORY_SEPARATOR .$class_name.".php";
    //Se este arquivo existir, ele é invocado
    if (file_exists(($filename))){
        require_once($filename);
    }
});
?>

Index
<?php
    include('user.php');

    $classUser = new User();
    $classUser_select = $classUser->usr_idLogged;

    if ((!empty($classUser_select)) && (file_exists($classUser_select))) {
        echo '';
    }
    else {
    echo '';
    }
?>

Espero ter ajudado.


Index Array without Elements

Question: I have a vector
a = Vector(1:4)

[1, 2, 3, 4]

and I want to index it to all elements but the third to get
[1, 2, 4]

in R you could do a[-3]. What do you do in Julia?
(Eventually I want to loop through all the elements and compare each of them to the rest - maybe this is relevant.)
Comment: About your parenthesis, you can probably loop through them (without comparing any to itself) like so
`[(a[i], a[j]) for i in eachindex(a), j in eachindex(a) if j ≠ i]`
Answer: This use case is a common one and is covered by the InvertedIndices.jl package. If you install it then you can run:
julia> using InvertedIndices

julia> a = 1:4
1:4

julia> a[Not(3)]
3-element Array{Int64,1}:
 1
 2
 4

Also some packages (like DataFrames.jl) automatically load this package (so if you e.g. use DataFrames.jl you do not have to install and load InvertedIndices.jl separately).
Answer: The Julia syntax will be unfortunately more verbose than those of R:
julia> a[1:end .!== 3]
3-element Array{Int64,1}:
 1
 2
 4

Another option is to mutate a:
julia> deleteat!(a,3)
3-element Array{Int64,1}:
 1
 2
 4

If your data is within a DataFrame than you can get a nicer syntax:
julia> df = DataFrame(a=1:4);

julia> df[Not(3),:]
3×1 DataFrame
│ Row │ a     │
│     │ Int64 │
├─────┼───────┤
│ 1   │ 1     │
│ 2   │ 2     │
│ 3   │ 4     │

and when DataFrames is imported Not will also work with a Vector:
julia> a[Not(3)]
3-element Array{Int64,1}:
 1
 2
 4

Answer: I have not seen
julia> a[1:end .≠ 3]
3-element Array{Int64,1}:
 1
 2
 4

or
julia> a[eachindex(a) .≠ 3]
3-element Array{Int64,1}:
 1
 2
 4

mentioned, but maybe there is a good reason?

EDIT: I was wrong, the first one is actually the same as Bogumil's first answer except !== has been replaced with ≠
Comment: Super inefficient if a is large

Index Array without Elements


Why do we write the expression in a different manner?

Question: Suppose, we are given to factor a polynomial $P(x) = 54x^4 + 27x^3a - 16x - 8a$. Here, $P(- \frac{a}{2}) = 0$, hence, $x - (- \frac{a}{2})$ or $(x + \frac{a}{2})$ will be a factor of $P(x)$. But, when we get that for $x = -\frac{a}{2}$ the polynomial becomes $0$, we transform the equation as $2x+a = 0$ and state that $2x+a$ will be a factor of $P(x)$. But why do we do so, that is my question.
Answer: In $\Bbb Q[x]$ and in $\Bbb Z[x]$ the polynomial is reducible and we have the factorization
$$
P(x)= (2x+a)(9x^2 + 6x + 4)(3x - 2).
$$
So indeed $2x+a$ is a factor. Of course, then every multiple
is also a factor, for example $x+\frac{a}{2}$ or $\frac{x}{2}+\frac{a}{4}$. If $a$ is an odd integer, and we want to view the factors in $\Bbb Z[x]$, then
we chose the factor $2x+a$, in order to have integer coefficients. The same applies for the factor $3x-2$, where we also have that $x-\frac{2}{3}$ is a factor.
Comment: Ok, I think I am getting the answer. Does it mean that if we use $x + \frac{a}{2}$ as the factor, we can still factorise the polynomial, but we won't get the integer coeffecients?
Comment: Yes. Take the polynomial $f(x)=2x+a$ itself. We could write it as $f(x)=2(x+\frac{a}{2})$, but the factor $x+\frac{a}{2}$ doesn't have integer coefficients in general. On the other hand it is monic, i..e, has leading coefficient $1$.
Comment: Thank you, I got it now.
Comment: If you are satisfied with the answer you can accept it.


Getting rid of module-specific control logic

Question: I'm writing a module that can have some additional functionality if other modules such as Block or Menu are enabled, but I don't want to declare them as a dependency.
Currently I'm using if(module_exists($module)) { ... } to provide module-specific functionality within my custom module (in this case, defining a particular view if the module in question is present).
However I've heard that this is not the right way to provide module-specific features, and that instead I should use hooks and plugins. The only problem is that I don't really know what that means or how to get started converting my module to using those instead of if()s.
How do I define a custom view that depends on another module without using an if()?
One of the things I am trying to do is to expose that module's SQL tables to Views if the module exists, and then define a custom view with those tables.
Comment: What specific functionality are you wanting to add? You may be able use the relevant module hooks, otherwise `module_exists` could be a reasonable solution.
Comment: One of the things I am trying to do is to expose that module's SQL tables to Views if the module exists, and then define a custom view with those tables.
Answer: If you want to provide Views with your module, dependent on enabled modules, you can implement
hook_views_default_views

This hook allows modules to provide their own views which can either
  be used as-is or as a "starter" for users to build from.
This hook should be placed in MODULENAME.views_default.inc and it will
  be auto-loaded. MODULENAME.views_default.inc must be in the directory
  specified by the 'path' key returned by MODULENAME_views_api(), or the
  same directory as the .module file, if 'path' is unspecified.
The $view->disabled boolean flag indicates whether the View should be
  enabled (FALSE) or disabled (TRUE) by default.

In that hook implementation, you can check if the relevant module is enabled with module_exists or function_exists when defining that View or component of the View and return the View definition(s) accordingly.
Comment: This is what I'm already doing, as described above.
Comment: It wasn't clear that you're using `hook_views_default_views`, if so that seems like a reasonable solution. Alternatively, you could use features with a `dependencies[]` declaration in the .info file.
Comment: "...but I don't want to declare them as a dependency." Using `hook_views_default_view()`is part of exposing any custom fields to Views, and isn't really related to checking for the presence of modules like Block or Menu.
Comment: I saw you said you don't want to declare them as a dependency but it's not at all clear why, especially if it was a distinct feature module. hook_views_default_view defines the view, not custom fields, so you can return a view or not depending on available modules.
Comment: You're right, I was thinking of `hook_views_data()` instead. The reason I don't want to declare dependencies is because my module is meant to describe the current state of the site, not to alter it.
Answer: I think what you are looking for (or what other people meant when they said that you shouldn't use module_exists() so much) would be to implement hooks "on behalf of" another module.
E.g. Crumbs introduces a hook_crumbs_plugins(), and then it implements this hook on behalf of other modules: menu_crumbs_plugins(), taxonomy_crumbs_plugins(), etc. These hooks will only ever be triggered if the respective other modules are enabled.
Whether this is a good idea, depends. It is ok if you are really confident that the respective module will never ever implement this hook by itself. But you need to be aware that you are intruding in the other module's "namespace".
Module names as function prefixes in D7 are quite fragile anyway compared to real namespaces, so maybe we all don't care so much in D7 and just pray that nothing blows up.
Otherwise I don't think it is all too wrong to use module_exists() where it makes sense.
Next time someone says this is best practice, ask them to explain why! There are a lot of mythical and unquestioned DOs and DONTs floating around in the community..
Answer: If you're using hook_views_default_views, then using if module_exists is perfectly fine.
See the example how Entityform module implements that in entityform.views_default.inc file:
/**
 * Implements hook_views_default_views().
 */
function entityform_views_default_views() {
  $view = new view;
  $view->name = 'entityforms';
  // ...
  /* Display: Master */
  $handler = $view->new_display('default', 'Master', 'default');
  $handler->display->display_options['title'] = 'List';
  // ...
  $handler->display->display_options['relationships']['uid']['required'] = 0;

  if (module_exists('views_bulk_operations')) {
    /* Field: Bulk operations: Entityform */
    $handler->display->display_options['fields']['views_bulk_operations']['id'] = 'views_bulk_operations';
    $handler->display->display_options['fields']['views_bulk_operations']['table'] = 'entityform';
    // ...
    $handler->display->display_options['fields']['views_bulk_operations']['vbo']['force_single'] = 0;
  }

  /* Field: User: Name */
  $handler->display->display_options['fields']['name']['id'] = 'name';
  $handler->display->display_options['fields']['name']['table'] = 'users';
  // ...
  $handler->display->display_options['tab_options']['name'] = 'management';
  $views[$view->name] = $view;

  return $views;
}

Then if another module wants to alter the existing view definition, it can use hook_views_default_views_alter in similar way (see example here).


Java: Converter strings delimitadas por ponto para JSON aninhado

Question: Eu tenho um monte de atributos vindo como strings delimitadas por ponto como "company.id", "company.address.number", "user.name", "isAtive", e eu preciso criar um JSON aninhado com seus respectivos valores. Esses atributos e valores estão em um HashMap.
Nem tudo tem 3 níveis de profundidade: muitos têm apenas 1 nível de profundidade e muitos são mais profundos que 3 níveis.
Exemplo de código:
public static void main(String[] args) {
    Map<String, String[]> list = new HashMap<>();
    list.put("params.isAtive", new String[] {"true"});
    list.put("params.user.name", new String[] {"John Diggle"});
    list.put("params.company.id", new String[] {"1"});
    list.put("params.company.name", new String[] {"SICAL MOTORS"});
    list.put("params.company.address.number", new String[] {"525"});
    list.put("params.company.address.street", new String[] {"Park Avenue"});
    list.put("params.models", new String[] {"55", "65"});
    JSONObject jsonReq = new JSONObject();
    for(Entry<String, String[]> entry : list.entrySet()) {
        String key = entry.getKey().replaceAll("params\\.", "");
        String value = entry.getValue().length == 1 ? entry.getValue()[0] : Arrays.toString(entry.getValue());
        String [] spl = key.split("\\.");
        if(spl.length == 1) {
            jsonReq.put(key, value);
        } else {
            for (int i = 0; i < spl.length; i++) {
                if(i == spl.length - 1) {
                    jsonReq.getJSONObject(spl[i-1]).put(spl[i], value);
                } else {
                    if((i-1) > 0) {
                        if(!jsonReq.getJSONObject(spl[i-1]).has(spl[i])) {
                            jsonReq.getJSONObject(spl[i-1]).put(spl[i], new JSONObject());
                        }
                    } else {
                        if(!jsonReq.has(spl[i])) {
                            jsonReq.put(spl[i], new JSONObject());
                        }
                    }
                }
            }
        }
    }
    System.out.println(jsonReq.toString());
}

Resultado atual:
{"models":"[55, 65]","address":{"number":"525","street":"Park Avenue"},"company":{"name":"SICAL MOTORS","id":"1"},"user":{"name":"John Diggle"},"isAtive":"true"}

Resultado esperado:
{"models":"[55, 65]","company":{"name":"SICAL MOTORS","id":"1","address":{"number":"525","street":"Park Avenue"}},"user":{"name":"John Diggle"},"isAtive":"true"}

Lembrando que não é necessário utilizar JSONObject, se optar por outro não tem problema, só preciso resolver a questão.
Answer: Olá, veja se isso resolve pra vc
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import org.json.JSONObject;

public class Main {

  private static void addEntry(JSONObject jsonReq, String currentkey, String value) {
    String[] keys = currentkey.split("\\.");
    JSONObject newJson = new JSONObject();
    newJson = jsonReq;
    for(int i = 0; i < keys.length-1; i++){
        if (newJson.has(keys[i])) {
            newJson = newJson.getJSONObject(keys[i]);
        }else{
            newJson.put(keys[i], new JSONObject());
            newJson = newJson.getJSONObject(keys[i]);
        }
    }
    newJson.put(keys[keys.length-1], value);
    jsonReq=newJson;
  }

  public static void main(String[] args) {
    Map<String, String[]> list = new HashMap<>();
    list.put("params.isAtive", new String[] { "true" });
    list.put("params.user.name", new String[] { "John Diggle" });
    list.put("params.company.id", new String[] { "1" });
    list.put("params.company.name", new String[] { "SICAL MOTORS" });
    list.put("params.company.address.number", new String[] { "525" });
    list.put("params.company.address.street", new String[] { "Park Avenue" });
    list.put("params.models", new String[] { "55", "65" });
    JSONObject jsonReq = new JSONObject();

    for (Entry<String, String[]> entry : list.entrySet()) {
        String key = entry.getKey().replaceAll("params\\.", "");;
        String value = entry.getValue().length == 1 ? entry.getValue()[0] : Arrays.toString(entry.getValue());
        addEntry(jsonReq,key, value);
    }
    System.out.println(jsonReq.toString());
 }
}

Resultado atual
{"models":"[55, 65]","company":{"address":{"number":"525","street":"Park Avenue"},"name":"SICAL MOTORS","id":"1"},"user":{"name":"John Diggle"},"isAtive":"true"}

Resultado esperado:
{"models":"[55, 65]","company":{"name":"SICAL MOTORS","id":"1","address":{"number":"525","street":"Park Avenue"}},"user":{"name":"John Diggle"},"isAtive":"true"}