问:
Volley error occurs while swiping between fragments/viewpager
In my activity all tabs are created as dynamic. Each swiping json data is called. The volley error occurs after a number of swiping.  After this , no data is available on fragment and any of the other pages. This is my code</p>

```<code>fragmentParent.addPage(jsonObject.getString("name"),jsonObject.getString("cat_id"),shop_id);

    public class FragmentParent extends Fragment {
        private TabLayout tabLayout;
        private ViewPager viewPager;
        private ViewPagerAdapter1 adapter;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_parent, container, false);
        getIDs(view);
        setEvents();
        return view;
    }

    private void getIDs(View view) {
        viewPager = (ViewPager) view.findViewById(R.id.my_viewpager);
        tabLayout = (TabLayout) view.findViewById(R.id.my_tab_layout);
        adapter = new ViewPagerAdapter1(getFragmentManager(), getActivity(), viewPager, tabLayout);
        viewPager.setAdapter(adapter);
    }

    int selectedTabPosition;

    private void setEvents() {

        tabLayout.setOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(viewPager) {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                super.onTabSelected(tab);
                viewPager.setCurrentItem(tab.getPosition());
                selectedTabPosition = viewPager.getCurrentItem();
                Log.d("Selected", "Selected " + tab.getPosition());
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
                super.onTabUnselected(tab);
                Log.d("Unselected", "Unselected " + tab.getPosition());
            }
        });
    }

    public void addPage(String pagename, String id,String shop_id) {
        Bundle bundle = new Bundle();
        bundle.putString("data", id);
        bundle.putString("shop_id", shop_id);
        FragmentChild fragmentChild = new FragmentChild();
        fragmentChild.setArguments(bundle);
        adapter.addFrag(fragmentChild, pagename);
        adapter.notifyDataSetChanged();
        if (adapter.getCount() > 0) tabLayout.setupWithViewPager(viewPager);

        viewPager.setCurrentItem(adapter.getCount() - 1);
        setupTabLayout();
    }

    public void setupTabLayout() {
        selectedTabPosition = viewPager.getCurrentItem();
        for (int i = 0; i < tabLayout.getTabCount(); i++) {
            tabLayout.getTabAt(i).setCustomView(adapter.getTabView(i));
        }
    }
}

public class FragmentChild extends Fragment {
    String childname,shoppe_id;
    RecyclerView imgflag;
    CategoryItemAdapter categoryItemAdapter;
    HttpStack stack;
    List<ShopDetails> cat_item_list;
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_child, container, false);
        Bundle bundle = getArguments();
        childname = bundle.getString("data");
        shoppe_id=bundle.getString("shop_id");
        stack = new HurlStack();
        imgflag=(RecyclerView)view.findViewById(R.id.imgflag);
        cat_item_list = new ArrayList<ShopDetails>();
        categoryItemAdapter = new CategoryItemAdapter(getActivity(),cat_item_list);
        GridLayoutManager layoutManager
                = new GridLayoutManager(getActivity(),1, GridLayoutManager.VERTICAL,false);
        imgflag.setLayoutManager(layoutManager);
        imgflag.setAdapter(categoryItemAdapter);
       getCategoryItem(childname);
        return view;
    }

    public void getCategoryItem(String cat_id)
    {

        stack = new HurlStack(null, createSslSocketFactory());
        final RequestQueue requestQueue = Volley.newRequestQueue(getActivity(),stack);
        String url=config.api_url+"view_cat_item.php?cat_id="+cat_id;
        StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                if(response.equals("0 results"))
                {

                }
                else
                {

                    try {
                        JSONArray jsonArray=new JSONArray(response);
                        for(int i=0;i<jsonArray.length();i++)
                        {
                            JSONObject jsonObject=jsonArray.getJSONObject(i);
                            ShopDetails shopDetails=new ShopDetails();
                            shopDetails.setItem_name(jsonObject.getString("item_name"));
                            shopDetails.setItem_image(jsonObject.getString("image"));
                            shopDetails.setItem_price(jsonObject.getString("price"));
                            shopDetails.setItem_desc(jsonObject.getString("ingredients"));
                            cat_item_list.add(shopDetails);
                        }
                        if(cat_item_list!=null)
                        {

                            categoryItemAdapter.notifyDataSetChanged();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

                Toast.makeText(getActivity(), "Unable to connect. Please check your connection.", Toast.LENGTH_SHORT).show();

            }
        }){
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> params = new HashMap<String, String>();
                params.put("shoppe_id", shoppe_id);
                return params;
            }
        };
        stringRequest.setRetryPolicy(new DefaultRetryPolicy(
                60000,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        stringRequest.setShouldCache(false);
        requestQueue.add(stringRequest);
    }
    private static SSLSocketFactory createSslSocketFactory() {
        TrustManager[] byPassTrustManagers = new TrustManager[]{new X509TrustManager() {
            public X509Certificate[] getAcceptedIssuers() {
                return new X509Certificate[0];
            }

            public void checkClientTrusted(X509Certificate[] chain, String authType) {
            }

            public void checkServerTrusted(X509Certificate[] chain, String authType) {
            }
        }};

        SSLContext sslContext = null;
        SSLSocketFactory sslSocketFactory = null;
        try {
            sslContext = SSLContext.getInstance("TLS");
            sslContext.init(null, byPassTrustManagers, new SecureRandom());
            sslSocketFactory = sslContext.getSocketFactory();

        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
          Log.e(TAG, StringUtils.EMPTY, e);
        } catch (KeyManagementException e) {
           Log.e(TAG, StringUtils.EMPTY, e);
        }
        return sslSocketFactory;
    }
    public final boolean isInternetOn() {
        ConnectivityManager connec = (ConnectivityManager) getActivity().getSystemService(getActivity().getBaseContext().CONNECTIVITY_SERVICE);
        if (connec.getNetworkInfo(0).getState() == android.net.NetworkInfo.State.CONNECTED ||
                connec.getNetworkInfo(0).getState() == android.net.NetworkInfo.State.CONNECTING ||
                connec.getNetworkInfo(1).getState() == android.net.NetworkInfo.State.CONNECTING ||
                connec.getNetworkInfo(1).getState() == android.net.NetworkInfo.State.CONNECTED) {

            return true;
        } else if (
                connec.getNetworkInfo(0).getState() == android.net.NetworkInfo.State.DISCONNECTED ||
                        connec.getNetworkInfo(1).getState() == android.net.NetworkInfo.State.DISCONNECTED) {

            return false;
        }
        return false;
    }
}
</code>```

答:
I think it happens because when you switch fragments volley create request again and again. so you can cancel volley request when you leave from fragments by override onStop() method

```<code>@Override
public void onStop() {
    super.onStop();
    VolleySingleton.getInstance(getActivity()).getRequestQueue().cancelAll(VolleySingleton.TAG);
}
</code>```

you can set Tag like this

```<code>jsonObjectRequest.setTag(VolleySingleton.TAG);
</code>```

VolleySingleton.java

```<code>public class VolleySingleton {
    private static VolleySingleton mInstance;
    private RequestQueue mRequestQueue;
    private ImageLoader mImageLoader;
    private static Context mCtx;
    public static final String TAG = "tagData";

    private VolleySingleton(Context context) {
        mCtx = context;
        mRequestQueue = getRequestQueue();

        mImageLoader = new ImageLoader(mRequestQueue,
                new ImageLoader.ImageCache() {
                    private final LruCache<String, Bitmap>
                            cache = new LruCache<String, Bitmap>(20);

                    @Override
                    public Bitmap getBitmap(String url) {
                        return cache.get(url);
                    }

                    @Override
                    public void putBitmap(String url, Bitmap bitmap) {
                        cache.put(url, bitmap);
                    }
                });
    }

    public static synchronized VolleySingleton getInstance(Context context) {
        if (mInstance == null) {
            mInstance = new VolleySingleton(context);
        }
        return mInstance;
    }

    public RequestQueue getRequestQueue() {
        if (mRequestQueue == null) {
            // getApplicationContext() is key, it keeps you from leaking the
            // Activity or BroadcastReceiver if someone passes one in.
            mRequestQueue = Volley.newRequestQueue(mCtx.getApplicationContext());
        }
        return mRequestQueue;
    }

    public <T> void addToRequestQueue(Request<T> req) {
        getRequestQueue().add(req);
    }

    public ImageLoader getImageLoader() {
        return mImageLoader;
    }
}
</code>```

Body:
In my activity all tabs are created as dynamic. Each swiping json data is called. The volley error occurs after a number of swiping.  After this , no data is available on fragment and any of the other pages. This is my code

fragmentParent.addPage(jsonObject.getString("name"),jsonObject.getString("cat_id"),shop_id);

    public class FragmentParent extends Fragment {
        private TabLayout tabLayout;
        private ViewPager viewPager;
        private ViewPagerAdapter1 adapter;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_parent, container, false);
        getIDs(view);
        setEvents();
        return view;
    }

    private void getIDs(View view) {
        viewPager = (ViewPager) view.findViewById(R.id.my_viewpager);
        tabLayout = (TabLayout) view.findViewById(R.id.my_tab_layout);
        adapter = new ViewPagerAdapter1(getFragmentManager(), getActivity(), viewPager, tabLayout);
        viewPager.setAdapter(adapter);
    }

    int selectedTabPosition;

    private void setEvents() {

        tabLayout.setOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(viewPager) {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                super.onTabSelected(tab);
                viewPager.setCurrentItem(tab.getPosition());
                selectedTabPosition = viewPager.getCurrentItem();
                Log.d("Selected", "Selected " + tab.getPosition());
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
                super.onTabUnselected(tab);
                Log.d("Unselected", "Unselected " + tab.getPosition());
            }
        });
    }

    public void addPage(String pagename, String id,String shop_id) {
        Bundle bundle = new Bundle();
        bundle.putString("data", id);
        bundle.putString("shop_id", shop_id);
        FragmentChild fragmentChild = new FragmentChild();
        fragmentChild.setArguments(bundle);
        adapter.addFrag(fragmentChild, pagename);
        adapter.notifyDataSetChanged();
        if (adapter.getCount() > 0) tabLayout.setupWithViewPager(viewPager);

        viewPager.setCurrentItem(adapter.getCount() - 1);
        setupTabLayout();
    }

    public void setupTabLayout() {
        selectedTabPosition = viewPager.getCurrentItem();
        for (int i = 0; i < tabLayout.getTabCount(); i++) {
            tabLayout.getTabAt(i).setCustomView(adapter.getTabView(i));
        }
    }
}

