问:
Regarding to retrieve values inside the array
Hi
I am creating online quiz in asp.net c#. For that i have one form that displays testlist in dropdownlist & start button. After clicking 2nd form appears, 2nd form shows one label for question, radiobuttonlist for answers ,next & checkbox for review. I am creating array of random question ids in start button click event of the 1stform. when i click next button in 2nd form then next random question appears, i want array of questions those are checked for review. I used code for arrays of values ( eg.10101) 1 for true & 0 for false as follows but i want array of that question ids those are checked:</p>

```<code>        int[] a = (int[])Session["values"];//this is array of random question ids created in 1st form
        int g;
        if (chkmark.Checked == true)
        {
            g = 1;
        }
        else
        {
            g = 0;
        }
        int[] chkarray = new int[Convert.ToInt32(Session["Counter"]) - 1];
        int[] temp1 = (int[])Session["arrofchk"];
        int k, no;

        if (temp1 == null)
            no = 0;
        else
            no = temp.Length;
        for (k = 0; k < no; k++)
        {
       chkarray[k] = temp1[k];
        }
        chkarray[j] = g;
</code>```

答:
Personally, i would use a Dictionary<int, bool> for this.

In the key of the dictionary, you can store the random Question ID, in the value of the pair, you can store the checked item state. It might take you more work now to refactor it, but I believe it will save you a lot of time in the end when you want to do more actions on your quiz items.

Using a dictionary - or at least a well chosen collection, I think it will be easier to get the right data back.

For your example, it can work only if the positions of both arrays are the same.

```<code>Dictionary<int, bool> quizAnswers = new Dictionary<int, bool>(); // <questionID, checked>

// Fill dictionary with questions and answers
for(int i=0;i<a.length;i++)
{
  if(temp1.length > i) // Make sure we don't get an IndexOutOfBoundsException
  {
    quizAnswers.Add(a[i], temp1[i] == 1);
  }
}

// Get Answered question in array ( LINQ )
int[] checkedAnswers = (from KeyValuePair<int, bool> pair in quizAnswers
                        where pair.Value == true
                        select pair.Key).ToArray<int>();
</code>```

The reason I am using a Dictionary here, is because I personally think it's neater than having two separate arrays.

I believe you should implement a Dictionary in your quiz, in stead of those arrays. What if the array indexes don't match, or you want to dynamically add a question to a fixed size array, etc..

It's something to take into consideration. Hope I could help you out.

Body:
Hi
I am creating online quiz in asp.net c#. For that i have one form that displays testlist in dropdownlist & start button. After clicking 2nd form appears, 2nd form shows one label for question, radiobuttonlist for answers ,next & checkbox for review. I am creating array of random question ids in start button click event of the 1stform. when i click next button in 2nd form then next random question appears, i want array of questions those are checked for review. I used code for arrays of values ( eg.10101) 1 for true & 0 for false as follows but i want array of that question ids those are checked:

        int[] a = (int[])Session["values"];//this is array of random question ids created in 1st form
        int g;
        if (chkmark.Checked == true)
        {
            g = 1;
        }
        else
        {
            g = 0;
        }
        int[] chkarray = new int[Convert.ToInt32(Session["Counter"]) - 1];
        int[] temp1 = (int[])Session["arrofchk"];
        int k, no;

        if (temp1 == null)
            no = 0;
        else
            no = temp.Length;
        for (k = 0; k < no; k++)
        {
       chkarray[k] = temp1[k];
        }
        chkarray[j] = g;

Body:
Personally, i would use a Dictionary<int, bool> for this.

In the key of the dictionary, you can store the random Question ID, in the value of the pair, you can store the checked item state. It might take you more work now to refactor it, but I believe it will save you a lot of time in the end when you want to do more actions on your quiz items.

Using a dictionary - or at least a well chosen collection, I think it will be easier to get the right data back.

For your example, it can work only if the positions of both arrays are the same.

Dictionary<int, bool> quizAnswers = new Dictionary<int, bool>(); // <questionID, checked>

// Fill dictionary with questions and answers
for(int i=0;i<a.length;i++)
{
  if(temp1.length > i) // Make sure we don't get an IndexOutOfBoundsException
  {
    quizAnswers.Add(a[i], temp1[i] == 1);
  }
}

// Get Answered question in array ( LINQ )
int[] checkedAnswers = (from KeyValuePair<int, bool> pair in quizAnswers
                        where pair.Value == true
                        select pair.Key).ToArray<int>();

The reason I am using a Dictionary here, is because I personally think it's neater than having two separate arrays.

I believe you should implement a Dictionary in your quiz, in stead of those arrays. What if the array indexes don't match, or you want to dynamically add a question to a fixed size array, etc..

It's something to take into consideration. Hope I could help you out.


来源: stackexchange

问:
PHP - loops through an associative array and show each group as doc1, doc 2, doc3 and text1 and text 2
I have a list of 2 types of documents uploaded by a user. I need to display these documents for each type as such TypeADoc 1, TypeADoc 2, TypeADoc 3 and TypeBDoc 1, TypeBDoc 2 in an html table.

Can somebody please help me. Here is what i have done so far:

```<code>$doc_list_terminer = clients::recupereListDocClientTerminerPourProjet($CLIENT_PROJET_ID);
$iDocs             = 0;
while ($iDocs < count($doc_list_terminer)) {
    $CLIENT_PROJET_DOC_CLIENT_ID = $doc_list_terminer[$iDocs]['CLIENT_PROJET_DOC_CLIENT_ID'];?>
    <tr>
        <td width="45%">
            <?php echo ($doc_list_terminer[$iDocs]['DOC_CLIENT_NOM']); ?>
        </td>
        <td width="45%">
            <span class="textFromDB"><a href="<?php echo $doc_list_terminer[$iDocs]['CLIENT_PROJET_DOC_CLIENT_MODELE_DOC']; ?>" target="_blank">
                    <?php echo basename($doc_list_terminer[$iDocs]['CLIENT_PROJET_DOC_CLIENT_MODELE_DOC']); ?></a> </span>
        </td>
        <?php
    if (isset($isModification) && $isModification === true) {
            ?>
            <td width="5%">
                <a href="javascript:void(0);" id="btnDelDocClientProjet" onclick="delDocClientProjet(<?php echo $doc_list_terminer[$iDocs]['CLIENT_PROJET_DOC_CLIENT_ID'] ?>);"><img src="/images/delete.gif" alt="Modification" width="15" height="15"></a>
            </td>
            <?php
    }
    ?>
    </tr>
    <?php
$iDocs++;
}
</code>```

Sample Data:

```<code>Array
(
    [901] => Array
        (
            [0] => Array
                (
                    [CLIENT_PROJET_DOC_CLIENT_ID] => 701
                    [CLIENT_PROJET_ID] => 5701
                    [CLIENT_ID] => 3401
                    [PROJET_ID] => 3901
                    [DOC_CLIENT_ID] => 901
                    [CLIENT_PROJET_DOC_CLIENT_MODELE_DOC] => seo.txt
                    [DOC_CLIENT_NOM] => Pièce identité
                )

            [1] => Array
                (
                    [CLIENT_PROJET_DOC_CLIENT_ID] => 901
                    [CLIENT_PROJET_ID] => 5701
                    [CLIENT_ID] => 3401
                    [PROJET_ID] => 3901
                    [DOC_CLIENT_ID] => 901
                    [CLIENT_PROJET_DOC_CLIENT_MODELE_DOC] => Tags Manip.txt
                    [DOC_CLIENT_NOM] => Pièce identité
                )

            [2] => Array
                (
                    [CLIENT_PROJET_DOC_CLIENT_ID] => 1001
                    [CLIENT_PROJET_ID] => 5701
                    [CLIENT_ID] => 3401
                    [PROJET_ID] => 3901
                    [DOC_CLIENT_ID] => 901
                    [CLIENT_PROJET_DOC_CLIENT_MODELE_DOC] => test 2.txt
                    [DOC_CLIENT_NOM] => Pièce identité
                )
        )

    [1001] => Array
        (
            [0] => Array
                (
                    [CLIENT_PROJET_DOC_CLIENT_ID] => 101
                    [CLIENT_PROJET_ID] => 5701
                    [CLIENT_ID] => 3401
                    [PROJET_ID] => 3901
                    [DOC_CLIENT_ID] => 1001
                    [CLIENT_PROJET_DOC_CLIENT_MODELE_DOC] => html dom.txt
                    [DOC_CLIENT_NOM] => Nom de société
                )

            [1] => Array
                (
                    [CLIENT_PROJET_DOC_CLIENT_ID] => 1010
                    [CLIENT_PROJET_ID] => 5701
                    [CLIENT_ID] => 3401
                    [PROJET_ID] => 3901
                    [DOC_CLIENT_ID] => 1001
                    [CLIENT_PROJET_DOC_CLIENT_MODELE_DOC] => FINTECH.txt
                    [DOC_CLIENT_NOM] => Nom de société
                )
        )
)
</code>```

答:
Generally, I would recommend you to try to separate logic and view (see MVC architecture). There are plenty of frameworks, one of most common is Laravel.

If you choose to have everything in the same file, try to concentrate all php code you can in a function, so your html is not full of php code.

You can start changing the while condition into:

```<code>foreach ($doc_list_terminer as $key => $value) {
    dd($key, $value)
}
</code>```

