问:
Memory leaks when starting Activity in AsyncTask (changed from Thread)
I'm quite new to Android development and was about to finish my first application when I noticed that I have a huge memory leak.

The leak occurs when I start a new activity from within a thread:

```<code>private static class CatalogRowOnClickListener implements OnClickListener
{
    List<CatalogRow> catRows;
    WeakReference<CatalogViewActivity> mActivity;

    CatalogRowOnClickListener(WeakReference<CatalogViewActivity> mActivity)
    {
        this.mActivity = mActivity;
        catRows = new ArrayList<CatalogRow>();
    }

    public void addCatalogRow(CatalogRow row)
    {
        catRows.add(row);
    }

    public void onClick(View v)
    {
        v.setBackgroundColor(Color.argb(150, 255, 255, 255));

        final ProgressBar linProgressBar = (ProgressBar) v.findViewById(R.id.CatProgressBar);
        linProgressBar.setVisibility(View.VISIBLE);

        final View fv = v;
        final fItem fhitem = findFItem(fv);
        try
        {
            new Thread()
            {

                public void run()
                {
                    initializeApp();

                }
                public void initializeApp()
                {
                    // Initialize application data here

                    FItemListStore.getItemsFromWebservice(fhitem);
                    boolean isArticleOverview = false;

                    for(FItem item: FItemListStore.fItemViewStorage)
                    {
                        if( item instanceof fiArticle )
                        {
                            isArticleOverview = true;
                            break;
                        }
                    }

                    Intent intent = new Intent();
                    intent.setClassName("nl.project.Android", "nl.project.Android.Activities.HomeViewActivity");
                    Bundle bundle = new Bundle();

                    if(isArticleOverview)
                    {
                        bundle.putInt("OverviewNr", 1);
                    }
                    else
                    {
                        bundle.putInt("OverviewNr", 0);
                    }
                    intent.putExtras(bundle);

                    //if( mActivity.get() != null )
                        mActivity.get().startActivity(intent);

                    mActivity.clear();

                }
            }.start();
        }
        catch (Exception e) {}

        //Debug.stopMethodTracing();
        //android.os.Debug.stopMethodTracing();
    }
</code>```

A HPROF dump of the app after executing this code shows that the thread will always be retained in the heap and grow exponentially. Researching this points towards referencing a context inside a thread causing leaks. So I changed this code a few times until it became this version with only a weak reference in a static class (that's some things that were mentioned in other posts)

The reason why I want to start the Activity in a thread is because I need to read data from a slow and big webservice, which takes some time. I displayed a loading bar in the activity, highlighting the selected item until the XMLparser is done, and started a new activity afterwards.

Might it be that there is no correct way to start an activity within a thread without causing a memory leak? And, if so, is there another way for me to have the intent started after the xml parser finishes his job?

On advice of Vladimir and Heiko, I changed my thread to a AnyncTask. The grow of my retained heap has stopped but the AsyncTask threads I started still remain in the heap. Here's my new code:

```<code>private static class QueryFHTask extends AsyncTask<FredHopperItem, Integer, Boolean>
 {

     WeakReference<CatalogViewActivity> mActivity;

     QueryFHTask(WeakReference<CatalogViewActivity> mActivity)
     {
        this.mActivity = mActivity;

     }

     protected void onPreExecute()
     {

     }
     protected Boolean doInBackground(FItem... items) {
         int count = items.length;
         long totalSize = 0;
         for (int i = 0; i < count; i++) {
             FItemListStore.getItemsFromWebservice(items[i]);
             boolean isArticleOverview = false;

             for(FItem item: FItemListStore.fhItemViewStorage)
             {
                if( item instanceof FArticle )
                {
                    isArticleOverview = true;
                    break;
                }
             }

             Intent intent = new Intent();
             intent.setClassName("nl.project.Android", "nl.project.Android.Activities.HomeViewActivity");
             Bundle bundle = new Bundle();

             if(isArticleOverview)
             {
                bundle.putInt("OverviewNr", 1);
             }
             else
             {
                bundle.putInt("OverviewNr", 0);
             }
             intent.putExtras(bundle);
             mActivity.get().startActivity(intent);

         }
         return true;
     }

     protected void onProgressUpdate(Integer... progress) {
         //setProgressPercent(progress[0]);

     }

     protected void onPostExecute(Long result) {
         //showDialog("Downloaded " + result + " bytes");
     }
 }

private static class CatalogRowOnClickListener implements OnClickListener
{
    List<CatalogRow> catRows;
    WeakReference<CatalogViewActivity> mActivity;

    CatalogRowOnClickListener(WeakReference<CatalogViewActivity> mActivity)
    {
        this.mActivity = mActivity;
        catRows = new ArrayList<CatalogRow>();
    }

    public void addCatalogRow(CatalogRow row)
    {
        catRows.add(row);
    }

    public void onClick(View v)
    {
        v.setBackgroundColor(Color.argb(150, 255, 255, 255));
        final ProgressBar linProgressBar = (ProgressBar) v.findViewById(R.id.CatProgressBar);
        linProgressBar.setVisibility(View.VISIBLE);

        final View fv = v;
        final fItem fhitem = findFItem(fv);
        new QueryFHTask(mActivity).execute(fhitem);

    }
</code>```

To clarify my problem, here's a copy of one of my HPROF thread overview heap dumps (it's very hard to read because I was not allowed to post html with links and images like in MAT because of my user level...). The AsyncTask threads retain a heap of 376 or 344. As I browser the application longer, there will be more and more retained heaps from AsyncActivity threads...

```<code>Name Instance Shallow Heap Retained Heap Context Class Loader
main java.lang.Thread @ 0x40027550 80 1.464 dalvik.system.PathClassLoader @ 0x4051ce30
JDWP java.lang.Thread @ 0x40515838 80 384
AsyncTask #6 java.lang.Thread @ 0x406ea788 80 376 dalvik.system.PathClassLoader @ 0x4051ce30
AsyncTask #7 java.lang.Thread @ 0x40690178 80 376 dalvik.system.PathClassLoader @ 0x4051ce30
AsyncTask #4 java.lang.Thread @ 0x4068a630 80 376 dalvik.system.PathClassLoader @ 0x4051ce30
AsyncTask #3 java.lang.Thread @ 0x406851f0 80 376 dalvik.system.PathClassLoader @ 0x4051ce30
AsyncTask #5 java.lang.Thread @ 0x405d9f28 80 376 dalvik.system.PathClassLoader @ 0x4051ce30
AsyncTask #2 java.lang.Thread @ 0x40539db0 80 376 dalvik.system.PathClassLoader @ 0x4051ce30
AsyncTask #1 java.lang.Thread @ 0x40517180 80 376 dalvik.system.PathClassLoader @ 0x4051ce30
AsyncTask #8 java.lang.Thread @ 0x4068cdb0 80 344 dalvik.system.PathClassLoader @ 0x4051ce30
AsyncTask #9 java.lang.Thread @ 0x4068b558 80 344 dalvik.system.PathClassLoader @ 0x4051ce30
AsyncTask #10 java.lang.Thread @ 0x4068a178 80 344 dalvik.system.PathClassLoader @ 0x4051ce30
AsyncTask #11 java.lang.Thread @ 0x406639f0 80 344 dalvik.system.PathClassLoader @ 0x4051ce30
AsyncTask #12 java.lang.Thread @ 0x40661b00 80 344 dalvik.system.PathClassLoader @ 0x4051ce30
Binder Thread #2 java.lang.Thread @ 0x40519b20 80 344
Binder Thread #1 java.lang.Thread @ 0x40516868 80 344
Thread-2 java.util.logging.LogManager$2$1 @ 0x40195298 80 168 dalvik.system.PathClassLoader @ 0x400277f8
Signal Catcher java.lang.Thread @ 0x40515778 80 160
Compiler java.lang.Thread @ 0x405158e8 80 152
HeapWorker java.lang.Thread @ 0x40515618 80 152
GC java.lang.Thread @ 0x405156d0 80 136
Total: 21 entries  1.680 7.656
</code>```

答: Oh my, there is a special thing to start an activity after the some work in background is done. It is AsyncTask with ProgressDialog bounded. See an example.</p>

Body:
I'm quite new to Android development and was about to finish my first application when I noticed that I have a huge memory leak.

The leak occurs when I start a new activity from within a thread:

private static class CatalogRowOnClickListener implements OnClickListener
{
    List<CatalogRow> catRows;
    WeakReference<CatalogViewActivity> mActivity;

    CatalogRowOnClickListener(WeakReference<CatalogViewActivity> mActivity)
    {
        this.mActivity = mActivity;
        catRows = new ArrayList<CatalogRow>();
    }

    public void addCatalogRow(CatalogRow row)
    {
        catRows.add(row);
    }

