问:
Error parsing data org.json.JSONException: End of input at character 0 of - Android
I'm developing a test Android application that must display some data from a mysql db.
Here my logs:

```<code>05-22 17:10:56.865: E/JSON Parser(31648): Error parsing data org.json.JSONException: End of input at character 0 of
05-22 17:10:56.865: W/dalvikvm(31648): threadid=11: thread exiting with uncaught exception (group=0x418e3da0)
05-22 17:10:56.875: E/AndroidRuntime(31648): FATAL EXCEPTION: AsyncTask #1
05-22 17:10:56.875: E/AndroidRuntime(31648): Process: com.example.androidhive, PID: 31648
05-22 17:10:56.875: E/AndroidRuntime(31648): java.lang.RuntimeException: An error occured while executing doInBackground()
05-22 17:10:56.875: E/AndroidRuntime(31648):    at android.os.AsyncTask$3.done(AsyncTask.java:300)
05-22 17:10:56.875: E/AndroidRuntime(31648):    at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
05-22 17:10:56.875: E/AndroidRuntime(31648):    at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
05-22 17:10:56.875: E/AndroidRuntime(31648):    at java.util.concurrent.FutureTask.run(FutureTask.java:242)
05-22 17:10:56.875: E/AndroidRuntime(31648):    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
05-22 17:10:56.875: E/AndroidRuntime(31648):    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
05-22 17:10:56.875: E/AndroidRuntime(31648):    at java.lang.Thread.run(Thread.java:841)
05-22 17:10:56.875: E/AndroidRuntime(31648): Caused by: java.lang.NullPointerException
05-22 17:10:56.875: E/AndroidRuntime(31648):    at com.example.androidhive.AllProductsActivity$LoadAllProducts.doInBackground(AllProductsActivity.java:130)
05-22 17:10:56.875: E/AndroidRuntime(31648):    at com.example.androidhive.AllProductsActivity$LoadAllProducts.doInBackground(AllProductsActivity.java:1)
05-22 17:10:56.875: E/AndroidRuntime(31648):    at android.os.AsyncTask$2.call(AsyncTask.java:288)
05-22 17:10:56.875: E/AndroidRuntime(31648):    at java.util.concurrent.FutureTask.run(FutureTask.java:237)
05-22 17:10:56.875: E/AndroidRuntime(31648):    ... 3 more
05-22 17:10:57.436: D/AbsListView(31648): onDetachedFromWindow
05-22 17:10:57.436: D/AbsListView(31648): unregisterIRListener() is called
05-22 17:10:57.446: E/WindowManager(31648): android.view.WindowLeaked: Activity com.example.androidhive.AllProductsActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{42c02238 V.E..... R.....ID 0,0-914,346} that was originally added here
05-22 17:10:57.446: E/WindowManager(31648):     at android.view.ViewRootImpl.<init>(ViewRootImpl.java:456)
05-22 17:10:57.446: E/WindowManager(31648):     at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:267)
05-22 17:10:57.446: E/WindowManager(31648):     at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
05-22 17:10:57.446: E/WindowManager(31648):     at android.app.Dialog.show(Dialog.java:288)
05-22 17:10:57.446: E/WindowManager(31648):     at com.example.androidhive.AllProductsActivity$LoadAllProducts.onPreExecute(AllProductsActivity.java:117)
05-22 17:10:57.446: E/WindowManager(31648):     at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:587)
05-22 17:10:57.446: E/WindowManager(31648):     at android.os.AsyncTask.execute(AsyncTask.java:535)
05-22 17:10:57.446: E/WindowManager(31648):     at com.example.androidhive.AllProductsActivity.onCreate(AllProductsActivity.java:57)
05-22 17:10:57.446: E/WindowManager(31648):     at android.app.Activity.performCreate(Activity.java:5426)
05-22 17:10:57.446: E/WindowManager(31648):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
05-22 17:10:57.446: E/WindowManager(31648):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2269)
05-22 17:10:57.446: E/WindowManager(31648):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2363)
05-22 17:10:57.446: E/WindowManager(31648):     at android.app.ActivityThread.access$900(ActivityThread.java:161)
05-22 17:10:57.446: E/WindowManager(31648):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1265)
05-22 17:10:57.446: E/WindowManager(31648):     at android.os.Handler.dispatchMessage(Handler.java:102)
05-22 17:10:57.446: E/WindowManager(31648):     at android.os.Looper.loop(Looper.java:157)
05-22 17:10:57.446: E/WindowManager(31648):     at android.app.ActivityThread.main(ActivityThread.java:5356)
05-22 17:10:57.446: E/WindowManager(31648):     at java.lang.reflect.Method.invokeNative(Native Method)
05-22 17:10:57.446: E/WindowManager(31648):     at java.lang.reflect.Method.invoke(Method.java:515)
05-22 17:10:57.446: E/WindowManager(31648):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1265)
05-22 17:10:57.446: E/WindowManager(31648):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081)
05-22 17:10:57.446: E/WindowManager(31648):     at dalvik.system.NativeStart.main(Native Method)
05-22 17:11:01.279: I/Process(31648): Sending signal. PID: 31648 SIG: 9
</code>```

Here the class JSONParser.java

```<code>package com.example.androidhive;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

public class JSONParser {

    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";

    // constructor
    public JSONParser() {

    }

    // function get json from url
    // by making HTTP POST or GET mehtod
    public JSONObject makeHttpRequest(String url, String method,
            List<NameValuePair> params) {

        // Making HTTP request
        try {

            // check for request method
            if(method == "POST"){
                // request method is POST
                // defaultHttpClient
                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost(url);
                httpPost.setEntity(new UrlEncodedFormEntity(params));

                HttpResponse httpResponse = httpClient.execute(httpPost);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();

            }else if(method == "GET"){
                // request method is GET
                DefaultHttpClient httpClient = new DefaultHttpClient();
                String paramString = URLEncodedUtils.format(params, "utf-8");
                url += "?" + paramString;
                HttpGet httpGet = new HttpGet(url);

                HttpResponse httpResponse = httpClient.execute(httpGet);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();
            }
</code>```

Here the class I use to display the selected data:

```<code>package com.example.androidhive;

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

import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

public class AllProductsActivity extends ListActivity {

    // Progress Dialog
    private ProgressDialog pDialog;

    // Creating JSON Parser object
    JSONParser jParser = new JSONParser();

    ArrayList<HashMap<String, String>> productsList;

    // url to get all products list
    private static String url_all_products = "http://10.1.20.10/android/get_all_products.php";

    // JSON Node names
    private static final String TAG_SUCCESS = "success";
    private static final String TAG_PRODUCTS = "products";
    private static final String TAG_PID = "pid";
    private static final String TAG_NAME = "name";

    // products JSONArray
    JSONArray products = null;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.all_products);

        // Hashmap for ListView
        productsList = new ArrayList<HashMap<String, String>>();

        // Loading products in Background Thread
        new LoadAllProducts().execute();

        // Get listview
        ListView lv = getListView();

        // on seleting single product
        // launching Edit Product Screen
        lv.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
                // getting values from selected ListItem
                String pid = ((TextView) view.findViewById(R.id.pid)).getText()
                        .toString();

                // Starting new intent
                Intent in = new Intent(getApplicationContext(),
                        EditProductActivity.class);
                // sending pid to next activity
                in.putExtra(TAG_PID, pid);

                // starting new activity and expecting some response back
                startActivityForResult(in, 100);
            }
        });

    }

    // Response from Edit Product Activity
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // if result code 100
        if (resultCode == 100) {
            // if result code 100 is received
            // means user edited/deleted product
            // reload this screen again
            Intent intent = getIntent();
            finish();
            startActivity(intent);
        }

    }

    /**
     * Background Async Task to Load all product by making HTTP Request
     * */
    class LoadAllProducts extends AsyncTask<String, String, String> {

        /**
         * Before starting background thread Show Progress Dialog
         * */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(AllProductsActivity.this);
            pDialog.setMessage("Loading products. Please wait...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
            pDialog.show();
        }

        /**
         * getting All products from url
         * */
        protected String doInBackground(String... args) {
            // Building Parameters
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            // getting JSON string from URL
            JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);

            // Check your log cat for JSON reponse
            Log.d("All Products: ", json.toString());

            try {
                // Checking for SUCCESS TAG
                int success = json.getInt(TAG_SUCCESS);

                if (success == 1) {
                    // products found
                    // Getting Array of Products
                    products = json.getJSONArray(TAG_PRODUCTS);

                    // looping through All Products
                    for (int i = 0; i < products.length(); i++) {
                        JSONObject c = products.getJSONObject(i);

                        // Storing each json item in variable
                        String id = c.getString(TAG_PID);
                        String name = c.getString(TAG_NAME);

                        // creating new HashMap
                        HashMap<String, String> map = new HashMap<String, String>();

                        // adding each child node to HashMap key => value
                        map.put(TAG_PID, id);
                        map.put(TAG_NAME, name);

                        // adding HashList to ArrayList
                        productsList.add(map);
                    }
                } else {
                    // no products found
                    // Launch Add New product Activity
                    Intent i = new Intent(getApplicationContext(),
                            NewProductActivity.class);
                    // Closing all previous activities
                    i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    startActivity(i);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

            return null;
        }

        /**
         * After completing background task Dismiss the progress dialog
         * **/
        protected void onPostExecute(String file_url) {
            // dismiss the dialog after getting all products
            pDialog.dismiss();
            // updating UI from Background Thread
            runOnUiThread(new Runnable() {
                public void run() {
                    /**
                     * Updating parsed JSON data into ListView
                     * */
                    ListAdapter adapter = new SimpleAdapter(
                            AllProductsActivity.this, productsList,
                            R.layout.list_item, new String[] { TAG_PID,
                                    TAG_NAME},
                            new int[] { R.id.pid, R.id.name });
                    // updating listview
                    setListAdapter(adapter);
                }
            });

        }

    }
}
</code>```

Here the php file:

```<code>get_all_products.php
<?php

/*
 * Following code will list all the products
 */

// array for JSON response
$response = array();

// include db connect class
require_once __DIR__ . '/db_connect.php';

// connecting to db
$db = new DB_CONNECT();

// get all products from products table
$result = mysql_query("SELECT *FROM products") or die(mysql_error());

// check for empty result
if (mysql_num_rows($result) > 0) {
    // looping through all results
    // products node
    $response["products"] = array();

    while ($row = mysql_fetch_array($result)) {
        // temp user array
        $product = array();
        $product["pid"] = $row["pid"];
        $product["name"] = $row["name"];
        $product["price"] = $row["price"];
        $product["created_at"] = $row["created_at"];
        $product["updated_at"] = $row["updated_at"];

        // push single product into final response array
        array_push($response["products"], $product);
    }
    // success
    $response["success"] = 1;

    // echoing JSON response
    echo json_encode($response);
} else {
    // no products found
    $response["success"] = 0;
    $response["message"] = "No products found";

    // echo no users JSON
    echo json_encode($response);
}
?>
</code>```

