问:
Wordpress (Grow Pro): How to change primary header menu in header.php
I just started taking care of an already existing website and installed the max mega menu plugin to have more control over the menu buttons. However, on mobile devices the original menu toggle is still visible but not responsive.

So I deactivated the plugin again but the menu toggle remains unresponsive which means that right now the site has either no working menu or two menu toggles on mobile devices.

```<code>/**
 * The Header for our theme.
 *
 * Displays all of the <head> section and everything up until id="main-core".
 *
 * @package ThinkUpThemes
 */
?><!DOCTYPE html>

<html <?php language_attributes(); ?>>
<head>
<?php thinkup_hook_header(); ?>
<meta charset="<?php bloginfo( 'charset' ); ?>" />
<meta name="viewport" content="width=device-width" />
<link rel="profile" href="//gmpg.org/xfn/11" />
<link rel="pingback" href="<?php esc_url( bloginfo( 'pingback_url' ) ); ?>" />

<?php wp_head(); ?>
</head>

<body <?php body_class(); ?><?php thinkup_bodystyle(); ?>>
<?php /* Body hook */ thinkup_hook_bodyhtml(); ?>
<?php /* Notification Bar */ thinkup_input_notification(); ?>
<?php /* Header Image */ thinkup_input_headerimage(); ?>
<div id="body-core" class="hfeed site">

    <header>
    <div id="site-header">

        <?php  if ( get_header_image() ) : ?>
            <div class="custom-header"><img src="<?php header_image(); ?>" width="<?php echo esc_attr( get_custom_header()->width ); ?>" height="<?php echo esc_attr( get_custom_header()->height ); ?>" alt=""></div>
        <?php endif; // End header image check. ?>

        <div id="pre-header">
        <div class="wrap-safari">
        <div id="pre-header-core" class="main-navigation">

             <?php if ( has_nav_menu( 'pre_header_menu' ) ) : ?>
            <?php wp_nav_menu( array( 'container_class' => 'header-links', 'container_id' => 'pre-header-links-inner', 'theme_location' => 'pre_header_menu' ) ); ?>
            <?php endif; ?>

            <?php /* Pre Header Search */ thinkup_input_preheadersearch(); ?>

            <?php /* Social Media Icons */ thinkup_input_socialmediaheaderpre(); ?>

        </div>
        </div>
        </div>
        <!-- #pre-header -->

        <?php /* Add header - above slider */ thinkup_input_headerlocationabove(); ?>

        <?php /* Add responsive header menu */ thinkup_input_responsivehtml2_above(); ?>

        <?php /* Add sticky header */ thinkup_input_headersticky(); ?>

        <?php /* Custom Slider */ thinkup_input_sliderhome(); ?>

        <?php /* Custom Intro - Above */ thinkup_custom_introabove(); ?>

        <?php /* Custom Slider */ thinkup_input_sliderpage(); ?>

        <?php /* Add header - above slider */ thinkup_input_headerlocationbelow(); ?>

        <?php /* Add responsive header menu */ thinkup_input_responsivehtml2_below(); ?>

        <?php /* Custom Intro - Below */ thinkup_custom_introbelow(); ?>

    </div>

    </header>
    <!-- header -->

    <?php /*  Call To Action - Intro */ thinkup_input_ctaintro(); ?>
    <?php /*  Pre-Designed HomePage Content */ thinkup_input_homepagesection(); ?>

    <div id="content">
    <div id="content-core">

        <div id="main">
        <div id="main-core">
</code>```

The theme lets me choose between three menu positions: Pre header, primary header and footer. I looked into the header.php and found it strange that I could not find any code about the primary header menu. Please note that I am an absolute newbie to website hosting and css programming!!

How can I remove the 'old' menu toggle from the website and/or make it responsive again?

Thanks in advance!

答:
You can change the main menu of a wordpress, from the admin page /wp-admin/nav-menus.php, at the bottom it has a checkbox to indicate as Primary menu.

Your theme's header.php has the default function to display the wordpress primary menu:

<?php wp_nav_menu( array( 'container_class' => 'header-links', 'container_id' => 'pre-header-links-inner', 'theme_location' => 'pre_header_menu' ) ); ?>
```

<p>You can check the here the <code>wp_nav_menu()</code> wordpress function.</p>

<p>Alternatively you can change your header.php the obove line to:</p>

<pre class="lang-php prettyprint-override"><code><?php wp_nav_menu( array( 'menu' => $the_id_of_your_menu,'container_class' => 'header-links', 'container_id' => 'pre-header-links-inner', 'theme_location' => 'pre_header_menu' ) ); ?>
</code>```

You can find the $the_id_of_your_menu by visiting your menu in the wp-admin and clicking the select button as described here

Hope this helps

Body:
I just started taking care of an already existing website and installed the max mega menu plugin to have more control over the menu buttons. However, on mobile devices the original menu toggle is still visible but not responsive.

So I deactivated the plugin again but the menu toggle remains unresponsive which means that right now the site has either no working menu or two menu toggles on mobile devices.

/**
 * The Header for our theme.
 *
 * Displays all of the  section and everything up until id="main-core".
 *
 * @package ThinkUpThemes
 */
?><!DOCTYPE html>

<html <?php language_attributes(); ?>>

<?php thinkup_hook_header(); ?>
<meta charset="<?php bloginfo( 'charset' ); ?>" />
<meta name="viewport" content="width=device-width" />
<link rel="profile" href="//gmpg.org/xfn/11" />
<link rel="pingback" href="<?php esc_url( bloginfo( 'pingback_url' ) ); ?>" />

<?php wp_head(); ?>

<body <?php body_class(); ?><?php thinkup_bodystyle(); ?>>
<?php /* Body hook */ thinkup_hook_bodyhtml(); ?>
<?php /* Notification Bar */ thinkup_input_notification(); ?>
<?php /* Header Image */ thinkup_input_headerimage(); ?>

        <?php  if ( get_header_image() ) : ?>

<img src="<?php header_image(); ?>" width="<?php echo esc_attr( get_custom_header()->width ); ?>" height="<?php echo esc_attr( get_custom_header()->height ); ?>" alt="">

        <?php endif; // End header image check. ?>

             <?php if ( has_nav_menu( 'pre_header_menu' ) ) : ?>
            <?php wp_nav_menu( array( 'container_class' => 'header-links', 'container_id' => 'pre-header-links-inner', 'theme_location' => 'pre_header_menu' ) ); ?>
            <?php endif; ?>

            <?php /* Pre Header Search */ thinkup_input_preheadersearch(); ?>

            <?php /* Social Media Icons */ thinkup_input_socialmediaheaderpre(); ?>

        <?php /* Add header - above slider */ thinkup_input_headerlocationabove(); ?>

        <?php /* Add responsive header menu */ thinkup_input_responsivehtml2_above(); ?>

        <?php /* Add sticky header */ thinkup_input_headersticky(); ?>

        <?php /* Custom Slider */ thinkup_input_sliderhome(); ?>

        <?php /* Custom Intro - Above */ thinkup_custom_introabove(); ?>

        <?php /* Custom Slider */ thinkup_input_sliderpage(); ?>

        <?php /* Add header - above slider */ thinkup_input_headerlocationbelow(); ?>

        <?php /* Add responsive header menu */ thinkup_input_responsivehtml2_below(); ?>

        <?php /* Custom Intro - Below */ thinkup_custom_introbelow(); ?>

    <?php /*  Call To Action - Intro */ thinkup_input_ctaintro(); ?>
    <?php /*  Pre-Designed HomePage Content */ thinkup_input_homepagesection(); ?>

The theme lets me choose between three menu positions: Pre header, primary header and footer. I looked into the header.php and found it strange that I could not find any code about the primary header menu. Please note that I am an absolute newbie to website hosting and css programming!!

How can I remove the 'old' menu toggle from the website and/or make it responsive again?

Thanks in advance!

Body:
You can change the main menu of a wordpress, from the admin page /wp-admin/nav-menus.php, at the bottom it has a checkbox to indicate as Primary menu.

Your theme's header.php has the default function to display the wordpress primary menu:

<?php wp_nav_menu( array( 'container_class' => 'header-links', 'container_id' => 'pre-header-links-inner', 'theme_location' => 'pre_header_menu' ) ); ?>

You can check the here the wp_nav_menu() wordpress function.

Alternatively you can change your header.php the obove line to:

<?php wp_nav_menu( array( 'menu' => $the_id_of_your_menu,'container_class' => 'header-links', 'container_id' => 'pre-header-links-inner', 'theme_location' => 'pre_header_menu' ) ); ?>

You can find the $the_id_of_your_menu by visiting your menu in the wp-admin and clicking the select button as described here

Hope this helps


来源: stackexchange

问:
how to get all the multi valued attributes into a csv file
I have a sample data as below .Below attributes are belong to [data] dictionary.   In "XXXX" i have value "Naveen" and in "YYYYY" i have "Kumar" and "Rajesh" . i am trying with the below code to get 2 recorded output

Please help with any suggestion

```<code>    {
  "data": [
  {
      "Empid": "1234",
      "Empname": "ABC",
       "data1": {
          "XXXX": [
            {
              "relative": {
                "id": "Naveen"
              }
            }
          ],
          "YYYYY": [
            {
              "relative": {
                "id": "Kumar"
              }
            },
            {
              "relative": {
                "id": "Rajesh"
              }
            }
          ]
          }

     }
     ]
}
</code>```

Please find below code ( i am trying )

```<code>df = pd.DataFrame()
for i in range(len(json_file['data'])):
    temp = {}
    temp['Empid'] = json_file['data'][i]['Empid']
    temp['EmpName'] = json_file['data'][i]['EmpName']
        for key in json_file['data'][i]['data1'].keys():
                try:
                    for j in range(len(json_file['data'][i]['data1'][key])):
                        temp[key]  = json_file['data'][i]['data1'][key][j]['relative']['id']
                except:
                    temp[key] = None
        temp_df = pd.DataFrame([temp])
        df = pd.concat([df, temp_df], sort=True)
</code>```

Final output i am trying to achieve

```<code> EmpID EmpName XXXX   YYYYY
 1234  ABC     Naveen  Kumar
 1234  ABC     Nan     Rajesh
</code>```

but i am getting only 1 record

```<code> EmpID EmpName XXXX   YYYYY
 1234  ABC     Naveen  Kumar
</code>```

Please help me with any suggestion

答:
```<code>from pandas.io.json import json_normalize
key=list(json_file1['data'][0].keys())
df=pd.concat([json_normalize(json_file1['data'][0][key[0]]),json_normalize(json_file1['data'][0][key[1]])],axis=1)
df=df.ffill()
df.columns=key
df

   XXXX    YYYYY
0   Naveen  Kumar
1   Naveen  Rajesh
</code>```

For automating it , you can iterate over the distinct keys

```<code>DF={}
key=list(json_file1['data'][0].keys())
for i in range(len(key)):
    df=json_normalize(json_file1['data'][0][key[i]])
    DF[key[i]]=(pd.concat([df],axis=0))
DF1=pd.concat(DF,axis=1)
DF1=DF1.ffill()
DF1.columns=key
DF1
</code>```

output

