问:
Unable to bind jQuery DataTable in AJAX call with JSON data
I'm trying to bind jQuery DataTable by calling mvc action method using AJAX call and trying to populate the table using JSON data but it gets stuck on loading. Am I missing something?

Also, how can I implement server side Paging, Searching and Sorting in jQuery DataTable.

```<code>function initDataTable(ClientId)
    {
        var assetListVM;
        $(function () {
            assetListVM = {
                dt: null,

                init: function () {
                    var ClientId = $('#ddlClient').val();
                    dt = $('#records-data-table').dataTable({
                        "serverSide": true,
                        "processing": true,
                        "ajax": {
                            "type": "POST",
                            "dataType": "json",
                            "url": "@Url.Action("GetProcessingData", "Processing")?clientId=" + ClientId,
                            "success": function (data) {
                                alert(data);
                                console.log(data);

                            },
                            "error": function(){
                                alert("Error");
                            }

                    },
                        "columns": [
                            { "title": "Co Num",
                            "data": "CompanyNo",
                                "searchable": true },
                            { "title": "Cycle Date",
                            "data": "CycleDate",
                                "searchable": true },
                            { "title": "Policy Number",
                            "data": "PolicyNo",
                                "searchable": true },
                            { "title": "Issue Date",
                            "data": "IssueDate",
                                "searchable": true },
                            { "title": "Transaction Date",
                            "data": "TransactionDate"
                            },
                            { "title": "Transaction Amt",
                            "data": "TransactionAmount"
                            },
                            { "title": "Item Code",
                            "data": "ItemCode"
                            },
                                { "title": "Account",
                                "data": "Account"
                                },
                                { "title": "Owner Name",
                                "data": "OwnerName"
                                }

                        ],
                        "lengthMenu": [[10, 25, 50, 100], [10, 25, 50, 100]],
                        });
        }
        }

    // initialize the datatables
    assetListVM.init();
    });
    }
</code>```

Below is my action method:

```<code>public ActionResult GetProcessingData(int clientId)
    {
        ClientSummary ClientSUM = new ClientSummary();
        List<PolicyDownload> LstPData = new List<PolicyDownload>();
        DataTable dtProcessingData = new DataTable();
        try
        {
            using (DLpolicyDownload objDLpolicyDownload = new DLpolicyDownload())
            {
                dtProcessingData = objDLpolicyDownload.GetProcessingRecordDetails(clientId);
                if (dtProcessingData != null)
                {
                    foreach (DataRow dr in dtProcessingData.Rows)
                    {
                        PolicyDownload pData = new PolicyDownload();
                        pData.CompanyNo = Convert.ToInt32(dr["CO_NUM"]);
                        pData.CycleDate = Convert.ToString(dr["CYCLE_DATE"]);
                        pData.PolicyNo = Convert.ToString(dr["POLICY_NUMBER"]);
                        pData.IssueDate = Convert.ToString(dr["ISSUE_DATE"]);
                        pData.TransactionDate = Convert.ToString(dr["TRANSACTION_DATE"]);
                        pData.TransactionAmount = Convert.ToDouble(dr["TRANSACTION_AMOUNT"]);
                        pData.ItemCode = Convert.ToInt32(dr["ITEM_CODE"]);
                        pData.Account = Convert.ToString(dr["ACCOUNT"]);
                        pData.OwnerName = Convert.ToString(dr["OWNER_NAME"]);
                        LstPData.Add(pData);
                    }
                }
            }
        }
        catch (Exception ex)
        {
            if (logChoice)
            {
                log.Error(ex.Message, ex);
            }
        }
        var data = from s in LstPData
                   select s;
        return Json(new { data = data }, JsonRequestBehavior.AllowGet);
    }
</code>```

Below is the JSON output of this action method:

```<code>{"data":[{"PolicyDownloadID":0,"ImportDate":null,"CycleDate":"10/23/2017","CompanyID":0,"CompanyNo":40,"PolicyNo":"L0000001","PlanCode":null,"InsuranceType":null,"IssueDate":"05/02/2011","TransactionDate":"08/03/2017","TransactionAmount":7545.59,"ItemCode":0,"Account":"SBEN","Mode":null,"ModeAmount":0,"PayerName":null,"OwnerName":"CERNY, RAYMOND C","InsuredName":null,"PayeeName":null,"JointOwner":null,"SBC":0,"SBCAmount":0,"IsActive":false,"CreatedOn":"\/Date(-62135575200000)\/"},{"PolicyDownloadID":0,"ImportDate":null,"CycleDate":"10/23/2017","CompanyID":0,"CompanyNo":6,"PolicyNo":"FGL01234","PlanCode":null,"InsuranceType":null,"IssueDate":"07/23/2010","TransactionDate":"08/02/2017","TransactionAmount":26999.62,"ItemCode":0,"Account":"SBEN","Mode":null,"ModeAmount":0,"PayerName":null,"OwnerName":"BURNHAM, STEVEN L","InsuredName":null,"PayeeName":null,"JointOwner":null,"SBC":0,"SBCAmount":0,"IsActive":false,"CreatedOn":"\/Date(-62135575200000)\/"}]}
</code>```

Below is the screenshot where it stuck:

It is calling my action method but unable to bind the JSON data.

答:
success function - Must not be overridden as it is used internally in DataTables.
So remove success function and try once, hope it will help you.</p>

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to bind jQuery DataTable by calling mvc action method using AJAX call and trying to populate the table using JSON data but it gets stuck on loading. Am I missing something?

Also, how can I implement server side Paging, Searching and Sorting in jQuery DataTable.

function initDataTable(ClientId)
    {
        var assetListVM;
        $(function () {
            assetListVM = {
                dt: null,

                init: function () {
                    var ClientId = $('#ddlClient').val();
                    dt = $('#records-data-table').dataTable({
                        "serverSide": true,
                        "processing": true,
                        "ajax": {
                            "type": "POST",
                            "dataType": "json",
                            "url": "@Url.Action("GetProcessingData", "Processing")?clientId=" + ClientId,
                            "success": function (data) {
                                alert(data);
                                console.log(data);

                            },
                            "error": function(){
                                alert("Error");
                            }

                    },
                        "columns": [
                            { "title": "Co Num",
                            "data": "CompanyNo",
                                "searchable": true },
                            { "title": "Cycle Date",
                            "data": "CycleDate",
                                "searchable": true },
                            { "title": "Policy Number",
                            "data": "PolicyNo",
                                "searchable": true },
                            { "title": "Issue Date",
                            "data": "IssueDate",
                                "searchable": true },
                            { "title": "Transaction Date",
                            "data": "TransactionDate"
                            },
                            { "title": "Transaction Amt",
                            "data": "TransactionAmount"
                            },
                            { "title": "Item Code",
                            "data": "ItemCode"
                            },
                                { "title": "Account",
                                "data": "Account"
                                },
                                { "title": "Owner Name",
                                "data": "OwnerName"
                                }

                        ],
                        "lengthMenu": [[10, 25, 50, 100], [10, 25, 50, 100]],
                        });
        }
        }

    // initialize the datatables
    assetListVM.init();
    });
    }

Below is my action method:

public ActionResult GetProcessingData(int clientId)
    {
        ClientSummary ClientSUM = new ClientSummary();
        List<PolicyDownload> LstPData = new List<PolicyDownload>();
        DataTable dtProcessingData = new DataTable();
        try
        {
            using (DLpolicyDownload objDLpolicyDownload = new DLpolicyDownload())
            {
                dtProcessingData = objDLpolicyDownload.GetProcessingRecordDetails(clientId);
                if (dtProcessingData != null)
                {
                    foreach (DataRow dr in dtProcessingData.Rows)
                    {
                        PolicyDownload pData = new PolicyDownload();
                        pData.CompanyNo = Convert.ToInt32(dr["CO_NUM"]);
                        pData.CycleDate = Convert.ToString(dr["CYCLE_DATE"]);
                        pData.PolicyNo = Convert.ToString(dr["POLICY_NUMBER"]);
                        pData.IssueDate = Convert.ToString(dr["ISSUE_DATE"]);
                        pData.TransactionDate = Convert.ToString(dr["TRANSACTION_DATE"]);
                        pData.TransactionAmount = Convert.ToDouble(dr["TRANSACTION_AMOUNT"]);
                        pData.ItemCode = Convert.ToInt32(dr["ITEM_CODE"]);
                        pData.Account = Convert.ToString(dr["ACCOUNT"]);
                        pData.OwnerName = Convert.ToString(dr["OWNER_NAME"]);
                        LstPData.Add(pData);
                    }
                }
            }
        }
        catch (Exception ex)
        {
            if (logChoice)
            {
                log.Error(ex.Message, ex);
            }
        }
        var data = from s in LstPData
                   select s;
        return Json(new { data = data }, JsonRequestBehavior.AllowGet);
    }

Below is the JSON output of this action method:

{"data":[{"PolicyDownloadID":0,"ImportDate":null,"CycleDate":"10/23/2017","CompanyID":0,"CompanyNo":40,"PolicyNo":"L0000001","PlanCode":null,"InsuranceType":null,"IssueDate":"05/02/2011","TransactionDate":"08/03/2017","TransactionAmount":7545.59,"ItemCode":0,"Account":"SBEN","Mode":null,"ModeAmount":0,"PayerName":null,"OwnerName":"CERNY, RAYMOND C","InsuredName":null,"PayeeName":null,"JointOwner":null,"SBC":0,"SBCAmount":0,"IsActive":false,"CreatedOn":"\/Date(-62135575200000)\/"},{"PolicyDownloadID":0,"ImportDate":null,"CycleDate":"10/23/2017","CompanyID":0,"CompanyNo":6,"PolicyNo":"FGL01234","PlanCode":null,"InsuranceType":null,"IssueDate":"07/23/2010","TransactionDate":"08/02/2017","TransactionAmount":26999.62,"ItemCode":0,"Account":"SBEN","Mode":null,"ModeAmount":0,"PayerName":null,"OwnerName":"BURNHAM, STEVEN L","InsuredName":null,"PayeeName":null,"JointOwner":null,"SBC":0,"SBCAmount":0,"IsActive":false,"CreatedOn":"\/Date(-62135575200000)\/"}]}

Below is the screenshot where it stuck:

It is calling my action method but unable to bind the JSON data.


来源: stackexchange

问:
How to register the DBAL Doctrine connection as a service without the DoctrineBundle in Symfony 4

I'm trying to register only the Doctrine DBAL Connection component as a service in Symfony4.

I don't need the full DoctrineBundle symfony offers, but only the part which provides a basic database abstraction level.

Now I'm stuck on figuring out how to implement the raw library downloaded by composer as a service.

This is how the Connection class should be created, as from the official documentation:

```<code><?php
$config = new \Doctrine\DBAL\Configuration();
//..
$connectionParams = array(
    'dbname' => 'mydb',
    'user' => 'user',
    'password' => 'secret',
    'host' => 'localhost',
    'driver' => 'pdo_mysql',
);
$conn = \Doctrine\DBAL\DriverManager::getConnection($connectionParams, $config);
</code>```

If it is possible, how do I configure this type of service in the service.yml configuration?

If it is not, how do I proceed then?

答:
You might be better off just using the doctrine bundle and removing the orm section from the config file.  Does not really add much overhead and is easier that doing it yourself.

Having said that, here are the details for a minimal dbal setup