In addition, here the main Activity:

```<code>package com.example.androidhive;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainScreenActivity extends Activity{

    Button btnViewProducts;
    Button btnNewProduct;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_screen);

        // Buttons
        btnViewProducts = (Button) findViewById(R.id.btnViewProducts);
        btnNewProduct = (Button) findViewById(R.id.btnCreateProduct);

        // view products click event
        btnViewProducts.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                // Launching All products Activity
                Intent i = new Intent(getApplicationContext(), AllProductsActivity.class);
                startActivity(i);

            }
        });

        // view products click event
        btnNewProduct.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                // Launching create new product activity
                Intent i = new Intent(getApplicationContext(), NewProductActivity.class);
                startActivity(i);

            }
        });
    }

}
</code>```

I read various thread around the internet about this error, but it is even caused by differents problems, and I did not found a case similar to mine or a solution that solved my problem.

答:
UTF_8 encoding helped me survived
just use it like

```<code>$conn = mysqli_connect($HostName,$HostUser,$HostPass,$DatabaseName);
mysqli_set_charset($conn, 'utf8');
</code>```

reference https://stackoverflow.com/a/53425156/3405331

Body:
I'm developing a test Android application that must display some data from a mysql db.
Here my logs:

05-22 17:10:56.865: E/JSON Parser(31648): Error parsing data org.json.JSONException: End of input at character 0 of
05-22 17:10:56.865: W/dalvikvm(31648): threadid=11: thread exiting with uncaught exception (group=0x418e3da0)
05-22 17:10:56.875: E/AndroidRuntime(31648): FATAL EXCEPTION: AsyncTask #1
05-22 17:10:56.875: E/AndroidRuntime(31648): Process: com.example.androidhive, PID: 31648
05-22 17:10:56.875: E/AndroidRuntime(31648): java.lang.RuntimeException: An error occured while executing doInBackground()
05-22 17:10:56.875: E/AndroidRuntime(31648):    at android.os.AsyncTask$3.done(AsyncTask.java:300)
05-22 17:10:56.875: E/AndroidRuntime(31648):    at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
05-22 17:10:56.875: E/AndroidRuntime(31648):    at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
05-22 17:10:56.875: E/AndroidRuntime(31648):    at java.util.concurrent.FutureTask.run(FutureTask.java:242)
05-22 17:10:56.875: E/AndroidRuntime(31648):    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
05-22 17:10:56.875: E/AndroidRuntime(31648):    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
05-22 17:10:56.875: E/AndroidRuntime(31648):    at java.lang.Thread.run(Thread.java:841)
05-22 17:10:56.875: E/AndroidRuntime(31648): Caused by: java.lang.NullPointerException
05-22 17:10:56.875: E/AndroidRuntime(31648):    at com.example.androidhive.AllProductsActivity$LoadAllProducts.doInBackground(AllProductsActivity.java:130)
05-22 17:10:56.875: E/AndroidRuntime(31648):    at com.example.androidhive.AllProductsActivity$LoadAllProducts.doInBackground(AllProductsActivity.java:1)
05-22 17:10:56.875: E/AndroidRuntime(31648):    at android.os.AsyncTask$2.call(AsyncTask.java:288)
05-22 17:10:56.875: E/AndroidRuntime(31648):    at java.util.concurrent.FutureTask.run(FutureTask.java:237)
05-22 17:10:56.875: E/AndroidRuntime(31648):    ... 3 more
05-22 17:10:57.436: D/AbsListView(31648): onDetachedFromWindow
05-22 17:10:57.436: D/AbsListView(31648): unregisterIRListener() is called
05-22 17:10:57.446: E/WindowManager(31648): android.view.WindowLeaked: Activity com.example.androidhive.AllProductsActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{42c02238 V.E..... R.....ID 0,0-914,346} that was originally added here
05-22 17:10:57.446: E/WindowManager(31648):     at android.view.ViewRootImpl.<init>(ViewRootImpl.java:456)
05-22 17:10:57.446: E/WindowManager(31648):     at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:267)
05-22 17:10:57.446: E/WindowManager(31648):     at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
05-22 17:10:57.446: E/WindowManager(31648):     at android.app.Dialog.show(Dialog.java:288)
05-22 17:10:57.446: E/WindowManager(31648):     at com.example.androidhive.AllProductsActivity$LoadAllProducts.onPreExecute(AllProductsActivity.java:117)
05-22 17:10:57.446: E/WindowManager(31648):     at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:587)
05-22 17:10:57.446: E/WindowManager(31648):     at android.os.AsyncTask.execute(AsyncTask.java:535)
05-22 17:10:57.446: E/WindowManager(31648):     at com.example.androidhive.AllProductsActivity.onCreate(AllProductsActivity.java:57)
05-22 17:10:57.446: E/WindowManager(31648):     at android.app.Activity.performCreate(Activity.java:5426)
05-22 17:10:57.446: E/WindowManager(31648):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
05-22 17:10:57.446: E/WindowManager(31648):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2269)
05-22 17:10:57.446: E/WindowManager(31648):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2363)
05-22 17:10:57.446: E/WindowManager(31648):     at android.app.ActivityThread.access$900(ActivityThread.java:161)
05-22 17:10:57.446: E/WindowManager(31648):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1265)
05-22 17:10:57.446: E/WindowManager(31648):     at android.os.Handler.dispatchMessage(Handler.java:102)
05-22 17:10:57.446: E/WindowManager(31648):     at android.os.Looper.loop(Looper.java:157)
05-22 17:10:57.446: E/WindowManager(31648):     at android.app.ActivityThread.main(ActivityThread.java:5356)
05-22 17:10:57.446: E/WindowManager(31648):     at java.lang.reflect.Method.invokeNative(Native Method)
05-22 17:10:57.446: E/WindowManager(31648):     at java.lang.reflect.Method.invoke(Method.java:515)
05-22 17:10:57.446: E/WindowManager(31648):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1265)
05-22 17:10:57.446: E/WindowManager(31648):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081)
05-22 17:10:57.446: E/WindowManager(31648):     at dalvik.system.NativeStart.main(Native Method)
05-22 17:11:01.279: I/Process(31648): Sending signal. PID: 31648 SIG: 9

Here the class JSONParser.java

package com.example.androidhive;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

public class JSONParser {

    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";

    // constructor
    public JSONParser() {

    }

    // function get json from url
    // by making HTTP POST or GET mehtod
    public JSONObject makeHttpRequest(String url, String method,
            List<NameValuePair> params) {

        // Making HTTP request
        try {

            // check for request method
            if(method == "POST"){
                // request method is POST
                // defaultHttpClient
                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost(url);
                httpPost.setEntity(new UrlEncodedFormEntity(params));

                HttpResponse httpResponse = httpClient.execute(httpPost);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();

            }else if(method == "GET"){
                // request method is GET
                DefaultHttpClient httpClient = new DefaultHttpClient();
                String paramString = URLEncodedUtils.format(params, "utf-8");
                url += "?" + paramString;
                HttpGet httpGet = new HttpGet(url);

                HttpResponse httpResponse = httpClient.execute(httpGet);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();
            }

Here the class I use to display the selected data:

package com.example.androidhive;

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

import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

public class AllProductsActivity extends ListActivity {

    // Progress Dialog
    private ProgressDialog pDialog;

    // Creating JSON Parser object
    JSONParser jParser = new JSONParser();

    ArrayList<HashMap<String, String>> productsList;

    // url to get all products list
    private static String url_all_products = "http://10.1.20.10/android/get_all_products.php";

    // JSON Node names
    private static final String TAG_SUCCESS = "success";
    private static final String TAG_PRODUCTS = "products";
    private static final String TAG_PID = "pid";
    private static final String TAG_NAME = "name";

    // products JSONArray
    JSONArray products = null;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.all_products);

        // Hashmap for ListView
        productsList = new ArrayList<HashMap<String, String>>();

        // Loading products in Background Thread
        new LoadAllProducts().execute();

        // Get listview
        ListView lv = getListView();

        // on seleting single product
        // launching Edit Product Screen
        lv.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
                // getting values from selected ListItem
                String pid = ((TextView) view.findViewById(R.id.pid)).getText()
                        .toString();

                // Starting new intent
                Intent in = new Intent(getApplicationContext(),
                        EditProductActivity.class);
                // sending pid to next activity
                in.putExtra(TAG_PID, pid);

                // starting new activity and expecting some response back
                startActivityForResult(in, 100);
            }
        });

    }

    // Response from Edit Product Activity
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // if result code 100
        if (resultCode == 100) {
            // if result code 100 is received
            // means user edited/deleted product
            // reload this screen again
            Intent intent = getIntent();
            finish();
            startActivity(intent);
        }

    }

    /**
     * Background Async Task to Load all product by making HTTP Request
     * */
    class LoadAllProducts extends AsyncTask<String, String, String> {

        /**
         * Before starting background thread Show Progress Dialog
         * */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(AllProductsActivity.this);
            pDialog.setMessage("Loading products. Please wait...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
            pDialog.show();
        }

        /**
         * getting All products from url
         * */
        protected String doInBackground(String... args) {
            // Building Parameters
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            // getting JSON string from URL
            JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);

            // Check your log cat for JSON reponse
            Log.d("All Products: ", json.toString());

            try {
                // Checking for SUCCESS TAG
                int success = json.getInt(TAG_SUCCESS);

                if (success == 1) {
                    // products found
                    // Getting Array of Products
                    products = json.getJSONArray(TAG_PRODUCTS);

                    // looping through All Products
                    for (int i = 0; i < products.length(); i++) {
                        JSONObject c = products.getJSONObject(i);

                        // Storing each json item in variable
                        String id = c.getString(TAG_PID);
                        String name = c.getString(TAG_NAME);

                        // creating new HashMap
                        HashMap<String, String> map = new HashMap<String, String>();

                        // adding each child node to HashMap key => value
                        map.put(TAG_PID, id);
                        map.put(TAG_NAME, name);

                        // adding HashList to ArrayList
                        productsList.add(map);
                    }
                } else {
                    // no products found
                    // Launch Add New product Activity
                    Intent i = new Intent(getApplicationContext(),
                            NewProductActivity.class);
                    // Closing all previous activities
                    i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    startActivity(i);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

            return null;
        }

        /**
         * After completing background task Dismiss the progress dialog
         * **/
        protected void onPostExecute(String file_url) {
            // dismiss the dialog after getting all products
            pDialog.dismiss();
            // updating UI from Background Thread
            runOnUiThread(new Runnable() {
                public void run() {
                    /**
                     * Updating parsed JSON data into ListView
                     * */
                    ListAdapter adapter = new SimpleAdapter(
                            AllProductsActivity.this, productsList,
                            R.layout.list_item, new String[] { TAG_PID,
                                    TAG_NAME},
                            new int[] { R.id.pid, R.id.name });
                    // updating listview
                    setListAdapter(adapter);
                }
            });

        }

    }
}

