问:
Fatal error: Redefinition of parameter $post_id in C:\xampp\htdocs\wp-content\themes\couponer\functions.php on line 2533
I am Getting error

Fatal error: Redefinition of parameter $post_id in
  C:\xampp\htdocs\wp-content\themes\couponer\functions.php on line 2533

```<code>function coupon_smeta_images( $meta_key, $post_id, $default, $post_id){
    if(class_exists('SM_Frontend')){
        global $sm;
        return $result = $sm->sm_get_meta($meta_key, $post_id);
    }
    else{
        return $default;
    }
}

/* check if smeta plugin is installed */
</code>```

答:
You have a duplicate $post_id parameters in your functions. Try remove one like this:

```<code>function coupon_smeta_images( $meta_key, $post_id, $default){
    if(class_exists('SM_Frontend')){
        global $sm;
        return $result = $sm->sm_get_meta($meta_key, $post_id);
    }
    else{
        return $default;
    }
}
</code>```

Body:
I am Getting error

Fatal error: Redefinition of parameter $post_id in
  C:\xampp\htdocs\wp-content\themes\couponer\functions.php on line 2533

function coupon_smeta_images( $meta_key, $post_id, $default, $post_id){
    if(class_exists('SM_Frontend')){
        global $sm;
        return $result = $sm->sm_get_meta($meta_key, $post_id);
    }
    else{
        return $default;
    }
}

/* check if smeta plugin is installed */

Body:
You have a duplicate $post_id parameters in your functions. Try remove one like this:

function coupon_smeta_images( $meta_key, $post_id, $default){
    if(class_exists('SM_Frontend')){
        global $sm;
        return $result = $sm->sm_get_meta($meta_key, $post_id);
    }
    else{
        return $default;
    }
}


来源: stackexchange

问:
html aligning inputs under each other
I'm trying to get the following snippet to work so that the selects are aligned exactly underneath each other.

Type:
<select style="width: 200px"></select>Created at:

Encoding:
<select style="width: 200px"></select>Updated at:

Collation: <select style=" width: 200px"></select>

```

As you can see it doesn't look quite right and I'm not sure how, I've been experimenting with stuff like display and box-sizing as you can see but none of these seem to have any effect, I also tried to align the text to the right which makes it a little better but it's still not perfect.

Any ideas?

答:
I'd recommend using Bootstrap if possible, saves you the bother of needing to write any CSS if you simply need basic alignment in your form.

I used this example to somewhat transform your code with Bootstrap;

https://www.w3schools.com/bootstrap/tryit.asp?filename=trybs_form_horizontal&stacked=h

```<code><!DOCTYPE html>
<html lang="en">
<head>
  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>

    <body>
        <div class="container">
            <form class="form-horizontal">
                <div class="form-group">
                    <label class="control-label col-sm-2">Type:</label>
                    <div class="col-sm-4">
                        <select class="form-control"></select>
                    </div>
                </div>
                <div class="form-group">
                    <label class="control-label col-sm-2">Encoding:</label>
                    <div class="col-sm-4">
                        <select class="form-control"></select>
                    </div>
                </div>
                <div class="form-group">
                    <label class="control-label col-sm-2">Collation:</label>
                    <div class="col-sm-4">
                        <select class="form-control">:</select>
                    </div>
                </div>
            </form>
        </div>
    </body>
</html>
</code>```

ContentLicense: CC BY-SA 3.0

Title: html aligning inputs under each other

Body:
I'm trying to get the following snippet to work so that the selects are aligned exactly underneath each other.

Type:
<select style="width: 200px"></select>Created at:

Encoding:
<select style="width: 200px"></select>Updated at:

Collation: <select style=" width: 200px"></select>

As you can see it doesn't look quite right and I'm not sure how, I've been experimenting with stuff like display and box-sizing as you can see but none of these seem to have any effect, I also tried to align the text to the right which makes it a little better but it's still not perfect.

Any ideas?

Body:
I'd recommend using Bootstrap if possible, saves you the bother of needing to write any CSS if you simply need basic alignment in your form.

I used this example to somewhat transform your code with Bootstrap;

https://www.w3schools.com/bootstrap/tryit.asp?filename=trybs_form_horizontal&stacked=h

<!DOCTYPE html>
<html lang="en">
<head>
  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>

    <body>
        <div class="container">
            <form class="form-horizontal">
                <div class="form-group">
                    <label class="control-label col-sm-2">Type:</label>
                    <div class="col-sm-4">
                        <select class="form-control"></select>
                    </div>
                </div>
                <div class="form-group">
                    <label class="control-label col-sm-2">Encoding:</label>
                    <div class="col-sm-4">
                        <select class="form-control"></select>
                    </div>
                </div>
                <div class="form-group">
                    <label class="control-label col-sm-2">Collation:</label>
                    <div class="col-sm-4">
                        <select class="form-control">:</select>
                    </div>
                </div>
            </form>
        </div>
    </body>
</html>


问:
Can I use negated versions of arbitrary symbols in Isabelle?
Isabelle allows you to use symbols that are negated versions of certain other symbols. Examples are ≠ and ∉. Is there a mechanism for getting negated versions of arbitrary symbols, like the \not macro in LaTeX?

答:
Your question has two parts: whether arbitrary negated symbols can be used, and whether such symbols can be input with a convenient macro. Let's start with the first part:

The Isabelle FAQ explains that JEdit converts mathematical symbols input in various ways to Unicode, and uses/displays the unicode symbol. Therefore, if your desired symbol exists in Unicode, there is a chance that you could use it directly (i.e. ctrl-c ctrl-v the symbol). For example, the following allows you to define "not exists":

```<code>abbreviation notexists :: "(('a ⇒ bool) ⇒ bool)" ("∄") where "∄ Φ ≡ (¬ (∃x. Φ(x)))"
</code>```

However, not all unicode symbols are available. For instance, the italic nabla does not display correctly in jedit.

Now to the second part of your question: as far as I know, such a macro doesn't exist. However, Isabelle has a similar macro mechanism for making symbols boldface. For example, \<bold> \<exists> will be displayed as a bold "exists" symbol. This shows that the macro functionality exists, and it could be possible to have a macro for negating symbols, as you suggested, in the future.

Body:
Your question has two parts: whether arbitrary negated symbols can be used, and whether such symbols can be input with a convenient macro. Let's start with the first part:

The Isabelle FAQ explains that JEdit converts mathematical symbols input in various ways to Unicode, and uses/displays the unicode symbol. Therefore, if your desired symbol exists in Unicode, there is a chance that you could use it directly (i.e. ctrl-c ctrl-v the symbol). For example, the following allows you to define "not exists":

abbreviation notexists :: "(('a ⇒ bool) ⇒ bool)" ("∄") where "∄ Φ ≡ (¬ (∃x. Φ(x)))"

However, not all unicode symbols are available. For instance, the italic nabla does not display correctly in jedit.

Now to the second part of your question: as far as I know, such a macro doesn't exist. However, Isabelle has a similar macro mechanism for making symbols boldface. For example, \<bold> \<exists> will be displayed as a bold "exists" symbol. This shows that the macro functionality exists, and it could be possible to have a macro for negating symbols, as you suggested, in the future.


问:
trigger 2 time php code for top up
I would like to have this function of topping up e-wallet. I managed to top up, however, I found out that the PHP was called 2 times and hence the number will multiply by 2 for even number and for old number it will multiply 2 times +1. Can I know how can I solve this problem?
Image link this is the problem i faced in the above link

topup.html

```<code>    <!DOCTYPE HTML>
    <html>
    <head>

 <!--
    Customize the content security policy in the meta tag below as needed. Add 'unsafe-inline' to default-src to enable inline JavaScript.
    For details, see http://go.microsoft.com/fwlink/?LinkID=617521

    <meta http-equiv="Content-Security-Policy" content="default-src 'self' data: gap: http://mp08.mybitmp.org https://ssl.gstatic.com 'unsafe-eval'; style-src 'self' 'unsafe-inline'; media-src *">
    -->
    <meta http-equiv="content-type" content="text/html; charset=UTF-8" />
    <meta name="format-detection" content="telephone=no">
    <meta name="msapplication-tap-highlight" content="no">
    <meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

    <link rel="stylesheet" type="text/css" href="css/index.css">
    <link rel="stylesheet" href="css/jquery.mobile-1.4.5.css">

    <script src="lib/jquery-1.11.2.min.js"></script>
    <script src="lib/jquery.mobile-1.4.5.min.js"></script>
    <script src="lib/jquery.validate.min.js"></script>

    <script src="scripts/common.js"></script>
    <!--<script src="scripts/home.js"></script>-->
    <script src="scripts/topup.js"></script>
    <script src="scripts/home.js"></script>
    <!--<script src="https://www.paypalobjects.com/api/checkout.js"></script>-->
    <title>Community Connection</title>
</head>

<body>

    <div data-role="page" id="pageone">

        <div data-role="header">
            <h1>Community Connection </h1>
            <a href="#" onclick="home()" class="ui-btn ui-icon-home ui-btn-icon-left">Home</a>
            <a href="#" onclick="logout()" data-icon="power" class="ui-btn-right">Logout</a>
        </div>

        <div data-role="content" class="ui-content" id="newitem">
            <div id="credits"></div>
            <input type="range" name="slidercredits" id="slidercredits" value="0" min="0" max="100">

            <input type="button" id="btnTopUp" value="Top Up">
        </div>

        </div>
        <footer data-role="footer" data-position="fixed" data-tap-toggle="false" class="jqm-footer">

            <div data-role="navbar">
                <ul>
                    <li><a id='btnHome' href='#' data-icon='home'>Home</a></li>
                    <li><a id='btnSearch' href='#' data-icon='search'>Search</a></li>
                    <li><a id='btnFind' href='#' data-icon='heart'>Find</a></li>
                    <li><a id='btnNotification' href='#' data-icon='info'>Notification</a></li>
                    <li><a id='btnMore' href='#right-panel' data-icon='bars'>More</a></li>
                </ul>
            </div><!-- /navbar -->
        </footer>

</body>
</html>
</code>```

topup.js

```<code><!-- language: lang-js -->