```<code>composer create symfony/skeleton s40dbal
cd s40dbal
composer require server
composer require doctrine/dbal

# .env
DB_URL=mysql://user:password@localhost/dbname

# config/services.yaml
Doctrine\DBAL\Configuration:

Doctrine\DBAL\Connection:
    factory: 'Doctrine\DBAL\DriverManager::getConnection'
    arguments:
        -
            url : '%env(DB_URL)%'
            driverOptions: {20: false} # emulate prepared statements
        - '@Doctrine\DBAL\Configuration'

# DefaultController.php
use Doctrine\DBAL\Connection;
class DefaultController
{
    public function index(Connection $conn)
    {
        $stmt = $conn->prepare('SELECT id,name FROM users WHERE username = ?');
        $stmt->execute(['someuser']);
        $row = $stmt->fetch();
        var_dump($row);

        return new Response('dbal');
    }
}
</code>```

Enjoy

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to register only the Doctrine DBAL Connection component as a service in Symfony4.

I don't need the full DoctrineBundle symfony offers, but only the part which provides a basic database abstraction level.

Now I'm stuck on figuring out how to implement the raw library downloaded by composer as a service.

This is how the Connection class should be created, as from the official documentation:

<?php
$config = new \Doctrine\DBAL\Configuration();
//..
$connectionParams = array(
    'dbname' => 'mydb',
    'user' => 'user',
    'password' => 'secret',
    'host' => 'localhost',
    'driver' => 'pdo_mysql',
);
$conn = \Doctrine\DBAL\DriverManager::getConnection($connectionParams, $config);

If it is possible, how do I configure this type of service in the service.yml configuration?

If it is not, how do I proceed then?

Body:
You might be better off just using the doctrine bundle and removing the orm section from the config file.  Does not really add much overhead and is easier that doing it yourself.

Having said that, here are the details for a minimal dbal setup

composer create symfony/skeleton s40dbal
cd s40dbal
composer require server
composer require doctrine/dbal

# .env
DB_URL=mysql://user:password@localhost/dbname

# config/services.yaml
Doctrine\DBAL\Configuration:

Doctrine\DBAL\Connection:
    factory: 'Doctrine\DBAL\DriverManager::getConnection'
    arguments:
        -
            url : '%env(DB_URL)%'
            driverOptions: {20: false} # emulate prepared statements
        - '@Doctrine\DBAL\Configuration'

# DefaultController.php
use Doctrine\DBAL\Connection;
class DefaultController
{
    public function index(Connection $conn)
    {
        $stmt = $conn->prepare('SELECT id,name FROM users WHERE username = ?');
        $stmt->execute(['someuser']);
        $row = $stmt->fetch();
        var_dump($row);

        return new Response('dbal');
    }
}

Enjoy


问:
How to allow hard coded strings and stop asking about using strings.xml
I'm working currently on an android project and I have no plans in mind whatsoever to translate it to other languages, so I'm not saving string literals in strings.xml. However Android Studio keeps complaining everytime I hard code a string literal especially when setting the text value for a TextView.

Is there a way to disable these warnings?

答:
Add

```<code>@SuppressLint("SetTextI18n")
</code>```

on top of your function(s).
Example:

```<code>@SuppressLint("SetTextI18n")
private void updateEZWBMode2ConnectionStatus(){
    switch (IsConnected.checkMode2(mContext)){
        case IsConnected.USB_TETHERING:
            M2StatusTV.setText("Status: Connected");
            M2StatusTV.setTextColor(Color.argb(255,0,255,0));
            M2ReceiveTV.setVisibility(View.VISIBLE);
            startTestReceiverSafe(M2ReceiveTV);
            break;
        case IsConnected.USB_CONNECTED:
            M2StatusTV.setText("Status: No Tethering");
            M2StatusTV.setTextColor(Color.argb(255,255,51,51));
            M1ReceiveTV.setVisibility(View.GONE);
            M2ReceiveTV.setVisibility(View.GONE);
            stopTestReceiverSafe();
            break;
        case IsConnected.USB_NOTHING:
            M2StatusTV.setText("Status: No USB Connection");
            M2StatusTV.setTextColor(Color.argb(255,255,51,51));
            M1ReceiveTV.setVisibility(View.GONE);
            M2ReceiveTV.setVisibility(View.GONE);
            stopTestReceiverSafe();
            break;
    }
}
</code>```

Body:
Add

@SuppressLint("SetTextI18n")

on top of your function(s).
Example:

@SuppressLint("SetTextI18n")
private void updateEZWBMode2ConnectionStatus(){
    switch (IsConnected.checkMode2(mContext)){
        case IsConnected.USB_TETHERING:
            M2StatusTV.setText("Status: Connected");
            M2StatusTV.setTextColor(Color.argb(255,0,255,0));
            M2ReceiveTV.setVisibility(View.VISIBLE);
            startTestReceiverSafe(M2ReceiveTV);
            break;
        case IsConnected.USB_CONNECTED:
            M2StatusTV.setText("Status: No Tethering");
            M2StatusTV.setTextColor(Color.argb(255,255,51,51));
            M1ReceiveTV.setVisibility(View.GONE);
            M2ReceiveTV.setVisibility(View.GONE);
            stopTestReceiverSafe();
            break;
        case IsConnected.USB_NOTHING:
            M2StatusTV.setText("Status: No USB Connection");
            M2StatusTV.setTextColor(Color.argb(255,255,51,51));
            M1ReceiveTV.setVisibility(View.GONE);
            M2ReceiveTV.setVisibility(View.GONE);
            stopTestReceiverSafe();
            break;
    }
}


问:
Changing CSS attribute with JQuery
Today I was shown a really simple way to change the font-size  of an element using jQuery.
It looked very similar to the following:

```<code><script  type="text/javascript">
    jQuery(document.body) ({font-size:5em;});
</script>
</code>```

This obviously doesn't work, but I was wondering what's missing? I remember it being just one line of code.

Note: I have tried jQuery(document.body).css({font-size:5em;}); as well, without success.

Thanks.

答:
```<code>$('body').css('font-size', '5em');
</code>```

Should work.

ContentLicense: CC BY-SA 2.5

Title: Changing CSS attribute with JQuery

Body:
Today I was shown a really simple way to change the font-size  of an element using jQuery.
It looked very similar to the following:

This obviously doesn't work, but I was wondering what's missing? I remember it being just one line of code.

Note: I have tried jQuery(document.body).css({font-size:5em;}); as well, without success.

Thanks.

Body:
$('body').css('font-size', '5em');

Should work.


问:
Why do you skip void function calls without catching them?

I want to call a function that calculates the width of a circle.

```<code>#include <stdio.h>
void area(double*);
int main()
{
    void* vp = NULL;
    double r;
    printf("input value : ");
    scanf(" %lf", &r);
    (double*)vp = &r;
    void area(vp);
}
void area(double* dp)
{
    double result;
    result = (*dp) * (*dp) * (3.14);
    printf("circle are is : %.2lf", result);
    return 1;
}*
</code>```

I want to call a function in the //void area (vp)//, but I can not catch the error in visual stdio and proceed as it is. Do you know what the cause is?

答:
To call the function, you write area(vp); not void area(vp);.

The latter, as it appears in the function main, is a function prototype and has no run-time effect.

And fix that definition of PI: yours is terribly inadequate given that you use a double type. See Math constant PI value in C

Body:
I want to call a function that calculates the width of a circle.

#include <stdio.h>
void area(double*);
int main()
{
    void* vp = NULL;
    double r;
    printf("input value : ");
    scanf(" %lf", &r);
    (double*)vp = &r;
    void area(vp);
}
void area(double* dp)
{
    double result;
    result = (*dp) * (*dp) * (3.14);
    printf("circle are is : %.2lf", result);
    return 1;
}*

I want to call a function in the //void area (vp)//, but I can not catch the error in visual stdio and proceed as it is. Do you know what the cause is?


问:
Reference path for service account key
I am referring to the next article what is "serviceAccountKey.json" referring to in the Firebase device-to-device notifications tutorial

There is one statement written in the index.js file

```<code>var serviceAccount = require("path/to/serviceAccountKey.json");
</code>```

I would like to know what would be the path here when writing the script in the google cloud function web interface.

Do I have to upload the json file on a bucket and then give the bucket reference path?

答:
You should put your serviceAccountKey.json in the same folder as your index.json. Then when you deploy to Cloud Functions, both the code and the key file will be uploaded and you can refer to the JSON from the code with:

```<code>var serviceAccount = require("./serviceAccountKey.json");
</code>```

Note that you may want to consider using the Admin SDK for Firebase Cloud Messaging to send messages these days. This SDK didn't exist when I wrote blog post, but makes the code for sending messages simpler (at the cost of using an extra SDK).

Title: Reference path for service account key

Body:
I am referring to the next article what is "serviceAccountKey.json" referring to in the Firebase device-to-device notifications tutorial

There is one statement written in the index.js file

var serviceAccount = require("path/to/serviceAccountKey.json");

I would like to know what would be the path here when writing the script in the google cloud function web interface.

Do I have to upload the json file on a bucket and then give the bucket reference path?

Body:
You should put your serviceAccountKey.json in the same folder as your index.json. Then when you deploy to Cloud Functions, both the code and the key file will be uploaded and you can refer to the JSON from the code with:

var serviceAccount = require("./serviceAccountKey.json");

Note that you may want to consider using the Admin SDK for Firebase Cloud Messaging to send messages these days. This SDK didn't exist when I wrote blog post, but makes the code for sending messages simpler (at the cost of using an extra SDK).


问:
PowerShell output different between remote (invoke-command) and local commands
I have looked though Stack Overflow for this question and haven't been able to find it. I also searched the internet with no luck so far. The answers I have found so far do not address the difference I am seeing in the same command being run from two different locations for the same server.  Maybe I am not using the correct search parameters.

My Problem:

PowerShell commands shows different output when using remote invoke-command as opposed to running the command locally. I have seen this on a couple occasions.

For this example, The server running the remote invoke command is running Windows Server 2012 with PS 4 version.

The server being tested is running Windows Server 2008 R2 with PS 2 version.

I log into both servers with the Domain Administrator login.

```<code>====
**Notice Version shows 1.0.0.0 when using remote command.

2012 v4:
</code>```

(I tried piping to format table, but same result)

```<code>invoke-command -computername mail1.dcloud.cisco.com -scriptblock {Get-host}

PSComputerName   : mail1.dcloud.cisco.com
RunspaceId       : 6ccceb7b-5fa0-42b7-b78f-22b17116f4d3
Name             : ServerRemoteHost
Version          : 1.0.0.0
InstanceId       : 28263e00-11f9-4d78-98c2-f789659b23c8
UI               : System.Management.Automation.Internal.Host.InternalHostUserInterface
CurrentCulture   : en-US
CurrentUICulture : en-US
PrivateData      :

===========
** Notice version is 2.0 when run locally on server.

2008 R2 v2

PS C:\> $env:ComputerName
MAIL1

PS C:\> get-host

Name             : ConsoleHost
Version          : 2.0
InstanceId       : d4cf14b5-5925-4fb5-9307-eaf8cbcd11f5
UI               : System.Management.Automation.Internal.Host.InternalHostUserInterface
CurrentCulture   : en-US
CurrentUICulture : en-US
PrivateData      : Microsoft.PowerShell.ConsoleHost+ConsoleColorProxy
IsRunspacePushed : False
Runspace         : System.Management.Automation.Runspaces.LocalRunspace
</code>```

12/2/17 13:25 EDT - EDIT:
If I change my command to enter-pssession, I get the info that I believe to be correct.