Here the php file:

get_all_products.php
<?php

/*
 * Following code will list all the products
 */

// array for JSON response
$response = array();

// include db connect class
require_once __DIR__ . '/db_connect.php';

// connecting to db
$db = new DB_CONNECT();

// get all products from products table
$result = mysql_query("SELECT *FROM products") or die(mysql_error());

// check for empty result
if (mysql_num_rows($result) > 0) {
    // looping through all results
    // products node
    $response["products"] = array();

    while ($row = mysql_fetch_array($result)) {
        // temp user array
        $product = array();
        $product["pid"] = $row["pid"];
        $product["name"] = $row["name"];
        $product["price"] = $row["price"];
        $product["created_at"] = $row["created_at"];
        $product["updated_at"] = $row["updated_at"];

        // push single product into final response array
        array_push($response["products"], $product);
    }
    // success
    $response["success"] = 1;

    // echoing JSON response
    echo json_encode($response);
} else {
    // no products found
    $response["success"] = 0;
    $response["message"] = "No products found";

    // echo no users JSON
    echo json_encode($response);
}
?>

In addition, here the main Activity:

package com.example.androidhive;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainScreenActivity extends Activity{

    Button btnViewProducts;
    Button btnNewProduct;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_screen);

        // Buttons
        btnViewProducts = (Button) findViewById(R.id.btnViewProducts);
        btnNewProduct = (Button) findViewById(R.id.btnCreateProduct);

        // view products click event
        btnViewProducts.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                // Launching All products Activity
                Intent i = new Intent(getApplicationContext(), AllProductsActivity.class);
                startActivity(i);

            }
        });

        // view products click event
        btnNewProduct.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                // Launching create new product activity
                Intent i = new Intent(getApplicationContext(), NewProductActivity.class);
                startActivity(i);

            }
        });
    }

}

I read various thread around the internet about this error, but it is even caused by differents problems, and I did not found a case similar to mine or a solution that solved my problem.

Body:
UTF_8 encoding helped me survived
just use it like

$conn = mysqli_connect($HostName,$HostUser,$HostPass,$DatabaseName);
mysqli_set_charset($conn, 'utf8');

reference https://stackoverflow.com/a/53425156/3405331


来源: stackexchange

问:
How to fetch data from app registrations in Azure with status which says expiring soon
I would like to fetch data of apps from app registrations of which certificates with status are expiring soon.

If anyone could help with PowerShell script or any other way of fetching the data please help

答:
We have tried with the above requirement and able to fetch the details of certificate and secrets which will expire soon.

PowerShell script:-

```<code>Connect-AzureAD
$expiresWithinDays = 31
$expired = Get-AzureADApplication -All:$true | ForEach-Object {
$app = $_
@(
Get-AzureADApplicationPasswordCredential -ObjectId $_.ObjectId
Get-AzureADApplicationKeyCredential -ObjectId $_.ObjectId
) | Where-Object {
$_.EndDate -lt (Get-Date).AddDays($expiresWithinDays)
} | ForEach-Object {
$id = "Not set"
if($_.CustomKeyIdentifier) {
$id = [System.Text.Encoding]::UTF8.GetString($_.CustomKeyIdentifier)
}
[PSCustomObject] @{
App = $app.DisplayName
ObjectID = $app.ObjectId
AppId = $app.AppId
Type = $_.GetType().name
KeyIdentifier = $id
EndDate = $_.EndDate
}
}
}

$expired | Out-GridView
</code>```

SAMPLE OUTPUT:-

For more information please refer this Blog.

ContentLicense: CC BY-SA 4.0

Body:
We have tried with the above requirement and able to fetch the details of certificate and secrets which will expire soon.

PowerShell script:-

Connect-AzureAD
$expiresWithinDays = 31
$expired = Get-AzureADApplication -All:$true | ForEach-Object {
$app = $_
@(
Get-AzureADApplicationPasswordCredential -ObjectId $_.ObjectId
Get-AzureADApplicationKeyCredential -ObjectId $_.ObjectId
) | Where-Object {
$_.EndDate -lt (Get-Date).AddDays($expiresWithinDays)
} | ForEach-Object {
$id = "Not set"
if($_.CustomKeyIdentifier) {
$id = [System.Text.Encoding]::UTF8.GetString($_.CustomKeyIdentifier)
}
[PSCustomObject] @{
App = $app.DisplayName
ObjectID = $app.ObjectId
AppId = $app.AppId
Type = $_.GetType().name
KeyIdentifier = $id
EndDate = $_.EndDate
}
}
}

$expired | Out-GridView

SAMPLE OUTPUT:-

For more information please refer this Blog.


问:
How to get Expo Audio Recording Content as Base64?
I am trying to use the recording mp4 content as base64 buffer and send to rest api.

import { StatusBar } from 'expo-status-bar';
import React from 'react';
import { Button, StyleSheet, Text, View } from 'react-native';
import { Audio } from 'expo-av';
import axios     from 'axios';
import base64 from 'react-native-base64'

export default function App() {
  const [recording, setRecording] = React.useState();
  const [recordings, setRecordings] = React.useState([]);
  const [message, setMessage] = React.useState("");

  async function startRecording() {
    try {
      const permission = await Audio.requestPermissionsAsync();

      if (permission.status === "granted") {
        await Audio.setAudioModeAsync({
          allowsRecordingIOS: true,
          playsInSilentModeIOS: true
        });

        const RECORDING_OPTIONS_PRESET_HIGH_QUALITY: RecordingOptions = {
                android: {
                    extension: '.mp4',
                    outputFormat: Audio.RECORDING_OPTION_ANDROID_OUTPUT_FORMAT_MPEG_4,
                    audioEncoder: Audio.RECORDING_OPTION_ANDROID_AUDIO_ENCODER_AMR_NB,
                    sampleRate: 44100,
                    numberOfChannels: 2,
                    bitRate: 128000,
                },
                ios: {
                    extension: '.wav',
                    audioQuality: Audio.RECORDING_OPTION_IOS_AUDIO_QUALITY_MIN,
                    sampleRate: 44100,
                    numberOfChannels: 2,
                    bitRate: 128000,
                    linearPCMBitDepth: 16,
                    linearPCMIsBigEndian: false,
                    linearPCMIsFloat: false,
                },
            };

        const { recording } = await Audio.Recording.createAsync(
          RECORDING_OPTIONS_PRESET_HIGH_QUALITY
        );

        setRecording(recording);
      } else {
        setMessage("Please grant permission to app to access microphone");
      }
    } catch (err) {
      console.error('Failed to start recording', err);
    }
  }

  async function stopRecording() {
    setRecording(undefined);
    await recording.stopAndUnloadAsync();

    let updatedRecordings = [...recordings];
    const { sound, status } = await recording.createNewLoadedSoundAsync();
    updatedRecordings.push({
      sound: sound,
      duration: getDurationFormatted(status.durationMillis),
      file: recording.getURI()
    });
    setRecordings(updatedRecordings);
    //const response = await axios.post('http://192.18.0.4:8000/audio', base64.encode(sound));
    console.log(sound);
  }

  function getDurationFormatted(millis) {
    const minutes = millis / 1000 / 60;
    const minutesDisplay = Math.floor(minutes);
    const seconds = Math.round((minutes - minutesDisplay) * 60);
    const secondsDisplay = seconds < 10 ? `0${seconds}` : seconds;
    return `${minutesDisplay}:${secondsDisplay}`;
  }

  function getRecordingLines() {
    console.log(recordings);
    return recordings.map((recordingLine, index) => {
      return (
        <View key={index} style={styles.row}>
          <Text style={styles.fill}>Recording {index + 1} - {recordingLine.duration}</Text>
          <Button style={styles.button} onPress={() => {recordingLine.sound.replayAsync();
                                                        console.log(recordingLine);}} title="Play"></Button>
        </View>
      );
    });
  }

  return (
    <View style={styles.container}>
      <Text>{message}</Text>
      <Button
        title={recording ? 'Stop Recording' : 'Start Recording'}
        onPress={recording ? stopRecording : startRecording} />
      {getRecordingLines()}
      <StatusBar style="auto" />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
  row: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
  },
  fill: {
    flex: 1,
    margin: 16
  },
  button: {
    margin: 16
  }
});```

How to find the audio content instead of file path? For example, In the stopRecording() function, I want to send the recorded audio buffer to the URL. The getURI() returns a file path which is not the content. Is there any way to convert the content as byte array ? Thank you in advanced

答:
The common way to upload any file format from device file manager to server is through binary data mostly a binary large object (BLOB) then encode to any file final format (MP3, WAV, and more).

  async function stopRecording() {
  setRecording(undefined);
  await recording.stopAndUnloadAsync();

  let updatedRecordings = [...recordings];
  const { sound, status } = await recording.createNewLoadedSoundAsync();
  updatedRecordings.push({
    sound: sound,
    duration: getDurationFormatted(status.durationMillis),
    file: recording.getURI(),
  });
  setRecordings(updatedRecordings);

  // utitlity function to convert BLOB to BASE64
  const blobToBase64 = (blob) => {
    const reader = new FileReader();
    reader.readAsDataURL(blob);
    return new Promise((resolve) => {
      reader.onloadend = () => {
        resolve(reader.result);
      };
    });
  };

  // Fetch audio binary blob data

  const audioURI = recording.getURI();
  const blob = await new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest();
    xhr.onload = function () {
      resolve(xhr.response);
    };
    xhr.onerror = function (e) {
      reject(new TypeError("Network request failed"));
    };
    xhr.responseType = "blob";
    xhr.open("GET", audioURI, true);
    xhr.send(null);
  });

  const audioBase64 = await blobToBase64(blob);

  const response = await axios.post(
    "http://192.18.0.4:8000/audio",
    base64.encode(audioBase64)
  );

// We're done with the blob and file uploading, close and release it
  blob.close()
}

```

