问:
How to convert a Android SqlBrite model class to implement Parcelable
I am building an app where I am using SQLBrite sql wrapper for all my database operations. Also, I am using Auto Value to handle all my getters and setters automatically using Google AutoValue library.

Now, my issue is to handle the device rotation and to handle that my putParcelable() method expects two parameters where the first is the KEY and the second is the value of Parcelable type. As I said earlier my Recipe class (code below) is a SQLBrite implemented class and doesn't implement Parcelable. I would like some help to convert this to implement the Parcelable interface.

```<code>@AutoValue
public abstract class Recipe {
    public abstract int id();
    public abstract String name();
    public abstract List<Ingredients> ingredients();
    public abstract List<Step> steps();
    public abstract int servings();
    public abstract String image();

    public static Builder builder() {
        return new AutoValue_Recipe.Builder();
    }

    public static TypeAdapter<Recipe> typeAdapter(Gson gson) {
        return new AutoValue_Recipe.GsonTypeAdapter(gson);
    }

    @AutoValue.Builder
    public abstract static class Builder {
        public abstract Builder id(int id);
        public abstract Builder name(String name);
        public abstract Builder ingredients(List<Ingredients> ingredients);
        public abstract Builder steps(List<Step> steps);
        public abstract Builder servings(int servings);
        public abstract Builder image(String image);

        public abstract Recipe build();
    }
}
</code>```

Now, I tried converting the above code to implement the Parcelable interface, however, now my code is not working. Please help me convert this class to implement Parcelable interface.

```<code>@AutoValue
public abstract class Recipe implements Parcelable {
    public static final String ID = "id";
    public static final String NAME = "name";
    public static final String INGREDIENTS = "ingredients";
    public static final String STEPS = "steps";
    public static final String SERVINGS = "servings";
    public static final String IMAGE = "image";

    private int id;
    private String name;
    private List<Ingredients> ingredients;
    private List<Step> steps;
    private int servings;
    private String image;

    public abstract int id();
    public abstract String name();
    public abstract List<Ingredients> ingredients();
    public abstract List<Step> steps();
    public abstract int servings();
    public abstract String image();

    public static Recipe.Builder builder() {
        return new AutoValue_Recipe.Builder();
    }

    public static TypeAdapter<Recipe> typeAdapter(Gson gson) {
        return new AutoValue_Recipe.GsonTypeAdapter(gson);
    }

    public static final class Builder {
        private final ContentValues values = new ContentValues();
        List<Ingredients> ingredient;
        List<Step> step;

        public Recipe.Builder id(int id) {
            values.put(ID, id);
            return this;
        }

        public Builder name(String name) {
            values.put(NAME, name);
            return this;
        }

        public Builder ingredients(List<Ingredients> ingredients) {
        *//*for(int i=0; i<ingredients.size(); i++) {
            values.put(INGREDIENTS, ingredients.get(i).ingredient());
        }*//*
            this.ingredient = ingredients;
            return this;
        }

        public Builder steps(List<Step> steps) {
            *//*for(int i=0; i<steps.size(); i++) {
                values.put(STEPS, steps.get(i));
            }*//*
            this.step = steps;
            return this;
        }

        public Builder servings(int servings) {
            values.put(SERVINGS, servings);
            return this;
        }

        public Builder image(String image) {
            values.put(IMAGE, image);
            return this;
        }

        public Recipe build() {
            Recipe recipe = null;
            recipe.id = (int) values.get(ID);
            recipe.name = (String) values.get(NAME);
            recipe.ingredients = ingredient;
            recipe.steps = step;
            recipe.servings = (int) values.get(SERVINGS);
            recipe.image = (String) values.get(IMAGE);

            return recipe;
        }
    }

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeInt(id);
        dest.writeString(name);
        dest.writeList(ingredients);
        dest.writeList(steps);
        dest.writeInt(servings);
        dest.writeString(image);
    }
}
</code>```

Edit:
I will using the modified class to handle my device rotation to save scroll state of my recycler view inside a fragment. My onSaveInstanceState() method looks something like this,

```<code>private static final String BUNDLE_RECYCLER_LAYOUT = "BUNDLE_RECYCLER_LAYOUT";
ArrayList<Recipe> mRecipeList = new ArrayList<>(0);

@Override
public void onSaveInstanceState(Bundle bundle) {
    super.onSaveInstanceState(bundle);
   bundle.putParcelable(BUNDLE_RECYCLER_LAYOUT,
   mRecipeListRecyclerView.getLayoutManager().onSaveInstanceState());

   bundle.putParcelableArrayList(BUNDLE_RECYCLER_RECIPE_DATA, mRecipeList);
}
</code>```

The second parameter inside the putParcelable is of Parcelable type.

My onCreateView() method is as shown:

```<code>@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup
container, @Nullable Bundle savedInstanceState) {

     View view = inflater.inflate(R.layout.fragment_recipe_list, container, false);
    unbinder = ButterKnife.bind(this, view);

    if(savedInstanceState != null) {
        Parcelable savedRecyclerViewState = savedInstanceState.getParcelable(BUNDLE_RECYCLER_LAYOUT);
        mRecipeListRecyclerView.getLayoutManager().onRestoreInstanceState(savedRecyclerViewState);
        mRecipeList = savedInstanceState.getParcelableArrayList(BUNDLE_RECYCLER_RECIPE_DATA);
        mRecipeListAdapter.refreshRecipes(mRecipeList);
    } else {
        mRecipeList = getArguments().getParcelableArrayList(BUNDLE_RECYCLER_RECIPE_DATA);
    }

    mRecipeListAdapter = new RecipeListAdapter(getContext(), mRecipeList, recipeId
            -> mRecipeListPresenter.loadRecipeDetails(recipeId));
    mRecipeListAdapter.setHasStableIds(true);

    gridLayoutManager = new GridLayoutManager(getContext(), mGridColumnCount);
    mRecipeListRecyclerView.setLayoutManager(gridLayoutManager);
    mRecipeListRecyclerView.setHasFixedSize(true);
    mRecipeListRecyclerView.setAdapter(mRecipeListAdapter);

    return view;
}
</code>```

Any help would be great as I am stuck while converting the class to implement the Parcelable interface.

答:
```<code>        mRecipeListRecyclerView.getLayoutManager().onRestoreInstanceState(savedRecyclerViewState);
</code>```

You do not need to call onRestoreInstanceState(). This is already called automatically by the Android system. Additionally, you do not need to save and restore the ArrayList yourself. RecyclerView already takes care of these details for you.

As for saving the scroll position, you should do a little more research. For example, I found ListView jumps to the top on screen orientation change with a quick search. This link has a clear example of how to do what you want.

This answer is about ScrollView but the example code is very similar to what you need.

Body:
I am building an app where I am using SQLBrite sql wrapper for all my database operations. Also, I am using Auto Value to handle all my getters and setters automatically using Google AutoValue library.

Now, my issue is to handle the device rotation and to handle that my putParcelable() method expects two parameters where the first is the KEY and the second is the value of Parcelable type. As I said earlier my Recipe class (code below) is a SQLBrite implemented class and doesn't implement Parcelable. I would like some help to convert this to implement the Parcelable interface.

@AutoValue
public abstract class Recipe {
    public abstract int id();
    public abstract String name();
    public abstract List<Ingredients> ingredients();
    public abstract List<Step> steps();
    public abstract int servings();
    public abstract String image();

    public static Builder builder() {
        return new AutoValue_Recipe.Builder();
    }

    public static TypeAdapter<Recipe> typeAdapter(Gson gson) {
        return new AutoValue_Recipe.GsonTypeAdapter(gson);
    }

    @AutoValue.Builder
    public abstract static class Builder {
        public abstract Builder id(int id);
        public abstract Builder name(String name);
        public abstract Builder ingredients(List<Ingredients> ingredients);
        public abstract Builder steps(List<Step> steps);
        public abstract Builder servings(int servings);
        public abstract Builder image(String image);

        public abstract Recipe build();
    }
}

Now, I tried converting the above code to implement the Parcelable interface, however, now my code is not working. Please help me convert this class to implement Parcelable interface.

@AutoValue
public abstract class Recipe implements Parcelable {
    public static final String ID = "id";
    public static final String NAME = "name";
    public static final String INGREDIENTS = "ingredients";
    public static final String STEPS = "steps";
    public static final String SERVINGS = "servings";
    public static final String IMAGE = "image";

    private int id;
    private String name;
    private List<Ingredients> ingredients;
    private List<Step> steps;
    private int servings;
    private String image;

    public abstract int id();
    public abstract String name();
    public abstract List<Ingredients> ingredients();
    public abstract List<Step> steps();
    public abstract int servings();
    public abstract String image();

    public static Recipe.Builder builder() {
        return new AutoValue_Recipe.Builder();
    }

    public static TypeAdapter<Recipe> typeAdapter(Gson gson) {
        return new AutoValue_Recipe.GsonTypeAdapter(gson);
    }

    public static final class Builder {
        private final ContentValues values = new ContentValues();
        List<Ingredients> ingredient;
        List<Step> step;

        public Recipe.Builder id(int id) {
            values.put(ID, id);
            return this;
        }

        public Builder name(String name) {
            values.put(NAME, name);
            return this;
        }

        public Builder ingredients(List<Ingredients> ingredients) {
        *//*for(int i=0; i<ingredients.size(); i++) {
            values.put(INGREDIENTS, ingredients.get(i).ingredient());
        }*//*
            this.ingredient = ingredients;
            return this;
        }

        public Builder steps(List<Step> steps) {
            *//*for(int i=0; i<steps.size(); i++) {
                values.put(STEPS, steps.get(i));
            }*//*
            this.step = steps;
            return this;
        }

        public Builder servings(int servings) {
            values.put(SERVINGS, servings);
            return this;
        }

        public Builder image(String image) {
            values.put(IMAGE, image);
            return this;
        }

        public Recipe build() {
            Recipe recipe = null;
            recipe.id = (int) values.get(ID);
            recipe.name = (String) values.get(NAME);
            recipe.ingredients = ingredient;
            recipe.steps = step;
            recipe.servings = (int) values.get(SERVINGS);
            recipe.image = (String) values.get(IMAGE);

            return recipe;
        }
    }

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeInt(id);
        dest.writeString(name);
        dest.writeList(ingredients);
        dest.writeList(steps);
        dest.writeInt(servings);
        dest.writeString(image);
    }
}

Edit:
I will using the modified class to handle my device rotation to save scroll state of my recycler view inside a fragment. My onSaveInstanceState() method looks something like this,

private static final String BUNDLE_RECYCLER_LAYOUT = "BUNDLE_RECYCLER_LAYOUT";
ArrayList<Recipe> mRecipeList = new ArrayList<>(0);

@Override
public void onSaveInstanceState(Bundle bundle) {
    super.onSaveInstanceState(bundle);
   bundle.putParcelable(BUNDLE_RECYCLER_LAYOUT,
   mRecipeListRecyclerView.getLayoutManager().onSaveInstanceState());

   bundle.putParcelableArrayList(BUNDLE_RECYCLER_RECIPE_DATA, mRecipeList);
}

The second parameter inside the putParcelable is of Parcelable type.

My onCreateView() method is as shown:

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup
container, @Nullable Bundle savedInstanceState) {

     View view = inflater.inflate(R.layout.fragment_recipe_list, container, false);
    unbinder = ButterKnife.bind(this, view);

    if(savedInstanceState != null) {
        Parcelable savedRecyclerViewState = savedInstanceState.getParcelable(BUNDLE_RECYCLER_LAYOUT);
        mRecipeListRecyclerView.getLayoutManager().onRestoreInstanceState(savedRecyclerViewState);
        mRecipeList = savedInstanceState.getParcelableArrayList(BUNDLE_RECYCLER_RECIPE_DATA);
        mRecipeListAdapter.refreshRecipes(mRecipeList);
    } else {
        mRecipeList = getArguments().getParcelableArrayList(BUNDLE_RECYCLER_RECIPE_DATA);
    }

    mRecipeListAdapter = new RecipeListAdapter(getContext(), mRecipeList, recipeId
            -> mRecipeListPresenter.loadRecipeDetails(recipeId));
    mRecipeListAdapter.setHasStableIds(true);

    gridLayoutManager = new GridLayoutManager(getContext(), mGridColumnCount);
    mRecipeListRecyclerView.setLayoutManager(gridLayoutManager);
    mRecipeListRecyclerView.setHasFixedSize(true);
    mRecipeListRecyclerView.setAdapter(mRecipeListAdapter);

    return view;
}

