Getting the right average rate of growth

Question: I am trying to get the average rate of growth across a series of numbers that will lead to the same sum as the discrete rates of growth.
For example, if I have 1 unit at $t=1$ that grows at 2%, then 3%, then 2% again the resulting sum of units would be
$$1+1\cdot(1.02)+1\cdot(1.02)\cdot(1.03)+1\cdot(1.02)\cdot(1.03)\cdot(1.02)=4.142212$$
Unless I'm making a calculative error, I've found that the arithmetic, geometric, and harmonic averages all lead to an incorrect sum when scaled linearly over the same 4 periods. Is there a method to find the correct average growth rate that will give the same sum?
First time question asker, please forgive the potentially convoluted question. Welcome any tips on better question formatting.
Comment: Appreciate the feedback, Gerry. The problem becomes quite obvious when laid out like that. Solved your specified cubic function using Newton approximation and it yielded a root at 1.0233333, which yields the correct sum when used as a growth rate.
Comment: You want $1+x+x^2+x^3=4.142212$, so it's time for you to learn how to solve cubic equations.
Comment: How are the cubics coming along?
Comment: Please engage with the comments and with the answer that was posted.
Comment: Maybe you could write that up and post it as an answer.
Answer: Let's introduce some notation to describe your question. Suppose we perform $N$ measurements of a time-dependent quantity $x(t)$. Denote the observed value of $x$ at time $t_i$ as $x_i=x(t_i)$ for $i \in \{1,2,...,N\}$. Then define $r_{i+1}=\frac{x_{i+1}}{x_i}$ as the fractional increase of $x$ between times $t_i$ and $t_{i+1}$ for $i \in \{1,2,...,N-1\}$. Moreover, it is convenient to assign $r_1=1$. It follows by iterative application of this definition that $x_i=x_1 \prod_{j=1}^{i} r_j$, for all $i \in \{1,2,...,N\}$. The (unweighted) average of $x$ across the $N$ measurements is $$\bar{x}=\frac{1}{N} \sum_{i=1}^{N} x_i=\frac{x_1}{N} \sum_{i=1}^{N} \prod_{j=1}^{i} r_j\tag{1}.$$ The metric you are considering for the average fractional change is then $$\bar{r}=\frac{\bar{x}}{x_1}=\frac{1}{N} \sum_{i=1}^{N} \prod_{j=1}^{i} r_j \tag{2}.$$ For computational purposes, it is useful to note that $\sum_{i=1}^{N} \prod_{j=1}^{i} r_j =r_1\left(1+r_2\left(1+...r_{N-1}\left(1+r_N\right)\right)\right)$. In terms of your example, we would have that $N=4$, $x_1 = 1$, and $\vec{r}=(1,1.02,1.03,1.02)$. Then we would calculate $\bar{r}=1+r_2(1+r_3(1+r_4))=1.035553$ and $\bar{x}=\bar{r}x_1=1.035553$. It should hopefully be clear from $(2)$ why $\bar{r}$ is not simply the arithmetic, geometric, or harmonic mean of the components of $\vec{r}$.
In fact, I would argue that $\bar{r}$ as defined in $(2)$ should not be understood as an average of the components of $\vec{r}$. The prototypical property of an averaging function $\bar{s}:S^N \to S$ for $N$ elements of a set $S$ is that for all $s \in S$, we have that $\bar{s}(s,s,...,s)=s$. In the case that $S=(0,\infty)$ and $r_i=r \in S$ for all $i \in \{1,2,...N\}$, $$\bar{r}=\frac{1}{N} \sum_{i=1}^{N} \prod_{j=1}^{i} r = \frac{1}{N} \sum_{i=1}^{N} r^i = \frac{r}{N} \lim\limits_{r' \to r} \frac{1-r'^N}{1-r'},$$
where we have used the standard formula for a finite geometric series (the limit being needed for when $r=1$ or $N=1$). For all $r \neq 1$ and $N\geq 2$, it is then apparent that $\bar{r} = \frac{r}{N}\frac{1-r^N}{1-r} \neq r$, and even more alarming, $\lim\limits_{r \to \infty} \frac{\bar{r}}{r} = \frac{1}{N} \lim\limits_{r \to \infty} \frac{1-r^N}{1-r}=\infty$.
I would instead think of $\bar{r}$ as the fractional change between the first measurement of $x$ and the sample mean $\bar{x}$ as it is defined in $(2)$. I am afraid we do not have reason to extend its meaning beyond this.
Comment: Thank you for providing this very useful framework to think about the problem more generically. I was able to find the solution!


How to discard unsaved changes to a variant?

Question: While working on a variant for /node/%node I did something that now causes a 'The requested page "/admin/structure/pages/edit/node_view" could not be found.' error and am unable to access any of the variants.
How do I discard all the changes since the last save?
Answer: Finally got the answer from a Drupal guru- just deleted an entry from the ctools_object_cache table in the database. Everything works fine now.


Constructing a measure versus using an interaction

Question: My dataset is sports data and the outcome variable is wins in a season and I am trying to see the affect of the characteristics of the players on the team on this outcome. My question is, is it easier to use interactions or construct a measure?
I want to know if players attending a top 25 college affects wins when other teamate characteristics are considered. I have 3 possible structures, G1: at least one captain (of the two) went a top 25 and some other or no other players on the team did, G2: no captain attended a top 25 and other players on the team did, and G3: no one on the team attended a top 25 college. I am really interested in comparing G2 to G3 given my outcome.
Is it best to create 3 variables G1, G2, and G3 and then run my regression with either G2 or G3 as the reference group and see the effect of the coefficient or to crate a dummy for the captains and then the non-captains and then create interactions? I want the most accurate approach, but I am not sure how to setup these interactions or if they will be too confusing to compare to a reference group.
Answer: As described in the original post, your independent variables are mutually exclusive: a given team cannot meet more than one of your 3 structures. Thus, there cannot be an interaction term. You will likely be best served with dummy variables for the three structures modeling one as the reference, as you suggest.
If you wanted to evaluate the effect of top 25 schools and the captain/non-captain identity, consider separate variables for captains and other team members and the count of top 25 school attendance of each. With these variables in hand, you could evaluate for interactions between captains and other players (these are not mutually exclusive) or examine for the presence of non-linear effects of top 25 school attendance for either/both.
Answer: If you want to compare your three groups, just run your regression over them.
If you want to study specifically:

The effect of top25 captain(s) [0 or more]
The effect of top25 teammate(s) [0 or more]
The interaction between these two groups

You should study the complete design. In this case you will need a fourth group (no captains, no teammates from top25). The interaction could be hard to observe with small sample or small differences.
Comment: I only care about the groups, but I wanted to make sure that I was not confounding something/doing it incorrectly by creating measures versus finding some complicated interactions
Comment: There is nothing wrong here about studying the three groups. It's constrained only by the _question_ you want to ask and the meaning of the answer related to the target domain (here sport).


restric view row by the URL in block

Question: I have a view block disply that contains a list of nodes.
i want to restrict Nid's by my url in one field in node.(Similarly, system block visibility)
for example i have a field with name field_visibility and save node by fill that gallery
so, my list in block is:

view-row-1 => [nid]-1 => field_visibility ='gallery' view-row-2 =>
  [nid]-2 => field_visibility ='contact' view-row-3 => [nid]-3 =>
  field_visibility ='blog' . . .

so in page www.example.com/gallery, in block should be
1. [nid]-2
2. [nid]-3

and in page www.example.com/contact, in block should be
1. [nid]-1
2. [nid]-3

Comment: Have you tried to play a bit with contextual filters? Can I assume you tried to set contextual filter to "content: field visibility" and it somehow failed?
Comment: sorry, i use drupal 6-x and tried arguments but whit out success
Comment: Add both that informations to your question, then :) And I'm afraid I'm not able to help with 6, sorry.
Answer: No need to use field_visibility
try this if using Views 3

Click on the "advanced" tab.
Click on add under "contextual filters".
Choose Content:nid.
Under "when the filter variable is not available, choose "provide default value".
From the drop down menu select "content id from url".
Scroll all the way down to the bottom of the window and click on the "More" link.
Click "Exclude"
Comment: sorry, i use drupal 6-x and not see this options
Comment: then use arguments filter

restric view row by the URL in block


Detecting existence of Touch Listeners

Question: I want to find out if some items (Buttons, EditText etc) has Touch Listeners - and only if there aren't so I want to add my own Listeners (I get the items from another class).
Is there a way to detect that?
Answer: Thanks to Niko i was able to do what i want.
On api >= 15 , i used reflection (using Niko example) to get the field: mListenerInfo, then i used reflection again to get the field mOnTouchListener. now if it's null it means there is no touch listener, otherwise it has.
this is a code example (without try catch):
Field field_mListenerInfo = null;
Object originalListener = null;
Object myListenerInfo = null;
Field field_mOnTouchListener = null;

View viewForField = new View(activity); //needed just to get field name
field_mListenerInfo = viewForField.getClass().getDeclaredField("mListenerInfo");
field_mListenerInfo.setAccessible(true);
originalListener = field_mOnTouchListener.get(myListenerInfo );
myListenerInfo = field_mListenerInfo.get(view);
field_mOnTouchListener = myListenerInfo.getClass().getDeclaredField("mOnTouchListener");
field_mOnTouchListener.setAccessible(true);