(function () {

    $(document).on("pagebeforecreate", function () {
        printheader();
        taskbar();
        sidebar();
    });

    $(document).ready(function () {
         // var slidercredits = $("#slidercredits").val();
        getcurrentcredits();

        $("#btnTopUp").bind("click", function () {
            topup();
        });
    });

    //Profile Section
    function getcurrentcredits() {
        var url = serverURL() + "/getcurrentcredits.php";

        var JSONObject = {
            "user_name": localStorage.getItem("userid")
        };

        $.ajax({
            url: url,
            type: 'GET',
            data: JSONObject,
            dataType: 'json',
            contentType: "application/json; charset=utf-8",
            success: function (arr) {
                _getcurrentcredits(arr);
            },
            error: function () {
                validationMsg();
            }
        });
    }

   function _getcurrentcredits(arr) {
        userid = arr[0].user_name;
        credits = arr[0].credits;

        $("#credits").html("My Wallet: S$" + credits);
        //    $("#Sideusername").html("Username: " + userid);
        //  $("#imgProfilePicture").attr("src", serverURL() + "/images/" + profileimage + "_s");
    }

    function topup() {
        var userid = localStorage.getItem("userid");
        var slidercredits = $("#slidercredits").val();
        alert("slidercredits" + slidercredits);

        //var credits = $("#credits").val();

        //   if (validate()) {
        //var xmlhttp = new XMLHttpRequest();
        var url = serverURL() + "/topup.php";

        var JSONObject = {
            "user_name": userid,
            "credits": slidercredits
        };

        $.ajax({
            url: url,
            type: 'GET',
            data: JSONObject,
            dataType: 'json',
            contentType: "application/json; charset=utf-8",
            success: function (arr) {
                _topupResult(arr);
            },
            error: function () {
                validationMsg();
            }
        });

         url += "?userid=" + userid + "&credits=" + credits;

        xmlhttp.onreadystatechange = function () {
            if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {

                topupResult(xmlhttp.responseText);
            }
        }
        xmlhttp.open("GET", url, true);
        xmlhttp.send();
        //}

    }

    //function _topupResult(arr) {
    function topupResult(response) {
        var arr = JSON.parse(response);
        if (arr[0].result == "1") {
            alert("Topup success" + credits + "-->>>" + slidercredits);
            window.location = "topup.html";

        }
        else if (arr[0].result == "0") {
            alert("Topup failed.");
        }
    }
})();
</code>```

topup.php

```<code> <?php
    header('Access-Control-Allow-Origin: *');
    header('Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE, OPTIONS');
    header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token');
    header("Content-Type: application/json; charset=UTF-8");

    error_reporting(E_ERROR);

    include("global.php");

    try{
     $conn = new mysqli(server, dbuser, dbpw, db);
            $username = $_GET["user_name"];
            $credits = $_GET["credits"];

       $query = "update Users set credits = credits +  " . $credits . " where user_name = '" . $username . "'";
        $result = $conn->query($query);

        if (!$result){
            $json_out = "[" . json_encode(array("result"=>0)) . "]";
        }
        else {
            $json_out = "[" . json_encode(array("result"=>1)) . "]";
        }

        echo $json_out;

        $conn->close();
    }

    catch(Exception $e) {
        $json_out =  "[".json_encode(array("result"=>0))."]";
        echo $json_out;
    }

    ?>
</code>```

答:
Because function topup() in topup.js makes an ajax call to the top up url and then immediately afterwards you have this code which does the same thing again

```<code>    xmlhttp.open("GET", url, true);
    xmlhttp.send();
</code>```

Title: trigger 2 time php code for top up

Body:
I would like to have this function of topping up e-wallet. I managed to top up, however, I found out that the PHP was called 2 times and hence the number will multiply by 2 for even number and for old number it will multiply 2 times +1. Can I know how can I solve this problem?
Image link this is the problem i faced in the above link

topup.html

    <!DOCTYPE HTML>

    <meta http-equiv="content-type" content="text/html; charset=UTF-8" />
    <meta name="format-detection" content="telephone=no">
    <meta name="msapplication-tap-highlight" content="no">
    <meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

    <link rel="stylesheet" type="text/css" href="css/index.css">
    <link rel="stylesheet" href="css/jquery.mobile-1.4.5.css">

    <title>Community Connection</title>

Community Connection

            Home
            Logout

            <input type="range" name="slidercredits" id="slidercredits" value="0" min="0" max="100">

            <input type="button" id="btnTopUp" value="Top Up">

Home

Search

Find

Notification

More

topup.js

(function () {

    $(document).on("pagebeforecreate", function () {
        printheader();
        taskbar();
        sidebar();
    });

    $(document).ready(function () {
         // var slidercredits = $("#slidercredits").val();
        getcurrentcredits();

        $("#btnTopUp").bind("click", function () {
            topup();
        });
    });

    //Profile Section
    function getcurrentcredits() {
        var url = serverURL() + "/getcurrentcredits.php";

        var JSONObject = {
            "user_name": localStorage.getItem("userid")
        };

        $.ajax({
            url: url,
            type: 'GET',
            data: JSONObject,
            dataType: 'json',
            contentType: "application/json; charset=utf-8",
            success: function (arr) {
                _getcurrentcredits(arr);
            },
            error: function () {
                validationMsg();
            }
        });
    }

   function _getcurrentcredits(arr) {
        userid = arr[0].user_name;
        credits = arr[0].credits;

        $("#credits").html("My Wallet: S$" + credits);
        //    $("#Sideusername").html("Username: " + userid);
        //  $("#imgProfilePicture").attr("src", serverURL() + "/images/" + profileimage + "_s");
    }

    function topup() {
        var userid = localStorage.getItem("userid");
        var slidercredits = $("#slidercredits").val();
        alert("slidercredits" + slidercredits);

        //var credits = $("#credits").val();

        //   if (validate()) {
        //var xmlhttp = new XMLHttpRequest();
        var url = serverURL() + "/topup.php";

        var JSONObject = {
            "user_name": userid,
            "credits": slidercredits
        };

        $.ajax({
            url: url,
            type: 'GET',
            data: JSONObject,
            dataType: 'json',
            contentType: "application/json; charset=utf-8",
            success: function (arr) {
                _topupResult(arr);
            },
            error: function () {
                validationMsg();
            }
        });

         url += "?userid=" + userid + "&credits=" + credits;

        xmlhttp.onreadystatechange = function () {
            if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {

                topupResult(xmlhttp.responseText);
            }
        }
        xmlhttp.open("GET", url, true);
        xmlhttp.send();
        //}

    }

    //function _topupResult(arr) {
    function topupResult(response) {
        var arr = JSON.parse(response);
        if (arr[0].result == "1") {
            alert("Topup success" + credits + "-->>>" + slidercredits);
            window.location = "topup.html";

        }
        else if (arr[0].result == "0") {
            alert("Topup failed.");
        }
    }
})();

topup.php

 <?php
    header('Access-Control-Allow-Origin: *');
    header('Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE, OPTIONS');
    header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token');
    header("Content-Type: application/json; charset=UTF-8");

    error_reporting(E_ERROR);

    include("global.php");

    try{
     $conn = new mysqli(server, dbuser, dbpw, db);
            $username = $_GET["user_name"];
            $credits = $_GET["credits"];

       $query = "update Users set credits = credits +  " . $credits . " where user_name = '" . $username . "'";
        $result = $conn->query($query);

        if (!$result){
            $json_out = "[" . json_encode(array("result"=>0)) . "]";
        }
        else {
            $json_out = "[" . json_encode(array("result"=>1)) . "]";
        }

        echo $json_out;

        $conn->close();
    }

    catch(Exception $e) {
        $json_out =  "[".json_encode(array("result"=>0))."]";
        echo $json_out;
    }

    ?>

Body:
Because function topup() in topup.js makes an ajax call to the top up url and then immediately afterwards you have this code which does the same thing again

    xmlhttp.open("GET", url, true);
    xmlhttp.send();


问:
Using multi value field to count number of mult value fields that occurred in an event

I'm a new analyst for a small collection of cardiology practices (to give some context). I am looking for a way to group combinations of CPT codes (IDs used for a specific procedures) and use them to count the number of tests (tests are often a combination of CPT codes) that occurred during a patients visit.

I have found some related material on multi value fields here, but am trying to understand if MS access is able to look at grouping (patient visit in this case) of CPT codes and determine if one or more tests occurred.

Here is simplified data:

ID; OfficeVisit;    CPT;    CPTdesc;    PrcVolume;  PrcType;

1;  Alex, Doctor - 12345-15-09-2017 12:00:00;   93320;  DOPPLER ECHO HEART,COMPLETE;    1;  Echo;

2;  Alex, Doctor - 12345-15-09-2017 12:00:00;   93325;  DOPPLER COLOR FLOW VELOCITY MAP;    1;  Echo;

3;  Alex, Doctor - 12345-15-09-2017 12:00:00;   93351;  ECHO HEART XTHORACIC, STRESS/REST, W CONTIN ECG;    1;  Other;

4;  Alex, Doctor - 12345-15-09-2017 12:00:00;   93880;  DUPLEX SCAN EXTRACRANIAL,BILAT; 1;  Echo;

5;  Alex, Doctor - 12345-15-09-2017 12:00:00;   A4550;  SURGICAL TRAYS; 1;  Other

Where CPT 93320, 93325, and 93880 = Test A and 93351 and A4550 = Test B, I would like the count for that visit of Alex Doctor's to = 2.

Is this even possible with MS Access? Can it pick out predefined groups of records in a field but ignore others?

I like to use the multi value field to sort through 100K records.

Any help would be greatly appreciated!!!

答:
I made the following table as shown below.  The reason is that I think multi-valued is not the way to go for speed and large amounts of data.

tblPatientVisits

ID, Office Visit, fpkCPTCode, PrcVolume, PrcType

tblCPTCode

apkCPTCode, fpkProcedureType, CPTCode, CPTDescription

tblProcedureType

apkProcedureType, ProcedureType

I then made a query qryOfficeVisits with the following code:

SELECT tblPatientVisit.ID, tblPatientVisit.OfficeVisit, tblCPTCodes.CPTCode, tblCPTCodes.CPTDescription, tblProcedureType.ProcedureType, tblPatientVisit.PrcVolume, tblPatientVisit.PrcType
FROM tblPatientVisit
INNER JOIN (tblCPTCodes
INNER JOIN tblProcedureType ON tblCPTCodes.fpkProcedureType = tblProcedureType.apkProcedureType) ON tblPatientVisit.fpkCPTCode = tblCPTCodes.apkCPTCode
ORDER BY tblPatientVisit.ID;

and then used that query to do another query for sums and groupings such as:

SELECT qryOfficeVisits.OfficeVisit, qryOfficeVisits.ProcedureType, Count(qryOfficeVisits.CPTCode) AS CountOfCPTCode
FROM qryOfficeVisits
GROUP BY qryOfficeVisits.OfficeVisit, qryOfficeVisits.ProcedureType
ORDER BY qryOfficeVisits.ProcedureType;

which gives 3 for ECHO and 2 for OTHER.

Hope this helps

ContentLicense: CC BY-SA 4.0


问:
python pandas non-unique dict keys
I have an Excel file with data like this

```<code>Fruits                       Description
oranges                      This is an orange
apples                       This is an apple
oranges                      This is also oranges
plum                         this is a plum
plum                         this is also a plum
grape                        I can make some wine
grape                        make it red
</code>```

I'm turning this into a dictionary using the below code

```<code> import pandas as pd
 import xlrd
 file = 'example.xlsx'
 x1 = pd.ExcelFile(file)
 print(x1.sheet_names)
 df1 = x1.parse('Sheet1')
 #print(df1)
 print(df1.set_index('Fruits').T.to_dict('list'))