    public void onClick(View v)
    {
        v.setBackgroundColor(Color.argb(150, 255, 255, 255));

        final ProgressBar linProgressBar = (ProgressBar) v.findViewById(R.id.CatProgressBar);
        linProgressBar.setVisibility(View.VISIBLE);

        final View fv = v;
        final fItem fhitem = findFItem(fv);
        try
        {
            new Thread()
            {

                public void run()
                {
                    initializeApp();

                }
                public void initializeApp()
                {
                    // Initialize application data here

                    FItemListStore.getItemsFromWebservice(fhitem);
                    boolean isArticleOverview = false;

                    for(FItem item: FItemListStore.fItemViewStorage)
                    {
                        if( item instanceof fiArticle )
                        {
                            isArticleOverview = true;
                            break;
                        }
                    }

                    Intent intent = new Intent();
                    intent.setClassName("nl.project.Android", "nl.project.Android.Activities.HomeViewActivity");
                    Bundle bundle = new Bundle();

                    if(isArticleOverview)
                    {
                        bundle.putInt("OverviewNr", 1);
                    }
                    else
                    {
                        bundle.putInt("OverviewNr", 0);
                    }
                    intent.putExtras(bundle);

                    //if( mActivity.get() != null )
                        mActivity.get().startActivity(intent);

                    mActivity.clear();

                }
            }.start();
        }
        catch (Exception e) {}

        //Debug.stopMethodTracing();
        //android.os.Debug.stopMethodTracing();
    }

A HPROF dump of the app after executing this code shows that the thread will always be retained in the heap and grow exponentially. Researching this points towards referencing a context inside a thread causing leaks. So I changed this code a few times until it became this version with only a weak reference in a static class (that's some things that were mentioned in other posts)

The reason why I want to start the Activity in a thread is because I need to read data from a slow and big webservice, which takes some time. I displayed a loading bar in the activity, highlighting the selected item until the XMLparser is done, and started a new activity afterwards.

Might it be that there is no correct way to start an activity within a thread without causing a memory leak? And, if so, is there another way for me to have the intent started after the xml parser finishes his job?

On advice of Vladimir and Heiko, I changed my thread to a AnyncTask. The grow of my retained heap has stopped but the AsyncTask threads I started still remain in the heap. Here's my new code:

private static class QueryFHTask extends AsyncTask<FredHopperItem, Integer, Boolean>
 {

     WeakReference<CatalogViewActivity> mActivity;

     QueryFHTask(WeakReference<CatalogViewActivity> mActivity)
     {
        this.mActivity = mActivity;

     }

     protected void onPreExecute()
     {

     }
     protected Boolean doInBackground(FItem... items) {
         int count = items.length;
         long totalSize = 0;
         for (int i = 0; i < count; i++) {
             FItemListStore.getItemsFromWebservice(items[i]);
             boolean isArticleOverview = false;

             for(FItem item: FItemListStore.fhItemViewStorage)
             {
                if( item instanceof FArticle )
                {
                    isArticleOverview = true;
                    break;
                }
             }

             Intent intent = new Intent();
             intent.setClassName("nl.project.Android", "nl.project.Android.Activities.HomeViewActivity");
             Bundle bundle = new Bundle();

             if(isArticleOverview)
             {
                bundle.putInt("OverviewNr", 1);
             }
             else
             {
                bundle.putInt("OverviewNr", 0);
             }
             intent.putExtras(bundle);
             mActivity.get().startActivity(intent);

         }
         return true;
     }

     protected void onProgressUpdate(Integer... progress) {
         //setProgressPercent(progress[0]);

     }

     protected void onPostExecute(Long result) {
         //showDialog("Downloaded " + result + " bytes");
     }
 }

private static class CatalogRowOnClickListener implements OnClickListener
{
    List<CatalogRow> catRows;
    WeakReference<CatalogViewActivity> mActivity;

    CatalogRowOnClickListener(WeakReference<CatalogViewActivity> mActivity)
    {
        this.mActivity = mActivity;
        catRows = new ArrayList<CatalogRow>();
    }

    public void addCatalogRow(CatalogRow row)
    {
        catRows.add(row);
    }

    public void onClick(View v)
    {
        v.setBackgroundColor(Color.argb(150, 255, 255, 255));
        final ProgressBar linProgressBar = (ProgressBar) v.findViewById(R.id.CatProgressBar);
        linProgressBar.setVisibility(View.VISIBLE);

        final View fv = v;
        final fItem fhitem = findFItem(fv);
        new QueryFHTask(mActivity).execute(fhitem);

    }

To clarify my problem, here's a copy of one of my HPROF thread overview heap dumps (it's very hard to read because I was not allowed to post html with links and images like in MAT because of my user level...). The AsyncTask threads retain a heap of 376 or 344. As I browser the application longer, there will be more and more retained heaps from AsyncActivity threads...

Name Instance Shallow Heap Retained Heap Context Class Loader
main java.lang.Thread @ 0x40027550 80 1.464 dalvik.system.PathClassLoader @ 0x4051ce30
JDWP java.lang.Thread @ 0x40515838 80 384
AsyncTask #6 java.lang.Thread @ 0x406ea788 80 376 dalvik.system.PathClassLoader @ 0x4051ce30
AsyncTask #7 java.lang.Thread @ 0x40690178 80 376 dalvik.system.PathClassLoader @ 0x4051ce30
AsyncTask #4 java.lang.Thread @ 0x4068a630 80 376 dalvik.system.PathClassLoader @ 0x4051ce30
AsyncTask #3 java.lang.Thread @ 0x406851f0 80 376 dalvik.system.PathClassLoader @ 0x4051ce30
AsyncTask #5 java.lang.Thread @ 0x405d9f28 80 376 dalvik.system.PathClassLoader @ 0x4051ce30
AsyncTask #2 java.lang.Thread @ 0x40539db0 80 376 dalvik.system.PathClassLoader @ 0x4051ce30
AsyncTask #1 java.lang.Thread @ 0x40517180 80 376 dalvik.system.PathClassLoader @ 0x4051ce30
AsyncTask #8 java.lang.Thread @ 0x4068cdb0 80 344 dalvik.system.PathClassLoader @ 0x4051ce30
AsyncTask #9 java.lang.Thread @ 0x4068b558 80 344 dalvik.system.PathClassLoader @ 0x4051ce30
AsyncTask #10 java.lang.Thread @ 0x4068a178 80 344 dalvik.system.PathClassLoader @ 0x4051ce30
AsyncTask #11 java.lang.Thread @ 0x406639f0 80 344 dalvik.system.PathClassLoader @ 0x4051ce30
AsyncTask #12 java.lang.Thread @ 0x40661b00 80 344 dalvik.system.PathClassLoader @ 0x4051ce30
Binder Thread #2 java.lang.Thread @ 0x40519b20 80 344
Binder Thread #1 java.lang.Thread @ 0x40516868 80 344
Thread-2 java.util.logging.LogManager$2$1 @ 0x40195298 80 168 dalvik.system.PathClassLoader @ 0x400277f8
Signal Catcher java.lang.Thread @ 0x40515778 80 160
Compiler java.lang.Thread @ 0x405158e8 80 152
HeapWorker java.lang.Thread @ 0x40515618 80 152
GC java.lang.Thread @ 0x405156d0 80 136
Total: 21 entries  1.680 7.656


来源: stackexchange

问:
How to pass a parameter to the hibernate AttributeConverter
If I have a AttributeConverter that changes the length of the input before persisting it in the database, what would be the correct way to make sure that the modified input doesn't exceed the maximum length allowed by that column (without hardcoding it in the converter) ?

@Column(length = 1024)
@Convert(converter = MyConverter.class)
private String comment;

public class MyConverter implements AttributeConverter<String, String> {

   @Override
   public String convertToDatabaseColumn(String attribute) {
      return "hello world " + attribute;
   }
   ...
}
```

答:
You can achieve what you want with hibernate custom basic type that implements DynamicParameterizedType interface.

Below you can see a simple example of declaration custom type that read the length property of @Column annotation.

import java.io.Serializable;
import java.lang.annotation.Annotation;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.Objects;
import java.util.Properties;

import javax.persistence.Column;

import org.hibernate.HibernateException;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.usertype.DynamicParameterizedType;
import org.hibernate.usertype.UserType;

public class PersistableString implements UserType, DynamicParameterizedType
{
   private int sqlType;
   private int columnLength;

   public PersistableString()
   {
      this.sqlType = Types.VARCHAR;
   }

   @Override
   public void setParameterValues(Properties parameters)
   {
      ParameterType reader = (ParameterType) parameters.get(PARAMETER_TYPE);
      this.columnLength = getLength(reader);
   }

   private int getLength(ParameterType reader)
   {
      int length = -1; // default length
      for (Annotation annotation : reader.getAnnotationsMethod()){
         if (annotation instanceof Column) {
            length =  ((Column) annotation).length();
         }
      }
      return length;
   }

   @Override
   public int[] sqlTypes()
   {
      return new int[] {sqlType};
   }

   @Override
   public Class<?> returnedClass()
   {
      return String.class;
   }

   @Override
   public boolean equals(Object x, Object y) throws HibernateException
   {
      return Objects.equals(x, y);
   }

   @Override
   public int hashCode(Object x) throws HibernateException
   {
      return Objects.hashCode(x);
   }

   /*
      This method will be called when hibernate initializes your entity's
      field from the appropriate database table row
   */
   @Override
   public Object nullSafeGet(ResultSet rs,
         String[] names,
         SharedSessionContractImplementor session,
         Object owner) throws HibernateException, SQLException
   {
      // you can use this.columnLength here
      return rs.getString(names[0]);
   }

   /*
      This method will be called when hibernate persists your entity's field
      to the appropriate database table row
   */
   @Override
   public void nullSafeSet(PreparedStatement st,
         Object value,
         int index,
         SharedSessionContractImplementor session) throws HibernateException, SQLException
   {
      // you can use this.columnLength here
      if (value == null) {
         st.setNull(index, sqlType);
      }
      else {
         String val = (String) value;
         st.setString(index, val);
      }
   }

   @Override
   public Object deepCopy(Object value) throws HibernateException
   {
      return value;
   }

   @Override
   public boolean isMutable()
   {
      return false;
   }

   @Override
   public Serializable disassemble(Object value) throws HibernateException
   {
      return Objects.toString(value);
   }

   @Override
   public Object assemble(Serializable cached, Object owner) throws HibernateException
   {
      return cached;
   }

   @Override
   public Object replace(Object original, Object target, Object owner) throws HibernateException
   {
      return original;
   }
}
```

<p>and usage:</p>

<pre class="lang-java prettyprint-override"><code>import org.hibernate.annotations.Type;

@Entity
@Table
public class Account
{

   @Column(name = "acc_name", length = 50)
   @Type(type = "com.example.hibernate.PersistableString")
   private String name;

   @Column(name = "acc_pass", length = 30)
   @Type(type = "com.example.hibernate.PersistableString")
   private String pass;

   @Column(name = "acc_email", length = 355)
   @Type(type = "com.example.hibernate.PersistableString")
   private String email;
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
You can achieve what you want with hibernate custom basic type that implements DynamicParameterizedType interface.

Below you can see a simple example of declaration custom type that read the length property of @Column annotation.

import java.io.Serializable;
import java.lang.annotation.Annotation;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.Objects;
import java.util.Properties;

import javax.persistence.Column;

import org.hibernate.HibernateException;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.usertype.DynamicParameterizedType;
import org.hibernate.usertype.UserType;

public class PersistableString implements UserType, DynamicParameterizedType
{
   private int sqlType;
   private int columnLength;

   public PersistableString()
   {
      this.sqlType = Types.VARCHAR;
   }

   @Override
   public void setParameterValues(Properties parameters)
   {
      ParameterType reader = (ParameterType) parameters.get(PARAMETER_TYPE);
      this.columnLength = getLength(reader);
   }

   private int getLength(ParameterType reader)
   {
      int length = -1; // default length
      for (Annotation annotation : reader.getAnnotationsMethod()){
         if (annotation instanceof Column) {
            length =  ((Column) annotation).length();
         }
      }
      return length;
   }

   @Override
   public int[] sqlTypes()
   {
      return new int[] {sqlType};
   }

   @Override
   public Class<?> returnedClass()
   {
      return String.class;
   }

   @Override
   public boolean equals(Object x, Object y) throws HibernateException
   {
      return Objects.equals(x, y);
   }

   @Override
   public int hashCode(Object x) throws HibernateException
   {
      return Objects.hashCode(x);
   }

   /*
      This method will be called when hibernate initializes your entity's
      field from the appropriate database table row
   */
   @Override
   public Object nullSafeGet(ResultSet rs,
         String[] names,
         SharedSessionContractImplementor session,
         Object owner) throws HibernateException, SQLException
   {
      // you can use this.columnLength here
      return rs.getString(names[0]);
   }

   /*
      This method will be called when hibernate persists your entity's field
      to the appropriate database table row
   */
   @Override
   public void nullSafeSet(PreparedStatement st,
         Object value,
         int index,
         SharedSessionContractImplementor session) throws HibernateException, SQLException
   {
      // you can use this.columnLength here
      if (value == null) {
         st.setNull(index, sqlType);
      }
      else {
         String val = (String) value;
         st.setString(index, val);
      }
   }

   @Override
   public Object deepCopy(Object value) throws HibernateException
   {
      return value;
   }

   @Override
   public boolean isMutable()
   {
      return false;
   }

   @Override
   public Serializable disassemble(Object value) throws HibernateException
   {
      return Objects.toString(value);
   }

   @Override
   public Object assemble(Serializable cached, Object owner) throws HibernateException
   {
      return cached;
   }

   @Override
   public Object replace(Object original, Object target, Object owner) throws HibernateException
   {
      return original;
   }
}

and usage:

import org.hibernate.annotations.Type;

@Entity
@Table
public class Account
{

   @Column(name = "acc_name", length = 50)
   @Type(type = "com.example.hibernate.PersistableString")
   private String name;

   @Column(name = "acc_pass", length = 30)
   @Type(type = "com.example.hibernate.PersistableString")
   private String pass;

   @Column(name = "acc_email", length = 355)
   @Type(type = "com.example.hibernate.PersistableString")
   private String email;
}


问:
Application crash when calling method 'FirebaseApp.configure()' in a real device
Recently, I decided to run the application on a real device and received a crash application and, looking for the reason, I found that it appears after the FirebaseApp.configure() method.

The application does not crash when launched in the simulator.

Crash:

```<code>dyld`__abort_with_payload:
    0x101b0b2a4 <+0>:  mov    x16, #0x209
    0x101b0b2a8 <+4>:  svc    #0x80
->  0x101b0b2ac <+8>:  b.lo   0x101b0b2c8               ; <+36>
    0x101b0b2b0 <+12>: stp    x29, x30, [sp, #-0x10]!
    0x101b0b2b4 <+16>: mov    x29, sp
    0x101b0b2b8 <+20>: bl     0x101b097d8               ; cerror_nocancel
    0x101b0b2bc <+24>: mov    sp, x29
    0x101b0b2c0 <+28>: ldp    x29, x30, [sp], #0x10
    0x101b0b2c4 <+32>: ret
    0x101b0b2c8 <+36>: ret
</code>```

With this backtrace:

```<code>* thread #1, queue = 'com.apple.main-thread', stop reason = signal SIGABRT
  * frame #0: 0x0000000101b0b2ac dyld`__abort_with_payload + 8
    frame #1: 0x0000000101b12914 dyld`abort_with_payload_wrapper_internal + 104
    frame #2: 0x0000000101b12948 dyld`abort_with_payload + 16
    frame #3: 0x0000000101b0f77c dyld`dyld::halt(char const*) + 380
    frame #4: 0x0000000101ac0778 dyld`dyld::fastBindLazySymbol(ImageLoader**, unsigned long) + 176
    frame #5: 0x00000001b207963c libdyld.dylib`_dyld_fast_stub_entry(void*, long) + 80
    frame #6: 0x00000001b2077b80 libdyld.dylib`dyld_stub_binder + 60
    frame #7: 0x0000000100b88258 CheeseApp`__44+[UIViewController(APMScreenClassName) load]_block_invoke + 144
    frame #8: 0x000000010204327c libdispatch.dylib`_dispatch_client_callout + 20
    frame #9: 0x0000000102044c88 libdispatch.dylib`_dispatch_once_callout + 132
    frame #10: 0x0000000100b881c4 CheeseApp`+[UIViewController(APMScreenClassName) load] + 76
    frame #11: 0x00000001b1fa1500 libobjc.A.dylib`load_images + 1176
    frame #12: 0x0000000101abe19c dyld`dyld::notifySingle(dyld_image_states, ImageLoader const*, ImageLoader::InitializerTimingList*) + 480
    frame #13: 0x0000000101ace444 dyld`ImageLoader::recursiveInitialization(ImageLoader::LinkContext const&, unsigned int, char const*, ImageLoader::InitializerTimingList&, ImageLoader::UninitedUpwards&) + 556
    frame #14: 0x0000000101acd094 dyld`ImageLoader::processInitializers(ImageLoader::LinkContext const&, unsigned int, ImageLoader::InitializerTimingList&, ImageLoader::UninitedUpwards&) + 192
    frame #15: 0x0000000101acd160 dyld`ImageLoader::runInitializers(ImageLoader::LinkContext const&, ImageLoader::InitializerTimingList&) + 96
    frame #16: 0x0000000101abe4f8 dyld`dyld::initializeMainExecutable() + 220
    frame #17: 0x0000000101ac3038 dyld`dyld::_main(macho_header const*, unsigned long, int, char const**, char const**, char const**, unsigned long*) + 4668
    frame #18: 0x0000000101abd22c dyld`dyldbootstrap::start(dyld3::MachOLoaded const*, int, char const**, dyld3::MachOLoaded const*, unsigned long*) + 432
    frame #19: 0x0000000101abd038 dyld`_dyld_start + 56
</code>```

AppDelegate:

```<code>import UIKit
import Firebase

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        FirebaseApp.configure()
        return true
    }

    // MARK: UISceneSession Lifecycle

    func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
        // Called when a new scene session is being created.
        // Use this method to select a configuration to create the new scene with.
        return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
    }

    func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
        // Called when the user discards a scene session.
        // If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
        // Use this method to release any resources that were specific to the discarded scenes, as they will not return.
    }
}
</code>```

What I tried:

I updated the GoogleService-Info.plist file in the root directory

I updated all libraries in pod file

I tried to solve the problem by disabling the Address Sanitizer in scheme

I tried to add .plist file via "Add Files to..."

I tried to run the method like this:

```<code>    override init() {
        FirebaseApp.configure()
    }
