Remove all views in UIView hierarchy and jump to the first view

Question: I have an app which has few subviews added to superview using
<code> [self.view addSubview:subview.view];
</code>
All are different view controllers and have custom back buttons to come back to main/first view. Until now no issue.
At some of in the app I have to jump from screen/subview 4 to first view, where I recreate first view. (using initWithNibName and addSubview). This increases a memory of the app.
To solve this, I want to remove all subviews and come back to first view as it already exists but is not visible instead of creating first view again.
How to achieve this?
Please help.
Thanks in advance
Comment: Hey @Mobility if you are using iOS5 you could loop through all the sub view controllers, remove them from their superview AND [subViewController removeFromParentViewController]. That should remove them from the display and hierarchy
Comment: Hi @Mobility would [[self.view subviews] makeObjectsPerformSelector:@selector(removeFromSuperView)] suffice?? Its from the top of my head so take it as sudo-code rather than the exact code syntax.
Comment: @bennythemink I want to remove all views from view hierarchy and not just the subviews on view. WIll this work for the same?
Comment: My app support iOS 4.3 and higher. Any other way to achieve this?
Comment: mmm... maybe loop through the sub view controllers, removeFromSuperView for each sub view, and then set the controller = nil for ARC or nil & release it if using manual memory management making sure its not referenced anywhere else that may cause a crash. I think this is correct, my brain is fried at the moment after a late night, the community will let us know if I am incorrect :)
Comment: also as @Safecase mentioned in his answer place a conditional to check that you are not removing the view you want.
Answer: You can declare the tag value of particular view, and remove all the view according to your need :
*for (UIView *subview in [self.view subviews])
{
if(view isKindOfClass:[UIView class])
{
<code> if (subview.tag == 101 || subview.tag == 102)
</code>
{
<code> [subview removeFromSuperview];
</code>
}
}
}*
there is a sample code below this line: in this code button 'btn' created by xib  and which call btnClicked method

<code>- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    myViewNew = [[UIView alloc] initWithFrame:CGRectMake(50, 40, 150, 150)];
    [myViewNew setTag:102];
    [myViewNew setBackgroundColor:[UIColor redColor]];

    myView = [[UIView alloc] initWithFrame:CGRectMake(50, 40, 150, 150)];
    [myView setTag:101];
    [myView setBackgroundColor:[UIColor blueColor]];

    btn1 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [btn1 setFrame:CGRectMake(50, 50, 50, 50)];
    btn1.titleLabel.text = @"btn1";
    [myView addSubview:btn1];

    [btn1 addTarget:self action:@selector(btn11Pressed:) forControlEvents:UIControlEventTouchUpInside];

    btn2 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [btn2 setFrame:CGRectMake(50, 50, 50, 50)];
    btn2.titleLabel.text = @"btn2";
    [myViewNew addSubview:btn2];

    [btn2 addTarget:self action:@selector(btn2Pressed) forControlEvents:UIControlEventTouchUpInside];

}

-(void)btn2Pressed
{
     for (UIView *subview in [self.view subviews])
     {
       if(view isKindOfClass:[UIView class])

       {

        if (subview.tag == 101 || subview.tag == 102)
        {
            [subview removeFromSuperview];
        }
       }

      }
}

-(void) btn11Pressed:(id)sender
{
    [self.view addSubview:myViewNew];
}

-(IBAction)btnClicked:(id)sender
{
    [self.view addSubview:myView];
}
</code>
Answer: If you want remove all subview and come firstview:
<code>  //here view where you want remove all sub views containing in view
  [[self.view subviews] makeObjectsPerformSelector:@selector(removeFromSuperView)];
</code>
Do this to keep one subview on view:
<code>    NSArray *allSubViews = [self.view subviews];
    for(int i= 0; [allSubViews count];i++)
    {
      if(i !=0)
      {
          UIView *view = [allSubViews objectAtIndex:i];
          [view removeFromSuperview];
      }
    }
</code>
Comment: I did this just now, this gives me list of subviews added on a view e.g. nab bar, button, uitableview. But I want all the screens in view hierarchy and remove all of them and jump back to home screen
Comment: instead of view use homescreen reference like NSArray *allSubViews = [homescreen subviews];


Como cadastrar dados sempre no ultimo document gerado?

Question: No meu código toda vez que vou realizar um cadastro um document é criado. Gostaria de saber se tem como cadastrar informações neste ultimo document gerado em vez de gerar outro. Estou fazendo em Java, usando o Cloud Firestore.
  db.collection("enfermeiros").document()
                            .set(enfermeiro, SetOptions.merge())
                            .addOnSuccessListener(new OnSuccessListener<Void>() {
                                @Override
                                public void onSuccess(Void aVoid) {
                                    Log.d(TAG, "DEU BOM");
                                }
                            })
                            .addOnFailureListener(new OnFailureListener() {
                                @Override
                                public void onFailure(@NonNull Exception e) {
                                    Log.w(TAG, "DEU MERDA", e);
                                }
                            });

Answer: Eu faço assim:
firestoreMetas
.collection("metas_compras")
.document(metaCompra.id_meta)
.set(metaCompra)
.addOnSuccessListener {
    //Sucesso
}.addOnFailureListener{
    //Erro
}

Bom, basicamente, uso o id do document (metas) que eu quero, e passo um objeto (metaCompra) com as novas informações.
Espero ter ajudado...
Comment: Do jeito que vc sugeriu as informações vao ser cadastradas num id especifico(No ID que vc quer )?
Comment: Isso, pelo que entendi, você não quer criar um novo document, quer salvar as informações no que já está criado certo? Então, você usa o Id do que está criado e salva as novas informações nele.
Comment: na verdade oque eu queria era criar um document e cadastrar nele e repetir o processo a cada vez que for realizar um cadastro, cada vez num document diferente.


'WebFormsBundle' is not a valid script name. The name must end in '.js'

Question: What can i do to solve this error?

At the first the application was ok but than i dont know what happend.
i have curectly installed the packages and the references.
and here is the part than as i understand gives the error
<code>      <asp:ScriptManager runat="server">
        <Scripts>
            <%--To learn more about bundling scripts in ScriptManager see
       http://go.microsoft.com/fwlink/?LinkID=301884 --%>
            <%--Framework Scripts--%>
            <asp:ScriptReference Name="MsAjaxBundle" />
            <asp:ScriptReference Name="jquery" />
            <asp:ScriptReference Name="bootstrap" />
            <asp:ScriptReference Name="respond" />
            <asp:ScriptReference Name="WebForms.js" Assembly="System.Web"
     Path="~/Scripts/WebForms/WebForms.js" />
            <asp:ScriptReference Name="WebUIValidation.js"
     Assembly="System.Web" Path="~/Scripts/WebForms/WebUIValidation.js" />
            <asp:ScriptReference Name="MenuStandards.js"
     Assembly="System.Web" Path="~/Scripts/WebForms/MenuStandards.js" />
            <asp:ScriptReference Name="GridView.js" Assembly="System.Web"
     Path="~/Scripts/WebForms/GridView.js" />
            <asp:ScriptReference Name="DetailsView.js" Assembly="System.Web"
     Path="~/Scripts/WebForms/DetailsView.js" />
            <asp:ScriptReference Name="TreeView.js" Assembly="System.Web"
     Path="~/Scripts/WebForms/TreeView.js" />
            <asp:ScriptReference Name="WebParts.js" Assembly="System.Web"
     Path="~/Scripts/WebForms/WebParts.js" />
            <asp:ScriptReference Name="Focus.js" Assembly="System.Web"
     Path="~/Scripts/WebForms/Focus.js" />
            <asp:ScriptReference Name="WebFormsBundle"/>
            <%--Site Scripts--%>
        </Scripts>
    </asp:ScriptManager>
</code>
Comment: Were you ever able to resolve this? I'm encountering the same issue now.
Comment: I am facing same problem as well, and not able to find solution for this from anywhere. If you have resolved this problem then please share the solution.
Answer: This solution worked for me:
Install
Microsoft.AspNet.ScriptManager.WebForms
from Nuget (right-click your solution, select Manage Nuget packages)


My Chrome addon for removing Youtube autoplay breaks posting on forums

Question: I am trying to make a Chrome addon that removes the autoplay from embedded Youtube videos. However, when I try to post on a forum that has a minimum character limit for posts, I get an error about my post not being long enough. That occurs only when my addon is active. Here is my codes:
manifest.json:
{
   "content_scripts": [ {
      "js": [ "js/replace.js" ],
      "matches": [ "http://*/*" ],
      "run_at": "document_idle"
   } ],
   "description": "some text",
   "manifest_version": 2,
   "name": "No autoplay",
   "permissions": [ "tabs", "http://*/*" ],
   "version": "1.0"
}

replace.js:
var str1 = '&autoplay=1', str2 = '?autoplay=1', empty = '', regex1 = /\\&autoplay=1/gi, regex1 = /\\?autoplay=1/gi;
var ind = document.body.innerHTML.indexOf(str1);
while (ind != -1) {
    console.log("replacing");
    document.body.innerHTML = document.body.innerHTML.replace(regex1, empty);
    ind = document.body.innerHTML.indexOf(str1);
}
ind = document.body.innerHTML.indexOf(str2);
while (ind != -1) {
    console.log("replacing");
    document.body.innerHTML = document.body.innerHTML.replace(regex2, empty);
    ind = document.body.innerHTML.indexOf(str2);
}

Answer: If a link contains str2, you are deleting ? character. That means, all other $_GET parameters are being moved to url section.
For example:
someurl.com?autoplay=1&movie_id=10 turns into someurl.com&movie_id=10 ... and it is invalid, because it should be someurl.com?movie_id=10...
Safer way would be replacing autoplay=1 with autoplay=0.


React Native ERROR: Android tasks have already been created. Android Studio 3.3

Question: My react native app doesn't build after updating Android Studio and Gradle.
buildscript {
    repositories {
        jcenter()
        google()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.1.4'
    }
}

allprojects {
    repositories {
        google()
        mavenLocal()
        jcenter()
        maven {
            url "$rootDir/../node_modules/react-native/android"
        }
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}
subprojects {
    project.configurations.all {
        afterEvaluate {project ->
            if (project.hasProperty("android")) {
                android {
                    compileSdkVersion 27
                    buildToolsVersion "27.0.3"
                }
            }
        }

        resolutionStrategy.eachDependency { details ->
            if (details.requested.group == 'com.android.support'
                    && !details.requested.name.contains('multidex') ) {
                details.useVersion "26.1.0"
            }
        }
    }
}

FAILURE: Build failed with an exception.

* Where:
Build file 'D:\mobileinstein.app\android\build.gradle' line: 32

* What went wrong:
A problem occurred configuring project ':app'.
> Failed to notify project evaluation listener.
   > Android tasks have already been created.
     This happens when calling android.applicationVariants,
     android.libraryVariants or android.testVariants.
     Once these methods are called, it is not possible to
     continue configuring the model.
   > Android tasks have already been created.
     This happens when calling android.applicationVariants,
     android.libraryVariants or android.testVariants.
     Once these methods are called, it is not possible to
     continue configuring the model.
   > Android tasks have already been created.
     This happens when calling android.applicationVariants,
     android.libraryVariants or android.testVariants.
     Once these methods are called, it is not possible to
     continue configuring the model.
   > Android tasks have already been created.
     This happens when calling android.applicationVariants,
     android.libraryVariants or android.testVariants.
     Once these methods are called, it is not possible to
     continue configuring the model.

The error seems to be in "subprojects" section but I need it. Not sure what to do at this point.
Comment: Have you tried cleaning the project and invalidating cache / restart Android Studio?
Comment: Just change order of google() and jcenter()
Comment: Hi, did you solve it? I have exactly the same problem, any help would be helpful, thx!
Comment: @mjrdnk try to run gradle cleanup task. I think that was what helped me.
Answer: Try Change order google() then jcenter() that should work


Sorting and taking average in textfile

Question: I have two text files like this:
File1.txt
Size   Iterations
3        45
5        6
7        50
1        34
5        56
1        4

File2.txt
Size   Iterations
3        5
5        6
7        6
1        3
5        6
1        4

I want to do two things first:
1) Sort the two files on the basis of size.
File1.txt
Size   Iterations
1        34
1        4
3        45
5        6
5        56
7        50