Any help would be great as I am stuck while converting the class to implement the Parcelable interface.

Body:
        mRecipeListRecyclerView.getLayoutManager().onRestoreInstanceState(savedRecyclerViewState);

You do not need to call onRestoreInstanceState(). This is already called automatically by the Android system. Additionally, you do not need to save and restore the ArrayList yourself. RecyclerView already takes care of these details for you.

As for saving the scroll position, you should do a little more research. For example, I found ListView jumps to the top on screen orientation change with a quick search. This link has a clear example of how to do what you want.

This answer is about ScrollView but the example code is very similar to what you need.


来源: stackexchange

问:
How to extract css to file from vue-cli webpack-simple project?
I'm still learning Vue, so I'm struggling to figure out how to convert the inline css to a css file.

If anyone could help me out setting up the css(scss) extraction to a single css file, I would be grateful!

Or will that defeat the purpose of vue's scoped styles?

Here's my webpack.config code:

```<code>var path = require('path')
var webpack = require('webpack')

module.exports = {
  entry: './src/main.js',
  output: {
    path: path.resolve(__dirname, './dist'),
    publicPath: '/dist/',
    filename: 'build.js'
  },
  module: {
    rules: [
      {
        test: /\.vue$/,
        loader: 'vue-loader',
        options: {
          loaders: {
            'scss': 'vue-style-loader!css-loader!sass-loader',
            'sass': 'vue-style-loader!css-loader!sass-loader?indentedSyntax'
          }
        }
      },
      {
        test: /\.js$/,
        loader: 'babel-loader',
        exclude: /node_modules/
      },
      {
        test: /\.(png|jpg|gif|svg)$/,
        loader: 'file-loader',
        options: {
          name: '[name].[ext]?[hash]'
        }
      }
    ]
  },
  resolve: {
    alias: {
      'vue$': 'vue/dist/vue.esm.js'
    }
  },
  devServer: {
    historyApiFallback: true,
    noInfo: true
  },
  performance: {
    hints: false
  },
  devtool: '#eval-source-map'
}

if (process.env.NODE_ENV === 'production') {
  module.exports.devtool = '#source-map'

  module.exports.plugins = (module.exports.plugins || []).concat([
    new webpack.DefinePlugin({
      'process.env': {
        NODE_ENV: '"production"'
      }
    }),
    new webpack.optimize.UglifyJsPlugin({
      sourceMap: true,
      compress: {
        warnings: false
      }
    }),
    new webpack.LoaderOptionsPlugin({
      minimize: true
    })
  ])
}
</code>```

答:
So, to sum up our comments:

The answer here was for him to create a new 'full' Webpack project and move his code into it.

Reasons:

A full webpack project pulls out CSS from .vue files automatically into a single CSS file, which is what he wants.

"[T]he webpack-simple cli doesnt have [CSS] extraction built in".

The webpack config and build files can be very difficult to understand, and it could take him a long time to figure out how to set things up manually to replicate the behavior of a full Webpack project.

ContentLicense: CC BY-SA 3.0

Body:
I'm still learning Vue, so I'm struggling to figure out how to convert the inline css to a css file.

If anyone could help me out setting up the css(scss) extraction to a single css file, I would be grateful!

Or will that defeat the purpose of vue's scoped styles?

Here's my webpack.config code:

var path = require('path')
var webpack = require('webpack')

module.exports = {
  entry: './src/main.js',
  output: {
    path: path.resolve(__dirname, './dist'),
    publicPath: '/dist/',
    filename: 'build.js'
  },
  module: {
    rules: [
      {
        test: /\.vue$/,
        loader: 'vue-loader',
        options: {
          loaders: {
            'scss': 'vue-style-loader!css-loader!sass-loader',
            'sass': 'vue-style-loader!css-loader!sass-loader?indentedSyntax'
          }
        }
      },
      {
        test: /\.js$/,
        loader: 'babel-loader',
        exclude: /node_modules/
      },
      {
        test: /\.(png|jpg|gif|svg)$/,
        loader: 'file-loader',
        options: {
          name: '[name].[ext]?[hash]'
        }
      }
    ]
  },
  resolve: {
    alias: {
      'vue$': 'vue/dist/vue.esm.js'
    }
  },
  devServer: {
    historyApiFallback: true,
    noInfo: true
  },
  performance: {
    hints: false
  },
  devtool: '#eval-source-map'
}

if (process.env.NODE_ENV === 'production') {
  module.exports.devtool = '#source-map'

  module.exports.plugins = (module.exports.plugins || []).concat([
    new webpack.DefinePlugin({
      'process.env': {
        NODE_ENV: '"production"'
      }
    }),
    new webpack.optimize.UglifyJsPlugin({
      sourceMap: true,
      compress: {
        warnings: false
      }
    }),
    new webpack.LoaderOptionsPlugin({
      minimize: true
    })
  ])
}


问:
How to get the length of written bytes with BinaryWriter?
Considering a simple BinaryWriter procedure:

```<code>using (BinaryWriter writer = new BinaryWriter(File.Open(fileName, FileMode.Create)))
        {
            writer.Write(10000);
            writer.Write("Temp");
            writer.Write(30);
            writer.Write(50.6);
        }
</code>```

Now, how can I get the total number of written bytes by the BinaryWriter? And how to append this amount to the current writer object, e.g. writer.Write(totalNumberAsBytes)

答: Have you tried writer.BaseStream.Length? This should be the amount of bytes in the stream.

Body:
Considering a simple BinaryWriter procedure:

using (BinaryWriter writer = new BinaryWriter(File.Open(fileName, FileMode.Create)))
        {
            writer.Write(10000);
            writer.Write("Temp");
            writer.Write(30);
            writer.Write(50.6);
        }

Now, how can I get the total number of written bytes by the BinaryWriter? And how to append this amount to the current writer object, e.g. writer.Write(totalNumberAsBytes)


问:
VB.net 2017 Change background color of button
I just started using vb.net 2017 instead of the 2010 version and i can't figure out how to change the background color of a button. I used to be able to do

```<code>`but1.BackColor = Colors.Blue`
</code>```

But it seems as if BackColor isn't available anymore. What could be a possible solution?

Edit: added screenshots

Form screenshot VS auto corrects color to ColorInterpolationMode

Designer screenshot

答:
UWP is a completely different framework than WinForms (Windows Forms). If you want the standard WinForms library for desktop applications (which was what you were using in VS 2010) try downloading VS 2017 again and make sure you install the standard set of items/packages.

If you want to change the background color of a button in UWP you gotta use the Background property. Try this:

```<code>but1.Background = New SolidColorBrush(Colors.Blue)
</code>```

Body:
I just started using vb.net 2017 instead of the 2010 version and i can't figure out how to change the background color of a button. I used to be able to do

`but1.BackColor = Colors.Blue`

But it seems as if BackColor isn't available anymore. What could be a possible solution?

Edit: added screenshots

Form screenshot VS auto corrects color to ColorInterpolationMode

Designer screenshot

Body:
UWP is a completely different framework than WinForms (Windows Forms). If you want the standard WinForms library for desktop applications (which was what you were using in VS 2010) try downloading VS 2017 again and make sure you install the standard set of items/packages.

If you want to change the background color of a button in UWP you gotta use the Background property. Try this:

but1.Background = New SolidColorBrush(Colors.Blue)


问:
Laravel / Blackfire - Composer including autoloader taking significant time
I'm using Blackfire to profile my PHP / Laravel application.  Across most endpoints, Composer seems to be taking a long time.  Specifically, the method Composer\Autoload\includeFile.  In the example below, it gets called 240 times.

Now I have run composer dump-autoload --optimize and I have opcache enabled.  Is this behavior normal or is this indicative of an issue?  My understanding would be that the autoloader should only need to be included once.

答: The autoloader's primary purpose is to load all the various classes in your application. As such, it's likely to call includeFile many times in a single request.


问:
Change event in Boostrap3 dropdown
I have a web application written in Angular4 using ngx-bootstrap. I need to call a file open dialog from a bootstrap dropdown menu. I have found a nice example here on how to make the HTML and CSS so the dropdown looks nice here: make input look and behave like a link in bootstrap dropdown

My HTML looks like this:

```<code><li dropdown class="btn-group" container="body">
    <a href dropdownToggle (click)="false" role="button" >Desktop <span class="caret"></span></a>
    <ul *dropdownMenu class="dropdown-menu">
        <li role="menuitem" *ngFor="let desktop of desktops$ | async">
            <a class="dropdown-item" routerLink="/{{desktop.$key}}">{{desktop.name}}</a>
        </li>
        <li class="divider dropdown-divider"></li>
        <li role="menuitem"><a class="dropdown-item" (click)="childModal.show()" style="cursor:pointer;">New...</a>
        <li role="menuitem"><a class="dropdown-item" href="#">Delete...</a>
        <li role="menuitem"><a class="dropdown-item" href="#">Share...</a>
        <li class="divider dropdown-divider"></li>
        <li><a class="btn-file">
            Add files...<input type="file" (change)="detectFiles($event)" style="cursor:pointer;" />
        </a></li>
        <!--<li role="menuitem"><a class="dropdown-item" routerLink="/add-files">Add files...</a>-->
        <li role="menuitem"><a class="dropdown-item" href="#">Remove files...</a>
    </ul>
</li>
</code>```

To get the file the user selected I have added a (change)="detectFiles($event) to the input, but the function is newer called.

If I move the code:

```<code><li><a class="btn-file">
    Add files...<input type="file" (change)="detectFiles($event)" style="cursor:pointer;" />
</a></li>
</code>```

out of the dropdown detectFiles is called as expected.

I found some articles about bootstrap stopping event propagation on dropdowns like this Twitter bootstrap stop propagation on dropdown open but I cannot really understand the suggested solutions and how they can be applied in an Angular app.

So how can I get the (change) event from within a bootstrap3 dropdown?

答: The problem was that I had copied the HTML dropdown code from ngx-bootstaps v4 documentation. So remove container="body" and it works.</p>

Title: Change event in Boostrap3 dropdown

Body:
I have a web application written in Angular4 using ngx-bootstrap. I need to call a file open dialog from a bootstrap dropdown menu. I have found a nice example here on how to make the HTML and CSS so the dropdown looks nice here: make input look and behave like a link in bootstrap dropdown

My HTML looks like this:

    Desktop

            {{desktop.name}}

New...

Delete...

Share...

            Add files...<input type="file" (change)="detectFiles($event)" style="cursor:pointer;" />

Remove files...

To get the file the user selected I have added a (change)="detectFiles($event) to the input, but the function is newer called.

If I move the code:

    Add files...<input type="file" (change)="detectFiles($event)" style="cursor:pointer;" />

out of the dropdown detectFiles is called as expected.

I found some articles about bootstrap stopping event propagation on dropdowns like this Twitter bootstrap stop propagation on dropdown open but I cannot really understand the suggested solutions and how they can be applied in an Angular app.

So how can I get the (change) event from within a bootstrap3 dropdown?


问:
Android firebase modifying list with in runTransaction
I have very simple transactional code:

```<code>postRef.runTransaction(new Transaction.Handler() {
            @Override
            public Transaction.Result doTransaction(MutableData mutableData) {
                Post post = mutableData.getValue(Post.class);
                if (post == null) {
                    return Transaction.success(mutableData);
                }

                if(null == post.getLikes())
                    post.setLikes(new ArrayList<String>());

                String currentUserId = // get id

                if (post.getLikes().contains(currentUserId)) {
                    // Unstar the post and remove self from stars
                    post.setLikeCounts(post.getLikeCounts() - 1);
                    post.getLikes().remove(currentUserId);

                } else {
                    // Star the post and add self to stars
                    post.setLikeCounts(post.getLikeCounts() + 1);
                    post.getLikes().add(currentUserId);

                }

                // Set value and report transaction success
                mutableData.setValue(post);
                return Transaction.success(mutableData);
            }

            @Override
            public void onComplete(DatabaseError databaseError, boolean b,
                                   DataSnapshot dataSnapshot) {
                // Transaction completed
                Log.d(LOG_TAG, "postTransaction:onComplete:" + databaseError);
            }
        });
</code>```

But am seeing weird behavior here adding a string to the likes list is not modifying the list at all:

```<code>post.getLikes().add(currentUserId);
</code>```

I even stopped debugger and tried to add hardcoded values to the list but still no change.

Update (Post class):

```<code>package com.dsharew.aradavibes.model;

import com.dsharew.aradavibes.providers.LocalDataProvider;
import com.google.firebase.database.Exclude;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by dsharew on 6/1/17.
 */

public class Post extends Entity{

    public static final String FIELD_AUTHOR_ID = "authorId";
    public static final String FIELD_TITLE = "title";
    public static final String FIELD_DESCRIPTION = "description";
    public static final String FIELD_POST_IMAGE_IDS = "postImageIds";
    public static final String FIELD_POST_VIDEO_IDS = "postVideoIds";

    User author;
    String title;
    String description;
    String authorId;

    List<String> postImageIds;
    List<String> postVideoIds;

    List<PostImage> postImages;
    List<PostVideo> postVideos;

    int likeCounts;
    List<String> likes;

    int viewCounts;
    List<String>views;

    public Post(){

    }

    public Post(String title, String description, List<String> postImageIds, List<String> postVideoIds){

        super();
        this.title = title;
        this.description = description;
        this.postImageIds = postImageIds;
        this.postVideoIds = postVideoIds;

    }

    public List<String> getPostImageIds() {
        return postImageIds;
    }

    public void setPostImageIds(List<String> postImageIds) {
        this.postImageIds = postImageIds;
    }

    public List<String> getPostVideoIds() {
        return postVideoIds;
    }

    public void setPostVideoIds(List<String> postVideoIds) {
        this.postVideoIds = postVideoIds;
    }

    @Exclude
    public User getAuthor() {
        return author;
    }

    public void setAuthor(User author) {
        this.author = author;
    }

    public String getAuthorId() {
        return authorId;
    }

    public void setAuthorId(String authorId) {
        this.authorId = authorId;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    @Exclude
    public List<PostImage> getPostImages() {
        return postImages;
    }

    public void setPostImages(List<PostImage> postImages) {
        this.postImages = postImages;
    }

    public int getLikeCounts() {
        return likeCounts;
    }

    public void setLikeCounts(int likeCounts) {
        this.likeCounts = likeCounts;
    }

    public List<String> getLikes() {

        if(null == likes) return new ArrayList<String>();

        return likes;
    }

    public void setLikes(List<String> likes) {
        this.likes = likes;
    }

    @Exclude
    public List<PostVideo> getPostVideos() {

        if(null == postVideos)
            postVideos = new ArrayList<PostVideo>();

        return postVideos;
    }

    public int getViewCounts() {
        return viewCounts;
    }

    public void setViewCounts(int viewCounts) {
        this.viewCounts = viewCounts;
    }

    public List<String> getViews() {
        return views;
    }

    public void setViews(List<String> views) {
        this.views = views;
    }

    public void setPostVideos(List<PostVideo> postVideos) {
        this.postVideos = postVideos;
    }

    public boolean validate(){

        if(isEmpty()){

            return false;

        }

        return true;

    }

    @Exclude
    public boolean isEmpty(){

        if( (null == getTitle() || getTitle().isEmpty()) &&
                (null == getDescription() || getDescription().isEmpty()) &&
                (null == getPostImages() || getPostImages().isEmpty()) &&
                (null == getPostVideos() || getPostVideos().isEmpty())){

            return true;

        }

        return false;

    }

    public void incrementViews(String currentUserId, String postId){

        this.setViewCounts(this.getViewCounts() + 1);
        this.getViews().add(currentUserId);

        LocalDataProvider.getInstance().viewPost(postId);

    }

    public boolean containsUnsavedObjects(){

        if(null != getPostImages() && !getPostImages().isEmpty()){

            for(PostImage postImage : getPostImages()){

                if(null != postImage && null == postImage.getId()) return true;

            }

        }

        if(null != getPostVideos() && !getPostVideos().isEmpty()){

            for(PostVideo postVideo : getPostVideos()){

                if(null == postVideo.getId()) return true;

            }

        }

        return false;

    }

}
</code>```

Any clue here?

答:
The problem appears to be this method:

```<code>public List<String> getLikes() {
    if(null == likes) return new ArrayList<String>();
    return likes;
}
</code>```

When likes is null, this will return an anonymous ArrayList.  Any updates to that list are are lost, i.e. they are not applied to the state of the Post instance.  You probably intended:

```<code>public List<String> getLikes() {
    if(null == likes) likes = new ArrayList<String>();
    return likes;
}
</code>```

During your debugging, you may have suspected that something was odd about getLikes() and tried to fix it with this:

```<code>if(null == post.getLikes())
    post.setLikes(new ArrayList<String>());
</code>```

But that is ineffective because getLikes() never returns null.

Body:
I have very simple transactional code:

postRef.runTransaction(new Transaction.Handler() {
            @Override
            public Transaction.Result doTransaction(MutableData mutableData) {
                Post post = mutableData.getValue(Post.class);
                if (post == null) {
                    return Transaction.success(mutableData);
                }

                if(null == post.getLikes())
                    post.setLikes(new ArrayList<String>());

                String currentUserId = // get id

                if (post.getLikes().contains(currentUserId)) {
                    // Unstar the post and remove self from stars
                    post.setLikeCounts(post.getLikeCounts() - 1);
                    post.getLikes().remove(currentUserId);

                } else {
                    // Star the post and add self to stars
                    post.setLikeCounts(post.getLikeCounts() + 1);
                    post.getLikes().add(currentUserId);

                }

                // Set value and report transaction success
                mutableData.setValue(post);
                return Transaction.success(mutableData);
            }

            @Override
            public void onComplete(DatabaseError databaseError, boolean b,
                                   DataSnapshot dataSnapshot) {
                // Transaction completed
                Log.d(LOG_TAG, "postTransaction:onComplete:" + databaseError);
            }
        });

But am seeing weird behavior here adding a string to the likes list is not modifying the list at all:

post.getLikes().add(currentUserId);

I even stopped debugger and tried to add hardcoded values to the list but still no change.

Update (Post class):

package com.dsharew.aradavibes.model;

import com.dsharew.aradavibes.providers.LocalDataProvider;
import com.google.firebase.database.Exclude;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by dsharew on 6/1/17.
 */

public class Post extends Entity{

    public static final String FIELD_AUTHOR_ID = "authorId";
    public static final String FIELD_TITLE = "title";
    public static final String FIELD_DESCRIPTION = "description";
    public static final String FIELD_POST_IMAGE_IDS = "postImageIds";
    public static final String FIELD_POST_VIDEO_IDS = "postVideoIds";

    User author;
    String title;
    String description;
    String authorId;

    List<String> postImageIds;
    List<String> postVideoIds;

    List<PostImage> postImages;
    List<PostVideo> postVideos;

    int likeCounts;
    List<String> likes;

    int viewCounts;
    List<String>views;

    public Post(){

    }

    public Post(String title, String description, List<String> postImageIds, List<String> postVideoIds){

        super();
        this.title = title;
        this.description = description;
        this.postImageIds = postImageIds;
        this.postVideoIds = postVideoIds;

    }

    public List<String> getPostImageIds() {
        return postImageIds;
    }

    public void setPostImageIds(List<String> postImageIds) {
        this.postImageIds = postImageIds;
    }

    public List<String> getPostVideoIds() {
        return postVideoIds;
    }

    public void setPostVideoIds(List<String> postVideoIds) {
        this.postVideoIds = postVideoIds;
    }

    @Exclude
    public User getAuthor() {
        return author;
    }

    public void setAuthor(User author) {
        this.author = author;
    }

    public String getAuthorId() {
        return authorId;
    }

    public void setAuthorId(String authorId) {
        this.authorId = authorId;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    @Exclude
    public List<PostImage> getPostImages() {
        return postImages;
    }

    public void setPostImages(List<PostImage> postImages) {
        this.postImages = postImages;
    }

    public int getLikeCounts() {
        return likeCounts;
    }

    public void setLikeCounts(int likeCounts) {
        this.likeCounts = likeCounts;
    }

    public List<String> getLikes() {

        if(null == likes) return new ArrayList<String>();

        return likes;
    }

    public void setLikes(List<String> likes) {
        this.likes = likes;
    }

    @Exclude
    public List<PostVideo> getPostVideos() {

        if(null == postVideos)
            postVideos = new ArrayList<PostVideo>();

        return postVideos;
    }

    public int getViewCounts() {
        return viewCounts;
    }

    public void setViewCounts(int viewCounts) {
        this.viewCounts = viewCounts;
    }

    public List<String> getViews() {
        return views;
    }

    public void setViews(List<String> views) {
        this.views = views;
    }

    public void setPostVideos(List<PostVideo> postVideos) {
        this.postVideos = postVideos;
    }

    public boolean validate(){

        if(isEmpty()){

            return false;

        }

        return true;

    }

    @Exclude
    public boolean isEmpty(){

        if( (null == getTitle() || getTitle().isEmpty()) &&
                (null == getDescription() || getDescription().isEmpty()) &&
                (null == getPostImages() || getPostImages().isEmpty()) &&
                (null == getPostVideos() || getPostVideos().isEmpty())){

            return true;

        }

        return false;

    }

    public void incrementViews(String currentUserId, String postId){

        this.setViewCounts(this.getViewCounts() + 1);
        this.getViews().add(currentUserId);

        LocalDataProvider.getInstance().viewPost(postId);

    }

    public boolean containsUnsavedObjects(){

        if(null != getPostImages() && !getPostImages().isEmpty()){

            for(PostImage postImage : getPostImages()){

                if(null != postImage && null == postImage.getId()) return true;

            }

        }

        if(null != getPostVideos() && !getPostVideos().isEmpty()){

            for(PostVideo postVideo : getPostVideos()){

                if(null == postVideo.getId()) return true;

            }

        }

        return false;

    }

}

Any clue here?

Body:
The problem appears to be this method:

public List<String> getLikes() {
    if(null == likes) return new ArrayList<String>();
    return likes;
}

When likes is null, this will return an anonymous ArrayList.  Any updates to that list are are lost, i.e. they are not applied to the state of the Post instance.  You probably intended:

public List<String> getLikes() {
    if(null == likes) likes = new ArrayList<String>();
    return likes;
}

During your debugging, you may have suspected that something was odd about getLikes() and tried to fix it with this:

if(null == post.getLikes())
    post.setLikes(new ArrayList<String>());

But that is ineffective because getLikes() never returns null.


问:
How to remove unused styles from twitter bootstrap?
My bootstrap stylesheet size is around 120kb.

But I'm only using 25% of that stylesheet code.

I don't want that span* class. I tried it by customizing it in bootstrap customize page.

I unchecked grid system,  But I still see span1 - span12 class in forms, tables and responsive layouts.

Can someone help me to remove those codes?

答:
I have a template using Bootstrap 2, which is the required system for Joomla. I just did this manually and found it easy to do. The Bootstrap CSS file is very nicely constructed and well ordered in sections. I removed the entire contents of the file to bootstrap_unused.css and then also copied that to bootstrap_original.css.

I then cut out from bootstrap_unused.css what I knew was in use, being careful to preserve the order, and pasted it back in. Most of it worked first time and reduced the file size from 144KB to 14KB. I then needed to add some bits and pieces back in for forms etc. and ended up at 30KB.

If I need any other features in the future, I can pull them back in from bootstrap_unused.css and I always have bootstrap_original.css for reference.


问:
Pause jQuery On Hover (Mouse Over)
I looked around but didn't find anything, please see below for my code.

With that in mind, I just need the ability to be able to pause the animation on mouse hover.

Any assistance is gratefully appreciated!

(function ( $ ) {
 $.fn.textSlider = function ( options ) {

  /* Default settings */
  var settings = $.extend(
   {
    timeout: 2000,
    slideTime: 750,
   },
   options
  );

  var nextItem;

  var currentItem = 0;
  var count = 0;

  this.children('.slider-item').each(
   function ()
   {
    $(this).addClass( 'slide-' + ( count ) )
     .css(
      {
       //opacity:    0,
       //paddingTop: '100px',
       //paddingBottom: '0px'
      }
     );
    $(this).hide();
    count++;
   }
  );

  function firstSlide ()
  {
   $('.slide-' + currentItem ).show().animate({
    //paddingTop: '0px', paddingBottom: '50px',
    opacity: 1 }, settings.slideTime);

   setTimeout ( transition, settings.timeout );
  }

  function transition ()
  {
   nextItem = parseInt ( currentItem + 1 );

   if ( nextItem >= count )
    nextItem = 0;

   $('.slide-' + currentItem ).animate({
    //paddingTop: '100px', paddingBottom: '0px',
    opacity: 0 }, settings.slideTime, function () {
     $(this).hide();
     $('.slide-' + nextItem ).show().animate({
      //paddingTop: '0px', paddingBottom: '50px',
      opacity: 1 }, settings.slideTime);
   });

   currentItem = nextItem;
   setTimeout ( transition, settings.timeout );
  }
  return firstSlide ();
 };
}( jQuery ));

// Start the Text Slider
 $('.slide').textSlider({
  timeout: 5000,
  slideTime: 650,
  loop: 1
 });```
<pre class="snippet-code-css lang-css prettyprint-override"><code>/* Main Message & Text */
.main-message {
 font-size: 150%;
 font-weight: bold;
 padding-bottom: 20px;
 margin-left: 20px;
}
.main-text {
 font-size: 110%;
 margin-left: 20px;
}</code>```

Test 1

Sub text here 1

Test 2

Sub text here 2

Test 3

Sub text here 3