The dd function (as var_dump) will help you to debug your code and see the value of each variable (don't forget to remove it when you finish developing!).

=========== UPDATE ===========

In order to translate de CLIENT_PROJET_DOC_CLIENT_ID to its textual value, you can either create another table and use JOIN in order to have this text inside your associative array, or create (inside a function for example) an ENUM array that will do this work.

You can also use switch statement for taht.

ContentLicense: CC BY-SA 4.0

Body:
I have a list of 2 types of documents uploaded by a user. I need to display these documents for each type as such TypeADoc 1, TypeADoc 2, TypeADoc 3 and TypeBDoc 1, TypeBDoc 2 in an html table.

Can somebody please help me. Here is what i have done so far:

$doc_list_terminer = clients::recupereListDocClientTerminerPourProjet($CLIENT_PROJET_ID);
$iDocs             = 0;
while ($iDocs < count($doc_list_terminer)) {
    $CLIENT_PROJET_DOC_CLIENT_ID = $doc_list_terminer[$iDocs]['CLIENT_PROJET_DOC_CLIENT_ID'];?>

            <?php echo ($doc_list_terminer[$iDocs]['DOC_CLIENT_NOM']); ?>

            <a href="<?php echo $doc_list_terminer[$iDocs]['CLIENT_PROJET_DOC_CLIENT_MODELE_DOC']; ?>" target="_blank">
                    <?php echo basename($doc_list_terminer[$iDocs]['CLIENT_PROJET_DOC_CLIENT_MODELE_DOC']); ?>

        <?php
    if (isset($isModification) && $isModification === true) {
            ?>

                <a href="javascript:void(0);" id="btnDelDocClientProjet" onclick="delDocClientProjet(<?php echo $doc_list_terminer[$iDocs]['CLIENT_PROJET_DOC_CLIENT_ID'] ?>);">

            <?php
    }
    ?>

    <?php
$iDocs++;
}

Sample Data:

Array
(
    [901] => Array
        (
            [0] => Array
                (
                    [CLIENT_PROJET_DOC_CLIENT_ID] => 701
                    [CLIENT_PROJET_ID] => 5701
                    [CLIENT_ID] => 3401
                    [PROJET_ID] => 3901
                    [DOC_CLIENT_ID] => 901
                    [CLIENT_PROJET_DOC_CLIENT_MODELE_DOC] => seo.txt
                    [DOC_CLIENT_NOM] => Pièce identité
                )

            [1] => Array
                (
                    [CLIENT_PROJET_DOC_CLIENT_ID] => 901
                    [CLIENT_PROJET_ID] => 5701
                    [CLIENT_ID] => 3401
                    [PROJET_ID] => 3901
                    [DOC_CLIENT_ID] => 901
                    [CLIENT_PROJET_DOC_CLIENT_MODELE_DOC] => Tags Manip.txt
                    [DOC_CLIENT_NOM] => Pièce identité
                )

            [2] => Array
                (
                    [CLIENT_PROJET_DOC_CLIENT_ID] => 1001
                    [CLIENT_PROJET_ID] => 5701
                    [CLIENT_ID] => 3401
                    [PROJET_ID] => 3901
                    [DOC_CLIENT_ID] => 901
                    [CLIENT_PROJET_DOC_CLIENT_MODELE_DOC] => test 2.txt
                    [DOC_CLIENT_NOM] => Pièce identité
                )
        )

    [1001] => Array
        (
            [0] => Array
                (
                    [CLIENT_PROJET_DOC_CLIENT_ID] => 101
                    [CLIENT_PROJET_ID] => 5701
                    [CLIENT_ID] => 3401
                    [PROJET_ID] => 3901
                    [DOC_CLIENT_ID] => 1001
                    [CLIENT_PROJET_DOC_CLIENT_MODELE_DOC] => html dom.txt
                    [DOC_CLIENT_NOM] => Nom de société
                )

            [1] => Array
                (
                    [CLIENT_PROJET_DOC_CLIENT_ID] => 1010
                    [CLIENT_PROJET_ID] => 5701
                    [CLIENT_ID] => 3401
                    [PROJET_ID] => 3901
                    [DOC_CLIENT_ID] => 1001
                    [CLIENT_PROJET_DOC_CLIENT_MODELE_DOC] => FINTECH.txt
                    [DOC_CLIENT_NOM] => Nom de société
                )
        )
)

Body:
Generally, I would recommend you to try to separate logic and view (see MVC architecture). There are plenty of frameworks, one of most common is Laravel.

If you choose to have everything in the same file, try to concentrate all php code you can in a function, so your html is not full of php code.

You can start changing the while condition into:

foreach ($doc_list_terminer as $key => $value) {
    dd($key, $value)
}

The dd function (as var_dump) will help you to debug your code and see the value of each variable (don't forget to remove it when you finish developing!).

=========== UPDATE ===========

In order to translate de CLIENT_PROJET_DOC_CLIENT_ID to its textual value, you can either create another table and use JOIN in order to have this text inside your associative array, or create (inside a function for example) an ENUM array that will do this work.

You can also use switch statement for taht.


问:
Show function data without blinking with Volley in Android Studio
Recently I am working on Android project with Volley for registration and for further operation, I can make function for insertion and other one is for retrieval data. When insert button click 'Insert' function called and data has been inserted to database through volley, and at the same time retrieval function also called. But when USER clicked the button and function called then data showed(database inserted data) with blinking effect, look like loading.

I want to get rid of that effect. I want to show data smoothly without any blinking effect. I do searching but can not find any solution. Please suggest me solution I'am newbie so kindly short and efficient required.

```<code>package com.darkcoderz.parsejson;

public class MainActivity extends AppCompatActivity {
private Context mContext;
private Activity mActivity;

//private CoordinatorLayout mCLayout;
private TextView mTextView;
private String mJSONURLString = "http://192.168.10.4/volley/api.php";
String url = "http://192.168.10.4/volley/register.php";
private EditText sms;
private Button sendsms;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // Get the application context
    //mContext = getApplicationContext();
    //mActivity = MainActivity.this;

    // Get the widget reference from XML layout
    //mCLayout = (CoordinatorLayout) findViewById(R.id.coordinator_layout);
    mTextView = (TextView) findViewById(R.id.tv);

    sms = (EditText) findViewById(R.id.sms);
    sendsms = (Button) findViewById(R.id.sendsms);

    final Handler firesms = new Handler();
    firesms.post(new Runnable() {
        @Override
        public void run() {
            getdata();
            firesms.postDelayed(this, 100);
        }
    });

    sendsms.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            reg();
        }
    });

    getdata();
}

 //    insert
  public void reg()
 {
final String msg = sms.getText().toString();
StringRequest stringreq = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
    @Override
    public void onResponse(String response) {
        if (response.equals("success"))
        {
            Toast.makeText(MainActivity.this, "Registration Successfull!", Toast.LENGTH_SHORT).show();
        }
        else
        {
            Toast.makeText(MainActivity.this, "Username Already Exist!", Toast.LENGTH_SHORT).show();
        }

    }
}, new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error) {
        Toast.makeText(MainActivity.this, "Great Error "+error.toString(), Toast.LENGTH_LONG).show();
    }
})
{
    @Override
    protected Map<String, String> getParams() throws AuthFailureError {
        Map<String,String> params = new HashMap<>();
        params.put("sms",msg);
        return params;
    }
};
RequestQueue reqest = Volley.newRequestQueue(MainActivity.this);
reqest.add(stringreq);
</code>```

}

```<code>private void getdata() {

            // Empty the TextView
            mTextView.setText("");

            // Initialize a new RequestQueue instance
            RequestQueue requestQueue = Volley.newRequestQueue(MainActivity.this);

            // Initialize a new JsonArrayRequest instance
            JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, mJSONURLString, null, new Response.Listener<JSONArray>() {
                @Override
                public void onResponse(JSONArray response) {
                    // Do something with response
                    //mTextView.setText(response.toString());

                    // Process the JSON
                    try{
                        // Loop through the array elements
                        for(int i=0;i<response.length();i++){
                            // Get current json object
                            JSONObject student = response.getJSONObject(i);

                            // Get the current student (json object) data
             //                                String firstName = student.getString("fname");
                //                                String lastName = student.getString("lname");
                            String age = student.getString("email");

                            // Display the formatted json data in text view
                            mTextView.append("SMS : " + age);
                            mTextView.append("\n\n");
                        }
                    }catch (JSONException e){
                        e.printStackTrace();
                    }
                }
            },
                    new Response.ErrorListener(){
                        @Override
                        public void onErrorResponse(VolleyError error){
                            // Do something when error occurred

                            Toast.makeText(mContext, "Something Went Wrong", Toast.LENGTH_SHORT).show();
                        }
                    }
            );

            // Add JsonArrayRequest to the RequestQueue
            requestQueue.add(jsonArrayRequest);

}
</code>```

}