public class FragmentChild extends Fragment {
    String childname,shoppe_id;
    RecyclerView imgflag;
    CategoryItemAdapter categoryItemAdapter;
    HttpStack stack;
    List<ShopDetails> cat_item_list;
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_child, container, false);
        Bundle bundle = getArguments();
        childname = bundle.getString("data");
        shoppe_id=bundle.getString("shop_id");
        stack = new HurlStack();
        imgflag=(RecyclerView)view.findViewById(R.id.imgflag);
        cat_item_list = new ArrayList<ShopDetails>();
        categoryItemAdapter = new CategoryItemAdapter(getActivity(),cat_item_list);
        GridLayoutManager layoutManager
                = new GridLayoutManager(getActivity(),1, GridLayoutManager.VERTICAL,false);
        imgflag.setLayoutManager(layoutManager);
        imgflag.setAdapter(categoryItemAdapter);
       getCategoryItem(childname);
        return view;
    }

    public void getCategoryItem(String cat_id)
    {

        stack = new HurlStack(null, createSslSocketFactory());
        final RequestQueue requestQueue = Volley.newRequestQueue(getActivity(),stack);
        String url=config.api_url+"view_cat_item.php?cat_id="+cat_id;
        StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                if(response.equals("0 results"))
                {

                }
                else
                {

                    try {
                        JSONArray jsonArray=new JSONArray(response);
                        for(int i=0;i<jsonArray.length();i++)
                        {
                            JSONObject jsonObject=jsonArray.getJSONObject(i);
                            ShopDetails shopDetails=new ShopDetails();
                            shopDetails.setItem_name(jsonObject.getString("item_name"));
                            shopDetails.setItem_image(jsonObject.getString("image"));
                            shopDetails.setItem_price(jsonObject.getString("price"));
                            shopDetails.setItem_desc(jsonObject.getString("ingredients"));
                            cat_item_list.add(shopDetails);
                        }
                        if(cat_item_list!=null)
                        {

                            categoryItemAdapter.notifyDataSetChanged();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

                Toast.makeText(getActivity(), "Unable to connect. Please check your connection.", Toast.LENGTH_SHORT).show();

            }
        }){
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> params = new HashMap<String, String>();
                params.put("shoppe_id", shoppe_id);
                return params;
            }
        };
        stringRequest.setRetryPolicy(new DefaultRetryPolicy(
                60000,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        stringRequest.setShouldCache(false);
        requestQueue.add(stringRequest);
    }
    private static SSLSocketFactory createSslSocketFactory() {
        TrustManager[] byPassTrustManagers = new TrustManager[]{new X509TrustManager() {
            public X509Certificate[] getAcceptedIssuers() {
                return new X509Certificate[0];
            }

            public void checkClientTrusted(X509Certificate[] chain, String authType) {
            }

            public void checkServerTrusted(X509Certificate[] chain, String authType) {
            }
        }};

        SSLContext sslContext = null;
        SSLSocketFactory sslSocketFactory = null;
        try {
            sslContext = SSLContext.getInstance("TLS");
            sslContext.init(null, byPassTrustManagers, new SecureRandom());
            sslSocketFactory = sslContext.getSocketFactory();

        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
          Log.e(TAG, StringUtils.EMPTY, e);
        } catch (KeyManagementException e) {
           Log.e(TAG, StringUtils.EMPTY, e);
        }
        return sslSocketFactory;
    }
    public final boolean isInternetOn() {
        ConnectivityManager connec = (ConnectivityManager) getActivity().getSystemService(getActivity().getBaseContext().CONNECTIVITY_SERVICE);
        if (connec.getNetworkInfo(0).getState() == android.net.NetworkInfo.State.CONNECTED ||
                connec.getNetworkInfo(0).getState() == android.net.NetworkInfo.State.CONNECTING ||
                connec.getNetworkInfo(1).getState() == android.net.NetworkInfo.State.CONNECTING ||
                connec.getNetworkInfo(1).getState() == android.net.NetworkInfo.State.CONNECTED) {

            return true;
        } else if (
                connec.getNetworkInfo(0).getState() == android.net.NetworkInfo.State.DISCONNECTED ||
                        connec.getNetworkInfo(1).getState() == android.net.NetworkInfo.State.DISCONNECTED) {

            return false;
        }
        return false;
    }
}

Body:
I think it happens because when you switch fragments volley create request again and again. so you can cancel volley request when you leave from fragments by override onStop() method

@Override
public void onStop() {
    super.onStop();
    VolleySingleton.getInstance(getActivity()).getRequestQueue().cancelAll(VolleySingleton.TAG);
}

you can set Tag like this

jsonObjectRequest.setTag(VolleySingleton.TAG);

VolleySingleton.java

public class VolleySingleton {
    private static VolleySingleton mInstance;
    private RequestQueue mRequestQueue;
    private ImageLoader mImageLoader;
    private static Context mCtx;
    public static final String TAG = "tagData";

    private VolleySingleton(Context context) {
        mCtx = context;
        mRequestQueue = getRequestQueue();

        mImageLoader = new ImageLoader(mRequestQueue,
                new ImageLoader.ImageCache() {
                    private final LruCache<String, Bitmap>
                            cache = new LruCache<String, Bitmap>(20);

                    @Override
                    public Bitmap getBitmap(String url) {
                        return cache.get(url);
                    }

                    @Override
                    public void putBitmap(String url, Bitmap bitmap) {
                        cache.put(url, bitmap);
                    }
                });
    }

    public static synchronized VolleySingleton getInstance(Context context) {
        if (mInstance == null) {
            mInstance = new VolleySingleton(context);
        }
        return mInstance;
    }

    public RequestQueue getRequestQueue() {
        if (mRequestQueue == null) {
            // getApplicationContext() is key, it keeps you from leaking the
            // Activity or BroadcastReceiver if someone passes one in.
            mRequestQueue = Volley.newRequestQueue(mCtx.getApplicationContext());
        }
        return mRequestQueue;
    }

    public <T> void addToRequestQueue(Request<T> req) {
        getRequestQueue().add(req);
    }

    public ImageLoader getImageLoader() {
        return mImageLoader;
    }
}


来源: stackexchange

问:
Maven clean failing to delete files
Attempting to configure the maven clean plugin to remove additional directories in my project but it is not working properly. Here is a trivial reproduction using maven 3.5.

Get started with the simple demo app: https://maven.apache.org/guides/getting-started/maven-in-five-minutes.html

Modify the pom.xml to configure maven-clean-plugin:

```<code><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.mycompany.app</groupId>
    <artifactId>my-app</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>
    <name>Maven Quick Start Archetype</name>
    <url>http://maven.apache.org</url>
    <build>
        <plugins>
            <plugin>
                <artifactId>maven-clean-plugin</artifactId>
                <version>3.0.0</version>
                <executions>
                    <execution>
                        <id>auto-clean</id>
                        <phase>clean</phase>
                        <goals>
                            <goal>clean</goal>
                        </goals>
                        <configuration>
                            <verbose>true</verbose>
                            <fieldsets>
                                <fieldset>
                                    <directory>${basedir}</directory>
                                    <includes>
                                        <include>demo/**</include>
                                    </includes>
                                </fieldset>
                            </fieldsets>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.8.2</version>
            <scope>test</scope>
        </dependency>
    </dependencies>
</project>
</code>```

Create a dummy directory called demo

```<code> mkdir demo && touch demo/hello
</code>```

Now run:

```<code> mvn package
 mvn clean
</code>```

You'll notice the demo directory is still present. I do not know why this is. I have read these SO articles:

Remove or delete resource files from target directory using pom file

Maven clean not deleting files

Maven clean not working

and I have tried running different permutations of the goal, phase, and id:

clean

clean:clean

clean:auto-clean

and so on to no avail...

I did a simple sanity check to see what was passed to the mojo:

```<code>[DEBUG] Configuring mojo org.apache.maven.plugins:maven-clean-plugin:3.0.0:clean from plugin realm ClassRealm[plugin>org.apache.maven.plugins:maven-clean-plugin:3.0.0, parent: sun.misc.Launcher$AppClassLoader@55f96302]
[DEBUG] Configuring mojo 'org.apache.maven.plugins:maven-clean-plugin:3.0.0:clean' with basic configurator -->
[DEBUG]   (f) directory = /Users/djthomps/Desktop/test/target
[DEBUG]   (f) excludeDefaultDirectories = false
[DEBUG]   (f) failOnError = true
[DEBUG]   (f) followSymLinks = false
[DEBUG]   (f) outputDirectory = /Users/djthomps/Desktop/test/target/classes
[DEBUG]   (f) reportDirectory = /Users/djthomps/Desktop/test/target/classes
[DEBUG]   (f) retryOnError = true
[DEBUG]   (f) skip = false
[DEBUG]   (f) testOutputDirectory = /Users/djthomps/Desktop/test/target/test-classes
[DEBUG]   (f) verbose = true
[DEBUG] -- end configuration --
</code>```

and it looks like my configuration options are never set. Why?

Note: I have read the plugin documentation as well: https://maven.apache.org/plugins/maven-clean-plugin/examples/delete_additional_files.html. From what I understand what I want to do is possible.

答:
Maybe try using the fileset configuration, instead of fieldset, like this:

```<code><configuration>
    <followSymLinks>false</followSymLinks>
    <filesets>
        <fileset>
            <directory>*all_this_directory*</directory>
        </fileset>
        <fileset>
            <directory>*only_some_of_this_directory*</directory>
            <includes>
                <include>file1_with_wildcard*</include>
                <include>file2</include>
                <!--continue the same...-->
            </includes>
        </fileset>
    </filesets>
</configuration>
</code>```

ContentLicense: CC BY-SA 3.0

Title: Maven clean failing to delete files

Body:
Attempting to configure the maven clean plugin to remove additional directories in my project but it is not working properly. Here is a trivial reproduction using maven 3.5.

Get started with the simple demo app: https://maven.apache.org/guides/getting-started/maven-in-five-minutes.html