</code>```

When i execute the above i get the error

```<code>UserWarning: DataFrame columns are not unique, some columns will be omitted.
</code>```

I want to have a dictionary that looks like the below

```<code>{'oranges': ['this is an orange', 'this is also oranges'], 'apples':['this is an apple'],
'plum'['This is a plum', 'this is also a plum'], 'grape'['i can make some wine', 'make it red']}
</code>```

答:
How about this?</p>

```<code>df.groupby(['Fruits'])['Description'].apply(list).to_dict()

{'apples': ['This is an apple'],
 'grape': ['make it red', 'I can make some wine'],
 'oranges': ['This is an orange', 'This is also oranges'],
 'plum': ['this is a plum', 'this is also a plum']}
</code>```

Title: python pandas non-unique dict keys

Body:
I have an Excel file with data like this

Fruits                       Description
oranges                      This is an orange
apples                       This is an apple
oranges                      This is also oranges
plum                         this is a plum
plum                         this is also a plum
grape                        I can make some wine
grape                        make it red

I'm turning this into a dictionary using the below code

 import pandas as pd
 import xlrd
 file = 'example.xlsx'
 x1 = pd.ExcelFile(file)
 print(x1.sheet_names)
 df1 = x1.parse('Sheet1')
 #print(df1)
 print(df1.set_index('Fruits').T.to_dict('list'))

When i execute the above i get the error

UserWarning: DataFrame columns are not unique, some columns will be omitted.

I want to have a dictionary that looks like the below

{'oranges': ['this is an orange', 'this is also oranges'], 'apples':['this is an apple'],
'plum'['This is a plum', 'this is also a plum'], 'grape'['i can make some wine', 'make it red']}

Body:
How about this?

df.groupby(['Fruits'])['Description'].apply(list).to_dict()

{'apples': ['This is an apple'],
 'grape': ['make it red', 'I can make some wine'],
 'oranges': ['This is an orange', 'This is also oranges'],
 'plum': ['this is a plum', 'this is also a plum']}


问:
Importing database from file without triggering Firebase functions
I have a Firebase db and I implemented some functions. For example, when /lists/{list_id}/ is created, a function automatically sets /lists/{list_id}/created_on to the current timestamp.

I've just realized that when I import a database from a file, Firebase still runs all these functions, so the created_on for ALL the lists is set to the current timestamp.

I also have functions that send emails upon addition of stuff, and I definitely don't want them to fire either.

How do I avoid it? I want to restore the db from a file without triggering any functions.

答:
Are you restoring from a completely clean state where no actual users are using the project?  In that case, simply undeploy all your functions by deploying an empty index.js, perform your import, then deploy all your functions again.  This should be achievable all with the Firebase CLI.

If you have records to import while the product has legitimate use that you don't want to impact, it wouldn't be advisable to turn off your functions for any amount of time.  Instead, you could massage your import data to add a child that indicates that a particular field is to be exempt from processing by whatever functions you have, and have those functions check to see if that child exists.  You can delete that child later if it gets in the way.


问:
INTERVIEW QUESTION : Perl Log file
There is a log file where each line contains fields separated by spaces. One of the fields is the IP address of the source node. We want to find the list of IP Addresses that have the most log entries. Lets say find the top 10 IP Addresses with most log entries.

This is Perl Interview Question. Interviewer wants to know how the candidate would proceed.

P.S: This question was asked to my friend

答:
Ask if this is intended for one-off usage.

If no, Jonathan's answer is good.

If yes, use a one-liner.

Assuming that the first field contains the IPs:

```<code>perl -ane '$count{$F[0]}++ } END { print $_, "\n" for (sort { $b <=> $a } keys %count)[0..9]'
</code>```

A good question that tests the candidate's knowledge of data structures, string-array manipulation, sorting and use of array slices.

ContentLicense: CC BY-SA 2.5

Title: INTERVIEW QUESTION : Perl Log file

Body:
Ask if this is intended for one-off usage.

If no, Jonathan's answer is good.

If yes, use a one-liner.

Assuming that the first field contains the IPs:

perl -ane '$count{$F[0]}++ } END { print $_, "\n" for (sort { $b <=> $a } keys %count)[0..9]'

A good question that tests the candidate's knowledge of data structures, string-array manipulation, sorting and use of array slices.


问:
laravel project storing data in database does not work
I have a laravel project that is using a mysql database with a few tables.Lets start by showing you all my files that are being used.My problem is that when I try to create the 'Conseillere' into the database, I get error:

```<code>'SQLSTATE[HY000]: General error: 1364 Field 'date_anniversaire' doesn't have a default value (SQL: insert into `conseilleres` () values ())'
</code>```

Plus I dont know if what I did REALLY save it properly in the database. Basically, The conseillere model only has 2 date, but also have nom,prenom,adresse and adresse_courriel. Nom and Prenom are in another table called Personne.Adresse and ville are in another table named Adresse.Adresse_courriel is in another table called Courriel. Conseillere has all these attributes but they are referenced/contained in other tables/models.Conseillere model only contain date_anniversaire and date_entree column.Conseillere is a Personne. I am going to include some files that are needed, but im not sure if it would need more to help solve my issue.

First the usercontroller function that store the Conseillere into the database:

```<code>public function store(){

    $input = Input::all();
    $unepersonne = Personne::create([]);
    $uncourriel = new Courriel;
    $adresse = new Adresse;
    $conseillere = Conseillere::create([]);

    $uncourriel->adresse_courriel = $input['adresse_courriel'];
    $unepersonne->nom = $input['nom'];
    $unepersonne->prenom = $input['prenom'];

    $adresse->adresse = $input['adresse'];
    $adresse->ville = $input['ville'];

    //the following function are creating drop downs to input a date. for translation purpose, annee=year  mois=months and jour=day
    $conseillere->date_anniversaire = ConseillereController::construire_date($input['annee_anniversaire']-1, $input['mois_anniversaire']-1, $input['jour_anniversaire']-1);
    $conseillere->date_entree = ConseillereController::construire_date($input['annee_entree']-1, $input['mois_entree']-1, $input['jour_entree']-1);

    if ($unepersonne->save()){

    } else {

        return Redirect::back()->withInput()->withErrors($conseillere->validationMessages());
    }

}
</code>```

construire_date function:

```<code>    private function construire_date($annee, $mois, $jour)
{
    if (checkdate($mois, $jour, $annee)) {
        $dateTest = new DateTime;
        $dateTest->setDate($annee, $mois, $jour);
        return $dateTest->format('Y-m-d');
    } else {
        return "invalide";
    }
}
</code>```

}

Conseillere model:

```<code><?php

namespace App\Models;