File2.txt
Size   Iterations

1        3
1        4
3        5
5        6
5        6
7        6

2) Once the files get sorted on the basis of size then I want to create a new file and store the average of all the iterations corresponding to each unique size number
like this:
Size  Average
1      3.5
3      5
5      6
7      6

I am new to MATLAB. Please guide me which functions to follow to achieve the above task.
Comment: I don't get how you produce the _Average_ values based on _Size_ and _Iterations_ !! or whether they are related or not!!
Comment: Are the rows tab separated or not?
Comment: @Mohammad I want to take the  average of all the iterations corresponding to each unique size number
Comment: So this would be (34+4+3+4)/4 which is equal to 11.5. You better edit your question.
Comment: @phyrox they are three space separated.
Answer: You can use this code:
%1-Sort everything
s1 = tdfread('File1.txt','   ');%Three space separation
[sorted_s1_size,sorted_s1_idx]=sort(s1.size,'ascend');
sorted_s1_iterations = s1.iterations(sorted_s1_idx);

s2 = tdfread('File2.txt','   ');
[sorted_s2_size,sorted_s2_idx]=sort(s2.size,'ascend');
sorted_s2_iterations = s2.iterations(sorted_s2_idx);

%2-Get the average

sizes = [sorted_s1_size;sorted_s2_size];
iterations = [sorted_s1_iterations,sorted_s2_iterations];