 ```

答: By default, jQuery does not support pausing animations, but, as usual, there's a plugin for that: http://tobia.github.io/Pause/</p>

Title: Pause jQuery On Hover (Mouse Over)

Body:
I looked around but didn't find anything, please see below for my code.

With that in mind, I just need the ability to be able to pause the animation on mouse hover.

Any assistance is gratefully appreciated!

(function ( $ ) {
 $.fn.textSlider = function ( options ) {

  /* Default settings */
  var settings = $.extend(
   {
    timeout: 2000,
    slideTime: 750,
   },
   options
  );

  var nextItem;

  var currentItem = 0;
  var count = 0;

  this.children('.slider-item').each(
   function ()
   {
    $(this).addClass( 'slide-' + ( count ) )
     .css(
      {
       //opacity:    0,
       //paddingTop: '100px',
       //paddingBottom: '0px'
      }
     );
    $(this).hide();
    count++;
   }
  );

  function firstSlide ()
  {
   $('.slide-' + currentItem ).show().animate({
    //paddingTop: '0px', paddingBottom: '50px',
    opacity: 1 }, settings.slideTime);

   setTimeout ( transition, settings.timeout );
  }

  function transition ()
  {
   nextItem = parseInt ( currentItem + 1 );

   if ( nextItem >= count )
    nextItem = 0;

   $('.slide-' + currentItem ).animate({
    //paddingTop: '100px', paddingBottom: '0px',
    opacity: 0 }, settings.slideTime, function () {
     $(this).hide();
     $('.slide-' + nextItem ).show().animate({
      //paddingTop: '0px', paddingBottom: '50px',
      opacity: 1 }, settings.slideTime);
   });

   currentItem = nextItem;
   setTimeout ( transition, settings.timeout );
  }
  return firstSlide ();
 };
}( jQuery ));

// Start the Text Slider
 $('.slide').textSlider({
  timeout: 5000,
  slideTime: 650,
  loop: 1
 });

/* Main Message & Text */
.main-message {
 font-size: 150%;
 font-weight: bold;
 padding-bottom: 20px;
 margin-left: 20px;
}
.main-text {
 font-size: 110%;
 margin-left: 20px;
}

Test 1

Sub text here 1

Test 2

Sub text here 2

Test 3

Sub text here 3


问:
When I try to delete list I got a list size greater than list size+1
```<code>List<Studentdb> list = teacherDao.viewstudent(facultyid, batchid1);
System.out.println("" + list);
int i = 0;
for (Iterator<Studentdb> s = list.iterator(); s.hasNext(); ) {
     System.out.println("" + i);
     System.out.println("list========" + list.get(i).getRoll());
     if (teacherDao.viewmarks(subjectcode, list.get(i).getRoll())) {
           list.remove(s);
     }
    i++;
}
</code>```

When I try to delete a selected list i get the error java.lang.IndexOutOfBoundsException: Index: 3, Size: 3.

Here I have list size 3 i.e index 0 1 2 and I got the error in index 3.

答:
You're code has an infinite loop because it doesn't get the next item in the iterator.

So, by the time i is equal to 3 you're code is trying to get the 4th element in the list, which it's why you're getting this exception.

You should call the next() method in your s object.

Body:
List<Studentdb> list = teacherDao.viewstudent(facultyid, batchid1);
System.out.println("" + list);
int i = 0;
for (Iterator<Studentdb> s = list.iterator(); s.hasNext(); ) {
     System.out.println("" + i);
     System.out.println("list========" + list.get(i).getRoll());
     if (teacherDao.viewmarks(subjectcode, list.get(i).getRoll())) {
           list.remove(s);
     }
    i++;
}

When I try to delete a selected list i get the error java.lang.IndexOutOfBoundsException: Index: 3, Size: 3.

Here I have list size 3 i.e index 0 1 2 and I got the error in index 3.


问:
Does Clojure have an efficient, idiomatic approach for decorators?
In Clojure(script) you define programming constructs with deftype and defrecord.  We want our constructs to each have a specific, well-defined purpose.  Rather than evolve any one construct into a monolithic full-featured thing, we choose to segregate responsibilities.  Decorators (e.g. data structures that wrap other data structures) are good for this.

For example, you have a logger construct.  You add timestamping as a feature with a decorator.  You later add alerting support staff beepers as another decorator.  We can, in theory, layer on any number of features this way.  Our config file cleanly determines which features get included.

If our logger implements a 3-method Logging protocol and each decorator only augments one, you still have to implement the other two methods on each decorator to uphold the contractual api.  These add-nothing implementations simply pass the message down the chain.  This is the awkward bit.

The richer a construct's api, the worse the problem.  Consider a construct that implements a few protocols and the work necessary to decorate something that handles 12 or so methods.

Is there a mechanism, macro, or technique that you've found to overcomes this?

答:
As a wildly different approach from using extend, it's not too hard to define a defdecorator macro that'll supply any missing protocol definitions by delegating to the decorated implementation.

Again, starting with a protocol like:

```<code>(defprotocol Logger
  (info [logger s])
  (warn [logger s])
  (debug [logger s]))

(def println-logger
  (reify Logger
    (info [_ s]
      (println "Info:" s))
    (warn [_ s]
      (println "Warn:" s))
    (debug [_ s]
      (println "Debug:" s))))
</code>```

You can write some machinery to create protocol definitions by inspecting the protocol to get all of its functions, then creating delegating implementations for any that're missing:

```<code>(defn protocol-fn-matches?
  "Returns the protocol function definition
   if it matches the desired name and arglist."
  [[name arglist :as def] desired-name desired-arglist]
  (when (and (= name desired-name)
             (= (count arglist) (count desired-arglist)))
    def))

(defn genarglist
  "Takes an arglist and generates a new one with unique symbol names."
  [arglist]
  (mapv (fn [arg]
          (gensym (str arg)))
        arglist))

(defn get-decorator-definitions
  "Generates the protocol functions for a decorator,
   defaulting to forwarding to the implementation if
   a function is not overwritten."
  [protocol-symbol impl fs]
  (let [protocol-var (or (resolve protocol-symbol)
                         (throw (Exception. (str "Unable to resolve protocol: " protocol-symbol))))
        protocol-ns (-> protocol-var meta :ns)
        protocol (var-get protocol-var)]
    (for [{:keys [name arglists]} (vals (:sigs protocol))
          arglist arglists]
      (or (some #(protocol-fn-matches? % name arglist) fs)
          (let [arglist (genarglist arglist) ; Generate unique names to avoid collision
                forwarded-args (rest arglist) ; Drop the "this" arg
                f (symbol (str protocol-ns) (str name))] ; Get the function in the protocol namespace
            `(~name ~arglist
               (~f ~impl ~@forwarded-args)))))))
</code>```

You can then write a macro that takes the definitions and creates a record extending the given protocols, using get-decorator-definitions to supply any missing definitions:

```<code>(defmacro defdecorator
  [type-symbol fields impl & body]
  (let [provided-protocols-and-defs (->> body
                                         (partition-by symbol?)
                                         (partition-all 2))
        protocols-and-defs (mapcat (fn [[[protocol] fs]]
                                     (cons protocol
                                           (get-decorator-definitions protocol impl fs)))
                                   provided-protocols-and-defs)]
    `(defrecord ~type-symbol ~fields
       ~@protocols-and-defs)))
</code>```

And use it to create new decorators:

```<code>(defdecorator CapslockWarningLogger
              [impl] impl
              Logger
              (warn [_ s]
                    (warn impl (clojure.string/upper-case s))))

(defdecorator SelectiveDebugLogger
              [ignored impl] impl
              Logger
              (debug [_ s]
                     (when-not (ignored s)
                       (debug impl s))))
</code>```

Body:
As a wildly different approach from using extend, it's not too hard to define a defdecorator macro that'll supply any missing protocol definitions by delegating to the decorated implementation.

Again, starting with a protocol like:

(defprotocol Logger
  (info [logger s])
  (warn [logger s])
  (debug [logger s]))

(def println-logger
  (reify Logger
    (info [_ s]
      (println "Info:" s))
    (warn [_ s]
      (println "Warn:" s))
    (debug [_ s]
      (println "Debug:" s))))

You can write some machinery to create protocol definitions by inspecting the protocol to get all of its functions, then creating delegating implementations for any that're missing:

(defn protocol-fn-matches?
  "Returns the protocol function definition
   if it matches the desired name and arglist."
  [[name arglist :as def] desired-name desired-arglist]
  (when (and (= name desired-name)
             (= (count arglist) (count desired-arglist)))
    def))

(defn genarglist
  "Takes an arglist and generates a new one with unique symbol names."
  [arglist]
  (mapv (fn [arg]
          (gensym (str arg)))
        arglist))

(defn get-decorator-definitions
  "Generates the protocol functions for a decorator,
   defaulting to forwarding to the implementation if
   a function is not overwritten."
  [protocol-symbol impl fs]
  (let [protocol-var (or (resolve protocol-symbol)
                         (throw (Exception. (str "Unable to resolve protocol: " protocol-symbol))))
        protocol-ns (-> protocol-var meta :ns)
        protocol (var-get protocol-var)]
    (for [{:keys [name arglists]} (vals (:sigs protocol))
          arglist arglists]
      (or (some #(protocol-fn-matches? % name arglist) fs)
          (let [arglist (genarglist arglist) ; Generate unique names to avoid collision
                forwarded-args (rest arglist) ; Drop the "this" arg
                f (symbol (str protocol-ns) (str name))] ; Get the function in the protocol namespace
            `(~name ~arglist
               (~f ~impl ~@forwarded-args)))))))