</code>```

I updated library in 'Linked Binary With Libraries'

But nothing helped.

答:
This is another symptom of Apple blocking free developer accounts from using dynamic frameworks starting with iOS 13.3.1.

Options include
 - Upgrade to paid developer account
 - Downgrade to 13.3.
 - With CocoaPods, use use_modular_headers! instead of use_frameworks!

See also Library not loaded: @rpath/FBLPromises.framework/FBLPromises iOS 13.3.1

Body:
Recently, I decided to run the application on a real device and received a crash application and, looking for the reason, I found that it appears after the FirebaseApp.configure() method.

The application does not crash when launched in the simulator.

Crash:

dyld`__abort_with_payload:
    0x101b0b2a4 <+0>:  mov    x16, #0x209
    0x101b0b2a8 <+4>:  svc    #0x80
->  0x101b0b2ac <+8>:  b.lo   0x101b0b2c8               ; <+36>
    0x101b0b2b0 <+12>: stp    x29, x30, [sp, #-0x10]!
    0x101b0b2b4 <+16>: mov    x29, sp
    0x101b0b2b8 <+20>: bl     0x101b097d8               ; cerror_nocancel
    0x101b0b2bc <+24>: mov    sp, x29
    0x101b0b2c0 <+28>: ldp    x29, x30, [sp], #0x10
    0x101b0b2c4 <+32>: ret
    0x101b0b2c8 <+36>: ret

With this backtrace:

* thread #1, queue = 'com.apple.main-thread', stop reason = signal SIGABRT
  * frame #0: 0x0000000101b0b2ac dyld`__abort_with_payload + 8
    frame #1: 0x0000000101b12914 dyld`abort_with_payload_wrapper_internal + 104
    frame #2: 0x0000000101b12948 dyld`abort_with_payload + 16
    frame #3: 0x0000000101b0f77c dyld`dyld::halt(char const*) + 380
    frame #4: 0x0000000101ac0778 dyld`dyld::fastBindLazySymbol(ImageLoader**, unsigned long) + 176
    frame #5: 0x00000001b207963c libdyld.dylib`_dyld_fast_stub_entry(void*, long) + 80
    frame #6: 0x00000001b2077b80 libdyld.dylib`dyld_stub_binder + 60
    frame #7: 0x0000000100b88258 CheeseApp`__44+[UIViewController(APMScreenClassName) load]_block_invoke + 144
    frame #8: 0x000000010204327c libdispatch.dylib`_dispatch_client_callout + 20
    frame #9: 0x0000000102044c88 libdispatch.dylib`_dispatch_once_callout + 132
    frame #10: 0x0000000100b881c4 CheeseApp`+[UIViewController(APMScreenClassName) load] + 76
    frame #11: 0x00000001b1fa1500 libobjc.A.dylib`load_images + 1176
    frame #12: 0x0000000101abe19c dyld`dyld::notifySingle(dyld_image_states, ImageLoader const*, ImageLoader::InitializerTimingList*) + 480
    frame #13: 0x0000000101ace444 dyld`ImageLoader::recursiveInitialization(ImageLoader::LinkContext const&, unsigned int, char const*, ImageLoader::InitializerTimingList&, ImageLoader::UninitedUpwards&) + 556
    frame #14: 0x0000000101acd094 dyld`ImageLoader::processInitializers(ImageLoader::LinkContext const&, unsigned int, ImageLoader::InitializerTimingList&, ImageLoader::UninitedUpwards&) + 192
    frame #15: 0x0000000101acd160 dyld`ImageLoader::runInitializers(ImageLoader::LinkContext const&, ImageLoader::InitializerTimingList&) + 96
    frame #16: 0x0000000101abe4f8 dyld`dyld::initializeMainExecutable() + 220
    frame #17: 0x0000000101ac3038 dyld`dyld::_main(macho_header const*, unsigned long, int, char const**, char const**, char const**, unsigned long*) + 4668
    frame #18: 0x0000000101abd22c dyld`dyldbootstrap::start(dyld3::MachOLoaded const*, int, char const**, dyld3::MachOLoaded const*, unsigned long*) + 432
    frame #19: 0x0000000101abd038 dyld`_dyld_start + 56

AppDelegate:

import UIKit
import Firebase

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        FirebaseApp.configure()
        return true
    }

    // MARK: UISceneSession Lifecycle

    func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
        // Called when a new scene session is being created.
        // Use this method to select a configuration to create the new scene with.
        return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
    }

    func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
        // Called when the user discards a scene session.
        // If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
        // Use this method to release any resources that were specific to the discarded scenes, as they will not return.
    }
}

What I tried:

I updated the GoogleService-Info.plist file in the root directory

I updated all libraries in pod file

I tried to solve the problem by disabling the Address Sanitizer in scheme

I tried to add .plist file via "Add Files to..."

I tried to run the method like this:

    override init() {
        FirebaseApp.configure()
    }

I updated library in 'Linked Binary With Libraries'

But nothing helped.