now if originalListener is null it means there is no touchListner. else, you can actually use this Listener - for example to concat few listeners.
If there are no Listeners at all so  mListenerInfo will be null.
of course you should pack this code with try catch, otherwise it will break if any of your fields is null.
Answer: You can get private field of View called mOnTouchListener
Here is how you use reflection: Access to private inherited fields via reflection in Java
Comment: Here you can see classes for different API levels http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/4.4_r1/android/view/View.java/ In the latest SDK there seems to be method getListenerInfo() which has this private field mOnTouchListener. For multi API level support you will have to use different approaches to access the field.
Comment: Thanks for the Quick respond! It sounds like a great idea but i can't find this field mOnTouchListener you are talking about. All i see is some field called mListenerInfo but i can't understand what to do with it
Comment: thanks! i still got a lot of work to do but now i'm on the right direction!
Answer: Personally, I think that checking the documentation would be your best bet.
Comment: I did. couldn't find anything useful
Answer: After a while of searching for solutions for this problem myself, I've found a solution that works.
I hope the attached code helps:
private static View.OnTouchListener getOnTouchListener(View view) {
        View.OnTouchListener retrievedListener = null;
        String viewStr = "android.view.View";
        String lInfoStr = "android.view.View$ListenerInfo";
        try {

            Field listenerField = Class.forName(viewStr).getDeclaredField("mListenerInfo");
            Object listenerInfo = null;

            if (listenerField != null) {
                listenerField.setAccessible(true);
                listenerInfo = listenerField.get(view);
            }

            Field clickListenerField = Class.forName(lInfoStr).getDeclaredField("mOnTouchListener");

            if (clickListenerField != null && listenerInfo != null) {
                clickListenerField.setAccessible(true);
                retrievedListener = (View.OnTouchListener) clickListenerField.get(listenerInfo);
            }
        } catch (NoSuchFieldException ex) {
            Timber.e("getOnTouchListener() No Such Field. %s",ex.getMessage());
        } catch (IllegalAccessException ex) {
            Timber.e("getOnTouchListener() Illegal Access. %s",ex.getMessage());
        } catch (ClassNotFoundException ex) {
            Timber.e("getOnTouchListener() Class Not Found. %s",ex.getMessage());
        }

        return retrievedListener;
    }

Detecting existence of Touch Listeners


Por que não entra no loop das notas?

Question: Estou armazenando nome e notas de alunos e tentando exibir o nome, as notas e a média. O problema é que o programa está pulando o loop das notas e só está pegando o nome.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

/*
Síntese
Objetivo: Calcular a média das notas de um aluno
Entrada: Nome, Nota 1, nota 2, nota 3, e nota 4
Saída: Nome, notas do aluno e média
*/

#define MAX_NOME 100
#define MAX_NOTAS 4
#define VETOR_MAX 50
typedef struct Alunos{
    char nome[MAX_NOME];
    int notas[MAX_NOTAS];
}Aluno;

int leValidaOpcao();
int main(int argc, char *argv[]) {
    int cont=0, cont2=0, qtdAlunos=0, soma;
    char continuar = ' ';
    float media=0.0;

    Aluno * aluno1 = malloc(qtdAlunos * sizeof(Aluno));

    do{
        printf("Informe o %d%c nome :", cont+1, 167);
        scanf(" %[^\n]s", (aluno1+cont)->nome);

        for(cont2; cont2 < MAX_NOTAS;cont2++){
            printf("Informe a nota %d:", cont2+1);
            scanf("%d", &(aluno1+cont)->notas[cont2]);
            soma += (aluno1+cont)-> notas[cont2];
            system("cls");
        }

        printf("Nome = %s\n", (aluno1+cont)->nome);
        for(cont2; cont2 < MAX_NOTAS; cont2++){
            printf("Nota[%d] =  %d\n", cont2+1, (aluno1+cont)->notas[cont2]);
        }
        printf("\nMedia = %f", soma/MAX_NOTAS);

        continuar = leValidaOpcao();
        cont++;
    }while(continuar == 's' && cont < VETOR_MAX);

    free(aluno1);
    return 0;
}
int leValidaOpcao(){
    char opcao = ' ';
    int flag = 1;

    do{
        printf("Deseja continuar (S - sim ou Nao - N)");
        scanf(" %c", &opcao);
        opcao = tolower(opcao);

        if(opcao != 's' && opcao != 'n'){
            printf("\nOpcao invalida!\n");
            flag = 0;
        }
    }while(!flag);
    return opcao;
}

Comment: no `for` é preciso colocar `cont2=0`, basta fazer um mini debug para descobrir essa falha
Comment: Verdade, Fábio. Só que tá aparecendo lixo.
Comment: Descobri o erro. É na formatação dos dados.
Comment: Achei que havia descoberto, mas me enganei. Continua dando problema.
Answer: O problema é utilizar a mesma variável cont2 nos dois loops.
    for(cont2; cont2 < MAX_NOTAS;cont2++){
        printf("Informe a nota %d:", cont2+1);
        scanf("%d", &(aluno1+cont)->notas[cont2]);
        soma += (aluno1+cont)-> notas[cont2];
        system("cls");
    }

    printf("Nome = %s\n", (aluno1+cont)->nome);

    for(cont2; cont2 < MAX_NOTAS; cont2++){
        printf("Nota[%d] =  %d\n", cont2+1, (aluno1+cont)->notas[cont2]);
    }
    printf("\nMedia = %f", soma/MAX_NOTAS);

Por você inicializar não atribuir o valor 0 à variável após o primeiro loop, ela vai começar o segundo loop com o valor final do primeiro loop, ou seja, MAX_NOTAS - 1.
Para resolver esse problema, você pode utilizar variáveis diferentes em cada loop ou inicializar a variável cont2 novamente, por exemplo:
for(cont2; cont2 < MAX_NOTAS;cont2++){
    printf("Informe a nota %d:", cont2+1);
    scanf("%d", &(aluno1+cont)->notas[cont2]);
    soma += (aluno1+cont)-> notas[cont2];
    system("cls");
}

printf("Nome = %s\n", (aluno1+cont)->nome);

cont2 = 0;

for(cont2; cont2 < MAX_NOTAS; cont2++){
    printf("Nota[%d] =  %d\n", cont2+1, (aluno1+cont)->notas[cont2]);
}
printf("\nMedia = %f", soma/MAX_NOTAS);

Comment: Valeu, Marcelo. Eu consegui. Tinha outros erros também , mas já foram corrigidos.
Comment: De nada! Observei também que o cálculo da média não estava funcionando, não sei se você ja corrigiu esse erro também.
Comment: Mais simples e intuitivo seria fazer a atribuição a `0` dentro do `for` que é basicamente o propósito do primeiro bloco do `for`

Por que não entra no loop das notas?


Best Site Spider?

Question: I am moving a bunch of sites to a new server, and to ensure i don't miss anything, want to be able to give a program a list of sites and for it to download every page/image on there. Is there any software that can do this? I may also use it to download a copy of some wordpress sites, so i can just upload static files (some of my WP sites never get updated, so hardly worth setting up new dbs etc)
Comment: belongs on superuser.com
Comment: Are you not able to connect to the site via FTP and download the files that way? If you could do that, it'd be much easier, and you wouldn't have to worry about files being missed because nothing was currently linking to them.
Answer: You'll probably get lots of opinions.  Here is one: http://www.httrack.com/
Answer: wget is your tool.
on unix/linux systems, it may already be installed. for windows systems, download it from http://gnuwin32.sourceforge.net/packages/wget.htm.
it is a command line tool, with a bunch of command line options for controlling the way it crawls the target website. use "wget --help" to list all available options.

Best Site Spider?


Viola and Cello diamond notehead notation interpretation

Question: I'm attempting to transcribe (for playback) Dukas' L'Apprenti Sorcier into Musescore.
I don't understand what the following notation means, how it should be played, or possibly be approximated, should Musescore not be able to directly play the parts as written.
I thought it might be some sort of tremolo, as the note values for the diamond notes don't fit into 9/8ths, and then there's that extra stemless A-flat above.
I was working on the score uploaded in 2007, but see that a recent, much more legible score was uploaded recently to IMSLP, so I've used that image for clarity; it appears to be faithful to the original.
Any insight will be appreciated; I don't play these instruments myself.
Answer: These are harmonics. In this case, they're called artificial harmonics because they're not on open strings.
The player fingers the low (regular) note, and also places a finger at the point that would finger the diamond note but without pressing down. This results in a harmonic two octaves above the fingered note, which is indicated by the small black note head.
This is a little over-notated. The regular note head and the diamond note head are enough to specify what's going on. Alternatively, you can indicate the resulting pitch that you want and let the players figure out what harmonic to play to get it.
Comment: It's a wonderfully orchestrated piece, eh? Btw, he actually wrote it in 3/8 time. It was suggested he'd done it that way because he was being paid by the bar!
Comment: @NevinWilliams The sounding note would actually just be the high one two octaves up. The bottom two are what's fingered and the top is what comes out.
Comment: Might you have a suggestion as to what note(s) I'd have to play to approximate the intended passage?
Comment: Yeah. The two notes produced are as shown by the tiny black notes: the cello sounds the Ab in the second space of the treble stave, and the viola the Ab above (on one ledger line above the stave). To play the viola and cello parts just play the notes I described and sustain them through the 3 bars shown and beyond. The violins play the same two notes pizzicato (plucked) and with mutes (sourdines) fitted. At bar 3 they stop 'pizz'ing and switch to bows. The seconds divide in half: half of them playing the top line and half the lower. Or were you asking how to play the whole page?
Comment: Well, given that Musescore doesn't play that particular technique natively, what note(s) shall I use for those instruments?   Just the Ab?   Just to be clear.
Comment: Thanks for the help, folks!

I ended up using the A an octave above what was written, to match what I could hear in a recording of the symphony.
Answer: A side note:  the notation here (diamond a Fourth up) produces the 2-octave harmonic. You will also see other harmonic positions.  This table is copied from Dolmetsch online dictionary

position of little finger ------  pitch of 'flageolet tone' produced
  5th above stop    ----------one octaves + a 5th above the written note
  4th above stop    ---------two octaves above the written note
   maj 3rd    above stop  ------two octaves + a maj 3rd above the written note
  min    3rd above stop   -------two octaves + a 5th above the written note
Comment: I did end up using an octave above the A that was notated.


Event immediatelly as another item is selected in DataGridViewComboBoxCell

Question: I initialize cells from a list like this:
DataGridViewRow row = new DataGridViewRow();
List<string> itemNames = new List<string>(new string[]
{
    "ITEM 1",
    "ITEM 2",
    "ITEM 3",
    "Add new item..."
});
row.CreateCells(myDataGridView);
row.Cells[0].Value = "";
if(row.Cells[1] is DataGridViewComboBoxCell cell2)
{
    cell2.DataSource = itemNames;
}