答:
```<code>private void getdata() {

        // Empty the TextView
        mTextView.setText("");

        // Initialize a new RequestQueue instance
        RequestQueue requestQueue = Volley.newRequestQueue(MainActivity.this);

        // Initialize a new JsonArrayRequest instance
        JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, mJSONURLString, null, new Response.Listener<JSONArray>() {
            @Override
            public void onResponse(JSONArray response) {
                //before parsing check your response is in JSONArray Format or JSONObject format
                // Process the JSON
                try{

                }catch (JSONException e){
                    e.printStackTrace();
                   //print here to know JSONException if exists
                   Toast.makeText(mContext, "Exception"+e.toString(), Toast.LENGTH_SHORT).show();
                }
                }
            }
        },
                new Response.ErrorListener(){
                    @Override
                    public void onErrorResponse(VolleyError error){
                        // Do something when error occurred

                        Toast.makeText(mContext, "Something Went Wrong", Toast.LENGTH_SHORT).show();
                    }
                }
        );

        // Add JsonArrayRequest to the RequestQueue
        requestQueue.add(jsonArrayRequest);
   }
</code>```

Body:
Recently I am working on Android project with Volley for registration and for further operation, I can make function for insertion and other one is for retrieval data. When insert button click 'Insert' function called and data has been inserted to database through volley, and at the same time retrieval function also called. But when USER clicked the button and function called then data showed(database inserted data) with blinking effect, look like loading.

I want to get rid of that effect. I want to show data smoothly without any blinking effect. I do searching but can not find any solution. Please suggest me solution I'am newbie so kindly short and efficient required.

package com.darkcoderz.parsejson;

public class MainActivity extends AppCompatActivity {
private Context mContext;
private Activity mActivity;

//private CoordinatorLayout mCLayout;
private TextView mTextView;
private String mJSONURLString = "http://192.168.10.4/volley/api.php";
String url = "http://192.168.10.4/volley/register.php";
private EditText sms;
private Button sendsms;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // Get the application context
    //mContext = getApplicationContext();
    //mActivity = MainActivity.this;

    // Get the widget reference from XML layout
    //mCLayout = (CoordinatorLayout) findViewById(R.id.coordinator_layout);
    mTextView = (TextView) findViewById(R.id.tv);

    sms = (EditText) findViewById(R.id.sms);
    sendsms = (Button) findViewById(R.id.sendsms);

    final Handler firesms = new Handler();
    firesms.post(new Runnable() {
        @Override
        public void run() {
            getdata();
            firesms.postDelayed(this, 100);
        }
    });

    sendsms.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            reg();
        }
    });

    getdata();
}

 //    insert
  public void reg()
 {
final String msg = sms.getText().toString();
StringRequest stringreq = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
    @Override
    public void onResponse(String response) {
        if (response.equals("success"))
        {
            Toast.makeText(MainActivity.this, "Registration Successfull!", Toast.LENGTH_SHORT).show();
        }
        else
        {
            Toast.makeText(MainActivity.this, "Username Already Exist!", Toast.LENGTH_SHORT).show();
        }

    }
}, new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error) {
        Toast.makeText(MainActivity.this, "Great Error "+error.toString(), Toast.LENGTH_LONG).show();
    }
})
{
    @Override
    protected Map<String, String> getParams() throws AuthFailureError {
        Map<String,String> params = new HashMap<>();
        params.put("sms",msg);
        return params;
    }
};
RequestQueue reqest = Volley.newRequestQueue(MainActivity.this);
reqest.add(stringreq);

}

private void getdata() {

            // Empty the TextView
            mTextView.setText("");

            // Initialize a new RequestQueue instance
            RequestQueue requestQueue = Volley.newRequestQueue(MainActivity.this);

            // Initialize a new JsonArrayRequest instance
            JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, mJSONURLString, null, new Response.Listener<JSONArray>() {
                @Override
                public void onResponse(JSONArray response) {
                    // Do something with response
                    //mTextView.setText(response.toString());

                    // Process the JSON
                    try{
                        // Loop through the array elements
                        for(int i=0;i<response.length();i++){
                            // Get current json object
                            JSONObject student = response.getJSONObject(i);

                            // Get the current student (json object) data
             //                                String firstName = student.getString("fname");
                //                                String lastName = student.getString("lname");
                            String age = student.getString("email");

                            // Display the formatted json data in text view
                            mTextView.append("SMS : " + age);
                            mTextView.append("\n\n");
                        }
                    }catch (JSONException e){
                        e.printStackTrace();
                    }
                }
            },
                    new Response.ErrorListener(){
                        @Override
                        public void onErrorResponse(VolleyError error){
                            // Do something when error occurred

                            Toast.makeText(mContext, "Something Went Wrong", Toast.LENGTH_SHORT).show();
                        }
                    }
            );

            // Add JsonArrayRequest to the RequestQueue
            requestQueue.add(jsonArrayRequest);

}

}


问:
How to use Array.protoype.map() on array of objects to filter out some specific keys based on it's values?
I have the following array of objects, in which some specific keys have a value which is either a string or an array. I want to get the keys with string values as it is and remove "NA" from keys with array values.

I am trying to achieve the same by doing .map method on the array, check the type of the value of each key in the data object, if an array then use .filter to remove the "NA" values.

```<code>var dataArr = [
    {
     a: 'foo',
     b: [1, 2, "NA", "NA", 3],
     c: ["NA", 6]
    },
    {
     a: 'bar',
     b: ["NA", "NA", "NA"],
     c: []
    }
];
dataArr.map(dataObj => {
    for (let key in dataObj) {
        if (key !== 'a')
            dataObj[key] = dataObj[key].filter(val => { if(val != "NA") return val})
    }
    return dataObj;
});
</code>```

The above block of code works as expected but I want a better and future-proof solution. Moreover, this looks bad too.

答:
You can do that using nested map() and filter()

First of all use map() on the main array.

Then get the entries of each object using Object.entries()

Then use map() on the entries of each object.

Return the value as it is if the Array.isArray is false otherwise return the filtered value of array.

Finally use Object.fromEntries() to make an object.

var dataArr = [
    {
     a: 'foo',
     b: [1, 2, "NA", "NA", 3],
     c: ["NA", 6]
    },
    {
     a: 'bar',
     b: ["NA", "NA", "NA"],
     c: []
    }
];

const res = dataArr.map(x =>
               Object.fromEntries(
                   Object.entries(x)
                     .map(([k,v]) =>
                        [k,Array.isArray(v) ? v.filter(b => b !== "NA") : v])
                     )
               )

console.log(res)```

Body:
I have the following array of objects, in which some specific keys have a value which is either a string or an array. I want to get the keys with string values as it is and remove "NA" from keys with array values.

I am trying to achieve the same by doing .map method on the array, check the type of the value of each key in the data object, if an array then use .filter to remove the "NA" values.

var dataArr = [
    {
     a: 'foo',
     b: [1, 2, "NA", "NA", 3],
     c: ["NA", 6]
    },
    {
     a: 'bar',
     b: ["NA", "NA", "NA"],
     c: []
    }
];
dataArr.map(dataObj => {
    for (let key in dataObj) {
        if (key !== 'a')
            dataObj[key] = dataObj[key].filter(val => { if(val != "NA") return val})
    }
    return dataObj;
});

The above block of code works as expected but I want a better and future-proof solution. Moreover, this looks bad too.


答:
If you just want to update the original array, you could loop through the array using forEach. Then loop through each object's keys using for...in and check if it is an array using Array.isArray(). Update the property after filtering out the NA value

const dataArr = [{a:'foo',b:[1,2,"NA","NA",3],c:["NA",6]},{a:'bar',b:["NA","NA","NA"],c:[]}];

dataArr.forEach(o => {
  for (const key in o) {
    if (Array.isArray(o[key]))
      o[key] = o[key].filter(s => s !== "NA")
  }
})

console.log(dataArr)```
</div>
</div>
</p>

<p>If you want to get a new array without mutating the original objects, you can use <code>map</code> like this:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const dataArr = [{a:'foo',b:[1,2,"NA","NA",3],c:["NA",6]},{a:'bar',b:["NA","NA","NA"],c:[]}];

const newArray = dataArr.map(o => {
  const newObj = {};

  for (const key in o) {
    if (Array.isArray(o[key]))
      newObj[key] = o[key].filter(s => s !== "NA")
    else
      newObj[key] = o[key]
  }

  return newObj;
})

console.log(newArray)</code>```

Title: How to use Array.protoype.map() on array of objects to filter out some specific keys based on it's values?

Body:
If you just want to update the original array, you could loop through the array using forEach. Then loop through each object's keys using for...in and check if it is an array using Array.isArray(). Update the property after filtering out the NA value

const dataArr = [{a:'foo',b:[1,2,"NA","NA",3],c:["NA",6]},{a:'bar',b:["NA","NA","NA"],c:[]}];

dataArr.forEach(o => {
  for (const key in o) {
    if (Array.isArray(o[key]))
      o[key] = o[key].filter(s => s !== "NA")
  }
})

console.log(dataArr)

If you want to get a new array without mutating the original objects, you can use map like this:

const dataArr = [{a:'foo',b:[1,2,"NA","NA",3],c:["NA",6]},{a:'bar',b:["NA","NA","NA"],c:[]}];

const newArray = dataArr.map(o => {
  const newObj = {};

  for (const key in o) {
    if (Array.isArray(o[key]))
      newObj[key] = o[key].filter(s => s !== "NA")
    else
      newObj[key] = o[key]
  }

  return newObj;
})

console.log(newArray)


问:
python openpyxl max_row counts all the rows instead of counting non-empty rows
I am using a excel sheet where it has 999 in total of rows and in which 20 rows are data filled rows and others are empty.

so when i print max_rows it gives me 999 numbers instead of 20 number! i am following this tutorial - openpyxl tutorial

```<code>wb = openpyxl.load_workbook(path)
s = wb.active
print(s.max_row)
</code>```

答:
You'll need to count them yourself if you want to use openpyxl

```<code>wb = openpyxl.load_workbook(path)
ws = wb.active
count = 0
for row in ws:
    if not all([cell.value is None for cell in row]):
        count += 1

