Does Commerce Kickstart distribution include "advanced search" capabilities?

Question: By default the Commerce Kickstart distribution include a Search block. Just wondering if this distribution include a feature to add advanced search capabilities.
The advanced search would allow the user to filter by taxonomies terms.
Comment: Commerce Kickstart include only prepared commerce settings, no more...
Answer: Commerce kickstart includes the commerce search API module. http://drupal.org/project/commerce_search_api
Automatically created Search API db server, if none is found.
Auto-generated search index that includes all product display node types* and related product data.
Auto-generated facets for all node type categories and product attributes.
Optional integration with Search API Ranges (allowing for a price slider, for example).
Search API Filter class for product display node types* (allowing for an index composed only of product displays)
Facet API Filter class for removing facet items that do not change search results.
Facet API Filter class for hiding certain facets on the initial search (so that product attribute facets are only shown after the initial search, for example).
Comment: Exactly. All frontend views are powered by search api, and you get facets out of the box. Can't get more advanced than that.

(Note, that is Kickstart v2, not v1)
Comment: I understand, you are rigth. Facets search is much better thant the standar advanced search, it is just my client ask for the standar "advance search page" and I facets are kind of new.
Comment: Not sure what your definition of "standard advance search page" as this is open to interpretation. That being said, just create a view of product entities and some exposed filters for searching.


How to create a views filter for users who have never accessed a site?

Question: I have a view where I am trying to show all users who have a last access value of never, meaning they have never logged in.
The filter however expects a Date value which is no help to me because I just need to filter by users who have never accessed.

Does anyone know a way around this?
Answer: You can achieve this using following simple steps:

Add filter criteria User: Last access or User: Last login is equal to 1970-01-01

You could see the users.access = 0 in query

Note: Drupal uses Unix time. The unix time stamp is a way to track
  time as a running total of seconds. This count starts at the Unix
  Epoch on January 1st, 1970 at UTC. Therefore, the unix time stamp is
  merely the number of seconds between a particular date and the Unix
  Epoch.
Comment: +1 Good answer. Slight wrinkle though: As my site time zone is set at GMT+2 I had to set my access to 1970-01-01 02:00:00. Don't know what will happen if users are allowed to set their own time zone. Probably nothing.
Comment: Okay so this works better: Last access Is less than or equal to, Value 1970-01-02
Answer: Use hook_views_query_alter

Alter the query before executing the query.

Add a filter to your view on User: Last access and set Is equal to with Value: today
Next create a module and add following:
function MODULE_views_query_alter(&$view, &$query) {
  if ($view->name == 'useraccess') { // add your view name instead
    foreach ($query->where as &$condition_group) {
      foreach ($condition_group['conditions'] as &$condition) {
        if (strpos($condition['field'], 'users.access') === 0) {
          $condition = array(
              'field' => 'users.access',
              'value' => array(null),
              'operator' => '=',
          );
        }
      }
    }
  }
}

Answer: If you use GMT+x you can use "Regular expression" instead of "is equal to" and use ^0$ as expression.
The SQL result will be:
...
WHERE (( (users.uid NOT IN  ('0')) AND (users.access RLIKE '^0$') ))
...

Answer: In the value field just enter "never", exactly as it shows on /admin/people


How do uncovered tone holes in middle of a flute work?

Question: As a (mediocre) guitarist just starting to dabble with other instruments, the first several fingering diagrams for flutes, saxophones, etc make good intuitive sense to me because you're effectively just lengthening or shortening the resonance cavity, and coming from strings it's pretty easy to grasp that short=high and long=low.
After the first several notes, however, that intuition begins to break down and I really don't understand what's going on.
Take this fingering chart, for example:

D through B make total sense to me, but I don't understand how the subsequent broken-looking patterns work AT ALL. I can see how leaving the first tone hole uncovered will produce a higher pitch, but I don't understand how any open fingering after the first open fingering actually changes the note. If my original intuitions about D-B are correct, it seems like the first open hole the wave encounters should be the only one that matters...
Are you setting up two regions of resonance that interfere with one another? Can this be thought of like harmonics on a string instrument? What does a single open fingering in the middle (C# or that high E) actually DO? Is there an intuitive way to wrap my brain around this or am I just going to have to memorize diagrams?
Answer: There are a few things that closed holes below the first open tone hole can do.
In the case of that first C, what's happening is called shading. The tone holes of this instrument aren't as wide as the bore, so not all of the air can escape out of the first open tone hole. Some of it continues and goes out of the next open hole, and the result is that the resonant length is somewhere in between. These C fingerings are taking a C# and flattening it enough to be a serviceable C. Fingerings like this are called cross fingerings. Modern flutes have tone holes almost as large as the bore, and these kinds of fingerings don't work--they will affect the pitch slightly, but not anywhere near a half step.
For the second octave D, you have the right idea with the harmonics. Just as you can place your finger at the halfway point of a guitar string in order to prevent the string from vibrating there and force a higher harmonic to sound, you can open a hole halfway along the air column of a wind instrument to cause the same thing. This is also going on with the third octave D, E, and G. For the other notes in the second octave, and the third octave F, there's no hole where it would need to be, so you have to produce the overtone yourself by blowing higher across the embouchure hole.
Whether an open hole in the middle of the fingerings acts like the first open tone hole with shading, or as a harmonic-forcing vent, is a very tricky question involving complicated physics and tiny details of instrument construction.
Comment: With a small tonehole, the effect of the body below the tonehole is non-neglible, whereas with a large tonehole, there almost may as well be no more flute after the tonehole.  To put it another way, a small tonehole is the same as a large tonehole being nearly all whe way covered!  So the pitch is still lowered by the rest of the flute.  Whereas with a large open tonehole there's not that much more open it can get other than just sawing the end of the flute off
Comment: @Some_Guy even "sawing the end of the flute off" is not enough to create a "mathematically perfect" open end - to do that, you would need to add a trumpet-shaped bell to the open end as well. See my answer below.
Comment: The math is similar but not identical. For a rocket, you are modelling the steady flow of gas through the device. For a musical instrument, you are modelling the *unsteady* flow (i.e. "the sound waves") superimposed on that steady flow - and the steady flow component can usually be ignored, since its pressure and velocity are small (of the order of a few inches of water gauge and a few feet per second)
Comment: Interesting! So cross fingerings shouldn't crop up on modern instruments with large tone holes, but will probably be a feature on, say, a penny whistle or recorder? Wait... is this what the smaller holes in open-hole flutes are for?
Comment: @DavidPerry no, they're for being able to fit your fingers over.  Open holed boehm flutes (big keys with little holes) allow a player to have some of the control and freedom (e.g. half holing) given by traditional keyless flutes, but still have large boehm toneholes when the key is not pressed.  These large tone holes give you volume, and better intonation.  Of course, it also radically changes the sound of the instrument.  I personally love wooden flutes with smaller tone holes, but the Boehm flute (with keywork to allow very large toneholes) is undoubtedly a much more "powerful" instrument.
Comment: Probably off-topic as hell, but I also dabble in rocketry and that "mathematically perfect" open end sounds like it must be related to the math that determines the size and shape of engine bells, and the reason why aerospike efficiency vs altitude is practically a flat line (the outer edge of the bell geometry is determined by atmospheric pressure). Am I drawing a faulty connection here?
Answer: To add just a small amount of physics to MattPutnam's answer:
A guitar string is relatively simple to understand, because assuming that both ends of the string are fixed is a very good approximation - though it is not completely correct, since in an acoustic guitar the bridge must have some movement to transfer the vibrations from the string to the body of the instrument. That is one reason why guitars need to be "set up" to get the best intonation - the position of the frets can't be calculated "exactly" from the distance between the bridge and nut.
In high school physics courses it is often taught that the open end of a pipe corresponds to the free end of a vibrating string, and the closed end to the fixed end of a string.
That is over-simplified for the open end. When doing the simplest experiments on the resonance of a pipe, you have to apply an "end correction" by assuming the open end is actually a bit longer (in proportion to its diameter) than its measured length, but that simple "end correction formula" is itself only an approximation to the real behaviour.
To get close to the simple notion of the "open end" of a pipe, the pipe has to end in a bell or flare, like a trumpet or trombone, but that brings in different mathematical complications because the diameter of the pipe is no longer constant.
At a simple level, a flute can be considered as a pipe "open at both ends" but in fact the blowing hole affects the pitch in a similar way to the finger holes - and the size of the effect depends on the geometry of the complete system of the flute plus the player, not just on the flute!
The finger holes are not all the same diameter (as is shown in the OP's photo) and there is a tradeoff between the size of the hole and its position along the length of the pipe. It should be clear that the holes are spaced more or less evenly along the length, which is very different from the fret positions for the first octave along a guitar string.
It is easy to demonstrate the effect of the finger hole size on simple flute-like instruments (e.g. penny whistle, recorder, or even a baroque keyless flute) by playing a note while bringing a finger close to a finger-hole but not actually touching the flute.
The closer the finger, the lower the pitch. In fact this was a standard playing technique for "pitch bending" notes in baroque flute music.
Take home message: the acoustics of pipes are more complicated than they might seem at first sight - and they are much more complicated than stretched strings!
Comment: A more accurate acoustic model of a flute replaces each finger hole with a short *tube* branching at right angles to the flute, where the length of the tube is related to the hole diameter. The standard wave pressure is (approximately!) atmospheric at the "open" end of each of these tubes, but not where each side-tube branches off the main bore of the instrument.
Comment: To add another complication, there is also a significant length of *closed* pipe on the opposite side of the blowing-hole from the main instrument - and that closed pipe does *not* have a constant diameter bore. All these details matter!
Comment: "The tube length is basically modeling the back-pressure" - that is basically correct, but even when the finger hole is closed there is still a *cavity* in the side of the bore, because the instrument tube has a finite thickness, and on metal flutes (which tend to have thinner  tube walls than wooden ones) there may be an external "pad" to thicken it more where the hole is bored.
Comment: I hadn't even noticed or considered the spacing difference between tone holes and frets, but that makes total sense. If the resonant frequency of the cavity is determined by some function where the pressure of the standing wave is highest at the closed end and approximately atmospheric pressure at all openings, it stands to reason that the size of those openings relative to the instrument's bore would have a substantial effect on those functions - and I *had* noticed that some of the holes on my new flute were larger than others, but the spacing difference totally made that click a lot better!
Comment: That makes a lot of sense - the tube length is basically modeling the back-pressure applied by constricting the airflow if I'm intuiting the right things from this?


How to use ResultSet: absolute(int row) in java and dispaly retrieved rows in tabular format through jsp using jstl

Question: I want to retrieve some specific rows from ResultSet by using absolute(int row) method.I have retrieved all the rows in tabular format by following code:
public String[][] reference() {

        String a[][]=new String[46][2];
        int i=0;
        try
            {
              con = getConnection();
              stmt = con.createStatement(rs.TYPE_SCROLL_SENSITIVE,rs.CONCUR_READ_ONLY);
              String sql="select logtime,beam_current from INDUS2_BDS.dbo.DCCT where logtime between '2014-10-10 07:17:00' and '2014-10-10 08:46:00'"+
              "and (beam_current like '%9.96' or beam_current like '%9.97' or beam_current like '%9.98' or  beam_current like '%9.99'  or beam_current like '%0' or beam_current like '%_0.01' or beam_current like '%_0.02' or beam_current like '%_0.03' or beam_current like '%_0.04' or beam_current like '%_0.05' or beam_current like '%_0.06')";
              stmt.executeQuery(sql);
              rs = stmt.getResultSet();

              while(rs.next())
              {

                      for(int j=0; j<2; j++)

                        {
                            a[i][j] = rs.getString(j+1);

                        }

                        i++;
                  }
           }

         catch( Exception e )
            {
                System.out.println("\nException "+e);
            }
            finally
            {
                closeConnection(stmt, rs, con);
            }
        return a;

Now I only want to retrieve only 3,4,11,13,23,27,28 rows in-spite of all.How to do that?
Answer: Define int rowCounter=0; before the while and increase it in the end of the while body.
Add a check if (rowCounter==3 || rowCounter==4 ...) { //do your logic}
Comment: How to print that Resulset absolute() value on browser i.e when I do          if (rowCounter==3 || rowCounter==4 ...) {rs.absolute(3);rs.absolute(4)}return rs  , then I get **SQLServerResultSet:1** as output not that particular row
Comment: I'm not able to print the rows.


CMake 3.11 falha ao compilar REGEX

Question: Estou tentando configurar uma biblioteca com o CMake 3.11 e estou obtendo um erro de compilação de uma string REGEX, o projeto pede o FLEX 2.5 com a função find_package:
find_package(FLEX 2.5 REQUIRED)

Essa chamada utiliza o módulo FindFLEX.cmake, na linha 137 desse módulo tem a instrução que gera o erro:
string(REGEX REPLACE "^.*${FLEX_EXE_NAME_WE}(${FLEX_EXE_EXT})?\"? (version )?([0-9]+[^ ]*)( .*)?$" "\\3"

O erro é:

CMake Error at D:/CMake/share/cmake-3.1/Modules/FindFLEX.cmake:137 (string):
      string sub-command REGEX, mode REPLACE failed to compile regex
      "^.flex++(.exe)?"? (version )?([0-9]+[^ ])( .*)?$".
      Call Stack (most recent call first):
CMakeLists.txt:58 (find_package)

O diretório do FLEX 2.5 já foi configurado.
Agradeço a atenção de todos.
Answer: Faltou fechar o parêntese no final da linha.
string(REGEX REPLACE "^.*${FLEX_EXE_NAME_WE}(${FLEX_EXE_EXT})?\"?
(version )?([0-9]+[^ ]*)( .*)?$" "\\3")

No código do FindFLEX.cmake essa linha na verdade está assim:
string(REGEX REPLACE "^.*${FLEX_EXE_NAME_WE}(${FLEX_EXE_EXT})?\"?
(version )?([0-9]+[^ ]*)( .*)?$" "\\3" FLEX_VERSION "${FLEX_version_output}")

Comment: o executável do FLEX que eu estava utilizando era o flex++.exe, quando eu mudei para flex.exe funcionou, mas também não faz diferença, já mudei a API e já consegui compilar, agradeço por sua atenção.

CMake 3.11 falha ao compilar REGEX


On Play2 SecureSocial, POST is executed as GET after SecureadAction

Question: I'm using PlayFramework 2.1.4 and SecureSocial 2.1.1.
I defined routes like below, set the request as POST.
POST    /postComment                                  controllers.Application.postComment

It goes well at first, but after SecuredAction, the request changed to GET.
Logs:
[info] application - onRouteRequest() requestHander = POST /postComment
[debug] application - [securesocial] anonymous user trying to access : '/postComment'
[debug] application - [securesocial] assets controller = controllers.ReverseAssets
[info] application - onRouteRequest() requestHander = GET /login
[error] application - [securesocial] can't find provider for id userpass
[info] application - onRouteRequest() requestHander = GET /authenticate/facebook
[debug] application - [securesocial] user logged in : [SocialUser(IdentityId( ...)]
[info] application - onRouteRequest() requestHander = GET /postComment
[warn] application - onHandlerNotFound() requestHander = GET /postComment

What shall I do? Please give me your advice.
The form is like this (createComment.scala.html).
@helper.form(action=routes.Application.postComment){
@helper.textarea(commentForm("body"))

        <input type="submit" class="btn primary" value="submit">

}

and this is the Application.scala
case class CommentData(body: String, vote: String)

object Application extends Controller with SecureSocial {
val commentForm = Form(mapping("body" -> nonEmptyText)(CommentData.apply)(CommentData.unapply))
def postComment = SecuredAction { implicit request =>
val id=session.get("targetCommentId");
commentForm.bindFromRequest.fold(
formWithErrors => {
BadRequest(views.html.createComment(commentForm)).withSession(session+"targetCommentId"->id.toString)
},
commentData => {
val id = request.user.identityId.userId
val body = commentData.body
application.Application.createComment(id, body)
Ok(views.html.topiclist())
})
}
}

Answer: SecureSocial redirects to the original page after authentication, but will do so with an 303 See Other response that'll result in a GET request on the target resource. Whilst it's a simplification to say you can't redirect to a POST request, it won't work with SecureSocial AFAIK.
A better way to handle this would be to prompt for authentication before the user submits the comment form, i.e:

anon user wants to create a comment and clicks "add comment" (or whatever)
do authentication via FB
redirect back to comment form (GET), now with authenticated user
proceed to process form submission (POST)

You can read about some issues with POST redirects here.
Comment: Thank you very much!  I will make auth before the submission.


Bytes are different with clob data on Oracle db and original file

Question: I have a png file which is stored as CLOB in oracle db.
and i want to get this data with jdbc template using below code
LobHandler lob = new DefaultLobHandler();
return jdbcTemplate.queryForObject(
  "select table from column",
  arr,
  (rs, rowNum) -> lob.getClobAsString(rs, "CLOB_DATA")
);

and i am converting to byte array as follows since the encoding in oracle db is  WE8MSWIN1252
clob.getBytes(Charset.forName("windows-1252"));

however i get the different bytes when i read the file manually with below code and compare with the db data.
File path = new File("path/to/file");
Files.readAllBytes(path.toPath());

some chars are not loaded correctly. what could be the problem?
Comment: CLOBs are for storing character data. You want to be storing binary data in a BLOB
Comment: Image data should be stored in the database as a BLOB so you avoid problems with character conversion.  Does the image data from the database produce an image?
Comment: yes it does produce an image, and i cannot change it to blob since there are already added data as CLOB in DB.
Answer:
I have a png file which is stored as CLOB in oracle db.

Don't do this. If you have binary data then store it in a binary format, such as a BLOB, and don't store it in a format which was not intended for that purpose.

however i get the different bytes when i read the file manually with below code and compare with the db data.

That's because you're using a CLOB for something it wasn't intended for.

what could be the problem?

The problem is that you are using the wrong data type for your data.

i cannot change it to blob since there are already added data as CLOB in DB.

Change them all to a BLOB and then just convert the BLOB to a CLOB when you need to get character data out. Trying to do it the other way round (without any encoding of the binary to make is safe to store as a string) is going to continue creating issues like the one you already have.
If you really must use a CLOB (please, DON'T) then store the binary in an encoded format, such as Base64, which can be safely stored as character data.


Como eu deleto um arquivo, que tem aspas no nome, pelo CMD?

Question: Eu estou deletando uma pasta do meu HD e pude apagar tudo, exceto esse arquivo.
Porque ele tem aspas, eu não posso usar nomes curtos, e não posso apagá-lo do jeito que está.
Eu tentei fsutil file setshortname, mas eu não consigo manter as aspas em mai_68
Eu tentei aspas duplas, \, e outros caracteres especiais, como %, mas as aspas não são reconhecidas pelo shell, como vocês podem ver:
Comment: Mesmo com o espace para a `"` que é usar `""`, não consegui remover o ficheiro. Já tentei diversas formas mas tudo sem sucesso! Linux Live CD, apagar ficheiro, reiniciar ;)
Comment: @Zuul Publique sua sugestão como uma resposta. Eu tentei de tudo no Windows, inclusive usar editores de disco (WinHex, HxD, DiskExplorer), pra tentar renomear o arquivo à força, mas no Windows 7 dá acesso negado... os drivers de acesso ao disco o protegem contra escritas, sendo que a única forma seria desmontar a unidade para depois editar (ai o driver deixa). Acontece que o caminho é muito longo e chato, ou impossível no caso do drive de sistema... parece mais fácil fazer download de uma distro de Linux Live pequena, colocar num CD ou USB e então fazer da forma que você disse.
Comment: @MiguelAngelo Meti agora a resposta sugerindo uma LiveCD. Estive a tentar outros métodos que não os que indicaste e/ou já havia tentado, mas sem sucesso! LiveCD, 5min e tá arrumada a questão :)
Answer: Caracteres reservados
Em Windows, existem alguns caracteres que são reservados (Inglês) pois servem um propósito ao serem utilizados pelo sistema operativo:

< (menor que)
> (maior que)
: (dois-pontos)
" (aspas)
/ (barra)
\ (barra invertida)
| (barra vertical)
? (ponto de interrogação)
* (asterisco)

Estes caracteres não são permitidos em nomes de ficheiros ou directorias dado serem reservados, mas isso não quer dizer que não venham a estar presentes nos mesmos, dado que muitos sistemas operativos que não o Windows, permitem o seu uso.
Confrontado com ficheiros ou directorias que usem estes caracteres, torna-se difícil resolver o problema a partir de um sistema que não permite o seu uso, pelo que, uma solução passa utilizar outro sistema operativo para os renomear ou remover.
Solução
Felizmente, usar outro sistema operativo nos dias de hoje não requer mais que meia dúzia de minutos, como é o caso das LiveCD de Linux:

Descarregar um ISO de Linux;
Descarregar e executar este ou outro software para criar uma PEN de arranque;
Da lista de opções, escolher a distribuição correta, se do link que deixei em cima, será a opção "Linux Mint";
Escolher o ficheiro ISO da distribuição que descarregaste;
Criar a PEN de arranque.

Depois de criada, basta usar a mesma para arrancar com o computador, escolher a opção de "Experimentar".
Answer: Na linha de comando, e com o diretório corrente no local onde estão os arquivos, digite:
dir /x

Os nomes envoltos pela borda laranja são os nome em formato 8.3.
Com o nome curto do arquivo, você poderá exclui-lo.
Fonte: https://superuser.com/a/381516/90552
Comment: Nope, sem sucesso comigo! O problema é que `"` é um carácter ilegal para nomes de ficheiros ou diretorias... o próprio windows nem deixa criar ficheiros que contenham `"` no nome.
Comment: @Zuul Eu não consegui criar um arquivo com aspas duplas pra testar... você saberia como fazer isso pra que eu teste aqui?
Comment: Eu criei usando Linux, em Windows não consegui. Tenho os dois sistemas em paralelo, mas podes usar um LiveCD para rapidamente criares o ficheiro e voltares para o windows.
Answer: O Windows não reconhece arquivos que tenham caracteres especiais, portanto ele entende que se trata de um arquivo inválido. Uma maneira de remover esses arquivos é executando o chkdsk com  o parâmetro /f.
chkdsk o: /f

Onde O: é a partição onde se encontra os arquivos inválidos a serem corrigidos. Depois de terminado a operação, uma pasta chamada O:\found.000 será criada contendo o arquivo que agora pode ser deletado.
O valor 000 pode mudar dependendo da quantidade de arquivos inválidos encontrados.
Para deletar, entre na pasta  found.000 (use cd LETRA para acessar a partição):
>cd found.000

Depois delete todos os arquios com a extensão .chk:
> del *.chk

Comment: http://unix.stackexchange.com/questions/102043/how-to-delete-a-ntfs-filesystem-file-whose-name-contains#comment206207_102081


Is there a special term for this type of alternate picking?

Question: I'm looking to see if there's a special word for a type of alternate picking commonly heard in metal that involves playing a series of notes on a lower string while also playing notes on a higher string in between.
Something like this:

The technique I'm looking for starts at around 25 seconds. I've noticed a lot of heavier metal guitar players utilize this technique, and I have a hard time playing any of these songs. I'm trying to find a good way to search for this type of playing to find relevant practice exercises.
Comment: Maybe you are looking for _string-skipping_ exercises?
Comment: Am I correctly assuming that [Bullet for my Valentine - Suffocating under Words of Sorrow](https://www.youtube.com/watch?v=GNzdVsajedM) is another example of the picking style you mean?
Comment: @Ian Yes the main riff for this song is exactly what I'm looking for.
Answer: It sounds like string skipping which.  There is no special technique other than practice string skipping exercises slowly with a metronome until you can play clean.  As for alternate versus other picking methods that is up to you.  Mal Bay Grade 2 has some string skipping exercises near the end that are pretty tough to get fast and are worth the effort to work on.  I am sure you can find similar exercises in a book on shred guitar techniques.  But don't search for "alternate picking" search on "string skipping".


Como criar uma função no Arduino com argumentos opcionais

Question: Gostaria de criar uma função que recebe dois argumentos:
StatusPino(nPino,Valor)
Porém gostaria de, quando enviar somente o número do pino, a função ler o valor lógico do pino e quando eu informar o número do pino COM UM VALOR, a função gravar o valor atual no pino.
Ex:
If StatusPino(Sensor1);   // Se o Sensor1 tiver valor HIGH, retorna true
   // Sensor Ativado
Else
   // Sensor Desativado

ou
StatusPino(Sensor1,LOW);    // Seta o Sensor1 para LOW e retorna LOW

Não encontrei nenhuma função parecida.
Sim, eu poderia fazer 2 funções  LerStatusPino() e GravarStatusPino(), porém estou querendo evitar justamente isso.
Obrigado.
Answer: Tu só precisas declarar a função, como é feito no C, segue uma exemplo.
    void StatusPino(int nPino = 0,int Valorint = 0); \\ Declare a funcao com um parametro padrão

    void setup() {

        pinMode(13, OUTPUT);
    }

    void loop() {

        StatusPino(13,1);
        delay(1000);

        StatusPino(12,1);
        delay(1000);

        StatusPino(13);
        delay(1000);

        StatusPino(12);
        delay(1000);

    }

    void StatusPino(int nPino,int Valorint)
    {

        digitalWrite(nPino, Valorint);

    }


UITableview lags when scrolling.

Question: I'm trying to implement events table like in iOS 6 calendar.
I have UITableView with 500 rows(events). When I start scrolling animation is smooth.
But after two hundred rows begins lags. In native iOS 6 calendar events list all work smoothly.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    double begin = CFAbsoluteTimeGetCurrent();
    if(!self.isNoResults)
    {
        NSString *cellIdentifier = [NSString stringWithFormat: @"Cell %i %i", indexPath.row, indexPath.section];
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
        UIImageView *circleImgView;
        NSString *startTimeStr;
        NSDateFormatter *formatter;
        UILabel *timeLbl;
        UILabel *titleLbl;
        UILabel *endsLbl;
        UIImageView *eventTypeImgView;
        if(cell == nil)
        {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
            circleImgView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"newMesIcon.png"]];
            circleImgView.frame = CGRectMake(14, 19, 12, 12);
            [cell.contentView addSubview:circleImgView];

            timeLbl = [[UILabel alloc] init];
            [timeLbl setBackgroundColor:[UIColor clearColor]];
            timeLbl.frame = CGRectMake(35, 15, 200, 20);
            timeLbl.font = [UIFont systemFontOfSize:13];
            timeLbl.tag = 333;
            [cell.contentView addSubview:timeLbl];

            titleLbl = [[UILabel alloc] init];
            titleLbl.frame = CGRectMake(123, 15, 200, 20);
            titleLbl.font = [UIFont fontWithName:@"Arial-BoldMT" size:18];
            [titleLbl setBackgroundColor:[UIColor clearColor]];
            titleLbl.tag = 444;
            [cell.contentView addSubview:titleLbl];
            [cell.contentView setBackgroundColor:[UIColor colorWithRed:243 / 255.0 green:245 / 255.0 blue:247 / 255.0 alpha:1.0]];

            endsLbl = [[UILabel alloc] init];
            [endsLbl setBackgroundColor:[UIColor clearColor]];
            endsLbl.frame = CGRectMake(49, 11, 40, 8);
            [endsLbl setFont:[UIFont fontWithName:@"Arial-BoldMT" size:7]];
            [endsLbl setTextColor:[UIColor redColor]];
            endsLbl.tag = 555;
            [cell.contentView addSubview:endsLbl];

            eventTypeImgView = [[UIImageView alloc] init];
            eventTypeImgView.frame = CGRectMake(95, 16, 16, 17);
            eventTypeImgView.tag = 666;
            [cell.contentView addSubview:eventTypeImgView];
        }

        startTimeStr = [[self.sortedEventsDict[[[[self.sortedEventsDict allKeys] sortedArrayUsingSelector:@selector(compare:)] objectAtIndex:indexPath.section]]  objectAtIndex:indexPath.row] valueForKey:@"starts"];

        formatter = [[NSDateFormatter alloc] init];
        [formatter setDateFormat:@"yyy-MM-dd HH:mm"];
        NSDate *startDate = [formatter dateFromString:startTimeStr];
        NSDateFormatter *timeFormatter = [[NSDateFormatter alloc] init];
        [timeFormatter setDateFormat:@"HH:mm"];
        NSString *timeStr = [timeFormatter stringFromDate:startDate];

        NSString *endTimeStr = [[self.sortedEventsDict[[[[self.sortedEventsDict allKeys] sortedArrayUsingSelector:@selector(compare:)] objectAtIndex:indexPath.section]]  objectAtIndex:indexPath.row] valueForKey:@"ends"];
        NSDateFormatter *endformatter = [[NSDateFormatter alloc] init];
        [endformatter setDateFormat:@"yyy-MM-dd HH:mm"];
        NSDate *endDate = [endformatter dateFromString:endTimeStr];
        NSDateFormatter *endtimeFormatter = [[NSDateFormatter alloc] init];
        [endtimeFormatter setDateFormat:@"HH:mm"];
        NSString *endTime = [endtimeFormatter stringFromDate:endDate];

        if([[[self.sortedEventsDict[[[[self.sortedEventsDict allKeys] sortedArrayUsingSelector:@selector(compare:)] objectAtIndex:indexPath.section]]  objectAtIndex:indexPath.row] valueForKey:@"type"] isEqualToString:@"event"])
        {
            ((UIImageView *)[cell.contentView viewWithTag:666]).image = [UIImage imageNamed:@"eventsIcon.png"];
        }
        else
        {
            ((UIImageView *)[cell.contentView viewWithTag:666]).image = [UIImage imageNamed:@"appointmentsIcon.png"];
        }

        ((UILabel *)[cell.contentView viewWithTag:555]).text = @"";
        if([timeStr isEqualToString:@"00:00"] && [endTime isEqualToString:@"23:59"])
        {
            timeStr = @"all-day";

        }

        else if([timeStr isEqualToString:@"00:00"] && ![endTime isEqualToString:@"23:59"])
        {
            timeStr = endTime;

            ((UILabel *)[cell.contentView viewWithTag:555]).text = @"ENDS";

        }

        ((UILabel *)[cell.contentView viewWithTag:333]).text = timeStr;
        ((UILabel *)[cell.contentView viewWithTag:444]).text = [[self.sortedEventsDict[[[[self.sortedEventsDict allKeys] sortedArrayUsingSelector:@selector(compare:)] objectAtIndex:indexPath.section]]  objectAtIndex:indexPath.row] valueForKey:@"title"];

        startDate = nil;
        timeFormatter = nil;
        timeStr = nil;
        endTimeStr = nil;
        endformatter = nil;
        endDate = nil;
        endtimeFormatter = nil;
        endTime = nil;
        startTimeStr = nil;
        formatter = nil;
        [cell setBackgroundColor:[UIColor colorWithRed:243 / 255.0 green:245 / 255.0 blue:247 / 255.0 alpha:1.0]];
        double finish = CFAbsoluteTimeGetCurrent();
        NSLog(@"TIME DIFF = %f", finish - begin);
        return cell;
    }
    else
    {
        NSString *cellIdentifier = [NSString stringWithFormat: @"Cell No Results %i %i", indexPath.row, indexPath.section];
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
        if(cell == nil)
        {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
            if(indexPath.row == 2)
            {
                UILabel *noResultsLbl = [[UILabel alloc] init];
                noResultsLbl.text = self.noResultsString;
                [noResultsLbl setFont:[UIFont fontWithName:@"Arial-BoldMT" size:20]];
                [noResultsLbl setTextColor:[UIColor colorWithRed:204 / 255.0 green:204 / 255.0 blue:204 / 255.0 alpha:1.0]];
                noResultsLbl.frame = CGRectMake(60, 15, 200, 20);
                noResultsLbl.textAlignment = NSTextAlignmentCenter;
                [cell.contentView addSubview:noResultsLbl];
            }

        }
        [cell.contentView setBackgroundColor:[UIColor colorWithRed:243 / 255.0 green:245 / 255.0 blue:247 / 255.0 alpha:1.0]];
        cell.userInteractionEnabled = NO;
        double finish = CFAbsoluteTimeGetCurrent();
        NSLog(@"TIME DIFF = %f", finish - begin);
        return cell;
    }
}

Please, help me.
Comment: Use instruments and measure what the actual problem is. Everything else is just guesswork.
Comment: You're creating two date formatters for every single cell in the table view. This is guaranteed to grind your app to a halt.
Comment: Thank you all guys for help. +1 from me to all.
Comment: Use Instruments as  @David Rönnqvist suggests. In my case, I was doing some NSUTF8StringEncoding on Attributedtext. Instruments pointed out that this was a heavy operation. I rewrote it, and my performance was back to 60 fps
Answer: Your cellForRowAtIndexPath is 140 lines long, that is the reason its not running smoothly. I would recommend going over the code and trying to refactor out as much as you can. Formatters are incredibly expensive, and you're alloc/initing several. Make a prototype or xib based cell rather than setting it up programmatically every single time. Id also recommend against using tags for views, put that into a xib or prototype cell and make it an outlet.
Those changes will speed up your scrolling.
Answer: Check the size of the images you are using in the cell. I had this problem once when the images were larger than they needed to be. Try reducing the image sizes to their optimal size for the table.
Comment: I have a tableview with images and I solved the table's lag with image' resizing. Thank you! *** IMPORTANT *** right way to resize an image: http://vocaro.com/trevor/blog/2009/10/12/resize-a-uiimage-the-right-way/
Answer: You sort all your data for each cell.
if([[[self.sortedEventsDict[[[[self.sortedEventsDict allKeys] sortedArrayUsingSelector:@selector(compare:)] objectAtIndex:indexPath.section]]  objectAtIndex:indexPath.row] valueForKey:@"type"] isEqualToString:@"event"])

Try to use prepared data for each [table reloadData] call. Basically you could perform all calculations in one place, and then just fill cells with results.
And best way to find what goes wrong is to use Profiler. It will show you which part of code eats all your cpu between frames.
Answer: No cell reuse, several alloc/init-s and a lot of NSDateFormatter's with is really expensive
Todo:

Subclass UITableViewCell and make your custom cell
Reuse cell using a constant identifier
Reuse NSDateFormatters with DFDateFormatterFactory or manually use NSDateFormatter separated by format, because each format is like a new formatter

Reuse cell:
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath      *)indexPath
{
     static NSString *CellIdentifier = @"cell";
     UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    if (!cell) {
// Setup new cell and constant elements of cell
    }

// Setup data like images, strings and stuff with minimal calculations and formatting
     return cell;
}

Answer: My solution might be for a very rare case but it for sure helps.
I had a cell which contained a label with string of currency rubles "₽" (i think this also might be caused by other currency chars). This string was added to the label dynamically every time cell was reused. And the table view was very laggy. Then I removed only Ruble sign and lagging disappeared.
Solution: create a ready label and input the char into the label from the storyboard.
Answer: For me lags were caused by another tableView inside the main tableView cell (weird situation, I know). I've fixed it by removing additional tableView and rethinking my app's architecture without "tableView inside tableView" approach.

UITableview lags when scrolling.


Examples of self adjoint compact operators on Hilbert spaces

Question: As the titles says, I'm looking for examples of self adjoint compact operators on Hilbert spaces.
So far I know of the diagonal operator on $\ell^2$,
$$
(Tx)_i = \alpha_ix_i
$$
for some sequence $\alpha_i \to 0$;  and the Hilbert Schmidt integral operator in $L^2(\Omega)$,
$$
Kg = \int_{\Omega}K(x,y)g(y)dy
$$
with $K \in L^2(\Omega^2)$ a symmetric Hilbert-Schmidt kernel.
I would also like to know of some applications that use Hilbert Schmidt integral operators.
Edit: I'd be really grateful to know about the behaviour of the norm of the operators as well.
Thanks in advance.
Comment: @cmk awesome, thank you!
Answer: An important example is the inverse of the Laplace operator: $T=(-\Delta)^{-1}$ as mapping from $H^1_0(\Omega)^*$ to $H^1_0(\Omega)$. Here, $\Omega$ is an open and bounded domain in $\mathbb R^n$. That is, given $z\in H^1_0(\Omega)$, $u:=Tz$ is the weak solution of
$$
-\Delta u = z,
$$
which is equivalent to
$$
\int_\Omega \nabla u \cdot\nabla v \ dx = \int_\Omega zv \ dx \quad\forall v\in H^1_0(\Omega).
$$
Answer: There are tons of examples, but I'll give a few from the context of PDEs.
@daw already gave a very good example. Let me provide a similar one, in the form of the heat propagator. You may know that the study of the heat equation is fundamental in many fields of PDEs. To that end, let $M$ be a compact, Riemannian manifold without boundary with metric $g$. If $p$ denotes the fundamental solution to the heat equation on $M\times (0,\infty),$ then for $t>0,$ we define the heat propagator as the map $e^{-t\Delta_g}:L^2(M)\rightarrow L^2(M)$ via $$e^{-t\Delta_g} f(x)=\int\limits_M p(x,y,t) f(y)\, \omega_g(y),$$ where $\omega_g$ is the volume form. It's not too hard to show that $e^{-t\Delta_g}$ is a self-adjoint, compact operator on $L^2$.
Here is another example, which is of significant importance in the realm of semi-classical analysis. Note: I'm going to use $\mathcal{S}$ to denote the Schwartz space, and I'm going to use it for both  $\mathcal{S}(\mathbb{R}^n)$ and $\mathcal{S}(\mathbb{R}^{2n})$. Symbols will always be in the latter, and everything else in the former.
Let $a\in\mathcal{S},$ and $h>0.$ We define the Weyl quantization to be the operator $a^w(x,hD)$ on $\mathcal{S}$ so that $$a^w(x,hD)u(x)=\frac{1}{(2\pi h)^n}\int\limits_{\mathbb{R}^{n}}\int\limits_{\mathbb{R}^{n}}e^{\frac{i}{h}(x-y)\cdot\xi} a\left(\frac{x+y}{2},\xi\right)u(y)\, dyd\xi.$$ This is related to applying the conjugation of $a$ by the semi-classical Fourier transform to $u$, but the convex combination of $x$ and $y$ stops this from being quite a semi-classical Fourier multiplier (unless $a$ is independent of $x$). This is called a pseudodifferential operator (which can also be defined on manifolds, but I'd rather not make that digression). This operator can be defined as a map $a^w(x,hD):\mathcal{S}'\rightarrow\mathcal{S},$ and it is formally self-adjoint here, provided $a$ is real-valued. In fact, in a proof similar to proving that the Hilbert-Schmidt kernel operator is bounded in $L^2$, you get that the Weyl quantization sends $L^2\rightarrow L^2$, and it's bounded. In a proof similar to that of the Arzela-Ascoli theorem, one can show this is compact, as well.
You also asked about applications of Hilbert-Schmidt operators. First, here's a classical result:

If $T:L^2(X_1,\mu_1)\rightarrow L^2(X_2,\mu_2)$ is HS, then there exists $K\in L^2(X_1\times X_2,\mu_1\times \mu_2)$ such that $$(Tu,v)_{L^2}=\iint K(x_1,x_2)u(x_1)\overline{v(x_2)}\, d\mu_1(x_1)d\mu_2(x_2).$$ Note that $$\|T\|_{\text{HS}}=\|K\|_{L^2}.$$ Conversely, if $K\in L^2(X_1\times X_2,\mu_1\times \mu_2)$, then the above integral defines a Hilbert-Schmidt operator $T$, with the same norm equality.

If a bounded operator on a separable Hilbert space can be written as the product of two HS operators, then we say that this operator is trace-class. One characterization of such operators is that a bounded operator $C$ is trace-class if and only if $C$ is compact and $(C^*C)^{1/2}$ has summable eigenvalues. The norm on trace-class operators is given by the infimum over all decompositions of the operator (in the way described by the definition of trace-class) of the product of their respective Hilbert-Schmidt norms. This forms the space into a Banach space. A nice thing about trace-class operators is that we can define their determinants in an appropriate sense (although I won't go through this construction). Trace-class operators get their name because we can take their trace, in the sense that if $C$ is trace-class, then we can define its trace as $$\text{Tr}\ C=\sum c_{jj},$$ where $c_{jj}=(Cu_j,u_j)$, and $\{u_j\}$ is the orthonormal basis for the given Hilbert space. Alternatively, if we write $C=AB^*$, then $$\text{Tr}\ C=(A,B)_{\text{HS}}=\sum_{j,k} a_{jk}\overline{b}_{jk},$$ where $a_{jk}=(Au_j,u_k).$ We can talk about the trace of an integral operator as follows: Let $A,B$ be Hilbert-Schmidt on $L^2(X,\mu)$ with integral kernels $K_A,K_B\in L^2(X\times X,\mu\times \mu).$ If $C=AB$, then we can write $$Cu(x)=\iint K_A(x,z)K_B(z,y) u(y)\, d\mu(y)d\mu(z),$$ so we get the trace as $$\text{Tr}\ C=\iint  K_A(x,z)K_B(z,y) \, d\mu(y)d\mu(z).$$ The integral kernel of $C$ is given by $$K_C(x,y)=\int K_A (x,z)K_B(z,y)\, d\mu(z).$$ So, we might want the trace to be $$\text{Tr}\ C=\int K_C(x,x)\, d\mu(x).$$ The problem is that the diagonal might have measure zero, so this is a bit of a technical point. Essentially, we can define $K_C(x,x)$ by restriction a.e., and for nice spaces (those commonly looked at), we can get from the first expression of the trace to the second by continuity.
One more thing related to Hilbert-Schmidt operators. Earlier, I mentioned something that is sometimes referred to as the Hilbert-Schmidt kernel theorem. There is a similar result for distributions which is utilized constantly in microlocal analysis and the study of pseduodifferential operators, called the Schwartz kernel theorem:

Let $A:\mathcal{S}\rightarrow\mathcal{S}'$ be a continuous linear map. Then, there exists $K_A\in\mathcal{S}'(\mathbb{R}^n\times\mathbb{R}^n)$ so that for all $u,v\in\mathcal{S},$ $$\langle Au,v\rangle=\langle K_A, v\otimes u\rangle,$$ where $(v\otimes u)(x,y)=v(x)u(y)\in \mathcal{S}(\mathbb{R}^n\times\mathbb{R}^n).$

We sometimes abuse notation and write this as $Au(x)=\int K_A(x,y) u(y)\, dy,$ so that $$\langle Au,v\rangle=\iint K_A(x,y) v(x)u(y)\, dydx.$$ Seriously, this is used all the time in a very formal way. It, essentially, justifies a lot of work where people decide to only analyze the kernel.
References-
Yaiza Canzani: Analysis on Manifolds via the Laplacian http://canzani.web.unc.edu/files/2016/08/Laplacian.pdf
Michael Taylor: Partial Differential Equations I
Maciej Zworski: Semiclassical Analysis


My first module: db_select question

Question: I'm working on my first module, in this module I want to show a pager to two similar nodes. (Yes I know there are modules for this but it's more complex then the above but I kept it simple to make my question more clear). I'm completely new to making modules and the way de db_select works so I need some help with keeping my code clean and simple.
I have three tables I need information from.

Table 1: node
Table 2: field_data_field_issue (referenced node)
Table 3: field_data_field_order (order of nodes field)

First I need to get the current node id. For this I use the following code:
if (arg(0) == 'node' && is_numeric(arg(1))) {
  // Get the nid
  $nid = arg(1);
}

Now I need to find the nid of the node the current node refers to. I have to do this in Table 2. So I use this query:
$subquery = db_select('field_data_field_issue', 'i');
 ->fields('i', array('field_ref_nid'))
 ->condition('entity_id', $nid)
 ->execute();
 return $subquery;

Third I need to find all nodes that have the same referenced node and order them by nid and order. So I'm going for a query with join:
$query = db_select('node', 'n');
$query->join("field_data_field_issue", "i", "n.nid = i.entity_id");
$query->join("field_data_field_order", "o", "n.nid = o.entity_id");
->fields('n', array('nid', 'title'))
->fields('o', array('field_order_value'))
->fields('i', array('field_issue_value'))
->condition('field_issue_value', $resultsubquery) //I don't know how to get the result in here?
->orderBy('nid') //First order by nid
->orderBy('field_order_value') //Then order by order
->execute();
return $query;

This is what I have till now. Things I didn't figure out yet and where I could use some help with are.

How to get the result of $subquery in $query.
Is this the way to do it? Is this clean enough and am I missing out
on something?
I need the two nodes next to the current node. So if the ordering is
(nid): 3,2,4,5,1,6,8,9 and I'm currently at node 1 I want to output
node 5 and 6.

Thanks in advance!
Answer: $header = array(
        array('data' => 'title',        'field' => 'title', 'sort' => 'ASC'),
        array('data' => 'cal name 1',   'field' => 'field_order_value'),
        array('data' => 'Cal name 2',   'field' => 'field_issue_value'),
    );

// $result = db_query("SQL here");

$rpt_data = array();

    foreach ($results as $key => $rpt_data1){
        $rpt_data[$key][] = 'Result item';
        $rpt_data[$key][] = $rpt_data1->product_title;
        $rpt_data[$key][] = $rpt_data1->stock_value;
    }

    if (count($rpt_data) == 0) {
        $output = t('
Record not found.
');
    } else {
        $per_page = 20; // Initialize the pager
        $current_page = pager_default_initialize(count($rpt_data), $per_page);  // Split your list into page sized chunks
        $chunks = array_chunk($rpt_data, $per_page, TRUE);  // Show the appropriate items from the list
        $output = theme('table', array('header' => $header, 'rows' => $chunks[$current_page])); // Show the pager
        $output.= theme('pager', array('quantity',count($rpt_data)));
    }

Comment: Welcome to Drupal Answers! Answers with just code are not welcome here. The code is also wrong in some parts.
Comment: Thanks, but can you please explain this a little, I don't understand what is happing en how this works for me?

My first module: db_select question


Godaddy - How do I set a catchall CNAME?

Question: I have Ape installed in /APE_Server. I'm configuring APE and the tutorial says:

Create a subdomain pointing to the server where APE is installed.
Create a Catch-All CNAME redirecting all requests from *.ape.yourdomain.com to ape.yourdomain.com

So basically I must create a subdomain that points to the root and a wildcard DNS?
I can do the first. For the second, I click ADD RECORD, select CNAME and it says:
Enter an Alias Name:
Points to Host Name:

I tried to enter simply: *.ape and ape but it doesn't work. How do I do it?
Comment: I could point `*.ape` to `188.8.131.52` with type A record but I don't know if that is what I am supposed to do to get APE working. Anyone knows if this is equivalent to point 2 of the tutorial?
Answer: An earlier question asked whether a wildcard CNAME record was a good idea or not.  Answer mentioned that GoDaddy didn't support it even though it is technically fine.
I had the same issue. You can achieve what you need using an A record with * in the host field, and your server's IP address in the Points to Field. You can also set the host field of an A record to *.somesubdomain, if you only want wild-card subdomains of yet another subdomain.
Answer: Try a '@' and/or try an Arecord.
Comment: I could do A from `*.ape` to `22.214.171.124` but I don't know if that is what I am supposed to do to get APE working. I don't know the difference between A and CNAME either. Will doing this work the same as doing what is asked by the tutorial?
Comment: A CNAME is a reference to an Arecord. Using an Arecord instead of a Cname is preferred, since when looking up a Cname the initial request returns the target Arecord, then a second request returns the Arecord.
Answer: point *.ape to ape (CNAME)
and
ape to 188.8.131.52 (A record)
Comment: that's what I did but the system doesn't consider *.ape valid


How to control Block revisions before being published?

Question: Does Drupal support blocks versioning? Are there any modules can be used for controlling blocks revisions and publish selected version?
For example: a newly created blocks shall be published after being reviewed by a reviewer role user. So that the content will not be displayed in the page until it is published, meanwhile the content can be edited and sent for review and publish many times between the creator and reviewer.
Any suggestions about how to achieve this?
Comment: Any feedback about my answer below?
Answer: I would use the Bean module for this. Here is a quote about its project page:

Think of a Bean as a method to provide new types (compared to node this would be a content type) which then provides an add content interface to create as many blocks as you require (see screenshot below). The bean content can then be placed around the site just like any other block.

The Bean module also works great in combination with the UUID and UUID Features Integration modules. On top of that, after you become familiar with the Bean module, you might find other cases in your site where you also want to use the Bean module.
Moreover, by using Beans (i.e. entities), you qualify also for considering the Content Publishing System module (CPS for short) ... from commonly known "merlinofchaos". Here is an excerpt from that project page:

... CPS is a radical way of handling revisions for entities. It takes total control over revision management for all supported entities. For CPS-enabled entities, the revision tab is completely replaced and users are not allowed to manually create or move around revisions.

The video tutorial Drupal Bean module tutorial - using Bean Admin UI provides a great introduction to really understand the power of this module, and the kind of things you can do with it (by only using site building techniques, no custom coding involved). It also shows how the Bean module transforms Drupal blocks into fieldable entities.
A few more interesting issues related to all this:

bean workflow (published-deploy, unpublished-nodeploy)
Bean revision workflow support?


Sturm-Liouville Variational Problem

Question: I'm entirely clueless with this problem. No formal training in variational methods.
Show that for function $\phi\left ( x \right )$ with
$$\phi\left ( a \right )=\phi\left ( b \right )=0$$
and with the further constraint
$$I = \int_{a}^{b}r\left ( x \right )\left ( \phi'\left ( x \right ) \right )^{2}
dx=1 $$
that the functional
$$J\left ( \phi\left ( x \right ) \right )=\int_{a}^{b}\left [ p\left ( x \right )\left ( \phi'\left ( x \right ) \right )^{2}-q\left ( x \right )\left ( \phi^{2}\left ( x \right ) \right ) \right ]dx$$
is rendered stationary by the solution $y\left ( x, \lambda \right )$ of the Sturm-Liouville system
$$\left ( p\left ( x \right )y'\left ( x \right ) \right )'+\left ( q\left ( x \right ) +\lambda r\left ( x \right )y\left ( x \right ) \right )=0$$
in $a< x< b$ with $y\left ( a \right )=y\left ( b \right )=0$.
and that the minimum value of J is given by $\lambda_{1}$, the smallest eigen value of the Sturm-Liouville system
This popped up in a past year paper so I'm expecting something like this to spring up on the exam paper.
Help is appreciated
Answer: I am afraid your exam is long past, but maybe somebody else is interested. Your
functional $I$ should have $\phi$ not $\phi'$ in it. The functional is stationary at $y$ (more or less by definition) if there is a Lagrange multiplier $\lambda$ such that the derivative of
$$
F(s)=J(y+s\theta)-\lambda I(y+s\theta)
$$
at $s=0$ vanishes for all smooth functions $\theta$ vanishing at $a$ and $b$.
Since $F$ is a quadratic polynomial (for each $\theta$) it is easy to differentiate, and one obtains the condition
$$
\int_a^b(py'\theta'-(q+\lambda r)y\theta)=0.
$$
Now integrate by parts to move the derivative on $\theta$ to the other factor and you are done!

Sturm-Liouville Variational Problem


Rewrite as asynchronous + Rewrite without arrow functions

Question: I'm learning code for Web Development and currently am working with JavaScript and Node.js -
I need to
(A.) Rewrite the code without using any arrow functions and
(B.) Rewrite the code using an async/await function.
fetch("https://www.googleapis.com/books/v1/volumes?q=isbn:0747532699")
.then(res => res.json())
.then((result) => {
      items= result.items;
      console.log(items);
    }),
  (error) => {
   console.log(error);
  }

Any and all help will be appreciated, I have tried to find help but I just can't make sense of it.
Comment: Beyond this, how would I write the code to display only the title and description of the book returned?
Answer: You mean like so? Please let me know if this is what you want and if you need more information
async function getBooks() {
  try {
    const fetchResponse = await fetch("https://www.googleapis.com/books/v1/volumes?q=isbn:0747532699");
    const result = fetchResponse.json();
    const books = result.items;
    console.log(books);
  } catch(error) {
    console.log(error);
  }
}

// await getBooks();

Comment: Thank you for your help! This perfectly answers question B and is simple enough for me to follow. Do you have any good resources on arrow functions for question A?
Answer: First, to read arrow functions, you have to understand there are two ways to return value in arrow functions:
const func = x => x * x;  // concise body syntax, implied "return"
const func = (x, y) => { return x + y; };  // with block body, explicit "return" needed

Now, the following will go through the steps to convert code using a promise chain into code using async/await. By completing task B (replace promise chain with async/await), you will complete task A (code without arrow functions)
If a method returns a Promise, like fetch and Body.json() do, you can await its result:
const res = await fetch("https://www.googleapis.com/books/v1/volumes?q=isbn:0747532699");
const result = await res.json();
items = result.items;
console.log(items);

To handle error without chaining .catch, you wrap the code with try/catch block:
try {
  const res = await fetch(
    "https://www.googleapis.com/books/v1/volumes?q=isbn:0747532699"
  );
  const result = await res.json();
  items = result.items;
  console.log(items);
} catch (error) {
  console.log(error);
}

Lastly, await keyword can only be used inside an async function docs, that's why you have to wrap it into a function declared with async:
async function run() {
  try {
    const res = await fetch(
      "https://www.googleapis.com/books/v1/volumes?q=isbn:0747532699"
    );
    const result = await res.json();
    items = result.items;
    console.log(items);
  } catch (error) {
    console.log(error);
  }
}
run();

You should also know that any function declared with async keyword also returns a Promise which you can await.
Comment: Thanks for explaining it step by step, this helped me to better understand. Unfortunately, A and B must be done separately. Perhaps you could point me to a resource where I can learn more about arrow functions?
Comment: Sure. This [MDN docs](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions) may be helpful, especially the "Shorter functions" part. And @Pablo Darde's answer is pretty much what I would write.
Answer: A)
fetch("https://www.googleapis.com/books/v1/volumes?q=isbn:0747532699")
.then(function(res) { return res.json() })
.then(function(result) {
      const items= result.items;
      console.log(items);
    })
  .catch(function(error) {
   console.log(error);
  })

B)
async function getItems() {
  let results;
  try {
    const response = await fetch("https://www.googleapis.com/books/v1/volumes?q=isbn:0747532699")
    results = await response.json()
  } catch (e) {
    return new Error('error......')
  }

  return results.items
}
const items = await getItems()
console.log(items)

Comment: Thank you for providing your answer as A) and B)
A) works perfectly, but B) holds issue as the identifier 'items' has already been declared. This is something I now understand I should have included in my original question's code. I'm not sure how to make it work with this information.
Comment: Hi @jeMcFadzean, this is not possible. "items" is only defined once in B. If your code has already defined a variable called "items", try to change the variable name. Change the "items" variable name to "resultItems" in B, for example.


Commerce 2: Can Cash and Check payments be implemented?

Question: My client's business and website is primarily online purchases. However, there are instances when special customers or referrals come into their office and buy the product by cash or check.
My client wants those purchases to be recorded in the same database as online orders, along with the same captured contact information.
Is there a way to implement the checkout process so that certain employees with designated privileges can enter orders through the online store, but no request for payment information is required.  Or for those and only those privileged people an additional cash / check option is shown? (And the check option may also ask for additional info, such as the bank name and check number.)
Answer: You can do this by adding an additional payment gateway.

Add a role, Pay with Cash or whatever you want to call it.
Add a new payment gateway (at <code>/admin/commerce/config/payment-gateways/add</code>).

Name: Cash or Check
Plugin: Manual
Customer: Limit by Role: Pay with Cash role

The "Manual" gateway does not ask for any payment information, so orders with the manual payment selected (which only users with the Pay with Cash role will be able to select) will automatically be processed as completed when this payment method is selected.
If you want to record bank info for checks, you can make two separate gateways, one cash and one checks, and then customize the check gateway with additional fields.
Comment: Indeed. You can read more about where it was added to core for the RC1 release in the blog post: https://drupalcommerce.org/blog/113132/see-whats-new-drupal-commerce-20-rc1
Comment: Thank you Patrick and Ryan. I only have one "problem" with this.

The employee who sits at the front desk and who will process the walk-in orders is the one that has a userid/password defined and is assigned to that special role.

So any orders will be "credited" to their email address, instead of being able to capture the email address of the customer.

In addition, once the payment information (name, address) is filled in for that customer, it is assigned to the employee and will always be used.  How to allow separate name/address for each customer? (cont)
Comment: (cont) Obviously I don't want the front desk person to create new userids for each customer and assign them permanent "pay with cash" roles.

(Note: please re-read original comment above.  I hit "enter" before I was anywhere near ready to send it.  It has been edited/corrected to make more sense.)
Comment: @marrer Your original question was, "Can you give checks and cash by permission in Commerce 2?"  This is a fairly complex set of additional requirements.  Consider opening a new question.  (Hint: if you can't fit your comment into the amount of space the site provides, it's a new question, not a comment.)
Comment: I just experimented on a test site and it appears that in manual mode each new order asks for the customer's name and address. So it is not saved against the logged in user's account.  So that's a good thing. (Hopefully it will do the same on the live site.)

So it appears that figuring out how change the recorded email address would indeed be a separate question as you indicated.

Thank you again for your assistance, Patrick!


Order array of hashes by name but keep names with same id together

Question: I have the following array of hashes:
  [{:name=>"Albert", :id=>"1"},
  {:name=>"Billy", :id=>"3"},
  {:name=>"Carol", :id=>"4"},
  {:name=>"Dennis", :id=>"2"},
  {:name=>"Ellen", :id=>"1"},
  {:name=>"Frank", :id=>"5"},
  {:name=>"Gerald", :id=>"3"}]

I need to sort and have the result be:
  [{:name=>"Albert", :id=>"1"},
  {:name=>"Ellen", :id=>"1"},
  {:name=>"Billy", :id=>"3"},
  {:name=>"Gerald", :id=>"3"}
  {:name=>"Carol", :id=>"4"},
  {:name=>"Dennis", :id=>"2"},
  {:name=>"Frank", :id=>"5"}]

So sort names but group ids together also sorting by name.
I have tried looking at the sort_by method but I don't think it will work in this situation? Any help in the right direction would be appreciated.
Comment: Can you please elaborate on the algorithm how you created the result – especially why `Dennis` is the second last entry although its `id` is smaller than the one from `Gerald`?
Comment: The result is from a similar DB query which is ordered by the `name` column. So the result will always be ordered by name. I made a mistake when creating the sample result. I have updated the description.
Answer: You should group by id and then sort by the first's hash name value.
input.group_by { |h| h[:id] }.
      values.
      sort_by { |a| a.first[:name] }.
      flatten
#⇒ [{:name=>"Albert", :id=>"1"},
#   {:name=>"Ellen", :id=>"1"},
#   {:name=>"Billy", :id=>"3"},
#   {:name=>"Gerald", :id=>"3"},
#   {:name=>"Carol", :id=>"4"},
#   {:name=>"Dennis", :id=>"2"},
#   {:name=>"Frank", :id=>"5"}]


What factors contributed to Sochi 2014 being over-budget?

Question: The budget for the 2014 Winter Olympics in Sochi, Russia was originally $12 billion USD.
However, due to "various factors," the amount spent is believed to be around $51 billion USD, which is the highest spent for an Olympics ever, previously held by Beijing in 2008 with $44 billion USD(1).
What factors contributed to Sochi 2014 being over-budget?
Answer: As you mentioned in your question, Sochi 2014 is the most expensive games in Olympic history, surpassing Beijing 2008.  This is even more incredible when you realize that the Summer Games has three times more events than the Winter Games, which means that Russia has spent almost 4 times more per event than China did in 2008.
When Russia was bidding for the Olympics, President Putin gave a speech to the International Olympic Committee promising to turn Sochi into a world-class resort.  His original number of $12 Billion was much more than the other finalist nations were offering to spend.  Now, however, as the games are about to begin, the total spent by Russia is being reported as $51 Billion.
Joshua Yaffa has written a fascinating article for Bloomberg Businessweek that outlines some of the reasons for the out-of-control costs in Sochi.
Among the reasons that he discusses:

Engineering problems:  Sochi is in a narrow region between the Black Sea and the Caucasus Mountains.  There isn't a lot of room for large arenas and venues.  The best place to locate the Olympic venues is the Imereti Valley, an area that is prone to flooding.  The area constructed around Olympic Park has had to be built and rebuilt a few times due to flooding and inadequate engineering.  Also, in constructing the new railway between the Olympic Park and the Mountain venues, major tunneling was required.
Needed infrastructure: The Imereti Valley had very little infrastructure to begin with, and Russia has had to build roads, railroads, and utilities from scratch.
Corruption: The first two reasons are practical reasons for excessive costs, but the majority of the article gives example after example of corruption, both by government officials and by contractors.  According to the author, this is a very significant reason for the out-of-control spending.
Comment: +1 Great point in the first paragraph. Not to focus on the political side of things, but it sounds like Putin wanted to use the Olympics to make Sochi into a world-class resort.


how to use a generic list for inherited classes?

Question: I am stuck with a design and could use some advise if it is even possible in c# what I want.
To explain, I will put some code here
First, my base classes
public class TableBase
{
}

public class TableRepositoryBase
{
    public virtual void ReadFromDB(List<TableBase> list)
    {
    }
}

from here I want to inherit classed to use along with database tables,
for example user would look like this
public class TableUser : TableBase
{
    public int UserID { get; set; }
    public string FirstNane { get; set; }
    public string LastName { get; set; }
}

public class TableRepositoryUser : TableRepositoryBase
{
    public override void ReadFromDB(List<TableBase> list)
    {
        //base.ReadFromDB(list);

        // write code here to populate the list from the database
        for (int i = 0; i < 10; i++)
        {
            list.Add(new TableUser() { UserID = i, FirstNane = i.ToString(), LastName = i.ToString() });
        }
    }
}

Now I want to use this in a simple test project, so I create a new windows form project, drop a datagridview on it, and then I setup a new datasource like this

So, now I can bind this to the datagridview, no problems there. I can also add the columns in designtime. This all seems ok.
Also, the designer created a BindingSource for me, called tableUserBindingSource
Now I would like to populate the list with values, using the method ReadFromDB
So I try this code
TableRepositoryUser tableRepositoryUser = new TableRepositoryUser();

List<TableUser> list = (List<TableUser>)tableUserBindingSource.List;
tableRepositoryUser.ReadFromDB(list);

But the last line does not compiles, the error is

Severity  Code    Description Project File    Line    Suppression State
Error CS1503  Argument 1: cannot convert from
'System.Collections.Generic.List<ObjectListTest.TableUser>' to
'System.Collections.Generic.List<ObjectListTest.TableBase>'   ObjectListTest  C:\Users\source\repos\ObjectListTest\ObjectListTest\Form1.cs    65  Active

And this seems clear to me, the class expects a list of TableBase and not of TableUser.
But, TableUser is derived from TableBase so should this not work like this ?
Do I need some generic list or something to get this working ?
If so, an example on how to use a generic list like this (derived classes) would be nice.
I have been looking at examples of generic list for some time but I just cannot find how to use them for this case.
I also found this which suggests that what I want is not possible. But this question is many years old, maybe by know there is some alternative way of doing what I want ?
Comment: @OlivierRogier That is a lot to read, give me some time to analyze these links
Comment: Can you create the list in the method? `public override List ReadFromDB( )`  Seems odd that you would want a list passed in to modify anyways.  Then you can return `newList.OfType().ToList()`
Answer: Try to use these instead:
public interface ITableRepository<TEntity> where TEntity : TableBase
{
    public List<TEntity> ReadFromDb();
}

public class TableRepositoryUser : ITableRepository<TableUser>
{
    public List<TableUser> ReadFromDb()
    {
        var list = new List<TableUser>();

        for (int i = 0; i < 10; i++)
        {
            list.Add(new TableUser() { UserID = i, FirstNane = i.ToString(), LastName = i.ToString() });
        }

        return list;
    }
}

And then invoke it like this:
var list = tableRepositoryUser.ReadFromDb();

And yeah, you need to make your own class to bound data to the UI.
Comment: Also, you may experiment and use other types to return (e.g. IEnumerable or IAsyncEnumerable or IList).
Answer: I would consider having the list as a return type vs modifying an input object.
public override List<TableBase> ReadFromDB()
{
    List<TableUser> users = new List<TableUser>();

    // write code here to populate the list from the database
    for (int i = 0; i < 10; i++)
    {
        users.Add(new TableUser() { UserID = i, FirstNane = i.ToString(), LastName = i.ToString() });
    }
    return users.OfType<TableBase>().ToList();
}


Fractional polynomials vs GAMs

Question: I have been analyzing panel data for a while now using different methods (Generalized Linear Models, fractional polynomials and GAMs).
If we just ignore GMMs for now, I have come to find that Fractional polynomials are more intuitive than GAMs as they fit higher order polynomials which are easier and more intuitive for most readers to interpret/understand than splines. In addition, it is easier to compute the first and second derivative function to identify periods of significant change and Maximum or Minimum values of the polynomial function. Finally, I think that it is more likely you won't end up overfitting the data.
Would you agree with this? What are just briefly the advantages of one over the other one in your opinion?
Answer: In my mind they are equally intuitive.  What matters, whether using nonparametric smoothers, fractional polynomials, or splines, is that the quality of fit per degree of freedom spent is good on the average.  Note that fractional polynomials have a few disadvantages: $X$ must be $>0$ and if you shift $X$ by adding a constant the form of the fractional polynomial needed for a good fit can change substantially.

Fractional polynomials vs GAMs


Cronjob in cPanel

Question: I'd like to schedule a cronjob on my server to backup the entire public_html directory daily. I am logged into cPanel and I am on the Cron Job page where I have it set to run this command everyday at 2am: tar -vcf /site_backup.tar /public_html/
Is this command sufficient for what I want to do? I want to store the contents of public_html in the site_backup.tar that resides in the root directory (one level up from public_html). Do I need to provide anything else in the command for it to run correctly?
Answer: That command would serve its purpose but is there any reason you aren't using any compression like gzip or bzip? Also since this is in a cron I see no real reason to have the -v flag, no need to see the output.
Just add a -z to your command flags for gzip.
So  your final command would be:
tar -zcf /site_backup.tar.gz /public_html/

Answer: tar cvfz site_backup.tar.gz /path/to/your/user/public_html/ should be enough here, however it's better if you backup this using the cpanel functionality and do it to a remote ftp server.
Additionally you can use something like www.backupsetc.com to backup you cpanel account, using it is pretty straight-forward(you just have to specify your server and accounts to be backed up).

Cronjob in cPanel


Sum of a certain series related to the primes

Question: It is well known that $$\sum_{n > 0}\frac{1}{n}$$ diverges, but $$\sum_{n > 0}\frac{1}{n^2} = \frac{\pi^2}{6}$$ converges.
Similarly, $$\sum_{p}\frac{1}{p}$$ diverges, but $$\sum_{p} \frac{1}{p^2}$$ clearly converges. Is any simple closed form known for this sum, like the one for $\zeta(2)$?
Answer: There is the Prime Zeta Function for this:
$$P(2) = 0.4522474220041065...$$
In fact (according to the link),
$$P(2)=\sum_{k=1}^{\infty}{\mu(k)\over k}\log(\zeta(2k))=0.4522474200\dots$$
where $\mu(k)$ is the Mobius Function. In general,
$$P(s)=\sum_{k=1}^{\infty}{\mu(k)\over k}\log(\zeta(ks))$$


Checking for either/or with an EnumSet

Question: So I'm converting some bitfields in our application to use EnumSet instead, and I'm curious if there's a better way to do a comparison for X|Y. Currently we do something like:
if(bitfield & (X | Y) != 0) {
    //do stuff
}

The EnumSet equivalent seems to be:
if(enumSet.contains(X) || enumSet.contains(Y)) {
    //do stuff
}

Is there a cleaner way to do this? I know you can check for containsAll() like so:
EnumSet flagsToCheck = EnumSet.of(X, Y);
if(enumSet.containsAll(flagsToCheck)) {
    //do stuff
}

But that's for a scenario where you want to know if (X & Y) is set. Is there an equivalent way to check for (X | Y)? I would think there would be something like a containsAny() method, but I don't see anything that seems to have that effect.
Answer: I would say the existing approach is more readable than your bitwise approach. It says exactly what you mean: if the set contains X, or the set contains Y... Keep it as it is. It's already clean.
If the set becomes larger, you could use:
EnumSet<Foo> valid = EnumSet.of(Foo.X, Foo.Y, Foo.A, Foo.B);
valid.retainAll(enumSet);
if (valid.isEmpty()) {
    ...
}

But I'd only keep that for larger cases. For two or three options I'd use the longhand form.
Comment: @kcoppock: I prefer "verbose" over "clever" any day, when it's actually quicker to read. With bitmasking operations I'd probably have to double-check it every time - whereas with the simple "X or Y" the code reads really naturally.
Comment: You possibly want the opposite (`!valid.retainAll(enumSet)`) to avoid changing the original set.
Comment: I was about to comment as to @assylias's point. You're probably right that it's more readable as individuals for small sets, just seems sort of verbose.
Comment: @assylias is right. An option to that is to just create a new set based on the enum values you want and change/verify accordingly.
Answer: You can use the AbstractSet method removeAll (true if any of the elements was found). Obviously, probably you want to do that with a clone of the original set.
Comment: assylias comment of doing the opposite (removeAll of the original set from the set of values you are looking for) also applies here.
Comment: True, that's a good way to check as well. I just wanted to avoid an unnecessary copy.
Answer: If you can't update the set, just create a new one... @assylias is right. An option to that is to just create a new set based on the enum values you want and change/verify accordingly.
public enum ResultingState {
    NOT_PERSISTED, PERSISTED, NOT_CALCULATED, CALCULATED;
}
EnumSet<ResultingState> errorsState = EnumSet.of(ResultingState.NOT_PERSISTED, ResultingState.NOT_CALCULATED);
Collection<ResultingState> results = new HashSet<>(phaseResults.values());
boolean containsAny = results.retainAll(errorsState) && results.size() > 0;

Checking for either/or with an EnumSet


Theme inner field collection field(s)

Question: I'm looking for a way to theme the inner fields of field collection. Does anyone know, how to do that?
Currently the template output is like this:

        ... the field collection ...

but as you can see, there are now two ids with the same name
Comment: You shouldnt have duplicate ids...
Comment: Sorry @Alex ... I meant, the output is like "this", not my template. The template get's reparsed in itself.
Answer: What you're experiencing is a bug. It happens quite often with contributed code, since it usually moves faster than it is tested. But don't worry, being contributed also means there are lots of people using, and probably someone else will bump into the same issue as you are experiencing.
When you face an issue that looks like a bug, you should ask yourself whether you've configured everything properly. Check first, but if there's nothing obviously wrong, give the issue queue a visit. Every module, theme or profile has an issue queue where people report bugs, suggest features and ask for support.
Search the issue queue and you may find a patch to your issue. If there is no report of your bug, file a new issue and provide a step-by-step guide to reproduce the error. That means you will have to try installing and configuring the module again on a fresh Drupal install. When the module mantainer sees the bug report, the steps to reproduce will make it a lot easier to debug and provide you with a fresh patch.
Mantaining modules/themes are usually voluntary work, and if you don't provide the steps to reproduce nor reply to mantainer questions, your issue will probably be postponed. Get involved with the community, it pays off.
Comment: BTW, your issue has already been fixed: http://drupal.org/node/1658208 I just wanted to take the time and educate you on what to do when faced with contributed code bugs.
Comment: Also, to make finding and referencing this question and answer, try changing your question to "A contributed module is misbehaving, what should I do?" Or something like that ;)

Theme inner field collection field(s)


Uma trigger pode "anular/desfazer" a ação que a dispara?

Question: Cenário exemplo
Tenho uma tabela telefones onde tenho uma trigger que é disparada ao realizar a instrução insert.

Dúvida

Posso usar a trigger para verificar uma condição e diante do retorno, "cancelar" a ação na tabela que a disparou?
Teria como definir a mensagem de "atenção/erro" que o SQL irá retornar?

(Um exemplo seria extremamente importante)
Comment: Sim e Sim mas note que isso é uma má prática por vários motivos. A boa prática é colocar as regras de negócio na camada de regras de negócio e lá decidir se a ação deve ou não ser realizada e dar o devido feedback ao usuário
Comment: @jean Concordo com você, a trigger praticamente sempre será um "remendo". Mas nos casos de sistemas de terceiros que não há possibilidade de alteração no fonte, a trigger acaba salvando! rs
Comment: @JoséDiz tem alguma sugestão?
Answer: Pela descrição que você deu o ideal seria utilizar uma trigger do tipo instead of:
ALTER TRIGGER tr_tabela ON tabela
INSTEAD OF INSERT AS
BEGIN
    SET NOCOUNT ON;

    IF -- Sua condição para o erro aqui
    BEGIN
        RAISERROR('Mensagem de erro.', 16, 1);
    END
    ELSE -- Insere
    BEGIN
        INSERT tabela
        SELECT i.*
          FROM inserted i;
    END;
END;
GO

No caso do exemplo não executável acima a inserção somente será realizada na tabela caso a condição do IF não seja satisfeita.

INSTEAD OF
Especifica que o gatilho DML será executado em vez da instrução SQL de gatilho, substituindo as ações das instruções de gatilho. INSTEAD OF não pode ser especificado para gatilhos DDL ou de logon.
No máximo, um gatilho INSTEAD OF por instrução INSERT, UPDATE ou DELETE pode ser definido em uma tabela ou exibição. Entretanto, você pode definir exibições sobre exibições, onde cada uma tem seu próprio gatilho INSTEAD OF.
Os gatilhos INSTEAD OF não são permitidos em exibições atualizáveis que usam WITH CHECK OPTION. O SQL Server gera um erro quando um gatilho INSTEAD OF é adicionado a uma WITH CHECK OPTION de exibição atualizável especificado. O usuário deve remover essa opção usando ALTER VIEW antes de definir o gatilho INSTEAD OF.
Comment: @rbz No caso que você descreveu acredito que a única forma. Em um cenário onde você pudesse fazer a chamada por uma `procedure` acredito que seria o ideal.
Comment: Muito bom Sorack! Mas essa frase sua me confundiu e me deixou um pouco de dúvida "Pela descrição que você deu o ideal seria utilizar uma trigger do tipo instead of". Então só para extinguir qualquer dúvida mínima: o `instead of` seria o "ideal" ou seria a única forma?


média da população por cidade de cada estado

Question: Boa tarde, aqui estou empacado em mais questão de um trabalho, precisa fazer uma consulta onde ela retorne a média da população por cidade de cada estado, consegui até executar algumas pesquisas mas todas deram números absurdamente grandes que vou mostrar a abaixo.
SELECT e.nome,  AVG(m.populacao) pop
    FROM municipio m
    INNER JOIN estado e
    ON e.codestado = m.codestado
    GROUP BY e.nome
    ORDER BY pop ASC

Comment: Municipio já tem a população agregada ?
Comment: Neste casos faça aberta para um estado e confira.
Comment: Desculpe, mas vc não deveria pedir para que outras pessoas façam o seu trabalho por vc. Tente se esforçar para fazê-lo. Se é uma questão, foram passadas as instruções para permitir que vc o faça.
Comment: @Motta , a tabela de municipio se relaciona com a de estado por meio do CODESTADO, e a tabela regiao se relaciona com estado por meio de CODREGIAO. Eu imagino que tenha que fazer a soma da população dos estados e depois fazer a media, já tentei várias maneiras mas nenhuma delas pareceu dar o resultado certo. Se puder dizer qual comando devo usar pra fazer, comecei a estudar BD agora, então meu conhecimento é só o básico
Comment: Não estou pedindo pra fazer por mim BTW, tinha umas 18  questões nesse trabalho, respondi todas as outras sozinho, como o colega está dizendo que estou pedindo pra fazer por mim.
Comment: Sua sql me parece correta , tentou fazer um caso de um estado ? Pegue um pequeno , Sergipe ou Acre e faça um analitico para testar.
Comment: SELECT e.nome, m.nome , m.populacao pop
    FROM municipio m
    INNER JOIN estado e
    ON e.codestado = m.codestado andve.codestado = 'AC'
Comment: @Motta tava vendo aqui que o resultado pode estar certo mas tem muitas casas decimais, e eu  não tinha visto isso, por isso estava achando que estava errado,mas observando agora pode estar certo, por exemplo o do amazonas está dando '51966.774193548387'
Comment: @Motta realmente acho que estava certo, usei ROUND para arredondar para duas casas decimais e aparentemente estava certo
Answer: Sua query está correta, sua metodologia de teste é que está errada:

consegui até executar algumas pesquisas mas todas deram números
  absurdamente grandes

O que é grande? O que é pequeno? Qual era o valor esperado de retorno?
O fato é que sem uma referência não há como determinar se a sua consulta está certa ou errada.
Como você não especificou a estrutura das tabelas estado e municipio, vou me basear na sua query e assumir que sua estrutura de tabelas seja algo como:
CREATE TABLE estado
(
  codestado INTEGER PRIMARY KEY,
  uf CHARACTER VARYING(2),
  nome TEXT
);

CREATE TABLE municipio
(
  codmunicipio INTEGER PRIMARY KEY,
  codestado INTEGER REFERENCES estado (codestado),
  nome TEXT,
  populacao INTEGER
);

Agora, vamos inserir alguns dados nas tabelas criadas:
INSERT INTO estado (codestado, uf, nome) VALUES
( 1, 'PI', 'Piauí' ),
( 2, 'MA', 'Maranhão' ),
( 3, 'CE', 'Ceará' );

INSERT INTO municipio ( codmunicipio, codestado, nome, populacao ) VALUES
( 1, 1, 'Teresina', 864845 ),
( 2, 1, 'Parnaíba', 153078 ),
( 3, 1, 'Picos', 78222 ),
( 4, 2, 'São Luís', 1101884 ),
( 5, 2, 'Imperatriz', 258682 ),
( 6, 2, 'São José de Ribamar', 177687 ),
( 7, 3, 'Fortaleza', 2669342 ),
( 8, 3, 'Caucaia', 362400 ),
( 9, 3, 'Juazeiro do Norte', 274207 );

Primeiramente, vamos fazer uma simples consulta na tabela de municipios para se determinar qual o valor da média da população por cidade de um determinado estado da federação que devemos esperar em nossos testes, dividir para conquistar, vamos lá:
--- Média populacional apenas das cidades do estado do Piauí
SELECT AVG(populacao) FROM municipio WHERE codestado = 1;

Saída:
|               avg |
|-------------------|
| 365381.6666666667 |

Não sei se esse valor é grande ou pequeno, mas ele é uma boa referência para verificar se queries mais complexas estão funcionando como o esperado.
Agora vamos ao monstro:
SELECT
  e.codestado,
  e.nome,
  AVG(m.populacao) pop
FROM
   estado e
INNER JOIN
  municipio m ON (e.codestado = m.codestado)
GROUP BY
  e.codestado
ORDER BY
  pop ASC;

Saída:
| codestado | uf |     nome |               pop |
|-----------|----|----------|-------------------|
|         1 | PI |    Piauí | 365381.6666666667 |
|         2 | MA | Maranhão |            512751 |
|         3 | CE |    Ceará |           1101983 |

Repare que valor da média populacional esperado para o estado do Piauí corresponde ao valor esperado, demonstrando que seu INNER JOIN e seu GROUP BY estão funcionando corretamente.
Veja tudo isso rodando no SQL Fiddle
Comment: Eu só faria o analitico listando as cidades do estado e calculando a média.


Replace Unnamed values in date column with true values

Question: I'm working on this raw data frame that needs some cleaning. So far, I have transformed this xlsx file

into this pandas dataframe:
print(df.head(16))

                   date technician alkalinity colour     uv    ph turbidity  \
0   2020-02-01 00:00:00  Catherine       24.5     33   0.15  7.24      1.53
1            Unnamed: 2        NaN        NaN    NaN    NaN   NaN      2.31
2            Unnamed: 3        NaN        NaN    NaN    NaN   NaN      2.08
3            Unnamed: 4        NaN        NaN    NaN    NaN   NaN       2.2
4            Unnamed: 5     Michel         24     35  0.152  7.22      1.59
5            Unnamed: 6        NaN        NaN    NaN    NaN   NaN      1.66
6            Unnamed: 7        NaN        NaN    NaN    NaN   NaN      1.71
7            Unnamed: 8        NaN        NaN    NaN    NaN   NaN      1.53
8   2020-02-02 00:00:00  Catherine         24    NaN  0.145  7.21      1.44
9           Unnamed: 10        NaN        NaN    NaN    NaN   NaN      1.97
10          Unnamed: 11        NaN        NaN    NaN    NaN   NaN      1.91
11          Unnamed: 12        NaN        NaN   33.0    NaN   NaN      2.07
12          Unnamed: 13     Michel         24     34   0.15  7.24      1.76
13          Unnamed: 14        NaN        NaN    NaN    NaN   NaN      1.84
14          Unnamed: 15        NaN        NaN    NaN    NaN   NaN      1.72
15          Unnamed: 16        NaN        NaN    NaN    NaN   NaN      1.85

   temperature
0            3
1          NaN
2          NaN
3          NaN
4            3
5          NaN
6          NaN
7          NaN
8            3
9          NaN
10         NaN
11         NaN
12           3
13         NaN
14         NaN
15         NaN

From here, I want to combine the rows so that I only have one row for each date. The values for each row will be the mean in the respective columns. ie.
print(new_df.head(2))

          date      time  alkalinity  colour     uv    ph  turbidity  temperature
0   2020-02-01  00:00:00       24.25      34  0.151  7.23       1.83            3
1   2020-02-02  00:00:00          24    33.5  0.148  7.23       1.82            3

How can I accomplish this when I have Unnamed values in my date column? Thanks!
Comment: I would suggest pandas [groupby](https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.groupby.html) functionality, however, if those unnamed values are of no use then can they be filtered out?
Comment: I need to use those values so I can calculate the mean. If you take a look at the xlsx file above, the date spans over 8 columns.
Comment: Okay so then you will have to know which unnamed belongs to which date and after data transformation do the **groupby**
Comment: Yes, which is what I've been asking. How do I replace the `Unnamed` values in the date column with the true date?
Comment: Okay, I have posted a solution that can be referred to or the other answer that is given.
Answer: Try setting the values to NaN and then use ffill:
df.loc[df.date.str.contains('Unnamed', na=False), 'date'] = np.nan

df.date = df.date.ffill()

Comment: `ValueError: Cannot mask with non-boolean array containing NA / NaN values`
Comment: Try setting `na=False`. Updated answer.
Answer: If I understand, correctly you want to drop rows that contain 'Unnamed' in the date column, right?
Please look here:
https://stackoverflow.com/a/27360130/12790501
The solution would be something like this:
df = df.drop(df['Unnamed' in df.date].index)

Edit:

No, I would like to replace those Unnamed values with the date so I
could then use the groupby('date') function to return the mean values
for the columns

so in the case you should just iterate over the whole table
last_date = ''
for i in df.index:
    if 'Unnamed' not in df.at[i, 'date']:
        last_date = df.at[i, 'date']
    else:
        df.at[i, 'date'] = last_date

Comment: No, I would like to replace those `Unnamed` values with the date so I could then use the `groupby('date')` function to return the mean values for the columns
Comment: Ok, I have updated the answer
Comment: `TypeError: argument of type 'datetime.datetime' is not iterable`
Answer: If the 'date' column is of type object i.e. string
then just write a logic to loop over the number as seen in image provided it follows a certain pattern-
for _ in range(2,9):
    df.loc[(df['date'] == 'Unnamed: '+str(_), 'date'] = your_value


How to split a paragraph into two or more paragraphs in PHP?

Question: I have a string $text:
$text = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam in dui mauris. Vivamus hendrerit arcu sed erat molestie vehicula. Sed auctor neque eu tellus rhoncus ut eleifend nibh porttitor. Ut in nulla enim. Phasellus molestie magna non est bibendum non venenatis nisl tempor. Suspendisse dictum feugiat nisl ut dapibus. Mauris iaculis porttitor posuere. Praesent id metus massa, ut blandit odio. Proin quis tortor orci. Etiam at risus et justo dignissim congue. Donec congue lacinia dui, a porttitor lectus condimentum laoreet.Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam in dui mauris. Vivamus hendrerit arcu sed erat molestie vehicula. Sed auctor neque eu tellus rhoncus ut eleifend nibh porttitor. Ut in nulla enim. Phasellus molestie magna non est bibendum non venenatis nisl tempor. Suspendisse dictum feugiat nisl ut dapibus. Mauris iaculis porttitor posuere. Praesent id metus massa, ut blandit odio. Proin quis tortor orci. Etiam at risus et justo dignissim congue. Donec congue lacinia dui, a porttitor lectus condimentum laoreet.';

Now I want to convert this string into multiple paragraphs.I have tried word-wrap
echo wordwrap($text,100,"
",true);but It splits the string after every 100 character and is giving an odd look as it does not take care of full stops or words.
the new paragraph is often not organized.
Is there a way to split the paragraphs fairly well in two or more well-formatted paragraphs.
I Hope I have made the description clear.
Comment: drop the last parameter or set it to false. Refer to the docs in case of doubts http://php.net/manual/de/function.wordwrap.php
Answer: You can use regular expression to split the string after every X amount of words. This for instance, would split your $text after every 50 words and add them to paragraphs:
preg_replace( '~((?:\S*?\s){50})~', "
$1
", $text );

Comment: Hey thanks I tried this one It is generating a little problem
Comment: It is breaking the sentence too. for eg  Mauris

iaculis porttitor posuere. Praesent id metus massa, ut blandit odio.  Now it is a single sentence but the word "Mauris" remains in the first paragraph and other moves to the next paragraph.. Have I made you clear about my problem?
Comment: Then the regular expression needs to be changed to look for every nth occurance of a punctuation for example. Lets say that you want a paragraph after five occurances of ".". I dont have time to cook that one up just now, but Ill come back a bit later when I have lunch.
Answer: It's nice to look at the docs. :)
<?php
$text = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam in dui mauris. Vivamus hendrerit arcu sed erat molestie vehicula. Sed auctor neque eu tellus rhoncus ut eleifend nibh porttitor. Ut in nulla enim. Phasellus molestie magna non est bibendum non venenatis nisl tempor. Suspendisse dictum feugiat nisl ut dapibus. Mauris iaculis porttitor posuere. Praesent id metus massa, ut blandit odio. Proin quis tortor orci. Etiam at risus et justo dignissim congue. Donec congue lacinia dui, a porttitor lectus condimentum laoreet.Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam in dui mauris. Vivamus hendrerit arcu sed erat molestie vehicula. Sed auctor neque eu tellus rhoncus ut eleifend nibh porttitor. Ut in nulla enim. Phasellus molestie magna non est bibendum non venenatis nisl tempor. Suspendisse dictum feugiat nisl ut dapibus. Mauris iaculis porttitor posuere. Praesent id metus massa, ut blandit odio. Proin quis tortor orci. Etiam at risus et justo dignissim congue. Donec congue lacinia dui, a porttitor lectus condimentum laoreet.';
echo wordwrap($text,100,"
");

Output
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam in dui mauris. Vivamus hendrerit
arcu sed erat molestie vehicula. Sed auctor neque eu tellus rhoncus ut eleifend nibh porttitor. Ut
in nulla enim. Phasellus molestie magna non est bibendum non venenatis nisl tempor. Suspendisse
dictum feugiat nisl ut dapibus. Mauris iaculis porttitor posuere. Praesent id metus massa, ut
blandit odio. Proin quis tortor orci. Etiam at risus et justo dignissim congue. Donec congue lacinia
dui, a porttitor lectus condimentum laoreet.Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Nullam in dui mauris. Vivamus hendrerit arcu sed erat molestie vehicula. Sed auctor neque eu tellus
rhoncus ut eleifend nibh porttitor. Ut in nulla enim. Phasellus molestie magna non est bibendum non
venenatis nisl tempor. Suspendisse dictum feugiat nisl ut dapibus. Mauris iaculis porttitor posuere.
Praesent id metus massa, ut blandit odio. Proin quis tortor orci. Etiam at risus et justo dignissim
congue. Donec congue lacinia dui, a porttitor lectus condimentum laoreet.

Comment: Thanks @Surjit . I want to split the paragraph fairly.Actually this is my first question on stackoverflow. I think i have not made the problem clear. I will just add an image to make it clear


Editing a Package Dependency as a Local Package

Question: Overview

I have a project that uses a remote swift package.
I would like to edit this package in the same project so that I can refine it based on the usage.

Aim:

To do this I am trying to add the same package as a local package so that I can edit it.

Reference:
https://developer.apple.com/documentation/swift_packages/editing_a_package_dependency_as_a_local_package
Problem:

When I drag and drop the cloned folder containing Package.swift into the project, I can't see any of the local package source files in the project. (see screenshot)

I have been breaking my head over it. Any help on this would be much appreciated.
Xcode Version:

13.2 (13C90) (downloaded from the developer portal not the AppStore)
Comment: Have you got the package open in another Xcode window?
Comment: Wow!!! Spot on, could you please post that as an answer, would be helpful to others
Answer: The reason you cannot see the content of the package is that you have it open in another Xcode instance.
You can only edit a package in one Xcode instance at a time.
I find closing down Xcode completely, then opening up the particular project that I want to edit the package in solves the problem.
Comment: Amazing!!, thanks a ton was breaking my head over it. I remember now that a similar thing happens even with frameworks as well


R: calculate area under a density curve until a cutoff value

Question: I have the following problem.
The following code
library(tidyverse)

set.seed(1234)
df1 <- data.frame(x = rnorm(1000), group = "a")
df2 <- data.frame(x = rnorm(1000, mean = -1), group = "b")
df <- bind_rows(df1, df2)

df %>%
  ggplot(aes(x = x, fill = group)) +
  geom_density(alpha = 0.5) +
  geom_vline(aes(xintercept = quantile(x[group=="a"], probs = 0.05, names = FALSE)), color = "firebrick") +
  theme_light()

produces this plot:

The red line is the 0.05 quantile of the curve A. So if I understand it correctly, the red line separates the A in 5% of the area is left and 95% of the area is right of the vertical line.
My question is: Given the 0.05 quantile of A, how much of B is left and right of the red vertical line? How can I calculate these numbers?
I hope it is clear what I am trying to achieve. Thank you for your help!
Answer: Create an empirical cumulative distribution function:
q <- quantile(df[df$group=="a", "x"], probs = 0.05)
ecdf(df[df$group=="b", "x"])(q)
#[1] 0.255