class Conseillere extends EloquentValidating {
protected $guarded = array('id');

public $timestamps = false;

public function conseillere() {
    return $this->belongsTo('App\Models\Conseillere');
}

protected $fillable = [
        'nom',
        'prenom',
        'adresse',
        'ville',
        'adresse_courriel',
        'date_anniversaire',
        'date_entree'
    ];

/**
 * Validation
 */

public $validationMessages;

public function validationRules() {
    return [
            'date_anniversaire' => 'nullable|date',
            'date_entree' => 'nullable|date'
    ];
}
</code>```

}

Personne model:

```<code><?php

namespace App\Models;

class Personne extends EloquentValidating
{

protected $table = 'personnes';

public $timestamps = false;

protected $fillable = [

    'nom',
    'prenom',
];

public $validationMessages;

public function validationRules() {
    return
    [
            'personne' => 'required',
    ];
}

public function utilisateurs(){

    return $this->belongsToMany('App\Utilisateur');
}

public function adresse() {
    return $this->hasMany('App\Models\Adresse');
}

public function carte_credits(){

    return $this->belongsToMany('App\Carte_credit');
}

public function courriels(){
    return $this->hasMany('App\Models\Courriel');
}
</code>```

}

Migrations of Conseillere:

```<code>    public function up()
{
    Schema::create('conseilleres', function (Blueprint $table) {

        $table->increments('id');
        $table->dateTime('date_anniversaire');
        $table->dateTime('date_entree');

        $table->integer('personne_id')
                        ->unsigned();
        $table->foreign('personne_id')
                        ->references('id')
                        ->on('personnes')
                        ->onDelete('cascade');

    });
}
</code>```

Migrations of Personne:

```<code>    public function up()
{
    Schema::create('personnes', function (Blueprint $table) {
        $table->increments('id');
        $table->string('nom');
        $table->string('prenom');
        $table->timestamps();
    });
}
</code>```

Ive been searching for a while and cant figure why the store function isnt working and not saving into the db.

答:
Here's the line that is throwing the error you quote:

```<code>$conseillere = Conseillere::create([]);
</code>```

The create method creates and saves a record immediately.  It accepts an array of field => value data, but you are passing in an empty array, so it is trying to insert a blank record into the DB.

Going by your code, I think you are trying to create a new Conseillere model instance, set attributes, and then save it.  If so, change that line to:

```<code>$conseillere = new Conseillere;
</code>```

And then later, after you've set the required attributes:

```<code>$conseillere->date_entree = ...
$conseillere->save();
</code>```

UPDATE

Note though that I think you are going to have additional problems as your migration shows that a record in conseilleres has a foreign key personne_id.  So maybe you are trying to create your Personne, and save it along with the associated Conseillere?  If yes, you need to make a few changes.

First, AFAICT your Conseillere <-> Personne relationship is not defined correctly.  Your Conseillere model shows:

```<code>public function conseillere() {
    return $this->belongsTo('App\Models\Conseillere');
}
</code>```

But why would Conseillere be related to itself?  Shouldn't that be personne?

```<code>public function personne() {
    return $this->belongsTo('App\Models\Personne');
}
</code>```

You will also need to add the inverse relation on your Personne model, I do not see it in your code.

Next, you need to save both the Personne, and the related Conseillere.  You can do that as described in the docs:

```<code>// As above, change your create call to a simple 'new'
$conseillere = new Conseillere;

// ... rest of your code ...
$conseillere->date_entree = ...

// Now save the updated personne.  This only works bcs
// when you did $unepersonne = Personne::create([]) it created a
// blank record in the DB with an id, basically you are doing an
// update of an existing record here.
$unepersonne->save();

// Now save the related model.
$unepersonne->conseillere()->save($conseillere);
</code>```

Body:
I have a laravel project that is using a mysql database with a few tables.Lets start by showing you all my files that are being used.My problem is that when I try to create the 'Conseillere' into the database, I get error:

'SQLSTATE[HY000]: General error: 1364 Field 'date_anniversaire' doesn't have a default value (SQL: insert into `conseilleres` () values ())'

Plus I dont know if what I did REALLY save it properly in the database. Basically, The conseillere model only has 2 date, but also have nom,prenom,adresse and adresse_courriel. Nom and Prenom are in another table called Personne.Adresse and ville are in another table named Adresse.Adresse_courriel is in another table called Courriel. Conseillere has all these attributes but they are referenced/contained in other tables/models.Conseillere model only contain date_anniversaire and date_entree column.Conseillere is a Personne. I am going to include some files that are needed, but im not sure if it would need more to help solve my issue.

First the usercontroller function that store the Conseillere into the database:

public function store(){

    $input = Input::all();
    $unepersonne = Personne::create([]);
    $uncourriel = new Courriel;
    $adresse = new Adresse;
    $conseillere = Conseillere::create([]);

    $uncourriel->adresse_courriel = $input['adresse_courriel'];
    $unepersonne->nom = $input['nom'];
    $unepersonne->prenom = $input['prenom'];

    $adresse->adresse = $input['adresse'];
    $adresse->ville = $input['ville'];

    //the following function are creating drop downs to input a date. for translation purpose, annee=year  mois=months and jour=day
    $conseillere->date_anniversaire = ConseillereController::construire_date($input['annee_anniversaire']-1, $input['mois_anniversaire']-1, $input['jour_anniversaire']-1);
    $conseillere->date_entree = ConseillereController::construire_date($input['annee_entree']-1, $input['mois_entree']-1, $input['jour_entree']-1);

    if ($unepersonne->save()){

    } else {

        return Redirect::back()->withInput()->withErrors($conseillere->validationMessages());
    }

}

construire_date function:

    private function construire_date($annee, $mois, $jour)
{
    if (checkdate($mois, $jour, $annee)) {
        $dateTest = new DateTime;
        $dateTest->setDate($annee, $mois, $jour);
        return $dateTest->format('Y-m-d');
    } else {
        return "invalide";
    }
}

}

Conseillere model:

<?php

namespace App\Models;

class Conseillere extends EloquentValidating {
protected $guarded = array('id');

public $timestamps = false;

public function conseillere() {
    return $this->belongsTo('App\Models\Conseillere');
}

protected $fillable = [
        'nom',
        'prenom',
        'adresse',
        'ville',
        'adresse_courriel',
        'date_anniversaire',
        'date_entree'
    ];

/**
 * Validation
 */

public $validationMessages;

public function validationRules() {
    return [
            'date_anniversaire' => 'nullable|date',
            'date_entree' => 'nullable|date'
    ];
}

}

Personne model:

<?php

namespace App\Models;

class Personne extends EloquentValidating
{

protected $table = 'personnes';

public $timestamps = false;

protected $fillable = [

    'nom',
    'prenom',
];

public $validationMessages;

public function validationRules() {
    return
    [
            'personne' => 'required',
    ];
}

public function utilisateurs(){

    return $this->belongsToMany('App\Utilisateur');
}

public function adresse() {
    return $this->hasMany('App\Models\Adresse');
}

public function carte_credits(){

    return $this->belongsToMany('App\Carte_credit');
}

public function courriels(){
    return $this->hasMany('App\Models\Courriel');
}

}

Migrations of Conseillere:

    public function up()
{
    Schema::create('conseilleres', function (Blueprint $table) {

        $table->increments('id');
        $table->dateTime('date_anniversaire');
        $table->dateTime('date_entree');

        $table->integer('personne_id')
                        ->unsigned();
        $table->foreign('personne_id')
                        ->references('id')
                        ->on('personnes')
                        ->onDelete('cascade');

    });
}

Migrations of Personne:

    public function up()
{
    Schema::create('personnes', function (Blueprint $table) {
        $table->increments('id');
        $table->string('nom');
        $table->string('prenom');
        $table->timestamps();
    });
}

Ive been searching for a while and cant figure why the store function isnt working and not saving into the db.

Body:
Here's the line that is throwing the error you quote:

$conseillere = Conseillere::create([]);

The create method creates and saves a record immediately.  It accepts an array of field => value data, but you are passing in an empty array, so it is trying to insert a blank record into the DB.

Going by your code, I think you are trying to create a new Conseillere model instance, set attributes, and then save it.  If so, change that line to:

$conseillere = new Conseillere;

And then later, after you've set the required attributes:

$conseillere->date_entree = ...
$conseillere->save();

UPDATE

Note though that I think you are going to have additional problems as your migration shows that a record in conseilleres has a foreign key personne_id.  So maybe you are trying to create your Personne, and save it along with the associated Conseillere?  If yes, you need to make a few changes.

First, AFAICT your Conseillere <-> Personne relationship is not defined correctly.  Your Conseillere model shows:

public function conseillere() {
    return $this->belongsTo('App\Models\Conseillere');
}

But why would Conseillere be related to itself?  Shouldn't that be personne?

public function personne() {
    return $this->belongsTo('App\Models\Personne');
}

You will also need to add the inverse relation on your Personne model, I do not see it in your code.

Next, you need to save both the Personne, and the related Conseillere.  You can do that as described in the docs:

// As above, change your create call to a simple 'new'
$conseillere = new Conseillere;

// ... rest of your code ...
$conseillere->date_entree = ...

// Now save the updated personne.  This only works bcs
// when you did $unepersonne = Personne::create([]) it created a
// blank record in the DB with an id, basically you are doing an
// update of an existing record here.
$unepersonne->save();

// Now save the related model.
$unepersonne->conseillere()->save($conseillere);


问:
Stop Xcode automatically generating Swift interfaces for Objective-C headers
Is it possible to stop Xcode (8) from automatically generating a Swift interface when showing an Objective-C header? For example by setting a user defaults value.

In theory it’s a really nice feature of Xcode. Unfortunately it doesn’t work reliably. For me it even seem to fail most of the time. As I haven’t been able to discern why it happens, I’d like to opt out of it, until the bugs Xcode/SourceKit have been resolved.

答: The default behaviour should be dependent on your project settings. If you're in a Swift project it will want to show you Swift interfaces. Also if there is an Objective-C interface that Xcode generate Swift from then using Cmd+Alt+Enter you should be able to look at the Objective-C header "Counterpart" of the Swift code there for comparison.</p>


问:
Adding multiple user inputs into one variable in Bash

I am fairly new to unix bash scripting and need to know if this is possible. I want to ask user for their input multiple times and then store that input in to one variable.

```<code>userinputs=   #nothing at the start

read string
<code to add $string to $userinputs>
read string
<code to add $string to $userinputs> #this should add this input along with the other input
</code>```

so if the user enters "abc" when asked first time, it add's "abc" in $userinputs

then when asked again for the input and the user enters "123" the script should store it in the same $userinputs

this would make the $userinput=abc123

答:
The usual way to concat two strings in Bash is:

```<code>new_string="$string1$string2"
</code>```

{} are needed around the variable name only if we have a literal string that can obstruct the variable expansion:

```<code>new_string="${string1}literal$string2"
</code>```

rather than

```<code>new_string="$string1literal$string2"
</code>```

You can also use the += operator:

```<code>userinputs=
read string
userinputs+="$string"
read string
userinputs+="$string"
</code>```

Double quoting $string is optional in this case.

See also:

How to concatenate string variables in Bash?

Body:
I am fairly new to unix bash scripting and need to know if this is possible. I want to ask user for their input multiple times and then store that input in to one variable.

userinputs=   #nothing at the start

read string

read string
 #this should add this input along with the other input

so if the user enters "abc" when asked first time, it add's "abc" in $userinputs

then when asked again for the input and the user enters "123" the script should store it in the same $userinputs

this would make the $userinput=abc123

Body:
The usual way to concat two strings in Bash is:

new_string="$string1$string2"

{} are needed around the variable name only if we have a literal string that can obstruct the variable expansion:

new_string="${string1}literal$string2"

rather than

new_string="$string1literal$string2"

You can also use the += operator:

userinputs=
read string
userinputs+="$string"
read string
userinputs+="$string"

Double quoting $string is optional in this case.

See also:

How to concatenate string variables in Bash?


问:
Django API list with pagination - Page is not JSON serializable
I am trying to create a Django API for a list with pagination but have this error

```<code>TypeError: Object of type 'Page' is not JSON serializable
</code>```

The following is my API code:

```<code>@api_view(['POST'])
def employee_get_list_by_page(request):
    # ----- YAML below for Swagger -----
    """
    description: employee_get_list_by_page
    parameters:
      - name: token
        type: string
        required: true
        location: form
      - name: page
        type: string
        required: true
        location: form
      - name: page_limit
        type: string
        required: true
        location: form
    """
    token = request.POST['token']
    try:
        auth_employee = AuthEmployeeSessionToken.objects.get(token=token)

    except AuthEmployeeSessionToken.DoesNotExist:
        return Response("Invalid Token", status=status.HTTP_406_NOT_ACCEPTABLE)

    employee_list = Employee.objects.filter(company = auth_employee.employee.company.id)

    page = request.GET.get('page', request.POST['page'])
    paginator = Paginator(employee_list, request.POST['page_limit'])

    try:
        employees = paginator.page(page)
    except PageNotAnInteger:
        employees = paginator.page(request.POST['page'])
    except EmptyPage:
        employees = paginator.page(paginator.num_pages)

    return Response(employees,status=status.HTTP_200_OK) <-- passing employees probably cause this error that employees as Page is not JSON serializable.
</code>```

This is my model https://gist.github.com/axilaris/89b2ac6a7762f428ad715f4916f43967. as_dict notice I have this .as_dict() to create my json for response. I use it for single request but for list Im not sure how it is done.

How do an API query for this list with pagination support ?

Side issue which I want the JSON to list just the fields that I want.

答:
I just had a go at recreating this, and I see a few ways to fix it.

Firstly, JSON will not be able to parse either the Page object, nor the QuerySet underlying the page.object_list property.  It will say "Object of type 'Employee' is not JSON serialisable".

So to solve this, I'd try:

```<code>employee_list = Employee.objects.filter(company = auth_employee.employee.company.id).values().order_by('id')

page = request.GET.get('page', request.POST['page'])
paginator = Paginator(employee_list, request.POST['page_limit'])

try:
    employees = paginator.page(page)
except PageNotAnInteger:
    employees = paginator.page(request.POST['page'])
except EmptyPage:
    employees = paginator.page(paginator.num_pages)

return Response(list(employees) ,status=status.HTTP_200_OK)
</code>```

Firstly, we use .values() on the employees queryset because the resulting ValuesQuerySet of this call can be parsed with list(employees).  Inside the Page class, they evaluate the object list inside the instance this way before returning any results.

Lastly, because JSON can't serialise the Page class, we simply call list(Page) to return a list.  This works because Page implements __getitem__ and returns the underlying object_list.

Also, you may find that some datatypes will throw JSON serialization errors (values() will return DateTime objects for DateTime fields).  In my testing I had an issue with Object of type 'datetime' is not JSON serializable.  If this happens, you need to use a different JSON Encoder or extend your own.  The DjangoJSONEncoder can be found in django.core.serializers.json.DjangoJSONEncoder and handles datetimes, uuids, decimals, and other common datatypes in django.

Edit:: You've mentioned your model code as:

```<code>class Employee(models.Model):