print(count)
</code>```

Or

```<code>wb = openpyxl.load_workbook(path)
ws = wb.active
print(len([row for row in ws if not all([cell.value is None for cell in row])]))
</code>```

Explanation

If a cell doesn't have any value in an xlsx it is None when you get its value. The check cell.value is None for cell in row will only trigger if a row doesn't have any data at all. You could easily swap all for any to not count rows with any empty fields.

Body:
I am using a excel sheet where it has 999 in total of rows and in which 20 rows are data filled rows and others are empty.

so when i print max_rows it gives me 999 numbers instead of 20 number! i am following this tutorial - openpyxl tutorial

wb = openpyxl.load_workbook(path)
s = wb.active
print(s.max_row)

Body:
You'll need to count them yourself if you want to use openpyxl

wb = openpyxl.load_workbook(path)
ws = wb.active
count = 0
for row in ws:
    if not all([cell.value is None for cell in row]):
        count += 1

print(count)

Or

wb = openpyxl.load_workbook(path)
ws = wb.active
print(len([row for row in ws if not all([cell.value is None for cell in row])]))

Explanation

If a cell doesn't have any value in an xlsx it is None when you get its value. The check cell.value is None for cell in row will only trigger if a row doesn't have any data at all. You could easily swap all for any to not count rows with any empty fields.


问:
Avg of multiple columns in project operator
We have 2 customlogs in loganalytics out of that I am able to get avg of each one and I need to merge those 2 and make it as 1 means avg of vpn+url </p>

```<code>workspace(name).vpn_CL
| extend healty=iff(Status_s == 'Connected' , 100 , 0)
| summarize vpn = avg(healty) by EnvName_s, ClientName_s
|
join
(
    workspace(name).url_CL
    | extend Availability=iff(StatusDescription_s == 'OK' , 100 , 0)
    | summarize URL=avg(Availability) by EnvName_s, ClientName_s
 ) on ClientName_s
  | project Client=ClientName_s, Environment=EnvName_s , vpn , URL
</code>```

答:
Based on my understanding, I think the value of the average of vpn+url is the result of plus vpn value with url value when the number of healty entites is equals to the number of Availability entites.

Otherwise, if their entites quantity are not equal, the average of the two labels is a expected value based on their probabilities,

Then,

```<code>workspace(name).vpn_CL
| extend healty=iff(Status_s == 'Connected' , 100 , 0)
| summarize m = count(), vpn = avg(healty) by EnvName_s, ClientName_s
|
join
(
    workspace(name).url_CL
    | extend Availability=iff(StatusDescription_s == 'OK' , 100 , 0)
    | summarize n = count(), URL=avg(Availability) by EnvName_s, ClientName_s
 ) on ClientName_s
  | project Client=ClientName_s, Environment=EnvName_s , vpn , URL, avgOfVpnUrl = vpn*m/(m+n)+url*n/(m+n)
</code>```

Hope it helps.

Body:
We have 2 customlogs in loganalytics out of that I am able to get avg of each one and I need to merge those 2 and make it as 1 means avg of vpn+url

workspace(name).vpn_CL
| extend healty=iff(Status_s == 'Connected' , 100 , 0)
| summarize vpn = avg(healty) by EnvName_s, ClientName_s
|
join
(
    workspace(name).url_CL
    | extend Availability=iff(StatusDescription_s == 'OK' , 100 , 0)
    | summarize URL=avg(Availability) by EnvName_s, ClientName_s
 ) on ClientName_s
  | project Client=ClientName_s, Environment=EnvName_s , vpn , URL

Body:
Based on my understanding, I think the value of the average of vpn+url is the result of plus vpn value with url value when the number of healty entites is equals to the number of Availability entites.

Otherwise, if their entites quantity are not equal, the average of the two labels is a expected value based on their probabilities,

Then,

workspace(name).vpn_CL
| extend healty=iff(Status_s == 'Connected' , 100 , 0)
| summarize m = count(), vpn = avg(healty) by EnvName_s, ClientName_s
|
join
(
    workspace(name).url_CL
    | extend Availability=iff(StatusDescription_s == 'OK' , 100 , 0)
    | summarize n = count(), URL=avg(Availability) by EnvName_s, ClientName_s
 ) on ClientName_s
  | project Client=ClientName_s, Environment=EnvName_s , vpn , URL, avgOfVpnUrl = vpn*m/(m+n)+url*n/(m+n)

Hope it helps.


问:
How to implement a custom loss function with canned estimators in Tensorflow?
I am new to tensorflow.

Question: How can I add a custom loss function to a canned estimator like DNNLinearCombinedRegressor?

Thank you in advance for your help!

答:
I did not find a loss_fn argument to pass in to DNNLinearCombinedRegressor. But it looks straightforward to define any custom estimator:

A good reference is the code for DNNLinearCombinedRegressor.

I believe you need following steps:

define a custom loss_fn (what ever you like)

define or use a RegressionHead that uses the custom loss_fn defined above.

pass the custom head to your own Regressor. Of course, you might need to copy/build your own model_fn as well.


问:
Linking a C module to MASM in Visual Studio
I am working on a big MASM project (I've Compiled my MASM code using the ML compiler under VS 2019) , and I would like to call a C function I wrote, within my MASM code. I googled it a lot , but I couldn't find anything useful. How can I achieve that?

When I just tried to add my C source-code to the project and rebuild it , I got a bunch of linking errors (LNK2019) , like these:

LNK2019 unresolved external symbol __CrtDbgReport referenced in function __CRT_RTC_INIT

LNK2019 unresolved external symbol __CrtDbgReportW referenced in function __CRT_RTC_INITW

LNK2019 unresolved external symbol ___stdio_common_vsprintf_s referenced in function __vsprintf_s_l

Here is a screenshot of the errors window

答:
Answering my question

I've finally figured out a way to do this.

Create a Static library (.lib) from your C/C++ module.

Properies -> Project Defaults -> Configuration Type -> change to .lib

and then, In your masm code , add these lines:

```<code>includelib your_generated_lib.lib
</code>```

(Be sure to add your lib file to the directory of your masm code)

and add prototypes to your functoins like this:

```<code>function_name PROTO C :DWORD   ;(Just an Example )
</code>```

Hope it helps,

Omer

Body:
Answering my question

I've finally figured out a way to do this.

Create a Static library (.lib) from your C/C++ module.

Properies -> Project Defaults -> Configuration Type -> change to .lib

and then, In your masm code , add these lines:

includelib your_generated_lib.lib

(Be sure to add your lib file to the directory of your masm code)

and add prototypes to your functoins like this:

function_name PROTO C :DWORD   ;(Just an Example )

Hope it helps,

Omer


问:
Why is the bootstrap col not taking 12 columns automatically?
I am trying to make three cards behaving in a way in Bootstrap.

All three cards stack horizontally in laptop view and above (col-lg-4). This works fine.

First two cards stack up horizontally in iPad view while the last card stacks vertically below them (col-md-6 for first two and col-md-12 for last card). This works fine as well.

Since I didn't declare the behavior for mobile, I expect all three cards to automatically stack up vertically in small screen (mobile and below), but this isn't the case. The first two just take 6 cols each for mobile and even smaller screens.

I have tried adding the default col class to the first two but they don't work as well.

```<code>    <div class="col col-lg-4 col-md-6">
      <div class="card">
        <div class="card-header">
          <h3>Chihuahua</h3>
        </div>
        <div class="card-body">
          <h2>Free</h2>
          <p>5 Matches Per Day</p>
          <p>10 Messages Per Day</p>
          <p>Unlimited App Usage</p>
          <button type="button">Sign Up</button>
        </div>

      </div>

    </div>

    <div class="col col-lg-4 col-md-6">
      <div class="card">
        <div class="card-header">
          <h3>Labrador</h3>
        </div>
        <div class="card-body">
          <h2>$49 / mo</h2>
          <p>Unlimited Matches</p>
          <p>Unlimited Messages</p>
          <p>Unlimited App Usage</p>
          <button type="button">Sign Up</button>

        </div>

      </div>
    </div>

    <div class="col-lg-4">
      <div class="card">
        <div class="card-header">
          <h3>Mastiff</h3>
        </div>
        <div class="card-body">
          <h2>$99 / mo</h2>
          <p>Pirority Listing</p>
          <p>Unlimited Matches</p>
          <p>Unlimited Messages</p>
          <p>Unlimited App Usage</p>
          <button type="button">Sign Up</button>
        </div>

      </div>
    </div>