In the real program, the list is loaded from somewhere and the "Add new item..." entry is added at the end. What I want is to show a form when "Add new item..." is selected in the combobox.
    protected void checkIfNewItemSelected(DataGridViewComboBoxCell combocell)
    {
        if (combocell.Value + "" == ADD_CONFIG_TEXT)
        {
            // do something to add new item (show a form)
        }
    }

However I cannot find any suitable event that would trigger immediatelly after user selects the value. For example I tried CellEndEdit and CurrentCellDirtyStateChanged on the datagrid. Both of these events trigger only after the combobox loses focus. Specifically the latter is recommended by MSDN:
    private void dataGridViewConfigs_CurrentCellDirtyStateChanged(object sender, EventArgs e)
    {
        DataGridViewCell cell = dataGridViewConfigs.CurrentCell;
        // handle trigger for new PRJ config request
        if (cell is DataGridViewComboBoxCell combocell)
        {
            checkIfNewItemSelected(combocell);
        }
    }

So if you select the "Add new item...", this is what you end up seeing:

Only after you click somewhere else, the events that I tried are triggered. I need to take action IMMEDIATELY after user clicks on this particular entry.
How to do that?
Answer: You could hook up to the events directly on the editing control, for example...
private const string NEW_ITEM_TEXT = "Add new item..";

private void Form1_Load(object sender, EventArgs e)
{
    var comboCol = new DataGridViewComboBoxColumn();
    comboCol.Items.AddRange("A", "B", NEW_ITEM_TEXT);
    dataGridView1.Columns.Add(comboCol);
    dataGridView1.EditingControlShowing += DataGridView1_EditingControlShowing;
}

private void DataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
    var comboBox = e.Control as ComboBox;
    if (comboBox == null) return;
    comboBox.SelectedIndexChanged -= ComboBox_SelectedIndexChanged;
    comboBox.SelectedIndexChanged += ComboBox_SelectedIndexChanged;
}

private void ComboBox_SelectedIndexChanged(object sender, EventArgs e)
{
    DataGridViewComboBoxEditingControl editor = sender as DataGridViewComboBoxEditingControl;
    if (editor.SelectedItem.ToString() != NEW_ITEM_TEXT) return;
    Form2 f2 = new Form2();
    f2.Show();
}

Comment: Is there a way to very that the combobox is really the one I want to check? Can I find for which column and row is the control showing?
Comment: Yes, in EditingControlShowing event handler you can check `dataGridView1.CurrentCell` and from there get the row/column.


Picking a picture either from photos or multimedia, but not by recent images