    user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='employee')
    company = models.ForeignKey(Company)
    username = models.CharField(max_length=30, blank=False)
    email = models.CharField(max_length=30, blank=False)
    first_name = models.CharField(max_length=30, blank=False)
    last_name = models.CharField(max_length=30, blank=False)

    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.user.username

    def as_dict(self):

        return {"id": "%d" % self.id,
                "company": self.company.as_dict(),
                "username": self.username if self.username else "",
                "email": self.email if self.email else "",
                "first_name": self.first_name if self.first_name else "",
                "last_name": self.last_name if self.last_name else "",
                "tel":self.tel if self.tel else "",
                "created_at":self.created_at.strftime('%Y-%m-%d %H:%M'),
                "updated_at":self.updated_at.strftime('%Y-%m-%d %H:%M')}
</code>```

Because you have this as_dict method, we could use this to render the representation of your employees instead of relying on .values().  Here is how:

```<code>employee_list = Employee.objects.filter(company = auth_employee.employee.company.id).order_by('id')

page = request.GET.get('page', request.POST['page'])
paginator = Paginator(employee_list, request.POST['page_limit'])

try:
    employees = paginator.page(page)
except PageNotAnInteger:
    employees = paginator.page(request.POST['page'])
except EmptyPage:
    employees = paginator.page(paginator.num_pages)
#  Here we map a lambda function over the queryset of Models to return the dictionary representation for each element in the list
employees_page = list(
    map(lambda employee: employee.as_dict(), list(employees))
)
return Response(employees_page ,status=status.HTTP_200_OK)
</code>```

Body:
I am trying to create a Django API for a list with pagination but have this error

TypeError: Object of type 'Page' is not JSON serializable

The following is my API code:

@api_view(['POST'])
def employee_get_list_by_page(request):
    # ----- YAML below for Swagger -----
    """
    description: employee_get_list_by_page
    parameters:
      - name: token
        type: string
        required: true
        location: form
      - name: page
        type: string
        required: true
        location: form
      - name: page_limit
        type: string
        required: true
        location: form
    """
    token = request.POST['token']
    try:
        auth_employee = AuthEmployeeSessionToken.objects.get(token=token)

    except AuthEmployeeSessionToken.DoesNotExist:
        return Response("Invalid Token", status=status.HTTP_406_NOT_ACCEPTABLE)

    employee_list = Employee.objects.filter(company = auth_employee.employee.company.id)

    page = request.GET.get('page', request.POST['page'])
    paginator = Paginator(employee_list, request.POST['page_limit'])

    try:
        employees = paginator.page(page)
    except PageNotAnInteger:
        employees = paginator.page(request.POST['page'])
    except EmptyPage:
        employees = paginator.page(paginator.num_pages)

    return Response(employees,status=status.HTTP_200_OK) <-- passing employees probably cause this error that employees as Page is not JSON serializable.

This is my model https://gist.github.com/axilaris/89b2ac6a7762f428ad715f4916f43967. as_dict notice I have this .as_dict() to create my json for response. I use it for single request but for list Im not sure how it is done.

How do an API query for this list with pagination support ?

Side issue which I want the JSON to list just the fields that I want.

Body:
I just had a go at recreating this, and I see a few ways to fix it.

Firstly, JSON will not be able to parse either the Page object, nor the QuerySet underlying the page.object_list property.  It will say "Object of type 'Employee' is not JSON serialisable".

So to solve this, I'd try:

employee_list = Employee.objects.filter(company = auth_employee.employee.company.id).values().order_by('id')

page = request.GET.get('page', request.POST['page'])
paginator = Paginator(employee_list, request.POST['page_limit'])

try:
    employees = paginator.page(page)
except PageNotAnInteger:
    employees = paginator.page(request.POST['page'])
except EmptyPage:
    employees = paginator.page(paginator.num_pages)

return Response(list(employees) ,status=status.HTTP_200_OK)

Firstly, we use .values() on the employees queryset because the resulting ValuesQuerySet of this call can be parsed with list(employees).  Inside the Page class, they evaluate the object list inside the instance this way before returning any results.

Lastly, because JSON can't serialise the Page class, we simply call list(Page) to return a list.  This works because Page implements __getitem__ and returns the underlying object_list.

Also, you may find that some datatypes will throw JSON serialization errors (values() will return DateTime objects for DateTime fields).  In my testing I had an issue with Object of type 'datetime' is not JSON serializable.  If this happens, you need to use a different JSON Encoder or extend your own.  The DjangoJSONEncoder can be found in django.core.serializers.json.DjangoJSONEncoder and handles datetimes, uuids, decimals, and other common datatypes in django.

Edit:: You've mentioned your model code as:

class Employee(models.Model):

    user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='employee')
    company = models.ForeignKey(Company)
    username = models.CharField(max_length=30, blank=False)
    email = models.CharField(max_length=30, blank=False)
    first_name = models.CharField(max_length=30, blank=False)
    last_name = models.CharField(max_length=30, blank=False)

    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.user.username

    def as_dict(self):

        return {"id": "%d" % self.id,
                "company": self.company.as_dict(),
                "username": self.username if self.username else "",
                "email": self.email if self.email else "",
                "first_name": self.first_name if self.first_name else "",
                "last_name": self.last_name if self.last_name else "",
                "tel":self.tel if self.tel else "",
                "created_at":self.created_at.strftime('%Y-%m-%d %H:%M'),
                "updated_at":self.updated_at.strftime('%Y-%m-%d %H:%M')}

Because you have this as_dict method, we could use this to render the representation of your employees instead of relying on .values().  Here is how:

employee_list = Employee.objects.filter(company = auth_employee.employee.company.id).order_by('id')

page = request.GET.get('page', request.POST['page'])
paginator = Paginator(employee_list, request.POST['page_limit'])

try:
    employees = paginator.page(page)
except PageNotAnInteger:
    employees = paginator.page(request.POST['page'])
except EmptyPage:
    employees = paginator.page(paginator.num_pages)
#  Here we map a lambda function over the queryset of Models to return the dictionary representation for each element in the list
employees_page = list(
    map(lambda employee: employee.as_dict(), list(employees))
)
return Response(employees_page ,status=status.HTTP_200_OK)


问:
load spinner works only after first drop down select
My page loads and displays the  with the Loading spinner icon. Once data populates in my Data Table, subsequent selections [changes] in drop down selection does not trigger the spinner. I even put the jQuery inside the function that grabs new data to load into the Data Table. Too much code to paste the whole file, but the spinner is styled, then jQuery shows and hides it before Ajax call and after Success:

```<code><style>
#div_loading_image {
        display:none;
        position:absolute;
        background: rgba(255, 255, 255, .5);
        background-repeat: no-repeat;
        width: 100px;
        height: 100px;
        top: 10%;
        left: 60%;
    }