Body:
I am trying to use the recording mp4 content as base64 buffer and send to rest api.

import { StatusBar } from 'expo-status-bar';
import React from 'react';
import { Button, StyleSheet, Text, View } from 'react-native';
import { Audio } from 'expo-av';
import axios     from 'axios';
import base64 from 'react-native-base64'

export default function App() {
  const [recording, setRecording] = React.useState();
  const [recordings, setRecordings] = React.useState([]);
  const [message, setMessage] = React.useState("");

  async function startRecording() {
    try {
      const permission = await Audio.requestPermissionsAsync();

      if (permission.status === "granted") {
        await Audio.setAudioModeAsync({
          allowsRecordingIOS: true,
          playsInSilentModeIOS: true
        });

        const RECORDING_OPTIONS_PRESET_HIGH_QUALITY: RecordingOptions = {
                android: {
                    extension: '.mp4',
                    outputFormat: Audio.RECORDING_OPTION_ANDROID_OUTPUT_FORMAT_MPEG_4,
                    audioEncoder: Audio.RECORDING_OPTION_ANDROID_AUDIO_ENCODER_AMR_NB,
                    sampleRate: 44100,
                    numberOfChannels: 2,
                    bitRate: 128000,
                },
                ios: {
                    extension: '.wav',
                    audioQuality: Audio.RECORDING_OPTION_IOS_AUDIO_QUALITY_MIN,
                    sampleRate: 44100,
                    numberOfChannels: 2,
                    bitRate: 128000,
                    linearPCMBitDepth: 16,
                    linearPCMIsBigEndian: false,
                    linearPCMIsFloat: false,
                },
            };

        const { recording } = await Audio.Recording.createAsync(
          RECORDING_OPTIONS_PRESET_HIGH_QUALITY
        );

        setRecording(recording);
      } else {
        setMessage("Please grant permission to app to access microphone");
      }
    } catch (err) {
      console.error('Failed to start recording', err);
    }
  }

  async function stopRecording() {
    setRecording(undefined);
    await recording.stopAndUnloadAsync();

    let updatedRecordings = [...recordings];
    const { sound, status } = await recording.createNewLoadedSoundAsync();
    updatedRecordings.push({
      sound: sound,
      duration: getDurationFormatted(status.durationMillis),
      file: recording.getURI()
    });
    setRecordings(updatedRecordings);
    //const response = await axios.post('http://192.18.0.4:8000/audio', base64.encode(sound));
    console.log(sound);
  }

  function getDurationFormatted(millis) {
    const minutes = millis / 1000 / 60;
    const minutesDisplay = Math.floor(minutes);
    const seconds = Math.round((minutes - minutesDisplay) * 60);
    const secondsDisplay = seconds < 10 ? `0${seconds}` : seconds;
    return `${minutesDisplay}:${secondsDisplay}`;
  }

  function getRecordingLines() {
    console.log(recordings);
    return recordings.map((recordingLine, index) => {
      return (
        <View key={index} style={styles.row}>
          <Text style={styles.fill}>Recording {index + 1} - {recordingLine.duration}</Text>
          <Button style={styles.button} onPress={() => {recordingLine.sound.replayAsync();
                                                        console.log(recordingLine);}} title="Play"></Button>
        </View>
      );
    });
  }

  return (
    <View style={styles.container}>
      <Text>{message}</Text>
      <Button
        title={recording ? 'Stop Recording' : 'Start Recording'}
        onPress={recording ? stopRecording : startRecording} />
      {getRecordingLines()}
      <StatusBar style="auto" />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
  row: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
  },
  fill: {
    flex: 1,
    margin: 16
  },
  button: {
    margin: 16
  }
});

How to find the audio content instead of file path? For example, In the stopRecording() function, I want to send the recorded audio buffer to the URL. The getURI() returns a file path which is not the content. Is there any way to convert the content as byte array ? Thank you in advanced


问:
Flutter: How to personalize a Card borders and to add a header text

I want to realize the card as shown in the image, but I have not found any ways to add the date on the top right and that particular border on the left.

答:
Try below code hope its help to you.

```<code>Container(
        decoration: BoxDecoration(
          border: Border.all(
            color:Colors.indigo,
            width: 2,
          ),
          borderRadius:BorderRadius.circular(8),
        ),
        child: Row(
          children: <Widget>[
            ClipRRect(
              borderRadius: BorderRadius.only(
                topLeft: Radius.circular(6.0),
                bottomLeft: Radius.circular(6.0),
              ),
              child: Container(
                width: 20.0,
                height: 100.0,
                color: Colors.indigo,
              ),
            ),
            SizedBox(
              width: 10,
            ),
            Flexible(
              child: Column(
                crossAxisAlignment:CrossAxisAlignment.start,
                children: <Widget>[
                  Container(
                    padding: EdgeInsets.all(2),
                    alignment: Alignment.topRight,
                    child: Text(
                      '01/02/2022',
                      style: TextStyle(
                        fontStyle:FontStyle.italic,
                      ),

                    ),
                  ),
                  Text(
                    'Your Heading',
                    style: TextStyle(
                      fontSize: 20,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                  Text(
                    'Your Subheading Everyday-6:00 AM to 11:00 PM.',
                    textAlign: TextAlign.center,
                    style: TextStyle(
                      fontSize: 16,
                    ),
                  )
                ],
              ),
            )
          ],
        ),
      ),
</code>```

Your result Screen->

Body:
Try below code hope its help to you.