Modify the pom.xml to configure maven-clean-plugin:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.mycompany.app</groupId>
    <artifactId>my-app</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>
    <name>Maven Quick Start Archetype</name>
    <url>http://maven.apache.org</url>
    <build>
        <plugins>
            <plugin>
                <artifactId>maven-clean-plugin</artifactId>
                <version>3.0.0</version>
                <executions>
                    <execution>
                        <id>auto-clean</id>
                        <phase>clean</phase>
                        <goals>
                            <goal>clean</goal>
                        </goals>
                        <configuration>
                            <verbose>true</verbose>
                            <fieldsets>
                                <fieldset>
                                    <directory>${basedir}</directory>
                                    <includes>
                                        <include>demo/**</include>
                                    </includes>
                                </fieldset>
                            </fieldsets>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.8.2</version>
            <scope>test</scope>
        </dependency>
    </dependencies>
</project>

Create a dummy directory called demo

 mkdir demo && touch demo/hello

Now run:

 mvn package
 mvn clean

You'll notice the demo directory is still present. I do not know why this is. I have read these SO articles:

Remove or delete resource files from target directory using pom file

Maven clean not deleting files

Maven clean not working

and I have tried running different permutations of the goal, phase, and id:

clean

clean:clean

clean:auto-clean

and so on to no avail...

I did a simple sanity check to see what was passed to the mojo:

[DEBUG] Configuring mojo org.apache.maven.plugins:maven-clean-plugin:3.0.0:clean from plugin realm ClassRealm[plugin>org.apache.maven.plugins:maven-clean-plugin:3.0.0, parent: sun.misc.Launcher$AppClassLoader@55f96302]
[DEBUG] Configuring mojo 'org.apache.maven.plugins:maven-clean-plugin:3.0.0:clean' with basic configurator -->
[DEBUG]   (f) directory = /Users/djthomps/Desktop/test/target
[DEBUG]   (f) excludeDefaultDirectories = false
[DEBUG]   (f) failOnError = true
[DEBUG]   (f) followSymLinks = false
[DEBUG]   (f) outputDirectory = /Users/djthomps/Desktop/test/target/classes
[DEBUG]   (f) reportDirectory = /Users/djthomps/Desktop/test/target/classes
[DEBUG]   (f) retryOnError = true
[DEBUG]   (f) skip = false
[DEBUG]   (f) testOutputDirectory = /Users/djthomps/Desktop/test/target/test-classes
[DEBUG]   (f) verbose = true
[DEBUG] -- end configuration --

and it looks like my configuration options are never set. Why?

Note: I have read the plugin documentation as well: https://maven.apache.org/plugins/maven-clean-plugin/examples/delete_additional_files.html. From what I understand what I want to do is possible.

Body:
Maybe try using the fileset configuration, instead of fieldset, like this:

<configuration>
    <followSymLinks>false</followSymLinks>
    <filesets>
        <fileset>
            <directory>*all_this_directory*</directory>
        </fileset>
        <fileset>
            <directory>*only_some_of_this_directory*</directory>
            <includes>
                <include>file1_with_wildcard*</include>
                <include>file2</include>
                <!--continue the same...-->
            </includes>
        </fileset>
    </filesets>
</configuration>


问:
How to deal with Polish Characters while using regex?
I have street name as KRZYWOŃ ANIELI and so what should be my regex to allow this kind of expression. Currently I have simple one which uses /^[a-zA-Z ]+$/

Kindly advise.

答:
\p{L} catches not only Polish letters, but also Russian for example, may be some other too.

If you, like me, need Polish letters only, take this:

```<code>[AaĄąBbCcĆćDdEeĘęFfGgHhIiJjKkLlŁłMmNnŃńOoÓóPpRrSsŚśTtUuWwYyZzŹźŻż]
</code>```

Characters got from wiki

ContentLicense: CC BY-SA 2.5

Body:
\p{L} catches not only Polish letters, but also Russian for example, may be some other too.

If you, like me, need Polish letters only, take this:

[AaĄąBbCcĆćDdEeĘęFfGgHhIiJjKkLlŁłMmNnŃńOoÓóPpRrSsŚśTtUuWwYyZzŹźŻż]

Characters got from wiki


问:
Yii2 Color of gridview cells, compare date condition
```<code>[
            'attribute' => 'duedate',
            'contentOptions' => function ($model, $key, $index, $column) {
                $time = new \DateTime('now');
                $today = $time->format('Yyyy-mm-dd');
                return ['style' => 'background-color:'
                    . ($model->duedate < $today ? 'red' : 'white')];
            },
        ],
</code>```

I use this code to show if the date is overdue is will has red background color and white if not.

But it all show red. Please help me.

Thank you.

答:
You are getting current date in wrong format,

Just change your code like

```<code>[
     'attribute' => 'duedate',
     'contentOptions' => function ($model, $key, $index, $column) {
       $time = new \DateTime('now');
       $today = $time->format('Y-m-d H:i:s');
       return ['style' => 'background-color:'
                    . (strtotime($model->duedate) < strtotime($today) ? 'red' : 'white')];
     },
],
</code>```

Body:
[
            'attribute' => 'duedate',
            'contentOptions' => function ($model, $key, $index, $column) {
                $time = new \DateTime('now');
                $today = $time->format('Yyyy-mm-dd');
                return ['style' => 'background-color:'
                    . ($model->duedate < $today ? 'red' : 'white')];
            },
        ],

I use this code to show if the date is overdue is will has red background color and white if not.

But it all show red. Please help me.

Thank you.

Body:
You are getting current date in wrong format,

Just change your code like

[
     'attribute' => 'duedate',
     'contentOptions' => function ($model, $key, $index, $column) {
       $time = new \DateTime('now');
       $today = $time->format('Y-m-d H:i:s');
       return ['style' => 'background-color:'
                    . (strtotime($model->duedate) < strtotime($today) ? 'red' : 'white')];
     },
],


问:
Combine multiple row to single row for unique values in multiple column

I am trying to get unique rows based on unique values on multiple columns in SQL Server 2012.

Source Data:

UserId  ---- P1 ---- P2 ------ P3

101  ------- NO ---- NO ------- YES

101  ------- NO ---- YES ------ NO

101  ------- YES ---- NO ------- NO

102 -------- NO ----- NO ------- NO

My source data has 'YES' in single columns for multiple rows.

I'm trying to get the result as follows:

Desired Output:

UserId  ---- P1 ---- P2 ------ P3

101  ------- YES ---- YES ----- YES

102 -------- NO ----- NO ------- NO

Any ideas or code-sample will be greatly appreciated.

答:
In this case (handling only YES and NO values) simple MIN/MAX can solve the task.

```<code>DECLARE @SourceData TABLE
(
    [UserId] INT
   ,[P1] VARCHAR(3)
   ,[P2] VARCHAR(3)
   ,[P3] VARCHAR(3)
);

INSERT INTO @SourceData ([UserId], [P1], [P2], [P3])
VALUES ('101', 'NO', 'NO', 'YES')
      ,('101', 'NO', 'YES', 'NO')
      ,('101', 'YES', 'NO', 'NO')
      ,('102', 'NO', 'NO', 'NO');

SELECT [UserId]
      ,MAX([P1])
      ,MAX([P2])
      ,MAX([P3])
FROM @SourceData
GROUP By [UserId];
</code>```

Body:
In this case (handling only YES and NO values) simple MIN/MAX can solve the task.

DECLARE @SourceData TABLE
(
    [UserId] INT
   ,[P1] VARCHAR(3)
   ,[P2] VARCHAR(3)
   ,[P3] VARCHAR(3)
);

INSERT INTO @SourceData ([UserId], [P1], [P2], [P3])
VALUES ('101', 'NO', 'NO', 'YES')
      ,('101', 'NO', 'YES', 'NO')
      ,('101', 'YES', 'NO', 'NO')
      ,('102', 'NO', 'NO', 'NO');

SELECT [UserId]
      ,MAX([P1])
      ,MAX([P2])
      ,MAX([P3])
FROM @SourceData
GROUP By [UserId];


问:
linux server Creates cache and laravel project gone down
I have stuck in a problem that my laravel project deployed in linux server and server is creating cache in var directory. I run 'yum clean all' command but again creates cache.
I run command php artisan cache:clear, php artisan route:clear but no result.
is there any way to manage server cache?
I face, the error is...

```<code>ErrorException in Filesystem.php line 81:
file_put_contents(): Only 0 of 255 bytes written, possibly out of free disk space
</code>```

my project size is 120 mb.

答:
The one of the possible reason is, if the page size is greater than 4k. The servers usually cache the pages with larger size. The size increases with the data coming from database or excessive use of java script. </p>

<p>And these cache can not be cleared using laravel commands. </p>

Body:
I have stuck in a problem that my laravel project deployed in linux server and server is creating cache in var directory. I run 'yum clean all' command but again creates cache.
I run command php artisan cache:clear, php artisan route:clear but no result.
is there any way to manage server cache?
I face, the error is...

ErrorException in Filesystem.php line 81:
file_put_contents(): Only 0 of 255 bytes written, possibly out of free disk space

my project size is 120 mb.

Body:
The one of the possible reason is, if the page size is greater than 4k. The servers usually cache the pages with larger size. The size increases with the data coming from database or excessive use of java script.

And these cache can not be cleared using laravel commands.


问:
UIDatePicker Click done and display text
I would like to get the date after the UIPicker pop-up and straight away click done button to display the date on "dobTxt.text" without scroll and select the date from UIDatePicker. How to do it?

```<code>   func doneBtnForDate(){

    if (dobTxt.text == "Please select your DOB"){
         //let selectedDate = How to get picker date without scroll it?
         dobTxt.text = selectedDate
    }

    picker.isHidden = true
    toolBar2.isHidden = true
    datePicker.isHidden = true
}
</code>```

答:
Change your doneBtnForDate like below

```<code>func doneBtnForDate(){

    if (dobTxt.text == "Please select your DOB"){
         //let selectedDate = How to get picker date without scroll it?
         dobTxt.text = selectedDate
    }

   // IF you want to change date formatting then you need to change in "DateFormatter" below
   let dateFormatter = DateFormatter()
    dateFormatter.dateStyle = .full
    dateFormatter.timeStyle = .full
    let strDate = dateFormatter.string(from: yourPicker.date)
    dobTxt.text = strDate

    picker.isHidden = true
    toolBar2.isHidden = true
    datePicker.isHidden = true
}
</code>```

Body:
I would like to get the date after the UIPicker pop-up and straight away click done button to display the date on "dobTxt.text" without scroll and select the date from UIDatePicker. How to do it?

   func doneBtnForDate(){

    if (dobTxt.text == "Please select your DOB"){
         //let selectedDate = How to get picker date without scroll it?
         dobTxt.text = selectedDate
    }

    picker.isHidden = true
    toolBar2.isHidden = true
    datePicker.isHidden = true
}

Body:
Change your doneBtnForDate like below

func doneBtnForDate(){

    if (dobTxt.text == "Please select your DOB"){
         //let selectedDate = How to get picker date without scroll it?
         dobTxt.text = selectedDate
    }

   // IF you want to change date formatting then you need to change in "DateFormatter" below
   let dateFormatter = DateFormatter()
    dateFormatter.dateStyle = .full
    dateFormatter.timeStyle = .full
    let strDate = dateFormatter.string(from: yourPicker.date)
    dobTxt.text = strDate

    picker.isHidden = true
    toolBar2.isHidden = true
    datePicker.isHidden = true
}


问:
Select2 dropdown showing sometimes duplicate
I have added approx 10 fields in my view page of select2 dropdown using knockout Js but only few of them being duplicate which is multi select.

Html

```<code><div class="multiselect" data-bind="css: { 'pink-selectbox' : Passengers() == null || Passengers() == '' }">
                            <select class="multipleAccom" data-bind="attr: { name:'['+$index()+'].Passengers' ,id: $index()+'_Passengers' },options: $root.PassengerList,selectedOptions:Passengers, optionsText: 'Text', optionsValue: 'Value',event: {change: $root.CheckPassengerAssignment.bind($data,$index())},valueAllowUnset : true" multiple="multiple"></select></div>
</code>```

JS

```<code> $('.multipleAccom').multiselect({
        includeSelectAllOption: true,
        numberDisplayed: 0,
    });
</code>```

答: It was knockout issue, my DOM is not updating the values that time and select2 pulgin called, after populating data in DOM select2 reinitialized so it's duplicating dropdown.</p>

Body:
I have added approx 10 fields in my view page of select2 dropdown using knockout Js but only few of them being duplicate which is multi select.

Html

                            <select class="multipleAccom" data-bind="attr: { name:'['+$index()+'].Passengers' ,id: $index()+'_Passengers' },options: $root.PassengerList,selectedOptions:Passengers, optionsText: 'Text', optionsValue: 'Value',event: {change: $root.CheckPassengerAssignment.bind($data,$index())},valueAllowUnset : true" multiple="multiple"></select>

JS

 $('.multipleAccom').multiselect({
        includeSelectAllOption: true,
        numberDisplayed: 0,
    });


问:
Property [id] does not exist on this collection instance in laravel 5.5
I am working on purchaseOrder and purchaseOrderDetails database table.

I am saving data to two tables from one form. Here is the appended row table for purchaseOrderrDetails items. Insert data is working fine.

But, now I need to update the tables purchaseOrder and purchaseOrderDetails at a time.

I am trying to get all purchaseOrderDetails data to my form which is using the appended row system. And, I am getting this error:

Property [id] does not exist on this collection instance

What should be the right code please someone helps me? Here are my controller method and edit view bellow-

Purchase_OrderController.php

```<code>   //purchase order update form
public function update($id){
    $suppliers   = Supplier::all();
    $categories = Category::all();

   $purchaseorder_id = $id;
   $purchaseorder= Purchase_Order::where('id', '=', $purchaseorder_id)->get();

   $purchaseorder_details_id = Purchase_Order_Details::pluck('purchase_order_id');
   $purchaseorder_details = Purchase_Order_Details::where('purchase_order_id', '=', $id)->get();
   //$purchaseorder_details = Purchase_Order_Details::with('purchaseorder')->get();

  //dd($purchaseorder_details);

    return view('user/purchaseorder.edit')->with(['purchaseorder' => $purchaseorder, 'purchaseorder_details' => $purchaseorder_details, 'suppliers' => $suppliers, 'categories' => $categories]);
}
</code>```

edit.blade.php

```<code><tbody>
      <?php $item_row = 0; ?>
      @foreach($purchaseorder_details as $pur_detail)
       <tr id="item-row-{{ $item_row }}">
        <td class="text-center" style="vertical-align: middle;">
        <button type="button" onclick="$(\'#item-row-' + item_row + '\').remove();" title="Delete" class="btn btn-xs btn-danger"><i class="fa fa-trash"></i></button>
        </td>
        <td>
        <input value="{{ $pur_detail->code }}" class="form-control typeahead" required="required" placeholder="Item Code" name="item[{{ $item_row }}][code]" type="text" id="item-name-{{ $item_row }}">
        </td>
        <td>
        <input value="{{ $pur_detail->item_name }}" class="form-control" required="required" name="item[{{ $item_row }}][item_name]" type="text" id="item-name-{{ $item_row }}">
        </td>
        <td>
        <select class="form-control" required="required" name="item[{{ $item_row }}][category]" id="item-category-{{ $item_row }}">
       <option selected="selected" value="">Select Category</option>
         @foreach($categories as $category)
          <option value="{{ $category->id }}">{{ $category->name }}</option>
         @endforeach
        </select>
        </td>
        <td>
        <input value="{{ $pur_detail->quantity }}" class="form-control text-right" required="required" name="item[{{ $item_row }}][quantity]" type="text" id="item-quantity-{{ $item_row }}">
        </td>
        <td>
        <input value="{{ $pur_detail->uom }}" class="form-control text-right" required="required" name="item[{{ $item_row }}][uom]" type="text" id="item-uom-{{ $item_row }}">
        </td>
       </tr>
      @endforeach
       <?php $item_row++; ?>
       <tr id="addItem">
         <td class="text-center"><button type="button" onclick="addItem();" title="Add" class="btn btn-xs btn-primary" data-original-title="Add"><i class="fa fa-plus"></i></button></td>
         <td class="text-right" colspan="5"></td>
        </tr>
       </tbody>
</code>```

And first one is - purchaseOrder and second one is purchaseOrderDetails

答:
A Collection is a fancy object wrapper around an array, that is all. A Collection is NOT the things it contains, which is the mistake you are making.

```<code>$array = [
    ['id' => 1, 'name' => 'bob'],
    ['id' => 2, 'name' => 'tom'],
    ...
];
</code>```

You wouldn't do this because you know the indexes you want are not on the array but the arrays inside of it:

```<code>$array['id'];
// but you would do this:
$array[0]['id'];
</code>```

But with a Collection which is just an object around an array, you are doing that exact thing:

```<code>$collection->id;
</code>```

Collections contain items, you want the 'id' from one of those items not the Collection itself as the Collection has no property named 'id'.

```<code>$collection->first()->id;   // id from the first object

foreach ($collection as $item) {
    $item->id;
}

etc ...
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am working on purchaseOrder and purchaseOrderDetails database table.

I am saving data to two tables from one form. Here is the appended row table for purchaseOrderrDetails items. Insert data is working fine.

But, now I need to update the tables purchaseOrder and purchaseOrderDetails at a time.

I am trying to get all purchaseOrderDetails data to my form which is using the appended row system. And, I am getting this error:

Property [id] does not exist on this collection instance

What should be the right code please someone helps me? Here are my controller method and edit view bellow-

Purchase_OrderController.php

   //purchase order update form
public function update($id){
    $suppliers   = Supplier::all();
    $categories = Category::all();

   $purchaseorder_id = $id;
   $purchaseorder= Purchase_Order::where('id', '=', $purchaseorder_id)->get();

   $purchaseorder_details_id = Purchase_Order_Details::pluck('purchase_order_id');
   $purchaseorder_details = Purchase_Order_Details::where('purchase_order_id', '=', $id)->get();
   //$purchaseorder_details = Purchase_Order_Details::with('purchaseorder')->get();

  //dd($purchaseorder_details);

    return view('user/purchaseorder.edit')->with(['purchaseorder' => $purchaseorder, 'purchaseorder_details' => $purchaseorder_details, 'suppliers' => $suppliers, 'categories' => $categories]);
}

edit.blade.php

      <?php $item_row = 0; ?>
      @foreach($purchaseorder_details as $pur_detail)

        <button type="button" onclick="$(\'#item-row-' + item_row + '\').remove();" title="Delete" class="btn btn-xs btn-danger"></button>

        <input value="{{ $pur_detail->code }}" class="form-control typeahead" required="required" placeholder="Item Code" name="item[{{ $item_row }}][code]" type="text" id="item-name-{{ $item_row }}">

        <input value="{{ $pur_detail->item_name }}" class="form-control" required="required" name="item[{{ $item_row }}][item_name]" type="text" id="item-name-{{ $item_row }}">

        <select class="form-control" required="required" name="item[{{ $item_row }}][category]" id="item-category-{{ $item_row }}">
       <option selected="selected" value="">Select Category</option>
         @foreach($categories as $category)
          <option value="{{ $category->id }}">{{ $category->name }}</option>
         @endforeach
        </select>

        <input value="{{ $pur_detail->quantity }}" class="form-control text-right" required="required" name="item[{{ $item_row }}][quantity]" type="text" id="item-quantity-{{ $item_row }}">

        <input value="{{ $pur_detail->uom }}" class="form-control text-right" required="required" name="item[{{ $item_row }}][uom]" type="text" id="item-uom-{{ $item_row }}">

      @endforeach
       <?php $item_row++; ?>

         <button type="button" onclick="addItem();" title="Add" class="btn btn-xs btn-primary" data-original-title="Add"></button>

And first one is - purchaseOrder and second one is purchaseOrderDetails

Body:
A Collection is a fancy object wrapper around an array, that is all. A Collection is NOT the things it contains, which is the mistake you are making.

$array = [
    ['id' => 1, 'name' => 'bob'],
    ['id' => 2, 'name' => 'tom'],
    ...
];

You wouldn't do this because you know the indexes you want are not on the array but the arrays inside of it:

$array['id'];
// but you would do this:
$array[0]['id'];

But with a Collection which is just an object around an array, you are doing that exact thing:

$collection->id;

Collections contain items, you want the 'id' from one of those items not the Collection itself as the Collection has no property named 'id'.

$collection->first()->id;   // id from the first object

foreach ($collection as $item) {
    $item->id;
}

etc ...


问:
Easiest way to send a post request using an array of parameters in PHP?
I'm trying to send a POST request to an URL , I can do this easily in POSTMAN by setting the URL and the parameter array. But I need to send the request in PHP . What is the easiest way to do this ? below is an example parameter array .</p>

```<code> {
   "receiver":"01234567890A=",
   "min_api_version":1,
   "sender":{
      "name":"John McClane",
      "avatar":"http://avatar.example.com"
   },
   "tracking_data":"tracking data",
   "type":"url",
   "media":"http://www.website.com/go_here"
}
</code>```

答:
convert your input into array

then encode your input array to string and then send it using curl request

reference :: http://hayageek.com/php-curl-post-get/

```<code> $params = array(
       "receiver" => "01234567890A=",
       "min_api_version" => 1,
       "sender" => array(
           "name" => "John McClane",
           "avatar"  => "http://avatar.example.com"
       ),
       "tracking_data" => "tracking data",
       "type" => "url",
       "media" => "http://www.website.com/go_here"
    );

    $postData = json_encode($params);

    $ch = curl_init();

    curl_setopt($ch,CURLOPT_URL,$url);
    curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
    curl_setopt($ch,CURLOPT_HEADER, false);
    curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, "data=$postData");

    $output=curl_exec($ch);

    curl_close($ch);
    var_dump($output);
</code>```

Body:
I'm trying to send a POST request to an URL , I can do this easily in POSTMAN by setting the URL and the parameter array. But I need to send the request in PHP . What is the easiest way to do this ? below is an example parameter array .

 {
   "receiver":"01234567890A=",
   "min_api_version":1,
   "sender":{
      "name":"John McClane",
      "avatar":"http://avatar.example.com"
   },
   "tracking_data":"tracking data",
   "type":"url",
   "media":"http://www.website.com/go_here"
}

Body:
convert your input into array

then encode your input array to string and then send it using curl request

reference :: http://hayageek.com/php-curl-post-get/

 $params = array(
       "receiver" => "01234567890A=",
       "min_api_version" => 1,
       "sender" => array(
           "name" => "John McClane",
           "avatar"  => "http://avatar.example.com"
       ),
       "tracking_data" => "tracking data",
       "type" => "url",
       "media" => "http://www.website.com/go_here"
    );

    $postData = json_encode($params);

    $ch = curl_init();

    curl_setopt($ch,CURLOPT_URL,$url);
    curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
    curl_setopt($ch,CURLOPT_HEADER, false);
    curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, "data=$postData");

    $output=curl_exec($ch);

    curl_close($ch);
    var_dump($output);


问:
Programming style of method declaration of get/set method variables in C++?
Should you declare the getters/setters of the class inside the .h file and then define them in .cpp Or do both in .h file. Which style do you prefer and why? I personally like the latter wherein all of them are in .h and only methods which have logic associated with it other than setters/getters in .cpp. </p>

答:
I put put all single-liners in the header as long as they do not require too much additional headers included (because calling methods of other classes).
Also I do not try to put all code in one line so I can put most of the methods in the header :-)

But Josh mentioned a good reason to put them in the .cpp anyway: if the header is for external use.

LastEditorDisplayName: Eddie Parker

OwnerDisplayName: rstevens

LastEditorDisplayName: rstevens


问:
Trouble decoding tiled base64 data with javascript
I'm using tiled to create a tile map.
(Tiled is a tile map editor with support for orthogonal and isometric maps)

It saves the map in an XML file. It can use certain encoding structures:

regular base64

base64 + gzip

base64 + zlib

regular csv

Now, I've completely given up on gzip (my server gzips traffic it anyway, so no loss there)
So I thought I'd try regular base64 decoding, using a base64 jquery plugin

But the data comes out all garbled, like this:

```<code>��������������������������������������������������������
</code>```

I guess it's binary encoding it, but how do I get around that?

Example data that needs to be decoded (regular base64):

```<code>jQAAAI4AAACPAAAAkAAAAJEAAACSAAAAkwAAAKEAAACiAAAAowAAAKQAAAClAAAApgAAAKcAAAA=
</code>```

Example data that needs to be decoded (gzipped base64):

```<code>H4sIAAAAAAAACw3DhwnAMAwAMP8P2Rdk9s1KoBQR2WK12R1Ol9vj9fn5A/luZ4Y4AAAA
</code>```

Example data as csv:

```<code>141,142,143,144,145,146,147,
161,162,163,164,165,166,167
</code>```

So how can I turn the regular base64 encoded bit and turn it into the csv?

Edit:

Using the solution Pointy found I got a semi-correct array.
After a few thousand characters the 2 numbers would be wrong again, though. And even more frequent after that.

I then found someone who also uses tiled and the base64 encoding in his scheme.
After he decoded the array, he also did this to it:

```<code>        var d = base64_decode($(this).find('data').text());
    var e = new Array();
    for (var i = 0; i <= d.length; i += 4) {
    var f = d[i] | d[i + 1] << 8 | d[i + 2] << 16 | d[i + 3] << 24;
    e.push(f)
    }
</code>```

I have no idea why this is needed, but at least it works.
If anyone could explain, please do!

答: old topic, I know, but the answer for your last question is here: http://sourceforge.net/apps/mediawiki/tiled/index.php?title=Examining_the_map_format.</p>

Body:
I'm using tiled to create a tile map.
(Tiled is a tile map editor with support for orthogonal and isometric maps)

It saves the map in an XML file. It can use certain encoding structures:

regular base64

base64 + gzip

base64 + zlib

regular csv

Now, I've completely given up on gzip (my server gzips traffic it anyway, so no loss there)
So I thought I'd try regular base64 decoding, using a base64 jquery plugin

But the data comes out all garbled, like this:

��������������������������������������������������������

I guess it's binary encoding it, but how do I get around that?

Example data that needs to be decoded (regular base64):

jQAAAI4AAACPAAAAkAAAAJEAAACSAAAAkwAAAKEAAACiAAAAowAAAKQAAAClAAAApgAAAKcAAAA=

Example data that needs to be decoded (gzipped base64):

H4sIAAAAAAAACw3DhwnAMAwAMP8P2Rdk9s1KoBQR2WK12R1Ol9vj9fn5A/luZ4Y4AAAA

Example data as csv:

141,142,143,144,145,146,147,
161,162,163,164,165,166,167

So how can I turn the regular base64 encoded bit and turn it into the csv?

Edit:

Using the solution Pointy found I got a semi-correct array.
After a few thousand characters the 2 numbers would be wrong again, though. And even more frequent after that.

I then found someone who also uses tiled and the base64 encoding in his scheme.
After he decoded the array, he also did this to it:

        var d = base64_decode($(this).find('data').text());
    var e = new Array();
    for (var i = 0; i <= d.length; i += 4) {
    var f = d[i] | d[i + 1] << 8 | d[i + 2] << 16 | d[i + 3] << 24;
    e.push(f)
    }

I have no idea why this is needed, but at least it works.
If anyone could explain, please do!


问:
Something wrong with my Invert tree or BFS traverse?
I had already attached two tree to test, but the answer below is weird.
Input are two trees and to check if they are inverted version. So i wrote a invert function and a BFS traverse to store the tree node into a String, through comparing the two string to check if they are inverted version.

The first tree is
5
15
14
9
6
3
1
The second tree is:
5
15
14
9
6
3
1
5
14
15
3
6
9
1
No, not mirror imagines

Process finished with exit code 0

public class CheckMirrorTree{

```<code>public static void main(String[] args) {

    // add the first tree
    TreeNode root = new TreeNode(5);
    root.left = new TreeNode(15);
    root.right = new TreeNode(14);
    TreeNode rightChild = root.right;
    TreeNode leftChild = root.left;
    rightChild.left = new TreeNode(3);
    rightChild.left.right = new TreeNode(1);
    leftChild.right = new TreeNode(6);
    leftChild.left = new TreeNode(9);
    System.out.println("The first tree is");
    String root1 = traverse(root);

    // add the second tree
    System.out.println("The second tree is:");
    TreeNode secondRoot = new TreeNode(5);
    secondRoot.right = new TreeNode(15);
    secondRoot.left = new TreeNode(14);
    TreeNode secondRightChild = secondRoot.right;
    TreeNode secondLeftChild = secondRoot.left;
    secondRightChild.left = new TreeNode(6);
    secondRightChild.right = new TreeNode(9);
    secondLeftChild.right = new TreeNode(3);
    secondLeftChild.right.left = new TreeNode(1);
    String root2 = traverse(secondRoot);

    if (root1 == root2){
        System.out.println("Yes, mirror images");
    }else {
        System.out.println("No, not mirror imagines");
    }
}

static Deque<TreeNode> queue = new ArrayDeque();
static List<Integer> result = new LinkedList();
static Deque<TreeNode> invertQueue = new ArrayDeque();

static private TreeNode invertTree(TreeNode root) {
    invertQueue.add(root);
    TreeNode reserve = root;
    while (!invertQueue.isEmpty()) {
        if (root.left != null || root.right != null) {
            invertQueue.poll();
            TreeNode temp = root.right;
            root.right = root.left;
            root.left = temp;
            if (root.left != null)
                invertQueue.add(root.left);
            if (root.right != null)
                invertQueue.add(root.right);
        }
        root = invertQueue.poll();
    }

    return reserve;
}

static private String traverse (TreeNode root){ // Each child of a tree is a root of its subtree.
    queue.add(root);
    helper(root);
    // print out the tree
    String res = "";
    for (int i : result) {
        System.out.println(i);
        res += i;
    }
    return res;
}

static private void helper(TreeNode root) {

    while (!queue.isEmpty()) {
        if(root.left != null || root.right != null) {
            TreeNode temp = queue.poll();
            result.add(temp.val);
            if (root.left != null)
                queue.add(root.left);
            if (root.right != null)
                queue.add(root.right);
            helper(queue.peek());
        }
        // deal with the ending nodes
        if (root.left == null && root.right == null) {
            if (queue.size() == 0) {
                result.add(root.val);
                return;
            }
            result.add(queue.poll().val);
            root = queue.peek();
        }
    }
}
</code>```

}

答:
```<code>root1 == root2
</code>```

is not how you check if two strings are equal. Try:

```<code>root1.equals(root2);
</code>```

Then your if statement should be entered and something will be printed.
Since nothing else is getting printed I would suggest posting the traverse method since that's probably where the program is exiting early.

Body:
I had already attached two tree to test, but the answer below is weird.
Input are two trees and to check if they are inverted version. So i wrote a invert function and a BFS traverse to store the tree node into a String, through comparing the two string to check if they are inverted version.

The first tree is
5
15
14
9
6
3
1
The second tree is:
5
15
14
9
6
3
1
5
14
15
3
6
9
1
No, not mirror imagines

Process finished with exit code 0

public class CheckMirrorTree{

public static void main(String[] args) {

    // add the first tree
    TreeNode root = new TreeNode(5);
    root.left = new TreeNode(15);
    root.right = new TreeNode(14);
    TreeNode rightChild = root.right;
    TreeNode leftChild = root.left;
    rightChild.left = new TreeNode(3);
    rightChild.left.right = new TreeNode(1);
    leftChild.right = new TreeNode(6);
    leftChild.left = new TreeNode(9);
    System.out.println("The first tree is");
    String root1 = traverse(root);

    // add the second tree
    System.out.println("The second tree is:");
    TreeNode secondRoot = new TreeNode(5);
    secondRoot.right = new TreeNode(15);
    secondRoot.left = new TreeNode(14);
    TreeNode secondRightChild = secondRoot.right;
    TreeNode secondLeftChild = secondRoot.left;
    secondRightChild.left = new TreeNode(6);
    secondRightChild.right = new TreeNode(9);
    secondLeftChild.right = new TreeNode(3);
    secondLeftChild.right.left = new TreeNode(1);
    String root2 = traverse(secondRoot);

    if (root1 == root2){
        System.out.println("Yes, mirror images");
    }else {
        System.out.println("No, not mirror imagines");
    }
}

static Deque<TreeNode> queue = new ArrayDeque();
static List<Integer> result = new LinkedList();
static Deque<TreeNode> invertQueue = new ArrayDeque();

static private TreeNode invertTree(TreeNode root) {
    invertQueue.add(root);
    TreeNode reserve = root;
    while (!invertQueue.isEmpty()) {
        if (root.left != null || root.right != null) {
            invertQueue.poll();
            TreeNode temp = root.right;
            root.right = root.left;
            root.left = temp;
            if (root.left != null)
                invertQueue.add(root.left);
            if (root.right != null)
                invertQueue.add(root.right);
        }
        root = invertQueue.poll();
    }

    return reserve;
}

static private String traverse (TreeNode root){ // Each child of a tree is a root of its subtree.
    queue.add(root);
    helper(root);
    // print out the tree
    String res = "";
    for (int i : result) {
        System.out.println(i);
        res += i;
    }
    return res;
}

static private void helper(TreeNode root) {

    while (!queue.isEmpty()) {
        if(root.left != null || root.right != null) {
            TreeNode temp = queue.poll();
            result.add(temp.val);
            if (root.left != null)
                queue.add(root.left);
            if (root.right != null)
                queue.add(root.right);
            helper(queue.peek());
        }
        // deal with the ending nodes
        if (root.left == null && root.right == null) {
            if (queue.size() == 0) {
                result.add(root.val);
                return;
            }
            result.add(queue.poll().val);
            root = queue.peek();
        }
    }
}

}

Body:
root1 == root2

is not how you check if two strings are equal. Try:

root1.equals(root2);

Then your if statement should be entered and something will be printed.
Since nothing else is getting printed I would suggest posting the traverse method since that's probably where the program is exiting early.


问:
How to get location of Image from PHPhotoLibrary?
Since ALAssetLibrary Api is deprecated we are using PHPhotoLibrary to save images to PhotoAlbum

If we use ALAssetLibrary,we can able to get assetUri of the saved image, but we cannot able to get the same if we use PHPhotoLibrary .

Example For assetUri-

/Library/Developer/CoreSimulator/Devices/1ABD9386-B868-4B8D-9670-3F260D574569/data/Media/DCIM/100APPLE/

Is there another way to get the same path as mentioned above using PHPhotoLibrary?

Thanks in Advance

答:
AssetUri  is not available with PHPhotoLibrary .

We can use request.PlaceholderForCreatedAsset.LocalIdentifier instead.

```<code>UIImagePickerController controller = new UIImagePickerController {
      SourceType = UIImagePickerControllerSourceType.SavedPhotosAlbum,
      ImagePickerControllerDelegate = new PickerDelegate(),
      MediaTypes = new string[] { UTType.Image }
};
this.PresentViewController(controller, true, null);

public class PickerDelegate: UIImagePickerControllerDelegate
{
    public override void FinishedPickingImage(UIImagePickerController picker, UIImage image, NSDictionary editingInfo)
    {
        PHPhotoLibrary.SharedPhotoLibrary.PerformChanges(
            () => {
                PHAssetChangeRequest request = PHAssetChangeRequest.FromImage(image);
                string id = request.PlaceholderForCreatedAsset.LocalIdentifier;
            },
            (bool success, NSError error) => {
            }
        );
    }
}
</code>```

Refer to

How to get the URL of an image just added in PHPhotoLibrary

Get URL of a newly created asset, iOS 9 style

Body:
AssetUri  is not available with PHPhotoLibrary .

We can use request.PlaceholderForCreatedAsset.LocalIdentifier instead.

UIImagePickerController controller = new UIImagePickerController {
      SourceType = UIImagePickerControllerSourceType.SavedPhotosAlbum,
      ImagePickerControllerDelegate = new PickerDelegate(),
      MediaTypes = new string[] { UTType.Image }
};
this.PresentViewController(controller, true, null);

public class PickerDelegate: UIImagePickerControllerDelegate
{
    public override void FinishedPickingImage(UIImagePickerController picker, UIImage image, NSDictionary editingInfo)
    {
        PHPhotoLibrary.SharedPhotoLibrary.PerformChanges(
            () => {
                PHAssetChangeRequest request = PHAssetChangeRequest.FromImage(image);
                string id = request.PlaceholderForCreatedAsset.LocalIdentifier;
            },
            (bool success, NSError error) => {
            }
        );
    }
}

Refer to

How to get the URL of an image just added in PHPhotoLibrary

Get URL of a newly created asset, iOS 9 style


问:
Send string array from an activity in android
I have a quiz application I am working on whereby the questions, answers and options are embedded in the application with a timer. I also have two other activities: one for showing the user his current score and the other to review the answered questions once there is a timeout.
I intend to send the questions and answers the user has tried before the timer was over into my review activity for review.
For example, since I have 10 questions in my application, and the user was able to try 5 out of them before the time elapsed, I need to get those 5 questions into my Review Activity for review.

QuestionLibrary.Java

```<code>// This file contains questions from QuestionBank
class QuestionLibrary {
    // array of questions
    private String mQuestions [] = {
          // Question goes here
   };
    // array of multiple choices for each question
    private String mChoices [][] = {
           // question choices goes here
    };

    // array of correct answers - in the same order as array of questions
private String mCorrectAnswers[] = {
         // answers appear here
};

    // method returns number of questions
    int getLength(){
        return mQuestions.length;
    }

    // method returns question from array textQuestions[] based on array index
    String getQuestion(int a) {
        return mQuestions[a];
    }

    // method returns a single multiple choice item for question-based on array index,
    // based on number of multiple choice item in the list - 1, 2, 3 or 4 as an argument
    String getChoice(int index, int num) {
        return mChoices[index][num-1];
    }

    //  method returns correct answer for the question based on array index
    String getCorrectAnswer(int a) {
        return mCorrectAnswers[a];
    }

}
</code>```

MainActivity.java

```<code>public class MainActivity extends AppCompatActivity {
    private QuestionLibrary mQuestionLibrary = new QuestionLibrary();
    Button button1;
    Button button2;
    Button button3;
    Button button4;
    TextView msingleQuestion;
    TextView mQuestion; //current question to answer
    TextView timer;
   MainActivity.CounterClass count_timer;   //countdown timer class
    private int mQuestionNumber = 0; // current question number
    private String mAnswer;  // correct answer for question in mQuestionView
    private int mquizNumber = 1;
    private long resume_timer;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // set textViews here
        // Setting countdown timer
        timer = (TextView) findViewById(R.id.timer);
        timer.setText("00:5:00");
        // start timer here
        count_timer = new MainActivity.CounterClass(300000, 1000);
        count_timer.start();
        updateQuizNumber(mquizNumber);

    }

    private void updateQuizNumber(int mquizNumber) {
        msingleQuestion.setText("" + mquizNumber+"/"+mQuestionLibrary.getLength());
    }

    private void updateQuestion() {
        // check if we are not outside array bounds for questions
        if(mQuestionNumber<mQuestionLibrary.getLength() ){
            // set text for hint and click_me
            mClickMe.setText(mQuestionLibrary.getTextHint(mQuestionNumber));
            // set the text for new question, and new 4 alternative to answer on four buttons
            mQuestion.setText(mQuestionLibrary.getQuestion(mQuestionNumber));
            button1.setText(mQuestionLibrary.getChoice(mQuestionNumber, 1));
            button2.setText(mQuestionLibrary.getChoice(mQuestionNumber, 2));
            button3.setText(mQuestionLibrary.getChoice(mQuestionNumber, 3));
            button4.setText(mQuestionLibrary.getChoice(mQuestionNumber,4));
            mAnswer = mQuestionLibrary.getCorrectAnswer(mQuestionNumber);
            mQuestionNumber++;
        }
        else {
            Toast.makeText(BeginnerActivity.this, "That was the last question!", Toast.LENGTH_SHORT).show();
       startActivity(intent);
        }
    }

    public void onClick(View view) {
        //all logic for all answers buttons in one method

        if (mQuestionNumber < mQuestionLibrary.getLength()) {
            // once user answer the question, we move on to the next one, if any
                    updateQuestion();
                    mquizNumber++;
                    updateQuizNumber(mquizNumber);
                }

            }, 1000);

        } else {
            Handler handler = new Handler();
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    Intent intent = new Intent(MainActivity.this, ResultsActivity.class);
                    finish();
                    count_timer.cancel();
                }

            }, 1000);

        }

    @Override
    protected void onRestart() {
        //resume timer when user comes back to the app
        count_timer = new BeginnerActivity.CounterClass(resume_timer, 1000);
        count_timer.start();
        super.onRestart();
    }
}
</code>```

How do I get the tried questions from my Main Activity into another Activity for a proper review?

答:
You can use below code to send String array via intent

```<code>Bundle b=new Bundle();
b.putStringArray(key, stringArrayReference);
Intent i=new Intent(context, Class);
i.putExtras(b);
</code>```

In order to get the String array in other Activity you can use below code

```<code>Bundle b=this.getIntent().getExtras();
String[] array=b.getStringArray(key);
</code>```

Hope that helps

Body:
I have a quiz application I am working on whereby the questions, answers and options are embedded in the application with a timer. I also have two other activities: one for showing the user his current score and the other to review the answered questions once there is a timeout.
I intend to send the questions and answers the user has tried before the timer was over into my review activity for review.
For example, since I have 10 questions in my application, and the user was able to try 5 out of them before the time elapsed, I need to get those 5 questions into my Review Activity for review.

QuestionLibrary.Java

// This file contains questions from QuestionBank
class QuestionLibrary {
    // array of questions
    private String mQuestions [] = {
          // Question goes here
   };
    // array of multiple choices for each question
    private String mChoices [][] = {
           // question choices goes here
    };

    // array of correct answers - in the same order as array of questions
private String mCorrectAnswers[] = {
         // answers appear here
};

    // method returns number of questions
    int getLength(){
        return mQuestions.length;
    }

    // method returns question from array textQuestions[] based on array index
    String getQuestion(int a) {
        return mQuestions[a];
    }

    // method returns a single multiple choice item for question-based on array index,
    // based on number of multiple choice item in the list - 1, 2, 3 or 4 as an argument
    String getChoice(int index, int num) {
        return mChoices[index][num-1];
    }

    //  method returns correct answer for the question based on array index
    String getCorrectAnswer(int a) {
        return mCorrectAnswers[a];
    }

}

MainActivity.java

public class MainActivity extends AppCompatActivity {
    private QuestionLibrary mQuestionLibrary = new QuestionLibrary();
    Button button1;
    Button button2;
    Button button3;
    Button button4;
    TextView msingleQuestion;
    TextView mQuestion; //current question to answer
    TextView timer;
   MainActivity.CounterClass count_timer;   //countdown timer class
    private int mQuestionNumber = 0; // current question number
    private String mAnswer;  // correct answer for question in mQuestionView
    private int mquizNumber = 1;
    private long resume_timer;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // set textViews here
        // Setting countdown timer
        timer = (TextView) findViewById(R.id.timer);
        timer.setText("00:5:00");
        // start timer here
        count_timer = new MainActivity.CounterClass(300000, 1000);
        count_timer.start();
        updateQuizNumber(mquizNumber);

    }

    private void updateQuizNumber(int mquizNumber) {
        msingleQuestion.setText("" + mquizNumber+"/"+mQuestionLibrary.getLength());
    }

    private void updateQuestion() {
        // check if we are not outside array bounds for questions
        if(mQuestionNumber<mQuestionLibrary.getLength() ){
            // set text for hint and click_me
            mClickMe.setText(mQuestionLibrary.getTextHint(mQuestionNumber));
            // set the text for new question, and new 4 alternative to answer on four buttons
            mQuestion.setText(mQuestionLibrary.getQuestion(mQuestionNumber));
            button1.setText(mQuestionLibrary.getChoice(mQuestionNumber, 1));
            button2.setText(mQuestionLibrary.getChoice(mQuestionNumber, 2));
            button3.setText(mQuestionLibrary.getChoice(mQuestionNumber, 3));
            button4.setText(mQuestionLibrary.getChoice(mQuestionNumber,4));
            mAnswer = mQuestionLibrary.getCorrectAnswer(mQuestionNumber);
            mQuestionNumber++;
        }
        else {
            Toast.makeText(BeginnerActivity.this, "That was the last question!", Toast.LENGTH_SHORT).show();
       startActivity(intent);
        }
    }

    public void onClick(View view) {
        //all logic for all answers buttons in one method

        if (mQuestionNumber < mQuestionLibrary.getLength()) {
            // once user answer the question, we move on to the next one, if any
                    updateQuestion();
                    mquizNumber++;
                    updateQuizNumber(mquizNumber);
                }

            }, 1000);

        } else {
            Handler handler = new Handler();
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    Intent intent = new Intent(MainActivity.this, ResultsActivity.class);
                    finish();
                    count_timer.cancel();
                }

            }, 1000);

        }

    @Override
    protected void onRestart() {
        //resume timer when user comes back to the app
        count_timer = new BeginnerActivity.CounterClass(resume_timer, 1000);
        count_timer.start();
        super.onRestart();
    }
}

How do I get the tried questions from my Main Activity into another Activity for a proper review?

Body:
You can use below code to send String array via intent

Bundle b=new Bundle();
b.putStringArray(key, stringArrayReference);
Intent i=new Intent(context, Class);
i.putExtras(b);

In order to get the String array in other Activity you can use below code

Bundle b=this.getIntent().getExtras();
String[] array=b.getStringArray(key);

Hope that helps


问:
Unable to connect to Microsoft SSRS 2012 via SSMS or Report Server/Report Manager
I have installed Microsoft SQL Server Developer Edition in my local machine for my own development use with a Windows Authentication. I have been able to connect to DB Engine, SSAS (Multidimensional Model) Engine, SSIS Engine, SSAS (Tabular Model Engine using another instance).

I was able to connect to SSRS engine (Native Mode) a few weeks earlier. Recently I installed CheckPoint SSL VPN to access our client Remote Desktop. After this installation, whenever I connect to SSRS either using SSMS or Report Server or Report Manager, even though the SSRS Services is running (I have been able to verify from SQL Server Configuration Manager as well as Reporting Services Configuration Manager). I even tried to add the SSRS Report Server link in the SSMS for the SSRS Engine, but still not successful.

I get the following:

TITLE: Connect to Server

Cannot connect to LAPTOPNAME\SQL2012DEV.

ADDITIONAL INFORMATION:

Unable to connect to the server at LAPTOPNAME\SQL2012DEV. The specified URL might not be valid or there might be a problem with the report server version or configuration. Specify a different URL, or contact your
server administrator to verify that the report server runs SQL Server 2008 or later. Additionally, if you are trying to connect to a SharePoint-integrated report server, verify that SharePoint is installed on the server
 and that the report server uses SharePoint integrated mode. (Microsoft.SqlServer.Management.UI.RSClient)

BUTTONS:

OK

Could this be due to some permission issues ? I have restarted the SSRS services many times, though it is running, I am not able to connect. Should some Admin privileges be given to my Windows account ? If so, can you guide me how ?

Information from SQL Server Configuration Manager (for SSRS service):
Log on As: NT Service\ReportServer$SQL2012DEV

Information from Reporting Serivces Configuration Manager:
Service Account is built-in:  ReportServer$SQL2012DEV

Should I change built-in account to Local Service, Network Service, Local System ?

答: Open "Reporting Services Configuration Manager" in "Web Service URL" OR "Web Portal URL" tab check your IP and Port access & use the link in URLs to be sure. I think your new application changed this settings.</p>


问:
How to access adapter class textview in fragment
This is my adapter class

```<code>public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.MyHolder> {

List<ListData> listData;

public RecyclerViewAdapter(List<ListData> listData) {
    this.listData = listData;
}

@Override
public MyHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.card_view, parent, false);

    return new MyHolder(view);
}

public void onBindViewHolder(MyHolder holder, int position) {
    ListData data = listData.get(position);
    holder.name.setText(data.getName());
    holder.message.setText(data.getMessage());
}

@Override
public int getItemCount() {
    return listData.size();
}

class MyHolder extends RecyclerView.ViewHolder {
    TextView message, name, badge;

    public MyHolder(View itemView) {
        super(itemView);
        name = itemView.findViewById(R.id.tv_email);
        message = itemView.findViewById(R.id.tv_message);
        badge = itemView.findViewById(R.id.badge);

    }
}
</code>```

This is my Fragment class.

```<code>public View onCreateView(LayoutInflater inflater, ViewGroup group, Bundle b) {
    View view = inflater.inflate(R.layout.fragment_chats, group, false);
    recyclerview = view.findViewById(R.id.rview);
    badge = view.findViewById(R.id.badge);
    database = FirebaseDatabase.getInstance();
    myRef = database.getReference("message");
    hashMap = new HashMap<>();
    myRef.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            list = new ArrayList<>();

            for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) {

                UserDetails userdetails = dataSnapshot1.getValue(UserDetails.class);
                String name = userdetails.getName();
                String nameCaps = name.substring(0, 1).toUpperCase() + name.substring(1);
                String message = userdetails.getMessage();

                if (hashMap.containsKey(name)) {
                    if (!hashMap.get(name).equalsIgnoreCase(message))
                       hashMap.remove(name);
                        hashMap.put(nameCaps, message);
                    }
                } else
                    hashMap.put(nameCaps, message)
            }
            list = convertHashToObjectList(hashMap);
            RecyclerViewAdapter recycler = new RecyclerViewAdapter(list);
            RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getContext());
            recyclerview.setLayoutManager(layoutManager);
            recyclerview.setItemAnimator(new DefaultItemAnimator());
            recyclerview.setAdapter(recycler);
        }
        @Override
        public void onCancelled(DatabaseError error) {

        }
    });
    return view;
}
</code>```

private ArrayListconvertHashToObjectList(HashMap hashMap) {

```<code>    ArrayList<ListData> listData = new ArrayList<>();
    for (Map.Entry<String, String> entry : hashMap.entrySet()) {
        listData.add(new ListData(entry.getKey(), entry.getValue()));
    }
 return listData;
}
</code>```

I want to use the textview badge in fragment class. How to access the adapter class textview in fragment class. When i instantiated the textview in Fragment class it shows the error null object reference.

答:
Here is code for same:

```<code>  for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) {

                UserDetails userdetails = dataSnapshot1.getValue(UserDetails.class);
                String name = userdetails.getName();
                String nameCaps = name.substring(0, 1).toUpperCase() + name.substring(1);
                String message = userdetails.getMessage();

                if (!updateMessage.containsKey(nameCaps)) {

                    updateMessage.put(nameCaps,false);
                }
                if (hashMap.containsKey(name)) {
                    if (!hashMap.get(name).equalsIgnoreCase(message)) {

                        hashMap.remove(name);
                        hashMap.put(nameCaps, message);
                      updateMessage.put(nameCaps,true);

                    }
                } else
                    hashMap.put(nameCaps, message);

            }
            list = convertHashToObjectList(hashMap);

            RecyclerViewAdapter recycler = new RecyclerViewAdapter(list,updateMessage);
</code>```

"updatemessage" is a hashmap which holds the changes in message.

Body:
This is my adapter class

public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.MyHolder> {

List<ListData> listData;

public RecyclerViewAdapter(List<ListData> listData) {
    this.listData = listData;
}

@Override
public MyHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.card_view, parent, false);

    return new MyHolder(view);
}

public void onBindViewHolder(MyHolder holder, int position) {
    ListData data = listData.get(position);
    holder.name.setText(data.getName());
    holder.message.setText(data.getMessage());
}

@Override
public int getItemCount() {
    return listData.size();
}

class MyHolder extends RecyclerView.ViewHolder {
    TextView message, name, badge;

    public MyHolder(View itemView) {
        super(itemView);
        name = itemView.findViewById(R.id.tv_email);
        message = itemView.findViewById(R.id.tv_message);
        badge = itemView.findViewById(R.id.badge);

    }
}

This is my Fragment class.

public View onCreateView(LayoutInflater inflater, ViewGroup group, Bundle b) {
    View view = inflater.inflate(R.layout.fragment_chats, group, false);
    recyclerview = view.findViewById(R.id.rview);
    badge = view.findViewById(R.id.badge);
    database = FirebaseDatabase.getInstance();
    myRef = database.getReference("message");
    hashMap = new HashMap<>();
    myRef.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            list = new ArrayList<>();

            for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) {

                UserDetails userdetails = dataSnapshot1.getValue(UserDetails.class);
                String name = userdetails.getName();
                String nameCaps = name.substring(0, 1).toUpperCase() + name.substring(1);
                String message = userdetails.getMessage();

                if (hashMap.containsKey(name)) {
                    if (!hashMap.get(name).equalsIgnoreCase(message))
                       hashMap.remove(name);
                        hashMap.put(nameCaps, message);
                    }
                } else
                    hashMap.put(nameCaps, message)
            }
            list = convertHashToObjectList(hashMap);
            RecyclerViewAdapter recycler = new RecyclerViewAdapter(list);
            RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getContext());
            recyclerview.setLayoutManager(layoutManager);
            recyclerview.setItemAnimator(new DefaultItemAnimator());
            recyclerview.setAdapter(recycler);
        }
        @Override
        public void onCancelled(DatabaseError error) {

        }
    });
    return view;
}

private ArrayListconvertHashToObjectList(HashMap hashMap) {

    ArrayList<ListData> listData = new ArrayList<>();
    for (Map.Entry<String, String> entry : hashMap.entrySet()) {
        listData.add(new ListData(entry.getKey(), entry.getValue()));
    }
 return listData;
}

I want to use the textview badge in fragment class. How to access the adapter class textview in fragment class. When i instantiated the textview in Fragment class it shows the error null object reference.

Body:
Here is code for same:

  for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) {

                UserDetails userdetails = dataSnapshot1.getValue(UserDetails.class);
                String name = userdetails.getName();
                String nameCaps = name.substring(0, 1).toUpperCase() + name.substring(1);
                String message = userdetails.getMessage();

                if (!updateMessage.containsKey(nameCaps)) {

                    updateMessage.put(nameCaps,false);
                }
                if (hashMap.containsKey(name)) {
                    if (!hashMap.get(name).equalsIgnoreCase(message)) {

                        hashMap.remove(name);
                        hashMap.put(nameCaps, message);
                      updateMessage.put(nameCaps,true);

                    }
                } else
                    hashMap.put(nameCaps, message);

            }
            list = convertHashToObjectList(hashMap);

            RecyclerViewAdapter recycler = new RecyclerViewAdapter(list,updateMessage);

"updatemessage" is a hashmap which holds the changes in message.


问:
Array of strings: Segmentation fault(core dumped)
I'm trying to write a code that sorts an array of strings in alphabetical or reverse alphabetical order, depending on the command line argument given.

"-o a" for alphabetic.

"-o r" for reverse.

This is my code so far.

```<code>#include<stdio.h>
#include<string.h>

int string_compare(char *str1,char *str2){
    int ret;

    ret=strcmp(str1,str2);

    if(ret < 0) {
      return 0;
    }
    else if(ret > 0) {
      return 1;
    }
    else {
      return -1;
    }
}

void swap(char *str1, char *str2)
{
  char *temp = str1;
  str1 = str2;
  str2 = temp;
}

int main(int argc,char *argv[]){
    char *planets[9]={"Mercury","Venus","Earth","Mars","Jupiter","Saturn","Uranus","Neptune","Pluto"};
    int i,j;
    int a_ret=strcmp(argv[2],"a");
    int r_ret=strcmp(argv[2],"r");
    int cmp;

    for(i=0;i=8;i++){
        for(j=8;j=(i+1);j--){
            cmp=string_compare(planets[j],planets[j-1]);
            if(a_ret==0){
                if(cmp==0){
                    swap(planets[j],planets[j-1]);
                }
            }
            else if(r_ret==0){
                if(cmp==1){
                    swap(planets[j],planets[j-1]);
                }
            }
        }
    }
    printf("%s",planets[0]);
   return 0;
}
</code>```

The program is supposed to work something like this:

```<code>./planets –o a
The planets in alphabetical order are: Earth, Jupiter, Mars, Mercury, Neptune, Pluto, Saturn, Uranus, Venus
</code>```

or this:

```<code>./planets –o r
The planets in reverse alphabetical order are: Venus, Uranus, Saturn, Pluto, Neptune, Mercury, Mars, Jupiter, Earth
</code>```

The program compiles without error, but when I run it I get

```<code>Segmentation fault(core dumped)
</code>```

I'm new to C, and I don't quite fully understand how to manipulate the memory allocation. Any help or advice is much appreciated.

答:
In for loop you have used = operator instead of <= or >=.

NOTE: There are other logical errors also.

UPDATED:

You can use following code:

```<code>#include<stdio.h>
#include<string.h>
#define MAX_SIZE 9

void swap(char **str1, char **str2)
{
  char *temp = *str1;
  *str1 = *str2;
  *str2 = temp;
}

int main(int argc,char *argv[]){
    char *planets[MAX_SIZE]=    {"Mercury","Venus","Earth","Mars","Jupiter","Saturn","Uranus","Neptune","Pluto"};
    int i, j, cmp, minMax;

    //If we don't need an array sorted in accending order then it is obvious that
    //we need it to be sorted in decending order
    int a_ret= (strcmp(argv[2],"a") == 0);

    for(i=0;i<MAX_SIZE;i++){
        minMax = i;
        for(j=i+1;j<MAX_SIZE;j++){
            cmp=strcmp(planets[j],planets[minMax]);
            if(((a_ret==0) && (cmp>0)) || ((a_ret==1) && (cmp<0))){
                    minMax =j;
            }
        }

        //Swap only if required
        if(i != minMax)
           swap(&planets[i], &planets[minMax]);
    }

    //Print the sorted array
    for(i=0;i<MAX_SIZE;i++)
        printf("%s | ",planets[i]);
   return 0;
}
</code>```

You can see working code here(Command line argument are nor provided due to online IDE restriction).

Body:
I'm trying to write a code that sorts an array of strings in alphabetical or reverse alphabetical order, depending on the command line argument given.

"-o a" for alphabetic.

"-o r" for reverse.

This is my code so far.

#include<stdio.h>
#include<string.h>

int string_compare(char *str1,char *str2){
    int ret;

    ret=strcmp(str1,str2);

    if(ret < 0) {
      return 0;
    }
    else if(ret > 0) {
      return 1;
    }
    else {
      return -1;
    }
}

void swap(char *str1, char *str2)
{
  char *temp = str1;
  str1 = str2;
  str2 = temp;
}

int main(int argc,char *argv[]){
    char *planets[9]={"Mercury","Venus","Earth","Mars","Jupiter","Saturn","Uranus","Neptune","Pluto"};
    int i,j;
    int a_ret=strcmp(argv[2],"a");
    int r_ret=strcmp(argv[2],"r");
    int cmp;

    for(i=0;i=8;i++){
        for(j=8;j=(i+1);j--){
            cmp=string_compare(planets[j],planets[j-1]);
            if(a_ret==0){
                if(cmp==0){
                    swap(planets[j],planets[j-1]);
                }
            }
            else if(r_ret==0){
                if(cmp==1){
                    swap(planets[j],planets[j-1]);
                }
            }
        }
    }
    printf("%s",planets[0]);
   return 0;
}

The program is supposed to work something like this:

./planets –o a
The planets in alphabetical order are: Earth, Jupiter, Mars, Mercury, Neptune, Pluto, Saturn, Uranus, Venus

or this:

./planets –o r
The planets in reverse alphabetical order are: Venus, Uranus, Saturn, Pluto, Neptune, Mercury, Mars, Jupiter, Earth

The program compiles without error, but when I run it I get

Segmentation fault(core dumped)

I'm new to C, and I don't quite fully understand how to manipulate the memory allocation. Any help or advice is much appreciated.

Body:
In for loop you have used = operator instead of <= or >=.

NOTE: There are other logical errors also.

UPDATED:

You can use following code:

#include<stdio.h>
#include<string.h>
#define MAX_SIZE 9

void swap(char **str1, char **str2)
{
  char *temp = *str1;
  *str1 = *str2;
  *str2 = temp;
}

int main(int argc,char *argv[]){
    char *planets[MAX_SIZE]=    {"Mercury","Venus","Earth","Mars","Jupiter","Saturn","Uranus","Neptune","Pluto"};
    int i, j, cmp, minMax;

    //If we don't need an array sorted in accending order then it is obvious that
    //we need it to be sorted in decending order
    int a_ret= (strcmp(argv[2],"a") == 0);

    for(i=0;i<MAX_SIZE;i++){
        minMax = i;
        for(j=i+1;j<MAX_SIZE;j++){
            cmp=strcmp(planets[j],planets[minMax]);
            if(((a_ret==0) && (cmp>0)) || ((a_ret==1) && (cmp<0))){
                    minMax =j;
            }
        }

        //Swap only if required
        if(i != minMax)
           swap(&planets[i], &planets[minMax]);
    }

    //Print the sorted array
    for(i=0;i<MAX_SIZE;i++)
        printf("%s | ",planets[i]);
   return 0;
}

You can see working code here(Command line argument are nor provided due to online IDE restriction).


问:
Make git repo from a clone and preserve the history
Need to migrate a git repository from gitserver G1 to git server G2. Issue is that both G1 and G2 are in their respective private networks and cannot access each other directly.
I have access to both the servers from my machine. What I am trying to do is clone the repository from G1 to my local machine copy and scp that cloned project to G2. Now, Could you please let me know:

How to turn this clone on G2 into a proper repository, so that others can clone it afterwards.

Is there a better way to do it.

We normally create a clone from git repo, here I need to do the opposite, i.e. how do we create a git repo from a clone so that the history is preserved.

Thanks,

Kapil

答:
Create a blank repo on server G2. Then on the local repo, run:

```<code>git remote add G2 <blank_repo_url>
git push —all G2
</code>```

Because Git is designed to be decentralised, history is maintained when you push to a new repository.

Body:
Create a blank repo on server G2. Then on the local repo, run:

git remote add G2 <blank_repo_url>
git push —all G2

Because Git is designed to be decentralised, history is maintained when you push to a new repository.


问:
Getting the size of a S3 image from Stream using C#
I've uploaded an image to Amazon Web Service S3. I am reading the image from S3 using client.GetObject.

I am converting the image to a series of bytes. In order to do so, I am creating a buffer (byte[]) to hold the data when I convert the stream to bytes using Stream.read.

In order to do so, I need to allocate the right amount of bytes for the buffer array.

My question is: How can I get the size of the image after it has been read to S3Response object.I know I can run responseObject.ResponseStream to get the stream, but how do I get the size of the stream?

Developing with AWS SDK .NET C#

答:
ResponseStream.Length throws an exception because it's a network stream ("does not support seeking").

Before requesting the stream itself, get its info with a directory listing:

```<code>var request = new ListObjectsV2Request
{
    BucketName = bucketName,
    Prefix = $"{folderName}/{fileName}"
};
var response = Client.ListObjectsV2(request);
var fileSize = response.S3Objects.Any() ? response.S3Objects.First().Size : 0;
</code>```

Body:
ResponseStream.Length throws an exception because it's a network stream ("does not support seeking").

Before requesting the stream itself, get its info with a directory listing:

var request = new ListObjectsV2Request
{
    BucketName = bucketName,
    Prefix = $"{folderName}/{fileName}"
};
var response = Client.ListObjectsV2(request);
var fileSize = response.S3Objects.Any() ? response.S3Objects.First().Size : 0;