Question: I would like to pick picture similar to whatsapp:
Code:
   public void pickImage()
    {
        if (Build.VERSION.SDK_INT <19)
        {
            Intent pickPhoto = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

            Intent intent = new Intent();
            intent.setType("image/*");
            intent.setAction(Intent.ACTION_GET_CONTENT);
            startActivityForResult(Intent.createChooser(intent, "Select Picture"), SELECT_PICTURE);
        } else {
            Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
            intent.addCategory(Intent.CATEGORY_OPENABLE);
            intent.setType("image/*");
            startActivityForResult(intent, KITKAT_SELECT_PICTURE);

        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode != Activity.RESULT_OK) return;
        if (null == data) return;
        Uri originalUri = null;
        if (requestCode == SELECT_PICTURE)
        {
            originalUri = data.getData();
        }
        else if (requestCode == KITKAT_SELECT_PICTURE)
        {
            originalUri = data.getData();
            final int takeFlags = data.getFlags() & (Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            // Check for the freshest data.
            getContentResolver().takePersistableUriPermission(originalUri, takeFlags);
        }
    }

Question:
The above can pick pictures and then showing pic properly in an imageview. However, during the picking process, it messes up the pictures photoed by camera (called album) and pictures in other media, and is sorted by most recent images.
How could i make it similar to whatsapp, picking image from a folder containing only but all images taken from camera, or a folder containing all other multimedia, INSTEAD OF messing up camera photos and mutimedia pictures by most recently added?
Thank you.
Comment: you need to get recent path properly mostly it gives null..
Comment: I mean not to show the picking page in order of decending date, I would like it to be similar to whatsapp, in either by images from camera, or other images from mutimedia apart from camera?
Answer: Use MediaStore.Images.Media.query function with order by set DSC DATE_ADDED field. You can set content URI for internal/external storage based on your requirement.
Comment: i would like to separate the camera pictures from other multimedia pictures, instead of messing the camera photos and mulimedia images altogether sorting in descending order.
Answer: Try this hope so it will be helpful my problem was fix out with help of this code..
Uri selectedImageURI = data.getData();
imageFile = new File(getRealPathFromURI(selectedImageURI));

and:
private String getRealPathFromURI(Uri contentURI) {
    String result;
    Cursor cursor = getContentResolver().query(contentURI, null, null, null, null);
    if (cursor == null) { // Source is Dropbox or other similar local file path
        result = contentURI.getPath();
    } else {
        cursor.moveToFirst();
        int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
        result = cursor.getString(idx);
        cursor.close();
    }
    return result;
}

Comment: this will separate the camera pictures from other multimedia pictures?


How to remove  tags when printing out Menu

Question: Is there any way to remove HTML list tags when this function is called to access Main Menu?
This code is used in page.tpl.php in for a theme:
print theme(
  'links__system_main_menu',
  array(
    'links' => $main_menu,
    'attributes' => array('class' => array('topNavItem')),
  )
);

Answer: Sure, it's pretty easy. But first I think you need to know what's going on here.
Drupal's theme() call above is going to look for a theme_links__system_main_menu() function/hook and failing that, will look for a theme_links() function/hook.
theme_links() is in drupal core in includes/theme.inc if you want to take a look at it, as that's "who" is putting the ULs and LIs in there.  DONT just edit that file/function/hook, but create your own in your theme.  So, to take them out, or to put whatever you want in, you just write your own theme function to do it, and then theme() above will call it for you.
Drupal's theme layer is described well here:  http://api.drupal.org/api/drupal/includes--theme.inc/function/theme/7 and here: http://drupal.org/theme-guide/6-7 and should put you on the path to doing all that.


Show that $ E\Big[\sum_{i=1}^{n}(X_i - \bar{X_n})^2\Big] = (n-1)\sigma^2 $

Question:
$X_1, X_2, ..., X_n$ are i.i.d random variables with mean $\mu$ and variance $\sigma^2$. $\bar{X_n} = S_n/n$ where $S_n = X_1 + X_2 + ... + X_n$. Show that

$$ E\Big[\sum_{i=1}^{n}(X_i - \bar{X_n})^2\Big] = (n-1)\sigma^2 $$
Attempt:
$$ E\Big[\sum_{i=1}^{n}(X_i - X_n)^2\Big] = E\Big[\sum_{i=1}^{n}~X_i^2 - 2X_i\bar{X_n} + \bar{X_n}^2\Big] \tag{1} $$
$$ = \sum_{i=1}^{n}E\Big(X_i^2 - 2X_i\bar{X_n} + \bar{X_n}^2) \tag{2} $$
$$ = \sum_{i=1}^{n}\Big(E(X_i^2) - 2E(X_i\bar{X_n}) + E(\bar{X_n}^2)\Big) \tag{3} $$
I don't know how to proceed.
Comment: Duplicate of [Mean of $ \sum (X_i - \bar{X})^2$](https://math.stackexchange.com/questions/1701626/mean-of-sum-x-i-barx2).
Comment: The indices $i$ and parenthesis suddenly disappeared while simplifying. Take the sum first then take expectation. Plus you got (a-b)^2 wrong.
Comment: ok i added the indices even though they're all iid.. and i fixed the sign mistake.
Comment: @StubbornAtom would you mind showing me how to do the sum
Comment: see [here](https://math.stackexchange.com/questions/3459555/bessels-correction/3459637#3459637)
Comment: @StubbornAtom I had defined my $X$ above my attempt.
Comment: @VictorS. Okay I missed that.
Answer: Observe that
$$
(X_i-\mu)^2=(X_i-\bar{X})^2+(\bar{X}-\mu)^2+2(X_i-\bar{X})(\bar{X}-\mu)
$$
and moreover
$$
\sum_{i=1}^n (X_i-\bar{X})(\bar{X}-\mu)=(\bar{X}-\mu) \sum_{i=1}^n (X_i-\bar{X})=0
$$whence
$$
\sum_{i=1}^n(X_i-\mu)^2=\sum_{i=1}^n(X_i-\bar{X})^2+\sum_{i=1}^n(\bar{X}-\mu)^2.
$$
In particular
$$
\begin{align}
n\sigma^2=n\text{Var}(X_1)=E\left[\sum_{i=1}^n(X_i-\mu)^2\right]
&=
E\left[\sum_{i=1}^n(X_i-\bar{X})^2\right]+
E\left[\sum_{i=1}^n(\bar{X}-\mu)^2\right]\\
&=E\left[\sum_{i=1}^n(X_i-\bar{X})^2\right]+n\text{Var}(\bar{X})\\
&=E\left[\sum_{i=1}^n(X_i-\bar{X})^2\right]+\sigma^2
\end{align}
$$
from which the desired result follows.
Answer: $$E\Big[\sum_{i=1}^{n}(X_i - X_n)^2\Big]=\sum_{i=1}^{n}\Big(E(X_i^2) - 2E(X_i\bar{X_n}) + E(\bar{X_n}^2)\Big)$$
We have
$$E(X_i^2)=\sigma^2+\mu^2$$
$$E(X_i\bar{X_n})=\frac{1}{n}\sum_{k=1}^{n}{E(X_i X_k)}=E(X_i^2)+\frac{1}{n}\sum_{k=1, k \ne i}^{n}{E(X_i)E( X_k)}$$
because $X_i$'s are independent.
Thus,
$$E(X_i\bar{X_n})=\sigma^2+\mu^2+\frac{n-1}{n}\mu^2$$
Also,
$$E(\bar{X_n}^2)=\frac{1}{n^2}\sum_{i=1}^{n}\sum_{j=1}^{n}{E(X_iX_j)}=\frac{1}{n^2}\sum_{i=1}^{n}{E(X_i^2)}+{\frac{1}{n^2}\sum_{i=1}^{n}{\sum_{j=1, i\ne j}^{n}{E(X_i)E(X_j)}}}$$
Therefore,
$$E(\bar{X_n}^2)=\frac{n}{n^2}(\sigma^2+\mu^2)+\frac{n(n-1)}{n^2}\mu^2$$
Finally add them up, and you have the results wanted.


Image from sheet in imagebox control (VBA)

Question: I'm looking for a simple way to have an image loaded to the image control in a userform, vba project in excel.
Is it possible to load directly a pasted linked image from the sheet it self, and then have that object serving as source for the image control?
I found that it is possible to do so, but it takes exporting the image (or saving the image as image) and then load it to the image control, but I am looking for a way that does not involve external data from the excel file.
Thanks.
Comment: Take a look at my answer here.  http://stackoverflow.com/questions/32050403/have-jpg-files-within-excel-when-using-activex-image-control/32051569#32051569
Comment: Ok! I'll give it a go. Thanks!
Answer: Well, after searching with google, I found this solution:
For the example you will need:
+----------------+----------------+
| Control        | Name           |
+----------------+----------------+
| User Form      | UserForm1      |
| Image          | Image1         |
| Command Button | CommandButton1 |
+----------------+----------------+

And 2 normal modules, and I use this Names:
+---------------+
| Module Names  |
+---------------+
| Functions_VBA |
| Image_Job     |
+---------------+

Inside the UserForm1 use this code:
Option Explicit

Private Sub CommandButton1_Click()
    Paste_ThePicture 'I will explain later...
     Me.Image1.Picture = LoadPicture(thePath) 'Just this... load the picture
     'If you want to delete the picture from directory
     'Uncomment this:
     'Kill thePath
End Sub

Inside the Image_Job Module put this:
Option Explicit
Public thePath As String

Sub Paste_ThePicture() 'The procedure inside UserForm1
Dim fname As String
Dim objPicture As Variant

    With ActiveSheet.Shapes("Picture 1") 'The name of the picture inside the excel sheet
                                         'you can loop over the pictures or do somenthing
                                         'to take the picture you want
        .CopyPicture xlScreen, xlBitmap
        Set objPicture = PastePicture(xlBitmap) 'Store the picture inside the var
        fname = ThisWorkbook.Path & "\" & .Name & ".bmp" 'Create the path for the picture full path
    End With
    thePath = fname 'Store the full path to use it later
SavePicture objPicture, fname 'save the picture in the directory
                              'you can delete it later
                              'Look inside the userForm code
End Sub

And the magic come heres! Inside the Functions_VBA put this:
Option Explicit
Option Compare Text

''' User-Defined Types for API Calls
'Declare a UDT to store a GUID for the IPicture OLE Interface
Private Type GUID
    Data1 As Long
    Data2 As Integer
    Data3 As Integer
    Data4(0 To 7) As Byte
End Type
'Declare a UDT to store the bitmap information
Private Type uPicDesc
    Size As Long
    Type As Long
    hPic As Long
    hPal As Long
End Type

'''Windows API Function Declarations
'Does the clipboard contain a bitmap/metafile?

Private Declare Function IsClipboardFormatAvailable Lib "user32" (ByVal wFormat As Integer) As Long
'Open the clipboard to read
Private Declare Function OpenClipboard Lib "user32" (ByVal hwnd As Long) As Long
'Get a pointer to the bitmap/metafile
Private Declare Function GetClipboardData Lib "user32" (ByVal wFormat As Integer) As Long
'Close the clipboard
Private Declare Function CloseClipboard Lib "user32" () As Long
'Convert the handle into an OLE IPicture interface.
Private Declare Function OleCreatePictureIndirect Lib "olepro32.dll" (PicDesc As uPicDesc, RefIID As GUID, ByVal fPictureOwnsHandle As Long, IPic As IPicture) As Long
'Create our own copy of the metafile, so it doesn't get wiped out by subsequent clipboard updates.
Declare Function CopyEnhMetaFile Lib "gdi32" Alias "CopyEnhMetaFileA" (ByVal hemfSrc As Long, ByVal lpszFile As String) As Long
'Create our own copy of the bitmap, so it doesn't get wiped out by subsequent clipboard updates.
Declare Function CopyImage Lib "user32" (ByVal handle As Long, ByVal un1 As Long, ByVal n1 As Long, ByVal n2 As Long, ByVal un2 As Long) As Long
'The API format types we're interested in
Const CF_BITMAP = 2
Const CF_PALETTE = 9
Const CF_ENHMETAFILE = 14
Const IMAGE_BITMAP = 0
Const LR_COPYRETURNORG = &H4
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
''' Subroutine: PastePicture
'''
''' Purpose:    Get a Picture object showing whatever's on the clipboard.
'''
''' Arguments:  lXlPicType - The type of picture to create.  Can be one of:
'''                          xlPicture to create a metafile (default)
'''                          xlBitmap to create a bitmap
'''
''' Date        Developer           Action
''' --------------------------------------------------------------------------
''' 30 Oct 98   Stephen Bullen      Created
''' 15 Nov 98   Stephen Bullen      Updated to create our own copies of the clipboard images
'''

Function PastePicture(Optional lXlPicType As Long = xlPicture) As IPicture
'Some pointers
Dim h As Long, hPicAvail As Long, hPtr As Long, hPal As Long, lPicType As Long, hCopy As Long
'Convert the type of picture requested from the xl constant to the API constant
lPicType = IIf(lXlPicType = xlBitmap, CF_BITMAP, CF_ENHMETAFILE)
'Check if the clipboard contains the required format
hPicAvail = IsClipboardFormatAvailable(lPicType)
If hPicAvail <> 0 Then
    'Get access to the clipboard
    h = OpenClipboard(0&)
    If h > 0 Then
        'Get a handle to the image data
        hPtr = GetClipboardData(lPicType)
        'Create our own copy of the image on the clipboard, in the appropriate format.
        If lPicType = CF_BITMAP Then
            hCopy = CopyImage(hPtr, IMAGE_BITMAP, 0, 0, LR_COPYRETURNORG)
        Else
            hCopy = CopyEnhMetaFile(hPtr, vbNullString)
        End If
        'Release the clipboard to other programs
        h = CloseClipboard
        'If we got a handle to the image, convert it into a Picture object and return it
        If hPtr <> 0 Then Set PastePicture = CreatePicture(hCopy, 0, lPicType)
    End If
End If
End Function

''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
''' Subroutine: CreatePicture
'''
''' Purpose:    Converts a image (and palette) handle into a Picture object.
'''
'''             Requires a reference to the "OLE Automation" type library
'''
''' Arguments:  None
'''
''' Date        Developer           Action
''' --------------------------------------------------------------------------
''' 30 Oct 98  Stephen Bullen      Created
'''

Private Function CreatePicture(ByVal hPic As Long, ByVal hPal As Long, ByVal lPicType) As IPicture

' IPicture requires a reference to "OLE Automation"
Dim r As Long, uPicInfo As uPicDesc, IID_IDispatch As GUID, IPic As IPicture

'OLE Picture types
Const PICTYPE_BITMAP = 1
Const PICTYPE_ENHMETAFILE = 4
' Create the Interface GUID (for the IPicture interface)
With IID_IDispatch
    .Data1 = &H7BF80980
    .Data2 = &HBF32
    .Data3 = &H101A
    .Data4(0) = &H8B
    .Data4(1) = &HBB
    .Data4(2) = &H0
    .Data4(3) = &HAA
    .Data4(4) = &H0
    .Data4(5) = &H30
    .Data4(6) = &HC
    .Data4(7) = &HAB
End With
' Fill uPicInfo with necessary parts.
With uPicInfo
    .Size = Len(uPicInfo)                                                   ' Length of structure.
    .Type = IIf(lPicType = CF_BITMAP, PICTYPE_BITMAP, PICTYPE_ENHMETAFILE)  ' Type of Picture
    .hPic = hPic                                                            ' Handle to image.
    .hPal = IIf(lPicType = CF_BITMAP, hPal, 0)                              ' Handle to palette (if bitmap).
End With
' Create the Picture object.
r = OleCreatePictureIndirect(uPicInfo, IID_IDispatch, True, IPic)
' If an error occured, show the description
If r <> 0 Then Debug.Print "Create Picture: " & fnOLEError(r)
' Return the new Picture object.
Set CreatePicture = IPic
End Function
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
''' Subroutine: fnOLEError
'''
''' Purpose:    Gets the message text for standard OLE errors
'''
''' Arguments:  None
'''
''' Date        Developer           Action
''' --------------------------------------------------------------------------
''' 30 Oct 98   Stephen Bullen      Created
'''

Private Function fnOLEError(lErrNum As Long) As String
'OLECreatePictureIndirect return values
Const E_ABORT = &H80004004
Const E_ACCESSDENIED = &H80070005
Const E_FAIL = &H80004005
Const E_HANDLE = &H80070006
Const E_INVALIDARG = &H80070057
Const E_NOINTERFACE = &H80004002
Const E_NOTIMPL = &H80004001
Const E_OUTOFMEMORY = &H8007000E
Const E_POINTER = &H80004003
Const E_UNEXPECTED = &H8000FFFF
Const S_OK = &H0
Select Case lErrNum
Case E_ABORT
    fnOLEError = " Aborted"
Case E_ACCESSDENIED
    fnOLEError = " Access Denied"
Case E_FAIL
    fnOLEError = " General Failure"
Case E_HANDLE
    fnOLEError = " Bad/Missing Handle"
Case E_INVALIDARG
    fnOLEError = " Invalid Argument"
Case E_NOINTERFACE
    fnOLEError = " No Interface"
Case E_NOTIMPL
    fnOLEError = " Not Implemented"
Case E_OUTOFMEMORY
    fnOLEError = " Out of Memory"
Case E_POINTER
    fnOLEError = " Invalid Pointer"
Case E_UNEXPECTED
    fnOLEError = " Unknown Error"
Case S_OK
    fnOLEError = " Success!"
End Select
End Function

With all that, you will:
Open the UserForm1 and click the CommandButton1 this will take from the ActiveSheet the shape name "Picture 1" (it is your picture) and Save it in the same path of the Workbook, after that, take that path (the stored picture) and insert it into Image1.
If you want you can delete the picture from the path.
I try to take the picture directly from the clipboard, but I don not know if that is possible, if you can do it, please let me know how you did it, by now this is my help in your question.
Note: I take the magic code from here: Stephen Bullen
Comment: Well...thanks...that was no doubt an elaborate answer! I do believe that it would be through WIN API, but your example still requires external files (as having a temporary image file). In that sence, I have already seen examples that make Excel export an image with one line of code, saving the path, and using it in the .PICTURE property. I was thinking more in the lines of using BitBlt win api function, but am kinda lost on how to make it work. Nevertheless, thanks. I'll have a look at your answer to see what I can work with. Cheers!
Answer: With the code provided by Elbert Villarreal/Stephen Bullen (Functions_VBA/PastePicture), it is possible to paste the image directly from the clipboard (without saving it to disk):
Sub Paste_ThePicture()
    With ActiveSheet.Shapes("Picture 1")
        .CopyPicture xlScreen, xlBitmap
        UserForm1.Image1.Picture = PastePicture(xlBitmap)
    End With
End Sub


Explicit relation between dual and adjoint of a linear map

Question: Let $V$ and $W$ be finite-dimensional vector spaces over some arbitrary field $K$, and let $V^\ast$ and $W^\ast$ be their respective dual spaces. Let $f:V \rightarrow W$ be a linear map.
a) Define the dual of $f$ as the map $f^\ast : W^\ast \rightarrow V^\ast$, $e \mapsto e \circ f$.
b) Suppose we define two fixed non-degenerate bilinear forms $\langle \cdot,\cdot \rangle_V : V^2 \rightarrow K$, $\langle \cdot,\cdot \rangle_W : W^2 \rightarrow K$. Define the adjoint of $f$ as the map $\bar{f}: W \rightarrow V$ satisfying
$\langle v,\bar{f}(w) \rangle_V = \langle f(v),w \rangle_W$.
Since the bilinear forms are non-degenerate, the linear maps $\phi_V : V \rightarrow V^\ast$ and $\phi_W : W \rightarrow W^\ast$ given by
$$ \phi_V(v)(v_0) = \langle v,v_0 \rangle_V, \qquad \phi_W(w)(w_0) = \langle w,w_0 \rangle_W $$
are isomorphisms. Given this, how can we express $\bar{f}$ explicitly in terms of $f^\ast$ (and if required, $\phi_V$ and $\phi_W$)? Alternatively, how can we prove that the map $\bar{f}$ is guaranteed to exist?
EDIT: As pointed out by @levap I have fixed the definition of $\phi_W$.
Answer: For some reason, your definition of the map $\phi_W$ is mangled (the $w$ is missing). Let me fix a convention. Given a vector space $U$, and a bilinear form $\left< \cdot, \cdot \right>_U$ on $U$, define the map $\phi^{R}_U \colon U \rightarrow U^{*}$ by the formula
$$ \phi^{R}_U(u_0)(u) = \left< u, u_0 \right>_U $$
(the letter $R$ is there to designate that we use $u_0$ as the "rightmost" argument in $\left< \cdot, \cdot \right>_U$). Another meaningful choice would be to define
$$ \phi^{L}_U(u_0)(u) = \left< u_0, u \right>_U $$
(so we use $u_0$ in the left slot instead of the right slot). Unless the bilinear form is symmetric, the maps will be different.
Your definition of the adjoint is the map $\overline{f}$ which satisfies
$$ \left< v, \bar{f}(w) \right>_{V} = \left< f(v), w \right>_W. $$
To express this adjoint, it is better to work with the maps $\phi^R$ and then you have $\overline{f} = \left( \phi_V^R \right)^{-1} \circ f^{*} \circ \phi_W^R$. To see why, note that
$$ \phi_{V}^R(v_0) = \varphi \iff \left< v, v_0 \right>_V = \varphi(v) \,\,\, \forall v \in V $$
where $v_0 \in V, \varphi \in V^{*}$ (one direction is clear from the definition and the other follows because $\varphi_V$ is an isomorphism). Now, fix $v \in V, w \in W$ and then using the above we have
$$ \left< v, \left( \phi_{V}^R \right) ^{-1}(f^{*}(\phi_W^R(w))) \right>_V = f^{*}(\phi_W^R(w))(v) = \phi_W^R(w)(f(v)) = \left< f(v), w \right>_W.$$
You could have defined an adjoint of $f$ as the map which satisfies
$$ \left< \bar{f}(w), v \right>_V = \left< w, f(v) \right>_W $$
instead and in general, this would give you a different adjoint which is given by $\left( \phi_V^{L} \right)^{-1} \circ f^{*} \circ \phi_W^L$.
In fact, there are two other reasonable definitions of the adjoint in this general context and each of them can be expressed in terms of $\phi_V^{L},\phi_V^{R},\phi_W^L,\phi_W^{R},f^{*}$. When both $\left< \cdot, \cdot \right>_{V}, \left< \cdot, \cdot \right>_{W}$ are symmetric, all the adjoints coincide.
Comment: It looks like you are using $\phi_V(v)(v') = \langle v',v\rangle_V$ instead of $\phi_V(v)(v') = \langle v, v'\rangle_V$ as given by OP.
Comment: @Christoph: Arg, you are right. The problem is that the definition of $\phi_V, \phi_W$ of the OP is not consistent (the roles of $v_0,v$ and $w_0,w$ are switched which doesn't make any sense as $V,W$ are arbitrary vector spaces so why choose to use one convention for one and another convention for the other). I'll edit my answer.
Comment: I think it is consistent and just missing a "$(w)$" in "$\phi_W(w)(w_0)$", no?
Comment: @Christoph: Well, it depends whether the OP meant to write $\phi_W(w)(w_0)$ or $\phi_W(w_0)(w)$. In any case, I've edited the answer to treat both conventions.
Comment: @Christoph Indeed, I meant $\phi_W(w)(w_0)$. Thanks for pointing it out; I have corrected the definition.
Answer: Here's an approach using matrices.
By a choice of basis identify $V=K^n$ and $W=K^m$, elements are column vectors. We can identify their duals $V^*$ and $W^*$ with spaces of row vectors so that the usual matrix product serves as application of linear forms to vectors. In this setting, when $f\colon V\to W$ is given by an $m\times n$-matrix $A$ such that $f(v) = Av$, its dual $f^*\colon W^*\to V^*$ is given by $f^*(\beta) = \beta A$ since then
$$
(f^*(\beta))(v) = \beta A v = \beta(f(v)).
$$
Your bilinear forms are given by square matrices, namely
$$
\langle v, v'\rangle_V = v^t X v' \qquad\text{and}\qquad
\langle w, w'\rangle_W = w^t Y w'.
$$
for invertible matrices $X_{ij}=(\langle e_i, e_j\rangle_V)_{i,j=1,\dots,n}$ and $Y_{ij}=(\langle e_i, e_j\rangle_W)_{i,j=1,\dots,m}$.
Your isomorphisms $\phi_V \colon V\to V^*$ and $\phi_W\colon W\to W^*$ are given by $\phi_V(v)(v') = v^t X v'$ and $\phi_W(w)(w') = w^t Y w'$.
Now let's find the $n\times m$-matrix $B$ describing the adjoint $\bar f\colon W\to V$ as $\bar f(w) = Bw$. We want to have
$$
\langle v, \bar f(w) \rangle_V = \langle f(v), w\rangle_W,
$$
which can be written as
$$
v^t X B w = (Av)^t Y w = v^t A^t Y w.
$$
So we have $XB=A^t Y$ and hence $B = X^{-1} A^t Y$.


Caminho completo de arquivo em Python

Question: Estou utilizando o método os.listdir() para retornar uma lista de todos os arquivos, porém o retorno é apenas o nome do arquivo e eu gostaria que retornasse o caminho absoluto, alguém sabe alguma maneira ?
O método os.path.abspath() não está funcionando pois está me retornando a pasta do meu usuário + o arquivo sendo que o arquivo está dentro de subpastas do meu usuário.
Comment: Resolvi o meu problema utilizando a string que usei no método listdir() + o nome do arquivo, porém mesmo assim, seria bom saber qual o problema do método os.path.abspath()
Answer: O método os.listdir() retorna uma lista contendo os nomes dos arquivos e diretórios encontrados, o que pode estar acontecendo é que você deve estar utilizando o método os.path.abspath() apontando para a lista devolvida de os.listdir() de modo errado, aplicando os.path.abspath() para cada item da lista deverá funcionar.
import os

dirlist = os.listdir(".")
for i in dirlist:
    filename = os.path.abspath(i)
    print(filename)

A saída deve ser algo assim:
/home/user/dir1/dir2/arquivo1.py
/home/user/dir1/dir2/arquivo2.py
/home/user/dir1/dir2/foobarDir1
/home/user/dir1/dir2/foobarDir2

Atualização
Como alternativa ao método os.walk() poderíamos estar fazendo algo como:
import os

filedirlist = os.listdir(".")
filelist = [os.path.abspath(f) for f in filedirlist if os.path.isfile(f)]
dirlist  = [os.path.abspath(d) for d in filedirlist if os.path.isdir(d)]

# Lista de arquivos com path completo.
for i in filelist:
    print(i)

# Lista de diretórios com path completo.
for i in dirlist:
    print(i)

Answer: Gosto de utilizar o método os.walk('caminho'). O retorno é uma lista de tuplas. Onde cada tupla representa um caminho com seus respectivos diretórios e arquivos na forma de listas. O método percorre o diretório atual e seus subdiretórios.
import os
for caminho, diretorios, arquivos in os.walk():
    print caminho
    print diretorios
    print arquivos

Answer: Outra forma interessantes para resolver esta questão é utilizando o seguinte código:
from os import chdir, listdir
from os.path import isfile

cam = input('Digite o caminho: ')

chdir(cam)

soma = 0
for c in listdir():
    if isfile(c):
        print(cam + '\\' + c)
        soma += 1
print()
print(f'{soma} arquivos encontrados.')

Observe que este código recebe o caminho de um diretório (pasta), a partir do qual será listado todos os arquivos junto com seus caminhos absolutos.
Answer: costumo usar o os.walk()da seguinte forma:
from os import walk

for caminho,_,arquivo in walk('.'):
   print(str(caminho)+"/"+str(arquivo))

Caminho completo de arquivo em Python


How to make HTML table cell content to occupy all the cell rows?

Question: I have this table - http://jsfiddle.net/mark69_fnd/cgwyJ/
Notice, the last column - Notes, it spans all the rows.
How can I make its content to occupy all the rows, rather than cause the table to be the width of the page?
I am looking for something like http://jsfiddle.net/mark69_fnd/cgwyJ/4/, only without resorting to the width css parameter.
EDIT
Exhibit A:

Exhibit B:

EDIT 2

I am not looking for a fixed width table. I just want the row spanning cell to utilize the vertical space efficiently.
Please, do not provide answers involving the width. If you think either width or
 are needed, then you can just reply with "Nope, that's impossible".

EDIT 3
OK, there is a great deal of confusion around my question. Probably, because it is not formulated clearly.
Of course, there is a width limit involved somewhere underneath, but it is not a constant. It cannot be baked into the CSS. This is because it is a function of the following parameters:

The height of the available vertical space (N)
The average height of the characters in the given font (A)
The length of the given text, when presented on a single line, again in the given font (B)

Given these parameters, the required width is A * B / N. So, there is a well defined way to formulate what I want, but you just cannot express it with a constant width. So, my question is this - are there means to achieve this declaratively (i.e. in HTML/CSS) using some other attributes/properties?
Hope this clarifies a bit the picture.
Comment: Here both fiddles look the same.
Comment: @CristianoFontes the difference is that the second table has a specified width. the first one does not, so the long string in the notes column causes the table to get wider. OP wants it to take advantage of the vertical space, breaking automatically, instead of widening the cell.
Comment: @mark I don't know what you want to achieve, though, so I can't say there is a way. You want to break a line of text into multiple lines to fill up vertical space. Where do you break it up... how wide should each line be? If you don't know that, how do you expect to tell the computer to do it?
Comment: Why don't you want to use CSS `width`?
Comment: Because it is affected by the font and the font may change.
Comment: Chrome lastest they look exactly the same. I did not -1 the question btw.
Comment: @mark question: what would you expect it to do when there is more content than space? the current behavior (make fiddle 1 window really small) the cells of the last row get taller to make the content fit.
Comment: @sachleen - That's a tough question. I have already noticed this behavior. Ideally, the cells should be equal sized, however, I realize that doing so may required javascript, so I do not care. As long as the row spanning content uses the vertical space efficiently, I do not mind the last row being of different height.
Comment: @mark the problem you have is that you want the table to have a fixed width but you claim to not want that. How do you decide where to break to the next line?
Comment: @sachleen - I have never mentioned to want the fixed width. Have I? Where, so I can fix the question.
Comment: I'm saying by saying you want the lines to split to take advantage of the vertical space, at what point should it break a line? That point is defined by a fixed width.
Comment: @sachleen - Please, agree with me that what I am asking is achievable by writing some javascript code without relying on the fixed width. So there is a way to do it without having a width baked into the CSS. Now, all I am asking is whether there is a declarative way to request this behavior, through some HTML attributes and/or CSS properties. If you think there is none, well, maybe you are right, but then maybe you are wrong.
Comment: @sachleen - Given: vertical space `N` pixels high, a text, when presented on a single line - `A` pixels high and `B` pixels long. Then the text could be split in `N / A` lines. Which means, the length of the text becomes `B / (N / A) = (A * B) / N` pixels. So, the last cell should be roughly `(A * B) / N` pixels in width. This is the algorithm, which does not rely on a width baked in the CSS. Of course, at the end it calculates a width, but this width is a function of the current font and the given text. No constant magic widths.
Comment: What if the value of the notes column is only a single word? Also I don't think this is possible with only CSS+HTML.
Answer: Either
 The Paragraph or just resort to the width: ; CSS Parameter, and Why wouldn't you want to do that?
but line breaking (
) it all would be the only other option I can think of.
Comment: Because width is affected by the font. What renders nice with one font will be rendered badly in another, because the width does not take it into account.
Comment: @KevinBoucher - I beg your pardon?
Comment: Yes if you were to do this, that is the only down side
Answer: Honestly the CSS way is the best if you ask me, but you could always set the width to that paragraph cell, the problem with that is if there is too much text it will make the bottom row taller than the others.
http://jsfiddle.net/calder12/cgwyJ/6/

  Browser
  http --> http
  http --> https
  Notes

  Chrome
  CORS
  CORS (*)
  If the SSL certificate validation fails, neither CORS nor JSONP will work. However, there is a workaround. The respective request .

  Firefox
  CORS
  CORS (*)

Comment: @mark you're completely missing the point: it HAS to cut off the lines at some width. If you disagree, that's the current behavior where it stretches horizontally. You have to know *where* you want it to split lines or it doesn't split lines. And if you know where you want it to split lines, that's a fixed width. no?
Comment: I do not want any explicit width parameters. They screw the layout if a different font is used.


Is there anyway to cross reference a view?

Question: I have View1 where I would like to add a filter which stops any rows appearing if there are rows in View2.
I thought I would have been able to execute some PHP as a filter, but I can't see any options for that.
Is there any way to use another view as a filter?
Comment: Quick question: are these views both shown on the same page?
Answer: For this you could use the advance option of the view where you could add the contextual filters and relationships.
This would help you in filtration.
For php filtration you could use the Views PHP module; that would help you in your filtration.

This module allows the admin account (user 1) to add fields, filters and sorts to views which use PHP code. It also supports additional accounts when the core PHP Filter module is enabled.

For information about how to use the module you could refer to README.txt of the module.
Answer: Your can also filter your view programmaticly with hook_views_query_alter
Example:
<code>function custom_views_query_alter(&$view, &$query){

  switch ( $view->name ){

    case 'view1':

      $view2 = views_get_view( 'view2' );
      $view2->set_items_per_page(0);
      $view2->execute();

      $custom_query = array();
      foreach( $view2->result as $row ){
        $custom_query[ $row->field_custom ] =  $row->field_custom;
      }
      $query_nids = implode(',', $custom_query );
      if( !$query_nids ) $query_nids = 0;

      $query->where[0]['clauses'] = array(
        'node.nid IN ('. $query_nids .')'
      );
      break;
  }
}
</code>
It's a D6 example, need some ajustments for D7
in D7 looks like :
<code>$query->where[1]['conditions'][] = array(
  'field' => 'node.nid',
  'value' => $query_nids,
  'operator' => 'IN'
);
</code>
Answer: Use views php module to have a filter based on custom PHP code; use PHP to filter out any row.


como colocar máscara monetária para EditText em um aplicativo Android?

Question: como colocar máscara monetária para EditText em um aplicativo Android somente com valores numéricos sem o R$, ou seja, imprimir no EditText 2,99? Se tiverem um exemplo.
Answer: Modifique o onChanged do TextEdit via código que da certo. E vc nem precisa de uma mascara para isso. Segue um exemplo:
<code>        seu_text_edit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            private String current = "";
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if(!s.toString().equals(current)) {
                    Locale myLocale = new Locale("pt", "BR");
                    //Nesse bloco ele monta a maskara para money
                    txtUnitario.removeTextChangedListener(this);
                    String cleanString = s.toString().replaceAll("[R$,.]", "");
                    Decimal parsed = Double.parseDouble(cleanString);
                    String formatted = NumberFormat.getCurrencyInstance(myLocale).format((parsed / 100));
                    current = formatted;
                    txtUnitario.setText(formatted);
                    txtUnitario.setSelection(formatted.length());

                    //Nesse bloco ele faz a conta do total (Caso a qtde esteja preenchida)
                    String qtde = txtQtdeLitros.getText().toString();

                    txtUnitario.addTextChangedListener(this);
                }
            }
            @Override
            public void afterTextChanged(Editable s) {

            }
        });
</code>
Essa é apenas uma maneira básica de fazer um campo monetario, existem muitas outras maneiras de fazer e na minha opinião, esse tipo de campo não precisa de máscara pois é só vc falar que ele é tipo currency e tratar os dados usando Decimal ( Sempre evite trabalhar com valores Double ou Float quando for monetario ).
Detalhe, Usando essa lógica ao invés de uma máscara vc também vai dar um efeito super legal para o EditText, pois ele vai preencher a partir dos centavos.
Comment: É que eu preciso realizar cálculos, posso usar mesmo assim seu código?
Comment: Pode, sem problemas. No meu sistema eu faço um calculo de litros x valor, eu uso esse mesmo código para o valor unitario, litros e total e funciona 100%
Comment: Olá, tive um problema como posso salvar no banco MYSQL o valor gerado? irei salvar como String ele salva nesse formato R$ 2,99 ou posso salvar como Decimal? mas mostra o seguinte erro após salvar em String. Vou postar na edição.
Answer: Você pode usar esta lib:
https://github.com/santalu/mask-edittext
Depois só adicionar o edittext já com mascara no xml:
<code> <com.santalu.maskedittext.MaskEditText
android:id="@+id/et_phone_number"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="@string/hint_phone_number"
android:inputType="number"
app:mask="#,##"/>
</code>
Comment: Fiz o teste deu certo mas ele só trata valores no formato 1,20 e se caso precisa-se de valor 12,40 ou 1200,00?
Comment: é só mudar a mascara do jeito que você quer por exemplo: Para 12,40 é app:mask="##,##"
Comment: Eu preciso de uma mask que permita apenas letras maiúsculas e números, sem ponto, espaço ou outro caracter, Sabe se atende? Valeu


Regex to allow a pattern of chars but not an individual char from that pattern

Question: I am trying to create a regex that will do the following
Match the String if:

The String is between 4-35 chars
The String must contain the $ as the last char in the String
The String does not contain any $ anywhere else unless the dollar sign is wrapped within a bracket, i.e. [$]

I currently have the following regex: [^\$]{3,34}\$$
You can see the example here
This catches not allowing $ except at the end, however I still need to allow the dollar sign if it is wrapped within brackets [$]. How can I add a way to "allow" the [$]?
Some Positive examples:

ABCD$
ABC[$]D$
[$]ABCDEFG$
!@#%^&*[$]^%$

Some Negative examples:

AB$CD
ABCD
$$ABCD$
AB$[$]CD$
Answer: You may use
^(?=.{4,35}$)(?:\[\$]|[^$])*\$$

See the regex demo
Details:

^ - start of string (can be omitted if the pattern is used with matches())
(?=.{4,35}$)  - a positive lookahead requiring 4 to 35 chars in the string
(?:\[\$]|[^$])* - 0+ [$] substrings or any chars other than $
\$ - a literal $
$ - end of string (may be omitted if used with matches()).

Java demo:
String lines[]  = {"ABCD$","ABC[$]D$","[$]ABCDEFG$","!@#%^&*[$]^%$","AB$CD","ABCD","$$ABCD$","AB$[$]CD$"};
String pat = "(?=.{4,35}$)(?:\\[\\$]|[^$])*\\$";
for(String line : lines)
{
    System.out.println(line + ": " + line.matches(pat));
}

Result:
ABCD$: true
ABC[$]D$: true
[$]ABCDEFG$: true
!@#%^&*[$]^%$: true
AB$CD: false
ABCD: false
$$ABCD$: false
AB$[$]CD$: false


How to flag an entity when it is created or updated?

Question: I have a Drupal 8 site with the Flag module.
I want when a user creates or updates a node, product, store, group, ... the updated entity is flagged.
How to flag an entity when it is created or updated ?
I'm testing the "Rules" module which is finally (usable) in production.
But how do you flag down a new entity when it is created ?
What should be put in "Action", because it is no longer like in Drual 7 with an interface.
Comment: @bleen Yes, but the Rules module seems completely dead, it's been years since there is a stable version and I don't dare install it on my non-production site.
Comment: Have you looked into the Rules module?
Comment: Might this be a duplicate of: https://drupal.stackexchange.com/questions/2076/how-to-use-the-rules-module-to-flag-a-node-that-has-just-been-created
Comment: @bleen Can the "Actions" module do this ?
Comment: @sdiff your statement is completely false and misleading - Rules is extremely active and under development, and is even compatible with D9 and is used by tens of thousands of sites. This posters task is trivial with Rules.
Comment: I updated my question.
Comment: @anonymous Sorry I just retested the rules module and it's still not possible to do such a simple task.
Answer: You can use HOOK_entity_presave to trigger when node gets created. I updated code for you. Make sure that you change the capital letters to correct values.
<code>function MODULENAME_entity_update(Drupal\Core\Entity\EntityInterface $entity) {
  // Check which content type would you like to flag.
  // You can use https://www.php.net/manual/en/function.in-array.php to check for
  // multiple content types
  if (in_array($entity->bundle(), ['mycontentype1', 'mycontentype2'])) {
    $flag_id = 'yourflagname';

    $flag_service = \Drupal::service('flag');
    $flag = $flag_service->getFlagById($flag_id);

    // Flag an entity with a specific flag.
    // https://www.drupal.org/docs/drupal-apis/entity-api/introduction-to-entity-api-in-drupal-8
    $flag_service->flag($flag, $entity);
  }
}
</code>
Comment: Thanks, but I'll try to do this from the Drupal 8 interface.
Comment: I don't know programming very well. I know how to create the base of a module, but what should the module file contain ?
Comment: @sdfff I updated the code for you.
Comment: Thanks, I just created a module with your code, but I have 2 PHP error when I register a node https://ibb.co/2q8YgXp https://ibb.co/fGwxXGx https://ibb.co/4dWRpJr
Comment: is the content already flagged? than maybe need to add another check
Comment: The flag is created but the content is not created
Comment: ok, that means that we need to use a new hook because the entity does not exist yet. Replace presave with MODULENAME_entity_update
Comment: Thanks, it works. If I do the same for groups, stores and prosuit, is it the same code ?
Comment: I updated the answer for easier code reading - use PHP function in_array which accepts two parameters array of machine names of content types and the second parameter actual entity type which we update. You can place your content type machine names in the array
Comment: Thanks, i just tested but i got this error in terminal after doing a drush cr `PHP Parse error:  syntax error, unexpected ';' in /var/www/www-s1biose-com/web/modules/custom/admin_report/admin_report.module on line 5
 [warning] Drush command terminated abnormally.` https://pastebin.com/v5w5ke4Z
Comment: there is one bracket missing for if clause )
Comment: Yes indeed it was missing the closure. I fixed and I still have a PHP error :-( `Message Warning : in_array() expects parameter 2 to be array, string given dans admin_task_notify_entity_update() (/var/www/www-s1biose-com/web/modules/custom/admin_task_notify/admin_task_notify.module ligne 4)`
Comment: https://pastebin.com/5LAK3Vh8
Comment: hm, seems like we did a mistake, in_array must first accept the string we searching for for the second parameter you need the array in which you're searching for. my bad. I updated the answer
Comment: Thanks a lot, now it's working. One last question, if I have to flog several totally different entities, what do I do? I created a flag per type of entity. Here is the complete code that I would like to do: https://pastebin.com/h80nCdbb
Comment: that is the correct way to do it.You can place  $flag_service = \Drupal::service('flag'); to the first line of the function so you don't have to repeat it all the time
Comment: Ok but there is a problem, how does it tell the difference between the different type of entity. For example between nodes and comments that have the same machine name? Should we put a comma at the end of each IF ?
Comment: If I apply my code, when I post a comment, I have lots of errors in my logs https://ibb.co/ygPfqdh
Comment: I posted my code here https://git.drupalcode.org/sandbox/zenimagine-3170711
Comment: I found a similar module but I don't know what I need to change in mine so that it no longer displays an error
 https://git.drupalcode.org/project/rules_flag/-/tree/1.0.x


Proof of a theorem of Cauchy's on the convergence of an infinite product

Question: Well it is relatively well known that the condition for absolute convergence is given by the following theorem: In order that the infinite product
$\prod _{n=1}^{\infty }\left( 1+a_{n}\right) $ may be absolutely convergent, it is necessary and sufficient that the series $\sum _{n=1}^{\infty }a_{n}$ should be absolutely convergent.
I am trying to prove a little less famous result from Cauchy, which states If $\sum _{n=1}^{\infty }a_{n}$ be a conditionally convergent series of real terms, then $\prod _{n=1}^{\infty }\left( 1+a_{n}\right) $ converges (but not absolutely) or diverges to zero according as $\sum _{n=1}^{\infty }a_{n}^{2}$ converges or diverges.
Some thoughts towards the Proof
Although i could eb wrong here but since we do not know that $a_{n}\rightarrow 0$ under the given circumstances i guess a proof by comparison to $\sum _{k=0}^{\infty }\dfrac {1} {k^{2}}$ or which required the ln series kind of seem to fall apart. I was hoping some one could possibly provide an idea/ strategy for this proof.
Any help would be much appreciated.
Comment: "Cauchy's Theorem" is like saying "Mozart's composition", "Euler's paper", or "president's speech"... there's so many to choose from
Comment: That's fair enough, please suggest a more appropriate title ?
Comment: i c the new one thanks
Answer: We can assume $\displaystyle a_n \neq 0$.
Define $\displaystyle b_n$ as follows
$$ b_n = \frac{\log(1+a_n) - a_n}{a_n^2}$$
Notice that $\displaystyle b_n \lt 0$ for all $n$.
Thus
$$\sum_{k=1}^{n} a_k^2b_k - \sum_{k=1}^{n} \log(1+a_k) = \sum_{k=1}^{n} a_k$$
Using the Taylor expansion of $\displaystyle \log (1+x)$, (note that $\displaystyle a_n \to 0$), we see that $\displaystyle b_n \to \frac{-1}{2}$.
Now, it is well known that if $\displaystyle \sum x_n$ converges absolutely and $\displaystyle y_n$ is bounded, then $\displaystyle \sum x_n y_n$ converges.
Thus
If $\displaystyle \sum_{k=1}^{n} a_k^2 $ converges then so does $\displaystyle \sum_{k=1}^{n} a_k^2 b_k$ and as a consequence, so does $\displaystyle \sum \log (1+a_k)$ and $\displaystyle \prod (1+a_k)$.
If $\displaystyle \prod(1+a_n)$ converges, then so does $\displaystyle \sum_{k=1}^{n} \log(1+a_k)$, and so $\displaystyle \sum_{k=1}^{n} a_k^2 b_k$ converges. Since $\displaystyle b_k \lt 0$, this convergence is absolute and thus  the sequence $\displaystyle \sum_{k=1}^{n} a_n^2 b_k \times \frac{1}{b_k} = \sum_{k=1}^{n} a_k^2$ converges, as the sequence $\displaystyle \frac{1}{b_n}$ is bounded.
Comment: @Hardy: When considering products, it is natural to consider the logarithms and trying to get $a_n$, $a_n^2$ and $\log(1+a_n)$ into the picture kind of leads to $b_n$. It could also be that I might have read a similar proof earlier... Conditional convergence implies convergence (not necessarily absolute) and so $a_n \to 0$ isn't it?
Comment: @Hardy: If $S_n =\sum_{k=1}^n a_k$ is convergent (absolute or not), then $a_n = S_n - S_{n-1} \to 0$. Note that the _sum_ of positive terms could go to $\infty$. We are talking about the individual term. For instance $\sum \frac{(-1)^n }{n}$ is the classic example of such a series and what $a_n \to 0$ is saying is that  $\frac{(-1)^n }{n} \to 0$.
Comment: Firstly buddy thanks very much for your answer. I have to tell you i think it is quite ingenious how you created a $b_{n}$ to represent the problem. I would love to hear why you chose that particular value for $b_{n}$. Although i am not sure that we are allowed to choose $a_{n}$ goes to zero as the result states a conditional convergence only instead of an absolute one. Any thoughts ?
Comment: see i think absolute convergence could only occur if the underlying sequence $a_{n}$ goes to zero, on the contrary conditional convergence can occur i believe even with the underlying sequence $a_{n}$'s even and odd terms going to $+\inf$ and $-\inf$. I can n't think of a definitive example of the top of my head but i am quite confident that it exists. If you are not convinced please let me know and i shall find an example of such a series for our discussion.
Comment: @Aryabhata How do you know that $log(1+a_n)$ is always defined for all $n \in \mathbb{N}$.
Comment: How do you show that the infinite product diverges to 0 when $\sum (a_n)^2$ diverges?
Comment: It is not necessary that $\displaystyle \sum x_n$ converges absolutely. The *normal* convergence suffices.


How can I form a Views query that retrieves all nodes that are referenced by a node in another content type?

Question: I have a content type of Artist. I also have a content type of Release. The Artist content type has a node reference field that points to the Release content type. This node reference field allows an Artist to have 1 or more Releases.
I created a view that displays fields from the Artist content type as a page. Let's call this view "Artist Page." Artist Page has a single argument of Node: Title and a path of artist/%. This works really well.
I would like to add another view for a block of Releases belonging to a particular Artist. I hope to display this block in the sidebar for Artist Page.
How can I form a Views query that retrieves all Releases that are referenced by an Artist?
(I am making my first non-trivial Drupal 6 site and I appreciate your patience. I am happy to RTFM but please tell me where to go!)
Answer: Ok, So the way to do this is with arguments and relationships.
Normally using the "Provide default argument" option would work but since you're not using the actual "artist" node you can't actually get the node id from the URL.
Also just an FYI, passing the title for a views argument is a bad idea because then the query is doing a lookup based on text instead of a numeric value such as the node id which is better on performance.
But anyways the solution to your problem is add the same argument to your block view as you did to your "artist" page view. This should be the node title argument. Now add a relation to your view. The relationship you want to add is the content: [name of node reference field] relationship.
Now you can add what ever fields to your view that you would want to include from the "release" content type but now you will see you get a relationship option in the field option. When you want to display fields from the "release" content type just be sure to select the [node reference] relationship.
Also we need to do one more thing. Which is getting the proper argument to be picked up by your block view. This is a bit trickier mainly because of what I mention earlier which is that you're passing the node title as an argument. So now you can edit your Node: Title argument and you should see the "option to take if the argument is not present" select the "provide default argument" and select the php code option. In there you want to paste this piece of code.
return arg(1);

Now save your view and place that block on the page and visit the artist/% page and you should now see what ever fields you want to use. This php code is telling your block view to pick up the artist/% argument from the url.
A couple of things to lookout for:

php code in the views is bad, I just mentioned that here as a quick fix to your problem.
When using relationship be sure to select the relationship option only when you want to display a field from the "related" item. In other works if you want to display the title of the related node select node title and be sure the relationship is selected. If you want to display the title of the node being passed in on the argument select node title just don't select any relationship.

Hope this is helpful, is a long post but relationships can be confusing.
Hope this helps.
Answer: Add an argument for the node reference, and choose "Provide default argument", setting that to "Node ID from URL".
Comment: Which URL? I never display "bare" Artist nodes -- just views that are referenced by the URL: artist/[artist node title]
Comment: Hm, not sure if it'll still pick it up. Worth a try.
Comment: Aha. Let me try that now.
Comment: Yes, thanks, but that is not working. :( The block View has a filter of Node: Type = Release, an argument of the Releases node reference in Artist (with a default argument type of Node ID from URL), and a single field of the Release's name. When I go to an Artist Page, nothing appears in the block.
Answer:
The Artist content type has a node reference field that points to the Release content type.

That way, every time a new Release is created, an Artist must be edited. If you instead give the Release content type a node reference to the Artist content type, a Release can be created without editing an Artist.
In that case the view would have the node reference field for the artist as a relationship and a node nid argument that uses this relationship.
As ericduran explained in his answer, use a default argument to circumvent the limitation that block displays do not automatically receive arguments from the URL.


How can I recreate a previously deleted Content Type?

Question: I have deleted a Content Type called news some months ago using Drupal's Field UI. Now I would like to recreate a new Content Type with the exact same machine name news. However no Content Type shows up. When I take a look at the database a new entry has been created in the node_type table.
Somehow Drupal doesn't remove the Content Type in the database. What's the recommended way to cleanup orphaned Content Types? Why does Drupal keep these leftovers? I don't want to mess around in database.
Comment: Drupal doesn't keep "leftovers". When you delete a content type, it's gone. Modules are given the chance to clear up via a hook invocation, so maybe you're using a dodgy custom/contrib module. You can see what happens in [node_type_delete](https://api.drupal.org/api/drupal/modules!node!node.module/function/node_type_delete/7.x). There's no room for ambiguity in there as I'm sure you'll see
Comment: No additional Contrib modules were involved. Only Drupal's Field UI.
Comment: As you can see from those few lines of code, the record is explicitly removed from the table, then the bundle is removed from the field system, the hook is invoked, and the cache is reset. Once cron has run to remove any to-be-deleted data, it's like it never existed as far as any core modules are concerned. Make sure your cron jobs are actually running and clearing out the old field data, other than that check any custom code you have in the site, as what you're describing doesn't line up with what Drupsl's core code is doing
Answer: You should delete the actual content first before deleting the content type. And nodes are going to be orphaned too and provably they will not display same as the content type news. can you try to search the existing news node in admin/content and check if you can still see the existing node type news that you created before. and try to delete them all before deleting the news content type and try to re-create the news content type.
Comment: Yes, I have deleted all Content first. No additional Contrib modules were involved. Somehow "news" is references in additional tables? I don't want to use a different machine name. What can I do?
Comment: I am not sure if this will work, I haven't tried it. run cron and clear your cache then try to re-create the content type news again.
Comment: Thank you for your reply. I have cleared the cache and run update.php a couple of times. When I recreated the Content Type "news" it doesn't show up.
Comment: cron is different in update.php you can run cron here `admin/config/system/cron`
Comment: Thanks, unfortunately news Content Type still doesn't show up.


Why is UDP slower than TCP on Ubuntu Server?

Question: I transfer data between two Ubuntu Servers (12.04) via iperf on 1Gb LAN.
iperf -s    <->     iperf -c <addr> -n2G
TCP speed = 925 Mbits/sec

iperf -su   <->     iperf -uc<addr> -b1G -n2G
UDP speed = 810 Mbits/sec
Jitter = 0.016 ms
Lost = 0 .. 0.01%

I expected that UDP is much faster than TCP. Could anyone please explain why does UDP slower than TCP on Ubuntu Server?
Comment: I'm trying to determine maximun UDP transmission speed on my Linux servers, Ubuntu 12.04 on my 1GB LAN. Could you please suggest any appropriate approach?
Comment: No I can't. **You haven't mentioned what you actually plan on doing**. I think your missing the point of what I'm saying. Make the test reflective of what your are actually trying to do. So if your future plans for the servers is just to run `iperf` tests continuously, then your methodology is fine. If your future plans is to run OpenVPN over UDP - then your testing methodology is useless. All you're getting at the moment is a throughput figure for `iperf` - but that ***is not*** the same as what your actual application throughput may be.
Comment: It could be anything. Your testing methodology and setup is probably just the cause.
Comment: sonassi, do you know a methodology that is better/more accurate than mine?
Comment: Not really - you haven't mentioned what you actually plan on doing. ie. why you need UDP to be faster. Unless of course, your intention was just to run `iperf` - in which case, its the perfect test. Your testing should reflect the real world load - otherwise the results can be somewhat meaningless.
Answer: Each frame goes through several buffers as you send it: The application buffer, The Protocol Buffer, The Software interface buffer and the Hardware interface buffer. As you start stressing the stack by sending high speed data you will fill up these buffers and either block or lose data. You also have strategies for timeliness and polling that can impact your performance. For example, by using a larger buffer and poll less often you can get much better performance while sacrificing latency.
TCP is optimized for high speed bulk transfers while UDP is optimized for low latency in the Linux kernel. This has an impact on buffer sizes and how data is polled and handed over. In addition to this, you frequently have offloading to hardware for TCP. I would expect considerably better performance for TCP compared to UDP.
Note that sending high speed data over UDP is usually a bad idea, unless you implement your own congestion control. TCP protects your network from congestion collapses. Use UDP when you have small amounts of data or high timeliness requirements.
Answer: As it is said above, iperf limits itself by design. In src/Client.cpp, method
void Client::Run( void )

calls
ReportPacket( mSettings->reporthdr, reportstruct );

after writing each UDP datagram.
ReportPacket() is rather slow and it slows the whole thing.
In iperf3, burst writes are introduced for UDP, you can specify number of burst writes in -b command line parameter, like -b 10240M/2000
otherwise, you can use netperf with -t UDP_STREAM.
Comment: I tried both params but still see `iperf` UDP tests run about 10000X slower than TCP (1Mbit/s vs 10Gbit/s).
Answer: The problem is inside iperf itself. When you send a UDP flow iperf will do some internal bookkeeping for each datagram in the flow. On the other hand when you send a TCP stream iperf does bookkeeping only once per stream. In my measurements it came out that iperf-UDP wastes a lot of time doing the per-datagram measurements hence the slower performance.
If you really want to compare TCP vs UDP performance is better to write your own test program. and make sure that the amount of computations is the same in both cases.