```<code>   XXXX   YYYYY    ZZZZZ
0   Naveen  Kumar   Kumar1
1   Naveen  Rajesh  Rajesh1
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a sample data as below .Below attributes are belong to [data] dictionary.   In "XXXX" i have value "Naveen" and in "YYYYY" i have "Kumar" and "Rajesh" . i am trying with the below code to get 2 recorded output

Please help with any suggestion

    {
  "data": [
  {
      "Empid": "1234",
      "Empname": "ABC",
       "data1": {
          "XXXX": [
            {
              "relative": {
                "id": "Naveen"
              }
            }
          ],
          "YYYYY": [
            {
              "relative": {
                "id": "Kumar"
              }
            },
            {
              "relative": {
                "id": "Rajesh"
              }
            }
          ]
          }

     }
     ]
}

Please find below code ( i am trying )

df = pd.DataFrame()
for i in range(len(json_file['data'])):
    temp = {}
    temp['Empid'] = json_file['data'][i]['Empid']
    temp['EmpName'] = json_file['data'][i]['EmpName']
        for key in json_file['data'][i]['data1'].keys():
                try:
                    for j in range(len(json_file['data'][i]['data1'][key])):
                        temp[key]  = json_file['data'][i]['data1'][key][j]['relative']['id']
                except:
                    temp[key] = None
        temp_df = pd.DataFrame([temp])
        df = pd.concat([df, temp_df], sort=True)

Final output i am trying to achieve

 EmpID EmpName XXXX   YYYYY
 1234  ABC     Naveen  Kumar
 1234  ABC     Nan     Rajesh

but i am getting only 1 record

 EmpID EmpName XXXX   YYYYY
 1234  ABC     Naveen  Kumar

Please help me with any suggestion

Body:
from pandas.io.json import json_normalize
key=list(json_file1['data'][0].keys())
df=pd.concat([json_normalize(json_file1['data'][0][key[0]]),json_normalize(json_file1['data'][0][key[1]])],axis=1)
df=df.ffill()
df.columns=key
df

   XXXX    YYYYY
0   Naveen  Kumar
1   Naveen  Rajesh

For automating it , you can iterate over the distinct keys

DF={}
key=list(json_file1['data'][0].keys())
for i in range(len(key)):
    df=json_normalize(json_file1['data'][0][key[i]])
    DF[key[i]]=(pd.concat([df],axis=0))
DF1=pd.concat(DF,axis=1)
DF1=DF1.ffill()
DF1.columns=key
DF1

output

   XXXX   YYYYY    ZZZZZ
0   Naveen  Kumar   Kumar1
1   Naveen  Rajesh  Rajesh1


问:
In Angular 6 how to logout user from Multiple tabs if we are using MsAdal
Am using MsAdalAngular6Service in My Angular 6 application. Issue is when we open the application in multiple tables, Then If I log out in tab , the user needs to be logged out in all other tabs as well.Currently use is being logged out only in one tab.

In my Log out Am calling msdal.logout().

Thanks for the help.

答:
You will need to watch for localStorage change event, refer to this stackoverflow thread.

Then check if the values that changed were the ones you want (token, credentials, etc.) and execute the logout service.


问:
Volley parse Json object with file sending string to server
This is my Java code:

```<code> public void imageUpload(final Context context, final String imagePath) {
    final String requestBody;
    JSONObject jsonUser = null;
    JSONObject jsonAddress = null;
    JSONObject jsonDriver = null;
    JSONObject jsonImage = null;
    String URL = SIGN_UP;
    final String ConvertImage;

    jsonUser = new JSONObject();
    try {
        jsonUser.put("first_name", "ABC");
        jsonUser.put("last_name", "XYZ");
        jsonUser.put("email", "yash@gmail.com");
        jsonUser.put("phone", "9999900000");
        jsonUser.put("password", "Yash@123");

        jsonAddress = new JSONObject();
        jsonAddress.put("address", "MUMBAI");
        jsonAddress.put("city", "MUMBAI");
        jsonAddress.put("state", "MH");
        jsonAddress.put("zip", "369852");

        jsonDriver = new JSONObject();
        jsonDriver.put("middle_name", "GG");
        jsonDriver.put("vehicle_type", "CAR");
        jsonDriver.put("car_plate_number", "123456");
        jsonDriver.put("car_brand", "BMW");
        jsonDriver.put("making_year", "2011");
        jsonDriver.put("date_of_birth", "2019-06-01");
        jsonDriver.put("license_number", "12346579");
        jsonDriver.put("license_state", "MH");
        jsonDriver.put("social_security_number", "123456");

        JSONObject jsonObjectFinal = new JSONObject();
        jsonObjectFinal.put("user", jsonUser);
        jsonObjectFinal.put("address", jsonAddress);
        jsonObjectFinal.put("driver", jsonDriver);

    } catch (JSONException e) {
        e.printStackTrace();
    }

    SimpleMultiPartRequest smr = new SimpleMultiPartRequest(Request.Method.POST, URL,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    Log.d("Response", response);
                    try {
                        JSONObject jObj = new JSONObject(response);
                        String message = jObj.getString("message");

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

            Toast.makeText(context, "" + error.getMessage(), Toast.LENGTH_SHORT).show();

        }
    }) {
        @Override
        protected Map<String, String> getParams() throws AuthFailureError {

            Map<String, String> params = new HashMap<String, String>();
            /*params.put("user", jsonUser + "");
            params.put("address", jsonAddress + "");
            params.put("driver", jsonDriver + "");
            Log.d("Param", "" + params + "***");*/
            return params;
        }
    };
    smr.addFile("license_image", imagePath);
    smr.addMultipartParam("user", "text/plain", jsonUser + "");
    smr.addMultipartParam("address", "text/plain", jsonAddress + "");
    smr.addMultipartParam("driver", "text/plain", jsonDriver + "");
    Log.d("Param", "" + smr.getMultipartParams() + "***");
    MySingleton.getInstance(context).addToRequestQueue(smr);
}
</code>```

The server shows:

```<code>data:->

[Object: null prototype] {
 address:
  '{"address":"SURAT","city":"SURAT","state":"GUJARAT","zip":"369852"}',
 driver:
  '{"middle_name":"GG","vehicle_type":"CAR","car_plate_number":"123456","car_brand":"BMW","making_year":"2011","date_of_birth":"2019-06-01","license_number":"12346579","license_state":"MH","social_security_number":"123456"}',
 user:
  '{"first_name":"YASH","last_name":"PANCHAL","email":"yash@gmail.com","phone":"8460277210","password":"Yash@123"}' }
files:-> [ { fieldname: 'license_image',
   originalname: '1559197608373.jpg',
   encoding: 'binary',
   mimetype: 'application/octet-stream',
   destination: 'C:\\Users\\Admin\\AppData\\Local\\Temp',
   filename: 'license_image-m6i0vcx0-1559197611770.octet-stream',
   path:
    'C:\\Users\\Admin\\AppData\\Local\\Temp\\license_image-m6i0vcx0-1559197611770.octet-stream',
   size: 53156 } ]