unique_sizes = unique(sizes);
avg_iterations = zeros(1,length(unique_sizes);
for i=1:length(unique_sizes)
  w_size = unique_sizes(i);
  w_idx=find(sizes==w_size);
  avg_iterations(i) = mean(iterations);
end

%4-Write the file
fid = fopen('output.txt','w');
for k=1:length(unique_sizes)
   fprintf(fid,'.2f\t%.2f\n',unique_sizes(i),avg_iterations(i));
end
fclose(fid);

You can optimize it removing the two sorting operations (as unique also sorts by id).
Answer: I presumed that the first raw in file1.txt and file2.txt do not exist. I mean those lines which contain ASCII characters.
clear all
a = load('file1.txt');
b = load('file2.txt');
c = [a;b]; % appends file2 below file1

[aa I] = sort(c(:,1)); % you can find sorted IDs in I
ids = unique(c(I,1));
ave = zeros(1,ids);
for i=1:length(ids)
    currentIds = I(c(I,1) == ids(i)); %boolean indexing in sorted IDs
    ave(i) = mean(c(currentIds,2));
end
disp([ids,ave'])

Comment: It works great. Can you please explain how the average is computed in this code.
Comment: This is pretty simple! Inside _for_ loop we have: a Group of indexes which belong to _i_th _Size_ is specified from vector _I_ which contains sorted indexes. Now indexes of rows of _i_th Size which exist in _currentIds_ leads us to calculate the mean value. This is possible by indexing _c_ matrix.

Sorting and taking average in textfile


Webform block: reload page with anchor link

Question: I have a webform shown in a block that appears at the bottom of my page.
If I select 'no redirect (reload current page)' when the form is submitted you are taken back to the top of the page and the confirmation message is shown above the form, so unless you scroll down it appears as if nothing happened.
If I select 'Custom redirect URL' and enter <code>[current-page:url]#my-form</code> when the form is submitted you do get taken down the page to the form only now the confirmation message is shown at the top of the page, so unless you scroll up you won't see it.
Is there a way to refresh the page, scroll down to my form and show the confirmation above it or do I have to use AJAX for this?
Answer: You can achieve that by using the Webform Ajax module

This module adds AJAX support to Webform (3.0 and above).
As a first step it focusses to simply add form AJAX paging and submit. Form submissions get ajaxified including prev/next pages. Especially for multipage forms, this leads to faster loading (less data transfer), better usability and finally smaller server load.
Comment: I thought as much, I'm just not a big fan off adding modules for functionality it's already provided and I just don't know how to use it properly. Thanks!


Groupby unique value in column, and join data in same row

Question: I have this kind of dataframe:

I want to groupby ID and get all the next columns info into the same row, and of course in each cell like this and add more packs if there are more rows for unique values:

so far i can get all other columns in just one as list, but would like to be in proper order like second picture
df1 = df.groupby('ID').agg({'Grade':lambda x:list(np.r_[x])})

thanks for the help
Answer: Try something like this:
df_out = (dfm := (df.set_index(['Name', 'ID', df.groupby('Name').cumcount()])
             .unstack()
             .sort_index(level=1, axis=1)))\
   .set_axis([f'{i}_{j}' for i,j in dfm.columns], axis=1)\
   .reset_index()

Output:
      Name    ID Class_0  Grade_0  Score_0 Class_1  Grade_1  Score_1 Class_2  Grade_2  Score_2 Class_3  Grade_3  Score_3
0  Gustavo  2222      LB      2.0     80.0      HD      3.0     90.0      CF      4.0     70.0     NaN      NaN      NaN
1    Maria  3333      AD      3.0     70.0      KD      4.0     70.0      LB      5.0     70.0      CF      7.0     80.0

Comment: columns names are not in order but I can fix that, works like a charm thank you so much


Views Group By with profile with aggregation and relationship

Question: I am looking for solution for following problem.
Problem:
I have "article" content type.
I have list of some users who are associated with different - 2 roles.
User having role "editor" can create articles. So editors type of user have created number of contents.
Now I need to display a list of featured articles on home page using Views-block with given conditions.

Every author who have created most articles, his block should come in top of list with his recent one article.
It should be followed by author name.
I will show top 10 articles of different - 2 authors with correct author ordering. I mean  author who have created most articles should come on top followed by rest of authors.

Note: In this block one author should come once with correct order.
Resolution:

I created views block with filter criteria where content type =
'article'.
I enabled aggregation.
I make relationship with User and in fields choose COUNT(DISTINCT
Content: Title) | Aggregation settings option.
I choose Query settings: Distinct.

I tried above possible solution but unable to get correct result. I am still getting duplicate result and also the order is not correct.
Answer: Consider using the Views Distinct module. From its project page:

Relationships or other joins in Views often create "duplicate" results. For example, a node with a field that has multiple values may show up in the View once per value in the multi-value field. It's frustrating, and the "DISTINCT" SQL query option in the Views UI does not actually solve the problem because the result row is technically distinct. This module aims to give a simple GUI method to remove or aggregate these "duplicate" rows.

Curious to hear if this helps to answer this question.


Is that sort order from subselect guaranteed?

Question: Is it guaranteed that the sort order from statement's
SELECT nr
FROM
(
    SELECT 1 AS nr FROM dual
    UNION
    SELECT 2 AS nr FROM dual
    UNION
    SELECT 3 AS nr FROM dual
);

result set is always
1
2
3

?
Comment: No, use ORDER BY to be sure.
Answer: No, this is not guaranteed.  SQL tables represent unordered sets.  SQL results sets are also unordered -- unless the code has an explicit ORDER BY.
With no ORDER BY, you will get the same three rows, but the values could be in any order.  I would strongly recommend that you do the following:
SELECT nr
FROM (SELECT 1 AS nr FROM dual
      UNION ALL
      SELECT 2 AS nr FROM dual
      UNION ALL
      SELECT 3 AS nr FROM dual
     ) x
ORDER BY nr;

Note that this uses UNION ALL rather than UNION.  UNION incurs overhead for removing duplicates -- something not needed for this data.
Answer: Use order by -- then it is guaranteed
SELECT nr
FROM
(
    SELECT 1 AS nr FROM dual
    UNION
    SELECT 2 AS nr FROM dual
    UNION
    SELECT 3 AS nr FROM dual
)a order by nr


How can I have custom content as last page?

Question: I have a view which shows nodes of 3 specific content types. The content shown is coming from the parent node with entity reference fields where the nodes can be selected to be shown in the view.
I was wondering how I could add custom content, or maybe a node to the end of a that view without having to select it on the parent, because this is always the same content.
What I want is like have the view display a node or some programmatically custom content. It should be there as last page. For example I have a view with 4 nodes, the pager should show 5 and have the 5th page be the node/content I want. I don't want to have to add it every time on the parent node with the entity reference field. It should be there by default.
Answer: Probably the easiest way to do this would be to add a footer to your view. If you are on the admin screen for your view, you should see options for Page Settings, Header, and Footer in the middle column.

If you "Add" content to the Footer area it will always output below your view content. There are several options including to display a rendered node.
Comment: Thank you for your reply! This could be a solution. This is not exactly what i want, what i want is like have the view display a node or some programatticaly custom content. It should be there as last page. For example i have a view with 4 nodes, the pager should show 5 and have the 5th item be the node/content i want. I dont want to have to add it every time on the parent node with the entity reference field. It should be there by default.
Answer: You can achieve this by creating your own views template file in themes/custom/MYTHEME_NAME/templates. See this documentation for naming conventions
https://api.drupal.org/api/drupal/core%21modules%21views%21views.theme.inc/group/views_templates/8.6.x
In my case, I am using the Views Bootstrap Module and wanted to change the template of a view which uses the Bootstrap Grid mode. So I copied views-bootstrap-grid.html.twig from the module's directory (/modules/contrib/views_bootstrap/templates) into my theme's template directory and renamed it to views-bootstrap-grid--companies--block.html.twig
Inside the template file, I added the needed html code:
{#
/**
 * @file views-bootstrap-grid.html.twig
 * Default simple view template to display Bootstrap Grids.
 *
 *
 * - columns: Contains rows grouped by columns.
 * - rows: Contains a nested array of rows. Each row contains an array of
 *   columns.
 * - column_type: Contains a number (default Bootstrap grid system column type).
 *
 * @ingroup views_templates
 */
#}
{%
  set classes = [
    'views-view-grid',
  ]
%}
{% if title %}

{{ title }}

{% endif %}

    {% for row in rows %}

        {{ row }}

    {% endfor %}

        MY CUSTOM TEXT


Unexplained exception thrown by calling deallocate from a custom allocator

Question: Visual Studio doesn't explain anything to me, it just breaks and sends me conveniently to the operator delete implementation....
Why is it unable to deallocate?
#include <iostream>

template<typename T>
struct Allocator
{
    using size_type = std::size_t;
    using pointer = T*;

    pointer allocate(size_type n)
    {
        return static_cast<pointer>(::operator new(n * sizeof(T)));
    }

    void deallocate(pointer p)
    {
        ::operator delete((void*)p);
    }
};

int main()
{
    Allocator<int> al;

    int a = 5;
    int* p = al.allocate(1);
    p = &a;
    al.deallocate(p);
}

Comment: So you deallocate a variable with automatic storage and wonder why it breaks?
Comment: That simple program you show *should* work just fine. Are you doing something you don't show us? If you enable more warnings do you get any?
Comment: @JoachimPileborg Apologies. Missed a few details. Edited.
Comment: When you do `p = &a`, it's the same as doing `int i = 5; i = 34;`  and then wonder why `i` no longer is `5`. You first make `p` point to some memory (that you allocate dynamically), then you make `p` point to some *other* memory, loosing the original pointer.
Answer: You are deallocating something else other than what you allocated.
You are allocating, assigning the result to p, then immediately overwrite the result with some other, random pointer, which you attempt to deallocate.
The reason for your crash should be obvious.
P.S. As far as Visual Studio goes, it correctly brings you to the line where the illegal memory access occured. Sadly, the state of modern technology is not yet to the point where you also get a detailed explanation of what exactly went wrong, at that point.
Comment: I am not sure it is a sad thing. The moment it happens, we all would be flipping burgers.


How do you pass a variable with the method name to @selector()?

Question: I need to pass a method name to @selector(method) inside a loop where the method is a value contained in an array.
[myButton addTarget:self action:@selector(method:)  forControlEvents:UIControlEventTouchDown];

How can I define a @selector() inside a loop an avoid having to hard code each @selector(method)? Can I pass in a string value?
Answer: You can use either NSSelectorFromString(), which maps an NSString to a SEL, or you can use sel_registerName(), which maps a char* to a SEL.


Showing different page layouts based on form data

Question: I'm trying to build a multi step form. Before the second step I have to process the data inserted in step one and render different layout and form fields based on the results.
I use "drupal_get_form" callback in _menu hooks to display the form, but I think I have to use a different approach, because I can't find a way to specify a template and\or HTML code this way.
What can I do? Thanks!
MENU DECLARATION:
<code>/**
 * Implementation of hook_menu().
 */
function clientform_menu() {
    $items['clientform/step1'] = array(
        'title' => "Estimate",
        'type' => MENU_CALLBACK,
        'access arguments' => array('access content'),
        'page callback' => 'drupal_get_form',
        'page arguments'=>array('clientform_step1'));

    return $items;
}

function clientform_step1($form, &$form_state){
    if(isset($form_state['values'])) {
        $currstep = $form_state['step'] + 1;
    }else {
        $currstep = 0;
    }

    $form_state['step'] = $currstep;
    $allsteps = getForm();
    $currform =  $allsteps[$currstep];

    return $currform;
}

function clientform_step1_submit($form, &$form_state){
    $form_state['storedvalues'][$form_state['step']] = $form_state['values'];
    if($form_state['step'] + 1 != getNumberOfSteps()) {
        $form_state['rebuild'] = TRUE;
    }else {

        //Reached end of multipage form

    }
}
</code>
Comment: Could you be more specific about what you want on the different pages of the form? Have you taken a look at webform and conditional fields? You might be able to do all of this via the UI.
Comment: @Andy each page of the wizard has a slightly different layout, namely button positions, divs... for now I manage to solve with #prefix and #suffix, hardcoding the layout in the form declaration, but I wonder if there is a better way, like plain html with some php inline (ex: ) in template files.
Answer: You can set a "theme callback" in a menu declaration, but that would only work if you had some way to distinguish which page/step the user is on.
The only other way I can think of would be to have some if/then statements in your form that check for what step the user is on, and alter the form how you need.
Comment: I'm a newbie of Drupal, can you provide me an example? I'll update my question with my menu declaration.
Answer: just an idea:
what if you split you form in 2 forms
The first form will be composed of the first 2 steps
Then you create a Rule which, on Form1 Submission, Elaborates the data and redirect the user to the second form.
If you don't need extremely complex thing, this should work just fine. I used this strategy in one case and it worked nicely. Not to mention that it is very flexible and can be modified also by inexpert users.
Comment: Mmmm, can I create a specific layout for the second form page based on previous processing by this way? I'm kind of newbie with Drupal :\
Comment: you can customize the layout with Display Suite and than you can do everything with CSS. I am not sure if you can have different layouts for the same content type, BUT if you choose a smart layout with Display then you have really no limits using CSS. You can enable CSS on different pages using many methods such as jQuery or conditionally including css using php...or use css injector module to inject different css depending on the page


Proof of Frullani's theorem

Question: How can I prove the Theorem of Frullani? I did not even know all the hypothesis that $f$ must satisfy, but I think that this are
Let $\,f:\left[ {0,\infty } \right) \to \mathbb R$ be a a continuously differentiable function such that $$
\mathop {\lim }\limits_{x \to \infty } f\left( x \right) = 0,
$$
and let $
a,b \in \left( {0,\infty } \right)$.
Prove that $$
\int\limits_0^{\infty}  {\frac{{f\left( {ax} \right) - f\left( {bx} \right)}}
{x}}dx  = f\left( 0 \right)\left[ {\ln \frac{b}
{a}} \right]
$$
If you know a more general version please give it to me )= I can't prove it.
Comment: The answers below are all good.  There  is an AMS article (1990) at: http://www.ams.org/journals/proc/1990-109-01/S0002-9939-1990-1007485-4/  and it's free//available!
Answer: We will assume $a<b$.
Let $x,y>0$. We have:
\begin{align*}
\int_x^y\dfrac{f(at)-f(bt)}{t}dt&=\int_x^y\dfrac{f(at)}{t}dt-
\int_x^y\dfrac{f(bt)}{t}dt\\
&=\int_{ax}^{ay}\dfrac{f(u)}{\frac ua}\frac{du}a-
\int_{bx}^{by}\dfrac{f(u)}{\frac ub}\frac{du}b\\
&=\int_{ax}^{ay}\dfrac{f(u)}udu-\int_{bx}^{by}\dfrac{f(u)}udu\\
&=\int_{ax}^{bx}\dfrac{f(u)}udu+\int_{bx}^{ay}\dfrac{f(u)}udu
-\int_{bx}^{ay}\dfrac{f(u)}udu-\int_{ay}^{by}\dfrac{f(u)}udu\\
&=\int_{ax}^{bx}\dfrac{f(u)}udu-\int_{ay}^{by}\dfrac{f(u)}udu.
\end{align*}
Since $\displaystyle\int_0^{+\infty}\dfrac{f(at)-f(bt)}tdt=\lim_{y\to +\infty}\lim_{x\to 0}
\int_x^y\dfrac{f(at)-f(bt)}{t}dt$ if these limits exist, we only have to show that the
limits $\displaystyle\lim_{x\to 0}\int_{ax}^{bx}\dfrac{f(u)}udu$ and $\displaystyle\lim_{y\to +\infty}\int_{ay}^{by}\dfrac{f(u)}udu$ exists, by computing them.
For the first, we denote $\displaystyle m(x):=\min_{t\in\left[ax,bx\right]}f(t)$ and
$\displaystyle M(x):=\max_{t\in\left[ax,bx\right]}f(t)$. We have for $x>0$:
$$m(x)\ln\left(\dfrac ba\right)\leq \int_{ax}^{bx}\dfrac{f(u)}udu\leq
M(x)\ln\left(\dfrac ba\right) $$ and we get $\displaystyle\lim_{x\to 0}\,m(x)=\lim_{x\to 0}\, M(x)=f(0)$ thanks to the continuity of $f$.
For the second, fix $\varepsilon>0$. We can find $x_0$ such that if $u\geq x_0$ then
$|f(u)|\leq \varepsilon$.
For $y\geq \frac{x_0}a$, we get $\displaystyle\left|\int_{ay}^{by}\frac{f(u)}udu\right|
\leq \varepsilon\ln\left(\dfrac ba\right) $.
We notice that we didn't need the differentiability of $f$.
Added later, thanks to Didier's remark: if $f$ has a limit $l$ at $+\infty$, then $g\colon
x\mapsto f(x)-l$ is still continuous and has a limit $0$  at $+\infty$. Then
$$\int_0^{+\infty}\dfrac{f(at)-f(tb)}tdt =
\int_0^{+\infty}\dfrac{g(at)-g(tb)}tdt =g(0)\ln\left(\dfrac ba\right) =
\left(f(0)-l\right)\ln\left(\dfrac ba\right).$$
Comment: +1. I like your solution. But you should replace lim m = lim M = 0 by lim m = lim M = f(0), to deduce that this part converges to f(0)log(b/a). // An extension is to assume that f has a limit at +oo, say f(+oo). Then your proof shows that the same result holds, with the limit (f(0)+f(+oo))log(b/a).
Comment: It is enough to assume that $f$ is continuous on $(0,\infty)$ and $\lim_{x\to 0+} f(x)=:f(0+)$ is finite (and of course, $f$ has a finite limit in $+\infty$). You can replace $f(0)$ by $f(0+)$ in the answer of @Giraudo.
Comment: @Davide Giraudo: awesome (+1)
Comment: I'm really stupid.
Comment: @Didier: yes, it's of course $f(0)$ and I have corrected it. Maybe I should add the extension.
Comment: Wait. What if $f(t) = 1, a = 2, b = 1$, so that the integral is of $1/t$? Then the RHS diverges, the LHS becomes $0\dot ln(2)$ = $0$. Am I being silly?
Comment: @FarazMasroor If $f(t)=1$, the difference $f(ax)-f(bx)$ vanishes.
Answer: The result is true under weaker assumptions than you state, but under your conditions, there is a cute proof using double integrals. (To be on the safe side, assume that $f$ is monotone, or at least that $f' \in L^1$. This will guarantee that we can change the order of integration.)
Let $D = \{ (x,y) \in \mathbb{R}^2 : x \ge 0, a \le y \le b \}$, and compute the integral
$$\iint_D -f'(xy)\,dx\,dy$$
in two different ways.
Firstly
\begin{align}
\iint_D -f'(xy)\,dx\,dy &= \int_a^b \left( \int_0^\infty -f'(xy)\,dx \right)\,dy \\ &= \int_a^b \left[ \frac{-f(xy)}{y}\right]^\infty_0\,dy \\
 &= \int_a^b \frac{f(0)}{y}\,dy = f(0)(\ln b - \ln a).
\end{align}
On the other hand,
\begin{align}
\iint_D -f'(xy)\,dx\,dy &= \int_0^\infty \left( \int_a^b -f'(xy)\,dy \right)\,dx\\
&= \int_0^\infty \left[ \frac{-f(xy)}{x} \right]_a^b\,dx \\
&= \int_0^\infty \frac{f(ax)-f(bx)}{x}\,dx.
\end{align}
Comment: (+1), but why do you need $f$ to be monotone? It's enough for $g=f'$ to be continuous, which is what the OP wrote (continuously differentiable)
Comment: Can we use this method to find the integral: for $a <b$ $$\int_0^{\infty} \frac{\cos(ax)- \cos(bx)}{x} dx$$?
Answer: There is a claim that is slightly more general.

Let $f$ be such that $\int_a^b f$ exists for each $a,b>0$. Suppose that $$A=\lim_{x\to 0^+}x\int_{x}^1 \frac{f(t)}{t^2}dt\\B=\lim_{x\to+\infty}\frac 1 x\int_1^x f(t)dt$$ exist.
Then $$\int_0^\infty\frac{f(ax)-f(bx)}xdx=(B-A)\log \frac ab$$

PROOF Define $xg(x)=\displaystyle \int_1^x f(t)dt$. Since $g'(x)+\dfrac{g(x)}x=\dfrac{f(x)}x$ we have $$\int_a^b \frac{f(x)}xdx=g(b)-g(a)+\int_a^b\frac{g(x)}xdx$$
Thus for $T>0$
$$\int_{Ta}^{Tb} \frac{f(x)}xdx=g(Tb)-g(Ta)+\int_{Ta}^{Tb}\frac{g(x)}xdx$$
But
$$\int_{Ta}^{Tb}\frac{g(x)}xdx-B\int_a^b \frac{dx}x=\int_a^b\frac{g(Tx)-B}xdx$$
Thus $$\lim_{T\to+\infty}\int_{Ta}^{Tb}\frac{g(x)}xdx=B\log\frac ba$$ so
$$\lim_{T\to+\infty}\int_{Ta}^{Tb}\frac{f(x)}xdx=B\log\frac ba$$
It follows, since $$\int_1^T\frac{f(ax)-f(bx)}xdx=\int_{bT}^{aT}\frac{f(x)}xdx+\int_a^b \frac{f(x)}xdx$$ (note $a,b$ are swapped) that $$\int_1^\infty \frac{f(ax)-f(bx)}xdx=B\log\frac ab+\int_a^b \frac{f(x)}xdx$$
Let $\varepsilon >0$, $\hat f(x)=f(1/x)$. Then $$\int\limits_\varepsilon ^1 {\frac{{f\left( x \right)}}{x}dx}  = \int\limits_1^{{\varepsilon ^{ - 1}}} {\frac{{\hat f\left( x \right)}}{x}dx} $$ and $$x\int\limits_x^1 {\frac{{f\left( t \right)}}{{{t^2}}}dt}  = \frac{1}{{{x^{ - 1}}}}\int\limits_1^{{x^{ - 1}}} {\hat f\left( t \right)dt}  = g\left( {{x^{ - 1}}} \right)$$
So $\hat f(t)$ is in the hypothesis of the preceding work. It follows that $$\lim_{T\to+\infty}\int\limits_1^T {\frac{{\hat f\left( {x{a^{ - 1}}} \right) - \hat f\left( {x{b^{ - 1}}} \right)}}{x}} dx = A\log \frac ba + \int\limits_{{a^{ - 1}}}^{{b^{ - 1}}} {\frac{{\hat f\left( x \right)}}{x}dx} $$
and by a change of variables $x\mapsto x^{-1}$ we get $$\int\limits_0^1 {\frac{{f\left( {ax} \right) - f\left( {bx} \right)}}{x}} dx = A\log \frac ba - \int\limits_a^b {\frac{{f\left( x \right)}}{x}dx} $$ and summing gives the desired $$\int\limits_0^\infty  {\frac{{f\left( {ax} \right) - f\left( {bx} \right)}}{x}} dx = \left( {B - A} \right)\log \frac ab$$
This is due to T.M. Apostol.
OBS By L'Hôpital, if the limits at $x=0^+$ and $x=+\infty$ exist, they equal $A$ and $B$ respectively.
Comment: Sorry for the (absurdly) late comment, but $ g $ may not be differentiable, so your justification of $\int_{a}^{b}f(x)/x\,dx=g(b)-g(a)+\int_{a}^{b}g(x)/x\,dx $, I think, is not quite right. It can be made more accurate, though. We have $\int_{a}^{b} g(x)/x\,dx=\int_{a}^{b} x\,g(x)\,d(-1/x)$, the last integral being Riemann-Stieltjes. Now, by integration by parts, $\int_{a}^{b} g(x)/x\,dx=g(a)-g(b)+\int_{a}^{b}x^{-1} \,d(x\,g(x))$. Now, invoke Theorem 7.26 (Apostol's Analysis) to get $ \int_{a}^{b} x^{-1}\,d(x\,g(x))=\int_{a}^{b} f(x)/x\,dx $.
Comment: @user149844 True. If $f$ is continuous then we're good.
Answer: The following theorem is a beautiful generalization of Frullani's integral theorem.
Let $f(x)-f(\infty)=\sum_{k=0}^{\infty}\frac{u(k)(-x)^k}{k!}$ and $g(x)-g(\infty)=\sum_{k=0}^{\infty}\frac{v(k)(-x)^k}{k!}$

$Theorem1$:
Let f, and g be continuous function on $[0,\infty),$ assume that $f(0)=g(0)$ and $f(\infty)=g(\infty)$. Then if $a,b>0$
$$\lim_{n \to 0+}I_{n}\equiv \lim_{n \to 0+} \int_{0}^{\infty}x^{n-1}\lbrace f(ax)-g(bx) \rbrace dx=\lbrace f(0)-f(\infty)\rbrace \bigg \lbrace \log \bigg(\frac{b}{a} \bigg)+\frac{d}{ds}\bigg(\log\bigg(\frac{v(s)}{u(s)}\bigg) \bigg)_{s=0} \bigg \rbrace$$

if $f(x)=g(x),$ this theorem reduces to the Frullani's  theorem
$$\int_{0}^{\infty} \frac{f(ax)-f(bx)}{x}dx=\lbrace f(0)-f(\infty) \rbrace \log \bigg(\frac{b}{a} \bigg).$$
Let prove $Theorem1$, To do this we need to use Ramanujan's master theorem , Which lies in the fact that

$$\int_0^\infty x^{n-1}\sum_{k=0}^\infty \frac {\phi(k)(-x)^k}{k!}dx= \Gamma(n)\phi(-n).$$

Applying the Master Theorem with $0<n<1,$ we find
$$I_n=\int_{0}^{\infty} x^{n-1}( f(ax)-g(bx))dx=\int_{0}^{\infty} x^{n-1}( \lbrace f(ax)-f(\infty) \rbrace-\lbrace g(bx)-g(\infty) \rbrace) dx$$
$$=\Gamma(n)\lbrace a^{-n}u(-n)-b^{-n}v(-n) \rbrace$$
$$=\Gamma(n+1) \bigg \lbrace \frac{a^{-n}u(-n)-b^{-n}v(-n)}{n} \bigg \rbrace
$$
Letting $n$ tend to $0$, using L'Hospital's Rule  and fact that $u(0)=v(0)=f(0)-f(\infty).$  we deduce that
$$\lim_{n \to \infty}I_n=\lim_{n \to \infty} \bigg \lbrace \frac{b^nv(n)-a^nu(n)}{n} \bigg \rbrace$$
$$=\lim_{n \to \infty} \lbrace b^nv(n) \log b+ b^nv'(n)-a^nu(n)\log a-a^nu'(n)\rbrace$$
$$= \lbrace f(0)-f(\infty) \rbrace \log \bigg(\frac{b}{a} \bigg)+v'(0)-u'(0)$$
$$=\lbrace f(0)-f(\infty) \rbrace \bigg \lbrace \log \bigg(\frac{b}{a} \bigg)+\frac{d}{ds}\bigg(\log\bigg(\frac{v(s)}{u(s)}\bigg) \bigg)_{s=0} \bigg \rbrace$$
Comment: This is incredible! May I ask is there a source for this? I'd like to know about some related analysis.
Answer: You might be interested in an approach to Frullani's theorem I came across online. It is proven for the Lebesgue integral and the Denjoy-Perron integral. We are looking to prove the integral
\begin{equation*}
\int^{\infty}_{0}\frac{f(ax)-f(bx)}{x}dx=A\ln(\frac{a}{b})
\end{equation*}
where $A$ is a constant. For the Lebesgue integral, the substitution $x=e^t,~\alpha=\ln(\alpha),~\beta=\ln(b)$ is used to get
\begin{equation*}
\int^{+\infty}_{-\infty}\{ f(e^{t+\alpha})-f(e^{t+\beta})\}dt=A(\alpha-\beta)
\end{equation*}
which is equivalent to Frullani's theorem. Then verifying the integral
\begin{equation*}
\int^{+\infty}_{-\infty}\{ g(x+\alpha)-g(x+\beta)\}dx=A(\alpha-\beta)
\end{equation*}
for a Lebesgue integrable function $g:\mathbb{R}\to\mathbb{R}~\forall \alpha,\beta\in \mathbb{R}$ will suffice. This is proved by setting an integrable function on the real line
\begin{equation*}
h_{\alpha}(x)=g(x+\alpha)-g(x)~\forall\alpha\in\mathbb{R}
\end{equation*}
and applying the Fourier transform (as well as a little manipulation).
The Denjoy-Perron integral is used instead of the Lebesgue integral to avoid the problem of a locally integrable function $f:\mathbb{R}\to\mathbb{C}$ admitting a derivative $f'(x)~\forall x\in\mathbb{R}$ without $f'$ being locally integrable.
The case for the Denjoy-Perron integral is proved in a similar fashion.
Check out the following paper by J. Reyna
http://www.ams.org/journals/proc/1990-109-01/S0002-9939-1990-1007485-4/S0002-9939-1990-1007485-4.pdf
Answer: On the assumption that $f$ is differentiable and $a,b>0$, an application of Fubini's theorem gives the result.

$$\int_{(0,\infty)} \frac{f(ax)-f(bx)}{x} dx$$
$$=\int_{(0,\infty)} \int_{[bx,ax]} f'(y) \frac{1}{x} dy dx$$
Let $0<bx \leq y \leq ax$.
$$=\int_{(0,\infty)} \int_{\frac{1}{a} y}^{\frac{1}{b} y} f'(y) \frac{1}{x} dx dy$$
$$=\int_{(0,\infty)} f'(y) \ln (\frac{a}{b}) dy$$
$$=(f(0)-f(\infty)) \ln \frac{b}{a}$$
Comment: Can we use this method to find the integral: for  $a < b$
$$ \int_0^{\infty} \frac{\cos(ax)- \cos(bx)}{x} dx$$?
Answer: The following is just a speeded-up version of the answer by Davide Giraudo.

Let $f(x)$ be a real-valued function defined for $x\geq 0$.
  Suppose that $f(x)$ is Riemann integrable on every bounded interval
  of nonnegative real numbers,
  that $f(x)$ is continuous at $x=0$,
  and that the limit $f(\infty):=\lim_{x\to\infty} f(x)$ exists
  (as a finite quantity).
  If $a>0$ and $b>0$, then the integral
  \begin{equation*}
\int_{\,0}^{\,\infty} \frac{f(ax)-f(bx)}{x} dx \tag{1}
\end{equation*}
  exists and is equal to $\bigl(f(\infty)-f(0)\bigr)\,\ln(a/b)$.

The assertion that the integral $(1)$ exists means
that the following limit exists,
\begin{equation*}
\lim_{l\to0,\,h\to\infty} \int_{\,l}^{\,h} \frac{f(ax)-f(bx)}{x} dx
\end{equation*}
where $l$ approaches $0$ independently of $h$ approaching $\infty$,
and that this limit is the integral $(1)$.
Proof.$\,$ Assume that $a\geq b\,$; this does not lose us any generality.
Let $0<l<h\,$.
The change of variables $ax=by$ shows that
\begin{equation*}
\int_{\,l/a}^{\,h/a}\frac{f(ax)}{x}dx
        ~=~ \int_{\,l/b}^{\,h/b}\frac{f(by)}{y}dy~,
\end{equation*}
so we have
\begin{align*}
\int_{\,l/a}^{\,h/a}\frac{f(ax)-f(bx)}{x}dx
&~=~ \int_{\,l/b}^{\,h/b}\frac{f(bx)}{x}dx
        ~-~ \int_{\,l/a}^{\,h/a}\frac{f(bx)}{x}dx \\
&~=~ \int_{\,h/a}^{\,h/b}\frac{f(bx)}{x}dx
        ~-~ \int_{\,l/a}^{\,l/b}\frac{f(bx)}{x}dx~;
\end{align*}
we write the difference in the second line as $I(h) - I(l)$.
Let $\varepsilon>0$.
There exists $l_\varepsilon>0$ such that
$f(0)-\varepsilon\leq f(bx)\leq f(0)+\varepsilon$
for $0\leq x\leq l_\varepsilon/b$.
Since by assumption $l/a\leq l/b$ for every $l>0$, we obtain the estimate
\begin{equation*}
\int_{\,l/a}^{\,l/b}\frac{f(0)-\varepsilon}{x}dx
        ~\leq~ I(l)
        ~\leq~ \int_{\,l/a}^{\,l/b}\frac{f(0)+\varepsilon}{x}dx
        \qquad\qquad \text{for $0<l\leq l_\varepsilon$}~,
\end{equation*}
that is,
\begin{equation*}
\bigl(f(0)-\varepsilon\bigr)\,\ln\frac{a}{b}
        ~\leq~ I(l)
        ~\leq~ \bigl(f(0)+\varepsilon\bigr)\,\ln\frac{a}{b}
        \qquad\qquad \text{for $0<l\leq l_\varepsilon$}~.
\end{equation*}
In other words, $I(l)$ converges to $f(0)\,\ln(a/b)$ as $l$ approaches $0$.
In the same way we see that $I(h)$ converges to $f(\infty)$
as $h$ approaches $\infty$.$\,$ Done.
Answer: $$F(a) = \int_0^\infty \frac{f(ax)}x dx, $$
$$F'(a) = \int_0^\infty f'(ax) dx = \frac{f(\infty) - f(0)}{a}.$$
$$\Rightarrow F(a) = (f(\infty) - f(0)) \ln a + C_1.$$
Similarly
$$F(b) = (f(\infty) - f(0)) \ln b + C_2$$
Here $C_1 = C_2$ since basically function are the same. Subtracting gives
$$F(a) - F(b) = (f(\infty) - f(0)) \ln (a/b).$$
I think we can prove it by splitting the integral into two, treat each part as functions of a and b respectively, differentiate wrt a and b respectively (after this step finding the integral is trivial). This will be followed by the integration of the obtained functions wrt to a and b. The constants of integration will be the same as the function essentially remains the same, only the variables are changed. So on subtraction, the constants get cancelled, and hence the result! At least for an undergraduate, this should be fine.
Comment: Please format your answer using mathjax.
Comment: Seems I have to learn it.
Comment: I have edited your post, you can click "edit" and see what I did.
Comment: Thank you Arctic Char
Answer: Another generalization is as follows:
view formula
I proved it here.
Stackexchange won't let me post pictures, so here is the LaTeX version:
$$\int_0^\infty \frac{qf(qx)}{g(qx)} - \frac{pf(px)}{g(px)}dx
 = \int_0^\infty \frac{qf(qx)g(px)-pf(px)g(qx)} {g(qx)g(px)}dx =E(f)\cdot\log\frac{q}{p}$$
Answer: This is not an answer but motivated by the question
Can we use this method to find the integral: for $a<b$
$$\int_0^{\infty} \frac{\cos(ax)- \cos(bx)}{x} dx$$
by user008.
I try to use Laplace method to prove it. Since we have
\begin{align}
\mathcal{L_s}\left[\frac{f(t)}{t}\right]_{s=0}=\int_0^{\infty}F(s)ds
\end{align}
then
\begin{align}
\int_0^{\infty} \frac{\cos(ax)- \cos(bx)}{x} dx&=\int_0^{\infty}\left[\frac{s}{s^2+a^2}-\frac{s}{s^2+b^2}\right]ds\\
&=\frac12\int_0^{\infty}\frac{d(s^2+a^2)}{s^2+a^2}-\frac12\int_0^{\infty}\frac{d(s^2+b^2)}{s^2+b^2}\\
&=\left.\frac12\ln{\frac{s^2+a^2}{s^2+b^2}}\right|_0^\infty\\
&=\ln{\frac{b}{a}}
\end{align}
However, when I continue to show the Frullani's theorem, I was stucked...
\begin{align}
\int\limits_0^\infty{\frac{{f\left({ax} \right) - f\left( {bx} \right)}}{x}} dx&=\int\limits_0^\infty\mathcal{L_s}[f(ax)]-\mathcal{L_s}[f(bx)]ds\\
&=\int\limits_0^\infty\int\limits_0^\infty\left(f(ax)e^{-sx}-f(bx)e^{-sx}\right)dxds\\
&=\int\limits_0^\infty\int\limits_0^\infty\left(f(u)e^{-su/a}-f(u)e^{-su/b}\right)dsdu\\
&=\int\limits_0^\infty f(u)\left(\frac{a^2-b^2}{u}\right)du\\
&=(a^2-b^2)\int\limits_0^\infty\frac{f(u)}{u}du\\
&\overset{?}=(a^2-b^2)\lim_{\epsilon\to0^+}\int_0^\infty\frac{f(\epsilon u)}{u}du~\ldots...
\end{align}
Can anyone please help with what is next?
Thanks a lot :-)!

Proof of Frullani's theorem


Is there a "standard" or "typical" drum kit layout?

Question: I am dipping my toes in the water of getting a "real" drum kit -- by drumming standards, it's still pretty crap since it's (basically) the Alesis DM6 entry level electronic drum kit. But one thing I didn't even consider when making the leap is that I don't know where to properly place the drum heads and cymbals.
I am ashamed to admit I learned everything I know about drumming from playing Rock Band, and this includes the default layout of the drums and cymbals. I know, I know, but ... I'm trying to figure this stuff out as I go!
This is the default Rock Band kit layout, with 4 pads and 3 cymbals in a particular arrangement perhaps more determined by mass manufacturing than anything else:

Now if we look at this picture of a real, actual drum set …

… the default Rock Band drum/cymbal layout is maybe in the ballpark. But it seems there are important differences when you have a fully positionable set of drums. Is this picture representative of a "standard" or "typical" drum kit layout? (Yes, I realize that layout is of course a personal preference at some level, and there will be variance.)
Based on what I've seen, these positionable electronic drums should not mimic the default Rock Band setup, but perhaps should be more like so?

That is:

Snare between your legs and significantly lower than the toms
Hi-hat to the left of the snare, so I am now playing snare "crossed over" with my left hand and hihat with my right (as a righty)
Two toms paired above, with a lower ("floor") tom to the far right
Crash and Ride cymbals to the right and significantly higher than the toms?

I'm not looking for a perfect layout, just seeking advice on what's typical or standard in drumming. I want to break any bad positioning habits I might have accidentally developed from learning on the original Rock Band kit as I progress to the brave new world of real-ish electronic drum kits.
Comment: You didn't mention: are you right- or left-handed? Left handed people can invert all the positions or learn to play "regular"
Comment: I did actually mention it "as a righty"
Comment: You should go here. I've learned a lot from these videos http://vicfirth.com/education/drumset/houghton_beginner_lessons.php
Comment: It's not "standard", but worth seeing :)  http://www.youtube.com/watch?v=Hxe-SWxDEcw
Comment: @thechaz I will see your video link and raise you http://www.youtube.com/watch?v=ItZyaOlrb7E
Comment: Surely an instant classic! So how long have you been playing drums?
Also, look into how Carter Beauford sets his up... he's a lefty, more or less
Comment: In practice there is no real Standard set up, because you need to adjust the positioning of each individual element to suit your person. Each kit is unique to its user. that's the way I see to be honest.
Comment: *"Hi-hat to the left of the snare, so I am now playing snare "crossed over" with my left hand and hihat with my right (as a righty)"* - Note that some drummers play "open" style, where they play the hi-hat primarily with their left hand and snare with their right, with arms/sticks *not* crossed. (The hi-hats are still on the left.) Both left- and right-handed drummers do this. (It's not common, but it's not obscure either.)
Answer: Your description at the end is pretty close to the default (assuming right handed) for a rock kit, which is the most commonly used setup. There are other standard kit setups such as Jazz Kits see @Eric K's answer for a description of a Jazz kit.
So for a "standard" rock kit you'd have:

Snare between your legs usually just above knee height on your left
Hi hat above the snare - as you say so you can play crossed over
Two middle toms higher in front of you - both at same height, usually around chest height when sitting
Floor tom to your right - probably about same height as snare drum
Ride to the right of your kit
Crash positioning is your preference but usually if you have one you have it on the left next to the hi-hat. This gives you easy access and makes the kit look a little balanced.
All the cymbals are usually at shoulder height or above when seated

Also you'll have the middle toms and snare angled slightly towards with the cymbals at a much more aggressive angle towards you.
The positioning & height of the toms allows for good runs up and down the kit and is somewhat in line with their relative positions on a musical score - or that's how I see them when I look at a score.
This is a good visual representation of the heights & positions:

Once drummers get more experienced you'll see more crash, splash etc. cymbals of various sizes and other bits and pieces popping up on their kits but the above is the usual starting point for a rock kit.
Comment: I can't say I've ever sat at a kit where it has just one crash and it's on the right. As you're usually keeping time with the high hat you want to be able to move back to the high hat from the crash as quickly/smoothly as possible. And being a righty most of the time you'll be hitting the crash with your right hand.
Comment: I think if your just starting out you have too many drums. You want to focus on timing when you first start out and not get tempted to play around with the rest of the set. So you really should just have a snare, base drum, 1 top tom, 1 floor tom & 1 ride cymbal to your right. As you get comfortable with time then start adding more pieces. Maybe in this order. Crash, hi-hat, & then another tom.
Comment: @Jeff I think the reason the crash was on the right in Rock Band is partially ergonomics (hihat and snare are already the left half of the kit, and fills wouldn't work well if the crash was on the blue pad) and partially history (Drummania, the well-established Japanese game which definitely inspired Rock Band, combined the ride and crash as one pad on the right. It worked surprisingly well).
Comment: interesting how the Rock Band cymbals put the crash by default on the "other side" with the ride (the right), but you're correct that many pictures of drumkits and drummers show crash on the same side as the hihat (the left). How common is it to put crash on the right, as a preference, in your experience?
Comment: +1 The only thing I'd add is that the angle of the snare drum can vary significantly depending on how you hold the stick with your left hand: if you use matched grip, the snare should be more-or-less level, but if you use traditional grip, the snare should be angled more. Getting the angle correct for your grip will make rim shots much easier.
Comment: +1 But I need to mention that putting the cymbals at "shoulder height or above" can result in very fast fatigue when playing. I've found the easiest thing to do is get your drums set up comfortably and get your cymbals set up fairly low so you can be as efficient as possible - obviously you need to be careful with the hi-hat, too low and you'll be slapping your sticks all the time!
Comment: I often have only one crash set up, and I usually have it on the right. I tend to use my ride a lot though, even though I play rock/metal. I will often put the ride in the middle over the toms, and the crash on the right. That way, both the crash and the hi-hat are easy to reach from the ride. The important thing is to put things where you can reach them based on how you usually play.
Answer: I've played drums for 35 years so a few thoughts that may (or not!) help:

don't forget the only real reason you traditionally cross your hands to play the hi-hat, is the need to put the pedal under the left foot. If you have a remote pedal like in an electronic kit (and acoustic kits as an add-on) you can put it anywhere.  Some big kits have 2 hi-hats, one on the right.  Also, a common mistake: allow some height (say 6 inches or more) between hi-hat and snare if you're finding your hands/sticks are hitting each other when crossed over.
traditional 70's and 80's acoustic rock kits had high crash cymbals and deep angled toms for show, these days toms are less deep and less angled (almost flat), and lower to be as near to snare as possible, to allow faster rolls around the kit.
modern rock kit cymbals (real ones) are lower, perhaps roughly around shoulder height.  This is to allow faster rolls around the kit, but also to reduce the risk of breaking sticks (from hitting them edge-on) and breaking cymbals (which should ideally by hit by a downward sweeping motion). So, if acoustic drummers have no good reason for high cymbals don't think electronic ones have to either. Also, you want your crashes as easy to reach as possible as you'll use them loads, don't tuck them too far away so you have to reach and slow you down.
So, in conclusion, even heavy metal drummers on acoustic kits are moving towards lower, closer, flatter kits, to allow for faster (and easier) playing so there's every good reason to do that with an electronic kit.  Just make your layout as comfortable as possible! Cheers, Steve.
Comment: On point 1), [here's a good video](https://www.youtube.com/watch?v=4nR49qEdONs) I've seen that goes over the implications of putting your hi-hat on the right side of your kit.
Answer: The "standard" kit setup pictured in @DEfusion's answer is optimized for a right-handed drummer playing primarily rock songs.  The snare and hi-hat are the two most easily accessible pieces with the primary crash  (closest to the hi-hat) also within easy reach for accents.  The rest of the drums fill out from there in order of utilization.
If, however, you wanted to play something more ride-heavy (like jazz) you might prefer a slight modification to remove the middle tom and bring the ride cymbal in closer...something like this:

Basically, the idea is to keep the pieces of the kit that you'll strike the most within easy reach and then build the rest of the kit out from there. An efficient drumset lets the music and creativity flow freely!
Comment: @Jeff: Most cymbal packs come with two crashes, a ride, and the hi-hats
Comment: apparently the "standard" generally means **four** cymbals instead of three? That is, there are two crash cymbals, one on the left, one on the right?
Comment: I would agree with @The-Chaz that defining a standard kit probably depends on what you can buy in a package deal at a music store. I think the idea behind having two crash cymbals is that you have the leftmost crash for easy accents from riding on the hi-hat and the rightmost crash for accents coming off the ride cymbal or to cap off a tom fill. With this setup in mind, most rock drummers will put their medium crash (shorter decay) on the left and their loud crash (long decay, bigger volume) on the right. On the jazz kit pictured above, it looks like the bigger crash is on the left.
Answer: Apparently, most standard drum kits have four cymbals, not three. That's something I was missing. Quoting from another site I asked this on, which has both drummers and gamers:

the kit you've linked in the top pic is what I'd consider extremely barebones. Here's what I consider a pretty basic drumkit:

In most anything but a barebones drum kit, you're going to have four cymbals: the hi hat on the far left, the ride cymbal on the right, and two crash cymbals above, left and right. So it's completely natural to have a crash cymbal on your upper right.

and

A drum set with a single crash typically is either a jazz kit or a travel kit. It works for jazz because you don't do a lot of crashes and milking a smooth sizzling sound out of the hi-hat can be used for a similar effect.
In those setups the crash is between the ride and hi-hat because it allows you to use it as a transition between the two, and also because when playing faster tempo'd songs it would be very difficult to go from a right-positioned crash back to the left-positioned hi-hat. This isn't as noticable on a Rock Band kit because it's so much smaller, but a real kit might have 3 or more feet between the crash and the hi-hat - not insurmountable distance to move your arm.

... and thus there are typically two crash cymbals, one on the left, one on the right.
Comment: I wouldn't put that right-hand crash cymbal as far to the right as in your diagram. If using two crashes, I put the left one roughly where that diagram shows it, and the right one sort of between the "medium" tom and the ride - higher than and partially overlapping both. (Looks like the one in the photograph is roughly what I mean.)
Answer: You're almost right. The typical layout is like in the last picture you posted, except for the crash. You'd typically put that on the left. On your picture, it would be above the hihat, and to the left of the tom. That's just on your picture. In reality (in 3D), it would be higher than your tom, sort of mirrored by your ride cymbal (but a little higher maybe, depending on how low you put your ride - I put mine fairly low).
This makes it easier to come back to your hihat when you hit your crash. The distance for your right hand to travel would be less.
Then, when you add more cymbals (not always that easy with digital drums), you sort of put them where you want: in the middle, to the right but higher than the ride, etc.
I have a Roland TD-9K, just like this one. My cymbals are a little lower than in the image, but that's personal preference.
Answer: I agree the Rock Band setup is odd.  The hi-hat should really be red instead of yellow.  I moved the yellow cymbal (hi-hat) to the left of the red drum (snare).  I play it with my hands crossed over like a real drummer would. (I have the ION drum set which allows you more flexibility).  Messes with your mind a little at the beginning.  Probably couldn't have learned it that way since it no longer matches the order on the TV screen, but I already have the muscle memory.
I also agree the Rock Band blue(ride) and Green(crash) cymbals are backwards. I didn't bother to switch those, but I did move the blue(ride) to the left of the toms and Green (crash) between the toms so they are at least in the normal position for cymbals.  p.s. besides switching them, the crash should really be yellow.  Only if they added a second crash should it be green.
Hey, if I was still in high-school maybe I would be a real drummer.  But I'm 47 and love to hang with my 16yr old on Rock Band.  Most teens don't even want to be with their parents....
Answer: For rock the standard kit (depending on the era as I believe it changes all the time)is bass drum, snare drum, high tom, low tom, floor tom, high hat, high crash, low crash/ crash ride and ride cymbal.
Answer: At the end of the day it is what you're comfortable with, what you can afford, or  what 'looks' good. Back in the 80's when I played with goth/punk band Legion (UK), I used to have a 10 piece, which was a standard right hand set-up 5 piece, with an additional two rack mounted small toms (left) and a raised floor tom (right) plus two timbale drums mounted above the central toms. As for my ride cymbal, always directly above my hi-hats, with crash/china placed anywhere else - well I am a leftie. I actually did use all the drums (lots and loud), yet as time went by, I have slimmed right down to a small size irregular 5 piece (with no floor toms). It is unusual, but it works for me, looks pretty cool, and fits in the boot of any car! In fact as a recent development, I have adapted to lead vocals for even less to cart around!! Cheers guys. Whatever you play 'Keep Rocking'!!
Answer: Depends entirely upon what you want to do. For the music I play (and where I'm at now as a person, as opposed to 20-30 years ago when I first started) I only use a 3 piece (bass drum, snare, floor tom with a hihat and a few cymbals) because I'm comfortable on it. On slight occasion I will use one mounted tom for some color but (blues, funk, jazzy) styles require more rhythm that color so its what I go with. Your mileage may vary but be proficient at what you do decide to go with. Nothing worse than a crappy drummer with a massive setup. Cheers!


Create a table with the data read from XML file into word document using Open XML

Question: I am trying to read the data from XML file and would like to generate the table in word document populated with the same  data. I am using below XML file and c# code to do the same.
I am using below code to create the table in word document
class DocumentCreation :IDisposable
{
    private MemoryStream _ms;
    private WordprocessingDocument _wordprocessingDocument;

    public DocumentCreation()
    {
        _ms = new MemoryStream();
        _wordprocessingDocument = WordprocessingDocument.Create(_ms, WordprocessingDocumentType.Document);
        var mainDocumentPart = _wordprocessingDocument.AddMainDocumentPart();
        Body body = new Body();
        mainDocumentPart.Document = new Document(body);
        ApplyHeader(_wordprocessingDocument);
        InsertTable(_wordprocessingDocument);
    }

    private void InsertTable(WordprocessingDocument wordprocessingDocument)
    {
        string xmlFile = @"C:\wordDoc\movies.xml";
        MainDocumentPart mainPart = wordprocessingDocument.MainDocumentPart;

        // How to read the XML and create a table in word document filled with data from XML
    }

    public static void ApplyHeader(WordprocessingDocument doc)
    {
        // Get the main document part.
        MainDocumentPart mainDocPart = doc.MainDocumentPart;

        HeaderPart headerPart1 = mainDocPart.AddNewPart<HeaderPart>("r97");
        .......
        ......
        ......
    }
    public void AddBulletList(List<Run> runList)
    {
        .......
        .......
     }
  }

below is where i am calling above class
   static void Main(string[] args)
    {

        string fileToCreate = @"C:\wordDoc\test.docx";

        if (File.Exists(fileToCreate))
            File.Delete(fileToCreate);

        var writer = new DocumentCreation();
        List<string> fruitList = new List<string>() { "This is bulleted point 1", "This is bulleted point 2", "This is bulleted point 3" };

        writer.AddBulletList(fruitList);
        writer.SaveToFile(fileToCreate);
    }

I am looking for a way to create a table in word document with populated data from above XML document.
Comment: would any one please suggest any idea or any other way to achieve this solution
Comment: Did you share precisely the XML that you are trying to insert into the custom XML part? What you posted is malformed, because the opening `` tag is missing. Further, can you elaborate on what you are trying to achieve? You are merely creating a custom XML part into which you insert some XML. How does that relate to your question about how to create a table?
Comment: @ThomasBarnekow i modified my question , hope it will be clear now
Answer: What you likely want is an Open XML Table (w:tbl element) like the following:
<w:tbl xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
  <w:tr>
    <w:tc>
      <w:p>
        <w:r>
          <w:t>Name</w:t>
        </w:r>
      </w:p>
    </w:tc>
    <w:tc>
      <w:p>
        <w:r>
          <w:t>Released</w:t>
        </w:r>
      </w:p>
    </w:tc>
  </w:tr>
  <w:tr>
    <w:tc>
      <w:p>
        <w:r>
          <w:t>Crash</w:t>
        </w:r>
      </w:p>
    </w:tc>
    <w:tc>
      <w:p>
        <w:r>
          <w:t>2005</w:t>
        </w:r>
      </w:p>
    </w:tc>
  </w:tr>
  <w:tr>
    <w:tc>
      <w:p>
        <w:r>
          <w:t>The Departed</w:t>
        </w:r>
      </w:p>
    </w:tc>
    <w:tc>
      <w:p>
        <w:r>
          <w:t>2006</w:t>
        </w:r>
      </w:p>
    </w:tc>
  </w:tr>
  <w:tr>
    <w:tc>
      <w:p>
        <w:r>
          <w:t>The Pursuit of Happiness</w:t>
        </w:r>
      </w:p>
    </w:tc>
    <w:tc>
      <w:p>
        <w:r>
          <w:t>2006</w:t>
        </w:r>
      </w:p>
    </w:tc>
  </w:tr>
  <w:tr>
    <w:tc>
      <w:p>
        <w:r>
          <w:t>The Bucket List</w:t>
        </w:r>
      </w:p>
    </w:tc>
    <w:tc>
      <w:p>
        <w:r>
          <w:t>2007</w:t>
        </w:r>
      </w:p>
    </w:tc>
  </w:tr>
</w:tbl>

The above w:tbl is created from your XML by the following CanCreateTableFromXml unit test, which simply calls the TransformMovies(XElement) pure functional transformation method. The latter creates a header row based on the first movie and one content row for each movie.
        private const string MoviesXml =
            @"<?xml version=""1.0"" encoding=""UTF-8""?>
<Movies>
  <Movie>
    <Name>Crash</Name>
    <Released>2005</Released>
  </Movie>
  <Movie>
    <Name>The Departed</Name>
    <Released>2006</Released>
  </Movie>
  <Movie>
    <Name>The Pursuit of Happiness</Name>
    <Released>2006</Released>
  </Movie>
  <Movie>
    <Name>The Bucket List</Name>
    <Released>2007</Released>
  </Movie>
</Movies>";

        private static Table TransformMovies(XElement movies)
        {
            var headerRow = new[]
            {
                new TableRow(movies
                    .Elements()
                    .First()
                    .Elements()
                    .Select(e => new TableCell(new Paragraph(new Run(new Text(e.Name.LocalName))))))
            };
            var movieRows = movies.Elements().Select(TransformMovie);

            return new Table(headerRow.Concat(movieRows));
        }

        private static OpenXmlElement TransformMovie(XElement element)
        {
            return element.Name.LocalName switch
            {
                "Movie" => new TableRow(element.Elements().Select(TransformMovie)),
                _ => new TableCell(new Paragraph(new Run(new Text(element.Value)))),
            };
        }

        [Fact]
        public void CanCreateTableFromXml()
        {
            var movies = XElement.Parse(MoviesXml);
            var table = TransformMovies(movies);
        }

Update on 2019-12-29: How to Call TransformMovies
The following example shows how you can call the TransformMovies method in your InsertTable method.
        private void InsertTable(WordprocessingDocument wordprocessingDocument)
        {
            const string xmlFile = @"Resources\Movies.xml";
            MainDocumentPart mainPart = wordprocessingDocument.MainDocumentPart;

            // How to read the XML and create a table in word document filled
            // with data from XML

            // First, read the Movies XML string from your XML file.
            string moviesXml = File.ReadAllText(xmlFile);

            // Second, create the table as previously shown in the unit test method.
            XElement movies = XElement.Parse(moviesXml);
            Table table = TransformMovies(movies);

            // Third, append the Table to your empty Body.
            mainPart.Document.Body.AppendChild(table);
        }

Update on 2019-12-30: How to Add Table Borders
Looking at your changed TransformMovies method in which you are trying to add table borders, this method produces the following Open XML table markup:
<w:tbl xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
  <w:tr>
    <w:tc>
      <w:p>
        <w:r>
          <w:t>Name</w:t>
        </w:r>
      </w:p>
    </w:tc>
    <w:tc>
      <w:p>
        <w:r>
          <w:t>Released</w:t>
        </w:r>
      </w:p>
    </w:tc>
  </w:tr>
  <w:tblPr>
    <w:tblBorders>
      <w:top w:val="single" w:sz="24" />
      <w:bottom w:val="single" w:sz="24" />
      <w:left w:val="single" w:sz="24" />
      <w:right w:val="single" w:sz="24" />
      <w:insideH w:val="single" w:sz="24" />
      <w:insideV w:val="single" w:sz="24" />
    </w:tblBorders>
  </w:tblPr>
</w:tbl>

We can only see the header row while the movie rows are missing. The w:tblPr element (TableProperties instance) is added as the last child element of w:tbl (Table).
Why are you not able to render the data (or why are those movie rows missing)? You are not adding the movieRows to the headerRow in your changed TransformMovies method. Concat is a pure method that does not mutate headerRow. It only returns a concatenated sequence but does not change the first sequence (headerRow in this case).
Why are you not able to add border lines to the table? You are adding the TableProperties as the last child element of the Table. However, as per the Open XML standard, it must be the first one. While Microsoft Word often tolerates invalid Open XML markup, it does not do that in this case.
The following excerpt from your changed TransformedMovies method points out the mistakes that lead to those issues:
Table table = new Table();

var headerRow = new[]
{
    new TableRow(movies
        .Elements()
        .First()
        .Elements()
        .Select(e => new TableCell(new Paragraph(new Run(new Text(e.Name.LocalName))))))
};
var movieRows = movies.Elements().Select(TransformMovie);

// The following line of code is the first culprit.
// The return value of the pure method is not used (Visual Studio should show a warning).
// The headerRow array is unchanged.
headerRow.Concat(movieRows);

TableProperties tblProp = ...

// At this point, you append the unchanged header row.
table.Append(headerRow);

// The following line of code is the second culprit.
// tblProp is appended as the last child of table. It must be the first one.
table.AppendChild(tblProp);

You should rewrite your method as follows to make it work:
private static Table TransformMovies(XElement movies)
{
    var table = new Table();

    var tblPr = new TableProperties(
        new TableBorders(
            new TopBorder { Val = BorderValues.Single, Size = 24 },
            new BottomBorder { Val = BorderValues.Single, Size = 24 },
            new LeftBorder { Val = BorderValues.Single, Size = 24 },
            new RightBorder { Val = BorderValues.Single, Size = 24 },
            new InsideHorizontalBorder { Val = BorderValues.Single, Size = 24 },
            new InsideVerticalBorder { Val = BorderValues.Single, Size = 24 }));

    var headerRow = new TableRow(movies
        .Elements()
        .First()
        .Elements()
        .Select(e => new TableCell(new Paragraph(new Run(new Text(e.Name.LocalName))))));

    IEnumerable<OpenXmlElement> movieRows = movies.Elements().Select(TransformMovie);

    // Append child elements in the right order.
    table.AppendChild(tblPr);
    table.AppendChild(headerRow);
    table.Append(movieRows);

    return table;
}

Note that I created a headerRow array in my earlier answer to then use headerRow.Concat(movieRows) in the following return statement:
// Return Table with IEnumerable<OpenXmlElement> added to it.
return new Table(headerRow.Concat(movieRows));

I did this because I like a functional approach to programming but, unfortunately, the constructors of the strongly typed classes provided by the Open XML SDK don't let you mix individual OpenXmlElement and IEnumerable<OpenXmlElement> instances as required in the following return statement (which does not work, mind you):
// Return Table with OpenXmlElement and IEnumerable<OpenXmlElement> added to it.
return new Table(headerRow, movieRows);

Now, if you have to add multiple individual instances (i.e., TableProperties, TableRow) and a collection (i.e., IEnumerable<OpenXmlElement>), you can as well use the AppendChild (for individual instances) and Append (for collections) methods. In this case, you don't need to create arrays or lists for individual instances to concatenate those and pass them to the constructor in one go.
Comment: many thanks for quick response , how can i call `transformMovies` method in this method `InsertTable(WordprocessingDocument wordprocessingDocument)`
Comment: @EnigmaState, please have a look at my updated answer. Please mark as the answer and upvote if this is helpful.
Comment: many thanks , one last query i would like to add table border as well .. with the above table i am getting table without borders .. Could you please help me on this..
Comment: I also updated my code to reflect your changes.. thanks
Comment: @EnigmaState, please have a look at my update. I added this to my original answer but it might have been better to ask a separate question.
Answer: Here is an alternative approach that uses GemBox.Document, it can simplify DOCX file's processing (creation, editing, printing, converting, etc...):
string xmlFile = @"C:\wordDoc\movies.xml";
string docxFile = @"C:\wordDoc\test.docx";

var document = new DocumentModel();

var section = new Section(document);
document.Sections.Add(section);

var table = new Table(document);
section.Blocks.Add(table);

foreach (var xmlRow in XDocument.Load(xmlFile).Descendants("Movie"))
    table.Rows.Add(
        new TableRow(document,
            new TableCell(document,
                new Paragraph(document, xmlRow.Element("Name").Value)),
            new TableCell(document,
                new Paragraph(document, xmlRow.Element("Released").Value))));

table.TableFormat.Borders.SetBorders(MultipleBorderTypes.All, BorderStyle.Double, Color.Red, 2);

document.Save(docxFile);

Here is how the resulting "test.docx" file looks like:

Also, you can easily add those list items from "fruitList".
For instance, see Lists example.
Comment: Just note that GemBox.Document is a commercial product the free version of which is limited to 20 paragraphs (meaning one header row and 9 movies in this example). It might still be interesting for those who want to abstract away some of the complexities of using the very low-level Open XML SDK. In that case, you should also look at other commercial products such as Aspose.Words, for example.
Comment: @ThomasBarnekow yes, GemBox.Document has free and pro version and unfortunately in case of a table element the free version limitation can be easily exceeded because each cell contains at least one paragraph. Regarding Aspose, when I was researching the available solutions I did find it as well, but it's extremely expensive, especially if you need to deploy it somewhere like on a server…


What is a grounded opponent?

Question: I just heard that for example knees to the head are not allowed to a grounded opponent in MMA.
Does it mean he is lying on the ground or does he has to be on the ground with both legs and both hands?
Answer: A fighter is grounded anytime they have more than just the soles of their feet on the ground.  If they have so much as a finger or a shin on the ground, they are grounded.  Also, if they are leaning on the cage fence, and would be on the ground if it weren't for the cage holding them up, they are also considered grounded.
From the Association of Boxing Commissions Unified Rules of MMA, Fouls section:

16.Kicking the head of a grounded opponent.
A grounded opponent is any fighter who has more than just the soles of
their feet on the ground. (i.e. could have one shin or one finger down
to be considered a downed fighter) If the referee determines that a
fighter would be a grounded fighter but is not solely because the ring
ropes or cage fence has held fighter from the ground, the referee can
instruct the combatants that he is treating the fighter held up solely
by the cage or ropes as a grounded fighter
17.Kneeing the Head of a grounded opponent
A grounded opponent is any fighter who has more than just the soles of
their feet on the ground. If the referee determines that a fighter
would be a grounded fighter but is not solely because the ring ropes
or cage fence has held fighter from the ground, the referee can
instruct the combatants that he is treating the fighter held up solely
by the cage or ropes as a grounded fighter.
18.Stomping of a grounded fighter
Stomping is considered any type of striking action with the feet where
the fighter lifts their leg up bending their leg at the knee and
initiating a striking action with the bottom of their foot or heel .
(Note) Axe kicks are not stomps. Standing foot stops are NOT a foul.
As such, this foul does not include stomping the feet of a standing
fighter.

This rule has seen some abuse, as fighters would often put a hand to the ground as a strike was coming in an attempt to draw a foul.
The 2013 ABC Convention addressed this, and issued a "Touching Down" rule statement that suggested a change be made to the rules to allow the referee to consider a fighter still standing in this case, and/or penalize them for timidity.

Referees should instruct the fighters that they may still be
considered a  standing fighter even if they have a finger or portion
of the hand (or entire  hand) on the canvas. In the discretion of the
referee, a fighter who has a  finger or hand on the canvas may still
be legally struck in the head with  knees and kicks. The referee may
decide that the downed fighter is placing  his or her finger or hand
down without doing so for an offensive or  countering maneuver in an
attempt to advance or improve their position. The  referee may decide
that the downed fighter is instead simply trying to draw a  foul. If
the referee decides that the fighter is "touching down" simply to
benefit from a foul, the referee may consider that fighter a standing
fighter  and decide that no foul has occurred.
Additionally, a
referee may penalize, via warning or point deduction, the  offending
fighter for timidity.

What is a grounded opponent?


Open local server's page on Android Chrome

Question: I'm trying to access a website on my local server from my Android cellphone.
Following this google tutorial.

Chrome DevTools detects my device
i set Port Forwarding rule localhost:5000 -> localhost:8000

But i can't get it to work...
When i access localhost:5000, the browser renders This site can't be reached.
I also tried 127.0.0.1:5000
I researched a lot and couldn't find any solution.
Is this a conection problem?
Comment: If you have port forwarded, you should be accessing the forwarded port from your external IP: http://www.whatsmyip.org; not your internal IP which is what `localhost` and `127.0.0.1` usually are.
Comment: @zero298 The [tutorial](https://developers.google.com/web/tools/chrome-devtools/remote-debugging/local-server) teaches you to access the website through `localhost`, not depending on any network configuration (all the traffic going through USB cable). So i should be able to access through `localhost:5000`, which will be maped to `localhost:8000` on my local development machine, but somehow i can't get it to work
Comment: I'm sorry, I think I misunderstood.  I didn't read your link and thought that you were trying to do something else.  However, for clarity, where are you  trying to navigate to the forwarded address, your mobile or your desktop?
Comment: Additionally what port do you usually use to access your site?  Is it mapped to in your tools or are you just using `5000` from the tutorial?
Comment: @zero298 I'm trying to navigate to the forwarded address from my cellphone, to the website that's being served by my laptop server. Usually i serve on port 8000 on my local Webpack development server, the tutorial says i can navigate (on my cellphone) to `localhost:5000` and get the content being served in my laptop's `localhost:8000`
Comment: It works now, but i did nothing lol...thanks for the help!!
Answer: try using http://localhost:8080/ [the number can be your port number] worked for me.


Should I assert the same values in every test?

Question: I have simple class with the public build method I want to test. Currently I assert all values it returns in every test. Is it a good practice or I should write one test for static values and in other tests only check values which change depending on input?
Implementation
class FiltersAttachment:
    TYPE_OPTIONS = [
        {"text": "All types", "value": "all"},
        {"text": ":link: Webpages", "value": "web_pages"}
    ]

    STATUS_OPTIONS = [
        {"text": "Available / Unavailable", "value": "all"},
        {"text": ":white_circle: Available", "value": "available"},
        {"text": ":red_circle: Unavailable", "value": "unavailable"}
    ]

    @classmethod
    def _filter_options(cls, options, selected):
        return list(filter(lambda t: t['value'] == selected, options))

    @classmethod
    def build(cls, check_type='', status=''):
        return {
            'fallback': 'Filters',
            'callback_id': 'resource_filters',
            'color': '#d2dde1',
            'mrkdwn_in': ['text'],
            'actions': [
                {
                    'name': 'resource_type',
                    'text': 'Type',
                    'type': 'select',
                    'options': cls.TYPE_OPTIONS,
                    'selected_options': cls._filter_options(
                        cls.TYPE_OPTIONS, check_type)
                },
                {

                    'name': 'resource_status',
                    'text': 'Status',
                    'type': 'select',
                    'options': cls.STATUS_OPTIONS,
                    'selected_options': cls._filter_options(
                        cls.STATUS_OPTIONS, status)
                }
            ]
        }

Tests
class TestFiltersAttachment(TestCase):
    def assert_attachment(self, attachment):
        self.assertEqual(attachment['fallback'], 'Filters')
        self.assertEqual(attachment['callback_id'], 'resource_filters')
        self.assertEqual(attachment['color'], '#d2dde1')
        self.assertEqual(attachment['mrkdwn_in'], ['text'])

        type_action = attachment['actions'][0]
        self.assertEqual(type_action['name'], 'resource_type')
        self.assertEqual(type_action['text'], 'Type')
        self.assertEqual(type_action['type'], 'select')
        self.assertEqual(type_action['options'][0]['text'], 'All types')
        self.assertEqual(type_action['options'][0]['value'], 'all')
        self.assertEqual(type_action['options'][1]['text'], ':link: Webpages')
        self.assertEqual(type_action['options'][1]['value'], 'web_pages')

        status_action = attachment['actions'][1]
        self.assertEqual(status_action['name'], 'resource_status')
        self.assertEqual(status_action['text'], 'Status')
        self.assertEqual(status_action['type'], 'select')
        self.assertEqual(status_action['options'][0]['text'], 'Available / Unavailable')
        self.assertEqual(status_action['options'][0]['value'], 'all')
        self.assertEqual(status_action['options'][1]['text'], ':white_circle: Available')
        self.assertEqual(status_action['options'][1]['value'], 'available')
        self.assertEqual(status_action['options'][2]['text'], ':red_circle: Unavailable')
        self.assertEqual(status_action['options'][2]['value'], 'unavailable')

    def test_all_type_selected(self):
        attachment = FiltersAttachment.build(check_type='all')
        self.assert_attachment(attachment)

        selected_type = attachment['actions'][0]['selected_options'][0]
        self.assertEqual(selected_type['text'], 'All types')
        self.assertEqual(selected_type['value'], 'all')

    def test_all_status_selected(self):
        attachment = FiltersAttachment.build(status='all')
        self.assert_attachment(attachment)

        selected_status = attachment['actions'][1]['selected_options'][0]
        self.assertEqual(selected_status['text'], 'Available / Unavailable')
        self.assertEqual(selected_status['value'], 'all')
        ...

Answer: One of the criteria for the quality of a test suite is, how well the test suite supports you in case of test failures to identify the problem.  Ideally, you should be able to identify the problem alone by looking at which tests failed and which did not.  You should not need to use a debugger to find out what actually went wrong.
The way you have written your tests will not give you the best possible support.  You have packed many assertions in one test function.  Therefore, the test functions will fail for many different reasons, and when you see one of the functions fail, you will have to do a detailed analysis or use debugging to find out for which reason it failed.  When making your tests check aspects redundantly (as you have asked in your question), you make them even less specific, which makes the problem worse.
Therefore, each test should check one specific aspect, such that a failure of a test gives the most specific information.  This is achieved by the combination of the following two principles:

Each test should verify one specific aspect.
There should not be redundant tests for the same aspect.

Turning each assertion into a test of its own can be done conveniently with the help of so called parameterized tests.  Some hints for Python can be found at this question: How do you generate dynamic (parameterized) unit tests in python?


unset form error for specific field

Question: I have a a kind of conditional field for a sign up form where the user can optionally sign up with a mobile number or an email address.
I'm trying out a custom form validate eg.
  function signup_validate($form, FormStateInterface $form_state) {
    $mobile = $form_state->getValue('field_mobile');
    $email = $form_state->getValue('field_email_address');

    if ($email[0]['value'] != '' || $mobile[0]['value'] != '') {
      $form_state->clearErrors();
    }
  }

Now clearErrors();  obviously clears all errors for the form even if other fields are invalid, I want to know how to clear the error only for field_mobile or field_email_address
Answer: While I agree with the accepted answer, one way to accomplish your goal is to:

Assign the form errors to a variable, such as $form_errors
Clear all form errors from $form_state
Remove the particular form error from $form_errors
Loop through the remaining $form_errors, re-setting them to $form_state.

So to clear the field_mobile error you would use the following code:
// Temporarily store all form errors.
$form_errors = $form_state->getErrors();

// Clear the form errors.
$form_state->clearErrors();

// Remove the field_mobile form error.
unset($form_errors['field_mobile']);

// Now loop through and re-apply the remaining form error messages.
foreach ($form_errors as $name => $error_message) {
  $form_state->setErrorByName($name, $error_message);
}

Comment: For me this requirement it's needed on credit card fields required with no name attribute and for security reasons not received on my server, only a token from my payment provider.
Comment: Ended up needing to use for a plugin configuration form in `validateConfigurationForm()` as I couldn't get #states to function as expected.
Comment: It's working for me
Comment: Good answer. Should be the accepted answer.
Answer: Instead of removing the error, you should make sure that only the needed validation errors are set in the first place.
For example, you could use '#states' in your form elements to set 'required' depending on the user input of the other field.
Comment: States affect only client side validation, not server side.  "Since states are driven by JavaScript only, it is important to understand that all states are applied on presentation only" > https://www.drupal.org/docs/drupal-apis/form-api/conditional-form-fields#statesproperty

unset form error for specific field


API em Laravel receber POST JSON e gravar em banco de dados

Question: Irei receber através da API um JSON com esta estrutura:

{"leads":
  [{"id":"1",
    "email":"email@example.com",
    "name":"Bruno Ghisi",
    "company":"Resultados Digitais",
    "job_title":"IT",
    "bio":"This is my bio",
    "created_at":"2012-06-04T15:31:35-03:00",
    "opportunity":"false",
    "number_conversions":"3",
    "first_conversion": {
      "content": {
        "identificador":"ebook-abc",
        "nome":"Bruno",
        "email_lead":"email@example.com",
        "telefone":"99999999",
        "empresa":"Resultados Digitais",
        "cargo":"IT"
      },
      "created_at":"2012-06-04T15:31:35-03:00",
      "cumulative_sum":"1",
      "source":"source 1"
    },
    "last_conversion": {
      "content": {
        "identificador":"webinar-abc",
        "email_lead":"firstname.lastname@example.com"
      },
      "created_at":"2012-06-04T15:31:35-03:00",
      "cumulative_sum":"2",
      "source":"source 2"
    }
  }]
}

Minha API deve receber estes dados e gravar em meu banco de dados, estou iniciando a utilização do Laravel e segui um tutorial do Vedovelli, a API está recebendo e gravando POSTs realizados sem ser no formato json porém qnd vou testar neste formato ele insere uma linha no banco de dados gravando somente o ID sem as demais informações.
Meu Controller está desta forma:

public function saveLead()
    {
        return Response::json($this->lead->saveLead(), 200);
    }

e o Model desta forma:

 public function saveLead()
    {
        $input = Input::all(); //pega todos os dados do input
        $lead = new Lead(); //criar um novo registro
        $lead->fill($input); //inclui todos os dados do input
        $lead->save(); //salva o input
        return $lead; //retorna o lead gravado
    }

Se eu acrescentar um dd($input); ele me mostra um array com os dados, porém na hora de gravar não insere os valores na base.
Desde já agradeço a quem conseguir me ajudar. :/
Comment: a sua estrutura do bd está seguindo as mesmas nomenclaturas do retorno do json? inclusive case-sensitives
Comment: Pelo que eu entendi, em uma mesma action de um controller você pode receber um `request` tanto "normal" quanto em JSON. É isso mesmo? Sua action tem que ser inteligente o bastante para saber se o Request vindo contém o JSON ou não?
Answer: Consegui resolver desta forma:

public function saveConversion()
    {
        $input = file_get_contents('php://input'); // Pega todos os dados do json
        $jsonDecode = json_decode($input); // Decodifica o json e transforma em objeto
        $leads = $jsonDecode->leads[0];

        $lead->id = $leads->id;
        $lead->email = $leads->email;
        $lead->name = $leads->name;
        $lead->company = $leads->company;
        $lead->job_title = $leads->job_title;
        $lead->bio = $leads->bio;
        $lead->opportunity = $leads->opportunity;
        $lead->number_conversions = $leads->number_conversions;

        $lead->save(); // Salva o input

        return $lead; // Retorna o lead gravado
    }


Mesclar duas funcionalidades

Question: Tenho 1 branch no meu projeto
1 - Master

Criei mais 1 branch e desenvolvi 1 feature. Agora tenho 2 branchs
1 - Master
2 - feature1

Comecei a desenvolver outra feature e agora tenho 3 branchs
1 - Master
2 - feature1
3 - feature2

Finalizei a primeira feature e agora tenho 2 branchs
1 - Master
2 - feature2

Mas agora preciso da feature1 no branch da feature2, pois uma funcionalidade da feature2 depende de uma funcionalidade que foi implementada na feature1.
Qual o procedimento correto pra fazer o merge dos branchs nesse caso, sem que eu precise fazer um merge de tudo no master?
Estou usando o gitflow.
Answer: Você está num fluxo de desenvolvimento chamado feature-branch workflow. É bom conhecer esses nomes porque assim você pode procurar por coisas mais especializadas nisso no Google.
Eu gosto bastante da descrição da Atlassian desse worflow: https://www.atlassian.com/br/git/tutorials/comparing-workflows/feature-branch-workflow
Nesse caso específico, houve um problema de levantamento de requisitos antes de se começar o trabalho. Por quê? Porque a feature2 só deveria ter sido implementada após um código básico proveniente da feature1. Talvez não fosse possível resolver esse problema de requisitos antes de começar a implementar, porque talvez só se percebesse essa dependência durante a escrita do código.
Existem algumas alternativas para a sua situação. A mais "básica" e que funciona para quase tudo (não a melhor sempre, entretanto), é fazer
$ git fetch && git merge origin/Master

no branch feature2. Assim, você garante que o código requisito está no lugar correto.
Outra alternativa é diminuir a entrega. Como assim?
Bem, se foi possível começar o código da feature2 antes de existir o código da feature1, então isso significa que tem uma parte da feature2 que é independente da feature1. Nesse caso, você poderia fazer um pull request/merge request do trecho de código independente. Ele não entregará a feature inteira, mas dará um passo importante nela. Só depois de misturado esse código você poderá dar seguimento na feature2-codigo-dependente-da-feautre1 em cima do branch Master já mergeado com essa primeira parte da feature.
Existe outra abordagem que é tentar manter os feature branches todos partindo da cabeça estável, mas para isso é necessário dar constantes rebase após cada merge. Conheço uma equipe que trabalha (mais ou menos) assim (mas com giflow, não feature-branch workflow), o histórico de commits linear fica lindo, mas como eles trabalham com lançamentos "futuros" (manutenções na versão 3.X geram rebase na 4.X [primeiro futuro] que gera rebase na 5.X [segundo futuro] que gera rebase na 6.X [terceiro e último futuro]), fica confuso retro-referência de commits.
Particularmente eu, como revisor de código, prefiro sempre a solução que gere a maior quantidade de merge requests com o menor diferencial de código em cada merge request individual. Claro, desde que cada merge request seja autocontido e autossuficiente, e que também seja realmente uma unidade lógica de mudança. Talvez essas mudanças individualmente ofendam temporariamente o YAGNI, mas se a funcionalidade como um todo precisa entrar, a versão estável do código não ofenderá o YAGNI por muito tempo.
Answer: Você pode simplesmente sincronizar sua branch feature2 com a branch master utilizando os seguintes comandos:
$ git checkout feature2
$ git pull origin master

O fato de você realizar o pull da sua branch master para a feature2 irá sincronizar sua branch com a master, e consequentemente você terá o código da sua feature1 na feature2 (visto que a feature1 já está na master).
Essa operação pode apresentar conflitos, após a resolução você deve gerar um commit para finalização do merge:
git commit

Mesclar duas funcionalidades


Select query using Group By 3 first varchars

Question: I would like to make a SELECT query which group by 3 first varchars ond shows it onces for each. for example the table "tblanimals":
id      name   age
--      ----   ---
1       DOG1   10
2       DOG2   12
3       DOG3   14
4       CAT1   16
5       CAT2   18

the output should be:
DOG
CAT

after it I need to make another (inside loop) simple query to show the details of each result from the last query we made:
DOG   DOG1   10
      DOG2   12
      DOG3   14
CAT   CAT1   16
      CAT2   18

10X
Comment: BTW can you tell us what actually you wanna accomplish by executing such queries?
Comment: Is this grouping (your last example) required in PHP? Or straight from MySQL? that wont be possible like that
Comment: For this specific example, you should really separate out the string component from the integer component. But either way, this is pretty simple. What have you tried?
Answer: You can group this using SUBSTR()
select SUBSTR(name,1,3) as n from test group by n;

DEMO
Result you want:
select SUBSTR(name,1,3) as n,id,name,age from test;

DEMO
Comment: When grouping is used it's limiting the record set to the first record. They likely meant `order by n` so they could show more than one result.
Comment: I believe that's what op wants @AbsoluteƵERØ
Answer: This query would help you:
Fiddle : here
select
(
case i.rank
when 1 then i.subname
else '' end
) groupname,
i.name,i.age
from

 (SELECT SUBSTRING(`NAME`,1,3)AS SUBNAME, t.name,t.AGE ,

       (
            CASE SUBSTRING(`NAME`,1,3)
            WHEN @curType
            THEN @rownum := @rownum + 1
            ELSE @rownum := 1 AND @curType := (SUBSTRING(`NAME`,1,3)) END
          )+1 AS rank

  FROM TEST t,
       (SELECT @rownum := 0, @curType := '') r
  ) i

OUTPUT:
GROUPNAME | NAME |  AGE
DOG       | DOG1 |  10
          | DOG2 |  12
          | DOG3 |  14
CAT       | CAT1 |  16
          | CAT2 |  18

QUERY EXPLANATION
The innerQuery (i) is for Ranking and getting the rownumbers based on the first 3 characters of the animal name. Using case statement to display the animal name only if rownumber=1. A blank character would be displayed if rownumber is anything else other than 1.
Answer: SELECT SUBSTRING(name,1,3) AS first3Char, name,age FROM test2
GROUP BY first3Char,fName,lName

Please check if above Query would serve your purpose.