```<code>PS C:\python> enter-pssession mail1
Get-host

Name             : Windows PowerShell ISE Host
Version          : 4.0
InstanceId       : 7e3f6039-3b63-4c8e-af49-bc748c07ed7e
UI               :System.Management.Automation.Internal.Host.InternalHostUserInterface
CurrentCulture   : en-US
CurrentUICulture : en-US
PrivateData      : Microsoft.PowerShell.Host.ISE.ISEOptions
IsRunspacePushed : True
Runspace         : System.Management.Automation.RemoteRunspace

[mail1]: PS C:\Users\Administrator.DCLOUD\Documents> exit-pssession
</code>```

Still have not found out why Invoke-Command gives a different output for the command Get-Host.

答:
Get-Host returns the details of the current host. If you are in PowerShell console, it returns the version of the console host. If you are in a remote session it returns the version of the remote host(not the PS version in remote server).

Note: Host version and PowerShell version aren't same.

even ISE is a different host for powershell

Body:
I have looked though Stack Overflow for this question and haven't been able to find it. I also searched the internet with no luck so far. The answers I have found so far do not address the difference I am seeing in the same command being run from two different locations for the same server.  Maybe I am not using the correct search parameters.

My Problem:

PowerShell commands shows different output when using remote invoke-command as opposed to running the command locally. I have seen this on a couple occasions.

For this example, The server running the remote invoke command is running Windows Server 2012 with PS 4 version.

The server being tested is running Windows Server 2008 R2 with PS 2 version.

I log into both servers with the Domain Administrator login.

====
**Notice Version shows 1.0.0.0 when using remote command.

2012 v4:

(I tried piping to format table, but same result)

invoke-command -computername mail1.dcloud.cisco.com -scriptblock {Get-host}

PSComputerName   : mail1.dcloud.cisco.com
RunspaceId       : 6ccceb7b-5fa0-42b7-b78f-22b17116f4d3
Name             : ServerRemoteHost
Version          : 1.0.0.0
InstanceId       : 28263e00-11f9-4d78-98c2-f789659b23c8
UI               : System.Management.Automation.Internal.Host.InternalHostUserInterface
CurrentCulture   : en-US
CurrentUICulture : en-US
PrivateData      :

===========
** Notice version is 2.0 when run locally on server.

2008 R2 v2

PS C:\> $env:ComputerName
MAIL1

PS C:\> get-host

Name             : ConsoleHost
Version          : 2.0
InstanceId       : d4cf14b5-5925-4fb5-9307-eaf8cbcd11f5
UI               : System.Management.Automation.Internal.Host.InternalHostUserInterface
CurrentCulture   : en-US
CurrentUICulture : en-US
PrivateData      : Microsoft.PowerShell.ConsoleHost+ConsoleColorProxy
IsRunspacePushed : False
Runspace         : System.Management.Automation.Runspaces.LocalRunspace

12/2/17 13:25 EDT - EDIT:
If I change my command to enter-pssession, I get the info that I believe to be correct.

PS C:\python> enter-pssession mail1
Get-host

Name             : Windows PowerShell ISE Host
Version          : 4.0
InstanceId       : 7e3f6039-3b63-4c8e-af49-bc748c07ed7e
UI               :System.Management.Automation.Internal.Host.InternalHostUserInterface
CurrentCulture   : en-US
CurrentUICulture : en-US
PrivateData      : Microsoft.PowerShell.Host.ISE.ISEOptions
IsRunspacePushed : True
Runspace         : System.Management.Automation.RemoteRunspace

[mail1]: PS C:\Users\Administrator.DCLOUD\Documents> exit-pssession

Still have not found out why Invoke-Command gives a different output for the command Get-Host.


答:
```<code><script>
$(document).ready(function() {
var data = '[{"Maxretail":...,"Itemname":"Youth Chameleon T-Shirt"]';
var table = '<table><thead><th>First Name</th><th>Last Name</th><th>Image</th><th>More</th></thead><tbody>';
var obj = $.parseJSON(data);
$.each(obj, function() {
    table += '<tr><td>' + this['Itemname'] + '</td><td>' + this['Supplieritemid'] + '</td><td><img src="https://cdn.distributorcentral.com/' + this['Imagepath'] + ' alt="' + this['Itemname'] + '" /></td><td><img src="https://cdn.distributorcentral.com/' + this['addlImagesSmall'] + ' alt="' + this['Itemname'] + '" />' + this['addlImagesSmall'] + '</td></tr>';
});
table += '</tbody></table>';
document.getElementById("datalist").innerHTML = table;
</code>```

<p>});
    </p>

Title: Make it pretty using php

Body:
<script>
$(document).ready(function() {
var data = '[{"Maxretail":...,"Itemname":"Youth Chameleon T-Shirt"]';
var table = '<table><thead><th>First Name</th><th>Last Name</th><th>Image</th><th>More</th></thead><tbody>';
var obj = $.parseJSON(data);
$.each(obj, function() {
    table += '<tr><td>' + this['Itemname'] + '</td><td>' + this['Supplieritemid'] + '</td><td><img src="https://cdn.distributorcentral.com/' + this['Imagepath'] + ' alt="' + this['Itemname'] + '" /></td><td><img src="https://cdn.distributorcentral.com/' + this['addlImagesSmall'] + ' alt="' + this['Itemname'] + '" />' + this['addlImagesSmall'] + '</td></tr>';
});
table += '</tbody></table>';
document.getElementById("datalist").innerHTML = table;

});


问:
Fatal error: Call to undefined function mb_strlen()
I'm trying to make a donation center which I use the source code from Totorialzine.

Everything works fine for me at this moment so far but the only problem I was struggling on and trying to look at for the whole day and can't figure what is actually wrong with the code exactly

here is what I get when I submit the comment on the page when my visitors donate.

```<code>Fatal error: Call to undefined function mb_strlen() in /home/yoursn0w/public_html/livetv/premium/thankyou.php on line 14
</code>```

and here is the code in the php file.

```<code><?php

require "config.php";
require "connect.php";

if(isset($_POST['submitform']) && isset($_POST['txn_id']))
{
    $_POST['nameField'] = esc($_POST['nameField']);
    $_POST['websiteField'] =  esc($_POST['websiteField']);
    $_POST['messageField'] = esc($_POST['messageField']);

    $error = array();

    if(mb_strlen($_POST['nameField'],"utf-8")<2)
    {
        $error[] = 'Please fill in a valid name.';
    }

    if(mb_strlen($_POST['messageField'],"utf-8")<2)
    {
        $error[] = 'Please fill in a longer message.';
    }

    if(!validateURL($_POST['websiteField']))
    {
        $error[] = 'The URL you entered is invalid.';
    }

    $errorString = '';
    if(count($error))
    {
        $errorString = join('<br />',$error);
    }
    else
    {
        mysql_query("   INSERT INTO dc_comments (transaction_id, name, url, message)
                        VALUES (
                            '".esc($_POST['txn_id'])."',
                            '".$_POST['nameField']."',
                            '".$_POST['websiteField']."',
                            '".$_POST['messageField']."'
                        )");

        if(mysql_affected_rows($link)==1)
        {
            $messageString = '<a href="donate.php">You were added to our donor list! »</a>';
        }
    }
}

?>
</code>```

I have my database in the phpMyAdmin uploaded completed

here is where I follow the instruction of the installation

http://tutorialzine.com/2010/05/donation-center-php-mysql-paypal-api/

答:
For me the following command did the trick</p>

```<code>sudo apt install php-mbstring
</code>```

Body:
I'm trying to make a donation center which I use the source code from Totorialzine.

Everything works fine for me at this moment so far but the only problem I was struggling on and trying to look at for the whole day and can't figure what is actually wrong with the code exactly

here is what I get when I submit the comment on the page when my visitors donate.

Fatal error: Call to undefined function mb_strlen() in /home/yoursn0w/public_html/livetv/premium/thankyou.php on line 14

and here is the code in the php file.

<?php

require "config.php";
require "connect.php";