</code>```

The files are sent perfectly but the JSON object is parsed as String, I want to send data like:

```<code>  {
user:{
'first_name': 'yash',
'last_name': 'panchal'
},
address:{
...
},
driver:{
...
},
licence_image: [file]
}
</code>```

In Android I have to pass request in JSON object or array including files.
If I try to parse the image via bitmap, the server returns undefined and if I try with pas as String it's working fine but when passing JSON data as above it results in sending object data as a single String.

答:
Have a look at this multipart request with parameter's to a particular server and parsing its response as json :</p>

```<code>private void saveProfileAccount() {
        // loading or check internet connection or something...
        // ... then
        String url = "http://www.angga-ari.com/api/something/awesome";
        VolleyMultipartRequest multipartRequest = new VolleyMultipartRequest(Request.Method.POST, url, new Response.Listener<NetworkResponse>() {
            @Override
            public void onResponse(NetworkResponse response) {
                String resultResponse = new String(response.data);
                try {
                    JSONObject result = new JSONObject(resultResponse);
                    String status = result.getString("status");
                    String message = result.getString("message");

                    if (status.equals(Constant.REQUEST_SUCCESS)) {
                        // tell everybody you have succed upload image and post strings
                        Log.i("Messsage", message);
                    } else {
                        Log.i("Unexpected", message);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                NetworkResponse networkResponse = error.networkResponse;
                String errorMessage = "Unknown error";
                if (networkResponse == null) {
                    if (error.getClass().equals(TimeoutError.class)) {
                        errorMessage = "Request timeout";
                    } else if (error.getClass().equals(NoConnectionError.class)) {
                        errorMessage = "Failed to connect server";
                    }
                } else {
                    String result = new String(networkResponse.data);
                    try {
                        JSONObject response = new JSONObject(result);
                        String status = response.getString("status");
                        String message = response.getString("message");

                        Log.e("Error Status", status);
                        Log.e("Error Message", message);

                        if (networkResponse.statusCode == 404) {
                            errorMessage = "Resource not found";
                        } else if (networkResponse.statusCode == 401) {
                            errorMessage = message+" Please login again";
                        } else if (networkResponse.statusCode == 400) {
                            errorMessage = message+ " Check your inputs";
                        } else if (networkResponse.statusCode == 500) {
                            errorMessage = message+" Something is getting wrong";
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
                Log.i("Error", errorMessage);
                error.printStackTrace();
            }
        }) {
            @Override
            protected Map<String, String> getParams() {
                Map<String, String> params = new HashMap<>();
                params.put("api_token", "gh659gjhvdyudo973823tt9gvjf7i6ric75r76");
                params.put("name", mNameInput.getText().toString());
                params.put("location", mLocationInput.getText().toString());
                params.put("about", mAvatarInput.getText().toString());
                params.put("contact", mContactInput.getText().toString());
                return params;
            }

            @Override
            protected Map<String, DataPart> getByteData() {
                Map<String, DataPart> params = new HashMap<>();
                // file name could found file base or direct access from real path
                // for now just get bitmap data from ImageView
                params.put("avatar", new DataPart("file_avatar.jpg", AppHelper.getFileDataFromDrawable(getBaseContext(), mAvatarImage.getDrawable()), "image/jpeg"));
                params.put("cover", new DataPart("file_cover.jpg", AppHelper.getFileDataFromDrawable(getBaseContext(), mCoverImage.getDrawable()), "image/jpeg"));

                return params;
            }
        };

        VolleySingleton.getInstance(getBaseContext()).addToRequestQueue(multipartRequest);
    }
</code>```

Body:
This is my Java code:

 public void imageUpload(final Context context, final String imagePath) {
    final String requestBody;
    JSONObject jsonUser = null;
    JSONObject jsonAddress = null;
    JSONObject jsonDriver = null;
    JSONObject jsonImage = null;
    String URL = SIGN_UP;
    final String ConvertImage;

    jsonUser = new JSONObject();
    try {
        jsonUser.put("first_name", "ABC");
        jsonUser.put("last_name", "XYZ");
        jsonUser.put("email", "yash@gmail.com");
        jsonUser.put("phone", "9999900000");
        jsonUser.put("password", "Yash@123");

        jsonAddress = new JSONObject();
        jsonAddress.put("address", "MUMBAI");
        jsonAddress.put("city", "MUMBAI");
        jsonAddress.put("state", "MH");
        jsonAddress.put("zip", "369852");

        jsonDriver = new JSONObject();
        jsonDriver.put("middle_name", "GG");
        jsonDriver.put("vehicle_type", "CAR");
        jsonDriver.put("car_plate_number", "123456");
        jsonDriver.put("car_brand", "BMW");
        jsonDriver.put("making_year", "2011");
        jsonDriver.put("date_of_birth", "2019-06-01");
        jsonDriver.put("license_number", "12346579");
        jsonDriver.put("license_state", "MH");
        jsonDriver.put("social_security_number", "123456");

        JSONObject jsonObjectFinal = new JSONObject();
        jsonObjectFinal.put("user", jsonUser);
        jsonObjectFinal.put("address", jsonAddress);
        jsonObjectFinal.put("driver", jsonDriver);

    } catch (JSONException e) {
        e.printStackTrace();
    }

    SimpleMultiPartRequest smr = new SimpleMultiPartRequest(Request.Method.POST, URL,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    Log.d("Response", response);
                    try {
                        JSONObject jObj = new JSONObject(response);
                        String message = jObj.getString("message");

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

            Toast.makeText(context, "" + error.getMessage(), Toast.LENGTH_SHORT).show();

        }
    }) {
        @Override
        protected Map<String, String> getParams() throws AuthFailureError {

            Map<String, String> params = new HashMap<String, String>();
            /*params.put("user", jsonUser + "");
            params.put("address", jsonAddress + "");
            params.put("driver", jsonDriver + "");
            Log.d("Param", "" + params + "***");*/
            return params;
        }
    };
    smr.addFile("license_image", imagePath);
    smr.addMultipartParam("user", "text/plain", jsonUser + "");
    smr.addMultipartParam("address", "text/plain", jsonAddress + "");
    smr.addMultipartParam("driver", "text/plain", jsonDriver + "");
    Log.d("Param", "" + smr.getMultipartParams() + "***");
    MySingleton.getInstance(context).addToRequestQueue(smr);
}

The server shows:

data:->

[Object: null prototype] {
 address:
  '{"address":"SURAT","city":"SURAT","state":"GUJARAT","zip":"369852"}',
 driver:
  '{"middle_name":"GG","vehicle_type":"CAR","car_plate_number":"123456","car_brand":"BMW","making_year":"2011","date_of_birth":"2019-06-01","license_number":"12346579","license_state":"MH","social_security_number":"123456"}',
 user:
  '{"first_name":"YASH","last_name":"PANCHAL","email":"yash@gmail.com","phone":"8460277210","password":"Yash@123"}' }
files:-> [ { fieldname: 'license_image',
   originalname: '1559197608373.jpg',
   encoding: 'binary',
   mimetype: 'application/octet-stream',
   destination: 'C:\\Users\\Admin\\AppData\\Local\\Temp',
   filename: 'license_image-m6i0vcx0-1559197611770.octet-stream',
   path:
    'C:\\Users\\Admin\\AppData\\Local\\Temp\\license_image-m6i0vcx0-1559197611770.octet-stream',
   size: 53156 } ]

The files are sent perfectly but the JSON object is parsed as String, I want to send data like:

  {
user:{
'first_name': 'yash',
'last_name': 'panchal'
},
address:{
...
},
driver:{
...
},
licence_image: [file]
}

In Android I have to pass request in JSON object or array including files.
If I try to parse the image via bitmap, the server returns undefined and if I try with pas as String it's working fine but when passing JSON data as above it results in sending object data as a single String.

Body:
Have a look at this multipart request with parameter's to a particular server and parsing its response as json :

private void saveProfileAccount() {
        // loading or check internet connection or something...
        // ... then
        String url = "http://www.angga-ari.com/api/something/awesome";
        VolleyMultipartRequest multipartRequest = new VolleyMultipartRequest(Request.Method.POST, url, new Response.Listener<NetworkResponse>() {
            @Override
            public void onResponse(NetworkResponse response) {
                String resultResponse = new String(response.data);
                try {
                    JSONObject result = new JSONObject(resultResponse);
                    String status = result.getString("status");
                    String message = result.getString("message");

                    if (status.equals(Constant.REQUEST_SUCCESS)) {
                        // tell everybody you have succed upload image and post strings
                        Log.i("Messsage", message);
                    } else {
                        Log.i("Unexpected", message);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                NetworkResponse networkResponse = error.networkResponse;
                String errorMessage = "Unknown error";
                if (networkResponse == null) {
                    if (error.getClass().equals(TimeoutError.class)) {
                        errorMessage = "Request timeout";
                    } else if (error.getClass().equals(NoConnectionError.class)) {
                        errorMessage = "Failed to connect server";
                    }
                } else {
                    String result = new String(networkResponse.data);
                    try {
                        JSONObject response = new JSONObject(result);
                        String status = response.getString("status");
                        String message = response.getString("message");

                        Log.e("Error Status", status);
                        Log.e("Error Message", message);

                        if (networkResponse.statusCode == 404) {
                            errorMessage = "Resource not found";
                        } else if (networkResponse.statusCode == 401) {
                            errorMessage = message+" Please login again";
                        } else if (networkResponse.statusCode == 400) {
                            errorMessage = message+ " Check your inputs";
                        } else if (networkResponse.statusCode == 500) {
                            errorMessage = message+" Something is getting wrong";
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
                Log.i("Error", errorMessage);
                error.printStackTrace();
            }
        }) {
            @Override
            protected Map<String, String> getParams() {
                Map<String, String> params = new HashMap<>();
                params.put("api_token", "gh659gjhvdyudo973823tt9gvjf7i6ric75r76");
                params.put("name", mNameInput.getText().toString());
                params.put("location", mLocationInput.getText().toString());
                params.put("about", mAvatarInput.getText().toString());
                params.put("contact", mContactInput.getText().toString());
                return params;
            }

            @Override
            protected Map<String, DataPart> getByteData() {
                Map<String, DataPart> params = new HashMap<>();
                // file name could found file base or direct access from real path
                // for now just get bitmap data from ImageView
                params.put("avatar", new DataPart("file_avatar.jpg", AppHelper.getFileDataFromDrawable(getBaseContext(), mAvatarImage.getDrawable()), "image/jpeg"));
                params.put("cover", new DataPart("file_cover.jpg", AppHelper.getFileDataFromDrawable(getBaseContext(), mCoverImage.getDrawable()), "image/jpeg"));

                return params;
            }
        };

        VolleySingleton.getInstance(getBaseContext()).addToRequestQueue(multipartRequest);
    }


问:
Cutting a database down to size
Say you have a database that has served a company for 10 years. It is 500GB in size, it has myriad tables, stored procedures and triggers.

Now say you wish to create a cut down version of the database to use as a test bed for use in integration testing and for individual testers and developers to spin up instances of to play around with.

In broad terms how would you set about this task?

In case it matters, the database I have in mind is SQL Server 2008.

Edit: removed "unit testing" because of course unit tests should not test db integration

答:
What about looking at the transaction log file?
Make sure you do a backup of the original database.

```<code>USE db;
GO
-- Truncate the log by changing the database recovery model to SIMPLE.
ALTER DATABASE db
SET RECOVERY SIMPLE;
GO
-- Shrink the truncated log file to 1 MB.
DBCC SHRINKFILE (db_log, 1);
GO
-- Reset the database recovery model.
ALTER DATABASE db
SET RECOVERY FULL;
GO
</code>```

I've also found great success in rebuilding indexes and defragmenting.

Tara Kizer posted this it has proven to help us out with DB performance:
Thanks Tara Kizer if you read this!

```<code>-- required table
IF OBJECT_ID('DefragmentIndexes') IS NULL
    CREATE TABLE DefragmentIndexes
    (
        DatabaseName nvarchar(100) NOT NULL,
        SchemaName nvarchar(100) NOT NULL,
        TableName nvarchar(100) NOT NULL,
        IndexName nvarchar(100) NOT NULL,
        DefragmentDate datetime NOT NULL,
        PercentFragmented decimal(4, 2) NOT NULL,
        CONSTRAINT PK_DefragmentIndexes PRIMARY KEY CLUSTERED
        (
            DatabaseName,
            SchemaName,
            TableName,
            IndexName,
            DefragmentDate
        )
    )
GO

IF OBJECT_ID(N'[dbo].[isp_ALTER_INDEX]') IS NOT NULL
    DROP PROC [dbo].[isp_ALTER_INDEX]
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------------------
-- OBJECT NAME           : isp_ALTER_INDEX
--
-- AUTHOR                : Tara Kizer
--
-- INPUTS                : @dbName         - name of the database
--                         @statsMode      - LIMITED, SAMPLED or DETAILED
--                         @defragType     - REORGANIZE (INDEXDEFRAG) or REBUILD (DBREINDEX)
--                         @minFragPercent - minimum fragmentation level
--                         @maxFragPercent - maximum fragmentation level
--                         @minRowCount    - minimum row count
--                         @logHistory     - whether or not to log what got defragmented
--                         @sortInTempdb   - whether or not to sort the index in tempdb;
--                                           recommended if your tempdb is optimized (see BOL for details)
--
-- OUTPUTS               : None
--
-- DEPENDENCIES          : DefragmentIndexes, sys.dm_db_index_physical_stats, sys.objects, sys.schemas,
--                         sys.indexes, sys.partitions, sys.indexes, sys.index_columns, INFORMATION_SCHEMA.COLUMNS
--
-- DESCRIPTION           : Defragments indexes
/*
                           EXEC isp_ALTER_INDEX
                             @dbName = 'QHOSClient1',
                             @statsMode = 'SAMPLED',
                             @defragType = 'REBUILD',
                             @minFragPercent = 10,
                             @maxFragPercent = 100,
                             @minRowCount = 1000,
                             @logHistory = 1,
                             @sortInTempdb = 1
*/
/*
    http://weblogs.sqlteam.com/tarad/archive/2009/03/27/Defragmenting-Indexes-in-SQL-Server-2005Again.aspx
        Bug Fix - added SET QUOTED_IDENTIFIER ON to the script
        Feature - added logging feature
    http://weblogs.sqlteam.com/tarad/archive/2009/06/23/DefragmentingRebuilding-Indexes-in-SQL-Server-2005.aspx
        Bug Fix - initialized @lobData to 0 for each pass through the loop
        Bug Fix - checked for LOB data in included columns of non-clustered indexes
        Feature - added SORT_IN_TEMPB option
    http://weblogs.sqlteam.com/tarad/archive/2009/08/31/DefragmentingRebuilding-Indexes-in-SQL-server-2005-and-2008.aspx
        Bug Fix - added index_level = 0 to sys.dm_db_index_physical_stats query
    http://weblogs.sqlteam.com/tarad/archive/2009/11/03/DefragmentingRebuilding-Indexes-in-SQL-Server-2005-and-2008Again.aspx
        Bug Fix - for SQL Server 2008, @indexType could be 'XML INDEX' or 'PRIMARY XML INDEX' for XML indexes
*/
-------------------------------------------------------------------------------------------
CREATE PROC [dbo].[isp_ALTER_INDEX]
(
    @dbName sysname,
    @statsMode varchar(8) = 'SAMPLED',
    @defragType varchar(10) = 'REORGANIZE',
    @minFragPercent int = 25,
    @maxFragPercent int = 100,
    @minRowCount int = 0,
    @logHistory bit = 0,
    @sortInTempdb bit = 0
)
AS

SET NOCOUNT ON

IF @statsMode NOT IN ('LIMITED', 'SAMPLED', 'DETAILED')
BEGIN
    RAISERROR('@statsMode must be LIMITED, SAMPLED or DETAILED', 16, 1)
    RETURN
END

IF @defragType NOT IN ('REORGANIZE', 'REBUILD')
BEGIN
    RAISERROR('@defragType must be REORGANIZE or REBUILD', 16, 1)
    RETURN
END

DECLARE
    @i int, @objectId int, @objectName sysname, @indexId int, @indexName sysname,
    @schemaName sysname, @partitionNumber int, @partitionCount int,
    @sql nvarchar(4000), @edition int, @parmDef nvarchar(500), @allocUnitType nvarchar(60),
    @indexType nvarchar(60), @online bit, @disabled bit, @dataType nvarchar(128),
    @charMaxLen int, @allowPageLocks bit, @lobData bit, @fragPercent float

SELECT @edition = CONVERT(int, SERVERPROPERTY('EngineEdition'))

SELECT
    IDENTITY(int, 1, 1) AS FragIndexId,
    [object_id] AS ObjectId,
    index_id AS IndexId,
    avg_fragmentation_in_percent AS FragPercent,
    record_count AS RecordCount,
    partition_number AS PartitionNumber,
    index_type_desc AS IndexType,
    alloc_unit_type_desc AS AllocUnitType
INTO #FragIndex
FROM sys.dm_db_index_physical_stats (DB_ID(@dbName), NULL, NULL, NULL, @statsMode)
WHERE
    avg_fragmentation_in_percent > @minFragPercent AND
    avg_fragmentation_in_percent < @maxFragPercent AND
    index_id > 0 AND
    index_level = 0
ORDER BY ObjectId

-- LIMITED does not include data for record_count
IF @statsMode IN ('SAMPLED', 'DETAILED')
    DELETE FROM #FragIndex
    WHERE RecordCount < @minRowCount

SELECT @i = MIN(FragIndexId)
FROM #FragIndex

SELECT
    @objectId = ObjectId,
    @indexId = IndexId,
    @fragPercent = FragPercent,
    @partitionNumber = PartitionNumber,
    @indexType = IndexType,
    @allocUnitType = AllocUnitType
FROM #FragIndex
WHERE FragIndexId = @i

WHILE @@ROWCOUNT <> 0
BEGIN
    -- get the table and schema names for the index
    SET @sql = '
        SELECT @objectName = o.[name], @schemaName = s.[name]
        FROM ' + QUOTENAME(@dbName) + '.sys.objects o
        JOIN ' + QUOTENAME(@dbName) + '.sys.schemas s
            ON s.schema_id = o.schema_id
        WHERE o.[object_id] = @objectId'

    SET @parmDef = N'@objectId int, @objectName sysname OUTPUT, @schemaName sysname OUTPUT'

    EXEC sp_executesql
        @sql, @parmDef, @objectId = @objectId,
        @objectName = @objectName OUTPUT, @schemaName = @schemaName OUTPUT

    -- get index information
    SET @sql = '
        SELECT @indexName = [name], @disabled = is_disabled, @allowPageLocks = allow_page_locks
        FROM ' + QUOTENAME(@dbName) + '.sys.indexes
        WHERE [object_id] = @objectId AND index_id = @indexId'

    SET @parmDef = N'
            @objectId int, @indexId int, @indexName sysname OUTPUT,
            @disabled bit OUTPUT, @allowPageLocks bit OUTPUT'

    EXEC sp_executesql
        @sql, @parmDef, @objectId = @objectId, @indexId = @indexId,
        @indexName = @indexName OUTPUT, @disabled = @disabled OUTPUT,
        @allowPageLocks = @allowPageLocks OUTPUT

    SET @lobData = 0

    -- for clustered indexes, check for columns in the table that use a LOB data type
    IF @indexType = 'CLUSTERED INDEX'
    BEGIN
        -- CHARACTER_MAXIMUM_LENGTH column will equal -1 for max size or xml
        SET @sql = '
            SELECT @lobData = 1
            FROM ' + QUOTENAME(@dbName) + '.INFORMATION_SCHEMA.COLUMNS c
            WHERE   TABLE_SCHEMA = @schemaName AND
                    TABLE_NAME = @objectName AND
                    (DATA_TYPE IN (''text'', ''ntext'', ''image'') OR
                    CHARACTER_MAXIMUM_LENGTH = -1)'

        SET @parmDef = N'@schemaName sysname, @objectName sysname, @lobData bit OUTPUT'

        EXEC sp_executesql
            @sql, @parmDef, @schemaName = @schemaName, @objectName = @objectName,
            @lobData = @lobData OUTPUT
    END
    -- for non-clustered indexes, check for LOB data type in the included columns
    ELSE IF @indexType = 'NONCLUSTERED INDEX'
    BEGIN
        SET @sql = '
            SELECT @lobData = 1
            FROM ' + QUOTENAME(@dbName) + '.sys.indexes i
            JOIN ' + QUOTENAME(@dbName) + '.sys.index_columns ic
                ON i.object_id = ic.object_id
            JOIN ' + QUOTENAME(@dbName) + '.INFORMATION_SCHEMA.COLUMNS c
                ON ic.column_id = c.ORDINAL_POSITION
            WHERE   c.TABLE_SCHEMA = @schemaName AND
                    c.TABLE_NAME = @objectName AND
                    i.name = @indexName AND
                    ic.is_included_column = 1 AND
                    (c.DATA_TYPE IN (''text'', ''ntext'', ''image'') OR c.CHARACTER_MAXIMUM_LENGTH = -1)'

        SET @parmDef = N'@schemaName sysname, @objectName sysname, @indexName sysname, @lobData bit OUTPUT'

        EXEC sp_executesql
            @sql, @parmDef, @schemaName = @schemaName, @objectName = @objectName,
            @indexName = @indexName, @lobData = @lobData OUTPUT
    END

    -- get partition information for the index
    SET @sql = '
        SELECT @partitionCount = COUNT(*)
        FROM ' + QUOTENAME(@dbName) + '.sys.partitions
        WHERE [object_id] = @objectId AND index_id = @indexId'

    SET @parmDef = N'@objectId int, @indexId int, @partitionCount int OUTPUT'

    EXEC sp_executesql
        @sql, @parmDef, @objectId = @objectId, @indexId = @indexId,
        @partitionCount = @partitionCount OUTPUT

    -- Developer and Enterprise have the ONLINE = ON option for REBUILD.
    -- Indexes, including indexes on global temp tables, can be rebuilt online with the following exceptions:
    -- disabled indexes, XML indexes, indexes on local temp tables, partitioned indexes,
    -- clustered indexes if the underlying table contains LOB data types (text, ntext, image, varchar(max),
    -- nvarchar(max), varbinary(max) or xml), and
    -- nonclustered indexes that are defined with LOB data type columns.
    -- When reoganizing and page locks is disabled for the index, we'll switch to rebuild later on,
    -- so we need to get setup with the proper online option.
    IF @edition = 3 AND (@defragType = 'REBUILD' OR (@defragType = 'REORGANIZE' AND @allowPageLocks = 0))
    BEGIN
        SET @online =
                CASE
                    WHEN @indexType IN ('XML INDEX', 'PRIMARY XML INDEX') THEN 0
                    WHEN @indexType = 'NONCLUSTERED INDEX' AND @allocUnitType = 'LOB_DATA' THEN 0
                    WHEN @lobData = 1 THEN 0
                    WHEN @disabled = 1 THEN 0
                    WHEN @partitionCount > 1 THEN 0
                    ELSE 1
                END
    END
    ELSE
        SET @online = 0

    -- build the ALTER INDEX statement
    SET @sql = 'ALTER INDEX ' + QUOTENAME(@indexName) + ' ON ' + QUOTENAME(@dbName) + '.' +
        QUOTENAME(@schemaName) + '.' + QUOTENAME(@objectName) +
        CASE
            WHEN @defragType = ' REORGANIZE' AND @allowPageLocks = 0 THEN ' REBUILD'
            ELSE ' ' + @defragType
        END

    -- WITH options
    IF @online = 1 OR @sortInTempdb = 1
    BEGIN
        SET @sql = @sql + ' WITH (' +
            CASE
                WHEN @online = 1 AND @sortInTempdb = 1 THEN 'ONLINE = ON, SORT_IN_TEMPDB = ON'
                WHEN @online = 1 AND @sortInTempdb = 0 THEN 'ONLINE = ON'
                WHEN @online = 0 AND @sortInTempdb = 1 THEN 'SORT_IN_TEMPDB = ON'
            END + ')'
    END

    IF @partitionCount > 1 AND @disabled = 0 AND @indexType <> 'XML INDEX'
        SET @sql = @sql + ' PARTITION = ' + CAST(@partitionNumber AS varchar(10))

    -- run the ALTER INDEX statement
    EXEC (@SQL)

    -- log some information into a history table
    IF @logHistory = 1
        INSERT INTO DefragmentIndexes (DatabaseName, SchemaName, TableName, IndexName, DefragmentDate, PercentFragmented)
        VALUES(@dbName, @schemaName, @objectName, @indexName, GETDATE(), @fragPercent)

    SELECT @i = MIN(FragIndexId)
    FROM #FragIndex
    WHERE FragIndexId > @i

    SELECT
        @objectId = ObjectId,
        @indexId = IndexId,
        @fragPercent = FragPercent,
        @partitionNumber = PartitionNumber,
        @indexType = IndexType,
        @allocUnitType = AllocUnitType
    FROM #FragIndex
    WHERE FragIndexId = @i
END

GO
</code>```

The original post is here:

http://weblogs.sqlteam.com/tarad/archive/2009/08/31/DefragmentingRebuilding-Indexes-in-SQL-server-2005-and-2008.aspx

Aside from rebuilding the indexes and defragging the only other thing you can do is eliminate or get rid of data.  If you've got int / bigints as PK's this will allow you to then reseed your PK using  DBCC CHECKIDENT(tablename, value).

You could use ALTER INDEX ALL ON MyTable REBUILD to rebuild your indexes on your table.

ContentLicense: CC BY-SA 3.0

Title: Cutting a database down to size

Body:
What about looking at the transaction log file?
Make sure you do a backup of the original database.

USE db;
GO
-- Truncate the log by changing the database recovery model to SIMPLE.
ALTER DATABASE db
SET RECOVERY SIMPLE;
GO
-- Shrink the truncated log file to 1 MB.
DBCC SHRINKFILE (db_log, 1);
GO
-- Reset the database recovery model.
ALTER DATABASE db
SET RECOVERY FULL;
GO

I've also found great success in rebuilding indexes and defragmenting.

Tara Kizer posted this it has proven to help us out with DB performance:
Thanks Tara Kizer if you read this!

-- required table
IF OBJECT_ID('DefragmentIndexes') IS NULL
    CREATE TABLE DefragmentIndexes
    (
        DatabaseName nvarchar(100) NOT NULL,
        SchemaName nvarchar(100) NOT NULL,
        TableName nvarchar(100) NOT NULL,
        IndexName nvarchar(100) NOT NULL,
        DefragmentDate datetime NOT NULL,
        PercentFragmented decimal(4, 2) NOT NULL,
        CONSTRAINT PK_DefragmentIndexes PRIMARY KEY CLUSTERED
        (
            DatabaseName,
            SchemaName,
            TableName,
            IndexName,
            DefragmentDate
        )
    )
GO

IF OBJECT_ID(N'[dbo].[isp_ALTER_INDEX]') IS NOT NULL
    DROP PROC [dbo].[isp_ALTER_INDEX]
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------------------
-- OBJECT NAME           : isp_ALTER_INDEX
--
-- AUTHOR                : Tara Kizer
--
-- INPUTS                : @dbName         - name of the database
--                         @statsMode      - LIMITED, SAMPLED or DETAILED
--                         @defragType     - REORGANIZE (INDEXDEFRAG) or REBUILD (DBREINDEX)
--                         @minFragPercent - minimum fragmentation level
--                         @maxFragPercent - maximum fragmentation level
--                         @minRowCount    - minimum row count
--                         @logHistory     - whether or not to log what got defragmented
--                         @sortInTempdb   - whether or not to sort the index in tempdb;
--                                           recommended if your tempdb is optimized (see BOL for details)
--
-- OUTPUTS               : None
--
-- DEPENDENCIES          : DefragmentIndexes, sys.dm_db_index_physical_stats, sys.objects, sys.schemas,
--                         sys.indexes, sys.partitions, sys.indexes, sys.index_columns, INFORMATION_SCHEMA.COLUMNS
--
-- DESCRIPTION           : Defragments indexes
/*
                           EXEC isp_ALTER_INDEX
                             @dbName = 'QHOSClient1',
                             @statsMode = 'SAMPLED',
                             @defragType = 'REBUILD',
                             @minFragPercent = 10,
                             @maxFragPercent = 100,
                             @minRowCount = 1000,
                             @logHistory = 1,
                             @sortInTempdb = 1
*/
/*
    http://weblogs.sqlteam.com/tarad/archive/2009/03/27/Defragmenting-Indexes-in-SQL-Server-2005Again.aspx
        Bug Fix - added SET QUOTED_IDENTIFIER ON to the script
        Feature - added logging feature
    http://weblogs.sqlteam.com/tarad/archive/2009/06/23/DefragmentingRebuilding-Indexes-in-SQL-Server-2005.aspx
        Bug Fix - initialized @lobData to 0 for each pass through the loop
        Bug Fix - checked for LOB data in included columns of non-clustered indexes
        Feature - added SORT_IN_TEMPB option
    http://weblogs.sqlteam.com/tarad/archive/2009/08/31/DefragmentingRebuilding-Indexes-in-SQL-server-2005-and-2008.aspx
        Bug Fix - added index_level = 0 to sys.dm_db_index_physical_stats query
    http://weblogs.sqlteam.com/tarad/archive/2009/11/03/DefragmentingRebuilding-Indexes-in-SQL-Server-2005-and-2008Again.aspx
        Bug Fix - for SQL Server 2008, @indexType could be 'XML INDEX' or 'PRIMARY XML INDEX' for XML indexes
*/
-------------------------------------------------------------------------------------------
CREATE PROC [dbo].[isp_ALTER_INDEX]
(
    @dbName sysname,
    @statsMode varchar(8) = 'SAMPLED',
    @defragType varchar(10) = 'REORGANIZE',
    @minFragPercent int = 25,
    @maxFragPercent int = 100,
    @minRowCount int = 0,
    @logHistory bit = 0,
    @sortInTempdb bit = 0
)
AS

SET NOCOUNT ON

IF @statsMode NOT IN ('LIMITED', 'SAMPLED', 'DETAILED')
BEGIN
    RAISERROR('@statsMode must be LIMITED, SAMPLED or DETAILED', 16, 1)
    RETURN
END

IF @defragType NOT IN ('REORGANIZE', 'REBUILD')
BEGIN
    RAISERROR('@defragType must be REORGANIZE or REBUILD', 16, 1)
    RETURN
END

DECLARE
    @i int, @objectId int, @objectName sysname, @indexId int, @indexName sysname,
    @schemaName sysname, @partitionNumber int, @partitionCount int,
    @sql nvarchar(4000), @edition int, @parmDef nvarchar(500), @allocUnitType nvarchar(60),
    @indexType nvarchar(60), @online bit, @disabled bit, @dataType nvarchar(128),
    @charMaxLen int, @allowPageLocks bit, @lobData bit, @fragPercent float

SELECT @edition = CONVERT(int, SERVERPROPERTY('EngineEdition'))

SELECT
    IDENTITY(int, 1, 1) AS FragIndexId,
    [object_id] AS ObjectId,
    index_id AS IndexId,
    avg_fragmentation_in_percent AS FragPercent,
    record_count AS RecordCount,
    partition_number AS PartitionNumber,
    index_type_desc AS IndexType,
    alloc_unit_type_desc AS AllocUnitType
INTO #FragIndex
FROM sys.dm_db_index_physical_stats (DB_ID(@dbName), NULL, NULL, NULL, @statsMode)
WHERE
    avg_fragmentation_in_percent > @minFragPercent AND
    avg_fragmentation_in_percent < @maxFragPercent AND
    index_id > 0 AND
    index_level = 0
ORDER BY ObjectId

-- LIMITED does not include data for record_count
IF @statsMode IN ('SAMPLED', 'DETAILED')
    DELETE FROM #FragIndex
    WHERE RecordCount < @minRowCount

SELECT @i = MIN(FragIndexId)
FROM #FragIndex

SELECT
    @objectId = ObjectId,
    @indexId = IndexId,
    @fragPercent = FragPercent,
    @partitionNumber = PartitionNumber,
    @indexType = IndexType,
    @allocUnitType = AllocUnitType
FROM #FragIndex
WHERE FragIndexId = @i

WHILE @@ROWCOUNT <> 0
BEGIN
    -- get the table and schema names for the index
    SET @sql = '
        SELECT @objectName = o.[name], @schemaName = s.[name]
        FROM ' + QUOTENAME(@dbName) + '.sys.objects o
        JOIN ' + QUOTENAME(@dbName) + '.sys.schemas s
            ON s.schema_id = o.schema_id
        WHERE o.[object_id] = @objectId'

    SET @parmDef = N'@objectId int, @objectName sysname OUTPUT, @schemaName sysname OUTPUT'

    EXEC sp_executesql
        @sql, @parmDef, @objectId = @objectId,
        @objectName = @objectName OUTPUT, @schemaName = @schemaName OUTPUT

    -- get index information
    SET @sql = '
        SELECT @indexName = [name], @disabled = is_disabled, @allowPageLocks = allow_page_locks
        FROM ' + QUOTENAME(@dbName) + '.sys.indexes
        WHERE [object_id] = @objectId AND index_id = @indexId'

    SET @parmDef = N'
            @objectId int, @indexId int, @indexName sysname OUTPUT,
            @disabled bit OUTPUT, @allowPageLocks bit OUTPUT'

    EXEC sp_executesql
        @sql, @parmDef, @objectId = @objectId, @indexId = @indexId,
        @indexName = @indexName OUTPUT, @disabled = @disabled OUTPUT,
        @allowPageLocks = @allowPageLocks OUTPUT

    SET @lobData = 0

    -- for clustered indexes, check for columns in the table that use a LOB data type
    IF @indexType = 'CLUSTERED INDEX'
    BEGIN
        -- CHARACTER_MAXIMUM_LENGTH column will equal -1 for max size or xml
        SET @sql = '
            SELECT @lobData = 1
            FROM ' + QUOTENAME(@dbName) + '.INFORMATION_SCHEMA.COLUMNS c
            WHERE   TABLE_SCHEMA = @schemaName AND
                    TABLE_NAME = @objectName AND
                    (DATA_TYPE IN (''text'', ''ntext'', ''image'') OR
                    CHARACTER_MAXIMUM_LENGTH = -1)'

        SET @parmDef = N'@schemaName sysname, @objectName sysname, @lobData bit OUTPUT'

        EXEC sp_executesql
            @sql, @parmDef, @schemaName = @schemaName, @objectName = @objectName,
            @lobData = @lobData OUTPUT
    END
    -- for non-clustered indexes, check for LOB data type in the included columns
    ELSE IF @indexType = 'NONCLUSTERED INDEX'
    BEGIN
        SET @sql = '
            SELECT @lobData = 1
            FROM ' + QUOTENAME(@dbName) + '.sys.indexes i
            JOIN ' + QUOTENAME(@dbName) + '.sys.index_columns ic
                ON i.object_id = ic.object_id
            JOIN ' + QUOTENAME(@dbName) + '.INFORMATION_SCHEMA.COLUMNS c
                ON ic.column_id = c.ORDINAL_POSITION
            WHERE   c.TABLE_SCHEMA = @schemaName AND
                    c.TABLE_NAME = @objectName AND
                    i.name = @indexName AND
                    ic.is_included_column = 1 AND
                    (c.DATA_TYPE IN (''text'', ''ntext'', ''image'') OR c.CHARACTER_MAXIMUM_LENGTH = -1)'

        SET @parmDef = N'@schemaName sysname, @objectName sysname, @indexName sysname, @lobData bit OUTPUT'

        EXEC sp_executesql
            @sql, @parmDef, @schemaName = @schemaName, @objectName = @objectName,
            @indexName = @indexName, @lobData = @lobData OUTPUT
    END

    -- get partition information for the index
    SET @sql = '
        SELECT @partitionCount = COUNT(*)
        FROM ' + QUOTENAME(@dbName) + '.sys.partitions
        WHERE [object_id] = @objectId AND index_id = @indexId'

    SET @parmDef = N'@objectId int, @indexId int, @partitionCount int OUTPUT'

    EXEC sp_executesql
        @sql, @parmDef, @objectId = @objectId, @indexId = @indexId,
        @partitionCount = @partitionCount OUTPUT

    -- Developer and Enterprise have the ONLINE = ON option for REBUILD.
    -- Indexes, including indexes on global temp tables, can be rebuilt online with the following exceptions:
    -- disabled indexes, XML indexes, indexes on local temp tables, partitioned indexes,
    -- clustered indexes if the underlying table contains LOB data types (text, ntext, image, varchar(max),
    -- nvarchar(max), varbinary(max) or xml), and
    -- nonclustered indexes that are defined with LOB data type columns.
    -- When reoganizing and page locks is disabled for the index, we'll switch to rebuild later on,
    -- so we need to get setup with the proper online option.
    IF @edition = 3 AND (@defragType = 'REBUILD' OR (@defragType = 'REORGANIZE' AND @allowPageLocks = 0))
    BEGIN
        SET @online =
                CASE
                    WHEN @indexType IN ('XML INDEX', 'PRIMARY XML INDEX') THEN 0
                    WHEN @indexType = 'NONCLUSTERED INDEX' AND @allocUnitType = 'LOB_DATA' THEN 0
                    WHEN @lobData = 1 THEN 0
                    WHEN @disabled = 1 THEN 0
                    WHEN @partitionCount > 1 THEN 0
                    ELSE 1
                END
    END
    ELSE
        SET @online = 0

    -- build the ALTER INDEX statement
    SET @sql = 'ALTER INDEX ' + QUOTENAME(@indexName) + ' ON ' + QUOTENAME(@dbName) + '.' +
        QUOTENAME(@schemaName) + '.' + QUOTENAME(@objectName) +
        CASE
            WHEN @defragType = ' REORGANIZE' AND @allowPageLocks = 0 THEN ' REBUILD'
            ELSE ' ' + @defragType
        END

    -- WITH options
    IF @online = 1 OR @sortInTempdb = 1
    BEGIN
        SET @sql = @sql + ' WITH (' +
            CASE
                WHEN @online = 1 AND @sortInTempdb = 1 THEN 'ONLINE = ON, SORT_IN_TEMPDB = ON'
                WHEN @online = 1 AND @sortInTempdb = 0 THEN 'ONLINE = ON'
                WHEN @online = 0 AND @sortInTempdb = 1 THEN 'SORT_IN_TEMPDB = ON'
            END + ')'
    END

    IF @partitionCount > 1 AND @disabled = 0 AND @indexType <> 'XML INDEX'
        SET @sql = @sql + ' PARTITION = ' + CAST(@partitionNumber AS varchar(10))

    -- run the ALTER INDEX statement
    EXEC (@SQL)

    -- log some information into a history table
    IF @logHistory = 1
        INSERT INTO DefragmentIndexes (DatabaseName, SchemaName, TableName, IndexName, DefragmentDate, PercentFragmented)
        VALUES(@dbName, @schemaName, @objectName, @indexName, GETDATE(), @fragPercent)

    SELECT @i = MIN(FragIndexId)
    FROM #FragIndex
    WHERE FragIndexId > @i

    SELECT
        @objectId = ObjectId,
        @indexId = IndexId,
        @fragPercent = FragPercent,
        @partitionNumber = PartitionNumber,
        @indexType = IndexType,
        @allocUnitType = AllocUnitType
    FROM #FragIndex
    WHERE FragIndexId = @i
END

GO

The original post is here:

http://weblogs.sqlteam.com/tarad/archive/2009/08/31/DefragmentingRebuilding-Indexes-in-SQL-server-2005-and-2008.aspx

Aside from rebuilding the indexes and defragging the only other thing you can do is eliminate or get rid of data.  If you've got int / bigints as PK's this will allow you to then reseed your PK using  DBCC CHECKIDENT(tablename, value).

You could use ALTER INDEX ALL ON MyTable REBUILD to rebuild your indexes on your table.


问:
The identifier is not in the scope [Unity, VS2019]
I've recently switched to the Visual Studio 2019 (previously 2017) along with Unity 2019.1.3f1 (previously ~2019.1.0 something), with new Tools for Unity in Visual Studio and I have stumbled upon a problem.

When I am debugging, I can't see the variable from my Singleton class (e.g., GameManager.Instance.Var, Instance is public static). If I try to see it through Immediate Window it gives me this:

The identifier 'GameManager' is not in the scope

Hovering over any part of it (GameManager, Instance, Var) doesn't give any info at all, CodeLens is not working with it.

It sucks, because now I can't debug properly, only Debug.Log lol...

Help! What can I do? It seems that I can't find any similiar issues.

Here's a pic of my settings for Tools for Unity:

Thanks!

答:
So, I figured it out, it was a Visual Studio 2019 bug, I've reported it to the Microsoft, they are going to fix it.
Here's the link to the problem:
https://developercommunity.visualstudio.com/content/problem/581763/unity-development-in-visual-studio-2019.html</p>


问:
Benefits of bundling NodeJS/TypeScript application using webpack
I'm building node/Express application and want to utilize 'latest and greatest':

node/Express + TypeScript + webpack.

Question: What are the benefits of using webpack to bundle all my nodejs code into one file? Just trying to understand if it is an overkill to use webpack for such purpose.

答:
Good that you're using the good combination of languages at the server-side.
First of all understand why should we use Webpack.
Webpack is used for module bundling by the builds we’re generating. As a best practice, we should not run the source directly.

Also, there two common modes available by default in webpack are,

Development

Production

Development build produces source map files and it’s not minified and uglified. It holds the information about the source files and even it is compressed and compiled it is easy to debug the development build.
FYI, my development build file size is just ~51KB since I use mongoDB in my stack.

Production build compresses our source code into a minimized single file but performs the same task as source code does. It won’t produce source map files and it’s uglified and minified so the debugging is not possible. My prod build file size is just ~9KB.

Notice the size difference after the file compression from dev to prod.

So, I recommend to use webpack not only for bundling, also we can configure transpiler options using loaders in it.

Note: Webpack can be used for both Client and Server side.

Happy Coding!


问:
How to reiterate through all the view in recyclerview?
I want to achieve expandable item inside RecyclerView and when one item is expanded the other expanded item must automatically close, can someone please help?</p>

答:
Use your custom view inside main Recylerview's ViewHolder according to the requirement, use a flag(boolean) in your DataList(ArrayList) naming "isColapsed" which will be false initially when you want all the views collapsed.

Show or Hide the inner custom view according to the flags state if isColapsed is true then set the visibility of your inner RecyclerView to VISIBLE or if isCollapsed is false then set the visibility VISIBLE.

Each time you select the view to be expanded then set all other (isCollapsed) flags in the DataList(ArrayList) to true except for the particular position's flag as false then most important use notifyDataSetChanged(); method to update Your UI.


问:
Ampersand parsed as & in Thymeleaf
Here's my thymeleaf template:

```<code><html lang="en">
<head>
    <script>
       function postForm() {
          window.location.href = '[[${azSsoUrl}]]';
       }
    </script>
    <title></title>
</head>
<body onload="postForm()">
</body>
</html>
</code>```

actual value of azSsoUrl:

```<code>http://localhost:8080/gc-restful/sso-login?spEntityID=someId&metaAlias=%2FEmployee;
</code>```

but after parsing, this is what I get in the response. Note that & becomes

&

```<code><html lang="en">
<head>
    <script>
       function postForm() {
          window.location.href = 'http://localhost:8080/gc-restful/sso-login?spEntityID=someId&metaAlias=%2FEmployee;';
       }
    </script>
    <title></title>
</head>
<body onload="postForm()">
</body>
</html>
</code>```

I'm not really sure, using [[${azSsoUrl}]] is the right way to do this. What am I doing wrong here?

Edit:

I tried various things mentioned in the answer of possible duplicate question. But nothing seems to fix my problem.

答:
This is how I ended up solving my problem. It seems th:inline="javascript" is required with the script tag.

```<code><html lang="en" xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<head>
    <script th:inline="javascript">
       function postForm() {

          /*<![CDATA[*/

          window.location.href = /*[[${azSsoUrl}]]*/ 'redirect url';

          /*]]>*/
       }
    </script>
    <title></title>
</head>
<body onload="postForm()">
</body>
</html>
</code>```

Title: Ampersand parsed as & in Thymeleaf

Body:
Here's my thymeleaf template:

    <title></title>

actual value of azSsoUrl:

http://localhost:8080/gc-restful/sso-login?spEntityID=someId&metaAlias=%2FEmployee;

but after parsing, this is what I get in the response. Note that & becomes

&

    <title></title>

I'm not really sure, using [[${azSsoUrl}]] is the right way to do this. What am I doing wrong here?

Edit:

I tried various things mentioned in the answer of possible duplicate question. But nothing seems to fix my problem.

Body:
This is how I ended up solving my problem. It seems th:inline="javascript" is required with the script tag.

<html lang="en" xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<head>
    <script th:inline="javascript">
       function postForm() {

          /*<![CDATA[*/

          window.location.href = /*[[${azSsoUrl}]]*/ 'redirect url';

          /*]]>*/
       }
    </script>
    <title></title>
</head>
<body onload="postForm()">
</body>
</html>


问:
How to use strong parameters to refactor code
I'm new to Ruby on Rails and don't understand private methods using strong params.

How would I refactor this? Can someone give me an example?

I've tried looking it up, but all I find are examples of CRUD using strong params in CRUD.

```<code>def create
    title = params["song"]["title"]
    rating = params["song"]["rating"]
    artist_id = params["song"]["artist_id"]
    song = Song.create(title: title, rating: rating, artist_id:
    artist_id)
    redirect_to song_path(song)
end

def update
    title = params["song"]["title"]
    rating = params["song"]["rating"]
    artist_id = params["song"]["artist_id"]
    song = Song.find(params[:id])
    song.update(title: title, rating: rating, artist_id: artist_id)
    redirect_to song_path(song)
end
</code>```

答:
Have you tried anything like this? Note that you're not managing errors here

```<code>def create
    song = Song.create(song_params)
    redirect_to song_path(song)
end

def update
    song = Song.find(params[:id])
    song.update(song_params)
    redirect_to song_path(song)
end

private

def song_params
  params.require(:song).permit(:title, :rating, :artist_id)
end
</code>```

In this line you're simply whitelisting those three params' names in a song object and this method is called in the create and update actions

```<code>params.require(:song).permit(:title, :rating, :artist_id)
</code>```

This means that if a duration was sent inside the song object that attribute is not changed because it's not whitelisted

Body:
I'm new to Ruby on Rails and don't understand private methods using strong params.

How would I refactor this? Can someone give me an example?

I've tried looking it up, but all I find are examples of CRUD using strong params in CRUD.

def create
    title = params["song"]["title"]
    rating = params["song"]["rating"]
    artist_id = params["song"]["artist_id"]
    song = Song.create(title: title, rating: rating, artist_id:
    artist_id)
    redirect_to song_path(song)
end

def update
    title = params["song"]["title"]
    rating = params["song"]["rating"]
    artist_id = params["song"]["artist_id"]
    song = Song.find(params[:id])
    song.update(title: title, rating: rating, artist_id: artist_id)
    redirect_to song_path(song)
end

Body:
Have you tried anything like this? Note that you're not managing errors here

def create
    song = Song.create(song_params)
    redirect_to song_path(song)
end

def update
    song = Song.find(params[:id])
    song.update(song_params)
    redirect_to song_path(song)
end

private

def song_params
  params.require(:song).permit(:title, :rating, :artist_id)
end

In this line you're simply whitelisting those three params' names in a song object and this method is called in the create and update actions

params.require(:song).permit(:title, :rating, :artist_id)

This means that if a duration was sent inside the song object that attribute is not changed because it's not whitelisted


问:
async until doesn't enter iteratee (async 3.0.1)
Iteratee of async.until function is never called

Tried with node.js 10.16.0, async 3.0.1 on Windows 10 (1809)

```<code>const async = require('async');
var counter = 0;

async.until(() => {
    console.log('here?')
    return (counter > 10)
}, (cb) => {
    console.log('not here?');
    counter++;
    cb()
}, () => {
    console.log('the end');
})
</code>```

Terminal output

```<code>PS C:\Users\hofman\Desktop\Tools\GIT\test> node .
here?
PS C:\Users\hofman\Desktop\Tools\GIT\test>
</code>```

答:
test parameter should be an asynchronous function, like this

```<code>const async = require('async');
var counter = 0;

async.until(async () => {
    console.log('here?')
    return (counter > 10)
}, (cb) => {
    console.log('not here?');
    counter++;
    cb()
}, () => {
    console.log('the end');
})
</code>```

see documentation here: https://caolan.github.io/async/v3/docs.html#until

or using normal Node style async function, like this

```<code>const async = require('async');
var counter = 0;

async.until((cb) => {
    console.log('here?')
    cb(null, counter > 10)
}, (cb) => {
    console.log('not here?');
    counter++;
    cb()
}, () => {
    console.log('the end');
})
</code>```

And in version 2.x the test parameter was defined as a normal function
https://caolan.github.io/async/v2/docs.html#until

Here's the Changelog for v3.0:
https://github.com/caolan/async/blob/master/CHANGELOG.md#breaking-changes

whilst, doWhilst, until and doUntil now have asynchronous test functions

Body:
Iteratee of async.until function is never called

Tried with node.js 10.16.0, async 3.0.1 on Windows 10 (1809)

const async = require('async');
var counter = 0;

async.until(() => {
    console.log('here?')
    return (counter > 10)
}, (cb) => {
    console.log('not here?');
    counter++;
    cb()
}, () => {
    console.log('the end');
})

Terminal output

PS C:\Users\hofman\Desktop\Tools\GIT\test> node .
here?
PS C:\Users\hofman\Desktop\Tools\GIT\test>

Body:
test parameter should be an asynchronous function, like this

const async = require('async');
var counter = 0;

async.until(async () => {
    console.log('here?')
    return (counter > 10)
}, (cb) => {
    console.log('not here?');
    counter++;
    cb()
}, () => {
    console.log('the end');
})

see documentation here: https://caolan.github.io/async/v3/docs.html#until

or using normal Node style async function, like this

const async = require('async');
var counter = 0;

async.until((cb) => {
    console.log('here?')
    cb(null, counter > 10)
}, (cb) => {
    console.log('not here?');
    counter++;
    cb()
}, () => {
    console.log('the end');
})

And in version 2.x the test parameter was defined as a normal function
https://caolan.github.io/async/v2/docs.html#until

Here's the Changelog for v3.0:
https://github.com/caolan/async/blob/master/CHANGELOG.md#breaking-changes

whilst, doWhilst, until and doUntil now have asynchronous test functions


问:
Using mac ports to install py26-gtk switches off my Mac
I'm trying to run sudo port install py26-gtk but my MacBook doesn't get further than building gcc43, while doing that it switches off without shutting down.

It is not overheating since I tried it again while my MacBook was sandwiched between two cold packs. The Mac was cool and the ventilation was not running. i.e. the Mac was not trying to cool itself when I used the cold packs.

Does anyone have any idea what is causing my Mac to switch off?

I have a Mac OS 10.6.3, python 2.6, mac ports 1.8.2.

答: If this happens to you this means you have a hardware problem. Let's hope you still have apple care. I can't help but get the impression that apple hardware quality gets worse every year : (</p>


答:
if you json is like that :

```<code>json_file = {
  "data": [
     {
          "XXXX": [
            {
              "relative": {
                "id": "Naveen"
              }
            }
          ],
          "YYYYY": [
            {
              "relative": {
                "id": "Kumar"
              }
            },
            {
              "relative": {
                "id": "Rajesh"
              }
            }
          ]
    }
     ]
}
</code>```

The code below put the result in the matrix temp :

```<code>temp = []
for key in json_file['data'][0].keys():
    for i in json_file['data'][0][key]:
        temp.append([key,i['relative']['id']])
</code>```

The result is :

```<code>[['XXXX', 'Naveen'], ['YYYYY', 'Kumar'], ['YYYYY', 'Rajesh']]
</code>```

Title: how to get all the multi valued attributes into a csv file

Body:
if you json is like that :

json_file = {
  "data": [
     {
          "XXXX": [
            {
              "relative": {
                "id": "Naveen"
              }
            }
          ],
          "YYYYY": [
            {
              "relative": {
                "id": "Kumar"
              }
            },
            {
              "relative": {
                "id": "Rajesh"
              }
            }
          ]
    }
     ]
}

The code below put the result in the matrix temp :

temp = []
for key in json_file['data'][0].keys():
    for i in json_file['data'][0][key]:
        temp.append([key,i['relative']['id']])

The result is :

[['XXXX', 'Naveen'], ['YYYYY', 'Kumar'], ['YYYYY', 'Rajesh']]


问:
xml error code file
we are thinking use xml file to store our error codes for our C# application. for the following two structures, which one is better?

```<code><error>
<code>0x00000001</code>
<description>Error PIB: Clamp</description>
<reaction>Display</reaction>
</error>
</code>```

or

```<code><error code=0x00000001 >
<description>Error PIB: Clamp</description>
<reaction>Display</reaction>
</error>
</code>```

or your better suggestion?

seems the second one save some space and easiler for lookup through it?

I need to get the description and reaction string by lookup the error code. do you have an effective way to lookup through file?

答:
In general, if you want the code to describe the element, make it an attribute.  If you want the code to be an element (meaning that the code will also require attributes or even sub information) make it a child.

In your code, option 2 is best IMO

Title: xml error code file

Body:
we are thinking use xml file to store our error codes for our C# application. for the following two structures, which one is better?

<error>
0x00000001
<description>Error PIB: Clamp</description>
<reaction>Display</reaction>
</error>

or

<error code=0x00000001 >
<description>Error PIB: Clamp</description>
<reaction>Display</reaction>
</error>

or your better suggestion?

seems the second one save some space and easiler for lookup through it?

I need to get the description and reaction string by lookup the error code. do you have an effective way to lookup through file?


问:
How to close/kill app on Flutter
I am actually aware of this implementation: Flutter programmatically closing the app, but when the app closes is still in background. How can I absolutely kill the app and not let it be in background?

Thank you!

答:
You can use exit(0). But app exits abruptly. You can use the below code which is much smoother.

```<code>SystemChannels.platform.invokeMethod<void>('SystemNavigator.pop')
</code>```

Documentation is available here.

Title: How to close/kill app on Flutter

Body:
You can use exit(0). But app exits abruptly. You can use the below code which is much smoother.

SystemChannels.platform.invokeMethod<void>('SystemNavigator.pop')

Documentation is available here.


问:
How do I pass runtime parameters to dotnet test on the command line?
I have a set of unit tests in a .NET Core project and using a runsettings file. I am trying to setup Azure DevOps to do automated testing on my deployments. As part of this process, I need to override parameters from the run settings on the command line.

I have a runsettings file with the following section:

```<code>  <TestRunParameters>
    <Parameter name="ApiUrl" value="https://myurl..." />
  </TestRunParameters>
</code>```

I have a static constructor that saves the TestContext like this:

```<code>        [ClassInitialize]
        public static void TestClassInitialize(TestContext context)
        {
            TestContext = context;
        }
</code>```

I am retrieving settings from the TestContext with the following method:

```<code>        protected string GetStringSetting(string settingName)
        {
            return TestContext.Properties[settingName] as string;
        }
</code>```

When I run the test with the runsettings file selected, it gets the TestContext and I see the ApiUrl entry is retrieved successfully.

Now, I want to set this parameter from the command line. I am using a command like:

```<code>    dotnet test <myproject.csproj> --configuration Release -- ApiUrl=https://newurl
</code>```

I get an error that says the dictionary does not contain the key "ApiUrl" which indicates that the setting was not processed. From reading documentation, I thought that maybe I need to fully specify the name of the setting with TestRunParameters.ApiUrl. This gives me an XML error.

From everything I have read, I think I am doing this right and can't figure out what is wrong. I am using version 2.1.503 of the tools.

Can someone please give me guidance on how to make this work?

答:
You can't substitute the TestRunParameters from the command-line when using the DotNetCoreCLI@2 task or the dotnet test command, but you can create a temporary .runsettings file that contains the valid parameter value as part of your build pipeline in Azure Pipelines:

```<code>- powershell: |
   [xml]$doc = Get-Content Tests/Settings.runsettings
   $doc.RunSettings.TestRunParameters.ChildNodes.Item(0).value = 'https://newurl'
   $doc.Save("$(Build.SourcesDirectory)/Tests/UpdatedSettings.runsettings")
  displayName: 'Override TestRunParameters'

- task: DotNetCoreCLI@2
  displayName: 'Run Tests'
  inputs:
   command: test
   projects: 'Tests/Tests.csproj'
   arguments: '-s $(Build.SourcesDirectory)/Tests/UpdatedSettings.runsettings'

- powershell: |
   Remove-Item $(Build.SourcesDirectory)/Tests/UpdatedSettings.runsettings
  displayName: Remove temporary .runsettings file
</code>```

You'll find a complete YAML file and a sample test project on GitHub.

Body:
I have a set of unit tests in a .NET Core project and using a runsettings file. I am trying to setup Azure DevOps to do automated testing on my deployments. As part of this process, I need to override parameters from the run settings on the command line.

I have a runsettings file with the following section:

  <TestRunParameters>
    <Parameter name="ApiUrl" value="https://myurl..." />
  </TestRunParameters>

I have a static constructor that saves the TestContext like this:

        [ClassInitialize]
        public static void TestClassInitialize(TestContext context)
        {
            TestContext = context;
        }

I am retrieving settings from the TestContext with the following method:

        protected string GetStringSetting(string settingName)
        {
            return TestContext.Properties[settingName] as string;
        }

When I run the test with the runsettings file selected, it gets the TestContext and I see the ApiUrl entry is retrieved successfully.

Now, I want to set this parameter from the command line. I am using a command like:

    dotnet test <myproject.csproj> --configuration Release -- ApiUrl=https://newurl

I get an error that says the dictionary does not contain the key "ApiUrl" which indicates that the setting was not processed. From reading documentation, I thought that maybe I need to fully specify the name of the setting with TestRunParameters.ApiUrl. This gives me an XML error.

From everything I have read, I think I am doing this right and can't figure out what is wrong. I am using version 2.1.503 of the tools.

Can someone please give me guidance on how to make this work?

Body:
You can't substitute the TestRunParameters from the command-line when using the DotNetCoreCLI@2 task or the dotnet test command, but you can create a temporary .runsettings file that contains the valid parameter value as part of your build pipeline in Azure Pipelines:

- powershell: |
   [xml]$doc = Get-Content Tests/Settings.runsettings
   $doc.RunSettings.TestRunParameters.ChildNodes.Item(0).value = 'https://newurl'
   $doc.Save("$(Build.SourcesDirectory)/Tests/UpdatedSettings.runsettings")
  displayName: 'Override TestRunParameters'

- task: DotNetCoreCLI@2
  displayName: 'Run Tests'
  inputs:
   command: test
   projects: 'Tests/Tests.csproj'
   arguments: '-s $(Build.SourcesDirectory)/Tests/UpdatedSettings.runsettings'

- powershell: |
   Remove-Item $(Build.SourcesDirectory)/Tests/UpdatedSettings.runsettings
  displayName: Remove temporary .runsettings file

You'll find a complete YAML file and a sample test project on GitHub.


问:
No serializer found for class org.hibernate.proxy.pojo.javassist.Javassist?
I am working on SpringMVC, Hibernate & JSON but I am getting this error.

```<code>HTTP Status 500 - Could not write JSON: No serializer found for class org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationConfig.SerializationFeature.FAIL_ON_EMPTY_BEANS) )
</code>```

Please check my Entity below

```<code>    @Entity
@Table(name="USERS")
public class User {

    @Id
    @GeneratedValue
    @Column(name="USER_ID")
    private Integer userId;

    @Column(name="USER_FIRST_NAME")
    private String firstName;

    @Column(name="USER_LAST_NAME")
    private String lastName;

    @Column(name="USER_MIDDLE_NAME")
    private String middleName;

    @Column(name="USER_EMAIL_ID")
    private String emailId;

    @Column(name="USER_PHONE_NO")
    private Integer phoneNo;

    @Column(name="USER_PASSWORD")
    private String password;

    @Column(name="USER_CONF_PASSWORD")
    private String  confPassword;

    @Transient
    private String token;

    @Column(name="USER_CREATED_ON")
    private Date createdOn;

    @OneToMany(fetch=FetchType.EAGER,cascade=CascadeType.ALL)
    @Fetch(value = FetchMode.SUBSELECT)
    @JoinTable(name = "USER_ROLES", joinColumns = { @JoinColumn(name = "USER_ID") }, inverseJoinColumns = { @JoinColumn(name = "ROLE_ID") })
    private List<ActifioRoles> userRole = new ArrayList<ActifioRoles>();

    @OneToMany(fetch=FetchType.EAGER,cascade=CascadeType.ALL,mappedBy="userDetails")
    @Fetch(value = FetchMode.SUBSELECT)
    private List<com.actifio.domain.Address> userAddress = new ArrayList<com.actifio.domain.Address>();

    @OneToOne(cascade=CascadeType.ALL)
    private Tenant tenantDetails;

    public Integer getUserId() {
        return userId;
    }
    public void setUserId(Integer userId) {
        this.userId = userId;
    }
    public String getFirstName() {
        return firstName;
    }
    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }
    public String getLastName() {
        return lastName;
    }
    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
    public String getEmailId() {
        return emailId;
    }
    public void setEmailId(String emailId) {
        this.emailId = emailId;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public String getConfPassword() {
        return confPassword;
    }
    public void setConfPassword(String confPassword) {
        this.confPassword = confPassword;
    }
    public Date getCreatedOn() {
        return createdOn;
    }
    public void setCreatedOn(Date createdOn) {
        this.createdOn = createdOn;
    }

    public List<ActifioRoles> getUserRole() {
        return userRole;
    }

    public void setUserRole(List<ActifioRoles> userRole) {
        this.userRole = userRole;
    }
    public String getMiddleName() {
        return middleName;
    }
    public void setMiddleName(String middleName) {
        this.middleName = middleName;
    }
    public Integer getPhoneNo() {
        return phoneNo;
    }
    public void setPhoneNo(Integer phoneNo) {
        this.phoneNo = phoneNo;
    }

    public List<com.actifio.domain.Address> getUserAddress() {
        return userAddress;
    }
    public void setUserAddress(List<com.actifio.domain.Address> userAddress) {
        this.userAddress = userAddress;
    }
    public Tenant getTenantDetails() {
        return tenantDetails;
    }
    public void setTenantDetails(Tenant tenantDetails) {
        this.tenantDetails = tenantDetails;
    }
    public String getToken() {
        return token;
    }
    public void setToken(String token) {
        this.token = token;
    }

    }
</code>```

How can I Solve this?

答:
The solution is inspired from the below solution by @marco. I have also updated his answer with these datails.

The problem here is about lazy loading of the sub-objects, where Jackson only finds hibernate proxies, instead of full blown objects.

So we are left with two options - Suppress the exception, like done above in most voted answer here, or make sure that the LazyLoad objects are loaded.

If you choose to go with latter option, solution would be to use jackson-datatype library, and configure the library to initialize lazy-load dependencies prior to the serialization.

I added a new config class to do that.

```<code>@Configuration
public class JacksonConfig extends WebMvcConfigurerAdapter {

@Bean
@Primary
public MappingJackson2HttpMessageConverter jacksonMessageConverter(){
    MappingJackson2HttpMessageConverter messageConverter = new MappingJackson2HttpMessageConverter();
    ObjectMapper mapper = new ObjectMapper();
    Hibernate5Module module = new Hibernate5Module();
    module.enable(Hibernate5Module.Feature.FORCE_LAZY_LOADING);
    mapper.registerModule(module);
    messageConverter.setObjectMapper(mapper);
    return messageConverter;
}
</code>```

}

@Primary makes sure that no other Jackson config is used for initializing any other beans. @Bean is as usual. module.enable(Hibernate5Module.Feature.FORCE_LAZY_LOADING); is to enable Lazy loading of the dependencies.

Caution - Please watch for its performance impact. sometimes EAGER fetch helps, but even if you make it eager, you are still going to need this code, because proxy objects still exist for all other Mappings except @OneToOne

PS : As a general comment, I would discourage the practice of sending whole data object back in the Json response, One should be using Dto's for this communication, and use some mapper like mapstruct to map them. This saves you from accidental security loopholes, as well as above exception.

Body:
I am working on SpringMVC, Hibernate & JSON but I am getting this error.

HTTP Status 500 - Could not write JSON: No serializer found for class org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationConfig.SerializationFeature.FAIL_ON_EMPTY_BEANS) )

Please check my Entity below

    @Entity
@Table(name="USERS")
public class User {

    @Id
    @GeneratedValue
    @Column(name="USER_ID")
    private Integer userId;

    @Column(name="USER_FIRST_NAME")
    private String firstName;

    @Column(name="USER_LAST_NAME")
    private String lastName;

    @Column(name="USER_MIDDLE_NAME")
    private String middleName;

    @Column(name="USER_EMAIL_ID")
    private String emailId;

    @Column(name="USER_PHONE_NO")
    private Integer phoneNo;

    @Column(name="USER_PASSWORD")
    private String password;

    @Column(name="USER_CONF_PASSWORD")
    private String  confPassword;

    @Transient
    private String token;

    @Column(name="USER_CREATED_ON")
    private Date createdOn;

    @OneToMany(fetch=FetchType.EAGER,cascade=CascadeType.ALL)
    @Fetch(value = FetchMode.SUBSELECT)
    @JoinTable(name = "USER_ROLES", joinColumns = { @JoinColumn(name = "USER_ID") }, inverseJoinColumns = { @JoinColumn(name = "ROLE_ID") })
    private List<ActifioRoles> userRole = new ArrayList<ActifioRoles>();

    @OneToMany(fetch=FetchType.EAGER,cascade=CascadeType.ALL,mappedBy="userDetails")
    @Fetch(value = FetchMode.SUBSELECT)
    private List<com.actifio.domain.Address> userAddress = new ArrayList<com.actifio.domain.Address>();

    @OneToOne(cascade=CascadeType.ALL)
    private Tenant tenantDetails;

    public Integer getUserId() {
        return userId;
    }
    public void setUserId(Integer userId) {
        this.userId = userId;
    }
    public String getFirstName() {
        return firstName;
    }
    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }
    public String getLastName() {
        return lastName;
    }
    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
    public String getEmailId() {
        return emailId;
    }
    public void setEmailId(String emailId) {
        this.emailId = emailId;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public String getConfPassword() {
        return confPassword;
    }
    public void setConfPassword(String confPassword) {
        this.confPassword = confPassword;
    }
    public Date getCreatedOn() {
        return createdOn;
    }
    public void setCreatedOn(Date createdOn) {
        this.createdOn = createdOn;
    }

    public List<ActifioRoles> getUserRole() {
        return userRole;
    }

    public void setUserRole(List<ActifioRoles> userRole) {
        this.userRole = userRole;
    }
    public String getMiddleName() {
        return middleName;
    }
    public void setMiddleName(String middleName) {
        this.middleName = middleName;
    }
    public Integer getPhoneNo() {
        return phoneNo;
    }
    public void setPhoneNo(Integer phoneNo) {
        this.phoneNo = phoneNo;
    }

    public List<com.actifio.domain.Address> getUserAddress() {
        return userAddress;
    }
    public void setUserAddress(List<com.actifio.domain.Address> userAddress) {
        this.userAddress = userAddress;
    }
    public Tenant getTenantDetails() {
        return tenantDetails;
    }
    public void setTenantDetails(Tenant tenantDetails) {
        this.tenantDetails = tenantDetails;
    }
    public String getToken() {
        return token;
    }
    public void setToken(String token) {
        this.token = token;
    }

    }

How can I Solve this?

Body:
The solution is inspired from the below solution by @marco. I have also updated his answer with these datails.

The problem here is about lazy loading of the sub-objects, where Jackson only finds hibernate proxies, instead of full blown objects.

So we are left with two options - Suppress the exception, like done above in most voted answer here, or make sure that the LazyLoad objects are loaded.

If you choose to go with latter option, solution would be to use jackson-datatype library, and configure the library to initialize lazy-load dependencies prior to the serialization.

I added a new config class to do that.

@Configuration
public class JacksonConfig extends WebMvcConfigurerAdapter {

@Bean
@Primary
public MappingJackson2HttpMessageConverter jacksonMessageConverter(){
    MappingJackson2HttpMessageConverter messageConverter = new MappingJackson2HttpMessageConverter();
    ObjectMapper mapper = new ObjectMapper();
    Hibernate5Module module = new Hibernate5Module();
    module.enable(Hibernate5Module.Feature.FORCE_LAZY_LOADING);
    mapper.registerModule(module);
    messageConverter.setObjectMapper(mapper);
    return messageConverter;
}

}

@Primary makes sure that no other Jackson config is used for initializing any other beans. @Bean is as usual. module.enable(Hibernate5Module.Feature.FORCE_LAZY_LOADING); is to enable Lazy loading of the dependencies.

Caution - Please watch for its performance impact. sometimes EAGER fetch helps, but even if you make it eager, you are still going to need this code, because proxy objects still exist for all other Mappings except @OneToOne

PS : As a general comment, I would discourage the practice of sending whole data object back in the Json response, One should be using Dto's for this communication, and use some mapper like mapstruct to map them. This saves you from accidental security loopholes, as well as above exception.


问:
Hosting for a medium sized Python/Django App
I'm planning to build an app with Python/Django with a web interface and web services providing data feeds for mobile apps.

The solution should be scaleable.
Since there is obviously no guarantee that a lot of people will use the service I can't really tell how big the project gonna become. But it should be at least designed to scale quite a bit.

The data being served will mostly be text and pictures, so no need for the real heavy stuff for things like video or audio streaming, real time search and so on.

My question is, what host (best based in Europe) would you recommend?
I'm not so confident using Appengine due to evental lock-in effects and its data base restrictions. But if anyone can share good experiences with it, let me hear them.

答:
If you are comfortable with setting up the server yourself, you can use http://linode.com, they are a US company with servers in the UK.

Here you can scale up the resources of the server very easily.


问:
Select data where condition matches and if none, then select all?

select * from (values
    ('dept1','user1'),
    ('dept2','user2'),
    ('dept3','user3'),
    ('dept4','user4')
    )table1([department],[user])
where [user] = @id
```

<p>scenario1:
     @id = 'user1'</p>

```dept1
```

<p>scenario2:
    @id = 'user5'</p>

```dept1
dept2
dept3
dept4
```

<p>this is what it looks like from a noobish query</p>

<pre class="lang-sql prettyprint-override"><code>declare @id varchar(12) = 'user1'
declare @var int = (select count(*) from table1 where [user] = @id)

select * from table1 where [user] = @id or @var = 0
</code>```

答:
I would do this with a simple OR, not a CASE expression in the WHERE.

In general, you want to avoid CASE expressions in the WHERE clause for several reasons:

The logic can almost be written concisely using basic boolean operations.

Adding additional constructs (in addition to AND, OR, and NOT) just makes the logic harder for people to follow.

It pretty much kills any optimization paths.

I would suggest:

```<code>with table1 as
      select v.*
      from (values ('dept1', 'user1'),
                   ('dept2', 'user2'),
                   ('dept3', 'user3'),
                   ('dept4', 'user4')
           ) v([department], [user])
     )
select t1.*
from table1 t1
where t1.[user] = @id or
      not exists (select 1 from table1 t1 where t1.user = @id);
</code>```

Body:
select * from (values
    ('dept1','user1'),
    ('dept2','user2'),
    ('dept3','user3'),
    ('dept4','user4')
    )table1([department],[user])
where [user] = @id

scenario1:
     @id = 'user1'

dept1

scenario2:
    @id = 'user5'

dept1
dept2
dept3
dept4

this is what it looks like from a noobish query

declare @id varchar(12) = 'user1'
declare @var int = (select count(*) from table1 where [user] = @id)

select * from table1 where [user] = @id or @var = 0

Body:
I would do this with a simple OR, not a CASE expression in the WHERE.

In general, you want to avoid CASE expressions in the WHERE clause for several reasons:

The logic can almost be written concisely using basic boolean operations.

Adding additional constructs (in addition to AND, OR, and NOT) just makes the logic harder for people to follow.

It pretty much kills any optimization paths.

I would suggest:

with table1 as
      select v.*
      from (values ('dept1', 'user1'),
                   ('dept2', 'user2'),
                   ('dept3', 'user3'),
                   ('dept4', 'user4')
           ) v([department], [user])
     )
select t1.*
from table1 t1
where t1.[user] = @id or
      not exists (select 1 from table1 t1 where t1.user = @id);