Container(
        decoration: BoxDecoration(
          border: Border.all(
            color:Colors.indigo,
            width: 2,
          ),
          borderRadius:BorderRadius.circular(8),
        ),
        child: Row(
          children: <Widget>[
            ClipRRect(
              borderRadius: BorderRadius.only(
                topLeft: Radius.circular(6.0),
                bottomLeft: Radius.circular(6.0),
              ),
              child: Container(
                width: 20.0,
                height: 100.0,
                color: Colors.indigo,
              ),
            ),
            SizedBox(
              width: 10,
            ),
            Flexible(
              child: Column(
                crossAxisAlignment:CrossAxisAlignment.start,
                children: <Widget>[
                  Container(
                    padding: EdgeInsets.all(2),
                    alignment: Alignment.topRight,
                    child: Text(
                      '01/02/2022',
                      style: TextStyle(
                        fontStyle:FontStyle.italic,
                      ),

                    ),
                  ),
                  Text(
                    'Your Heading',
                    style: TextStyle(
                      fontSize: 20,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                  Text(
                    'Your Subheading Everyday-6:00 AM to 11:00 PM.',
                    textAlign: TextAlign.center,
                    style: TextStyle(
                      fontSize: 16,
                    ),
                  )
                ],
              ),
            )
          ],
        ),
      ),

Your result Screen->


问:
some error failed to run custom build command for `librocksdb-sys v6.11.4`
I tried to create my first substrate chain. Create Your First Substrate Chain

But I got some error while compiling substrate.

failed to run custom build command for librocksdb-sys v6.11.4

Does anybody know how to fix this problem?

答:
You had better update cargo to the nightly version and then try it.
If it keep in stuck error try comment commands, you may will need to study link.

#rustup component add --toolchain=nightly rust-src rustfmt

```<code>rustup target add wasm32-unknown-unknown
</code>```

#apt-get install llvm clang linux-headers-"$(uname -r)" #

```<code>apt install llvm clang
cargo build --release
</code>```

#cargo fix --allow-dirty #cargo fix --edition

```<code> #lsb_release -a
   No LSB modules are available.
   Distributor ID:  Ubuntu
   Description: Ubuntu 20.04.3 LTS
   Release: 20.04
   Codename:    focal
 #ldconfig --version
   ldconfig (Ubuntu GLIBC 2.31-0ubuntu9.2) 2.31
 #cargo --version
   cargo 1.60.0-nightly (25fcb13 2022-02-01)
 #rustc --version
   rustc 1.60.0-nightly (f624427f8 2022-02-06)
 #rustup show
   Default host: x86_64-unknown-linux-gnu
   rustup home:  /root/.rustup
   installed targets for active toolchain
 --------------------------------------
 wasm32-unknown-unknown
 x86_64-unknown-linux-gnu
 active toolchain
 ----------------
 nightly-x86_64-unknown-linux-gnu (default)
 rustc 1.60.0-nightly (f624427f8 2022-02-06)
</code>```

#ArmanRiazi.blockchain#Substrate#Dr.GavinWood
For details:
Walk-Through/Substrate/NodeSetup

Body:
You had better update cargo to the nightly version and then try it.
If it keep in stuck error try comment commands, you may will need to study link.

#rustup component add --toolchain=nightly rust-src rustfmt

rustup target add wasm32-unknown-unknown

#apt-get install llvm clang linux-headers-"$(uname -r)" #

apt install llvm clang
cargo build --release

#cargo fix --allow-dirty #cargo fix --edition

 #lsb_release -a
   No LSB modules are available.
   Distributor ID:  Ubuntu
   Description: Ubuntu 20.04.3 LTS
   Release: 20.04
   Codename:    focal
 #ldconfig --version
   ldconfig (Ubuntu GLIBC 2.31-0ubuntu9.2) 2.31
 #cargo --version
   cargo 1.60.0-nightly (25fcb13 2022-02-01)
 #rustc --version
   rustc 1.60.0-nightly (f624427f8 2022-02-06)
 #rustup show
   Default host: x86_64-unknown-linux-gnu
   rustup home:  /root/.rustup
   installed targets for active toolchain
 --------------------------------------
 wasm32-unknown-unknown
 x86_64-unknown-linux-gnu
 active toolchain
 ----------------
 nightly-x86_64-unknown-linux-gnu (default)
 rustc 1.60.0-nightly (f624427f8 2022-02-06)

#ArmanRiazi.blockchain#Substrate#Dr.GavinWood
For details:
Walk-Through/Substrate/NodeSetup


问:
update with exists in oracle
I have this query :

```<code>update rexcms e
   set e.cocnd=(select r.cocnd
                  from rexcms r
                 where NVL(r.marche,'*')=NVL(e.marche,'*')
                   and r.cocrd= e.cocrd
                   and r.cocol=e.cocol
                   and r.cocol='CHBIL'
                   and r.marche='CBOT')
 where e.cocol ='CDVHB' ;
</code>```

how can use EXISTS to optimize it

答:
Per my understanding, This is optimized code. There is one more syntax as MERGE that you can use to achieve the result -</p>
```<code>MERGE INTO rexcms e
USING rexcms r
   ON (NVL(r.marche,'*') = NVL(e.marche,'*')
       and r.cocrd = e.cocrd
       and r.cocol = e.cocol
       and r.cocol = 'CHBIL'
       and r.marche = 'CBOT')
 WHEN MATCHED THEN UPDATE
                      SET e.cocnd = r.cocnd
                    WHERE e.cocol ='CDVHB';
</code>```

Title: update with exists in oracle

Body:
I have this query :

update rexcms e
   set e.cocnd=(select r.cocnd
                  from rexcms r
                 where NVL(r.marche,'*')=NVL(e.marche,'*')
                   and r.cocrd= e.cocrd
                   and r.cocol=e.cocol
                   and r.cocol='CHBIL'
                   and r.marche='CBOT')
 where e.cocol ='CDVHB' ;

how can use EXISTS to optimize it

Body:
Per my understanding, This is optimized code. There is one more syntax as MERGE that you can use to achieve the result -

MERGE INTO rexcms e
USING rexcms r
   ON (NVL(r.marche,'*') = NVL(e.marche,'*')
       and r.cocrd = e.cocrd
       and r.cocol = e.cocol
       and r.cocol = 'CHBIL'
       and r.marche = 'CBOT')
 WHEN MATCHED THEN UPDATE
                      SET e.cocnd = r.cocnd
                    WHERE e.cocol ='CDVHB';


问:
Can I avoid repartition in the below kafka stream
I am trying to create a table from streaming through topic by changing the key but the value remains the same. Is it possible to avoid repartition?</p>
```<code>streamsBuilder.stream(
            TOPIC,
            Consumed.with(IdSerde(), ValueSerde())
        )
            .peek { key, value -> logger.info("Consumed $TOPIC, key: $key, value: $value") }
            .filter { _, value -> value != null }
            .selectKey(
                { _, value -> NewKey(value.newKey.toString()) },
                Named.`as`("changeKey")
            )
            .toTable(
                Materialized.`as`<NewKey, Value, KeyValueStore<Bytes, ByteArray>>(
                    NEW_TABLE_NAME
                )
                    .withKeySerde(NewKeySerde())
                    .withValueSerde(ValueSerde())
            )
        return streamsBuilder.build()
</code>```

答:
The only way I can think off is that your producer shoud send the data to the input topic with the appropriate key rather than you selecting the key in the streams application.

Otherwise, the answer is no.

Before going into the explanation, a bit of background on KTable

A KTable is an abstraction of a changelog stream. This means a KTable
holds only the latest value for a given key.

Consider the following four records(in order) being sent to the stream

```<code>("alice", 1) --> ("bob", 100) --> ("alice", 3) --> ("bob", 50)
</code>```

For the above the KTable would look as follows (alice and bob being keys of the message):

```<code>("alice", 3)
("bob", 50)
</code>```

Explanation

Whenever we run multiple instances of the kafka streams application,
the KTable in each instance holds only the local state of the
application. Hence, repartitioning is required to ensure that the
messages with the same key land in the same partition.

To understand this better let's consider an example. We have a topic with two partitions. Partition 0 has a single event and Partition 1 has three events as follows(null represents no key):

```<code>Topic Partition 0:  (null, {"name": alice,"count": 1}) ,
Topic Partition 1:  (null, {"name": alice,"count": 3}) , (null, {"name": "bob","count": 100}), (null, {"name": "bob","count": 50})
</code>```

We create a kafka streams application to read data from this topic and create a KTable using the name field as key. Also, the streams application is running with two instances. Each instance will be assigned a single partition as shown below:

```<code>Topic Partition 0: -----> Instance 1
Topic Partition 1: -----> Instance 2
</code>```

Since KTables are maintained locally per instance, if no repartitioning is done - KTable will be in an inconsistent state for both the instances.
This is shown below:

```<code>Instance 1  KTable : ("alice", {"count":1})
Instance 2 KTable : ("alice", {"count":1}), ("bob", {"count":50})
</code>```

Hence, to avoid issues like above kafka streams repartitions the topic if a KTable is created after a selectKey operation.

Body:
I am trying to create a table from streaming through topic by changing the key but the value remains the same. Is it possible to avoid repartition?

streamsBuilder.stream(
            TOPIC,
            Consumed.with(IdSerde(), ValueSerde())
        )
            .peek { key, value -> logger.info("Consumed $TOPIC, key: $key, value: $value") }
            .filter { _, value -> value != null }
            .selectKey(
                { _, value -> NewKey(value.newKey.toString()) },
                Named.`as`("changeKey")
            )
            .toTable(
                Materialized.`as`<NewKey, Value, KeyValueStore<Bytes, ByteArray>>(
                    NEW_TABLE_NAME
                )
                    .withKeySerde(NewKeySerde())
                    .withValueSerde(ValueSerde())
            )
        return streamsBuilder.build()

Body:
The only way I can think off is that your producer shoud send the data to the input topic with the appropriate key rather than you selecting the key in the streams application.

Otherwise, the answer is no.

Before going into the explanation, a bit of background on KTable

A KTable is an abstraction of a changelog stream. This means a KTable
holds only the latest value for a given key.

Consider the following four records(in order) being sent to the stream

("alice", 1) --> ("bob", 100) --> ("alice", 3) --> ("bob", 50)

For the above the KTable would look as follows (alice and bob being keys of the message):

("alice", 3)
("bob", 50)

Explanation

Whenever we run multiple instances of the kafka streams application,
the KTable in each instance holds only the local state of the
application. Hence, repartitioning is required to ensure that the
messages with the same key land in the same partition.

To understand this better let's consider an example. We have a topic with two partitions. Partition 0 has a single event and Partition 1 has three events as follows(null represents no key):

Topic Partition 0:  (null, {"name": alice,"count": 1}) ,
Topic Partition 1:  (null, {"name": alice,"count": 3}) , (null, {"name": "bob","count": 100}), (null, {"name": "bob","count": 50})

We create a kafka streams application to read data from this topic and create a KTable using the name field as key. Also, the streams application is running with two instances. Each instance will be assigned a single partition as shown below:

Topic Partition 0: -----> Instance 1
Topic Partition 1: -----> Instance 2

Since KTables are maintained locally per instance, if no repartitioning is done - KTable will be in an inconsistent state for both the instances.
This is shown below:

Instance 1  KTable : ("alice", {"count":1})
Instance 2 KTable : ("alice", {"count":1}), ("bob", {"count":50})

Hence, to avoid issues like above kafka streams repartitions the topic if a KTable is created after a selectKey operation.


问:
Replace same occurrence of word with different words using sed
I want to replace 2 same words in file(app.properties) with 2 different words using sed command.
Example:

```<code>mysql.host=<<CHANGE_ME>>
mysql.username=testuser
mysql.port=3306
mysql.db.password=<<CHANGE_ME>>
</code>```

required output will be

```<code>mysql.host=localhost
mysql.username=testuser
mysql.port=3306
mysql.db.password=password123
</code>```

I tried below command:

sed -e "s/<<CHANGE_ME>>/localhost/1" -e "s/<<CHANGE_ME>>/password123/2" app.properties > /home/centos/SCRIPT/io.properties_new

However I am getting localhost at both the places.

答:
With sed, using a wonderfully confusing if (first time) do x, else do y logic:

sed '/<CHANGE_ME>/{bb;:a;s/<CHANGE_ME>/password123/;:b;x;s/E//;x;ta;s/<CHANGE_ME>/localhost/;x;s/^/E/;x}' input_file
```
<p>Writing each command of the sed script on its own line makes it more understandable, or at least easier for me to expain it:</p>
```/<CHANGE_ME>/{
  bb
  :a
  s/<CHANGE_ME>/password123/
  :b
  x
  s/E//
  x
  ta
  s/<CHANGE_ME>/localhost/
  x
  s/^/E/
  x
}
```

Here's the explanation:

/<CHANGE_ME>/{…} means that the stuff in {…} is only applied to lines matching <CHANGE_ME>;

bb: "branch to (go to) :b", in this case used to skip the first substitution command;

:a: a target for another branch or test-and-branch command;

s/…/…/: you know what it does, but we skip this the first time the script is run;

b: branches to the end of the script, skipping everything (because we are giving no argument to b);

:b: the target of the command bb at 1.;

x: swap patter space (the line you're dealing with at the moment), with the hold space (a kind of variable that you can put stuff into via x, h, and H commands);

s/E//: tries to match and delete a E (just because that's the initial of my name), which fails the first time we run this, because the hold space that we've swapped earlier with the patter space was empty;

x: undos what the previous x did, so we're back on working with the line matching <CHANGE_ME>;

ta: tests if last peformed s/…/…/ command succeeded and, if so, it goes to :a, otherwise it's a no-op; the first time we run the script this is a no-op, because step 6 failed;

s/…/…/: you know what it does;

x: see above

s/^/E/: inserts the E at the beginning of the line, so that next time we run the script substitution of step 7 succeedes, step 9 successfully branches to :a, step 3 is peformed for the first time, and step 4 exits the script for ever;

x: see above

Body:
I want to replace 2 same words in file(app.properties) with 2 different words using sed command.
Example:

mysql.host=<<CHANGE_ME>>
mysql.username=testuser
mysql.port=3306
mysql.db.password=<<CHANGE_ME>>

required output will be

mysql.host=localhost
mysql.username=testuser
mysql.port=3306
mysql.db.password=password123

I tried below command:

sed -e "s/<<CHANGE_ME>>/localhost/1" -e "s/<<CHANGE_ME>>/password123/2" app.properties > /home/centos/SCRIPT/io.properties_new

However I am getting localhost at both the places.

Body:
With sed, using a wonderfully confusing if (first time) do x, else do y logic:

sed '/<CHANGE_ME>/{bb;:a;s/<CHANGE_ME>/password123/;:b;x;s/E//;x;ta;s/<CHANGE_ME>/localhost/;x;s/^/E/;x}' input_file

Writing each command of the sed script on its own line makes it more understandable, or at least easier for me to expain it:

/<CHANGE_ME>/{
  bb
  :a
  s/<CHANGE_ME>/password123/
  :b
  x
  s/E//
  x
  ta
  s/<CHANGE_ME>/localhost/
  x
  s/^/E/
  x
}

Here's the explanation:

/<CHANGE_ME>/{…} means that the stuff in {…} is only applied to lines matching <CHANGE_ME>;

bb: "branch to (go to) :b", in this case used to skip the first substitution command;

:a: a target for another branch or test-and-branch command;

s/…/…/: you know what it does, but we skip this the first time the script is run;

b: branches to the end of the script, skipping everything (because we are giving no argument to b);

:b: the target of the command bb at 1.;

x: swap patter space (the line you're dealing with at the moment), with the hold space (a kind of variable that you can put stuff into via x, h, and H commands);

s/E//: tries to match and delete a E (just because that's the initial of my name), which fails the first time we run this, because the hold space that we've swapped earlier with the patter space was empty;

x: undos what the previous x did, so we're back on working with the line matching <CHANGE_ME>;

ta: tests if last peformed s/…/…/ command succeeded and, if so, it goes to :a, otherwise it's a no-op; the first time we run the script this is a no-op, because step 6 failed;

s/…/…/: you know what it does;

x: see above

s/^/E/: inserts the E at the beginning of the line, so that next time we run the script substitution of step 7 succeedes, step 9 successfully branches to :a, step 3 is peformed for the first time, and step 4 exits the script for ever;

x: see above


问:
Creating ibm queue on container startup
I use TestContainers with ibm mq image in it. Through config I set host, port, user=app, default passw0rd, manager = QM1. I also have more custom queues and besides default DEV.QUEUE.1 - 3 ,created by container, I gotta start up mine. I found such operator like withCommand, accepting String argument, and try to set it like
.withCommand("sh","-c","runmqsc QM1 | define qlocal(LQ1) | end") https://www.ibm.com/docs/en/ibm-mq/7.5?topic=75-creating-queue-called-lq1
Unfortunately, it seems not starting with it.

My full snap of code related:

```<code> @Container
    static GenericContainer<?> mqContainer = new GenericContainer<>(DockerImageName.parse("ibmcom/mq"))
            .withEnv("LICENSE", "accept")
            .withEnv("MQ_QMGR_NAME", "QM1")
     /*       .withCommand("sh","-c","runmqsc")*/

            .withExposedPorts(1414)
            .withStartupTimeout(Duration.of(1, ChronoUnit.HALF_DAYS))
            .withLogConsumer(new Slf4jLogConsumer(log));
</code>```

答:
ibmcom/mq image already covers this scenario. Create a mqsc script with all custom resources. Copy this script in /etc/mq folder. All resources defined in script will be created on startup.

See Customizing the queue manager configuration for details.

Title: Creating ibm queue on container startup

Body:
I use TestContainers with ibm mq image in it. Through config I set host, port, user=app, default passw0rd, manager = QM1. I also have more custom queues and besides default DEV.QUEUE.1 - 3 ,created by container, I gotta start up mine. I found such operator like withCommand, accepting String argument, and try to set it like
.withCommand("sh","-c","runmqsc QM1 | define qlocal(LQ1) | end") https://www.ibm.com/docs/en/ibm-mq/7.5?topic=75-creating-queue-called-lq1
Unfortunately, it seems not starting with it.

My full snap of code related:

 @Container
    static GenericContainer<?> mqContainer = new GenericContainer<>(DockerImageName.parse("ibmcom/mq"))
            .withEnv("LICENSE", "accept")
            .withEnv("MQ_QMGR_NAME", "QM1")
     /*       .withCommand("sh","-c","runmqsc")*/

            .withExposedPorts(1414)
            .withStartupTimeout(Duration.of(1, ChronoUnit.HALF_DAYS))
            .withLogConsumer(new Slf4jLogConsumer(log));


问:
I Get System.NullReferenceException when I try to add an item into a Room
Like said in the question, I can not figure out why I cannot add item to my rooms if anyone has an insight on this I would appreciate it. I'm not sure if need to somehow import dicitonary to CreateRooms( ) if yes how?

```<code>    public void CreateRooms()
    {
        // create the rooms
        Room outside = new Room("outside the main entrance of the university");
        Room hallway = new Room("inside the hallway of the university");
        Room theatre = new Room("in a lecture theatre");
        Room basement = new Room("in the basement");
        Room pub = new Room("in the campus pub");
        Room lab = new Room("in a computing lab");
        Room office = new Room("in the computing admin office");

        // initialise room exits
        outside.AddExit("east", hallway);
        outside.AddExit("south", lab);
        outside.AddExit("west", pub);

        hallway.AddExit("west", outside);
        hallway.AddExit("up", theatre);
        hallway.AddExit("down", basement);

        theatre.AddExit("down", hallway);

        basement.AddExit("up", hallway);

        pub.AddExit("east", outside);

        lab.AddExit("north", outside);
        lab.AddExit("east", office);

        office.AddExit("west", lab);

        Item axe = new Item(5, "a sharp axe");

        outside.Chest.Put("axe", axe); // System.NullReferenceException

        player.currentRoom = outside;  // start game outside

    }
</code>```

These are the methods that put items to the room and where I get/take item from room to my inventory.

```<code>   public bool Put(string itemName, Item item)
    {
        items.Add(itemName, item);
        Console.WriteLine("There is " + itemName + " in this room. Will you take it?");
        return true;
    }
    public Item Get(string itemName)
    {
        Item item = null;
        if (items.ContainsKey(itemName))
        {
            item = items[itemName];
            items.Remove(itemName);
        }
        return item;
    }
</code>```

答: I think your 'Chest' is null - or mabye your list in Chest - you must instantiate objects before you can use them.</p>

Body:
Like said in the question, I can not figure out why I cannot add item to my rooms if anyone has an insight on this I would appreciate it. I'm not sure if need to somehow import dicitonary to CreateRooms( ) if yes how?

    public void CreateRooms()
    {
        // create the rooms
        Room outside = new Room("outside the main entrance of the university");
        Room hallway = new Room("inside the hallway of the university");
        Room theatre = new Room("in a lecture theatre");
        Room basement = new Room("in the basement");
        Room pub = new Room("in the campus pub");
        Room lab = new Room("in a computing lab");
        Room office = new Room("in the computing admin office");

        // initialise room exits
        outside.AddExit("east", hallway);
        outside.AddExit("south", lab);
        outside.AddExit("west", pub);

        hallway.AddExit("west", outside);
        hallway.AddExit("up", theatre);
        hallway.AddExit("down", basement);

        theatre.AddExit("down", hallway);

        basement.AddExit("up", hallway);

        pub.AddExit("east", outside);

        lab.AddExit("north", outside);
        lab.AddExit("east", office);

        office.AddExit("west", lab);

        Item axe = new Item(5, "a sharp axe");

        outside.Chest.Put("axe", axe); // System.NullReferenceException

        player.currentRoom = outside;  // start game outside

    }

These are the methods that put items to the room and where I get/take item from room to my inventory.

   public bool Put(string itemName, Item item)
    {
        items.Add(itemName, item);
        Console.WriteLine("There is " + itemName + " in this room. Will you take it?");
        return true;
    }
    public Item Get(string itemName)
    {
        Item item = null;
        if (items.ContainsKey(itemName))
        {
            item = items[itemName];
            items.Remove(itemName);
        }
        return item;
    }


问:
Changes not reflecting in html when the Observable is subscribed
I'm trying to pass the object to object Model using a shared service to a already loaded component , even though i get data after subscription, it is not reflecting in html view.</p>
```<code><div *ngFor="let emp of emps" class="card">
      <div class="card-body">
            <img class="img-icon" [src]="emp?.logo" />
                </div>
      <div class="icon-text">
      <p class="maintext" >{{emp?.name}}</p>
      <p class="subtext">Emp Code: {{emp?.code}}</p>
       </div>

       <div class="icon-text">
             <a class="view-btn" >View Details</a>
       </div>
  </div>
</code>```
```<code>emps : EmployeeModel[];

ngOnInit(): void {

    this.service.getData().subscribe(data => {
      this.emps = data
      console.log(this.emps))
    })
   }

</code>```
```<code>export class EmployeeService {
  employeeData:any;
  private subject = new Subject<any>();
  constructor() { }

  setEmployeeData(data) {
    this.employeeData = data
    this.subject.next(data);
  }

 getData(): Observable<any> {
    return this.subject.asObservable();
 }
}

</code>```

答:
Use BehaviorSubject instead of Subject</p>
```<code>private subject = new BehaviorSubject<any>(null);
</code>```

Body:
I'm trying to pass the object to object Model using a shared service to a already loaded component , even though i get data after subscription, it is not reflecting in html view.

{{emp?.name}}

Emp Code: {{emp?.code}}

             View Details

emps : EmployeeModel[];

ngOnInit(): void {

    this.service.getData().subscribe(data => {
      this.emps = data
      console.log(this.emps))
    })
   }

export class EmployeeService {
  employeeData:any;
  private subject = new Subject<any>();
  constructor() { }

  setEmployeeData(data) {
    this.employeeData = data
    this.subject.next(data);
  }

 getData(): Observable<any> {
    return this.subject.asObservable();
 }
}

Body:
Use BehaviorSubject instead of Subject

private subject = new BehaviorSubject<any>(null);


问:
how to print star hypen pattern in python
How to print the pattern like this:

(need to print n-1 lines)

input=3

```<code>----@
--@-@-@
</code>```

input=6

```<code>----------@
--------@-@-@
------@---@---@
----@-----@-----@
--@-------@-------@
</code>```

My code:

```<code>row = int(input())
for i in range(1, row):
    for j in range(1,row-i+1):
        print("-", end="")
    for j in range(1, 2*i):
        if j==1 or j==2*i-1:
            print("@", end="")
        else:
            print("-", end="")
    print()
</code>```

MY OUTPUT:
input=5

```<code>----@
---@-@
--@---@
-@-----@
</code>```

Please explain how to do??

答:
There are a few things missing and to be improved in your code:

There's no need to make a loop to print the same character again and again: on python you can use the product to repeat the character an x number of times. For example: "-" * 3 == "---"

They way you calculate the hyphens in the middle is fine, but you need to do it twice and add an "@" in between.

You can build the strings part by part first and then print the whole line, avoiding having to print an empty line in the end of the loop.

Personally, since the first line is going to have one "@" and not three, I prefer to calculate it and print it separately.

With these improvements, a solution to your problem could be:

```<code>row = int(input())
print("-" * (row - 1) * 2 + "@")
for i in range(row - 2, 0, -1):
    left_hyphens = "-" * i * 2
    mid_hyphens = "-" * (1 + 2 * (row - 2 - i))
    print(left_hyphens + "@" + mid_hyphens + "@" + mid_hyphens + "@")
</code>```

Body:
How to print the pattern like this:

(need to print n-1 lines)

input=3

----@
--@-@-@

input=6

----------@
--------@-@-@
------@---@---@
----@-----@-----@
--@-------@-------@

My code:

row = int(input())
for i in range(1, row):
    for j in range(1,row-i+1):
        print("-", end="")
    for j in range(1, 2*i):
        if j==1 or j==2*i-1:
            print("@", end="")
        else:
            print("-", end="")
    print()

MY OUTPUT:
input=5

----@
---@-@
--@---@
-@-----@

Please explain how to do??

Body:
There are a few things missing and to be improved in your code:

There's no need to make a loop to print the same character again and again: on python you can use the product to repeat the character an x number of times. For example: "-" * 3 == "---"

They way you calculate the hyphens in the middle is fine, but you need to do it twice and add an "@" in between.

You can build the strings part by part first and then print the whole line, avoiding having to print an empty line in the end of the loop.

Personally, since the first line is going to have one "@" and not three, I prefer to calculate it and print it separately.

With these improvements, a solution to your problem could be:

row = int(input())
print("-" * (row - 1) * 2 + "@")
for i in range(row - 2, 0, -1):
    left_hyphens = "-" * i * 2
    mid_hyphens = "-" * (1 + 2 * (row - 2 - i))
    print(left_hyphens + "@" + mid_hyphens + "@" + mid_hyphens + "@")


问:
How to view all new resource provisions in AWS
I am trying create a automation based on the new resource provisions in AWS. but i can't find any service/api which helps to view new provisions. I have tried to use CloudTrail to check create APIs. but CloudTrail logs are not enough for my use case.

Is there any service/api for this use case?

答:
You can use the AWS Config or AWS CloudTrail services for this, but, for AWS Config you will need to specify which kind of resource you want to be notified, like the following:

```<code>{
    "source": [
        "aws.config"
    ],
    "detail-type": [
        "Config Configuration Item Change"
    ],
    "detail": {
    "messageType": [
        "ConfigurationItemChangeNotification"
    ],
    "configurationItem": {
        "resourceType": [
            "AWS::EC2::Instance"
        ],
        "configurationItemStatus": [
            "ResourceDiscovered"
        ]
    }
    }
}
</code>```

For more information of how to do this with AWS Config, check this link: Receive custom email notifications when a resource is created with AWS Config

If you want something to check the changes on Console, or other kind of changes you will need to use AWS CloudTrail, together with the AWS Lambda service.

An example can be found here: Get Real-time Alerts When Users Modify AWS Infrastructure

In both you will need a service like AWS SNS to send the notifications.

Body:
You can use the AWS Config or AWS CloudTrail services for this, but, for AWS Config you will need to specify which kind of resource you want to be notified, like the following:

{
    "source": [
        "aws.config"
    ],
    "detail-type": [
        "Config Configuration Item Change"
    ],
    "detail": {
    "messageType": [
        "ConfigurationItemChangeNotification"
    ],
    "configurationItem": {
        "resourceType": [
            "AWS::EC2::Instance"
        ],
        "configurationItemStatus": [
            "ResourceDiscovered"
        ]
    }
    }
}

For more information of how to do this with AWS Config, check this link: Receive custom email notifications when a resource is created with AWS Config

If you want something to check the changes on Console, or other kind of changes you will need to use AWS CloudTrail, together with the AWS Lambda service.

An example can be found here: Get Real-time Alerts When Users Modify AWS Infrastructure

In both you will need a service like AWS SNS to send the notifications.


问:
Get owner of a file using python on windows system
I want to extract the owner of a file within a python3 script on a Windows system.

When I run: os.path.expanduser(fp)
or
os.stat(fp).st_uid
I receive a 0 for all my discussed files.

Does anybody know how to extract the id or name of an owner of a file using python on windows.

Thanks
-d-

答:
```<code>import win32api
import win32con
import win32security

FILENAME = "temp.txt"
open (FILENAME, "w").close ()

print "I am", win32api.GetUserNameEx (win32con.NameSamCompatible)

sd = win32security.GetFileSecurity (FILENAME, win32security.OWNER_SECURITY_INFORMATION)
owner_sid = sd.GetSecurityDescriptorOwner ()
name, domain, type = win32security.LookupAccountSid (None, owner_sid)

print "File owned by %s\\%s" % (domain, name)
</code>```


问:
mongoimport Error, Failed: invalid JSON input
I have many mongodb instance files like below;

```<code>[
{
    "_id" : ObjectId("35d455de983c0e6a53ea0848"),
    "createdAt" : ISODate("2019-12-05T23:25:04.347+0000"),
    "__v" : NumberInt(0)
},
{
    "_id" : ObjectId("1ecbe0f75df8ccd52a7b1662"),
    "createdAt" : ISODate("2019-12-17T12:40:53.521+0000"),
    "__v" : NumberInt(0)
}
]
</code>```

I couldn't import these files because of invalid format.

```<code>mongoimport --db DATABASENAME --collection COLLECTIONNAME --file filename.json --jsonArray
</code>```

And it says;

Failed: invalid JSON input. Position: 16. Character: O

Is there any other way to import those files?

If not, how can I convert them to be imported?

答:
invalid JSON input. Position: 96. Character: N

For me it was "N" for NaN that I replaced with 0 and it wroked.

It also worked with adding the --legacy option, but I preferred to fix the file as the legacy option did not work within my docker container.

Body:
I have many mongodb instance files like below;

[
{
    "_id" : ObjectId("35d455de983c0e6a53ea0848"),
    "createdAt" : ISODate("2019-12-05T23:25:04.347+0000"),
    "__v" : NumberInt(0)
},
{
    "_id" : ObjectId("1ecbe0f75df8ccd52a7b1662"),
    "createdAt" : ISODate("2019-12-17T12:40:53.521+0000"),
    "__v" : NumberInt(0)
}
]

I couldn't import these files because of invalid format.

mongoimport --db DATABASENAME --collection COLLECTIONNAME --file filename.json --jsonArray

And it says;

Failed: invalid JSON input. Position: 16. Character: O

Is there any other way to import those files?

If not, how can I convert them to be imported?


问:
fbprophet Exponential Growth
So I currently have the following code where I am trying to forecast the number of electric vehicles miles in 30 years.

```<code>miles = [7851400, 22362800, 46612600, 78121800, 194901200, 416005800, 724719000, 1117932800, 1590637400, 2186914600]
years = []

for i in range(2010, 2020):
    years.append(i)

zipped_list = zip(years, miles)

EV_df = pd.DataFrame(list(zipped_list), columns = ['year', 'Electric Vehicles Miles'])
EV_df['year'] = pd.to_datetime(EV_df['year'], format='%Y')
EV_df[['y', 'ds']] = EV_df[['Electric Vehicles Miles', 'year']]
</code>```

I then fit a prophet model and ask it to predict 30 years down the line.

```<code>ev_model = Prophet(weekly_seasonality=True)
ev_model.fit(EV_df)
future_electric = ev_model.make_future_dataframe(periods=30, freq='Y')
forecast_electric = ev_model.predict(future_electric)
</code>```

However, the result is pretty much a linear trend where you can see how in the last 5 points it's starting to have some sort of exponential or massive increase in the number of miles which isn't really being recognized from the graph

How would I get it to recognize this spike and plot a smooth exponential graph and not assume it is linear?

答: You can also try changing your growth='linear parameter to growth='logistic' - which would handle exponetial or geometric growth. You would also need to add the saturation values if any.</p>

Title: fbprophet Exponential Growth

Body:
So I currently have the following code where I am trying to forecast the number of electric vehicles miles in 30 years.

miles = [7851400, 22362800, 46612600, 78121800, 194901200, 416005800, 724719000, 1117932800, 1590637400, 2186914600]
years = []

for i in range(2010, 2020):
    years.append(i)

zipped_list = zip(years, miles)

EV_df = pd.DataFrame(list(zipped_list), columns = ['year', 'Electric Vehicles Miles'])
EV_df['year'] = pd.to_datetime(EV_df['year'], format='%Y')
EV_df[['y', 'ds']] = EV_df[['Electric Vehicles Miles', 'year']]

I then fit a prophet model and ask it to predict 30 years down the line.

ev_model = Prophet(weekly_seasonality=True)
ev_model.fit(EV_df)
future_electric = ev_model.make_future_dataframe(periods=30, freq='Y')
forecast_electric = ev_model.predict(future_electric)

However, the result is pretty much a linear trend where you can see how in the last 5 points it's starting to have some sort of exponential or massive increase in the number of miles which isn't really being recognized from the graph

How would I get it to recognize this spike and plot a smooth exponential graph and not assume it is linear?


问:
Shopify webhook products/update before after
I need to syncrhonize another store on the Shopify products.
I need to keep synchronized content (including pictures), inventory and price.

To do so I'm using the products/update webhook.
When a product is updated I resynchronize the whole product on the other store.

Problem is, when I receive the webhook object it doesn't contain any information about what has changed.

So for example if I have a product with 20 variants and I update 20 prices I synchronise 20 times all the variants because the API doesn't tell me which field has changed or which variant was modified.

Is there any way to know what has changed? I could compare the data on the other store, but in practice it is more complicated than just overwrite (think about the pictures...).

There is no field "last edit" on the variant so I cannot check that, to see if it's recent.

答:
There is no actual solution for this.
The solution I'm using is to throttle.

When I receive a product/update hook I save the variant ids on a table (where the variant_id is unique).

On a separate process, every few minutes I process all (actually some) variant ids in the table. This way if a variant_id is repeated I process it only once every few minutes.

This won't avoid processing unedited variants, but I couldn't find any way to discard those.


问:
accessing host machine from a pod running on a kind cluster
I'm running a kind cluster and from one of the pods I need to access the host machine.  I know in minikube you can access it using 10.0.0.2 is there some way I can access it, the same way I could use host.docker.internal on Docker Desktop?

答:
Check Is it possible accessing host machine ports from Kind pods?
, that most probably solution you are looking for.

workaround using qoomon/docker-host

```<code>---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: dockerhost
  labels:
    k8s-app: dockerhost
spec:
  replicas: 1
  selector:
    matchLabels:
      k8s-app: dockerhost
  template:
    metadata:
      labels:
        k8s-app: dockerhost
    spec:
      containers:
      - name: dockerhost
        image: qoomon/docker-host
        securityContext:
          capabilities:
            add: ["NET_ADMIN", "NET_RAW"]
        env:
        # Not needed in MacOs:
        - name: DOCKER_HOST
           value: 172.17.0.1 # <-- docker bridge network default gateway

---
apiVersion: v1
kind: Service
metadata:
  name: dockerhost
spec:
  clusterIP: None # <-- Headless service
  selector:
    k8s-app: dockerhost
</code>```

check iptables way

kind pod with a container name: test

local container: myapp exposing port 8081

Allow port in the firewall

iptables -I INPUT -p tcp --dport 8081 -j ACCEPT
now from inside container test in kind cluster, you can run:

```<code>curl 172.17.0.1:8081
</code>```

where 172.17.0.1 is your docker bridge default gateway.

Body:
Check Is it possible accessing host machine ports from Kind pods?
, that most probably solution you are looking for.

workaround using qoomon/docker-host

---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: dockerhost
  labels:
    k8s-app: dockerhost
spec:
  replicas: 1
  selector:
    matchLabels:
      k8s-app: dockerhost
  template:
    metadata:
      labels:
        k8s-app: dockerhost
    spec:
      containers:
      - name: dockerhost
        image: qoomon/docker-host
        securityContext:
          capabilities:
            add: ["NET_ADMIN", "NET_RAW"]
        env:
        # Not needed in MacOs:
        - name: DOCKER_HOST
           value: 172.17.0.1 # <-- docker bridge network default gateway

---
apiVersion: v1
kind: Service
metadata:
  name: dockerhost
spec:
  clusterIP: None # <-- Headless service
  selector:
    k8s-app: dockerhost

check iptables way

kind pod with a container name: test

local container: myapp exposing port 8081

Allow port in the firewall

iptables -I INPUT -p tcp --dport 8081 -j ACCEPT
now from inside container test in kind cluster, you can run:

curl 172.17.0.1:8081

where 172.17.0.1 is your docker bridge default gateway.


问:
Don't get max date values from one column from multiple rows in 2 columns because column is invalid in the select list
I must get max date values from one column from multiple rows in 2 columns based on IdType in one rows for IDUser.

I simplify my tables like this :

```<code>TableDoc
IDUser  IdCourse
John    C
Jeff    E
Michael F
Tom     A
John    E
Jeff    C
Michael A
Tom     E

TableCourse
IdCourse IdType DateCourse
A        2      2020-07-31 00:00:00
C        2      2019/06/06 00:00:00
C        1      2021/04/14 00:00:00
E        2      2021/04/29 00:00:00
E        2      2020/06/09 00:00:00
F        1      2020/06/25 00:00:00
F        2      2021/04/09 00:00:00
F        2      2020/06/01 00:00:00
</code>```

I must get this:

```<code>
IDUser      DateInsert              DateUpdate
Jeff        2021-04-14 00:00        2021-04-29 00:00
John        2021-04-14 00:00        2021-04-29 00:00
Michael     2020-06-25 00:00        2021-04-09 00:00
Tom         null                    2021-04-29 00:00
</code>```

This is my query:

```<code>SELECT d.IDUser, c.IdType,
DateInsert = MAX(CASE WHEN c.IdType = 1 THEN DateCourse END),
DateUpdate = MAX(CASE WHEN c.IdType = 2 THEN DateCourse END)
FROM dbo.TableDoc d
inner join TableCourse c
on d.IdCourse = c.IdCourse
GROUP BY IDUser;
</code>```

In [Sql Fiddle][1] is ok, but in Sql Server Management (with my real tables) I have this error:

```<code>Column 'TableCourse.IdType' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.```

What could be the problem?

  [1]: http://sqlfiddle.com/#!18/9c982/3
```

答:
It's tempting to think abut PIVOT but in this case conditional aggregation is better IMHO:

```<code>SELECT [User],
  DateType1 = MAX(CASE WHEN [Type] = 1 THEN LastDate END),
  DateType2 = MAX(CASE WHEN [Type] = 2 THEN LastDate END)
FROM dbo.tablename GROUP BY [User];
</code>```

I also recommend you stay away from special words like User and Type because they force you to add these gross [square brackets] all over the place.

Body:
I must get max date values from one column from multiple rows in 2 columns based on IdType in one rows for IDUser.

I simplify my tables like this :

TableDoc
IDUser  IdCourse
John    C
Jeff    E
Michael F
Tom     A
John    E
Jeff    C
Michael A
Tom     E

TableCourse
IdCourse IdType DateCourse
A        2      2020-07-31 00:00:00
C        2      2019/06/06 00:00:00
C        1      2021/04/14 00:00:00
E        2      2021/04/29 00:00:00
E        2      2020/06/09 00:00:00
F        1      2020/06/25 00:00:00
F        2      2021/04/09 00:00:00
F        2      2020/06/01 00:00:00

I must get this:

IDUser      DateInsert              DateUpdate
Jeff        2021-04-14 00:00        2021-04-29 00:00
John        2021-04-14 00:00        2021-04-29 00:00
Michael     2020-06-25 00:00        2021-04-09 00:00
Tom         null                    2021-04-29 00:00

This is my query:

SELECT d.IDUser, c.IdType,
DateInsert = MAX(CASE WHEN c.IdType = 1 THEN DateCourse END),
DateUpdate = MAX(CASE WHEN c.IdType = 2 THEN DateCourse END)
FROM dbo.TableDoc d
inner join TableCourse c
on d.IdCourse = c.IdCourse
GROUP BY IDUser;

In [Sql Fiddle][1] is ok, but in Sql Server Management (with my real tables) I have this error:

Column 'TableCourse.IdType' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.```

What could be the problem?

  [1]: http://sqlfiddle.com/#!18/9c982/3

Body:
It's tempting to think abut PIVOT but in this case conditional aggregation is better IMHO:

SELECT [User],
  DateType1 = MAX(CASE WHEN [Type] = 1 THEN LastDate END),
  DateType2 = MAX(CASE WHEN [Type] = 2 THEN LastDate END)
FROM dbo.tablename GROUP BY [User];

I also recommend you stay away from special words like User and Type because they force you to add these gross [square brackets] all over the place.


问:
How to submit multiple forms in Stepper in Angular material
I have used angular mat-stepper to implement a form of multiple steps. The first step is one form and there are 3 such steps.
Something like this:

```<code>    firstFormGroup: FormGroup;
  secondFormGroup: FormGroup;
  thirdFormGroup: FormGroup;
  fourthFormGroup: FormGroup;
  rows: FormArray;

  constructor(private formBuilder: FormBuilder) {

  }

  ngOnInit() {
    this.firstFormGroup = this.formBuilder.group({
      name : ['', Validators.required],
      gender : ['', Validators.required]
    });
    this.secondFormGroup = this.formBuilder.group({
      permanentHouseName: ['', Validators.required],
      permanentHouseNumber: ['', Validators.required],
      permanentPlace: ['', Validators.required]
    });
    this.thirdFormGroup = this.formBuilder.group({
      profession  : ['', Validators.required],
      designation  : ['', Validators.required],
    });
</code>```

I want to submit all 3 forms at once on click of submit at the last third step. I am able to access the data of the forms individually but is there any way we can submit it as one form data to my java spring controller in backend.

Access to data:

```<code> submit() {

    if (this.basicInfoForm.valid) {
      console.log(this.firstFormGroup.value);
    }
    console.log(this.secondFormGroup.value);
  }
</code>```

答:
You can submit all 3 forms by using a spread operator Spread Operator Syntax which  allows us to expand an iterable like array or object into its individual elements.

submit() {

  if (this.firstFormGroup.valid && this.secondFormGroup.valid &&& this.thirdFormGroup.valid) {

    const data = {
    ...this.firstFormGroup.value,
    ...this.secondFormGroup.value,
    ...this.thirdFormGroup.value
    };

    // Continue with your submit operation
  }

}```

Body:
I have used angular mat-stepper to implement a form of multiple steps. The first step is one form and there are 3 such steps.
Something like this:

    firstFormGroup: FormGroup;
  secondFormGroup: FormGroup;
  thirdFormGroup: FormGroup;
  fourthFormGroup: FormGroup;
  rows: FormArray;

  constructor(private formBuilder: FormBuilder) {

  }

  ngOnInit() {
    this.firstFormGroup = this.formBuilder.group({
      name : ['', Validators.required],
      gender : ['', Validators.required]
    });
    this.secondFormGroup = this.formBuilder.group({
      permanentHouseName: ['', Validators.required],
      permanentHouseNumber: ['', Validators.required],
      permanentPlace: ['', Validators.required]
    });
    this.thirdFormGroup = this.formBuilder.group({
      profession  : ['', Validators.required],
      designation  : ['', Validators.required],
    });

I want to submit all 3 forms at once on click of submit at the last third step. I am able to access the data of the forms individually but is there any way we can submit it as one form data to my java spring controller in backend.

Access to data:

 submit() {

    if (this.basicInfoForm.valid) {
      console.log(this.firstFormGroup.value);
    }
    console.log(this.secondFormGroup.value);
  }


问:
How to randomly reshuffle letters in words
I am trying to make a word scrambler in R. So i have put some words in a collection and tried to use strsplit() to split the letters of each word in the collection.

But I don't understand how to jumble the letters of a word and merge them to one word in R Tool. Does anyone know how can I solve this?

This is what I have done
enter image description here

答:
You can use the sample function for this.
here is an example of doing it for a single word. You can use this within your for-loop:

yourword <- "hello"

# split: Split will return a list with one char vector in it.
# We only want to interact with the vector not the list, so we extract the first
# (and only) element with "[[1]]"
jumble <- strsplit(yourword,"")[[1]]
jumble <- sample(jumble, # sample random element from jumble
                 size =  length(jumble), # as many times as the length of jumble
                 # ergo all Letters
                 replace = FALSE # do not sample an element multiple times
                 )
restored <- paste0(jumble,
                   collapse = "" # bas
                   )
```

As the answer from langtang suggests, you can use the apply family for this, which is more efficient. But maybe this answer helps the understanding of what R is actually doing here.

Body:
You can use the sample function for this.
here is an example of doing it for a single word. You can use this within your for-loop:

yourword <- "hello"

# split: Split will return a list with one char vector in it.
# We only want to interact with the vector not the list, so we extract the first
# (and only) element with "[[1]]"
jumble <- strsplit(yourword,"")[[1]]
jumble <- sample(jumble, # sample random element from jumble
                 size =  length(jumble), # as many times as the length of jumble
                 # ergo all Letters
                 replace = FALSE # do not sample an element multiple times
                 )
restored <- paste0(jumble,
                   collapse = "" # bas
                   )

As the answer from langtang suggests, you can use the apply family for this, which is more efficient. But maybe this answer helps the understanding of what R is actually doing here.