if(isset($_POST['submitform']) && isset($_POST['txn_id']))
{
    $_POST['nameField'] = esc($_POST['nameField']);
    $_POST['websiteField'] =  esc($_POST['websiteField']);
    $_POST['messageField'] = esc($_POST['messageField']);

    $error = array();

    if(mb_strlen($_POST['nameField'],"utf-8")<2)
    {
        $error[] = 'Please fill in a valid name.';
    }

    if(mb_strlen($_POST['messageField'],"utf-8")<2)
    {
        $error[] = 'Please fill in a longer message.';
    }

    if(!validateURL($_POST['websiteField']))
    {
        $error[] = 'The URL you entered is invalid.';
    }

    $errorString = '';
    if(count($error))
    {
        $errorString = join('
',$error);
    }
    else
    {
        mysql_query("   INSERT INTO dc_comments (transaction_id, name, url, message)
                        VALUES (
                            '".esc($_POST['txn_id'])."',
                            '".$_POST['nameField']."',
                            '".$_POST['websiteField']."',
                            '".$_POST['messageField']."'
                        )");

        if(mysql_affected_rows($link)==1)
        {
            $messageString = 'You were added to our donor list! »';
        }
    }
}

?>

I have my database in the phpMyAdmin uploaded completed

here is where I follow the instruction of the installation

http://tutorialzine.com/2010/05/donation-center-php-mysql-paypal-api/

Body:
For me the following command did the trick

sudo apt install php-mbstring


问:
Convert XSLT 1.0 to 2.0
I need help converting an XSLT 1.0 file to 2.0 (so I can use the XSLT 2.0 replace() function call).

I've Googled, searched different books and SO with no success. I tried changing version="1.0" to 2.0 and changing html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en" to simply html but this all just results in XSLTProcessor errors.

Any help is greatly appreciated. Thanks in advance.

Here is my XSLT:

```<code><?xml version="1.0" encoding="ISO-8859-1" ?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns="http://www.w3.org/1999/xhtml" version="1.0">
<xsl:output method="xml" omit-xml-declaration="yes" indent="no"
        doctype-system="http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"
        doctype-public="-//W3C//DTD XHTML 1.0 Transitional//EN" encoding="ISO-8859-1" />
<xsl:template match="/">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<xsl:element name="meta">
<xsl:attribute name="name">description</xsl:attribute>
<xsl:attribute name="content"><xsl:value-of select="EventList/title"/></xsl:attribute>
</xsl:element>
<xsl:element name="link"><xsl:attribute name="rel">alternate</xsl:attribute><xsl:attribute name="type">application/rss+xml</xsl:attribute><xsl:attribute name="title">RSS</xsl:attribute><xsl:attribute name="href"><xsl:value-of select="EventList/rssURL"/></xsl:attribute></xsl:element>
</head>
<body>
 <xsl:apply-templates select="EventList" />
</body>
</html>
</xsl:template>
<xsl:template match="EventList">
 <xsl:choose>
  <xsl:when test="Event">
   <xsl:apply-templates select="Event"/>
  </xsl:when>
  <xsl:otherwise>
   <div class="eventItem">
    <div class="eventItemText">
     <p>There are currently no events posted for this category.</p>
    </div>
   </div>
  </xsl:otherwise>
 </xsl:choose>
</xsl:template>
<!-- List -->
<xsl:template match="Event">
 <li>
  <!-- Title -->
  <xsl:if test="eventStatus = 2"><xsl:value-of select="eventStatusString"/> - </xsl:if>
  <xsl:element name="a"><xsl:attribute name="href">http://events.stanford.edu/e/e/?d=<xsl:value-of select="replace(detailpath,'/events/','')"/></xsl:attribute><xsl:attribute name="id"><xsl:value-of select="eventID"/></xsl:attribute><xsl:attribute name="rel">external</xsl:attribute>
   <xsl:value-of select="title" disable-output-escaping="yes"/>
  </xsl:element>
  <!-- Date and time -->
  <xsl:element name="a"><xsl:attribute name="href">http://events.stanford.edu/e/details.php?detailpath=<xsl:value-of select="detailpath"/></xsl:attribute><xsl:attribute name="rel">external</xsl:attribute>
   <xsl:choose>
    <xsl:when test="repeatRuleID > 0">
     Ongoing <xsl:value-of select="repeatRuleText"/> from <xsl:value-of select="beginDate"/> through <xsl:value-of select="repeatUntilDate"/>.
     <xsl:if test="repeatRuleID=99">See details for exact dates and times.</xsl:if>
    </xsl:when>
    <xsl:otherwise>
     <xsl:if test="string(beginDay)"><xsl:value-of select="beginDay"/>, </xsl:if>
     <xsl:value-of select="beginDate"/>.
    </xsl:otherwise>
   </xsl:choose>
   <xsl:if test="repeatRuleID!=99">
    <xsl:if test="string(beginTime)">
     <xsl:text disable-output-escaping="yes"></xsl:text><xsl:value-of select="beginTime"/>.
    </xsl:if>
   </xsl:if>
  </xsl:element>
  <!-- Location -->
  <xsl:element name="a"><xsl:attribute name="href">http://events.stanford.edu/e/details.php?detailpath=<xsl:value-of select="detailpath"/></xsl:attribute><xsl:attribute name="rel">external</xsl:attribute>
   <xsl:value-of select="locationText"/>
  </xsl:element>
 </li>
</xsl:template>
</xsl:stylesheet>
</code>```

答:
In addition to changing the version attribute to '2.0', you need to feed your XSLT 2.0 code to an XSLT 2.0 processor.

At present, some of the XSLT 2.0 processors I use are:

Saxon 9.x

XQSharp 2.0

AltovaXML (XMLSpy)

Do note that an existing XSLT 1.0 code may behave differently under XSLT 2.0 -- the most obvious differences are that <xsl:value-of> no longer produces the string value of only the first node from a node-set, and that in XSLT 2.0 the dreaded RTF type has been eliminated, so no xxx:node-set() extension function is needed/provided.

Title: Convert XSLT 1.0 to 2.0

Body:
I need help converting an XSLT 1.0 file to 2.0 (so I can use the XSLT 2.0 replace() function call).

I've Googled, searched different books and SO with no success. I tried changing version="1.0" to 2.0 and changing html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en" to simply html but this all just results in XSLTProcessor errors.

Any help is greatly appreciated. Thanks in advance.

Here is my XSLT:

<?xml version="1.0" encoding="ISO-8859-1" ?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns="http://www.w3.org/1999/xhtml" version="1.0">
<xsl:output method="xml" omit-xml-declaration="yes" indent="no"
        doctype-system="http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"
        doctype-public="-//W3C//DTD XHTML 1.0 Transitional//EN" encoding="ISO-8859-1" />
<xsl:template match="/">

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<xsl:element name="meta">
<xsl:attribute name="name">description</xsl:attribute>
<xsl:attribute name="content"><xsl:value-of select="EventList/title"/></xsl:attribute>
</xsl:element>
<xsl:element name="link"><xsl:attribute name="rel">alternate</xsl:attribute><xsl:attribute name="type">application/rss+xml</xsl:attribute><xsl:attribute name="title">RSS</xsl:attribute><xsl:attribute name="href"><xsl:value-of select="EventList/rssURL"/></xsl:attribute></xsl:element>

 <xsl:apply-templates select="EventList" />

</xsl:template>
<xsl:template match="EventList">
 <xsl:choose>
  <xsl:when test="Event">
   <xsl:apply-templates select="Event"/>
  </xsl:when>
  <xsl:otherwise>

There are currently no events posted for this category.

  </xsl:otherwise>
 </xsl:choose>
</xsl:template>

<xsl:template match="Event">

  <xsl:if test="eventStatus = 2"><xsl:value-of select="eventStatusString"/> - </xsl:if>
  <xsl:element name="a"><xsl:attribute name="href">http://events.stanford.edu/e/e/?d=<xsl:value-of select="replace(detailpath,'/events/','')"/></xsl:attribute><xsl:attribute name="id"><xsl:value-of select="eventID"/></xsl:attribute><xsl:attribute name="rel">external</xsl:attribute>
   <xsl:value-of select="title" disable-output-escaping="yes"/>
  </xsl:element>

  <xsl:element name="a"><xsl:attribute name="href">http://events.stanford.edu/e/details.php?detailpath=<xsl:value-of select="detailpath"/></xsl:attribute><xsl:attribute name="rel">external</xsl:attribute>
   <xsl:choose>
    <xsl:when test="repeatRuleID > 0">
     Ongoing <xsl:value-of select="repeatRuleText"/> from <xsl:value-of select="beginDate"/> through <xsl:value-of select="repeatUntilDate"/>.
     <xsl:if test="repeatRuleID=99">See details for exact dates and times.</xsl:if>
    </xsl:when>
    <xsl:otherwise>
     <xsl:if test="string(beginDay)"><xsl:value-of select="beginDay"/>, </xsl:if>
     <xsl:value-of select="beginDate"/>.
    </xsl:otherwise>
   </xsl:choose>
   <xsl:if test="repeatRuleID!=99">
    <xsl:if test="string(beginTime)">
     <xsl:text disable-output-escaping="yes"></xsl:text><xsl:value-of select="beginTime"/>.
    </xsl:if>
   </xsl:if>
  </xsl:element>

  <xsl:element name="a"><xsl:attribute name="href">http://events.stanford.edu/e/details.php?detailpath=<xsl:value-of select="detailpath"/></xsl:attribute><xsl:attribute name="rel">external</xsl:attribute>
   <xsl:value-of select="locationText"/>
  </xsl:element>

</xsl:template>
</xsl:stylesheet>


问:
How can I sort a Java list using two different values?
```<code>public void sortLeagueTable(List<LeagueTableItem> table) {
    Collections.sort(table, new Comparator<LeagueTableItem>(){
        public int compare(LeagueTableItem o1, LeagueTableItem o2){
            return o2.getPoints() - o1.getPoints();
        }
    });
}
</code>```

This code sorts two lists based on the value of the object called points. After I sort it based on the value point I want to sort it again based on the value goalScored. So, if the points of two teams are equal, I want to sort it again based on the goalScored value.

How can I do that?

答:
Just add another condition to your comparator:</p>

```<code>public int compare(LeagueTableItem o1, LeagueTableItem o2){
     int diff = o2.getPoints() - o1.getPoints();
     if (diff == 0) {
        diff = o2.goalScored() - o1.goalScored();
     }
     return diff;
}
</code>```

Body:
public void sortLeagueTable(List<LeagueTableItem> table) {
    Collections.sort(table, new Comparator<LeagueTableItem>(){
        public int compare(LeagueTableItem o1, LeagueTableItem o2){
            return o2.getPoints() - o1.getPoints();
        }
    });
}

This code sorts two lists based on the value of the object called points. After I sort it based on the value point I want to sort it again based on the value goalScored. So, if the points of two teams are equal, I want to sort it again based on the goalScored value.

How can I do that?

Body:
Just add another condition to your comparator:

public int compare(LeagueTableItem o1, LeagueTableItem o2){
     int diff = o2.getPoints() - o1.getPoints();
     if (diff == 0) {
        diff = o2.goalScored() - o1.goalScored();
     }
     return diff;
}


问:
Redirect to welcome page on pressing back button in react Single page application
I have a react single page application, so on pressing back button, its redirecting me to welcome page as expected. Now due to some requirement, I have to update the URL of the app in between and due to which if now I press back button, its first redirect me to old url page and then welcome page.
How can I control this behavior, means even after updating the URL, user should directly redirected to welcome page on pressing back button.</p>

答:
I don't know how to do it using react router, but you can use window.history.pushState() to solve your problem. In your third component add the following code into the render() method.

window.history.pushState(null, null, '/your-welcome-page-url');```

It will change the current url to welcome page url without reloading the page; and when you will press the browser back button, the browser will be redirected to welcome page.

Body:
I don't know how to do it using react router, but you can use window.history.pushState() to solve your problem. In your third component add the following code into the render() method.

window.history.pushState(null, null, '/your-welcome-page-url');

It will change the current url to welcome page url without reloading the page; and when you will press the browser back button, the browser will be redirected to welcome page.


问:
How to create mysite.wsgi file?
I am following this tutorial http://uwsgi-docs.readthedocs.io/en/latest/tutorials/Django_and_nginx.html to setup django with nginx and uwsgi. But I am confused about this line:

```<code>uwsgi --http :8000 --module mysite.wsgi
</code>```

In the tutorial there's nothing about mysite.wsgi file. What should be the content of this file?

答:
Actually, that's not a filename.

That's a python module path.

The relevant file is actually mysite/wsgi.py (but to import it in a python interpreter, you'd have to import mysite.wsgi, hence the name used in command line).

Title: How to create mysite.wsgi file?

Body:
I am following this tutorial http://uwsgi-docs.readthedocs.io/en/latest/tutorials/Django_and_nginx.html to setup django with nginx and uwsgi. But I am confused about this line:

uwsgi --http :8000 --module mysite.wsgi

In the tutorial there's nothing about mysite.wsgi file. What should be the content of this file?


问:
Behaviour of train_test_split() from Scikit-learn
I am curious how the train_test_split() method of Scikit-learn will behave in the following scenario:

An imaginary dataset:

```<code>id, count, size
1, 4, 8
2, 5, 9
3, 6, 0
</code>```

say I would divide it into two separate sets like this (keeping 'id' in both):

```<code>id, count      |       id, size
1, 4           |       1, 8
2, 5           |       2, 9
3, 6           |       3, 0
</code>```

And split them both with train_test_split() with the same random_state of 0. Would the order of both be the same with 'id' as reference? (since you are shuffling the same dataset but with different parts left out)

I am curious as to how this works because I have two models. The first one gets trained with the dataset and adds it's results to the dataset, part of which is then used to train the second model.

When doing this it's important that when testing the generalization of the second model, no data points are used which were also used to train the first model. This is because the data was 'seen before' and the model will know what to do with it, so then you are not testing the generalization to new data anymore.

It would be great if train_test_split() would shuffle it the same since then one would not need to keep track of what data was used to train the first algorithm to prevent contamination of the test results.

答:
They should have the same resulting indices if you use the same random_state parameter in each call.

However--you could also just reverse your order of operations.  Call test/train split on the parent dataset, then create two sub-sets from both the test and train sets that result.

Example:

```<code>print(df)
   id  count  size
0   1      4     8
1   2      5     9
2   3      6     0

from sklearn.model_selection import train_test_split
dfa = df[['id', 'count']].copy()
dfb = df[['id', 'size']].copy()
rstate = 123
traina, testa = train_test_split(dfa, random_state=123)
trainb, testb = train_test_split(dfb, random_state=123)
assert traina.index.equals(trainb.index)
# True
</code>```

Body:
I am curious how the train_test_split() method of Scikit-learn will behave in the following scenario:

An imaginary dataset:

id, count, size
1, 4, 8
2, 5, 9
3, 6, 0

say I would divide it into two separate sets like this (keeping 'id' in both):

id, count      |       id, size
1, 4           |       1, 8
2, 5           |       2, 9
3, 6           |       3, 0

And split them both with train_test_split() with the same random_state of 0. Would the order of both be the same with 'id' as reference? (since you are shuffling the same dataset but with different parts left out)

I am curious as to how this works because I have two models. The first one gets trained with the dataset and adds it's results to the dataset, part of which is then used to train the second model.

When doing this it's important that when testing the generalization of the second model, no data points are used which were also used to train the first model. This is because the data was 'seen before' and the model will know what to do with it, so then you are not testing the generalization to new data anymore.

It would be great if train_test_split() would shuffle it the same since then one would not need to keep track of what data was used to train the first algorithm to prevent contamination of the test results.

Body:
They should have the same resulting indices if you use the same random_state parameter in each call.

However--you could also just reverse your order of operations.  Call test/train split on the parent dataset, then create two sub-sets from both the test and train sets that result.

Example:

print(df)
   id  count  size
0   1      4     8
1   2      5     9
2   3      6     0

from sklearn.model_selection import train_test_split
dfa = df[['id', 'count']].copy()
dfb = df[['id', 'size']].copy()
rstate = 123
traina, testa = train_test_split(dfa, random_state=123)
trainb, testb = train_test_split(dfb, random_state=123)
assert traina.index.equals(trainb.index)
# True


问:
In writing a purely relational prolog program, is it ok to use a carefully placed cut?
I am trying my hand in writing a relational prolog program that manages a key, value store. The initial code is taken from some lecture slides i found on the internet (http://people.eng.unimelb.edu.au/pstuckey/book/course.html -- see: using data structure slides).

```<code>newdic([]).
addkey(D0,K,I,D) :- D = [p(K,I)|D0].
delkey([],_,[]).
delkey([p(K,_)|D],K,D).
delkey([p(K0,I)|D0],K,[p(K0,I)|D]) :-
    dif(K, K0), delkey(D0,K,D).
</code>```

This code allows adding more than one value with the same key -- which, is fine with me. However, it also adds the same key, value pair twice, e.g.

```<code>?- newdic(D), addkey(D, a, 1, D2), addkey(D2, a, 1, D3), lookup(D3, a, X).
D = [],
D2 = [p(a, 1)],
D3 = [p(a, 1), p(a, 1)],
X = 1
</code>```

D3 includes p(a,1) twice.

To ensure that this doesn't happen i added the following code; and to ensure that backtracking doesn't find the alternative addkey clause, I added a cut in the end of the first clause.

Is this fair game for a purely relational program -- or are the better ways to ensure that no duplicate key,value pairs are added --without the use of a cut.

```<code>newdic([]).
addkey(D0,K,I,D0) :- lookup(D0, K, I), !.   % if the key already do nothing
addkey(D0,K,I,D) :- D = [p(K,I)|D0].
delkey([],_,[]).
delkey([p(K,_)|D],K,D).
delkey([p(K0,I)|D0],K,[p(K0,I)|D]) :-
    dif(K, K0), delkey(D0,K,D).
</code>```

this leads to the following:

```<code>?- newdic(D), addkey(D, a, 1, D2), addkey(D2, a, 1, D3), lookup(D3, a, X).
D = [],
D2 = D3, D3 = [p(a, 1)],
X = 1.
</code>```

No, more solutions are available -- the program returns immediately.

any suggestions are much appreciated,

Daniel

Note: as an aside: that if i add for the same key different values, the cut does allow to backtrack to identify the second value for the same key:

```<code>?- newdic(D), addkey(D, a, 1, D2), addkey(D2, a, 1, D3), addkey(D3, a, 2, D4), lookup(D4, a, X).
D = [],
D2 = D3, D3 = [p(a, 1)],
D4 = [p(a, 2), p(a, 1)],
X = 2 ;
D = [],
D2 = D3, D3 = [p(a, 1)],
D4 = [p(a, 2), p(a, 1)],
X = 1.
</code>```

答:
You can use if-then-else instead of cut:</p>

```<code>addkey(D0,K,I,D0) :-
  ( lookup(D0, K, I) ->
    D = D0 % if the key already [exists] do nothing
  ; D = [p(K,I)|D0] ).
</code>```

Body:
I am trying my hand in writing a relational prolog program that manages a key, value store. The initial code is taken from some lecture slides i found on the internet (http://people.eng.unimelb.edu.au/pstuckey/book/course.html -- see: using data structure slides).

newdic([]).
addkey(D0,K,I,D) :- D = [p(K,I)|D0].
delkey([],_,[]).
delkey([p(K,_)|D],K,D).
delkey([p(K0,I)|D0],K,[p(K0,I)|D]) :-
    dif(K, K0), delkey(D0,K,D).

This code allows adding more than one value with the same key -- which, is fine with me. However, it also adds the same key, value pair twice, e.g.

?- newdic(D), addkey(D, a, 1, D2), addkey(D2, a, 1, D3), lookup(D3, a, X).
D = [],
D2 = [p(a, 1)],
D3 = [p(a, 1), p(a, 1)],
X = 1

D3 includes p(a,1) twice.

To ensure that this doesn't happen i added the following code; and to ensure that backtracking doesn't find the alternative addkey clause, I added a cut in the end of the first clause.

Is this fair game for a purely relational program -- or are the better ways to ensure that no duplicate key,value pairs are added --without the use of a cut.

newdic([]).
addkey(D0,K,I,D0) :- lookup(D0, K, I), !.   % if the key already do nothing
addkey(D0,K,I,D) :- D = [p(K,I)|D0].
delkey([],_,[]).
delkey([p(K,_)|D],K,D).
delkey([p(K0,I)|D0],K,[p(K0,I)|D]) :-
    dif(K, K0), delkey(D0,K,D).

this leads to the following:

?- newdic(D), addkey(D, a, 1, D2), addkey(D2, a, 1, D3), lookup(D3, a, X).
D = [],
D2 = D3, D3 = [p(a, 1)],
X = 1.

No, more solutions are available -- the program returns immediately.

any suggestions are much appreciated,

Daniel

Note: as an aside: that if i add for the same key different values, the cut does allow to backtrack to identify the second value for the same key:

?- newdic(D), addkey(D, a, 1, D2), addkey(D2, a, 1, D3), addkey(D3, a, 2, D4), lookup(D4, a, X).
D = [],
D2 = D3, D3 = [p(a, 1)],
D4 = [p(a, 2), p(a, 1)],
X = 2 ;
D = [],
D2 = D3, D3 = [p(a, 1)],
D4 = [p(a, 2), p(a, 1)],
X = 1.

Body:
You can use if-then-else instead of cut:

addkey(D0,K,I,D0) :-
  ( lookup(D0, K, I) ->
    D = D0 % if the key already [exists] do nothing
  ; D = [p(K,I)|D0] ).


问:
That A-Ha Moment for Understanding OO Design in C#
I've been studying C# for a couple of years, reading voraciously, even taking a few C# data access courses from Microsoft.  I've also been reading books on OOP.  I'm coding a web-based database application at work.  While my job title is not "programmer", I'm fortunate enough to be able to work on this as a side project.  I coded in Basic in the early 80's and was even good at utilizing pokes and peeks to manipulate the Apple ][ + and the TRS-80 to astound and amaze my friends.  But that was a very linear approach to coding.

All this being said, something is just not clicking with me.  I haven't had that a-ha moment with either C# or OOP that gives me the ability to sit down, open up VS2008, and start coding.  I have to study other people's code so much that it simply seems like I'm not doing anything on my own.  I'm getting discouraged.

It's not like I'm not capable of it.  I picked up t-sql really quickly.  Someone can tell me what information they want out of the database and I can code out the tsql in a matter of a few minutes to give them what they want.  SQL is something that I get.  This isn't happening for me with OOP or C#.  Granted, C# is inherently more complex, but at some point it has to click.  Right?

I read over stackoverflow and I'm overwhelmed at how infinitely smart you all are.

What was it for you that made it click?

Edited to add:
A lot of the answers here were outstanding.  However, one in particular seemed to have risen to the top and that's the one I marked as the "answer".  I also hate not marking my questions with the answer.

答:
I remember this feeling. I was contracted to work on an application in ASP.NET and C#. Problem is, I wasn't a C# developer, and the Employer knew it! But because I had previous programming experience with them, they encouraged me to give it a shot. I was a PHP developer, stepping into a .NET world.

The first week was frustrating. I remember getting angry asking why I can't just include("sideNavigation.php") to get my navigation on the page. Instead I have to make some control, add it to some other control - it didn't make any sense. But I kept reading.

ASP.NET started catching on, and the markup was making a lot of sense. As I learned the markup aspect, I started becoming a bit more familiar in the code-behind. I knew what properties and methods existed for more things, and what types of values they accepted.

Of course places like www.learnvisualstudio.net came in handy too, with video-tutorials on C# and VB.NET.

Today I'm still a PHP Developer, but I feel comfortable enough with .NET that I could get back into VS2008 and tinker around until I get my solution(s).

All things with time, my friend. Another helpful thing is to find a .NET user-group and visit regularly.

OwnerDisplayName: GregD

LastEditorDisplayName: GregD

OwnerDisplayName: Jonathan Sampson

LastEditorDisplayName: Jonathan Sampson


问:
Is it worth creating an interface for a trivial return type?
Consider the following interfaces:

```<code>public interface IPlayerRepository
{
  IPlayerInfo GetPlayerInfo(int id);
}

public interface IPlayerInfo
{
  public int Id { get; set; }
  public int GamesPlayed { get; set; }
  public int GamesWon { get; set; }
}
</code>```

and the associated implementations:

```<code>public class PlayerRepository : IPlayerRepository
{
  IPlayerInfo GetPlayerInfo(int id)
  {
    // read from external data store
    return new PlayerInfo();
  }
}

public class PlayerInfo : IPlayerInfo
{
  public int Id { get; set; }
  public int GamesPlayed { get; set; }
  public int GamesWon { get; set; }
}
</code>```

Is there any value in having the separate IPlayerInfo interface, given that the class only exists as a collection of properties to be returned by this method?  Would it be preferable to just have the IPlayerRepository.GetPlayerInfo method return a concrete PlayerInfo object?

答:
It's not just whether you will ever have a different kind of an entity, but also whether it will need mocking during testing. </p>

<p>If your entity will never perform any business logic, I wouldn't bother, personally. </p>

Body:
Consider the following interfaces:

public interface IPlayerRepository
{
  IPlayerInfo GetPlayerInfo(int id);
}

public interface IPlayerInfo
{
  public int Id { get; set; }
  public int GamesPlayed { get; set; }
  public int GamesWon { get; set; }
}

and the associated implementations:

public class PlayerRepository : IPlayerRepository
{
  IPlayerInfo GetPlayerInfo(int id)
  {
    // read from external data store
    return new PlayerInfo();
  }
}

public class PlayerInfo : IPlayerInfo
{
  public int Id { get; set; }
  public int GamesPlayed { get; set; }
  public int GamesWon { get; set; }
}

Is there any value in having the separate IPlayerInfo interface, given that the class only exists as a collection of properties to be returned by this method?  Would it be preferable to just have the IPlayerRepository.GetPlayerInfo method return a concrete PlayerInfo object?

Body:
It's not just whether you will ever have a different kind of an entity, but also whether it will need mocking during testing.

If your entity will never perform any business logic, I wouldn't bother, personally.


问:
Type inference with lazy initialization and generic factory method in Kotlin
I have a factory method that produces some list of <T>:

```<code>inline fun <reified T> getObject(fileName: String): List<T>
</code>```

The factory method should be used for lazy initialization like this:

```<code>val points: List<Point> by lazy {
    ObjectFactory.getObject(pointsFileName)
}
</code>```

Now the Kotlin compiler obviously has not enough type information inside the lambda and complains:

```<code>Type inference failed:
Not enough information to infer parameter T in
inline fun <reified T> getObject(fileName: String): List<T>
Please specify it explicitly.
</code>```

The compiler is not considering the type to which the result of the lazy initialization will be assigned. I can work around this by providing the type locally, but it's not pretty:

```<code>val points by lazy {
    val pointsToCommunicateType: List<Point> =
            ObjectFactory.getObject(pointsFileName)
    pointsToCommunicateType
}
</code>```

What is the right way to do this?

答:
You can specify the type like this:</p>

```<code>ObjectFactory.getObject<Point>(pointsFileName)
</code>```

Body:
I have a factory method that produces some list of <T>:

inline fun <reified T> getObject(fileName: String): List<T>

The factory method should be used for lazy initialization like this:

val points: List<Point> by lazy {
    ObjectFactory.getObject(pointsFileName)
}

Now the Kotlin compiler obviously has not enough type information inside the lambda and complains:

Type inference failed:
Not enough information to infer parameter T in
inline fun <reified T> getObject(fileName: String): List<T>
Please specify it explicitly.

The compiler is not considering the type to which the result of the lazy initialization will be assigned. I can work around this by providing the type locally, but it's not pretty:

val points by lazy {
    val pointsToCommunicateType: List<Point> =
            ObjectFactory.getObject(pointsFileName)
    pointsToCommunicateType
}

What is the right way to do this?

Body:
You can specify the type like this:

ObjectFactory.getObject<Point>(pointsFileName)


问:
Prevent Page from reloading after AJAX PUT Request
I need to prevent my page from reloading after an Ajax PUT Request.

Basically i have a PUT request to update my database which is fired from a button click, on success of this i want to call another function which is an ajax GET, to reload the data i have just updated, However when doing this, i hit the controller method and get the new list of data, but the page reloads to default and does nothing with my new list

Ajax PUT

```<code>function SendDeleteToController(checkid) {
    $.ajax({
        type: "PUT",
        url: '@Url.Action("PutCheck", "Admin")',
        contentType: "application/json; charset=utf-8",
        datatype: JSON,
        data: JSON.stringify({ methodParam: checkid }),
        success: function () {
            GetListofChecks();
        },
        error: function () {
            alert("error");
        }
</code>```

AJAX GET

```<code>function GetListofChecks() {
    var department = $('#department').val();
    var process = $('#process').val();

    $.ajax({
        type: 'GET',
        url: '@Url.Action("GetListofChecks", "Admin")',
        contentType: "application/json; charset=utf-8",
        datatype: JSON,
        data: { "Department": department, "Process": process },
        success: function (result) {
            $("#mainData").empty();

            $.each(JSON.parse(result),
                function (i, item) {
                    var row = i + 1;
                    $("#mainData").append()
        },
        error: function (result) {
            alert(result);
        }
    });
}
</code>```

controller that returns list of new data

```<code>public JsonResult GetListofChecks(string department, string process)
{
    var listofChecks = new List<Check>();

    listofChecks = AdminModel.GetListofchecks(department, process);

    var json = new JavaScriptSerializer().Serialize(listofChecks);
    return Json(json, JsonRequestBehavior.AllowGet);
}
</code>```

答:
This is what i have tried

```<code> function SendDeleteToController(checkid) {

    var department = $('#department').val();
    var process = $('#process').val();

    $.ajax({
        type: "PUT",
        url: '@Url.Action("PutCheck", "Admin")',
        contentType: "application/json; charset=utf-8",
        datatype: JSON,
        data: JSON.stringify({ID: checkid, Department: department, Process: process}),
        success: function (result) {

            $("#mainData").empty();

            debugger;

            $.each(JSON.parse(result),
                function (i, item)
                {
                    var row = i + 1;

                    $("#mainData").append(
                        "<tr>" +
                        "<td id='application" + row + "'" + ">" + item.Application + "</td>" +

                        "<td id='department" + row + "'" + ">" + item.Department + "</td>" +

                        "<td id='process" + row + "'" + ">" + item.Process + "</td>" +

                        "<td id='checks" + row + "'" + ">" + item.Checks + "</td>" +

                        "<td id='Action" + row + "'" +">" +
                        "<button id='test' class='btn btn-xs btn-danger " +
                        "'" + "onclick='DeleteProcess(" + item.Id + ")" +
                        "'" + ">" + "<i class='glyphicon glyphicon-trash" +
                        "'" + "></i>" + "</button>" + "&nbsp" +

                        "<button class='btn btn-xs btn-primary " +"'" +
                        "onclick='EditProcess(" + item.Id + ")" +
                        "'" + ">" +
                        "<i class='glyphicon glyphicon-pencil" + "'" + "></i>" +
                        "</button>" +
                        "</td>" + "</tr>");
                });
        },
        error: function (result) {
            alert("error " + result);
        }
    });
}
</code>```

updated controller

```<code>    [HttpPut]
    public JsonResult PutCheck(string ID, string department, string process)
    {
        var checkId = ID;
        var listofChecks = new List<Check>();

        if (checkId != null)
        {

            // delete data
            AdminModel.DeleteCheck(checkId);

            // get update list of data
            listofChecks = AdminModel.GetListofchecks(department, process);

        }

        return Json(listofChecks, JsonRequestBehavior.AllowGet);
    }
</code>```

Body:
I need to prevent my page from reloading after an Ajax PUT Request.

Basically i have a PUT request to update my database which is fired from a button click, on success of this i want to call another function which is an ajax GET, to reload the data i have just updated, However when doing this, i hit the controller method and get the new list of data, but the page reloads to default and does nothing with my new list

Ajax PUT

function SendDeleteToController(checkid) {
    $.ajax({
        type: "PUT",
        url: '@Url.Action("PutCheck", "Admin")',
        contentType: "application/json; charset=utf-8",
        datatype: JSON,
        data: JSON.stringify({ methodParam: checkid }),
        success: function () {
            GetListofChecks();
        },
        error: function () {
            alert("error");
        }

AJAX GET

function GetListofChecks() {
    var department = $('#department').val();
    var process = $('#process').val();

    $.ajax({
        type: 'GET',
        url: '@Url.Action("GetListofChecks", "Admin")',
        contentType: "application/json; charset=utf-8",
        datatype: JSON,
        data: { "Department": department, "Process": process },
        success: function (result) {
            $("#mainData").empty();

            $.each(JSON.parse(result),
                function (i, item) {
                    var row = i + 1;
                    $("#mainData").append()
        },
        error: function (result) {
            alert(result);
        }
    });
}

controller that returns list of new data

public JsonResult GetListofChecks(string department, string process)
{
    var listofChecks = new List<Check>();

    listofChecks = AdminModel.GetListofchecks(department, process);

    var json = new JavaScriptSerializer().Serialize(listofChecks);
    return Json(json, JsonRequestBehavior.AllowGet);
}

Body:
This is what i have tried

 function SendDeleteToController(checkid) {

    var department = $('#department').val();
    var process = $('#process').val();

    $.ajax({
        type: "PUT",
        url: '@Url.Action("PutCheck", "Admin")',
        contentType: "application/json; charset=utf-8",
        datatype: JSON,
        data: JSON.stringify({ID: checkid, Department: department, Process: process}),
        success: function (result) {

            $("#mainData").empty();

            debugger;

            $.each(JSON.parse(result),
                function (i, item)
                {
                    var row = i + 1;

                    $("#mainData").append(
                        "<tr>" +
                        "<td id='application" + row + "'" + ">" + item.Application + "</td>" +

                        "<td id='department" + row + "'" + ">" + item.Department + "</td>" +

                        "<td id='process" + row + "'" + ">" + item.Process + "</td>" +

                        "<td id='checks" + row + "'" + ">" + item.Checks + "</td>" +

                        "<td id='Action" + row + "'" +">" +
                        "<button id='test' class='btn btn-xs btn-danger " +
                        "'" + "onclick='DeleteProcess(" + item.Id + ")" +
                        "'" + ">" + "<i class='glyphicon glyphicon-trash" +
                        "'" + "></i>" + "</button>" + "&nbsp" +

                        "<button class='btn btn-xs btn-primary " +"'" +
                        "onclick='EditProcess(" + item.Id + ")" +
                        "'" + ">" +
                        "<i class='glyphicon glyphicon-pencil" + "'" + "></i>" +
                        "</button>" +
                        "</td>" + "</tr>");
                });
        },
        error: function (result) {
            alert("error " + result);
        }
    });
}

updated controller

    [HttpPut]
    public JsonResult PutCheck(string ID, string department, string process)
    {
        var checkId = ID;
        var listofChecks = new List<Check>();

        if (checkId != null)
        {

            // delete data
            AdminModel.DeleteCheck(checkId);

            // get update list of data
            listofChecks = AdminModel.GetListofchecks(department, process);

        }

        return Json(listofChecks, JsonRequestBehavior.AllowGet);
    }


问:
many selectize inputs in RShiny connected with each other
I'm quite a beginner in R Shiny and I would like to create many multiple selectize inputs which are connected with each other. In other words : if an item is selected in one of the selectizeinputs i would like that it disappears from the other selectizeinputs' choices.

Below is an example of what i want (does not work)

```<code> modalities <- LETTERS[1:10]

 library(shiny)

 app <- shinyApp(
   ui = tabPanel("Change modalities",
            selectizeInput("ui_mod_choose1", label=paste0("Modality 1"),choices=NULL, multiple = TRUE),
            selectizeInput("ui_mod_choose2", label=paste0("Modality 2"),choices=NULL, multiple = TRUE),
            selectizeInput("ui_mod_choose3", label=paste0("Modality 3"),choices=NULL, multiple = TRUE)
   ),

 server = function(input, output, session) {
   observe({
updateSelectizeInput(session,"ui_mod_choose1",choices=  modalities)
updateSelectizeInput(session,"ui_mod_choose2",choices=  modalities)
updateSelectizeInput(session,"ui_mod_choose3",choices=  modalities)
   })
 }

      )
 runApp(app)
</code>```

EDIT : Here is a solution based on Bertil Nestorius' answer

```<code> modalities <- LETTERS[1:10]

 library(shiny)

 app <- shinyApp(
   ui = tabPanel("Change modalities",
            numericInput("ui_number", label="Number of modalities",min = 1, max = 4, value=3),
            uiOutput("renderui")
   ),

   server = function(input, output, session) {

     output$renderui <- renderUI({
       output = tagList()
       for(i in 1:input$ui_number){
         output[[i]] = tagList()
         output[[i]][[1]] = selectizeInput(paste0("ui_mod_choose",i), label=paste0("Modality ",i),choices=modalities, multiple = TRUE)
  }
  return(output)
})

 lapply(
  X = 1:100, ####### QUESTION HERE
  FUN = function(j){
    observeEvent({
      input[[paste0("ui_mod_choose",j)]]
    },
    {
      sapply(1:input$ui_number,function(i){
        vecteur <- do.call(c,lapply((1:input$ui_number)[-i],function(i){input[[paste0("ui_mod_choose",i)]]}))
        updateSelectizeInput(session,paste0("ui_mod_choose",i),choices=  modalities[!modalities %in% vecteur],selected = input[[paste0("ui_mod_choose",i)]])
      })
    },
    ignoreNULL = FALSE)

  }
)

observeEvent({
  input$ui_num
},
{
  sapply(1:nput$ui_num,function(i){
    updateSelectizeInput(session,paste0("ui_mod_choose",i),choice= modalities,selected=NULL)
       })
     }
     )

   }

 )
 runApp(app)
</code>```

The only problem I have left is on the following line  :

```<code>  X = 1:100, ####### QUESTION HERE
</code>```

See this issue for more information : lapply function using a numericInput parameter around an observeEvent in RShiny

答:
To have them all interconnected I would do something like this</p>

```<code>modalities <- LETTERS[1:10]

library(shiny)

app <- shinyApp(
  ui = tabPanel("Change modalities",
                selectizeInput("ui_mod_choose1", label=paste0("Modality 1"),choices=NULL, multiple = TRUE),
                selectizeInput("ui_mod_choose2", label=paste0("Modality 2"),choices=NULL, multiple = TRUE),
                selectizeInput("ui_mod_choose3", label=paste0("Modality 3"),choices=NULL, multiple = TRUE)
  ),

  server = function(input, output, session) {
    observe({
      updateSelectizeInput(session,"ui_mod_choose1",choices=  modalities)
      updateSelectizeInput(session,"ui_mod_choose2",choices=  modalities)
      updateSelectizeInput(session,"ui_mod_choose3",choices=  modalities)
    })
    observeEvent({
      input$ui_mod_choose2
      input$ui_mod_choose3
    },
    {
      updateSelectizeInput(session,"ui_mod_choose1",choices=  modalities[!modalities %in% c(input$ui_mod_choose2,input$ui_mod_choose3)],selected = input$ui_mod_choose1)
    },
    ignoreNULL = FALSE)
    observeEvent({
      input$ui_mod_choose1
      input$ui_mod_choose3
    },
    {
      updateSelectizeInput(session,"ui_mod_choose2",choices=  modalities[!modalities %in% c(input$ui_mod_choose1,input$ui_mod_choose3)],selected = input$ui_mod_choose2)
    },
    ignoreNULL = FALSE)
    observeEvent({
      input$ui_mod_choose2
      input$ui_mod_choose1
    },
    {
      updateSelectizeInput(session,"ui_mod_choose3",choices=  modalities[!modalities %in% c(input$ui_mod_choose2,input$ui_mod_choose1)],selected = input$ui_mod_choose3)
    },
    ignoreNULL = FALSE)
  }

)
runApp(app)
</code>```

Body:
I'm quite a beginner in R Shiny and I would like to create many multiple selectize inputs which are connected with each other. In other words : if an item is selected in one of the selectizeinputs i would like that it disappears from the other selectizeinputs' choices.

Below is an example of what i want (does not work)

 modalities <- LETTERS[1:10]

 library(shiny)

 app <- shinyApp(
   ui = tabPanel("Change modalities",
            selectizeInput("ui_mod_choose1", label=paste0("Modality 1"),choices=NULL, multiple = TRUE),
            selectizeInput("ui_mod_choose2", label=paste0("Modality 2"),choices=NULL, multiple = TRUE),
            selectizeInput("ui_mod_choose3", label=paste0("Modality 3"),choices=NULL, multiple = TRUE)
   ),

 server = function(input, output, session) {
   observe({
updateSelectizeInput(session,"ui_mod_choose1",choices=  modalities)
updateSelectizeInput(session,"ui_mod_choose2",choices=  modalities)
updateSelectizeInput(session,"ui_mod_choose3",choices=  modalities)
   })
 }

      )
 runApp(app)

EDIT : Here is a solution based on Bertil Nestorius' answer

 modalities <- LETTERS[1:10]

 library(shiny)

 app <- shinyApp(
   ui = tabPanel("Change modalities",
            numericInput("ui_number", label="Number of modalities",min = 1, max = 4, value=3),
            uiOutput("renderui")
   ),

   server = function(input, output, session) {

     output$renderui <- renderUI({
       output = tagList()
       for(i in 1:input$ui_number){
         output[[i]] = tagList()
         output[[i]][[1]] = selectizeInput(paste0("ui_mod_choose",i), label=paste0("Modality ",i),choices=modalities, multiple = TRUE)
  }
  return(output)
})

 lapply(
  X = 1:100, ####### QUESTION HERE
  FUN = function(j){
    observeEvent({
      input[[paste0("ui_mod_choose",j)]]
    },
    {
      sapply(1:input$ui_number,function(i){
        vecteur <- do.call(c,lapply((1:input$ui_number)[-i],function(i){input[[paste0("ui_mod_choose",i)]]}))
        updateSelectizeInput(session,paste0("ui_mod_choose",i),choices=  modalities[!modalities %in% vecteur],selected = input[[paste0("ui_mod_choose",i)]])
      })
    },
    ignoreNULL = FALSE)

  }
)

observeEvent({
  input$ui_num
},
{
  sapply(1:nput$ui_num,function(i){
    updateSelectizeInput(session,paste0("ui_mod_choose",i),choice= modalities,selected=NULL)
       })
     }
     )

   }

 )
 runApp(app)

The only problem I have left is on the following line  :

  X = 1:100, ####### QUESTION HERE

See this issue for more information : lapply function using a numericInput parameter around an observeEvent in RShiny

Body:
To have them all interconnected I would do something like this

modalities <- LETTERS[1:10]

library(shiny)

app <- shinyApp(
  ui = tabPanel("Change modalities",
                selectizeInput("ui_mod_choose1", label=paste0("Modality 1"),choices=NULL, multiple = TRUE),
                selectizeInput("ui_mod_choose2", label=paste0("Modality 2"),choices=NULL, multiple = TRUE),
                selectizeInput("ui_mod_choose3", label=paste0("Modality 3"),choices=NULL, multiple = TRUE)
  ),

  server = function(input, output, session) {
    observe({
      updateSelectizeInput(session,"ui_mod_choose1",choices=  modalities)
      updateSelectizeInput(session,"ui_mod_choose2",choices=  modalities)
      updateSelectizeInput(session,"ui_mod_choose3",choices=  modalities)
    })
    observeEvent({
      input$ui_mod_choose2
      input$ui_mod_choose3
    },
    {
      updateSelectizeInput(session,"ui_mod_choose1",choices=  modalities[!modalities %in% c(input$ui_mod_choose2,input$ui_mod_choose3)],selected = input$ui_mod_choose1)
    },
    ignoreNULL = FALSE)
    observeEvent({
      input$ui_mod_choose1
      input$ui_mod_choose3
    },
    {
      updateSelectizeInput(session,"ui_mod_choose2",choices=  modalities[!modalities %in% c(input$ui_mod_choose1,input$ui_mod_choose3)],selected = input$ui_mod_choose2)
    },
    ignoreNULL = FALSE)
    observeEvent({
      input$ui_mod_choose2
      input$ui_mod_choose1
    },
    {
      updateSelectizeInput(session,"ui_mod_choose3",choices=  modalities[!modalities %in% c(input$ui_mod_choose2,input$ui_mod_choose1)],selected = input$ui_mod_choose3)
    },
    ignoreNULL = FALSE)
  }

)
runApp(app)


问:
How to prevent many duplicate results after search in wordpress
when I perform a search in my wordpress site (search widget) I got pages and pages with the same result. It is not duplicate content because the results are all pointing to the exact same url. Obviously I want to display every distinct result only once.

Can anybody explain to me why this is happening and what I should do about it?

EDIT:

Here the loop from my search.php. There is no searchform.php (as far as I know).

```<code><main id="main" class="site-main" role="main">

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

        <?php if ( $masonry_layout ) : ?>
        <div id="masonry-loop">
        <?php endif; ?>

        <?php /* Start the Loop */ ?>
        <?php while ( have_posts() ) : the_post(); ?>

            <?php
            /**
             * Run the loop for the search to output the results.
             * If you want to overload this in a child theme then include a file
             * called content-search.php and that will be used instead.
             */
            get_template_part( 'template-parts/content', 'search' );
            ?>

        <?php endwhile; ?>

        <?php if ( $masonry_layout ) : ?>
        </div><!--/#masonry-loop-->
        <?php endif; ?>

        <?php the_posts_pagination(); ?>

    <?php else : ?>

        <?php get_template_part( 'template-parts/content', 'none' ); ?>

    <?php endif; ?>

    </main><!-- #main -->
</code>```

答:
Found it.

Just added this snippet to m functions.php file:

```<code>function search_distinct() {
return "DISTINCT";
}
add_filter('posts_distinct', 'search_distinct');
</code>```

Body:
when I perform a search in my wordpress site (search widget) I got pages and pages with the same result. It is not duplicate content because the results are all pointing to the exact same url. Obviously I want to display every distinct result only once.

Can anybody explain to me why this is happening and what I should do about it?

EDIT:

Here the loop from my search.php. There is no searchform.php (as far as I know).

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

        <?php if ( $masonry_layout ) : ?>

        <?php endif; ?>

        <?php /* Start the Loop */ ?>
        <?php while ( have_posts() ) : the_post(); ?>

            <?php
            /**
             * Run the loop for the search to output the results.
             * If you want to overload this in a child theme then include a file
             * called content-search.php and that will be used instead.
             */
            get_template_part( 'template-parts/content', 'search' );
            ?>

        <?php endwhile; ?>

        <?php if ( $masonry_layout ) : ?>

        <?php endif; ?>

        <?php the_posts_pagination(); ?>

    <?php else : ?>

        <?php get_template_part( 'template-parts/content', 'none' ); ?>

    <?php endif; ?>

Body:
Found it.

Just added this snippet to m functions.php file:

function search_distinct() {
return "DISTINCT";
}
add_filter('posts_distinct', 'search_distinct');


问:
SQL Server Bulk insert of CSV file with inconsistent quotes
Is it possible to BULK INSERT (SQL Server) a CSV file in which the fields are only OCCASSIONALLY surrounded by quotes? Specifically, quotes only surround those fields that contain a ",".

In other words, I have data that looks like this (the first row contain headers):

```<code>id, company, rep, employees
729216,INGRAM MICRO INC.,"Stuart, Becky",523
729235,"GREAT PLAINS ENERGY, INC.","Nelson, Beena",114
721177,GEORGE WESTON BAKERIES INC,"Hogan, Meg",253
</code>```

Because the quotes aren't consistent, I can't use '","' as a delimiter, and I don't know how to create a format file that accounts for this.

I tried using ',' as a delimter and loading it into a temporary table where every column is a varchar, then using some kludgy processing to strip out the quotes, but that doesn't work either, because the fields that contain ',' are split into multiple columns.

Unfortunately, I don't have the ability to manipulate the CSV file beforehand.

Is this hopeless?

Many thanks in advance for any advice.

By the way, i saw this post SQL bulk import from csv, but in that case, EVERY field was consistently wrapped in quotes. So, in that case, he could use ',' as a delimiter, then strip out the quotes afterwards.

答:
I have also created a function to convert a CSV to a usable format for Bulk Insert.  I used the answered post by Chris Clark as a starting point to create the following C# function.

I ended up using a regular expression to find the fields.  I then recreated the file line by line, writing it to a new file as I went, thus avoiding having the entire file loaded into memory.

```<code>private void CsvToOtherDelimiter(string CSVFile, System.Data.Linq.Mapping.MetaTable tbl)
{
    char PH1 = '|';
    StringBuilder ln;

    //Confirm file exists. Else, throw exception
    if (File.Exists(CSVFile))
    {
        using (TextReader tr = new StreamReader(CSVFile))
        {
            //Use a temp file to store our conversion
            using (TextWriter tw = new StreamWriter(CSVFile + ".tmp"))
            {
                string line = tr.ReadLine();
                //If we have already converted, no need to reconvert.
                //NOTE: We make the assumption here that the input header file
                //      doesn't have a PH1 value unless it's already been converted.
                if (line.IndexOf(PH1) >= 0)
                {
                    tw.Close();
                    tr.Close();
                    File.Delete(CSVFile + ".tmp");
                    return;
                }
                //Loop through input file
                while (!string.IsNullOrEmpty(line))
                {
                    ln = new StringBuilder();

                    //1. Use Regex expression to find comma separated values
                    //using quotes as optional text qualifiers
                    //(what MS EXCEL does when you import a csv file)
                    //2. Remove text qualifier quotes from data
                    //3. Replace any values of PH1 found in column data
                    //with an equivalent character
                    //Regex:  \A[^,]*(?=,)|(?:[^",]*"[^"]*"[^",]*)+|[^",]*"[^"]*\Z|(?<=,)[^,]*(?=,)|(?<=,)[^,]*\Z|\A[^,]*\Z
                    List<string> fieldList = Regex.Matches(line, @"\A[^,]*(?=,)|(?:[^"",]*""[^""]*""[^"",]*)+|[^"",]*""[^""]*\Z|(?<=,)[^,]*(?=,)|(?<=,)[^,]*\Z|\A[^,]*\Z")
                            .Cast<Match>()
                            .Select(m => RemoveCSVQuotes(m.Value).Replace(PH1, '¦'))
                            .ToList<string>();

                    //Add the list of fields to ln, separated by PH1
                    fieldList.ToList().ForEach(m => ln.Append(m + PH1));

                    //Write to file. Don't include trailing PH1 value.
                    tw.WriteLine(ln.ToString().Substring(0, ln.ToString().LastIndexOf(PH1)));

                    line = tr.ReadLine();
                }

                tw.Close();
            }
            tr.Close();

            //Optional:  replace input file with output file
            File.Delete(CSVFile);
            File.Move(CSVFile + ".tmp", CSVFile);
        }
    }
    else
    {
        throw new ArgumentException(string.Format("Source file {0} not found", CSVFile));
    }
}
//The output file no longer needs quotes as a text qualifier, so remove them
private string RemoveCSVQuotes(string value)
{
    //if is empty string, then remove double quotes
    if (value == @"""""") value = "";
    //remove any double quotes, then any quotes on ends
    value = value.Replace(@"""""", @"""");
    if (value.Length >= 2)
        if (value.Substring(0, 1) == @"""")
            value = value.Substring(1, value.Length - 2);
    return value;
}
</code>```

Body:
Is it possible to BULK INSERT (SQL Server) a CSV file in which the fields are only OCCASSIONALLY surrounded by quotes? Specifically, quotes only surround those fields that contain a ",".

In other words, I have data that looks like this (the first row contain headers):

id, company, rep, employees
729216,INGRAM MICRO INC.,"Stuart, Becky",523
729235,"GREAT PLAINS ENERGY, INC.","Nelson, Beena",114
721177,GEORGE WESTON BAKERIES INC,"Hogan, Meg",253

Because the quotes aren't consistent, I can't use '","' as a delimiter, and I don't know how to create a format file that accounts for this.

I tried using ',' as a delimter and loading it into a temporary table where every column is a varchar, then using some kludgy processing to strip out the quotes, but that doesn't work either, because the fields that contain ',' are split into multiple columns.

Unfortunately, I don't have the ability to manipulate the CSV file beforehand.

Is this hopeless?

Many thanks in advance for any advice.

By the way, i saw this post SQL bulk import from csv, but in that case, EVERY field was consistently wrapped in quotes. So, in that case, he could use ',' as a delimiter, then strip out the quotes afterwards.

LastEditorDisplayName: anon

Body:
I have also created a function to convert a CSV to a usable format for Bulk Insert.  I used the answered post by Chris Clark as a starting point to create the following C# function.

I ended up using a regular expression to find the fields.  I then recreated the file line by line, writing it to a new file as I went, thus avoiding having the entire file loaded into memory.

private void CsvToOtherDelimiter(string CSVFile, System.Data.Linq.Mapping.MetaTable tbl)
{
    char PH1 = '|';
    StringBuilder ln;

    //Confirm file exists. Else, throw exception
    if (File.Exists(CSVFile))
    {
        using (TextReader tr = new StreamReader(CSVFile))
        {
            //Use a temp file to store our conversion
            using (TextWriter tw = new StreamWriter(CSVFile + ".tmp"))
            {
                string line = tr.ReadLine();
                //If we have already converted, no need to reconvert.
                //NOTE: We make the assumption here that the input header file
                //      doesn't have a PH1 value unless it's already been converted.
                if (line.IndexOf(PH1) >= 0)
                {
                    tw.Close();
                    tr.Close();
                    File.Delete(CSVFile + ".tmp");
                    return;
                }
                //Loop through input file
                while (!string.IsNullOrEmpty(line))
                {
                    ln = new StringBuilder();

                    //1. Use Regex expression to find comma separated values
                    //using quotes as optional text qualifiers
                    //(what MS EXCEL does when you import a csv file)
                    //2. Remove text qualifier quotes from data
                    //3. Replace any values of PH1 found in column data
                    //with an equivalent character
                    //Regex:  \A[^,]*(?=,)|(?:[^",]*"[^"]*"[^",]*)+|[^",]*"[^"]*\Z|(?<=,)[^,]*(?=,)|(?<=,)[^,]*\Z|\A[^,]*\Z
                    List<string> fieldList = Regex.Matches(line, @"\A[^,]*(?=,)|(?:[^"",]*""[^""]*""[^"",]*)+|[^"",]*""[^""]*\Z|(?<=,)[^,]*(?=,)|(?<=,)[^,]*\Z|\A[^,]*\Z")
                            .Cast<Match>()
                            .Select(m => RemoveCSVQuotes(m.Value).Replace(PH1, '¦'))
                            .ToList<string>();

                    //Add the list of fields to ln, separated by PH1
                    fieldList.ToList().ForEach(m => ln.Append(m + PH1));

                    //Write to file. Don't include trailing PH1 value.
                    tw.WriteLine(ln.ToString().Substring(0, ln.ToString().LastIndexOf(PH1)));

                    line = tr.ReadLine();
                }

                tw.Close();
            }
            tr.Close();

            //Optional:  replace input file with output file
            File.Delete(CSVFile);
            File.Move(CSVFile + ".tmp", CSVFile);
        }
    }
    else
    {
        throw new ArgumentException(string.Format("Source file {0} not found", CSVFile));
    }
}
//The output file no longer needs quotes as a text qualifier, so remove them
private string RemoveCSVQuotes(string value)
{
    //if is empty string, then remove double quotes
    if (value == @"""""") value = "";
    //remove any double quotes, then any quotes on ends
    value = value.Replace(@"""""", @"""");
    if (value.Length >= 2)
        if (value.Substring(0, 1) == @"""")
            value = value.Substring(1, value.Length - 2);
    return value;
}


问:
iOS SceneKit lights not working in simulator
When I run my app containing a SCNView, containing some objects and some SCNLight (added a keylight and ambientlight), it does run correctly on real iOS devices.

However, when I try to run in iOS Simulator, the lighting does not work. When I set the scene background color, I can still see the objects as black silhouettes in the simulator.

Does anyone have an idea what causes this and is there any solution to let SCNLights work correctly on the iOS Simulator?

I already tried changing the render engine mode with various options:

```<code>defaults write com.apple.CoreSimulator.IndigoFramebufferServices FramebufferRendererHint X
</code>```

Where X is:

```<code>0 = auto
1 = Metal
2 = OpenCL
3 = OpenGL
</code>```

As mentioned here. However, this doesn't appear to make any difference (when I reset iOS simulator).

Some context:

Running iOS 11.1

It is a rather advanced app with another (separate) SceneView (an ARSCNView to be precise). Can the problem be caused because there are basically two SCNView's in the app? (they are never shown at the same time though).

答: Had same issue. Disabled shadows casting in the light's inspector and it light returned in the simulator. </p>

Body:
When I run my app containing a SCNView, containing some objects and some SCNLight (added a keylight and ambientlight), it does run correctly on real iOS devices.

However, when I try to run in iOS Simulator, the lighting does not work. When I set the scene background color, I can still see the objects as black silhouettes in the simulator.

Does anyone have an idea what causes this and is there any solution to let SCNLights work correctly on the iOS Simulator?

I already tried changing the render engine mode with various options:

defaults write com.apple.CoreSimulator.IndigoFramebufferServices FramebufferRendererHint X

Where X is:

0 = auto
1 = Metal
2 = OpenCL
3 = OpenGL

As mentioned here. However, this doesn't appear to make any difference (when I reset iOS simulator).

Some context:

Running iOS 11.1

It is a rather advanced app with another (separate) SceneView (an ARSCNView to be precise). Can the problem be caused because there are basically two SCNView's in the app? (they are never shown at the same time though).


问:
this.passthrough() functionality in Ember
I am writing an application in Ember.js and I am also using Ember mirage. I need to make requests to an external server and I am currently trying to set up my config.js file to deal with such requests. Adding this.passthrough() does not work and I still get an error when I try to make my request saying:

"Your Ember app tried to GET 'http://...' but there was no route defined to handle this request. Define a route that matches this path in your mirage/config.js file. Did you forget to add your namespace?

I believe this should be a simple thing to fix, any ideas of what is going wrong?

答:
Mirage helpdoc explaining it detail. configuration/#passthrough

If you want all requests on the current domain to pass through, simply invoke the method with no arguments:

```<code>this.passthrough();
</code>```

You can also allow other-origin hosts to passthrough. If you use a fully-qualified domain name, the namespace property will be ignored. Use two * wildcards to match all requests under a path:

```<code>this.passthrough('http://api.foo.bar/**');
</code>```

Note:Put all passthrough config at the bottom of your config.js file, to give your route handlers precedence.

Body:
Mirage helpdoc explaining it detail. configuration/#passthrough

If you want all requests on the current domain to pass through, simply invoke the method with no arguments:

this.passthrough();

You can also allow other-origin hosts to passthrough. If you use a fully-qualified domain name, the namespace property will be ignored. Use two * wildcards to match all requests under a path:

this.passthrough('http://api.foo.bar/**');

Note:Put all passthrough config at the bottom of your config.js file, to give your route handlers precedence.


问:
Calculate Distance Between Airports Using IATA Codes
I need to find the distance (as the Airbus A320 flies, not super accurate) between two airports, preferably using IATA codes (PHX, LAX, CLT for example).

I see many websites that do this but I need to find an API (Google Maps, Bing Maps?) that I could use to calculate the distances with. I'm aware that I might have to geo code the IATA codes, but I'd like to avoid that (I know that using Google maps you can specify the IATA code+Airport and it will get the location)

Any suggestions?

答:
There are tens of thousands of airports in the world, if you would find a database of all airports with latitudes and longitudes, you could set up a formula to calculate the distance between each and every one of them. </p>

<p>If you know how to work with REST API, you could use Aviation Edge which has a feature that allows you to find airports and cities nearby a certain coordinate. This should fit your requirements. Have a look at their developers page </p>

Body:
There are tens of thousands of airports in the world, if you would find a database of all airports with latitudes and longitudes, you could set up a formula to calculate the distance between each and every one of them.

If you know how to work with REST API, you could use Aviation Edge which has a feature that allows you to find airports and cities nearby a certain coordinate. This should fit your requirements. Have a look at their developers page