You can then write a macro that takes the definitions and creates a record extending the given protocols, using get-decorator-definitions to supply any missing definitions:

(defmacro defdecorator
  [type-symbol fields impl & body]
  (let [provided-protocols-and-defs (->> body
                                         (partition-by symbol?)
                                         (partition-all 2))
        protocols-and-defs (mapcat (fn [[[protocol] fs]]
                                     (cons protocol
                                           (get-decorator-definitions protocol impl fs)))
                                   provided-protocols-and-defs)]
    `(defrecord ~type-symbol ~fields
       ~@protocols-and-defs)))

And use it to create new decorators:

(defdecorator CapslockWarningLogger
              [impl] impl
              Logger
              (warn [_ s]
                    (warn impl (clojure.string/upper-case s))))

(defdecorator SelectiveDebugLogger
              [ignored impl] impl
              Logger
              (debug [_ s]
                     (when-not (ignored s)
                       (debug impl s))))


问:
Node.js: Gzip compression?
Am I wrong in finding that Node.js does no gzip compression and there are no modules out there to perform gzip compression? How can anyone use a web server that has no compression? What am I missing here? Should I try to—gasp—port the algorithm to JavaScript for server-side use?</p>

答:
There are multiple Gzip middlewares for Express, KOA and others. For example:
https://www.npmjs.com/package/express-static-gzip

However, Node is awfully bad at doing CPU intensive tasks like gzipping, SSL termination, etc. Instead, use a ‘real’ middleware services like nginx or HAproxy, see bullet 3 here:
http://goldbergyoni.com/checklist-best-practice-of-node-js-in-production/

Title: Node.js: Gzip compression?


问:
Group JSON by key
I have structured JSON data as below:

```<code>[
    {
        "Month": "Jan"
        "Year": 2015,
        "Count": 15
    },
    {
        "Month": "Feb"
        "Year": 2015,
        "Count": 5
    },
    {
        "Month": "Jan"
        "Year": 2016,
        "Count": 25
    },
        {
        "Month": "Feb"
        "Year": 2016,
        "Count": 50
    }
]
</code>```

I want to group the data using JavaScript to get the below output. Can someone help me with this?

```<code>[
    {
        "Month": "Jan"
        "Count_2015": 15,
        "Count_2016": 25
    },
    {
        "Month": "Feb"
        "Count_2015": 5,
        "Count_2016": 50
    }
]
</code>```

答:
You can use forEach() loop and use one object as thisArg param.

var data = [{"Month":"Jan","Year":2015,"Count":15},{"Month":"Feb","Year":2015,"Count":5},{"Month":"Jan","Year":2016,"Count":25},{"Month":"Feb","Year":2016,"Count":50}]

var result = []
data.forEach(function(e, i) {
  if (!this[e.Month]) {
    this[e.Month] = {
      Month: e.Month,
      ['Count_' + e.Year]: e.Count
    }
    result.push(this[e.Month])
  } else {
    this[e.Month]['Count_' + e.Year] = e.Count
  }
}, {})

console.log(result)```

Title: Group JSON by key

Body:
I have structured JSON data as below:

[
    {
        "Month": "Jan"
        "Year": 2015,
        "Count": 15
    },
    {
        "Month": "Feb"
        "Year": 2015,
        "Count": 5
    },
    {
        "Month": "Jan"
        "Year": 2016,
        "Count": 25
    },
        {
        "Month": "Feb"
        "Year": 2016,
        "Count": 50
    }
]

I want to group the data using JavaScript to get the below output. Can someone help me with this?

[
    {
        "Month": "Jan"
        "Count_2015": 15,
        "Count_2016": 25
    },
    {
        "Month": "Feb"
        "Count_2015": 5,
        "Count_2016": 50
    }
]


问:
Facebook with Membership Provider?
I am using Facebook connect for my project with custom written code to deal with authentication, Do you suggest using Membership provider to deal with users or should i develop some custom Database in Backend.

Please give a hint on how to do in any of the above ways....

Update

with custom Database i mean Developing a Custom membership Provider

Update

Please suggest what should be the schema of the Custom Database for the custom Membership provider

答:
The membership database is primarily for storing usernames and passwords, definitely not for storing cookies or session. I'm not familiar with how facebook connect works, but I'm guessing you can't even store the password.  If you can't manage passwords there's no reason use to asp.net membership.

My suggestion is to compare the membership database against your own concept for the database and see if there's any real overlap....I'm guessing there isn't.

http://superpatrick.wordpress.com/2007/11/21/aspnet-membership-schema/

ContentLicense: CC BY-SA 2.5

Title: Facebook with Membership Provider?


问:
Round up double to 2 decimal places
How do I round up currentRatio to two decimal places?

```<code>let currentRatio = Double (rxCurrentTextField.text!)! / Double (txCurrentTextField.text!)!
railRatioLabelField.text! = "\(currentRatio)"
</code>```

答:
Adding to above answer if we want to format Double multiple times, we can use protocol extension of Double like below:</p>

```<code>extension Double {
    var dollarString:String {
        return String(format: "$%.2f", self)
    }
}

let a = 45.666

print(a.dollarString) //will print "$45.67"
</code>```

Title: Round up double to 2 decimal places

Body:
How do I round up currentRatio to two decimal places?

let currentRatio = Double (rxCurrentTextField.text!)! / Double (txCurrentTextField.text!)!
railRatioLabelField.text! = "\(currentRatio)"

Body:
Adding to above answer if we want to format Double multiple times, we can use protocol extension of Double like below:

extension Double {
    var dollarString:String {
        return String(format: "$%.2f", self)
    }
}

let a = 45.666

print(a.dollarString) //will print "$45.67"


问:
Solving nonlinear system of differential equations in matlab usin ODE45
i am trying to solve a system of nonlinear differential equation using ODE45 MATLAB , i did that many times successfully , but this time i get the following error and i really don't know what is wrong i am confused compeletly. here are the codes.

%%  this is the error:

```<code>Subscript indices must either be real positive integers or logicals.

Error in non_L_ss (line 6)
        (-Fk*(ds0+x(3)-x(1))+Fk*ds0-Fc(x(4)-x(2)))/ms +Fa/ms ] ;

Error in odearguments (line 87)
f0 = feval(ode,t0,y0,args{:});   % ODE15I sets args{1} to yp0.

Error in ode45 (line 115)
odearguments(FcnHandlesUsed,solver_name,ode, tspan,y0,optio varargin);

Error in solve (line 50)
[t X]=ode45(@non_L_ss,t_span,IC);
</code>```

%% the equations be defined in a function:

```<code>function dX=non_L_ss(t,x)
global Fk Fc kt Fa q ds0 ms mu
dX=[ x(2);
     (Fk*(ds0+x(3)-x(1))-Fk*ds0+Fc*(x(4)-x(2))-kt*x(1))/mu-Fa/m-kt*q/mu ;
     x(4);
     (-Fk*(ds0+x(3)-x(1))+Fk*ds0-Fc(x(4)-x(2)))/ms +Fa/ms ] ;
end
</code>```

%%  and here the function be called to solve by ODE45:

```<code>clear
clc
global Fk Fc kt Fa q ds0 ms mu qdot v2
mu = 100 ;
ms = 1242 ;
k1s = 80000 ;
k2s = 32000 ;
kt = 405000 ;
c1s = 4000 ;
c2s = 1600 ;
v = 20 ;
Gq = 256e-6 ;
ds0 = 0.1538 ;
a = 1 ;
b = 0.001 ;
n0 = 0.1 ;
f0 = 0.011*v ;
w = 0.5 ;
Fa = 2000 ;
q = 0.05 ;
xs = 0.1 ;
xu = 0.1 ;
dxs = 0.1 ;
dxu = 0.2 ;

Fk = k1s+k2s*(ds0+xs-xu).^2 ;

if dxs >= dxu
Fc = c1s ;
elseif dxs < dxu
Fc = c2s ;
end

t_span=[0 1];
IC=[2 3 2 2];
[t X]=ode45(@non_L_ss,t_span,IC);
</code>```

答:
```<code>Subscript indices must either be real positive integers or logicals.

Error in non_L_ss (line 6)
    (-Fk*(ds0+x(3)-x(1))+Fk*ds0-Fc(x(4)-x(2)))/ms +Fa/ms ] ;
</code>```

means that you use something as an indexed array with a non-integer index. Which probably means that the object is no array at all. I'd propose to replace

```<code>Fc(x(4)-x(2))
</code>```

by

```<code>Fc*(x(4)-x(2))
</code>```

to try to solve this issue.

Body:
i am trying to solve a system of nonlinear differential equation using ODE45 MATLAB , i did that many times successfully , but this time i get the following error and i really don't know what is wrong i am confused compeletly. here are the codes.

%%  this is the error:

Subscript indices must either be real positive integers or logicals.

Error in non_L_ss (line 6)
        (-Fk*(ds0+x(3)-x(1))+Fk*ds0-Fc(x(4)-x(2)))/ms +Fa/ms ] ;

Error in odearguments (line 87)
f0 = feval(ode,t0,y0,args{:});   % ODE15I sets args{1} to yp0.

Error in ode45 (line 115)
odearguments(FcnHandlesUsed,solver_name,ode, tspan,y0,optio varargin);

Error in solve (line 50)
[t X]=ode45(@non_L_ss,t_span,IC);

%% the equations be defined in a function:

function dX=non_L_ss(t,x)
global Fk Fc kt Fa q ds0 ms mu
dX=[ x(2);
     (Fk*(ds0+x(3)-x(1))-Fk*ds0+Fc*(x(4)-x(2))-kt*x(1))/mu-Fa/m-kt*q/mu ;
     x(4);
     (-Fk*(ds0+x(3)-x(1))+Fk*ds0-Fc(x(4)-x(2)))/ms +Fa/ms ] ;
end

%%  and here the function be called to solve by ODE45:

clear
clc
global Fk Fc kt Fa q ds0 ms mu qdot v2
mu = 100 ;
ms = 1242 ;
k1s = 80000 ;
k2s = 32000 ;
kt = 405000 ;
c1s = 4000 ;
c2s = 1600 ;
v = 20 ;
Gq = 256e-6 ;
ds0 = 0.1538 ;
a = 1 ;
b = 0.001 ;
n0 = 0.1 ;
f0 = 0.011*v ;
w = 0.5 ;
Fa = 2000 ;
q = 0.05 ;
xs = 0.1 ;
xu = 0.1 ;
dxs = 0.1 ;
dxu = 0.2 ;

Fk = k1s+k2s*(ds0+xs-xu).^2 ;

if dxs >= dxu
Fc = c1s ;
elseif dxs < dxu
Fc = c2s ;
end

t_span=[0 1];
IC=[2 3 2 2];
[t X]=ode45(@non_L_ss,t_span,IC);

Body:
Subscript indices must either be real positive integers or logicals.

Error in non_L_ss (line 6)
    (-Fk*(ds0+x(3)-x(1))+Fk*ds0-Fc(x(4)-x(2)))/ms +Fa/ms ] ;

means that you use something as an indexed array with a non-integer index. Which probably means that the object is no array at all. I'd propose to replace

Fc(x(4)-x(2))

by

Fc*(x(4)-x(2))

to try to solve this issue.


问:
Tomcat apps fail to deploy with STRICT_SERVLET_COMPLIANCE=true
I am trying to deploy an application on Tomcat 8.0.39 with option STRICT_SERVLET_COMPLIANCE=true by updating apache-tomcat-8.0.39\conf\catalina.properties but as soon as I do that my application deployment fails.
i.e. I start getting errors:
SEVERE [localhost-startStop-1] org.apache.tomcat.util.digester.Digester.error Parse Error for all the tags in applications web.xml file.

One of the stack trace is as follows:

09-Feb-2017 15:06:32.189 SEVERE [localhost-startStop-1] org.apache.tomcat.util.digester.Digester.error Parse Error at line 5 column 66: Document root element "web-app", must match DOCTYPE root "xml".
   org.xml.sax.SAXParseException; systemId: file:/C:/Servers/Tomcat%208/apache-tomcat-8.0.39/webapps/file-service/WEB-INF/web.xml; lineNumber: 5; columnNumber: 66; Document root element "web-app", must match DOCTYPE root "xml".
      at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.createSAXParseException(Unknown Source)
      at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.error(Unknown Source)
      at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(Unknown Source)
      at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(Unknown Source)
      at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(Unknown Source)
      at com.sun.org.apache.xerces.internal.impl.dtd.XMLDTDValidator.rootElementSpecified(Unknown Source)
      at com.sun.org.apache.xerces.internal.impl.dtd.XMLDTDValidator.handleStartElement(Unknown Source)
      at com.sun.org.apache.xerces.internal.impl.dtd.XMLDTDValidator.startElement(Unknown Source)
      at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.scanStartElement(Unknown Source)
      at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl$NSContentDriver.scanRootElementHook(Unknown Source)
      at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl$FragmentContentDriver.next(Unknown Source)
      at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl$PrologDriver.next(Unknown Source)
      at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(Unknown Source)
      at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.next(Unknown Source)
      at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(Unknown Source)
      at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(Unknown Source)
      at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(Unknown Source)
      at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(Unknown Source)
      at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.parse(Unknown Source)
      at com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl$JAXPSAXParser.parse(Unknown Source)
      at org.apache.tomcat.util.digester.Digester.parse(Digester.java:1448)
      at org.apache.tomcat.util.descriptor.web.WebXmlParser.parseWebXml(WebXmlParser.java:119)
      at org.apache.catalina.startup.ContextConfig.webConfig(ContextConfig.java:1119)
      at org.apache.catalina.startup.ContextConfig.configureStart(ContextConfig.java:783)
      at org.apache.catalina.startup.ContextConfig.lifecycleEvent(ContextConfig.java:307)
      at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:95)
      at org.apache.catalina.util.LifecycleBase.fireLifecycleEvent(LifecycleBase.java:90)
      at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5213)
      at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:145)
      at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1408)
      at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1398)
      at java.util.concurrent.FutureTask.run(Unknown Source)
      at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
      at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
      at java.lang.Thread.run(Unknown Source)

For resolving that issue, I tried following options:

1) Added following in catalina.properties:

```<code>org.apache.catalina.STRICT_SERVLET_COMPLIANCE=true
org.apache.tomcat.util.http.ServerCookie.FWD_SLASH_IS_SEPARATOR=false
</code>```

2) Updated agent WAR web.xml File
Updated web-app_3_0.xsd with web-app_2_5.xsd
Updated version="3.0" with version="2.5"

I also tried copying "web-app" tag entry from apache-tomcat-8.0.39\conf\web.xml to my applications web.xml but of no use.

3) Tried setting following values to their respective default values [as setting

```<code>org.apache.catalina.STRICT_SERVLET_COMPLIANCE=true changes these defaults]
org.apache.catalina.core.ApplicationContext.GET_RESOURCE_REQUIRE_SLASH
org.apache.catalina.core.ApplicationDispatcher.WRAP_SAME_OBJECT
org.apache.catalina.core.StandardHostValve.ACCESS_SESSION
org.apache.catalina.session.StandardSession.ACTIVITY_CHECK
org.apache.catalina.session.StandardSession.LAST_ACCESS_AT_START
org.apache.tomcat.util.http.ServerCookie.STRICT_NAMING

The **URIEncoding** attribute of any HTTP connector or AJP connector element.
The **resourceOnlyServlets** attribute of any Context element.
The **tldValidation** attribute of any Context element.
The **useRelativeRedirects** attribute of any Context element.
The **xmlNamespaceAware** attribute of any Context element.
The **xmlValidation** attribute of any Context element.
</code>```

But nothing seems to be working fine. I am also not able to navigate to tomcat manager or any other application deployed.

On the other hand every thing works fine when I write STRICT_SERVLET_COMPLIANCE=false in catalina.properties

Is there something which I am missing here? Please help me in resolving this issue.

Regards,
Bhupesh

答:
I ran into this issue as well.  The environment we work in requires the STRICT_SERVLET_COMPLIANCE be set to true, but the validation of the web.xml was not the driving force behind the requirement.  To get around the issue try setting the xmlValidation to false in the conf/context.xml's  tag:</p>

```<code><Context xmlValidation="false"> ... </Context>
</code>```

Body:
I am trying to deploy an application on Tomcat 8.0.39 with option STRICT_SERVLET_COMPLIANCE=true by updating apache-tomcat-8.0.39\conf\catalina.properties but as soon as I do that my application deployment fails.
i.e. I start getting errors:
SEVERE [localhost-startStop-1] org.apache.tomcat.util.digester.Digester.error Parse Error for all the tags in applications web.xml file.

One of the stack trace is as follows:

09-Feb-2017 15:06:32.189 SEVERE [localhost-startStop-1] org.apache.tomcat.util.digester.Digester.error Parse Error at line 5 column 66: Document root element "web-app", must match DOCTYPE root "xml".
   org.xml.sax.SAXParseException; systemId: file:/C:/Servers/Tomcat%208/apache-tomcat-8.0.39/webapps/file-service/WEB-INF/web.xml; lineNumber: 5; columnNumber: 66; Document root element "web-app", must match DOCTYPE root "xml".
      at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.createSAXParseException(Unknown Source)
      at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.error(Unknown Source)
      at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(Unknown Source)
      at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(Unknown Source)
      at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(Unknown Source)
      at com.sun.org.apache.xerces.internal.impl.dtd.XMLDTDValidator.rootElementSpecified(Unknown Source)
      at com.sun.org.apache.xerces.internal.impl.dtd.XMLDTDValidator.handleStartElement(Unknown Source)
      at com.sun.org.apache.xerces.internal.impl.dtd.XMLDTDValidator.startElement(Unknown Source)
      at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.scanStartElement(Unknown Source)
      at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl$NSContentDriver.scanRootElementHook(Unknown Source)
      at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl$FragmentContentDriver.next(Unknown Source)
      at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl$PrologDriver.next(Unknown Source)
      at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(Unknown Source)
      at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.next(Unknown Source)
      at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(Unknown Source)
      at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(Unknown Source)
      at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(Unknown Source)
      at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(Unknown Source)
      at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.parse(Unknown Source)
      at com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl$JAXPSAXParser.parse(Unknown Source)
      at org.apache.tomcat.util.digester.Digester.parse(Digester.java:1448)
      at org.apache.tomcat.util.descriptor.web.WebXmlParser.parseWebXml(WebXmlParser.java:119)
      at org.apache.catalina.startup.ContextConfig.webConfig(ContextConfig.java:1119)
      at org.apache.catalina.startup.ContextConfig.configureStart(ContextConfig.java:783)
      at org.apache.catalina.startup.ContextConfig.lifecycleEvent(ContextConfig.java:307)
      at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:95)
      at org.apache.catalina.util.LifecycleBase.fireLifecycleEvent(LifecycleBase.java:90)
      at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5213)
      at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:145)
      at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1408)
      at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1398)
      at java.util.concurrent.FutureTask.run(Unknown Source)
      at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
      at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
      at java.lang.Thread.run(Unknown Source)

For resolving that issue, I tried following options:

1) Added following in catalina.properties:

org.apache.catalina.STRICT_SERVLET_COMPLIANCE=true
org.apache.tomcat.util.http.ServerCookie.FWD_SLASH_IS_SEPARATOR=false

2) Updated agent WAR web.xml File
Updated web-app_3_0.xsd with web-app_2_5.xsd
Updated version="3.0" with version="2.5"

I also tried copying "web-app" tag entry from apache-tomcat-8.0.39\conf\web.xml to my applications web.xml but of no use.

3) Tried setting following values to their respective default values [as setting

org.apache.catalina.STRICT_SERVLET_COMPLIANCE=true changes these defaults]
org.apache.catalina.core.ApplicationContext.GET_RESOURCE_REQUIRE_SLASH
org.apache.catalina.core.ApplicationDispatcher.WRAP_SAME_OBJECT
org.apache.catalina.core.StandardHostValve.ACCESS_SESSION
org.apache.catalina.session.StandardSession.ACTIVITY_CHECK
org.apache.catalina.session.StandardSession.LAST_ACCESS_AT_START
org.apache.tomcat.util.http.ServerCookie.STRICT_NAMING

The **URIEncoding** attribute of any HTTP connector or AJP connector element.
The **resourceOnlyServlets** attribute of any Context element.
The **tldValidation** attribute of any Context element.
The **useRelativeRedirects** attribute of any Context element.
The **xmlNamespaceAware** attribute of any Context element.
The **xmlValidation** attribute of any Context element.

But nothing seems to be working fine. I am also not able to navigate to tomcat manager or any other application deployed.

On the other hand every thing works fine when I write STRICT_SERVLET_COMPLIANCE=false in catalina.properties

Is there something which I am missing here? Please help me in resolving this issue.

Regards,
Bhupesh

Body:
I ran into this issue as well.  The environment we work in requires the STRICT_SERVLET_COMPLIANCE be set to true, but the validation of the web.xml was not the driving force behind the requirement.  To get around the issue try setting the xmlValidation to false in the conf/context.xml's  tag:

<Context xmlValidation="false"> ... </Context>


问:
Pandas: complex mapping between different sized DataFrames
I have two completely different dataframes that I need to map (thanks biology). All the tutorials out there on pandas are on much simpler conversions, and I can't get around solving this (real newbie) without 4 nested loops without success. Really curious on a pythonic way to solve this problem without having to go back to Excel.

The first is something like this df1. Observations of zeros and 1s for thousands of genes in a-j categories.

```<code>import pandas as pd
import numpy as np

df1 = pd.DataFrame(np.random.randint(0,2,size =(10,10)),columns=list('abcdefghij'), index = ['gene1','gene2','gene3','gene4','gene5','gene6','gene7','gene8','gene9','gene10'])

print(df1)

        a  b  c  d  e  f  g  h  i  j
gene1   1  0  1  0  1  0  1  1  1  0
gene2   0  1  0  0  0  0  0  0  1  0
gene3   0  1  1  1  1  1  0  0  0  0
gene4   1  0  1  0  0  1  0  1  1  1
gene5   0  0  1  0  0  0  0  0  0  0
gene6   0  1  0  0  1  0  1  0  1  0
gene7   1  1  0  1  1  0  0  0  1  0
gene8   0  0  0  1  1  1  1  0  1  0
gene9   1  0  1  0  1  0  1  1  0  1
gene10  1  0  0  0  1  0  1  0  1  1
</code>```

Then the second is something like this df2. A mapping of higher level categories (X-W) for the lower level ones. This girl has NaNs and no indexes.

```<code>df2 = pd.DataFrame({'X': ['a','NaN','NaN','NaN'],
                       'Y': ['d', 'b', 'c','f'],
                       'Z':['g', 'h','e','NaN'],
                       'W': ['i', 'j','NaN','Nan']},index=None)

print(df2)

     W    X  Y    Z
0    i    a  d    g
1    j  NaN  b    h
2  NaN  NaN  c    e
3  Nan  NaN  f  NaN
</code>```

What I need is something like result1. Here resides another tricky thing. E.g. gene4 is in i and j categories, and both are in W, but I still just want a '1' in result1.loc['gene4','W']. The final result still needs to be binary.

```<code>result1 = pd.DataFrame({'X': ['1','0','0','1','0','0','1','0','1','1'],
                   'Y': ['1','1','1','1','1','1','1','1','1','0'],
                   'Z': ['1','0','1','1','0','1','1','1','1','1'],
                   'W': ['1','1','0','1','0','1','1','1','1','1']}, index = ['gene1','gene2','gene3','gene4','gene5','gene6','gene7','gene8','gene9','gene10'])
print(result1)

        W  X  Y  Z
gene1   1  1  1  1
gene2   1  0  1  0
gene3   0  0  1  1
gene4   1  1  1  1
gene5   0  0  1  0
gene6   1  0  1  1
gene7   1  1  1  1
gene8   1  0  1  1
gene9   1  1  1  1
gene10  1  1  0  1
</code>```