</code>```

I expect all cards to stack up vertically when I go to mobile view, the first two in a horizontal line when I'm in iPad view but the third in vertical below them. But first two remains in horizontal line while 3rd is below in mobile and even smaller screens.

答:
Hope this is what you want. This solution is for  Bootstrap 3. If you are working on Bootstrap 4, then you will have to do some grid adjustments.</p>

```<code> <div class="container-fluid">

     <div class="row">

         <div class="col-sm-6 col-md-4">
             <div class="card">
                 <div class="card-header">
                     <h3>Chihuahua</h3>
                 </div>
                 <div class="card-body">
                     <h2>Free</h2>
                     <p>5 Matches Per Day</p>
                     <p>10 Messages Per Day</p>
                     <p>Unlimited App Usage</p>
                     <button type="button">Sign Up</button>
                 </div>
             </div>
         </div>

         <div class="col-sm-6 col-md-4">
             <div class="card">
                 <div class="card-header">
                    <h3>Labrador</h3>
                 </div>
                 <div class="card-body">
                     <h2>$49 / mo</h2>
                     <p>Unlimited Matches</p>
                     <p>Unlimited Messages</p>
                     <p>Unlimited App Usage</p>
                     <button type="button">Sign Up</button>
                 </div>
             </div>
         </div>

         <div class="col-md-4 visible-xs visible-md visible-lg">
             <div class="card">
                 <div class="card-header">
                     <h3>Mastiff</h3>
                 </div>
                 <div class="card-body">
                     <h2>$99 / mo</h2>
                     <p>Pirority Listing</p>
                     <p>Unlimited Matches</p>
                     <p>Unlimited Messages</p>
                     <p>Unlimited App Usage</p>
                     <button type="button">Sign Up</button>
                 </div>
             </div>
         </div>

         <div class="row visible-sm">
             <div class="col-sm-12">
                 <div class="card">
                     <div class="card-header">
                         <h3>Mastiff</h3>
                     </div>
                     <div class="card-body">
                         <h2>$99 / mo</h2>
                         <p>Pirority Listing</p>
                         <p>Unlimited Matches</p>
                         <p>Unlimited Messages</p>
                         <p>Unlimited App Usage</p>
                         <button type="button">Sign Up</button>
                     </div>
                 </div>
             </div>
         </div>

     </div>

 </div>
</code>```

Body:
I am trying to make three cards behaving in a way in Bootstrap.

All three cards stack horizontally in laptop view and above (col-lg-4). This works fine.

First two cards stack up horizontally in iPad view while the last card stacks vertically below them (col-md-6 for first two and col-md-12 for last card). This works fine as well.

Since I didn't declare the behavior for mobile, I expect all three cards to automatically stack up vertically in small screen (mobile and below), but this isn't the case. The first two just take 6 cols each for mobile and even smaller screens.

I have tried adding the default col class to the first two but they don't work as well.

Chihuahua

Free

5 Matches Per Day

10 Messages Per Day

Unlimited App Usage

          <button type="button">Sign Up</button>

Labrador

$49 / mo

Unlimited Matches

Unlimited Messages

Unlimited App Usage

          <button type="button">Sign Up</button>

Mastiff

$99 / mo

Pirority Listing

Unlimited Matches

Unlimited Messages

Unlimited App Usage

          <button type="button">Sign Up</button>

I expect all cards to stack up vertically when I go to mobile view, the first two in a horizontal line when I'm in iPad view but the third in vertical below them. But first two remains in horizontal line while 3rd is below in mobile and even smaller screens.

Body:
Hope this is what you want. This solution is for  Bootstrap 3. If you are working on Bootstrap 4, then you will have to do some grid adjustments.

 <div class="container-fluid">

     <div class="row">

         <div class="col-sm-6 col-md-4">
             <div class="card">
                 <div class="card-header">
                     <h3>Chihuahua</h3>
                 </div>
                 <div class="card-body">
                     <h2>Free</h2>
                     <p>5 Matches Per Day</p>
                     <p>10 Messages Per Day</p>
                     <p>Unlimited App Usage</p>
                     <button type="button">Sign Up</button>
                 </div>
             </div>
         </div>

         <div class="col-sm-6 col-md-4">
             <div class="card">
                 <div class="card-header">
                    <h3>Labrador</h3>
                 </div>
                 <div class="card-body">
                     <h2>$49 / mo</h2>
                     <p>Unlimited Matches</p>
                     <p>Unlimited Messages</p>
                     <p>Unlimited App Usage</p>
                     <button type="button">Sign Up</button>
                 </div>
             </div>
         </div>

         <div class="col-md-4 visible-xs visible-md visible-lg">
             <div class="card">
                 <div class="card-header">
                     <h3>Mastiff</h3>
                 </div>
                 <div class="card-body">
                     <h2>$99 / mo</h2>
                     <p>Pirority Listing</p>
                     <p>Unlimited Matches</p>
                     <p>Unlimited Messages</p>
                     <p>Unlimited App Usage</p>
                     <button type="button">Sign Up</button>
                 </div>
             </div>
         </div>

         <div class="row visible-sm">
             <div class="col-sm-12">
                 <div class="card">
                     <div class="card-header">
                         <h3>Mastiff</h3>
                     </div>
                     <div class="card-body">
                         <h2>$99 / mo</h2>
                         <p>Pirority Listing</p>
                         <p>Unlimited Matches</p>
                         <p>Unlimited Messages</p>
                         <p>Unlimited App Usage</p>
                         <button type="button">Sign Up</button>
                     </div>
                 </div>
             </div>
         </div>

     </div>

 </div>


问:
How to put icon on string in flutter?
I have array string and I want to put icons inside that string like this,

```<code>var arr = ['lorem ipsum dolor select icon '+Icons(Icons.search)+' blablabla...'];
</code>```

But I got error

```<code>The argument type 'Icons' can't be assigned to the parameter type 'String'
</code>```

How I can solve this problem? thanks

答:
Try declaring a list with the type of dynamic

```<code>List<dynamic> myList = <dynamic>[Text('Hello'),Icon(Icons.add),Text('World')];
</code>```

if you wish to use it inside your widget tree. you can to it by using the row or column widget:

```<code>`Column(children: myList)` OR `Row(children: myList)`
</code>```

Title: How to put icon on string in flutter?

Body:
I have array string and I want to put icons inside that string like this,

var arr = ['lorem ipsum dolor select icon '+Icons(Icons.search)+' blablabla...'];

But I got error

The argument type 'Icons' can't be assigned to the parameter type 'String'

How I can solve this problem? thanks

Body:
Try declaring a list with the type of dynamic

List<dynamic> myList = <dynamic>[Text('Hello'),Icon(Icons.add),Text('World')];

if you wish to use it inside your widget tree. you can to it by using the row or column widget:

`Column(children: myList)` OR `Row(children: myList)`


问:
Airflow: ValueError: Unable to configure handler 'processor' - wasb logger
I am trying to configure remote logging with Azure blob.

```<code>Airflow version: 1.10.2
Python: 3.6.5
Ubuntu: 18.04
</code>```

Following are the step I did:

In $AIRFLOW_HOME/config/log_config.py, I have put REMOTE_BASE_LOG_FOLDER = 'wasb-airflow-logs' (This is a folder inside the container (container name: airflow-logs))

Empty init.py is in $AIRFLOW_HOME/config/

$AIRFLOW_HOME/config/ is added in $PYTHONPATH

Renamed DEFAULT_LOGGING_CONFIG to LOGGING CONFIG everywhere in $AIRFLOW_HOME/config/log_config.py

User defined in Airflow blob connection has read/write access to REMOTE_BASE_LOG_FOLDER

$AIRFLOW_HOME/airflow.cfg it has remote_logging = True
logging_config_class = log_config.LOGGING_CONFIG
remote_log_conn_id =

Following is the error:

```<code>Unable to load the config, contains a configuration error.
Traceback (most recent call last):
  File "/home/gsingh/anaconda3/lib/python3.6/logging/config.py", line 382, in resolve
    found = getattr(found, frag)
AttributeError: module 'airflow.utils.log' has no attribute 'wasb_task_handler'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/gsingh/anaconda3/lib/python3.6/logging/config.py", line 384, in resolve
    self.importer(used)
  File "/home/gsingh/venv/lib/python3.6/site-packages/airflow/utils/log/wasb_task_handler.py", line 23, in <module>
    from airflow.contrib.hooks.wasb_hook import WasbHook
  File "/home/gsingh/venv/lib/python3.6/site-packages/airflow/contrib/hooks/wasb_hook.py", line 22, in <module>
    from airflow.hooks.base_hook import BaseHook
  File "/home/gsingh/venv/lib/python3.6/site-packages/airflow/hooks/base_hook.py", line 28, in <module>
    from airflow.models import Connection
  File "/home/gsingh/venv/lib/python3.6/site-packages/airflow/models.py", line 86, in <module>
    from airflow.utils.dag_processing import list_py_file_paths
  File "/home/gsingh/venv/lib/python3.6/site-packages/airflow/utils/dag_processing.py", line 49, in <module>
    from airflow.settings import logging_class_path
ImportError: cannot import name 'logging_class_path'

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/home/gsingh/anaconda3/lib/python3.6/logging/config.py", line 558, in configure
    handler = self.configure_handler(handlers[name])
  File "/home/gsingh/anaconda3/lib/python3.6/logging/config.py", line 708, in configure_handler
    klass = self.resolve(cname)
  File "/home/gsingh/anaconda3/lib/python3.6/logging/config.py", line 391, in resolve
    raise v
  File "/home/gsingh/anaconda3/lib/python3.6/logging/config.py", line 384, in resolve
    self.importer(used)
  File "/home/gsingh/venv/lib/python3.6/site-packages/airflow/utils/log/wasb_task_handler.py", line 23, in <module>
    from airflow.contrib.hooks.wasb_hook import WasbHook
  File "/home/gsingh/venv/lib/python3.6/site-packages/airflow/contrib/hooks/wasb_hook.py", line 22, in <module>
    from airflow.hooks.base_hook import BaseHook
  File "/home/gsingh/venv/lib/python3.6/site-packages/airflow/hooks/base_hook.py", line 28, in <module>
    from airflow.models import Connection
  File "/home/gsingh/venv/lib/python3.6/site-packages/airflow/models.py", line 86, in <module>
    from airflow.utils.dag_processing import list_py_file_paths
  File "/home/gsingh/venv/lib/python3.6/site-packages/airflow/utils/dag_processing.py", line 49, in <module>
    from airflow.settings import logging_class_path