</style>
</code>```

Then inside the  tag:

```<code><div id="div_loading_image"><img id="loading_image" src="images/ajax-loader.gif" /></div>
</code>```

Next, inside document ready, i get the data, set up the Data Table, add the drop down change function:

```<code>jQuery(document).ready(function (){
get_data(); //doing this here allows page refresh to populate page with current LP and FY selection.

var table = jQuery('#am_status').DataTable({
   scrollY:true,
   scrollX:true,
   scrollCollapse: true,
   paging:false,
   fixedHeader: true,
   autoWidth: true,
   //dom: 'Bfrtip', //has to be here, it puts the buttons in the dom.
   dom: 'Bfrtip',
   //buttons: ['copy', 'csv', 'excel', 'pdf', 'print']
   buttons: ['copy', 'csv', 'excel', 'print']
});

jQuery('#fy_select').on('change', function() {
    jQuery('#div_loading_image').show();
    get_data();
})
</code>```

Then get the data:

```<code> function get_data() {

    jQuery('#div_loading_image').show();
    var fy = jQuery('#fy_select').val();

jQuery.ajax({
            url: "https://fabrik.smartstartinc.net/ncpcphp/<?php echo THIS_DIR; ?>/am_status_get_info.php",
            //contentType: "application/json",
            data: {fy: fy},
            dataType: "json",
            type: 'post',
            success: function(data, XMLHttpRequest) {
                console.log(data);
                table.clear(); //otherwise the table will append to the previous Retrieve.
                var counter = 0; //to tag the dynamic fields with their own unique identifying class name.
                var index = 0;
                //console.log("data.length/before .each: " + data.length);
</code>```

Then go through the returned data:

```<code>jQuery.each(data, function(index) {
</code>```

Process the data and push it into the Data Table:

```<code>table.row.add([
                        info_01, info_02, info_03, info_04, info_05, info_06, info_07, info_08, info_09, info_10, info_11, info_12, info_13, info_14, info_15, info_16, info_17
                        //am_status_info[0], am_status_info[0], am_status_info[2], am_status_info[3], am_status_info[4], am_status_info[5], am_status_info[6], am_status_info[7], am_status_info[8], am_status_info[9], am_status_info[10], am_status_info[11], am_status_info[12], am_status_info[13], am_status_info[14], am_status_info[15], am_status_info[16]
                    ]).draw();
</code>```

Then finish out the get_data() function:

```<code>}); //.each
                //} //for

                jQuery('#div_loading_image').hide();
                console.log("data.length/after .each: " + data.length);

                //now after page is loaded, scroll through and check the the checkboxes.
                //note that above to add checking logic would make code readability much lower.
           },
           error: function(XMLHttpRequest, textStatus, errorThrown) {
                alert(errorThrown);
           }
        }); //.ajax
    //}, 0); //setTimeout

        setTimeout(align_table, 500); //otherwise, DataTable headers do not align with table data population.
        return false;
}
</code>```

});

I hope that omitting some of the code does not hinder the troubleshooting. Any ideas why a div show would not trigger after subsequent selections of a drop down?

答:
try something like:

```<code>$(document).on('change', '#fy_select', function () {

});
</code>```

The event jQuery('#fy_select').on('change', function() { just trigger based on existing DOM on event creation time..

Body:
My page loads and displays the  with the Loading spinner icon. Once data populates in my Data Table, subsequent selections [changes] in drop down selection does not trigger the spinner. I even put the jQuery inside the function that grabs new data to load into the Data Table. Too much code to paste the whole file, but the spinner is styled, then jQuery shows and hides it before Ajax call and after Success:

Then inside the  tag:

Next, inside document ready, i get the data, set up the Data Table, add the drop down change function:

jQuery(document).ready(function (){
get_data(); //doing this here allows page refresh to populate page with current LP and FY selection.

var table = jQuery('#am_status').DataTable({
   scrollY:true,
   scrollX:true,
   scrollCollapse: true,
   paging:false,
   fixedHeader: true,
   autoWidth: true,
   //dom: 'Bfrtip', //has to be here, it puts the buttons in the dom.
   dom: 'Bfrtip',
   //buttons: ['copy', 'csv', 'excel', 'pdf', 'print']
   buttons: ['copy', 'csv', 'excel', 'print']
});

jQuery('#fy_select').on('change', function() {
    jQuery('#div_loading_image').show();
    get_data();
})

Then get the data:

 function get_data() {

    jQuery('#div_loading_image').show();
    var fy = jQuery('#fy_select').val();

jQuery.ajax({
            url: "https://fabrik.smartstartinc.net/ncpcphp/<?php echo THIS_DIR; ?>/am_status_get_info.php",
            //contentType: "application/json",
            data: {fy: fy},
            dataType: "json",
            type: 'post',
            success: function(data, XMLHttpRequest) {
                console.log(data);
                table.clear(); //otherwise the table will append to the previous Retrieve.
                var counter = 0; //to tag the dynamic fields with their own unique identifying class name.
                var index = 0;
                //console.log("data.length/before .each: " + data.length);

Then go through the returned data:

jQuery.each(data, function(index) {

Process the data and push it into the Data Table:

table.row.add([
                        info_01, info_02, info_03, info_04, info_05, info_06, info_07, info_08, info_09, info_10, info_11, info_12, info_13, info_14, info_15, info_16, info_17
                        //am_status_info[0], am_status_info[0], am_status_info[2], am_status_info[3], am_status_info[4], am_status_info[5], am_status_info[6], am_status_info[7], am_status_info[8], am_status_info[9], am_status_info[10], am_status_info[11], am_status_info[12], am_status_info[13], am_status_info[14], am_status_info[15], am_status_info[16]
                    ]).draw();

Then finish out the get_data() function:

}); //.each
                //} //for

                jQuery('#div_loading_image').hide();
                console.log("data.length/after .each: " + data.length);

                //now after page is loaded, scroll through and check the the checkboxes.
                //note that above to add checking logic would make code readability much lower.
           },
           error: function(XMLHttpRequest, textStatus, errorThrown) {
                alert(errorThrown);
           }
        }); //.ajax
    //}, 0); //setTimeout

        setTimeout(align_table, 500); //otherwise, DataTable headers do not align with table data population.
        return false;
}

});

I hope that omitting some of the code does not hinder the troubleshooting. Any ideas why a div show would not trigger after subsequent selections of a drop down?

Body:
try something like:

$(document).on('change', '#fy_select', function () {

});

The event jQuery('#fy_select').on('change', function() { just trigger based on existing DOM on event creation time..


问:
angular 2 cli returns error if using --aot
I have this code that works fine:

```<code>samplesInfo: any = [];
selectedSampleType: Object = {};
selectedSampleTypeForModal: string; // pass type as string to the child component
userFormSubmitted: boolean;

ngOnInit() {

    this.SamplesInfoService.getSamplesInfo()
        .map((res: Response) => res)
        .subscribe(
            data => {
                function hasType(value) { return value.hasOwnProperty('type'); }
                this.samplesInfo = data,
                this.selectedSampleType = this.samplesInfo.filter(hasType)[0],
                this.selectedSampleTypeForModal = this.samplesInfo.filter(hasType)[0].type,
                console.log("OLGA " + this.samplesInfo.filter(hasType)[0]);
                },
            err => { console.log(err); return Observable.of(true); }
    );

}
</code>```

But if I try to build within CLI with the "--aot" added to the command, then I have an error: "Property 'type' does not exist on type 'Object'".

What am I doing wrong here?

Thanks,
Olga

答:
The problem is most likely due to the .subscribe() response returning an empty data set or null before it populates with data creating a possible error. You can prevent the error from occurring on empty data sets by first running the filter to determine if there are any results (and hopefully your AOT build will no longer fail if it is making this check):

```<code>this.SamplesInfoService.getSamplesInfo()
    .map((res: Response) => res)
    .subscribe(
        data => {
            function hasType(value) { return value.hasOwnProperty('type'); }
            this.samplesInfo = data,
            if ( this.samplesInfo.filter(hasType) ) {
              this.selectedSampleType = this.samplesInfo.filter(hasType)[0],
              this.selectedSampleTypeForModal = this.samplesInfo.filter(hasType)[0].type,[0]);
            }
            },
        err => { console.log(err); return Observable.of(true); }
);
</code>```

Body:
I have this code that works fine:

samplesInfo: any = [];
selectedSampleType: Object = {};
selectedSampleTypeForModal: string; // pass type as string to the child component
userFormSubmitted: boolean;

ngOnInit() {

    this.SamplesInfoService.getSamplesInfo()
        .map((res: Response) => res)
        .subscribe(
            data => {
                function hasType(value) { return value.hasOwnProperty('type'); }
                this.samplesInfo = data,
                this.selectedSampleType = this.samplesInfo.filter(hasType)[0],
                this.selectedSampleTypeForModal = this.samplesInfo.filter(hasType)[0].type,
                console.log("OLGA " + this.samplesInfo.filter(hasType)[0]);
                },
            err => { console.log(err); return Observable.of(true); }
    );

}

But if I try to build within CLI with the "--aot" added to the command, then I have an error: "Property 'type' does not exist on type 'Object'".

What am I doing wrong here?

Thanks,
Olga

Body:
The problem is most likely due to the .subscribe() response returning an empty data set or null before it populates with data creating a possible error. You can prevent the error from occurring on empty data sets by first running the filter to determine if there are any results (and hopefully your AOT build will no longer fail if it is making this check):

this.SamplesInfoService.getSamplesInfo()
    .map((res: Response) => res)
    .subscribe(
        data => {
            function hasType(value) { return value.hasOwnProperty('type'); }
            this.samplesInfo = data,
            if ( this.samplesInfo.filter(hasType) ) {
              this.selectedSampleType = this.samplesInfo.filter(hasType)[0],
              this.selectedSampleTypeForModal = this.samplesInfo.filter(hasType)[0].type,[0]);
            }
            },
        err => { console.log(err); return Observable.of(true); }
);


问:
How can I get the parent site, or the site where the file was sent from, in javascript?
I'm writing a node.js application with client-side javascript that uses fetch to get data from the node API that I wrote. I want to be able to put that application on any site (URL) without changing anything in the javascript. My current code goes something like fetch("http://localhost:8080/data.json"). If I wanted to deploy onto Heroku, for example, I would have to change that. Is there a way to overcome this fact?

答:
Window location might do the trick, if I am understanding correctly. Set it into a variable like this:

For browser:

If the hostname is http://localhost:8000, using this:

```<code>  // http://localhost:8000/data.json
    var url = window.location.hostname + "/data.json";
    fetch(url)
</code>```

Heres another example.

```<code>document.getElementById("demo").innerHTML =
"Page location is " + window.location.href;
</code>```

Result is

```<code>Page location is https://www.w3schools.com/js/js_window_location.asp
</code>```

More info:
https://www.w3schools.com/js/js_window_location.asp

I see you wanted NodeJS, for server

```<code>var os = require("os");
var port = process.env.PORT || 8000
var url = os.hostname;
var final = url + ":" + port
// localhost:port
var hostname = os.hostname();
</code>```

Body:
Window location might do the trick, if I am understanding correctly. Set it into a variable like this:

For browser:

If the hostname is http://localhost:8000, using this:

  // http://localhost:8000/data.json
    var url = window.location.hostname + "/data.json";
    fetch(url)

Heres another example.

document.getElementById("demo").innerHTML =
"Page location is " + window.location.href;

Result is

Page location is https://www.w3schools.com/js/js_window_location.asp

More info:
https://www.w3schools.com/js/js_window_location.asp

I see you wanted NodeJS, for server

var os = require("os");
var port = process.env.PORT || 8000
var url = os.hostname;
var final = url + ":" + port
// localhost:port
var hostname = os.hostname();


问:
Ember.js - change the format of a network request sent when getting a model's related objects
I am trying to make my network calls between my Ember app and my Rails API backend more efficient when fetching an ember data object's related objects. Let's say I have two models:

shop - a shop has many products

product - a product belongs to a shop

I am using a RESTAdapter for both of these models, so if I try to get a shop's products like so:

```<code>let shop = this.store.find("shop", 1);
let products = shop.get("products");
</code>```

Let's assume I have a shop with a hasMany relationship to the first 500 products in my database. The network requests will look something like this (assume all url paths are valid and lead to valid controllers and actions):

```<code>localhost:3000/api/v1/shops/1
localhost:3000/api/v1/products/1
localhost:3000/api/v1/products/2
localhost:3000/api/v1/products/3
localhost:3000/api/v1/products/4
localhost:3000/api/v1/products/5
...
</code>```

My products api endpoint can take in a filter parameter to feed into an ApplicationRecord.where call. So what I'd really like to do is to be able to change the outcome of the shop.get("products") call so it makes a single call to my products endpoint with a filter parameter and gets all related products in bulk, instead of 500 individual calls to the api endpoint.

Is there an established pattern for doing this?

答:
Yes there is a pattern/a parameter for that.

It's called coalesceFindRequests and would be set in your application adapter:

```<code>// app/adapters/application.js

export default DS.RESTAdapter.extend({
    coalesceFindRequests: true,
    // more params to be set here
});
</code>```

related links:

The Adapter Docs

an emberjs docs-entry

a forum entry

Body:
I am trying to make my network calls between my Ember app and my Rails API backend more efficient when fetching an ember data object's related objects. Let's say I have two models:

shop - a shop has many products

product - a product belongs to a shop

I am using a RESTAdapter for both of these models, so if I try to get a shop's products like so:

let shop = this.store.find("shop", 1);
let products = shop.get("products");

Let's assume I have a shop with a hasMany relationship to the first 500 products in my database. The network requests will look something like this (assume all url paths are valid and lead to valid controllers and actions):

localhost:3000/api/v1/shops/1
localhost:3000/api/v1/products/1
localhost:3000/api/v1/products/2
localhost:3000/api/v1/products/3
localhost:3000/api/v1/products/4
localhost:3000/api/v1/products/5
...

My products api endpoint can take in a filter parameter to feed into an ApplicationRecord.where call. So what I'd really like to do is to be able to change the outcome of the shop.get("products") call so it makes a single call to my products endpoint with a filter parameter and gets all related products in bulk, instead of 500 individual calls to the api endpoint.

Is there an established pattern for doing this?

Body:
Yes there is a pattern/a parameter for that.

It's called coalesceFindRequests and would be set in your application adapter:

// app/adapters/application.js

export default DS.RESTAdapter.extend({
    coalesceFindRequests: true,
    // more params to be set here
});

related links:

The Adapter Docs

an emberjs docs-entry

a forum entry


问:
reference and const confusion in C++
I knew that reference is just another name of a variable, they do not exist as a separate object in memory but what is happening here

```<code>double i = 24.7;
const int &ri = i;  //notice int here
std::cout << i << std::endl; //prints 24.7
i = 44.4;
std::cout << ri << std::endl; // prints 24
std::cout << i << std::endl; //prints 44.4
</code>```

My question is ri is alias of what ? [value 24 in somewhere memory]

答:
You can't bind reference to object with different type directly.

For const int &ri = i;, i needs to be converted to int at first, then a temporary int is created and then bound to ri, it has nothing to do with the original object i.

BTW: The lifetime of the temporary is extended to match the lifetime of the reference here.

BTW2: Temporary can only be bound to lvalue-reference to const or rvalue-reference.

Title: reference and const confusion in C++

Body:
I knew that reference is just another name of a variable, they do not exist as a separate object in memory but what is happening here

double i = 24.7;
const int &ri = i;  //notice int here
std::cout << i << std::endl; //prints 24.7
i = 44.4;
std::cout << ri << std::endl; // prints 24
std::cout << i << std::endl; //prints 44.4

My question is ri is alias of what ? [value 24 in somewhere memory]


问:
Unzip not replacing file
I have a problem with a zip file replacing an existing file. I have looked at other examples on here and I still can't seem to figure it out...
I have a loop that writes some stats of the file extracted into a textbox. I think that its this line:

if (!System.IO.File.Exists(fileUnzipFullName))

My Code:

```<code>    public void UnzipFileNew()
    {
        richTextBox1.AppendText("\r\n" + "EXTRACTING!");

        String rootpath = Environment.CurrentDirectory;
        //This stores the path where the file should be unzipped to,
        //including any subfolders that the file was originally in.
        string fileUnzipFullPath;

        //This is the full name of the destination file including
        //the path
        string fileUnzipFullName;

        //Opens the zip file up to be read
        using (ZipArchive archive = ZipFile.OpenRead(@"update.zip"))
        {
            //Loops through each file in the zip file
            foreach (ZipArchiveEntry file in archive.Entries)
            {

                //Outputs file information to the Textbox
                richTextBox1.AppendText("\r\n");
                richTextBox1.AppendText("File Name: "+ file.Name);
                richTextBox1.AppendText("\r\n");
                richTextBox1.AppendText("File Size: bytes "+ file.Length);
                richTextBox1.AppendText("\r\n");
                richTextBox1.AppendText("Compression Ratio: "+ ((double)file.CompressedLength / file.Length).ToString("0.0%"));
                richTextBox1.AppendText("\r\n");

                //Identifies the destination file name and path
                fileUnzipFullName = Path.Combine(rootpath, file.FullName); //fileUnzipFullName = Path.Combine(@"Example\", file.FullName);

                //Extracts
                if (!System.IO.File.Exists(fileUnzipFullName))
                {

                    fileUnzipFullPath = Path.GetDirectoryName(fileUnzipFullName);

                    //Creates the directory if it doesn't exist
                    Directory.CreateDirectory(fileUnzipFullPath);

                    //Extracts the file to (potentially new) path
                    file.ExtractToFile(fileUnzipFullName);
                }

            }
        }
    }
</code>```

答:
if (!System.IO.File.Exists(fileUnzipFullName)) will indeed prevent you even trying to extract the file if it already exists. So you will need to remove this or change it as per your use case.

Additionally, the ExtractToFile method will throw an IOException if the file already exists as you are using it. Fortunately, MSDN reveals that there is an overload with a boolean flag for overwriting:

```<code>public static void ExtractToFile(
    this ZipArchiveEntry source,
    string destinationFileName,
    bool overwrite
)
</code>```

So instead of

```<code>file.ExtractToFile(fileUnzipFullName);
</code>```

use

```<code>file.ExtractToFile(fileUnzipFullName, true);
</code>```

Using your code, this will indiscriminately overwrite all files with the ones extracted from the zip:

```<code>//Extracts
//if (!System.IO.File.Exists(fileUnzipFullName))
//{
    fileUnzipFullPath = Path.GetDirectoryName(fileUnzipFullName);

    //Creates the directory if it doesn't exist
    Directory.CreateDirectory(fileUnzipFullPath);

    //Extracts the file to (potentially new) path
    file.ExtractToFile(fileUnzipFullName, true);
//}
</code>```

Title: Unzip not replacing file

Body:
I have a problem with a zip file replacing an existing file. I have looked at other examples on here and I still can't seem to figure it out...
I have a loop that writes some stats of the file extracted into a textbox. I think that its this line:

if (!System.IO.File.Exists(fileUnzipFullName))

My Code:

    public void UnzipFileNew()
    {
        richTextBox1.AppendText("\r\n" + "EXTRACTING!");

        String rootpath = Environment.CurrentDirectory;
        //This stores the path where the file should be unzipped to,
        //including any subfolders that the file was originally in.
        string fileUnzipFullPath;

        //This is the full name of the destination file including
        //the path
        string fileUnzipFullName;

        //Opens the zip file up to be read
        using (ZipArchive archive = ZipFile.OpenRead(@"update.zip"))
        {
            //Loops through each file in the zip file
            foreach (ZipArchiveEntry file in archive.Entries)
            {

                //Outputs file information to the Textbox
                richTextBox1.AppendText("\r\n");
                richTextBox1.AppendText("File Name: "+ file.Name);
                richTextBox1.AppendText("\r\n");
                richTextBox1.AppendText("File Size: bytes "+ file.Length);
                richTextBox1.AppendText("\r\n");
                richTextBox1.AppendText("Compression Ratio: "+ ((double)file.CompressedLength / file.Length).ToString("0.0%"));
                richTextBox1.AppendText("\r\n");

                //Identifies the destination file name and path
                fileUnzipFullName = Path.Combine(rootpath, file.FullName); //fileUnzipFullName = Path.Combine(@"Example\", file.FullName);

                //Extracts
                if (!System.IO.File.Exists(fileUnzipFullName))
                {

                    fileUnzipFullPath = Path.GetDirectoryName(fileUnzipFullName);

                    //Creates the directory if it doesn't exist
                    Directory.CreateDirectory(fileUnzipFullPath);

                    //Extracts the file to (potentially new) path
                    file.ExtractToFile(fileUnzipFullName);
                }

            }
        }
    }

Body:
if (!System.IO.File.Exists(fileUnzipFullName)) will indeed prevent you even trying to extract the file if it already exists. So you will need to remove this or change it as per your use case.

Additionally, the ExtractToFile method will throw an IOException if the file already exists as you are using it. Fortunately, MSDN reveals that there is an overload with a boolean flag for overwriting:

public static void ExtractToFile(
    this ZipArchiveEntry source,
    string destinationFileName,
    bool overwrite
)

So instead of

file.ExtractToFile(fileUnzipFullName);

use

file.ExtractToFile(fileUnzipFullName, true);

Using your code, this will indiscriminately overwrite all files with the ones extracted from the zip:

//Extracts
//if (!System.IO.File.Exists(fileUnzipFullName))
//{
    fileUnzipFullPath = Path.GetDirectoryName(fileUnzipFullName);

    //Creates the directory if it doesn't exist
    Directory.CreateDirectory(fileUnzipFullPath);

    //Extracts the file to (potentially new) path
    file.ExtractToFile(fileUnzipFullName, true);
//}


问:
ref.on, ref.off with React
While reading a tutorial on React I noticed the following code.

```<code>componentDidMount () {
ref.on('value', function (snapshot) {
  this.setState(function () {
    return {
      friends: snapshot.val()
    }
  })
}.bind(this)
}
</code>```

Where does the 'ref.on' method come from? Is that something baked into React or is it a JavaScript function? I can't find it here https://facebook.github.io/react/docs/react-api.html or here https://developer.mozilla.org/en-US/docs/Web/JavaScript.  Also, there is 'ref.off' in another place in the React components.

```<code>componentWillUnmount () {
  ref.off()
}
</code>```

EDIT:

It's helpful to know that it may be pseudocode. It's from this course https://learn.tylermcginnis.com/courses/50507/lectures/762618. But you have to login to view it. It's in the section on React Life Cycle Events.

I'm asking about the '.on' and '.off' parts, not the 'ref'.

答: Looks like jQuery's method for adding and removing event listeners. Probably just using it as an example.</p>

Title: ref.on, ref.off with React

Body:
While reading a tutorial on React I noticed the following code.

componentDidMount () {
ref.on('value', function (snapshot) {
  this.setState(function () {
    return {
      friends: snapshot.val()
    }
  })
}.bind(this)
}

Where does the 'ref.on' method come from? Is that something baked into React or is it a JavaScript function? I can't find it here https://facebook.github.io/react/docs/react-api.html or here https://developer.mozilla.org/en-US/docs/Web/JavaScript.  Also, there is 'ref.off' in another place in the React components.

componentWillUnmount () {
  ref.off()
}

EDIT:

It's helpful to know that it may be pseudocode. It's from this course https://learn.tylermcginnis.com/courses/50507/lectures/762618. But you have to login to view it. It's in the section on React Life Cycle Events.

I'm asking about the '.on' and '.off' parts, not the 'ref'.


问:
Splitting associative array into two arrays with javascript
I have an array of clubs

```<code>var clubs =[{
    team: {name: "fcb barca", rank: 4},
    team: {name: "man utd", rank: 16},
    team: {name: "man city", rank: 36},
    team: {name: "fcb liverpool", rank: 57}
}];
</code>```

which I need to split into two arrays, so the expected result would be

```<code>  teams["fcb barca", "man utd" , "man city", "fcb liverpool"];
  rank[4,16,36,57];
</code>```

I've tried the following code but doesn't seem to work

```<code>var team = [];
 var rank = [];
 for(var i = 0; i < clubs.length; i++){
   var tempArray1 = teams{{name: clubs[i].name, grade: clubs[i].rank}};
   var tempArray2 = teams{name: clubs[i].name, grade: clubs[i].rank};
   team.push( tempArray1 );
   rank.push( tempArray2 );
 };

console.log(team);
console.log(rank);
</code>```

答:
Im going to hate myself for doing this in five minutes.
But first of all, you code isn't close to valid at all at this moment.

Lets assess what's wrong here:

```<code>clubs[{
    team{name: "fcb barca", rank: 4}
    team{name: "man utd", rank: 16}
    team{name: "man city", rank: 36}
    team{name: "fcb liverpool", rank: 57}
}];
</code>```

First off, clubs is missing a variable declaration like:

```<code>var clubs = [
</code>```

Secondly, you are declaring clubs as an array with [ however, your array is only containing one object, since you are following it with {

After this point, there are multiple issues. First one:

```<code>team{
</code>```

is not a valid javascript object. However team : { would be.
Now to the next issue, you have several objects following each other without a comma separation:

```<code>team : {name: "fcb barca", rank: 4}
team : {name: "man utd", rank: 16}
</code>```

Which should look like:

```<code>team : {name: "fcb barca", rank: 4},
team : {name: "man utd", rank: 16}
</code>```

This again however, if put correct would look like:

```<code>var clubs = [{
    team : {name: "fcb barca", rank: 4},
    team : {name: "man utd", rank: 16}
}];
</code>```

Now we have another issue. You have one array, clubs which contains one object, which has several keys with the same name team

Thats just not gonna work.

Your code should look like this:

```<code>let clubs = [
    {name: "fcb barca", rank: 4},
    {name: "man utd", rank: 16},
    {name: "man city", rank: 36},
    {name: "fcb liverpool", rank: 57}
];
</code>```

OR, if you want the to be objects of teams

```<code>let clubs = [
    { team: {name: "fcb barca", rank: 4} },
    { team: {name: "man utd", rank: 16} },
    { team: {name: "man city", rank: 36} },
    { team: {name: "fcb liverpool", rank: 57} }
];
</code>```

Then, when you're syntax is correct, you could loop it like this:

```<code>let teams = [];
let ranks = [];

clubs.forEach(function(club){
    teams.push(club.name);
    ranks.push(club.rank);
});
console.log(teams);
console.log(ranks);
</code>```

Body:
I have an array of clubs

var clubs =[{
    team: {name: "fcb barca", rank: 4},
    team: {name: "man utd", rank: 16},
    team: {name: "man city", rank: 36},
    team: {name: "fcb liverpool", rank: 57}
}];

which I need to split into two arrays, so the expected result would be

  teams["fcb barca", "man utd" , "man city", "fcb liverpool"];
  rank[4,16,36,57];

I've tried the following code but doesn't seem to work

var team = [];
 var rank = [];
 for(var i = 0; i < clubs.length; i++){
   var tempArray1 = teams{{name: clubs[i].name, grade: clubs[i].rank}};
   var tempArray2 = teams{name: clubs[i].name, grade: clubs[i].rank};
   team.push( tempArray1 );
   rank.push( tempArray2 );
 };

console.log(team);
console.log(rank);

Body:
Im going to hate myself for doing this in five minutes.
But first of all, you code isn't close to valid at all at this moment.

Lets assess what's wrong here:

clubs[{
    team{name: "fcb barca", rank: 4}
    team{name: "man utd", rank: 16}
    team{name: "man city", rank: 36}
    team{name: "fcb liverpool", rank: 57}
}];

First off, clubs is missing a variable declaration like:

var clubs = [

Secondly, you are declaring clubs as an array with [ however, your array is only containing one object, since you are following it with {

After this point, there are multiple issues. First one:

team{

is not a valid javascript object. However team : { would be.
Now to the next issue, you have several objects following each other without a comma separation:

team : {name: "fcb barca", rank: 4}
team : {name: "man utd", rank: 16}

Which should look like:

team : {name: "fcb barca", rank: 4},
team : {name: "man utd", rank: 16}

This again however, if put correct would look like:

var clubs = [{
    team : {name: "fcb barca", rank: 4},
    team : {name: "man utd", rank: 16}
}];

Now we have another issue. You have one array, clubs which contains one object, which has several keys with the same name team

Thats just not gonna work.

Your code should look like this:

let clubs = [
    {name: "fcb barca", rank: 4},
    {name: "man utd", rank: 16},
    {name: "man city", rank: 36},
    {name: "fcb liverpool", rank: 57}
];

OR, if you want the to be objects of teams

let clubs = [
    { team: {name: "fcb barca", rank: 4} },
    { team: {name: "man utd", rank: 16} },
    { team: {name: "man city", rank: 36} },
    { team: {name: "fcb liverpool", rank: 57} }
];

Then, when you're syntax is correct, you could loop it like this:

let teams = [];
let ranks = [];

clubs.forEach(function(club){
    teams.push(club.name);
    ranks.push(club.rank);
});
console.log(teams);
console.log(ranks);


问:
Parsing #regions within Code Files
I'm trying to create a C# program that extracts the code contained within #region tags in *.cs files.  I more or less just want to be able to anotate the code I'm working on and have it be accessible to this other program as just text.

Is there something that already exists that accomplishes this?

Say I have code like this:

```<code>#region ClassName.Test()
public static void Test()
{
     //Some method that does stuff
}
#endregion
</code>```

I'd like to be able to extract

```<code>public static void Test()
{
     //Some method that does stuff
}
</code>```

from the *.cs as a string when I specify that I'm looking for Class.Test().

答:
Lets say we have the whole code in a string classcode

we can do this

string[] regions =Regex.Split("#region",classcode);

now the region string array will consist of your region codes which you can access as you access arrays.

you will have to remove the region name and #endregion from the individual strings in array which is not so troublesome

Title: Parsing #regions within Code Files

Body:
I'm trying to create a C# program that extracts the code contained within #region tags in *.cs files.  I more or less just want to be able to anotate the code I'm working on and have it be accessible to this other program as just text.

Is there something that already exists that accomplishes this?

Say I have code like this:

#region ClassName.Test()
public static void Test()
{
     //Some method that does stuff
}
#endregion

I'd like to be able to extract

public static void Test()
{
     //Some method that does stuff
}

from the *.cs as a string when I specify that I'm looking for Class.Test().


问:
MySQL precision DECIMAL(13,9) for longitude
I am trying to update a row in the MySQL table, the data of the column is -122.333351900 and it already exists, so there is no problem on its length not matching the data type and its length.

But when I run a UPDATE sql command it fails with

```<code>ERROR 1264 (22003): Out of range value for column 'longitude' at row 1
</code>```

I don't understand why its wrong? It already has inserted this value and now when I run an UPDATE command it fails with an error!

答:
Check your table if it has a trigger on it. A trigger runs right before or after the update/insert on a table.

If it contains an error it looks like the update is going wrong when actually a related trigger fails.

Body:
I am trying to update a row in the MySQL table, the data of the column is -122.333351900 and it already exists, so there is no problem on its length not matching the data type and its length.

But when I run a UPDATE sql command it fails with

ERROR 1264 (22003): Out of range value for column 'longitude' at row 1

I don't understand why its wrong? It already has inserted this value and now when I run an UPDATE command it fails with an error!


问:
What is wrong with this attempt to get a JSON value?
I'm trying to get the Json value and put it in a label, the syntax seems to be correct, but there sure is something wrong with the code, the value simply doesn't display on the Label. What can it be?

NOTE: I have already added the Newstonsoft JSON reference and the timer is 5 seconds and is activated after the form is loaded.

```<code>Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick

    Dim json = New IO.StreamReader(DirectCast(DirectCast(Net.WebRequest.Create("https://www.bitstamp.net/api/ticker/"), Net.HttpWebRequest).GetResponse, Net.HttpWebResponse).GetResponseStream)
    Dim rq As Newtonsoft.Json.Linq.JToken = Newtonsoft.Json.Linq.JObject.Parse(json.ReadToEnd)

    BitCoinPrice = $"{rq.SelectToken("last")}"

    Label1.Text = BitCoinPrice

End Sub
</code>```

答:
I was inattentive but realized that I put the code to activate the Timer1 in the wrong place, instead of putting it when the form loads, it was in when WebBrowser1 loads.

Wrong

```<code>Private Sub WebBrowser1_DocumentCompleted(sender As Object, e As WebBrowserDocumentCompletedEventArgs) Handles WebBrowser1.DocumentCompleted

Timer1.Enabled = True 'Wrong Place

End Sub
</code>```

Correct

```<code>Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load

Timer1.Enabled = True 'Correct Place

End Sub
</code>```

Sorry for the inconvenience and thanks for the help.

Body:
I'm trying to get the Json value and put it in a label, the syntax seems to be correct, but there sure is something wrong with the code, the value simply doesn't display on the Label. What can it be?

NOTE: I have already added the Newstonsoft JSON reference and the timer is 5 seconds and is activated after the form is loaded.

Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick

    Dim json = New IO.StreamReader(DirectCast(DirectCast(Net.WebRequest.Create("https://www.bitstamp.net/api/ticker/"), Net.HttpWebRequest).GetResponse, Net.HttpWebResponse).GetResponseStream)
    Dim rq As Newtonsoft.Json.Linq.JToken = Newtonsoft.Json.Linq.JObject.Parse(json.ReadToEnd)

    BitCoinPrice = $"{rq.SelectToken("last")}"

    Label1.Text = BitCoinPrice

End Sub

Body:
I was inattentive but realized that I put the code to activate the Timer1 in the wrong place, instead of putting it when the form loads, it was in when WebBrowser1 loads.

Wrong

Private Sub WebBrowser1_DocumentCompleted(sender As Object, e As WebBrowserDocumentCompletedEventArgs) Handles WebBrowser1.DocumentCompleted

Timer1.Enabled = True 'Wrong Place

End Sub

Correct

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load

Timer1.Enabled = True 'Correct Place

End Sub

Sorry for the inconvenience and thanks for the help.


问:
chromium lldb debug not show string

I am debuging chromium in xcode,

and config the ../chromium/src/third_party/WebKit/Tool/lldb/lldb_webkit.py in ~/.lldinit file，

but it not show the string correct, it only show the length of the string,can not show the content,

so it is inconvenient for debuging, I can not see the content of the string, this problem show in the picture.

in the picture1, picture2

I hope the content is not empty, and show the string content currect, or is there a good way to show the content of string correct

答:
The summary formatter code doesn't look right to me.  It does:

```<code>def WTFStringImpl_SummaryProvider(valobj, dict):
    provider = WTFStringImplProvider(valobj, dict)
    return "{ length = %d, is8bit = %d, contents = '%s' }" % (provider.get_length(), provider.is_8bit(), provider.to_string())
</code>```

where the WTFStringImplProvider.is8_bit is:

```<code>def is_8bit(self):
    return self.valobj.GetChildMemberWithName('is8_bit_')
</code>```

That is returning an SBValue, not an integer, so printing it with a %d format doesn't seem like the right thing to do.

Title: chromium lldb debug not show string

Body:
The summary formatter code doesn't look right to me.  It does:

def WTFStringImpl_SummaryProvider(valobj, dict):
    provider = WTFStringImplProvider(valobj, dict)
    return "{ length = %d, is8bit = %d, contents = '%s' }" % (provider.get_length(), provider.is_8bit(), provider.to_string())

where the WTFStringImplProvider.is8_bit is:

def is_8bit(self):
    return self.valobj.GetChildMemberWithName('is8_bit_')

That is returning an SBValue, not an integer, so printing it with a %d format doesn't seem like the right thing to do.


问:
Do I really need Foreign key when using Pivot table?
let's say, I have a simple database with 3 tables = posts, categories and post_category (which is pivot table).

posts - ID | title | body | created_at/updated_at

categories - ID | name | created_at/updated_at

post_category - post_id | category_id

The primary key is an ID, but I have not specified a foreign key (in posts). Should I specify the foreign key (category_id) as a column in my posts table, or is it okay to use pivot table (post_category) where I already specified the relationship between those 2 tables?

Thanks in advance!

答:
SQL does not require foreign keys to be explicitly declared, particularly with respect to querying tables.  Foreign keys enforce relational integrity.  That is, they ensure that tables that should refer to each other actually do refer to each other.

That said, MySQL differs from most databases by actually doing something with a foreign key declaration: MySQL builds a secondary index.  This index can be quite handy for queries by improving performance.

However, nothing is required about a foreign key relationship.