问:
confusion with res.render in javascript
I have been doing coding lessons in my spare time and there is a slight confusion with some pieces of the code:

The first one is the action attribute in HTML

The second one is this piece of code:

```<code>app.get("/", (req, res) =>// The / is a shortcut for index.html
{
    res.render(index);//
});
</code>```

the thing that is confusing me about this is that index.html is is the req part of the function and in this function we are simply responding by rendering the exact page as before (whats the point in that)

the third and final confusion is to do with this piece of code here:

```<code>app.post("/thanks.html", (req, res) =>
{
    data = [];
    data.push(req.body);
    res.render("thanks", {data});
}
</code>```

What is confusing me about this code is that it is saying we are getting a req from the thanks.html which has not been made yet. It gets made when the res.render displays the thanks.html page.

答:
we are simply responding by rendering the exact page as before (whats the point in that)

There is no point, but its  looks like a tutorial designed to demonstrate basic principles and not be a practical and useful thing.

What is confusing me about this code is that it is saying we are getting a req from the thanks.html which has not been made yet.

The first argument of app.post or app.get is the path that should appear in the URL that the browser is requesting from the server.

This is not a file name.

The response is determined by the code in the function that is the second argument. That's not a file unless the code explicitly reads a file.

res.render("thanks", {data}); tells Express to use a template called thanks (and you should have previously configured a template engine) which gets passes the data from the request.

If you haven't make a thanks template, then requests for /thanks.html are probably just going to cause the server to throw an error.

Title: confusion with res.render in javascript

Body:
I have been doing coding lessons in my spare time and there is a slight confusion with some pieces of the code:

The first one is the action attribute in HTML

The second one is this piece of code:

app.get("/", (req, res) =>// The / is a shortcut for index.html
{
    res.render(index);//
});

the thing that is confusing me about this is that index.html is is the req part of the function and in this function we are simply responding by rendering the exact page as before (whats the point in that)

the third and final confusion is to do with this piece of code here:

app.post("/thanks.html", (req, res) =>
{
    data = [];
    data.push(req.body);
    res.render("thanks", {data});
}

What is confusing me about this code is that it is saying we are getting a req from the thanks.html which has not been made yet. It gets made when the res.render displays the thanks.html page.


问:
Entity framework with SAP HANA
I have built a WPF application with Entity Framework on SQL Server as database. I am trying to migrate the same application with SAP HANA as database. Following the same approach, I have created the tables in HANA db and now trying to add an entity model in the solution by following this SAP help:
SAP HANA Client Interface Programming Reference

While adding the entity model, after selection of data source and option to include sensitive data in connection string, the wizard disappears.
Please help if anyone has used entity framework with HANA.

I have used all the 32 bit versions of HANA client available on SAP market place without any success.

答:
You can use Entity Framework by using the adding a reference to the dll provided in the installation directory.

The name of the dll is System.Data.CData.SAPHANA.Entities.EF6.dll and you should have installed EntityFramework using Install-Package EntityFramework -Version 6.3.0  command. Please don't forget to use the version flag because it didn't work with another version and I didn't try to know why.

Now the remaining thing is the connection string

```<code><add name="HANA_DbContext" connectionString="Offline=False;User=system;
Password=Secret_Pass;Server=hana.office.internal.com;
Database=company_erp;" providerName="System.Data.CData.SAPHANA" />
</code>```

Here now, everything should work correctly as if it works MySQL, SQL Server or another ORM

ContentLicense: CC BY-SA 3.0

Title: Entity framework with SAP HANA

Body:
You can use Entity Framework by using the adding a reference to the dll provided in the installation directory.

The name of the dll is System.Data.CData.SAPHANA.Entities.EF6.dll and you should have installed EntityFramework using Install-Package EntityFramework -Version 6.3.0  command. Please don't forget to use the version flag because it didn't work with another version and I didn't try to know why.

Now the remaining thing is the connection string

<add name="HANA_DbContext" connectionString="Offline=False;User=system;
Password=Secret_Pass;Server=hana.office.internal.com;
Database=company_erp;" providerName="System.Data.CData.SAPHANA" />

Here now, everything should work correctly as if it works MySQL, SQL Server or another ORM


问:
How to stream a .m4v video with NodeJS
What I need is to be able to send videos that are on the server local files to the client. I can't create a static 'videos' folder as these videos will only be temporarily available, meaning i'll have dynamic videos.

So how can I retrieve the playable .m4v video file from the server files (if i know the path) and send it to the angular.io client to play

答:
This was enough with me. MP4 has native support for strimming (pseudo streaming). It worked very well for watching videos in the browser via streaming.

```<code>const router    = require('express').Router();
...
router.get('/video/:acckey', async (req, res, next)=>{
  ...
  let full_path = await myAccessControl.auth(acckey);
  ...
  if (fs.existsSync(full_path)) {
    res.setHeader('Content-Type', 'video/mp4');
    res.status(200).sendFile(full_path, function (err) {
      if (err) {...} else {...}
    });
  }
}
</code>```

In HTML (reduced):

```<code><VIDEO controls src="domain.com/video/PSMAPKMDPAMDPSMPSD/">
</code>```

Title: How to stream a .m4v video with NodeJS

Body:
This was enough with me. MP4 has native support for strimming (pseudo streaming). It worked very well for watching videos in the browser via streaming.

const router    = require('express').Router();
...
router.get('/video/:acckey', async (req, res, next)=>{
  ...
  let full_path = await myAccessControl.auth(acckey);
  ...
  if (fs.existsSync(full_path)) {
    res.setHeader('Content-Type', 'video/mp4');
    res.status(200).sendFile(full_path, function (err) {
      if (err) {...} else {...}
    });
  }
}

In HTML (reduced):

<VIDEO controls src="domain.com/video/PSMAPKMDPAMDPSMPSD/">


问:
How do I add several traces to a single plot?
I would like to add y axis traces to plotly object using map from purrr package. But instead of adding new traces to the existing plot, it creates individual plots for each trace. See:

```<code>library(purrr)
library(plotly)

data("iris")

p = plot_ly(iris, type = "bar")
xaxis = ~Species
map(c(~Sepal.Length, ~Sepal.Width, ~Petal.Length, ~Petal.Width), ~add_trace(p, x = xaxis, y = .x))
</code>```

Is there a way to remedy this?

答:
map is the wrong function for this because it iteratively applies the same function to different arguments in turn, by definition.

What you want to do is different: you want to aggregate a result over different arguments, by applying a given operation on the current aggregate and the next argument. In functional programming terminology, this is known as a reduction, and purrr provides the function reduce for it.

```<code>trace_vars = c(~Sepal.Length, ~Sepal.Width, ~Petal.Length, ~Petal.Width)
result = reduce(trace_vars, ~ add_trace(.x, x = xaxis, y = .y), .init = p)
</code>```

This is effectively the same as

```<code>add_trace(
  add_trace(
    …,
    x = xaxis, y = ~Sepal.Width
  ),
  x = xaxis, y = ~Sepal.Length
)
</code>```

You can invert the direction via reduce’s .dir argument.

To include names, use reduce2 with an adapted formula. Unfortunately extracting the names from the formulas is a bit annoying:

```<code>trace_names = map_chr(trace_vars, ~ as.character(.x[[2L]]))

result = reduce2(
    trace_vars, trace_names,
    ~ add_trace(..1, x = xaxis, y = ..2, name = ..3),
    .init = p
)
</code>```

Body:
I would like to add y axis traces to plotly object using map from purrr package. But instead of adding new traces to the existing plot, it creates individual plots for each trace. See:

library(purrr)
library(plotly)

data("iris")

p = plot_ly(iris, type = "bar")
xaxis = ~Species
map(c(~Sepal.Length, ~Sepal.Width, ~Petal.Length, ~Petal.Width), ~add_trace(p, x = xaxis, y = .x))

Is there a way to remedy this?

Body:
map is the wrong function for this because it iteratively applies the same function to different arguments in turn, by definition.

What you want to do is different: you want to aggregate a result over different arguments, by applying a given operation on the current aggregate and the next argument. In functional programming terminology, this is known as a reduction, and purrr provides the function reduce for it.

trace_vars = c(~Sepal.Length, ~Sepal.Width, ~Petal.Length, ~Petal.Width)
result = reduce(trace_vars, ~ add_trace(.x, x = xaxis, y = .y), .init = p)

This is effectively the same as

add_trace(
  add_trace(
    …,
    x = xaxis, y = ~Sepal.Width
  ),
  x = xaxis, y = ~Sepal.Length
)

You can invert the direction via reduce’s .dir argument.

To include names, use reduce2 with an adapted formula. Unfortunately extracting the names from the formulas is a bit annoying:

trace_names = map_chr(trace_vars, ~ as.character(.x[[2L]]))

result = reduce2(
    trace_vars, trace_names,
    ~ add_trace(..1, x = xaxis, y = ..2, name = ..3),
    .init = p
)


问:
Rust Reference Mods
I have a set of files in a workspace which I want to reference from another directory, but I cannot find the syntax I need to use.

The example is:

Primary
|_______ First
|            |_____ src
|                    |______ Cool_thing.rs
|_______ Second
            |_____ src
                    |______ main.rs
```

<p>I want to reference a struct in <code>Cool_things</code> from main.rs</p>

<p>In Primary's Cargo.toml I put:</p>

```[workspace]
members= ["First","Second", "Third"]

[dependencies.Second]
First= { path = "First" }
```

<p>In the Cargo.toml in the <code>Second</code> directory I have</p>

```[dependencies]
First = { path = "../First" }
```

<p>I have been trying things in my main.rs like:</p>

```extern crate First;
use First::Cool_things::Cool_things;
```

No variation of use or mod seems to allow me to reference the struct or impl or functions in mod Cool_things.

答:
The problem was it needed a "lib.rs" in the First src directory. Basically, the documentation for rust seems to be a bit remiss in telling people if you want to use local-dependancies then you have to have a lib.rs file which lists all the mods you are planning to access. So the creation of a lib.rs in the First src directory, and listing "Mod Cool_things" would allow the other package to reference the mod files in that directory.

The cargo.toml files: Inserted in the question above had the correct paths and dependancies, the issue was all around the lack of a lib.rs file.

So if you are planning a multiple binary program, you'll need to remember to have a lib.rs file whenever you're breaking up your code and then accessing modules from other parts of the workspace.

Title: Rust Reference Mods

Body:
I have a set of files in a workspace which I want to reference from another directory, but I cannot find the syntax I need to use.

The example is:

Primary
|_______ First
|            |_____ src
|                    |______ Cool_thing.rs
|_______ Second
            |_____ src
                    |______ main.rs

I want to reference a struct in Cool_things from main.rs

In Primary's Cargo.toml I put:

[workspace]
members= ["First","Second", "Third"]

[dependencies.Second]
First= { path = "First" }

In the Cargo.toml in the Second directory I have

[dependencies]
First = { path = "../First" }

I have been trying things in my main.rs like:

extern crate First;
use First::Cool_things::Cool_things;

No variation of use or mod seems to allow me to reference the struct or impl or functions in mod Cool_things.


问:
Media files with .mov are not playing in a cordova app
I am using Cordova to build my hybrid application. In this application i have a functionality to show preview of files before uploading them to server. For this when i am uploading video files and audio files recorded from device, it works if i am playing video/audio from device storage url. But it fails when i am binding the server url.

First i thought it is issue with content-type received from server so i changed it to video/quicktime. Obviously it didn't solved my problem.

Video files with mp4 extensions are playing perfectly. As iPad is returning .mov file and no other way to change video extension i cannot change encoding type.

My question is, what is issue when i am binding server url? it must not be issue with file codec as local file urls are playing without any issue. Is it a limitation of iOS/Cordova where we need to download and run the file instead of binding it to html5 video tag?

Is there any way where i can run these video files in an iOS/iPad device?

I am using html5  and  tags.

When url is binding to video/audio tag i am getting below issue in Xcode console

Server response for video file with .mov format

When i run the same video on Mac chrome browser it works. Only in case of mobile app it does not play media file. File is downloading as well when url is accessed directly.

Please let me know if you need more information on this particular issue.

Details of platform

Cordova:

```<code>"cordova-android": "^8.0.0",
"cordova-browser": "^5.0.4",
"cordova-ios": "^4.5.5",
"cordova-plugin-camera": "^4.0.3",
"cordova-plugin-device": "^2.0.2",
"cordova-plugin-file": "^6.0.1",
"cordova-plugin-file-opener2": "^3.0.0",
"cordova-plugin-geolocation": "^4.0.2",
"cordova-plugin-inappbrowser": "^3.0.0",
"cordova-plugin-media": "^5.0.2",
"cordova-plugin-media-capture": "^3.0.2",
"cordova-plugin-network-information": "^2.0.1",
"cordova-plugin-splashscreen": "^5.0.2",
"cordova-plugin-whitelist": "^1.3.3",
</code>```

答: Html5 has official support for a VERY limited number of codecs and containers. Mp4/h264/aac is basically the only file that is guaranteed to work in all browsers. Any other format and you must convert it. </p>

Body:
I am using Cordova to build my hybrid application. In this application i have a functionality to show preview of files before uploading them to server. For this when i am uploading video files and audio files recorded from device, it works if i am playing video/audio from device storage url. But it fails when i am binding the server url.

First i thought it is issue with content-type received from server so i changed it to video/quicktime. Obviously it didn't solved my problem.

Video files with mp4 extensions are playing perfectly. As iPad is returning .mov file and no other way to change video extension i cannot change encoding type.

My question is, what is issue when i am binding server url? it must not be issue with file codec as local file urls are playing without any issue. Is it a limitation of iOS/Cordova where we need to download and run the file instead of binding it to html5 video tag?

Is there any way where i can run these video files in an iOS/iPad device?

I am using html5  and  tags.

When url is binding to video/audio tag i am getting below issue in Xcode console

Server response for video file with .mov format

When i run the same video on Mac chrome browser it works. Only in case of mobile app it does not play media file. File is downloading as well when url is accessed directly.

Please let me know if you need more information on this particular issue.

Details of platform

Cordova:

"cordova-android": "^8.0.0",
"cordova-browser": "^5.0.4",
"cordova-ios": "^4.5.5",
"cordova-plugin-camera": "^4.0.3",
"cordova-plugin-device": "^2.0.2",
"cordova-plugin-file": "^6.0.1",
"cordova-plugin-file-opener2": "^3.0.0",
"cordova-plugin-geolocation": "^4.0.2",
"cordova-plugin-inappbrowser": "^3.0.0",
"cordova-plugin-media": "^5.0.2",
"cordova-plugin-media-capture": "^3.0.2",
"cordova-plugin-network-information": "^2.0.1",
"cordova-plugin-splashscreen": "^5.0.2",
"cordova-plugin-whitelist": "^1.3.3",


问:
how to solve "null is not object(evaluating RNGestureHandlerModule.default.direction" in react native 5.0
I have installed all the dependencies according to the react navigation docs.. when I copied code from docs this error occurs..
my dependencies are </p>

```<code>"dependencies": {
    "@react-native-community/masked-view": "^0.1.6",
    "@react-navigation/native": "^5.0.5",
    "@react-navigation/stack": "^5.0.5",
    "react": "16.9.0",
    "react-native": "0.61.5",
    "react-native-gesture-handler": "^1.6.0",
    "react-native-paper": "^3.6.0",
    "react-native-reanimated": "^1.7.0",
    "react-native-safe-area-context": "^0.7.3",
    "react-native-screens": "^2.0.0-beta.7"
  },
</code>```

答:
SOLUTION FOR ANDROID

From your project root folder run :

cd android

./gradlew clean

run project react-native run-android

SOLUTION FOR IOS

From your project root folder run :

cd ios

pod install

run project react-native run-ios

If these solutions didn't work remove your node_modules folder and re-install using npm install

NOTE :

Do not link packages using react-native link since you are using RN 0.60 >

Body:
I have installed all the dependencies according to the react navigation docs.. when I copied code from docs this error occurs..
my dependencies are

"dependencies": {
    "@react-native-community/masked-view": "^0.1.6",
    "@react-navigation/native": "^5.0.5",
    "@react-navigation/stack": "^5.0.5",
    "react": "16.9.0",
    "react-native": "0.61.5",
    "react-native-gesture-handler": "^1.6.0",
    "react-native-paper": "^3.6.0",
    "react-native-reanimated": "^1.7.0",
    "react-native-safe-area-context": "^0.7.3",
    "react-native-screens": "^2.0.0-beta.7"
  },


问:
Is there a CMS (WYSIWYG) Component for Agile Toolkit?
I haven't seen the code in the standard distribution of Agile Toolkit. Does anyone have a add-on code which integrates Agile Toolkit form with some WYSIWYG editor?</p>

答:
Ok, I have got this code from other developer:</p>

```<code>$url=$this->api->locateURL('js','wymeditor/jquery.wymeditor.js');
$this->api->template->append('js_include', '<script type="text/javascript" src="'.
     $url.'"></script>'."\n");

$form->getElement('description')
    ->js(true)
    ->wymeditor(
        array(
            'updateEvent' => 'mouseenter',
            'updateSelector' => '.ui-button',
    ));
</code>```

Body:
Ok, I have got this code from other developer:

$url=$this->api->locateURL('js','wymeditor/jquery.wymeditor.js');
$this->api->template->append('js_include', '<script type="text/javascript" src="'.
     $url.'"></script>'."\n");

$form->getElement('description')
    ->js(true)
    ->wymeditor(
        array(
            'updateEvent' => 'mouseenter',
            'updateSelector' => '.ui-button',
    ));


问:
Exclude a woocommerce product category from wordpress global search results
I'm using this code to exclude some post category from the wordpress search results :

```<code>function SearchFilter($query)
{
    if ($query->is_search)
    {
        $query->set('cat', '-709,-710,-614');
    }
    return $query;
}
add_filter('pre_get_posts','SearchFilter');
</code>```

My problem is that it doesn't work for woocommerce categories and products are not filtered.
How can I filter some woocommerce categories too ?

答:
Can you replace your category. hope this help you.</p>

```<code>function wpse188669_pre_get_posts( $query ) {

   if (

       ! is_admin()

&& $query->is_main_query()

&& $query->is_search()

   ) {

       $query->set( 'post_type', array( 'product' ) );

       // set your parameters according to

     // https://codex.wordpress.org/Class_Reference/WP_Query#Taxonomy_Parameters

       $tax_query = array(

           array(

               // likely what you are after

               'taxonomy' => 'product_cat',

               'field'   => 'slug',

               'terms'   => 'category-2',

               'operator' => 'NOT IN',

           ),

       );

       $query->set( 'tax_query', $tax_query );

}

}

add_action( 'pre_get_posts', 'wpse188669_pre_get_posts' );
</code>```

Body:
I'm using this code to exclude some post category from the wordpress search results :

function SearchFilter($query)
{
    if ($query->is_search)
    {
        $query->set('cat', '-709,-710,-614');
    }
    return $query;
}
add_filter('pre_get_posts','SearchFilter');

My problem is that it doesn't work for woocommerce categories and products are not filtered.
How can I filter some woocommerce categories too ?

Body:
Can you replace your category. hope this help you.

function wpse188669_pre_get_posts( $query ) {

   if (

       ! is_admin()

&& $query->is_main_query()

&& $query->is_search()

   ) {

       $query->set( 'post_type', array( 'product' ) );

       // set your parameters according to

     // https://codex.wordpress.org/Class_Reference/WP_Query#Taxonomy_Parameters

       $tax_query = array(

           array(

               // likely what you are after

               'taxonomy' => 'product_cat',

               'field'   => 'slug',

               'terms'   => 'category-2',

               'operator' => 'NOT IN',

           ),

       );

       $query->set( 'tax_query', $tax_query );

}

}

add_action( 'pre_get_posts', 'wpse188669_pre_get_posts' );


问:
How to Parse Nested JSON
I'm able to parse the JSON using following code,

```<code>Map<String, dynamic> map = jsonDecode(response.body); // import 'dart:convert';

List<dynamic> datalist  = map['data'];
</code>```

I got List dynamic but i need data list

My problem is if I get product items in data list then how should i parse the JSON. I got stuck here.

When it comes to nested array of JSON, how to parse it.

**

```<code>{
    "status": 0,
    "message": "Product Not Found",
    "data": [{
            "id": "1",
            "product_name": "Pet 0.5",
            "qty": "500",
            "unit": "ml",
            "product_img": "SRC.jpg",
            "description": "sgsdgdfhdfhh",
            "sale_price": "100",
            "donation_amt": "10"
        },
        {
            "id": "7",
            "product_name": "Pet 1l",
            "qty": "1",
            "unit": "l",
            "product_img": "SRC1.jpg",
            "description": "dgdg",
            "sale_price": "20",
            "donation_amt": "1"
        }
    ]
}
</code>```

**

My dart code for the JSON

```<code>    class ProductList {
      int status;
      String message;
      List<Data> data;

      ProductList({this.status, this.message, this.data});

      ProductList.fromJson(Map<String, dynamic> json) {
        status = json['status'];
        message = json['message'];
        if (json['data'] != null) {
          data = new List<Data>();
          json['data'].forEach((v) {
            data.add(new Data.fromJson(v));
          });
        }
      }

      Map<String, dynamic> toJson() {
        final Map<String, dynamic> data = new Map<String, dynamic>();
        data['status'] = this.status;
        data['message'] = this.message;
        if (this.data != null) {
          data['data'] = this.data.map((v) => v.toJson()).toList();
        }
        return data;
      }
    }

class Data {
  String id;
  String productName;
  String qty;
  String unit;
  String productImg;
  String description;
  String salePrice;
  String donationAmt;

  Data(
      {this.id,
      this.productName,
      this.qty,
      this.unit,
      this.productImg,
      this.description,
      this.salePrice,
      this.donationAmt});

  Data.fromJson(Map<String, dynamic> json) {
    id = json['id'];
    productName = json['product_name'];
    qty = json['qty'];
    unit = json['unit'];
    productImg = json['product_img'];
    description = json['description'];
    salePrice = json['sale_price'];
    donationAmt = json['donation_amt'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['id'] = this.id;
    data['product_name'] = this.productName;
    data['qty'] = this.qty;
    data['unit'] = this.unit;
    data['product_img'] = this.productImg;
    data['description'] = this.description;
    data['sale_price'] = this.salePrice;
    data['donation_amt'] = this.donationAmt;
    return data;
  }
}
</code>```

This is the code below for the drop down list. We need to populate the drop down with the product name and id. The product name and id fields are there in the data part of the JSON

```<code>                       Padding(
                      padding: const EdgeInsets.fromLTRB(25.0, 20.0, 0, 0),
                    child: Container(
                        width: 160,
                        height: 40,
                        decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(5.0),
                          border: Border.all(
                              color: Colors.red,
                              style: BorderStyle.solid,
                              width: 0.80),
                        ),
                        child: DropdownButton<Product>(
                            value: selectedUser,
                            icon: Padding(
                              padding: const EdgeInsets.only(left:15.0),
                              child: Icon(Icons.arrow_drop_down),
                            ),
                            iconSize: 25,
                            underline: SizedBox(),
                            onChanged: (Product newValue) {
                              setState(() {
                                selectedUser = newValue;
                              });
                            },

                            items: users.map((Product user) {
                              return DropdownMenuItem<Product>(
                                value: user,
                                child: Padding(
                                  padding:
                                      const EdgeInsets.only(left: 10.0),
                                  child: Text(
                                    user.name,
                                    style: TextStyle(
                                      fontSize: 18,
                                      color: Colors.black,
                                    ),
                                  ),
                                ),
                              );
                            }).toList()),
                      ),
                       ),
</code>```

答:
Remember:  "JSON is not 'nested.'"  When you're given a JSON string, you decode it and this gives you a data-structure ... which very well might be "nested."  How to handle that correctly is up to you.

Always treat JSON (or YAML, or XML) as a "black box."  Use the utilities provided in the language to encode, decode and parse them.

Title: How to Parse Nested JSON

Body:
I'm able to parse the JSON using following code,

Map<String, dynamic> map = jsonDecode(response.body); // import 'dart:convert';

List<dynamic> datalist  = map['data'];

I got List dynamic but i need data list

My problem is if I get product items in data list then how should i parse the JSON. I got stuck here.

When it comes to nested array of JSON, how to parse it.

**

{
    "status": 0,
    "message": "Product Not Found",
    "data": [{
            "id": "1",
            "product_name": "Pet 0.5",
            "qty": "500",
            "unit": "ml",
            "product_img": "SRC.jpg",
            "description": "sgsdgdfhdfhh",
            "sale_price": "100",
            "donation_amt": "10"
        },
        {
            "id": "7",
            "product_name": "Pet 1l",
            "qty": "1",
            "unit": "l",
            "product_img": "SRC1.jpg",
            "description": "dgdg",
            "sale_price": "20",
            "donation_amt": "1"
        }
    ]
}

**

My dart code for the JSON

    class ProductList {
      int status;
      String message;
      List<Data> data;

      ProductList({this.status, this.message, this.data});

      ProductList.fromJson(Map<String, dynamic> json) {
        status = json['status'];
        message = json['message'];
        if (json['data'] != null) {
          data = new List<Data>();
          json['data'].forEach((v) {
            data.add(new Data.fromJson(v));
          });
        }
      }

      Map<String, dynamic> toJson() {
        final Map<String, dynamic> data = new Map<String, dynamic>();
        data['status'] = this.status;
        data['message'] = this.message;
        if (this.data != null) {
          data['data'] = this.data.map((v) => v.toJson()).toList();
        }
        return data;
      }
    }

class Data {
  String id;
  String productName;
  String qty;
  String unit;
  String productImg;
  String description;
  String salePrice;
  String donationAmt;

  Data(
      {this.id,
      this.productName,
      this.qty,
      this.unit,
      this.productImg,
      this.description,
      this.salePrice,
      this.donationAmt});

  Data.fromJson(Map<String, dynamic> json) {
    id = json['id'];
    productName = json['product_name'];
    qty = json['qty'];
    unit = json['unit'];
    productImg = json['product_img'];
    description = json['description'];
    salePrice = json['sale_price'];
    donationAmt = json['donation_amt'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['id'] = this.id;
    data['product_name'] = this.productName;
    data['qty'] = this.qty;
    data['unit'] = this.unit;
    data['product_img'] = this.productImg;
    data['description'] = this.description;
    data['sale_price'] = this.salePrice;
    data['donation_amt'] = this.donationAmt;
    return data;
  }
}

This is the code below for the drop down list. We need to populate the drop down with the product name and id. The product name and id fields are there in the data part of the JSON

                       Padding(
                      padding: const EdgeInsets.fromLTRB(25.0, 20.0, 0, 0),
                    child: Container(
                        width: 160,
                        height: 40,
                        decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(5.0),
                          border: Border.all(
                              color: Colors.red,
                              style: BorderStyle.solid,
                              width: 0.80),
                        ),
                        child: DropdownButton<Product>(
                            value: selectedUser,
                            icon: Padding(
                              padding: const EdgeInsets.only(left:15.0),
                              child: Icon(Icons.arrow_drop_down),
                            ),
                            iconSize: 25,
                            underline: SizedBox(),
                            onChanged: (Product newValue) {
                              setState(() {
                                selectedUser = newValue;
                              });
                            },

                            items: users.map((Product user) {
                              return DropdownMenuItem<Product>(
                                value: user,
                                child: Padding(
                                  padding:
                                      const EdgeInsets.only(left: 10.0),
                                  child: Text(
                                    user.name,
                                    style: TextStyle(
                                      fontSize: 18,
                                      color: Colors.black,
                                    ),
                                  ),
                                ),
                              );
                            }).toList()),
                      ),
                       ),


问:
Specifying type of generic variable in angular component
I am trying to create a generic component which can expect data of two types only:

```<code>interface X{
    name: string,
    path: string,
    type: string,
}

interface Y{
    name: string,
    path: string,
}
</code>```

Both types X,Y have two common properties and X has one extra.
Now I am defining the type this way:

```<code>export class MyComponent<T extends X | Y> implements OnInit{
    @Input() data: T[];
    func(item: T){
        let temp = this.data.find(x => x.name === item.name);
        <<....some code....>>
    }
}
</code>```

Calling this from the parent component this way:

```<code><my-component [data]="xList"></my-component>     <!-- xList: X[] -->
<my-component [data]="yList"></my-component>     <!-- yList: y[] -->
</code>```

This is working fine but I am not sure if this <T extends X | Y> is the correct way to do this or not. Can anybody please suggest the best approach here?
Can we write something like where T implements X | Y in Typescript?

Or should I just use @Input() data: any[];?

答: I think this is fine but I would do T extends Y only because the type key is extra on the X and this component would break if we feed it an input of type array of Y and the component messes around with the type key.

Body:
I am trying to create a generic component which can expect data of two types only:

interface X{
    name: string,
    path: string,
    type: string,
}

interface Y{
    name: string,
    path: string,
}

Both types X,Y have two common properties and X has one extra.
Now I am defining the type this way:

export class MyComponent<T extends X | Y> implements OnInit{
    @Input() data: T[];
    func(item: T){
        let temp = this.data.find(x => x.name === item.name);
        <<....some code....>>
    }
}

Calling this from the parent component this way:

<my-component [data]="xList"></my-component>
<my-component [data]="yList"></my-component>

This is working fine but I am not sure if this <T extends X | Y> is the correct way to do this or not. Can anybody please suggest the best approach here?
Can we write something like where T implements X | Y in Typescript?

Or should I just use @Input() data: any[];?


问:
How to make React Native Animated.View clickable?
I'm using this react native tinder demo -> https://github.com/brentvatne/react-native-animated-demo-tinder

Is it possible to make the cards 'clickable' so it would navigate to another view on click? I've tried wrapping the "Touchable" components around the animated view but doing so disables the animations.

Any ideas would be highly appreciated, thanks!

答:
it's too late but in my case i have set the height of Animated.View less than the content inside it

so make sure that the Animated.View height must be greater or equal to the content on which TouchableOpacity is placed


问:
How do you pass variables to other JS modules with Fetch API?
A JavaScript app uses Web Audio API to create sounds from JSON data. I am fetching weather data, going through the JSON data and setting their properties to variables then using those variables to manipulate my application and create sounds. Each function in it's own JavaScript module script file. The main.js not shown here is the entry point to app.

A sample JSON that will get replaced with real weather data.

dummy-data.json

```<code>{
    "weather": {
        "temp": 4,
        "rain": 1,
        "wind": 1.2
    }
}
</code>```

The fetch API logic.

fetchWeather.js

```<code>import { manageData} from './manageScript.js';

const DUMMY = '../dummy-data.json';

const fetchWeather = () => {
    fetch(DUMMY)
        .then((res) => {
            return res.json();
        })
        .then((data) => {
            manageData(data); // attaches JSON weather properties to variables
        })
        .catch((error) => {
            console.log(error);
        });
};

export { fetchWeather };
</code>```

Attaches the JSON data to variables.

manageScript.js

```<code>function manageData(data) {
    let rain = data.weather.rain;
    //let wind = data.weather.wind;

    let rainProbability;

    if (rain == 1) {
        rainProbability = 1;
    }
    else {
        rainProbability = 0;
    }

    return rainProbability; // not sure how to return the data....?
};

export { manageData };
</code>```

I want the variables from manageData function above to work here

makeSynth.js

```<code>import { manageData } from './manageScript.js';

const createSynth = () => {
    //Web Audio API stuff goes here to create sounds from the variables.

    //How do I get the variables to work here. Code below does not work!
    let soundOfRain = manageData().rainProbability;
    console.log(soundOfRain);
};
</code>```

答:
You can add data as a property of manageData that would return this, and access it with manageData().data; :

fetchWeather.js

```<code>const fetchWeather = () => {
  fetch(DUMMY)
    .then(res => {
      return res.json();
    })
    .then(data => {
      manageData.data = data; // attaches JSON weather properties to variables
    })
    .catch(error => {
      console.log(error);
    });
};
</code>```

manageScript.js

```<code>function manageData() {
  // ...
  return this;
}
</code>```

makeSynth.js

```<code>let soundOfRain = manageData().data.rainProbability;
</code>```

Body:
A JavaScript app uses Web Audio API to create sounds from JSON data. I am fetching weather data, going through the JSON data and setting their properties to variables then using those variables to manipulate my application and create sounds. Each function in it's own JavaScript module script file. The main.js not shown here is the entry point to app.

A sample JSON that will get replaced with real weather data.

dummy-data.json

{
    "weather": {
        "temp": 4,
        "rain": 1,
        "wind": 1.2
    }
}

The fetch API logic.

fetchWeather.js

import { manageData} from './manageScript.js';

const DUMMY = '../dummy-data.json';

const fetchWeather = () => {
    fetch(DUMMY)
        .then((res) => {
            return res.json();
        })
        .then((data) => {
            manageData(data); // attaches JSON weather properties to variables
        })
        .catch((error) => {
            console.log(error);
        });
};

export { fetchWeather };

Attaches the JSON data to variables.

manageScript.js

function manageData(data) {
    let rain = data.weather.rain;
    //let wind = data.weather.wind;

    let rainProbability;

    if (rain == 1) {
        rainProbability = 1;
    }
    else {
        rainProbability = 0;
    }

    return rainProbability; // not sure how to return the data....?
};

export { manageData };

I want the variables from manageData function above to work here

makeSynth.js

import { manageData } from './manageScript.js';

const createSynth = () => {
    //Web Audio API stuff goes here to create sounds from the variables.

    //How do I get the variables to work here. Code below does not work!
    let soundOfRain = manageData().rainProbability;
    console.log(soundOfRain);
};

Body:
You can add data as a property of manageData that would return this, and access it with manageData().data; :

fetchWeather.js

const fetchWeather = () => {
  fetch(DUMMY)
    .then(res => {
      return res.json();
    })
    .then(data => {
      manageData.data = data; // attaches JSON weather properties to variables
    })
    .catch(error => {
      console.log(error);
    });
};

manageScript.js

function manageData() {
  // ...
  return this;
}

makeSynth.js

let soundOfRain = manageData().data.rainProbability;


问:
How to set a given table cell in Vue.js
I am using @vue/cli 4.1.2 and would like to update given table cells with values from an axios call.
It almost works however instead of putting the result value only into the cell from that row where I pressed the "Run Query" button the entire column "Results" is set to that given result.

Here my code:

```<code><template>
    <div class="container-fluid">
      <div class="text-center">
        <h1>Recon Query Automator</h1>
       <div v-if="queries.length === 0">
            <h2> No query found at the moment </h2>
        </div>
      </div>

        <div class="">
            <table class="table table-bordered">
              <thead class="thead-dark">
                <tr>
                  <th scope="col" @click="sort('id')">ID</th>
                  <th scope="col" @click="sort('cat')">Category</th>
                  <th scope="col" @click="sort('name')">Name</th>
                  <th scope="col">SQL</th>
                  <th scope="col">Result</th>
                  <th scope="col">Manage</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="query in sortedQueries" :key="query._id">
                  <td>{{ query.id }}</td>
                  <td>{{ query.cat }}</td>
                  <td>{{ query.name }}</td>
                  <td>{{ query.sql }}</td>
                  <td v-on:click="runQuery(query.id)">{{ result }}</td>
                  <td>
                    <div class="d-flex justify-content-between align-items-center">
                                <div class="btn-group" style="margin-bottom: 20px;">
                                  <router-link :to="{name: 'Edit', params: {id: query._id}}" class="btn btn-sm btn-outline-secondary">Edit Query </router-link>
                                  <button class="btn btn-sm btn-outline-secondary" v-on:click="deleteQuery(query._id)">Delete Query</button>
                                  <button class="btn btn-sm btn-outline-secondary" v-on:click="runQuery(query.id)">Run Query</button>

                                </div>
                              </div>
                  </td>
                </tr>
              </tbody>
            </table>
            <p>
            <button @click="prevPage">Previous</button>
            <button @click="nextPage">Next</button>
            </p>
          </div>
    </div>
</template>
</code>```

The typescript:

```<code><script>
import { server } from "../helper";
import axios from "axios";
export default {
  data() {
    return {
      queries: [],
      result: '',
      currentSort:'name',
      currentSortDir:'asc',
      pageSize:999,
      currentPage:1
    };
  },
  created() {
    this.fetchQueries();
  },
  computed: {
    sortedQueries:function() {
      return this.queries.sort((a,b) => {
        let modifier = 1;
        if(this.currentSortDir === 'desc') modifier = -1;
        if(a[this.currentSort] < b[this.currentSort]) return -1 * modifier;
        if(a[this.currentSort] > b[this.currentSort]) return 1 * modifier;
        return 0;
      }).filter((row, index) => {
        let start = (this.currentPage-1)*this.pageSize;
        let end = this.currentPage*this.pageSize;
        if(index >= start && index < end) return true;
    });;
    }
  },
  methods: {
    fetchQueries() {
      axios
        .get(`${server.baseURL}/reconQuery/queries`)
        .then(data =>
          {
            this.queries = data.data;
          });
    },
    deleteQuery(id) {
      axios
        .delete(`${server.baseURL}/reconQuery/delete?queryID=${id}`)
        .then(data => {
          console.log(data);
          window.location.reload();
        });
    },
    runQuery(id) {
      axios
        .get(`${server.msURL}/run/${id}`)
        .then(Response => {
          alert(Response.data);
          this.result = Response.data;
          console.log(this.result);
        });
        },
    sort(s) {
      //if s == current sort, reverse
      if(s === this.currentSort) {
        this.currentSortDir = this.currentSortDir==='asc'?'desc':'asc';
      }
      this.currentSort = s;
      },
      nextPage() {
        if((this.currentPage*this.pageSize) < this.cats.length) this.currentPage++;
      },
      prevPage() {
        if(this.currentPage > 1) this.currentPage--;
      }
   }
};
</script>
</code>```

I am only interested in the runQuery(id) method as else work fine.

答:
Your result is global for all queries, so it shows for all queries. You need something like:

```<code>data: () => ({
  result: {}
  ...
}),
methods: {
  runQuery(id) {
    axios
      .get(`${server.msURL}/run/${id}`)
      .then(Response => {
        this.$set(this.result, id, Response.data);
      });
  },
</code>```

and in template:

```<code><td v-on:click="runQuery(query.id)">{{ result[query.id] || '' }}</td>
</code>```

Title: How to set a given table cell in Vue.js

Body:
I am using @vue/cli 4.1.2 and would like to update given table cells with values from an axios call.
It almost works however instead of putting the result value only into the cell from that row where I pressed the "Run Query" button the entire column "Results" is set to that given result.

Here my code:

<template>

Recon Query Automator

 No query found at the moment

                  ID
                  Category
                  Name
                  SQL
                  Result
                  Manage

                  {{ query.id }}
                  {{ query.cat }}
                  {{ query.name }}
                  {{ query.sql }}
                  {{ result }}

                                  <router-link :to="{name: 'Edit', params: {id: query._id}}" class="btn btn-sm btn-outline-secondary">Edit Query </router-link>
                                  <button class="btn btn-sm btn-outline-secondary" v-on:click="deleteQuery(query._id)">Delete Query</button>
                                  <button class="btn btn-sm btn-outline-secondary" v-on:click="runQuery(query.id)">Run Query</button>

            <button @click="prevPage">Previous</button>
            <button @click="nextPage">Next</button>

</template>

The typescript:

I am only interested in the runQuery(id) method as else work fine.

Body:
Your result is global for all queries, so it shows for all queries. You need something like:

data: () => ({
  result: {}
  ...
}),
methods: {
  runQuery(id) {
    axios
      .get(`${server.msURL}/run/${id}`)
      .then(Response => {
        this.$set(this.result, id, Response.data);
      });
  },

and in template:

<td v-on:click="runQuery(query.id)">{{ result[query.id] || '' }}</td>


问:
pd.update with two matching rows
What I am trying to do is updating the empty df1 from df2, which is created in a while-loop that requests data through an API. I want to keep all rows and their order from df1.

```<code>df1:

df = pd.DataFrame({'A': ['c1', 'c1', 'c2','c2', 'c3', 'c3'], 'B': ['y1', 'y2', 'y1', 'y2', 'y1', 'y2'], 'C': ["","","","","",""], 'D': ["","","","","",""]})

    A   B   C   D
0   c1  y1
1   c1  y2
2   c2  y1
3   c2  y2
4   c3  y1
5   c3  y2

df2:

values_for_df = pd.DataFrame({'A': ['c1', 'c1', 'c2', 'c3'], 'B': ['y1', 'y2', 'y1', 'y2'], 'C': [4, 5, 4, 6], 'D': [7, 8, 9,""]})

    A   B   C   D
0   c1  y1  4   7
1   c1  y2  5   8
2   c2  y1  4   9
3   c3  y2  6

Output:
    A   B   C   D
0   c1  y1  4   7
1   c1  y2  5   8
2   c2  y1  4   9
3   c3  y2  6
4   c3  y1
5   c3  y2

Wanted output:

    A   B   C   D
0   c1  y1  4   7
1   c1  y2  5   8
2   c2  y1  4   9
3   c2  y2
4   c3  y1
5   c3  y2      6

</code>```

This process will be repated 1000s of times. Can someone help me with this, share his ideas / alternative ways or explain me why the actual output differs from my expected output?

答:
Try:</p>

```<code>df = df.set_index(['A','B'])
values_for_df = values_for_df.set_index(['A','B'])
df.update(values_for_df, filter_func=lambda x: x=='')
df.reset_index()

    A   B  C  D
0  c1  y1  4  7
1  c1  y2  5  8
2  c2  y1  4  9
3  c2  y2
4  c3  y1
5  c3  y2  6
</code>```

Title: pd.update with two matching rows

Body:
What I am trying to do is updating the empty df1 from df2, which is created in a while-loop that requests data through an API. I want to keep all rows and their order from df1.

df1:

df = pd.DataFrame({'A': ['c1', 'c1', 'c2','c2', 'c3', 'c3'], 'B': ['y1', 'y2', 'y1', 'y2', 'y1', 'y2'], 'C': ["","","","","",""], 'D': ["","","","","",""]})

    A   B   C   D
0   c1  y1
1   c1  y2
2   c2  y1
3   c2  y2
4   c3  y1
5   c3  y2

df2:

values_for_df = pd.DataFrame({'A': ['c1', 'c1', 'c2', 'c3'], 'B': ['y1', 'y2', 'y1', 'y2'], 'C': [4, 5, 4, 6], 'D': [7, 8, 9,""]})

    A   B   C   D
0   c1  y1  4   7
1   c1  y2  5   8
2   c2  y1  4   9
3   c3  y2  6

Output:
    A   B   C   D
0   c1  y1  4   7
1   c1  y2  5   8
2   c2  y1  4   9
3   c3  y2  6
4   c3  y1
5   c3  y2

Wanted output:

    A   B   C   D
0   c1  y1  4   7
1   c1  y2  5   8
2   c2  y1  4   9
3   c2  y2
4   c3  y1
5   c3  y2      6

This process will be repated 1000s of times. Can someone help me with this, share his ideas / alternative ways or explain me why the actual output differs from my expected output?

Body:
Try:

df = df.set_index(['A','B'])
values_for_df = values_for_df.set_index(['A','B'])
df.update(values_for_df, filter_func=lambda x: x=='')
df.reset_index()

    A   B  C  D
0  c1  y1  4  7
1  c1  y2  5  8
2  c2  y1  4  9
3  c2  y2
4  c3  y1
5  c3  y2  6


问:
How to disable an eventListener in RCP?
I've an EventListener dedicated to listen to the focusLost() event of a Text in my view  in Eclipse RCP. The Listener's working fine. But at some point of the execution I want to disable this Listener from Listening to the Text and Later I wish it to be activated.
How can it be deactivated or activated as per our needs programatically ?</p>

答:
The other common pattern used is to include a boolean with the listener (or associated with the text field).  While probably not too costly on a single widget, adding and removing listeners potentially involves array copies and allocations.  Just set enabled to false:</p>

```<code>public final void handleEvent(final Event event) {
    if (!textListenerEnabled) {
        return;
    }
    // the rest of your processing.
}
</code>```

Title: How to disable an eventListener in RCP?

Body:
The other common pattern used is to include a boolean with the listener (or associated with the text field).  While probably not too costly on a single widget, adding and removing listeners potentially involves array copies and allocations.  Just set enabled to false:

public final void handleEvent(final Event event) {
    if (!textListenerEnabled) {
        return;
    }
    // the rest of your processing.
}


问:
Oracle IO Error: The Network Adapter could not establish the connection
I am getting this error, but over mac An error was encountered performing the requested operation:

IO Error: The Network Adapter could not establish the connection

Vendor code 17002

I am not able to know where to get into services from mac , like windows. What solution?I am using version 19.0.1 latest

答:
Step 1: Check your IP by Apple -> System Preferences -> Network -> Click on a Network Service (Wifi connection or Ethernet connection) .

Step 2: Go to Applications -> Network Utility -> Port scan -> Copy your IP address there and Scan for available TCP ports.

Step 3: enter a open TCP port as the port in your oracle connection.


问:
Collapsing rows using two vectors as indicators
This is my first time posting; please let me know if I'm doing any beginner mistakes. In my specific case I have a vector of strings, and I want to collapse some adjacent rows. I have one vector indicating the starting position and one indicating the last element. How can I do this?

Here is some sample code and my approach that does not work:

```<code>text <- c("cat", "dog", "house", "mouse", "street")
x <- c(1,3)
y <- c(2,5)
result <- as.data.frame(paste(text[x:y],sep = " ",collapse = ""))
</code>```

In case it's not clear, the result I want is a data frame consisting of two strings: "cat dog" and "house mouse street".

答:
I think you want

```<code>result <- data.frame(combined = c(paste(text[x[1]:y[1]], collapse = " "),
                                  paste(text[x[2]:y[2]], collapse = " ")))
</code>```

Which gives you

```<code>result
#>             combined
#> 1            cat dog
#> 2 house mouse street
</code>```

Body:
This is my first time posting; please let me know if I'm doing any beginner mistakes. In my specific case I have a vector of strings, and I want to collapse some adjacent rows. I have one vector indicating the starting position and one indicating the last element. How can I do this?

Here is some sample code and my approach that does not work:

text <- c("cat", "dog", "house", "mouse", "street")
x <- c(1,3)
y <- c(2,5)
result <- as.data.frame(paste(text[x:y],sep = " ",collapse = ""))

In case it's not clear, the result I want is a data frame consisting of two strings: "cat dog" and "house mouse street".

Body:
I think you want

result <- data.frame(combined = c(paste(text[x[1]:y[1]], collapse = " "),
                                  paste(text[x[2]:y[2]], collapse = " ")))

Which gives you

result
#>             combined
#> 1            cat dog
#> 2 house mouse street


问:
How to use Jenkins credentials when running `mvn deploy`?
I have a Maven project and want to build it using mvn clean deploy so that the built artifact is deployed into a Nexus repository.

The access data (username and password) for that repository are stored in Jenkins credentials.

I want to call mvn deploy in Jenkins so that the credentials for that Nexus repository are read from Jenkins (not hardcoded in settings.xml).

How can I do it, if I cannot access settings.xml on the Jenkins server?

Update 1:

I created an entry in "Config File Management" (JENKINS_URL/configfiles/index) with following data:

Type: Maven settings.xml

Replace All: Yes

Server ID: myServer

Credentials: Credentials for the Nexus repository

Content:

```<code><?xml version="1.0" encoding="UTF-8"?>
<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0 http://maven.apache.org/xsd/settings-1.0.0.xsd">

  <servers>
    <server>
      <id>myServer</id>
      <username>foo</username>
      <password>bar</password>
    </server>
  </servers>
</settings>

</code>```

myServer is also used in the pom.xml of the artifact I want to build:

```<code>    <distributionManagement>
        <repository>
            <id>myServer</id>
            <url>http://nexus.mycompany.com</url>
        </repository>
    </distributionManagement>

</code>```

In the configuration of the job, I include those settings as shown below. Nexus settings.xml is the configuration from "Config File Management".

But it does not work -- I get "Forbidden" error when the build attempts to deploy artifacts to Nexus.

Update 2: When I run mvn -X deploy locally with the same credentials as in Jenkins (stored in my local settings.xml), I see following output:

```<code>[DEBUG] Failed to decrypt password for server XXX release repository: org.sonatype.plexus.components.sec.dispatcher.SecDispatcherException: java.io.FileNotFoundException: /XXXXXXXXXXXXXXX/.m2/settings-security.xml (No such file or directory)
org.sonatype.plexus.components.sec.dispatcher.SecDispatcherException: org.sonatype.plexus.components.sec.dispatcher.SecDispatcherException: java.io.FileNotFoundException: /XXXXXXXXXXXXXXX/.m2/settings-security.xml (No such file or directory)
    at org.sonatype.plexus.components.sec.dispatcher.DefaultSecDispatcher.decrypt(DefaultSecDispatcher.java:121)
    at org.apache.maven.settings.crypto.DefaultSettingsDecrypter.decrypt(DefaultSettingsDecrypter.java:107)
    at org.apache.maven.settings.crypto.DefaultSettingsDecrypter.decrypt(DefaultSettingsDecrypter.java:63)
    at org.apache.maven.internal.aether.DefaultRepositorySystemSessionFactory.newRepositorySession(DefaultRepositorySystemSessionFactory.java:165)
</code>```

However, the password in settings.xml is not encrypted at all:

```<code><settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0
                  https://maven.apache.org/xsd/settings-1.0.0.xsd">
<localRepository/>
<interactiveMode/>
<offline/>
<pluginGroups/>
<servers>
  <server>
    <id>NEXUS_REPOSITORY_SNAPSHOTS</id>
    <username>user</username>
    <password>password</password>
  </server>
</servers>
<mirrors/>
<proxies/>
<profiles/>
<activeProfiles/>
</settings>
</code>```

I found a report about similar error here.

答:
You can use the Jenkins config-file-provider plugin ( link: https://plugins.jenkins.io/config-file-provider/ ) to create one or several Maven settings.xml files.

NOTE: Really this helps also if you need differents settings.xml for
  different projects.

Then on the maven deploy step of your Jenkins project you can select to point to one of the settings.xml files defined ( instead of pointing to the general Jenkins server /.m2/settings.xml )

Body:
I have a Maven project and want to build it using mvn clean deploy so that the built artifact is deployed into a Nexus repository.

The access data (username and password) for that repository are stored in Jenkins credentials.

I want to call mvn deploy in Jenkins so that the credentials for that Nexus repository are read from Jenkins (not hardcoded in settings.xml).

How can I do it, if I cannot access settings.xml on the Jenkins server?

Update 1:

I created an entry in "Config File Management" (JENKINS_URL/configfiles/index) with following data:

Type: Maven settings.xml

Replace All: Yes

Server ID: myServer

Credentials: Credentials for the Nexus repository

Content:

<?xml version="1.0" encoding="UTF-8"?>
<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0 http://maven.apache.org/xsd/settings-1.0.0.xsd">

  <servers>
    <server>
      <id>myServer</id>
      <username>foo</username>
      <password>bar</password>
    </server>
  </servers>
</settings>

myServer is also used in the pom.xml of the artifact I want to build:

    <distributionManagement>
        <repository>
            <id>myServer</id>
            <url>http://nexus.mycompany.com</url>
        </repository>
    </distributionManagement>

In the configuration of the job, I include those settings as shown below. Nexus settings.xml is the configuration from "Config File Management".

But it does not work -- I get "Forbidden" error when the build attempts to deploy artifacts to Nexus.

Update 2: When I run mvn -X deploy locally with the same credentials as in Jenkins (stored in my local settings.xml), I see following output:

[DEBUG] Failed to decrypt password for server XXX release repository: org.sonatype.plexus.components.sec.dispatcher.SecDispatcherException: java.io.FileNotFoundException: /XXXXXXXXXXXXXXX/.m2/settings-security.xml (No such file or directory)
org.sonatype.plexus.components.sec.dispatcher.SecDispatcherException: org.sonatype.plexus.components.sec.dispatcher.SecDispatcherException: java.io.FileNotFoundException: /XXXXXXXXXXXXXXX/.m2/settings-security.xml (No such file or directory)
    at org.sonatype.plexus.components.sec.dispatcher.DefaultSecDispatcher.decrypt(DefaultSecDispatcher.java:121)
    at org.apache.maven.settings.crypto.DefaultSettingsDecrypter.decrypt(DefaultSettingsDecrypter.java:107)
    at org.apache.maven.settings.crypto.DefaultSettingsDecrypter.decrypt(DefaultSettingsDecrypter.java:63)
    at org.apache.maven.internal.aether.DefaultRepositorySystemSessionFactory.newRepositorySession(DefaultRepositorySystemSessionFactory.java:165)

However, the password in settings.xml is not encrypted at all:

<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0
                  https://maven.apache.org/xsd/settings-1.0.0.xsd">
<localRepository/>
<interactiveMode/>
<offline/>
<pluginGroups/>
<servers>
  <server>
    <id>NEXUS_REPOSITORY_SNAPSHOTS</id>
    <username>user</username>
    <password>password</password>
  </server>
</servers>
<mirrors/>
<proxies/>
<profiles/>
<activeProfiles/>
</settings>

I found a report about similar error here.