ValueError: Cannot resolve 'airflow.utils.log.wasb_task_handler.WasbTaskHandler': cannot import name 'logging_class_path'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/gsingh/venv/bin/airflow", line 21, in <module>
    from airflow import configuration
  File "/home/gsingh/venv/lib/python3.6/site-packages/airflow/__init__.py", line 36, in <module>
    from airflow import settings, configuration as conf
  File "/home/gsingh/venv/lib/python3.6/site-packages/airflow/settings.py", line 262, in <module>
    logging_class_path = configure_logging()
  File "/home/gsingh/venv/lib/python3.6/site-packages/airflow/logging_config.py", line 73, in configure_logging
    raise e
  File "/home/gsingh/venv/lib/python3.6/site-packages/airflow/logging_config.py", line 68, in configure_logging
    dictConfig(logging_config)
  File "/home/gsingh/anaconda3/lib/python3.6/logging/config.py", line 795, in dictConfig
    dictConfigClass(config).configure()
  File "/home/gsingh/anaconda3/lib/python3.6/logging/config.py", line 566, in configure
    '%r: %s' % (name, e))
ValueError: Unable to configure handler 'processor': Cannot resolve 'airflow.utils.log.wasb_task_handler.WasbTaskHandler': cannot import name 'logging_class_path'
</code>```

I am not sure which configuration I am missing. Has anyone faced the same issue?

答:
You need to install the azure package.

```<code>pip install 'apache-airflow[azure_blob_storage,azure_data_lake,azure_cosmos,azure_container_instances]
</code>```

As per updating.md

This now should be installed with

```<code>pip install apache-airflow[azure]
</code>```

But this didn't work for me.

Body:
I am trying to configure remote logging with Azure blob.

Airflow version: 1.10.2
Python: 3.6.5
Ubuntu: 18.04

Following are the step I did:

In $AIRFLOW_HOME/config/log_config.py, I have put REMOTE_BASE_LOG_FOLDER = 'wasb-airflow-logs' (This is a folder inside the container (container name: airflow-logs))

Empty init.py is in $AIRFLOW_HOME/config/

$AIRFLOW_HOME/config/ is added in $PYTHONPATH

Renamed DEFAULT_LOGGING_CONFIG to LOGGING CONFIG everywhere in $AIRFLOW_HOME/config/log_config.py

User defined in Airflow blob connection has read/write access to REMOTE_BASE_LOG_FOLDER

$AIRFLOW_HOME/airflow.cfg it has remote_logging = True
logging_config_class = log_config.LOGGING_CONFIG
remote_log_conn_id =

Following is the error:

Unable to load the config, contains a configuration error.
Traceback (most recent call last):
  File "/home/gsingh/anaconda3/lib/python3.6/logging/config.py", line 382, in resolve
    found = getattr(found, frag)
AttributeError: module 'airflow.utils.log' has no attribute 'wasb_task_handler'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/gsingh/anaconda3/lib/python3.6/logging/config.py", line 384, in resolve
    self.importer(used)
  File "/home/gsingh/venv/lib/python3.6/site-packages/airflow/utils/log/wasb_task_handler.py", line 23, in <module>
    from airflow.contrib.hooks.wasb_hook import WasbHook
  File "/home/gsingh/venv/lib/python3.6/site-packages/airflow/contrib/hooks/wasb_hook.py", line 22, in <module>
    from airflow.hooks.base_hook import BaseHook
  File "/home/gsingh/venv/lib/python3.6/site-packages/airflow/hooks/base_hook.py", line 28, in <module>
    from airflow.models import Connection
  File "/home/gsingh/venv/lib/python3.6/site-packages/airflow/models.py", line 86, in <module>
    from airflow.utils.dag_processing import list_py_file_paths
  File "/home/gsingh/venv/lib/python3.6/site-packages/airflow/utils/dag_processing.py", line 49, in <module>
    from airflow.settings import logging_class_path
ImportError: cannot import name 'logging_class_path'

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/home/gsingh/anaconda3/lib/python3.6/logging/config.py", line 558, in configure
    handler = self.configure_handler(handlers[name])
  File "/home/gsingh/anaconda3/lib/python3.6/logging/config.py", line 708, in configure_handler
    klass = self.resolve(cname)
  File "/home/gsingh/anaconda3/lib/python3.6/logging/config.py", line 391, in resolve
    raise v
  File "/home/gsingh/anaconda3/lib/python3.6/logging/config.py", line 384, in resolve
    self.importer(used)
  File "/home/gsingh/venv/lib/python3.6/site-packages/airflow/utils/log/wasb_task_handler.py", line 23, in <module>
    from airflow.contrib.hooks.wasb_hook import WasbHook
  File "/home/gsingh/venv/lib/python3.6/site-packages/airflow/contrib/hooks/wasb_hook.py", line 22, in <module>
    from airflow.hooks.base_hook import BaseHook
  File "/home/gsingh/venv/lib/python3.6/site-packages/airflow/hooks/base_hook.py", line 28, in <module>
    from airflow.models import Connection
  File "/home/gsingh/venv/lib/python3.6/site-packages/airflow/models.py", line 86, in <module>
    from airflow.utils.dag_processing import list_py_file_paths
  File "/home/gsingh/venv/lib/python3.6/site-packages/airflow/utils/dag_processing.py", line 49, in <module>
    from airflow.settings import logging_class_path
ValueError: Cannot resolve 'airflow.utils.log.wasb_task_handler.WasbTaskHandler': cannot import name 'logging_class_path'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/gsingh/venv/bin/airflow", line 21, in <module>
    from airflow import configuration
  File "/home/gsingh/venv/lib/python3.6/site-packages/airflow/__init__.py", line 36, in <module>
    from airflow import settings, configuration as conf
  File "/home/gsingh/venv/lib/python3.6/site-packages/airflow/settings.py", line 262, in <module>
    logging_class_path = configure_logging()
  File "/home/gsingh/venv/lib/python3.6/site-packages/airflow/logging_config.py", line 73, in configure_logging
    raise e
  File "/home/gsingh/venv/lib/python3.6/site-packages/airflow/logging_config.py", line 68, in configure_logging
    dictConfig(logging_config)
  File "/home/gsingh/anaconda3/lib/python3.6/logging/config.py", line 795, in dictConfig
    dictConfigClass(config).configure()
  File "/home/gsingh/anaconda3/lib/python3.6/logging/config.py", line 566, in configure
    '%r: %s' % (name, e))
ValueError: Unable to configure handler 'processor': Cannot resolve 'airflow.utils.log.wasb_task_handler.WasbTaskHandler': cannot import name 'logging_class_path'

I am not sure which configuration I am missing. Has anyone faced the same issue?

Body:
You need to install the azure package.

pip install 'apache-airflow[azure_blob_storage,azure_data_lake,azure_cosmos,azure_container_instances]

As per updating.md

This now should be installed with

pip install apache-airflow[azure]

But this didn't work for me.


问:
how to use session ids for authentication purpose
I am using just session variables $_SESSION['user_id'] and $_SESSION['passwd'] to store the id and password of user once when he logs in.

I am just checking these two variables with database each time the user moves to a new php page for authentication. Actually I didnt know about session_id() .

I dont think what i am doing for authentication is the right way. I feel that there is something to be done with session_id for security stuff.

and one more doubt- can these session variables be easily hacked when I use the session variables by the way i mentioned

What should I do?

答:
You should only authenticate against the database once, then store the result in the $_SESSION var. Example:</p>

```<code>if ($user_and_pass_ok) {
  $_SESSION['user_logged_in'] = true;
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
You should only authenticate against the database once, then store the result in the $_SESSION var. Example:

if ($user_and_pass_ok) {
  $_SESSION['user_logged_in'] = true;
}


问:
Make all the elemant zero except max n element in each row in numpy 2d-array
Let's say I have a 2D numpy array like:

```<code>[[1, 8, 3, 4, 5],
 [10,13,13,12,15]]
</code>```

I want to convert all the elements to zero except the maximum or maximum 2 elements in each row. The output I'd like to get is:

```<code>[[0, 8, 0,0, 5],
 [0,13,13,0,15]]
</code>```

How can I do this?

答:
This code is for only identifying max in row and and replacing all the other values as zero.
If you want to include top 2 highest value, I think you need to write for loop.

```<code>   import numpy as np
   import copy

   a = np.array([[1, 8, 3, 4, 5],
     [10,13,13,12,15]])

   b = copy.deepcopy(a)
</code>```

a == np.max(a) will raise an error in the future, so here's a tweaked version that will continue to broadcast correctly.

```<code># get max by row and convert from (n, ) -> (n, 1) which will broadcast
row_maxes = a.max(axis=1).reshape(-1, 1)
</code>```

if the update needs to be in place, you can do

```<code>a[:] = np.where(a == row_maxes, row_maxes, 0)

>> a
 array([[ 0,  8,  0,  0,  0],
           [ 0,  0,  0,  0, 15]])
</code>```

You can identify max 2 from each row and apply for loop to get the desired result.

```<code>b = np.sort(b)
max_two = np.array(list(map(lambda row : row[-2:], b)))

for i, row in enumerate(a):
   for j, elm in enumerate(row):
      if elm not in max_two:
         a[i][j] = 0

>> a
array([[ 0,  8,  0,  0,  5],
       [ 0,  13,  13,  0, 15]])
</code>```

Body:
Let's say I have a 2D numpy array like:

[[1, 8, 3, 4, 5],
 [10,13,13,12,15]]

I want to convert all the elements to zero except the maximum or maximum 2 elements in each row. The output I'd like to get is:

[[0, 8, 0,0, 5],
 [0,13,13,0,15]]

How can I do this?

Body:
This code is for only identifying max in row and and replacing all the other values as zero.
If you want to include top 2 highest value, I think you need to write for loop.

   import numpy as np
   import copy

   a = np.array([[1, 8, 3, 4, 5],
     [10,13,13,12,15]])

   b = copy.deepcopy(a)

a == np.max(a) will raise an error in the future, so here's a tweaked version that will continue to broadcast correctly.

# get max by row and convert from (n, ) -> (n, 1) which will broadcast
row_maxes = a.max(axis=1).reshape(-1, 1)

if the update needs to be in place, you can do

a[:] = np.where(a == row_maxes, row_maxes, 0)

>> a
 array([[ 0,  8,  0,  0,  0],
           [ 0,  0,  0,  0, 15]])

You can identify max 2 from each row and apply for loop to get the desired result.

b = np.sort(b)
max_two = np.array(list(map(lambda row : row[-2:], b)))

for i, row in enumerate(a):
   for j, elm in enumerate(row):
      if elm not in max_two:
         a[i][j] = 0

>> a
array([[ 0,  8,  0,  0,  5],
       [ 0,  13,  13,  0, 15]])


问:
Pass template to another template as parameter
I am working on an Angular 7 web app. I have got a few components. One of them is card.component which should be a container for others (not for all).

Card template body:

```<code><div id="main-container" class="container">
  <mat-card id="login-card">
    <div id="form-container">
      // here I want to paste another components view as a parameter
    </div>
  </mat-card>
</div>
</code>```

The next one is login.component. This component should use card.component template as a container and put the form from another component as a content.

I want it works something like that (psedocode):

```<code><app-card [my-html-param]="app-login-form"></app-card>
</code>```

Now in above component I would like to pass view from login-form.component

How can I achieve such functionality?

答:
You have to use <ng-content>, it will let you add some content inside app-card :

```<code><app-card>
    <app-login-form></app-login-form>
</app-card>
</code>```

Then, in your login-form.component.html you can include the lines inside app-card tags with <ng-content>.

Body:
I am working on an Angular 7 web app. I have got a few components. One of them is card.component which should be a container for others (not for all).

Card template body:

  <mat-card id="login-card">

      // here I want to paste another components view as a parameter

  </mat-card>

The next one is login.component. This component should use card.component template as a container and put the form from another component as a content.

I want it works something like that (psedocode):

<app-card [my-html-param]="app-login-form"></app-card>

Now in above component I would like to pass view from login-form.component

How can I achieve such functionality?

Body:
You have to use <ng-content>, it will let you add some content inside app-card :

<app-card>
    <app-login-form></app-login-form>
</app-card>

Then, in your login-form.component.html you can include the lines inside app-card tags with <ng-content>.


问:
compile() missing 1 required positional argument: 'loss'
I see the above error when executing the code below to add a custom loss function.

   mymodel.add_loss(custom_loss)
   mymodel.compile(optimizer='adam')
```

error: compile() missing 1 required positional argument: 'loss'

答:
see : https://github.com/llSourcell/autoencoder_explained/issues/1

change the code to

   mymodel.add_loss(custom_loss)
   mymodel.compile(optimizer='adam',loss='')
```

Body:
I see the above error when executing the code below to add a custom loss function.

   mymodel.add_loss(custom_loss)
   mymodel.compile(optimizer='adam')

error: compile() missing 1 required positional argument: 'loss'


问:
How to select the first element of a column of type array column using knex.select()?
We are able to select the first element of a column of type array in Postgres SQL database. But I'm not able to query the same using knex.

I have tried this.

```<code>database('items')
    .select({icon: 'images[0]})
    .then(data => {
    res.send(data)
}
</code>```

Expecting the first element of images column of items table.

答:
https://www.postgresql.org/docs/current/arrays.html#ARRAYS-ACCESSING

This seems to build correct kind of query for it in knex (notice that in postgresql arrays starts from index 1):

```<code>knex('items').select({icon: knex.raw('??[1]', ['images'])})
</code>```

Here is runkit example of generated query https://runkit.com/embed/1apx76bh4u40

Body:
We are able to select the first element of a column of type array in Postgres SQL database. But I'm not able to query the same using knex.

I have tried this.

database('items')
    .select({icon: 'images[0]})
    .then(data => {
    res.send(data)
}

Expecting the first element of images column of items table.

Body:
https://www.postgresql.org/docs/current/arrays.html#ARRAYS-ACCESSING

This seems to build correct kind of query for it in knex (notice that in postgresql arrays starts from index 1):

knex('items').select({icon: knex.raw('??[1]', ['images'])})

Here is runkit example of generated query https://runkit.com/embed/1apx76bh4u40


答:
    const dataArr = [{
            a: 'foo',
            b: [1, 2, "NA", "NA", 3],
            c: ["NA", 6]
        },
        {
            a: 'bar',
            b: ["NA", "NA", "NA"],
            c: []
        }
    ];

    const res = dataArr.map((obj) => {
        for(let i in obj){
            if(Array.isArray(obj[i])){
                obj[i] = obj[i].filter(el=>el!=="NA")
            }
        }
        return obj;
    });

    console.log('@>res', res)```

Body:
I have the following array of objects, in which some specific keys have a value which is either a string or an array. I want to get the keys with string values as it is and remove "NA" from keys with array values.

I am trying to achieve the same by doing .map method on the array, check the type of the value of each key in the data object, if an array then use .filter to remove the "NA" values.

var dataArr = [
    {
     a: 'foo',
     b: [1, 2, "NA", "NA", 3],
     c: ["NA", 6]
    },
    {
     a: 'bar',
     b: ["NA", "NA", "NA"],
     c: []
    }
];
dataArr.map(dataObj => {
    for (let key in dataObj) {
        if (key !== 'a')
            dataObj[key] = dataObj[key].filter(val => { if(val != "NA") return val})
    }
    return dataObj;
});

The above block of code works as expected but I want a better and future-proof solution. Moreover, this looks bad too.


问:
What other get method characters can be used? aside from question mark?
the normal get:
http://localhost/get.php?id=2&get=row

can it be done like this?

http://localhost/get.php&id=2&get=row

or in other way.

When a user make a parameter to my site like

http://test.com/?url=http://localhost/sample/

or what if it contains a "?id=234"

so the new url is http://test.com/?url=http://localhost/smaple?id=1234

it creates now a 2 question mark.

答:
You can always use URLRewriting
 if you are not a fan of having get variables in your URL but in response to you question the ? is part of the standard

if using apache user
RewriteRule in .htaccess


问:
SQL Server Why is geography::Point inside function non-deterministic?
I store Latitude and Longitude (float null) data from the user, and want to create a persisted computed column of Geography data type based on these values (with the intention of using a spatial index on this column).

The computed column formula is:

```<code>(case when @lat IS NULL OR @lng IS NULL then NULL else [geography]::Point(@lat,@lng,(4326)) end)
</code>```

This works as expected when persisted is set to true on the computed column (returns a Geography value when Latitude and Longitude are present, returns null otherwise.

However, I wish to abstract this into a user-defined function, as other tables will be using the same calculation. I have created the following function:

```<code>CREATE FUNCTION [dbo].[GetGeography]
(
    @lat float null,
    @lng float null
)
RETURNS geography
AS
BEGIN
    RETURN (case when @lat IS NULL OR @lng IS NULL then NULL else [geography]::Point(@lat,@lng,(4326)) end)
END
</code>```

When I try to use this function in the computed column formula, and set persisted to true, I get the following error message:

```<code>Computed column 'Geog_LatLng' in table 'Tmp_Locations' cannot be persisted because the column is non-deterministic.
</code>```

There is no documentation about the determinism of POINT, and the documentation on Deterministic Functions doesn't mention geography or point .

The short-term solution is to just replicate the formula across all tables, but I would like to know if it is possible to abstract the formula into a user-defined function.

答:
The solution is to use with schemabinding:

```<code>CREATE FUNCTION [dbo].[GetGeography]
(
    @lat float null,
    @lng float null
)
WITH SCHEMABINDING -- <--- modified
RETURNS geography
AS
BEGIN
    RETURN (case when @lat IS NULL OR @lng IS NULL then NULL else [geography]::Point(@lat,@lng,(4326)) end)
END
</code>```

An explanation is in the Docs.

Body:
I store Latitude and Longitude (float null) data from the user, and want to create a persisted computed column of Geography data type based on these values (with the intention of using a spatial index on this column).

The computed column formula is:

(case when @lat IS NULL OR @lng IS NULL then NULL else [geography]::Point(@lat,@lng,(4326)) end)

This works as expected when persisted is set to true on the computed column (returns a Geography value when Latitude and Longitude are present, returns null otherwise.

However, I wish to abstract this into a user-defined function, as other tables will be using the same calculation. I have created the following function:

CREATE FUNCTION [dbo].[GetGeography]
(
    @lat float null,
    @lng float null
)
RETURNS geography
AS
BEGIN
    RETURN (case when @lat IS NULL OR @lng IS NULL then NULL else [geography]::Point(@lat,@lng,(4326)) end)
END

When I try to use this function in the computed column formula, and set persisted to true, I get the following error message:

Computed column 'Geog_LatLng' in table 'Tmp_Locations' cannot be persisted because the column is non-deterministic.

There is no documentation about the determinism of POINT, and the documentation on Deterministic Functions doesn't mention geography or point .

The short-term solution is to just replicate the formula across all tables, but I would like to know if it is possible to abstract the formula into a user-defined function.

Body:
The solution is to use with schemabinding:

CREATE FUNCTION [dbo].[GetGeography]
(
    @lat float null,
    @lng float null
)
WITH SCHEMABINDING -- <--- modified
RETURNS geography
AS
BEGIN
    RETURN (case when @lat IS NULL OR @lng IS NULL then NULL else [geography]::Point(@lat,@lng,(4326)) end)
END

An explanation is in the Docs.


问:
How to use JavaScript to retrieve a html element that is also created in JavaScript
The html buttons are created in JavaScript, each with their own ID. They activate the same function when pressed, and I want to know which button is pressed. I use this.id to see the ID of the button pressed. I think, since I haven't retrieved the buttons in JavaScript (eg. button = document.getElementById('button')), it doesn't work. I don't know how to do this with HTML elements created inside the script.

var paragraph = document.getElementById('paragraph');

var cabins = [1,2,3];

for (var i = 0; i < cabins.length; i++) {
  paragraph.innerHTML += "Cabin " + cabins[i] + "

<button id='cabin" + cabins[i] +"' onclick='purchaseCabin()'>Purchase</button>

"
}

function purchaseCabin() {
  var cabinId = this.id;
  console.log(cabinId);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p id="paragraph"></p></code>```

Expected result: the ID of the pressed button is written in the console

Actual result: "undefined" is written in the console

答:
this inside the function refers to Window which does not have the property id, thus you get undefined:

Pass this object to the function so that you can refer that inside the function:

var paragraph = document.getElementById('paragraph');
var cabins = [1,2,3];
for (var i = 0; i < cabins.length; i++) {
  paragraph.innerHTML += "Cabin " + cabins[i] + "

<button id='cabin" + cabins[i] +"' onclick='purchaseCabin(this)'>Purchase</button>

"
}

function purchaseCabin(current) {
  //console.log(this.constructor.name); // Window
  var cabinId = current.id;
  console.log(cabinId);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p id="paragraph"></p></code>```

Body:
The html buttons are created in JavaScript, each with their own ID. They activate the same function when pressed, and I want to know which button is pressed. I use this.id to see the ID of the button pressed. I think, since I haven't retrieved the buttons in JavaScript (eg. button = document.getElementById('button')), it doesn't work. I don't know how to do this with HTML elements created inside the script.

var paragraph = document.getElementById('paragraph');

var cabins = [1,2,3];

for (var i = 0; i < cabins.length; i++) {
  paragraph.innerHTML += "Cabin " + cabins[i] + "

<button id='cabin" + cabins[i] +"' onclick='purchaseCabin()'>Purchase</button>

"
}

function purchaseCabin() {
  var cabinId = this.id;
  console.log(cabinId);
}

Expected result: the ID of the pressed button is written in the console

Actual result: "undefined" is written in the console

Body:
this inside the function refers to Window which does not have the property id, thus you get undefined:

Pass this object to the function so that you can refer that inside the function:

var paragraph = document.getElementById('paragraph');
var cabins = [1,2,3];
for (var i = 0; i < cabins.length; i++) {
  paragraph.innerHTML += "Cabin " + cabins[i] + "<br><br><button id='cabin" + cabins[i] +"' onclick='purchaseCabin(this)'>Purchase</button><br><br>"
}

function purchaseCabin(current) {
  //console.log(this.constructor.name); // Window
  var cabinId = current.id;
  console.log(cabinId);
}

<p id="paragraph"></p>


问:
How to add minor tick marks in MS Chart in C# Windows Form?
How to add minor tick marks in MS Chart in Windows Form.

I am using below code but minor tick marks are not showing up.

```<code> chart.ChartAreas[0].AxisX.MinorTickMark.Enabled = true;
 chart.ChartAreas[0].AxisX.MajorGrid.Interval = 1;
 chart.ChartAreas[0].AxisX.MajorGrid.IntervalType = DateTimeIntervalType.Seconds;
 chart.ChartAreas[0].AxisX.MinorTickMark.IntervalType = DateTimeIntervalType.Number;
chart.ChartAreas[0].AxisX.MinorTickMark.Interval = 2;
</code>```

Please help me.

答:
The way you turn on MinorTickMarks as such is fine.

But if you want to use different IntervalTypes you need to understand the numeric values behind the types.

Internally all values, both x- and y-values are defined and stored as doubles.

If you declare some of them to be DateTimes they get converted to double (and when necessary back to DateTime) by the conversion functions: double.ToOADate  (and FromOADate).

Let's have a look at the values resulting for one second:

```<code>DateTime dt0 = DateTime.Now;
DateTime dt1 = dt0 .AddSeconds(1);

double d0 = dt0.ToOADate();
double d1 = dt1.ToOADate();

double dd = d1 - d0;

Console.WriteLine(d0 + " .. " +  d1 + "  => "  + dd);
</code>```

Output:

43612,4597045023 .. 43612,4597160764  => 1,15740695036948E-05

So, with such a tiny value an Interval of 1, as in your code, just won't happen within the chart. Best use a different type, like DateTimeIntervalType.Milliseconds with an suitable Interval, like 500..!

Body:
How to add minor tick marks in MS Chart in Windows Form.

I am using below code but minor tick marks are not showing up.

 chart.ChartAreas[0].AxisX.MinorTickMark.Enabled = true;
 chart.ChartAreas[0].AxisX.MajorGrid.Interval = 1;
 chart.ChartAreas[0].AxisX.MajorGrid.IntervalType = DateTimeIntervalType.Seconds;
 chart.ChartAreas[0].AxisX.MinorTickMark.IntervalType = DateTimeIntervalType.Number;
chart.ChartAreas[0].AxisX.MinorTickMark.Interval = 2;

Please help me.

Body:
The way you turn on MinorTickMarks as such is fine.

But if you want to use different IntervalTypes you need to understand the numeric values behind the types.

Internally all values, both x- and y-values are defined and stored as doubles.

If you declare some of them to be DateTimes they get converted to double (and when necessary back to DateTime) by the conversion functions: double.ToOADate  (and FromOADate).

Let's have a look at the values resulting for one second:

DateTime dt0 = DateTime.Now;
DateTime dt1 = dt0 .AddSeconds(1);

double d0 = dt0.ToOADate();
double d1 = dt1.ToOADate();

double dd = d1 - d0;

Console.WriteLine(d0 + " .. " +  d1 + "  => "  + dd);

Output:

43612,4597045023 .. 43612,4597160764  => 1,15740695036948E-05

So, with such a tiny value an Interval of 1, as in your code, just won't happen within the chart. Best use a different type, like DateTimeIntervalType.Milliseconds with an suitable Interval, like 500..!


答:
You don't need to check everytime the user moves to a new php.
Once user authenticates, store the session_id in $_SESSION['session_id'] for example. After that all you need to do is check if $_SESSION['session_id'] is set. If it is, it means user is "logged in".

Hope it helps.

Title: how to use session ids for authentication purpose

Body:
I am using just session variables $_SESSION['user_id'] and $_SESSION['passwd'] to store the id and password of user once when he logs in.

I am just checking these two variables with database each time the user moves to a new php page for authentication. Actually I didnt know about session_id() .

I dont think what i am doing for authentication is the right way. I feel that there is something to be done with session_id for security stuff.

and one more doubt- can these session variables be easily hacked when I use the session variables by the way i mentioned

What should I do?


问:
remove an edge in network vis.js
In vis.js, i can add easily an edge (ex function test) but i can't remove an existing edge (ex function test 1). Why ?

Unfortunately, i can't access now to documentation : "There isn't a GitHub Pages site here" for visjs.org. Thanks !

<input onclick=test() type="button" value="add edge 1 to 4 : ok">
<input onclick=test1() type="button" value="remove edge 1 to 2: not ok">

```

答:
It's ok now !

I can do it with "id" for edges :

```<code>var edges = [
{id:1, from: 1, to: 2},
{id:2, from: 1, to: 3},
{id:3, from: 2, to: 4},
{id:4, from: 2, to: 5}
];

function test1(){
data.edges.remove([1]);
}
</code>```

Title: remove an edge in network vis.js

Body:
It's ok now !

I can do it with "id" for edges :

var edges = [
{id:1, from: 1, to: 2},
{id:2, from: 1, to: 3},
{id:3, from: 2, to: 4},
{id:4, from: 2, to: 5}
];

function test1(){
data.edges.remove([1]);
}