This could be another possible result format. [updated with actual expected result]. If someone is feeling like teaching them both (or an easy interconversion), much extra appreciation, and science is also grateful.

```<code>result1 = pd.DataFrame({'1': ['gene1','gene1','gene1','gene1'],
                       '2': ['gene2','gene4','gene2','gene3'],
                       '3': ['gene4','gene7','gene3','gene4'],
                       '4': ['gene6','gene9','gene4','gene6'],
                       '5': ['gene7','gene10','gene5','gene7'],
                       '6': ['gene8','NaN','gene6','gene8'],
                       '7': ['gene9','NaN','gene7','gene9'],
                       '8': ['gene10','NaN','gene8','gene10'],
                       '9': ['NaN','NaN','gene9','NaN'],
                       },
                       index = ['W','X','Y','Z'])
print(result1)

       1      2      3      4       5      6      7       8      9
W  gene1  gene2  gene4  gene6   gene7  gene8  gene9  gene10    NaN
X  gene1  gene4  gene7  gene9  gene10    NaN    NaN     NaN    NaN
Y  gene1  gene2  gene3  gene4   gene5  gene6  gene7   gene8  gene9
Z  gene1  gene3  gene4  gene6   gene7  gene8  gene9  gene10    NaN
</code>```

Thank you a lot for your patience reading this long question.

答:
Here we go!  Let's try this.

```<code>df1 = pd.DataFrame(np.random.randint(0,2,size =(10,10)),columns=list('abcdefghij'), index = ['gene1','gene2','gene3','gene4','gene5','gene6','gene7','gene8','gene9','gene10'])

df2 = pd.DataFrame({'X': ['a','NaN','NaN','NaN'],
                       'Y': ['d', 'b', 'c','f'],
                       'Z':['g', 'h','e','NaN'],
                       'W': ['i', 'j','NaN','NaN']},index=None)

df2 = df2.replace('NaN',np.nan)

gmap = df2.stack().reset_index().drop('level_0',axis=1).set_index(0)['level_1']

df3 = df1.stack().replace(0,np.nan).dropna().reset_index(level=1)['level_1'].map(gmap).reset_index().drop_duplicates()

df_out = df3.groupby(['index','level_1'])['level_1'].count().unstack()

print(df_out)
</code>```

Output:

```<code>level_1    W    X    Y    Z
index
gene1    1.0  NaN  NaN  NaN
gene10   1.0  1.0  1.0  1.0
gene2    1.0  1.0  1.0  1.0
gene3    1.0  1.0  1.0  1.0
gene4    1.0  NaN  1.0  1.0
gene5    1.0  NaN  1.0  NaN
gene6    1.0  1.0  1.0  1.0
gene7    NaN  1.0  1.0  1.0
gene8    NaN  NaN  1.0  1.0
gene9    1.0  NaN  NaN  1.0
</code>```

Edit to get optional output

```<code>df1 = pd.DataFrame(np.random.randint(0,2,size =(10,10)),columns=list('abcdefghij'), index = ['gene1','gene2','gene3','gene4','gene5','gene6','gene7','gene8','gene9','gene10'])

df2 = pd.DataFrame({'X': ['a','NaN','NaN','NaN'],
                       'Y': ['d', 'b', 'c','f'],
                       'Z':['g', 'h','e','NaN'],
                       'W': ['i', 'j','NaN','NaN']},index=None)

df2 = df2.replace('NaN',np.nan)

gmap = df2.stack().reset_index().drop('level_0',axis=1).set_index(0)['level_1']

df3 = df1.stack().replace(0,np.nan).dropna().reset_index(level=1)['level_1'].map(gmap).reset_index().drop_duplicates()

df3['cols'] = df3['index'].str.split('gene').str[1].astype(int)

df_out2 = df3.set_index(['level_1','cols'])['index'].unstack()
</code>```

Output:

```<code>cols        1      2      3      4      5      6      7      8      9       10
level_1
W        gene1  gene2  gene3  gene4  gene5   None  gene7  gene8  gene9  gene10
X         None   None  gene3   None  gene5   None   None  gene8  gene9  gene10
Y        gene1  gene2  gene3  gene4  gene5  gene6  gene7  gene8  gene9  gene10
Z         None  gene2   None  gene4   None  gene6   None  gene8  gene9    None
</code>```

Body:
I have two completely different dataframes that I need to map (thanks biology). All the tutorials out there on pandas are on much simpler conversions, and I can't get around solving this (real newbie) without 4 nested loops without success. Really curious on a pythonic way to solve this problem without having to go back to Excel.

The first is something like this df1. Observations of zeros and 1s for thousands of genes in a-j categories.

import pandas as pd
import numpy as np

df1 = pd.DataFrame(np.random.randint(0,2,size =(10,10)),columns=list('abcdefghij'), index = ['gene1','gene2','gene3','gene4','gene5','gene6','gene7','gene8','gene9','gene10'])

print(df1)

        a  b  c  d  e  f  g  h  i  j
gene1   1  0  1  0  1  0  1  1  1  0
gene2   0  1  0  0  0  0  0  0  1  0
gene3   0  1  1  1  1  1  0  0  0  0
gene4   1  0  1  0  0  1  0  1  1  1
gene5   0  0  1  0  0  0  0  0  0  0
gene6   0  1  0  0  1  0  1  0  1  0
gene7   1  1  0  1  1  0  0  0  1  0
gene8   0  0  0  1  1  1  1  0  1  0
gene9   1  0  1  0  1  0  1  1  0  1
gene10  1  0  0  0  1  0  1  0  1  1

Then the second is something like this df2. A mapping of higher level categories (X-W) for the lower level ones. This girl has NaNs and no indexes.

df2 = pd.DataFrame({'X': ['a','NaN','NaN','NaN'],
                       'Y': ['d', 'b', 'c','f'],
                       'Z':['g', 'h','e','NaN'],
                       'W': ['i', 'j','NaN','Nan']},index=None)

print(df2)

     W    X  Y    Z
0    i    a  d    g
1    j  NaN  b    h
2  NaN  NaN  c    e
3  Nan  NaN  f  NaN

What I need is something like result1. Here resides another tricky thing. E.g. gene4 is in i and j categories, and both are in W, but I still just want a '1' in result1.loc['gene4','W']. The final result still needs to be binary.

result1 = pd.DataFrame({'X': ['1','0','0','1','0','0','1','0','1','1'],
                   'Y': ['1','1','1','1','1','1','1','1','1','0'],
                   'Z': ['1','0','1','1','0','1','1','1','1','1'],
                   'W': ['1','1','0','1','0','1','1','1','1','1']}, index = ['gene1','gene2','gene3','gene4','gene5','gene6','gene7','gene8','gene9','gene10'])
print(result1)

        W  X  Y  Z
gene1   1  1  1  1
gene2   1  0  1  0
gene3   0  0  1  1
gene4   1  1  1  1
gene5   0  0  1  0
gene6   1  0  1  1
gene7   1  1  1  1
gene8   1  0  1  1
gene9   1  1  1  1
gene10  1  1  0  1

This could be another possible result format. [updated with actual expected result]. If someone is feeling like teaching them both (or an easy interconversion), much extra appreciation, and science is also grateful.

result1 = pd.DataFrame({'1': ['gene1','gene1','gene1','gene1'],
                       '2': ['gene2','gene4','gene2','gene3'],
                       '3': ['gene4','gene7','gene3','gene4'],
                       '4': ['gene6','gene9','gene4','gene6'],
                       '5': ['gene7','gene10','gene5','gene7'],
                       '6': ['gene8','NaN','gene6','gene8'],
                       '7': ['gene9','NaN','gene7','gene9'],
                       '8': ['gene10','NaN','gene8','gene10'],
                       '9': ['NaN','NaN','gene9','NaN'],
                       },
                       index = ['W','X','Y','Z'])
print(result1)

       1      2      3      4       5      6      7       8      9
W  gene1  gene2  gene4  gene6   gene7  gene8  gene9  gene10    NaN
X  gene1  gene4  gene7  gene9  gene10    NaN    NaN     NaN    NaN
Y  gene1  gene2  gene3  gene4   gene5  gene6  gene7   gene8  gene9
Z  gene1  gene3  gene4  gene6   gene7  gene8  gene9  gene10    NaN

Thank you a lot for your patience reading this long question.

Body:
Here we go!  Let's try this.

df1 = pd.DataFrame(np.random.randint(0,2,size =(10,10)),columns=list('abcdefghij'), index = ['gene1','gene2','gene3','gene4','gene5','gene6','gene7','gene8','gene9','gene10'])

df2 = pd.DataFrame({'X': ['a','NaN','NaN','NaN'],
                       'Y': ['d', 'b', 'c','f'],
                       'Z':['g', 'h','e','NaN'],
                       'W': ['i', 'j','NaN','NaN']},index=None)

df2 = df2.replace('NaN',np.nan)

gmap = df2.stack().reset_index().drop('level_0',axis=1).set_index(0)['level_1']

df3 = df1.stack().replace(0,np.nan).dropna().reset_index(level=1)['level_1'].map(gmap).reset_index().drop_duplicates()

df_out = df3.groupby(['index','level_1'])['level_1'].count().unstack()

print(df_out)

Output:

level_1    W    X    Y    Z
index
gene1    1.0  NaN  NaN  NaN
gene10   1.0  1.0  1.0  1.0
gene2    1.0  1.0  1.0  1.0
gene3    1.0  1.0  1.0  1.0
gene4    1.0  NaN  1.0  1.0
gene5    1.0  NaN  1.0  NaN
gene6    1.0  1.0  1.0  1.0
gene7    NaN  1.0  1.0  1.0
gene8    NaN  NaN  1.0  1.0
gene9    1.0  NaN  NaN  1.0

Edit to get optional output

df1 = pd.DataFrame(np.random.randint(0,2,size =(10,10)),columns=list('abcdefghij'), index = ['gene1','gene2','gene3','gene4','gene5','gene6','gene7','gene8','gene9','gene10'])

df2 = pd.DataFrame({'X': ['a','NaN','NaN','NaN'],
                       'Y': ['d', 'b', 'c','f'],
                       'Z':['g', 'h','e','NaN'],
                       'W': ['i', 'j','NaN','NaN']},index=None)

df2 = df2.replace('NaN',np.nan)

gmap = df2.stack().reset_index().drop('level_0',axis=1).set_index(0)['level_1']

df3 = df1.stack().replace(0,np.nan).dropna().reset_index(level=1)['level_1'].map(gmap).reset_index().drop_duplicates()

df3['cols'] = df3['index'].str.split('gene').str[1].astype(int)

df_out2 = df3.set_index(['level_1','cols'])['index'].unstack()

Output:

cols        1      2      3      4      5      6      7      8      9       10
level_1
W        gene1  gene2  gene3  gene4  gene5   None  gene7  gene8  gene9  gene10
X         None   None  gene3   None  gene5   None   None  gene8  gene9  gene10
Y        gene1  gene2  gene3  gene4  gene5  gene6  gene7  gene8  gene9  gene10
Z         None  gene2   None  gene4   None  gene6   None  gene8  gene9    None


问:
Call a Form and correct way to release? memory usage
I'm using Delphi 7.

I have two units containing Form1 and Form2. The secondary form will be called many times during some process, and I am very worried about memory usage.

When I start the program, memory usage is around 2.1 MB. When Form2 is called, memory grows to 2.9 MB.  After this process, I close Form2 and call it again to simulate regular usage, and memory grows to 3.1 MB, call again and memory grows to 3.4 MB, 3.6 MB, 3.8 MB, etc.

Memory usage is the main issue.

Form1 is calling Form2 like this:

```<code>uses
  Unit2;

...

private
  { Private declarations }
  FChild : TForm2;
...

FChild := TForm2.Create(nil);
try
  FChild.ShowModal;
finally
  FChild.Free;
end;
</code>```

Inside Unit2:

```<code>procedure TForm2.FormClose(Sender: TObject; var Action: TCloseAction);
begin
  Action := caFree;
end;
</code>```

Am I doing something wrong? Is there a better solution?

Please, this not a simple question, because this program will be running 24 hours, and the second form will be called many times.  This means that sometimes this program will freeze the computer.

I included FASTMM4 inside project:

```<code>program Project1;

uses
  FastMM4,
  Forms,
  Unit1 in 'Unit1.pas' {Form1},
  Unit2 in 'Unit2.pas' {Form2};

{$R *.res}

begin
  FullDebugModeScanMemoryPoolBeforeEveryOperation := True;
  SuppressMessageBoxes:=False;
  Application.Initialize;
  Application.CreateForm(TForm1, Form1);
  Application.Run;
end.
</code>```

This program is reading a fingerprint.

Unit1:

```<code>unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls, ExtCtrls, Unit2;

type
  TForm1 = class(TForm)
    btnForm2: TButton;
    btnReselease: TButton;
    procedure btnForm2Click(Sender: TObject);
    procedure btnReseleaseClick(Sender: TObject);
  private
    { Private declarations }
    FChild : TForm2;
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

procedure TForm1.btnForm2Click(Sender: TObject);

begin
  FChild := TForm2.Create(nil);
  try
    FChild.ShowModal;
  finally
    FChild.Free;
  end;
end;

procedure TForm1.btnReseleaseClick(Sender: TObject);
begin
  if FChild <> nil then
  begin
    FreeAndNil(FChild);
  end;
end;

end.
</code>```

Unit2:

```<code>unit Unit2;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls, Buttons, pngimage, ExtCtrls, Grids,  XMLIntf, XMLDoc,
  ComCtrls, CPort;

type
  TForm2 = class(TForm)
    btnSyncFP: TBitBtn;
    btnExitFP: TBitBtn;
    btnDeleteFP: TBitBtn;
    btnCaptureFP: TBitBtn;
    ComImage: TImage;
    FPGrid: TStringGrid;
    prgBar: TProgressBar;
    lblbar: TLabel;
    ComPortA: TComPort;
    ComDataPacket1: TComDataPacket;
    procedure LoadUsers2;
    procedure FormCreate(Sender: TObject);
    procedure ComPortAAfterOpen(Sender: TObject);
    procedure ComPortAAfterClose(Sender: TObject);
    procedure btnExitFPClick(Sender: TObject);
    procedure FormClose(Sender: TObject; var Action: TCloseAction);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
//  Form2: TForm2;
  L1, L2: TStringList;

implementation
{$R *.dfm}

procedure TForm2.LoadUsers2;
var
  XML : IXMLDOCUMENT;
  CurNode, CNode : IXMLNODE;
  i : Integer;
begin
  XML := NewXMLDocument;
  XML.LoadFromFile('usuario.xml');
  XML.Active := True;
  CurNode := XML.DocumentElement.ChildNodes[0]; // users
  FPGrid.RowCount := CurNode.ChildNodes.Count+1;
  prgBar.Min := 0;
  prgBar.Max := CurNode.ChildNodes.Count-1;
  lblBar.Caption := 'Carregando usuários...';
  for i := 0 to CurNode.ChildNodes.Count-1 do
  begin
    CNode := CurNode.ChildNodes[i]; // groups
    with CNode do
    begin
      FPGrid.Cells[2,i+1] := Attributes['group'];
      FPGrid.Cells[1,i+1] := Attributes['id'];
      FPGrid.Cells[0,i+1] := Attributes['name'];
      FPGrid.Cells[3,i+1] := Attributes['fingerID'];
      FPGrid.Cells[4,i+1] := Attributes['level'];
      FPGrid.Cells[5,i+1] := Attributes['status'];
    end;
    if FPGrid.Cells[3,i+1]<>'' then L1.Add(FPGrid.Cells[3,i+1]);
    prgBar.Position := i;
  end;
  XML := nil;
end;

procedure TForm2.FormCreate(Sender: TObject);
begin
  LoadUsers2;
  with FPGrid do
  begin
    Font.Name := 'Tahoma';
    Font.Size := 12;
    ColCount := 4;
    Cells[0,0] := 'Name';  Cells[1,0] := 'ID';
    Cells[2,0] := 'Group'; Cells[3,0] := 'Read ID';
    Cells[4,0] := 'Level'; Cells[5,0] := 'Status';
    ScrollBars := ssVertical;
    Options := Options + [goRowSelect];
  end;
  ComPortA.Open;
end;

procedure TForm2.ComPortAAfterOpen(Sender: TObject);
begin
  ComImage.Picture.LoadFromFile('conn_on.png');
end;

procedure TForm2.ComPortAAfterClose(Sender: TObject);
begin
  ComImage.Picture.LoadFromFile('conn_off.png');
end;

procedure TForm2.btnExitFPClick(Sender: TObject);
begin
  ComPortA.Close;
  Close;
end;

procedure TForm2.FormClose(Sender: TObject; var Action: TCloseAction);
begin
  Action := caFree;
end;

end.
</code>```

I know that Task Manager is the best to verify leak memory, but after few hours, the program is growing faster and not realeasing memory.

I let the program running all night and memory is backing, but there is a long time not enough as user usage.

答:
Don't use Action := caFree and Free() together on the same object.  Use one or the other, not both.  The call to Free() will actually cancel out the Action:=caFree, making it redundant.

But that is not the cause of your problem.

The code you have shown is fine in general, Form2 gets freed from memory correctly. What you are not taking into account is that Delphi's Memory Manager simply does not release freed memory back to the OS, it holds on to it and reuses it for future allocations.  If you are using Task Manager to track memory usage, that is not a good tool for diagnosing memory leaks, since it has no concept of how Delphi caches freed memory over time.

However, that being said, the growth you describe sounds more like memory fragmentation rather than a memory leak.   But it is hard to say for sure since you did not show what all is actually on Form2, or provide a Minimal, Complete, and Verifiable example to reproduce the issue.

In any case, Delphi 7's default memory manager wasn't very efficient in general.  That is why Borland eventually switched to FastMM in Delphi 2006.  You could try replacing the default memory manager with a newer one and see if it helps.

Body:
I'm using Delphi 7.

I have two units containing Form1 and Form2. The secondary form will be called many times during some process, and I am very worried about memory usage.

When I start the program, memory usage is around 2.1 MB. When Form2 is called, memory grows to 2.9 MB.  After this process, I close Form2 and call it again to simulate regular usage, and memory grows to 3.1 MB, call again and memory grows to 3.4 MB, 3.6 MB, 3.8 MB, etc.

Memory usage is the main issue.

Form1 is calling Form2 like this:

uses
  Unit2;

...

private
  { Private declarations }
  FChild : TForm2;
...

FChild := TForm2.Create(nil);
try
  FChild.ShowModal;
finally
  FChild.Free;
end;

Inside Unit2:

procedure TForm2.FormClose(Sender: TObject; var Action: TCloseAction);
begin
  Action := caFree;
end;

Am I doing something wrong? Is there a better solution?

Please, this not a simple question, because this program will be running 24 hours, and the second form will be called many times.  This means that sometimes this program will freeze the computer.

I included FASTMM4 inside project:

program Project1;

uses
  FastMM4,
  Forms,
  Unit1 in 'Unit1.pas' {Form1},
  Unit2 in 'Unit2.pas' {Form2};

{$R *.res}

begin
  FullDebugModeScanMemoryPoolBeforeEveryOperation := True;
  SuppressMessageBoxes:=False;
  Application.Initialize;
  Application.CreateForm(TForm1, Form1);
  Application.Run;
end.

This program is reading a fingerprint.

Unit1:

unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls, ExtCtrls, Unit2;

type
  TForm1 = class(TForm)
    btnForm2: TButton;
    btnReselease: TButton;
    procedure btnForm2Click(Sender: TObject);
    procedure btnReseleaseClick(Sender: TObject);
  private
    { Private declarations }
    FChild : TForm2;
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

procedure TForm1.btnForm2Click(Sender: TObject);

begin
  FChild := TForm2.Create(nil);
  try
    FChild.ShowModal;
  finally
    FChild.Free;
  end;
end;

procedure TForm1.btnReseleaseClick(Sender: TObject);
begin
  if FChild <> nil then
  begin
    FreeAndNil(FChild);
  end;
end;

end.

Unit2:

unit Unit2;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls, Buttons, pngimage, ExtCtrls, Grids,  XMLIntf, XMLDoc,
  ComCtrls, CPort;

type
  TForm2 = class(TForm)
    btnSyncFP: TBitBtn;
    btnExitFP: TBitBtn;
    btnDeleteFP: TBitBtn;
    btnCaptureFP: TBitBtn;
    ComImage: TImage;
    FPGrid: TStringGrid;
    prgBar: TProgressBar;
    lblbar: TLabel;
    ComPortA: TComPort;
    ComDataPacket1: TComDataPacket;
    procedure LoadUsers2;
    procedure FormCreate(Sender: TObject);
    procedure ComPortAAfterOpen(Sender: TObject);
    procedure ComPortAAfterClose(Sender: TObject);
    procedure btnExitFPClick(Sender: TObject);
    procedure FormClose(Sender: TObject; var Action: TCloseAction);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
//  Form2: TForm2;
  L1, L2: TStringList;

implementation
{$R *.dfm}

procedure TForm2.LoadUsers2;
var
  XML : IXMLDOCUMENT;
  CurNode, CNode : IXMLNODE;
  i : Integer;
begin
  XML := NewXMLDocument;
  XML.LoadFromFile('usuario.xml');
  XML.Active := True;
  CurNode := XML.DocumentElement.ChildNodes[0]; // users
  FPGrid.RowCount := CurNode.ChildNodes.Count+1;
  prgBar.Min := 0;
  prgBar.Max := CurNode.ChildNodes.Count-1;
  lblBar.Caption := 'Carregando usuários...';
  for i := 0 to CurNode.ChildNodes.Count-1 do
  begin
    CNode := CurNode.ChildNodes[i]; // groups
    with CNode do
    begin
      FPGrid.Cells[2,i+1] := Attributes['group'];
      FPGrid.Cells[1,i+1] := Attributes['id'];
      FPGrid.Cells[0,i+1] := Attributes['name'];
      FPGrid.Cells[3,i+1] := Attributes['fingerID'];
      FPGrid.Cells[4,i+1] := Attributes['level'];
      FPGrid.Cells[5,i+1] := Attributes['status'];
    end;
    if FPGrid.Cells[3,i+1]<>'' then L1.Add(FPGrid.Cells[3,i+1]);
    prgBar.Position := i;
  end;
  XML := nil;
end;

procedure TForm2.FormCreate(Sender: TObject);
begin
  LoadUsers2;
  with FPGrid do
  begin
    Font.Name := 'Tahoma';
    Font.Size := 12;
    ColCount := 4;
    Cells[0,0] := 'Name';  Cells[1,0] := 'ID';
    Cells[2,0] := 'Group'; Cells[3,0] := 'Read ID';
    Cells[4,0] := 'Level'; Cells[5,0] := 'Status';
    ScrollBars := ssVertical;
    Options := Options + [goRowSelect];
  end;
  ComPortA.Open;
end;

procedure TForm2.ComPortAAfterOpen(Sender: TObject);
begin
  ComImage.Picture.LoadFromFile('conn_on.png');
end;

procedure TForm2.ComPortAAfterClose(Sender: TObject);
begin
  ComImage.Picture.LoadFromFile('conn_off.png');
end;

procedure TForm2.btnExitFPClick(Sender: TObject);
begin
  ComPortA.Close;
  Close;
end;

procedure TForm2.FormClose(Sender: TObject; var Action: TCloseAction);
begin
  Action := caFree;
end;

end.

I know that Task Manager is the best to verify leak memory, but after few hours, the program is growing faster and not realeasing memory.

I let the program running all night and memory is backing, but there is a long time not enough as user usage.