问:
Send large stream to ServiceFabric Service
I have a ServiceFabric service hosting WebAPI. On a controller, I receive, in my Request, a FileStream. I have no problem reading the FileStream there.

Then, I want this WebAPI service to call another SF service (stateful) - let's call it Service2, giving a MemoryStream in parameter.

```<code>try
{
    await _service2Proxy.MyService2Method(myMemoryStream, otherParameters);
    // Line after
}
catch
{
    // Error handling
}
</code>```

And in the Service2

```<code>public Task MyService2Method(MemoryStream ms, string otherParam)
{
    // Log line
    // Do something
}
</code>```

It works perfectly well with a File < 3 MB. Yet, with a file > 5 MB, the call doesn't work. We never go on // Line after, // Error handling or // Log line.

I did add [assembly: FabricTransportServiceRemotingProvider(MaxMessageSize = int.MaxValue)] on the controller assembly, the WebAPI service assembly and the Service2 assembly.
The Service2 interface has the [OperationContract] and [ServiceContract] attributes.

I also tried sending a byte[] instead of a MemoryStream. The problem is still the same.

答:
If it's a StatefulService and you use some ReliableDictionary with huge data, it could lead to similar issues when SF replicates your dictionary data.

You can set two more settings to prevent this:

Set the MaxReplicationMessageSize when you create the service instance.

Init your ServiceReplicaListener with custom FabricTransportListenerSettings : MaxMessageSize

Code:

```<code>public MyStateFulService(StatefulServiceContext context)
    : base(context, new ReliableStateManager(context, new ReliableStateManagerConfiguration(new ReliableStateManagerReplicatorSettings
    {
        MaxReplicationMessageSize = 1073741824
    }))){ }

protected override IEnumerable<ServiceReplicaListener> CreateServiceReplicaListeners()
{
    var setting = new FabricTransportListenerSettings();
    setting.MaxMessageSize = 1073741824;
    return new[] { new ServiceReplicaListener(initParams => new FabricTransportServiceRemotingListener(initParams, this, setting), "RpcListener")};
}
</code>```

Edit :

A highly better way to do this: In case you have authentication between replica, you should set these settings in Settings.xml.

```<code>    <?xml version="1.0" encoding="utf-8" ?>
<Settings xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.microsoft.com/2011/01/fabric">
  <!-- This is used by the StateManager's replicator. -->
  <Section Name="ReplicatorConfig">
    <Parameter Name="ReplicatorEndpoint" Value="ReplicatorEndpoint" />
    <Parameter Name="MaxReplicationMessageSize" Value="1073741824" />
  </Section>
  <!-- This is used for securing StateManager's replication traffic. -->
  <Section Name="ReplicatorSecurityConfig">
    <Parameter Name="CredentialType" Value="Windows" />
    <Parameter Name="ProtectionLevel" Value="None" />
  </Section>

  <!-- Add your custom configuration sections and parameters here. -->
  <!--
  <Section Name="MyConfigSection">
    <Parameter Name="MyParameter" Value="Value1" />
  </Section>
  -->
</Settings>
</code>```

Body:
I have a ServiceFabric service hosting WebAPI. On a controller, I receive, in my Request, a FileStream. I have no problem reading the FileStream there.

Then, I want this WebAPI service to call another SF service (stateful) - let's call it Service2, giving a MemoryStream in parameter.

try
{
    await _service2Proxy.MyService2Method(myMemoryStream, otherParameters);
    // Line after
}
catch
{
    // Error handling
}

And in the Service2

public Task MyService2Method(MemoryStream ms, string otherParam)
{
    // Log line
    // Do something
}

It works perfectly well with a File < 3 MB. Yet, with a file > 5 MB, the call doesn't work. We never go on // Line after, // Error handling or // Log line.

I did add [assembly: FabricTransportServiceRemotingProvider(MaxMessageSize = int.MaxValue)] on the controller assembly, the WebAPI service assembly and the Service2 assembly.
The Service2 interface has the [OperationContract] and [ServiceContract] attributes.

I also tried sending a byte[] instead of a MemoryStream. The problem is still the same.

Body:
If it's a StatefulService and you use some ReliableDictionary with huge data, it could lead to similar issues when SF replicates your dictionary data.

You can set two more settings to prevent this:

Set the MaxReplicationMessageSize when you create the service instance.

Init your ServiceReplicaListener with custom FabricTransportListenerSettings : MaxMessageSize

Code:

public MyStateFulService(StatefulServiceContext context)
    : base(context, new ReliableStateManager(context, new ReliableStateManagerConfiguration(new ReliableStateManagerReplicatorSettings
    {
        MaxReplicationMessageSize = 1073741824
    }))){ }

protected override IEnumerable<ServiceReplicaListener> CreateServiceReplicaListeners()
{
    var setting = new FabricTransportListenerSettings();
    setting.MaxMessageSize = 1073741824;
    return new[] { new ServiceReplicaListener(initParams => new FabricTransportServiceRemotingListener(initParams, this, setting), "RpcListener")};
}

Edit :

A highly better way to do this: In case you have authentication between replica, you should set these settings in Settings.xml.

    <?xml version="1.0" encoding="utf-8" ?>
<Settings xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.microsoft.com/2011/01/fabric">
  <!-- This is used by the StateManager's replicator. -->
  <Section Name="ReplicatorConfig">
    <Parameter Name="ReplicatorEndpoint" Value="ReplicatorEndpoint" />
    <Parameter Name="MaxReplicationMessageSize" Value="1073741824" />
  </Section>
  <!-- This is used for securing StateManager's replication traffic. -->
  <Section Name="ReplicatorSecurityConfig">
    <Parameter Name="CredentialType" Value="Windows" />
    <Parameter Name="ProtectionLevel" Value="None" />
  </Section>

  <!-- Add your custom configuration sections and parameters here. -->
  <!--
  <Section Name="MyConfigSection">
    <Parameter Name="MyParameter" Value="Value1" />
  </Section>
  -->
</Settings>


来源: stackexchange

问:
How to store data to database with Ajax on Model Class Codeigniter
We want to put data from view () to database. We use Ajax to running some background process (insert data to database). But We can't save the data to database. I'm appreciate and thank's a lot for any suggest and good avice do you give. I'm sorry if this is just a newbie's question.

This is the View (form, fieldset, javascript, and ajax)

var popup, x, f31, f32, f33, f4, f5, f6, f7, f7a, f81, f82, f11, f14, f161, f17a1;

function _(x){
    return document.getElementById(x);
}

//fungsi tutup popup
function tutupPopup(){
    _("popup").style.display = "none";
}

function prosesc11(){
    f31 = _("f31").value;
    f32 = _("f32").value;
    f33 = _("f33").value;
    $.ajax({
        url    : "<?php echo base_url().'index.php/TracerStudy_model/simpan_data_ts';?>",
        type   : 'post',
        data   : {'f31' : f31, 'f32' : f32},
        success: function(data){
            console.log(data);
        }
    });

    if(f31.length>0||f32.length>0){
        _("formc1-1").style.display = "none";
        _("formc1-2").style.display = "block";
        _("progressBar").value = 50;
    }else{
        alert("Maaf data anda ada yang belum diisi.")
    }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form class="multiphaseForm" id="multiphaseForm" onsubmit="return false"
    method="post" action="<?php base_url();?>TracerStudy/masuk_data_ts"
>
<fieldset class="formc1-1" id="formc1-1"><!--fieldset pertama-->
    <!-- f3 -->
    <div class="form-group">
        <div class="row">
            <div class="col-md-8">
                <label>1. Kapan anda mulai mencari pekerjaan ?</label>
            </div>
        </div>
        <div class="row ">
            <input class="col-lg-1" id="f31" name="f3" type="radio" value="1" class="form-control">
            <label class="col-md-8" for="f31">Sebelum lulus</label>
        </div>
        <div class="row ">
            <input class="col-lg-1" id="f32" name="f3" type="radio" value="2" class="form-control">
            <label class="col-md-8" for="f32">Setelah lulus</label>
        </div>
        <div class="row ">
            <input class="col-lg-1" id="f33" name="f3" type="radio" value="3" class="form-control">
            <label class="col-md-8" for="f33">Tidak mencari kerja</label>
        </div>
    </div>
    <!-- <input class="btn_c1-1" id="simpan" name="simpan" type="submit" onclick="prosesc11" value="simpan"/> -->
    <button onclick="prosesc11()">Selanjutnya</button>
</fieldset><!--formc1-1-->
</form></code>```

This is Model Class

public function simpan_data_ts(){
      $idAlumni = $this->session->userdata('id_alumni');
      // $default = null;
      // $satu = $this->input->post('f3');
      // $datetime = date('Y-m-d');
      // $dataSimpan = array( 'f3' => $satu);

      //$f31 = $this->input->post('f31');
      $f32 = $this->input->post('f32');
      $data = array(
        'id_alumni_fk' => $idAlumni,
        'f3' => $this->input->post('f31')
      );
      $this->db->insert('tracer_study', $data);
}```

We hope, anyone can tell us what's wrong with it. And I have to say thank you for all your response.

答:
You cant go to codeigniter model directly.

just pass the data to the controller. there you can call the model by

```<code>$this->TracerStudy_model->simpan_data_ts();
</code>```

and pass the data from controller to model by

```<code>$this->TracerStudy_model->simpan_data_ts($data);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
We want to put data from view () to database. We use Ajax to running some background process (insert data to database). But We can't save the data to database. I'm appreciate and thank's a lot for any suggest and good avice do you give. I'm sorry if this is just a newbie's question.

This is the View (form, fieldset, javascript, and ajax)

var popup, x, f31, f32, f33, f4, f5, f6, f7, f7a, f81, f82, f11, f14, f161, f17a1;

function _(x){
    return document.getElementById(x);
}

//fungsi tutup popup
function tutupPopup(){
    _("popup").style.display = "none";
}

function prosesc11(){
    f31 = _("f31").value;
    f32 = _("f32").value;
    f33 = _("f33").value;
    $.ajax({
        url    : "<?php echo base_url().'index.php/TracerStudy_model/simpan_data_ts';?>",
        type   : 'post',
        data   : {'f31' : f31, 'f32' : f32},
        success: function(data){
            console.log(data);
        }
    });

    if(f31.length>0||f32.length>0){
        _("formc1-1").style.display = "none";
        _("formc1-2").style.display = "block";
        _("progressBar").value = 50;
    }else{
        alert("Maaf data anda ada yang belum diisi.")
    }
}

<form class="multiphaseForm" id="multiphaseForm" onsubmit="return false"
    method="post" action="<?php base_url();?>TracerStudy/masuk_data_ts"
>
<fieldset class="formc1-1" id="formc1-1">

                1. Kapan anda mulai mencari pekerjaan ?

            <input class="col-lg-1" id="f31" name="f3" type="radio" value="1" class="form-control">
            Sebelum lulus

            <input class="col-lg-1" id="f32" name="f3" type="radio" value="2" class="form-control">
            Setelah lulus

            <input class="col-lg-1" id="f33" name="f3" type="radio" value="3" class="form-control">
            Tidak mencari kerja

    <button onclick="prosesc11()">Selanjutnya</button>
</fieldset>
</form>

This is Model Class

public function simpan_data_ts(){
      $idAlumni = $this->session->userdata('id_alumni');
      // $default = null;
      // $satu = $this->input->post('f3');
      // $datetime = date('Y-m-d');
      // $dataSimpan = array( 'f3' => $satu);

      //$f31 = $this->input->post('f31');
      $f32 = $this->input->post('f32');
      $data = array(
        'id_alumni_fk' => $idAlumni,
        'f3' => $this->input->post('f31')
      );
      $this->db->insert('tracer_study', $data);
}

We hope, anyone can tell us what's wrong with it. And I have to say thank you for all your response.

Body:
You cant go to codeigniter model directly.

just pass the data to the controller. there you can call the model by

$this->TracerStudy_model->simpan_data_ts();

and pass the data from controller to model by

$this->TracerStudy_model->simpan_data_ts($data);


问:
AJAX function not works (ASP.NET MVC)
I have AJAX function in my View to pass data to Controller

Here is code of script

```<code> stop.onclick = function () {
    record.disabled = false;
    stop.disabled = true;
    window.onbeforeunload = null; //Solve trouble with deleting video
    preview.src = '';

    fileName = Math.round(Math.random() * 99999999) + 99999999;
    console.log(fileName);
    var full_url = document.URL; // Get current url
    var url_array = full_url.split('/') // Split the string into an array with / as separator
    var id = url_array[url_array.length - 1];  // Get the last part of the array (-1)
    function save() {
        $.ajax({
            type: 'Post',
            dataType: 'Json',
            data: {
                link: fileName.val(),
                id: id.val(),
            },
            url: '@Url.Action("LinkWriter", "Interwier")',
            success: function (da) {
                if (da.Result === "Success") {

                    alert("lol");

                } else {

                    alert('Error' + da.Message);
                }
            },
            error: function (da) {
                alert('Error');
            }
        });
    }
</code>```

Not works this part of code

```<code> function save() {
        $.ajax({
            type: 'Post',
            dataType: 'Json',
            data: {
                link: fileName.val(),
                id: id.val(),
            },
            url: '@Url.Action("LinkWriter", "Interwier")',
            success: function (da) {
                if (da.Result === "Success") {

                    alert("lol");

                } else {

                    alert('Error' + da.Message);
                }
            },
            error: function (da) {
                alert('Error');
            }
        });
    }
</code>```

Here is code in Controller

```<code>[HttpPost]
    public ActionResult LinkWriter(string link, int id) {

        Link link_ = new Link
        {
            Link1 = link,
            Interwier_Id = id,

        };

        db.Link.Add(link_);
        db.SaveChanges();
        return Json(new { Result = "Success", Message = "Saved Successfully" });
    }
</code>```

I don't understand why it not works

I think I doing all right

Can you help me?

答:
Try like this. It's more readable:

```<code> function save() {
     $.post("@Url.Action("LinkWriter", "Interwier")",
      {
       link: fileName.val(),
       id: id.val()
      })
      .done(function () {
         alert("lol");
      })
     .fail(function () {
         alert("error");
     });
}
</code>```

Note: Check that this fileName.val() is string and this id.val() is int .
Check also that your controller name is correctly written: InterwierController

UPDATE:
You can do it also with ViewModels. Check here.

Title: AJAX function not works (ASP.NET MVC)

Body:
I have AJAX function in my View to pass data to Controller

Here is code of script

 stop.onclick = function () {
    record.disabled = false;
    stop.disabled = true;
    window.onbeforeunload = null; //Solve trouble with deleting video
    preview.src = '';

    fileName = Math.round(Math.random() * 99999999) + 99999999;
    console.log(fileName);
    var full_url = document.URL; // Get current url
    var url_array = full_url.split('/') // Split the string into an array with / as separator
    var id = url_array[url_array.length - 1];  // Get the last part of the array (-1)
    function save() {
        $.ajax({
            type: 'Post',
            dataType: 'Json',
            data: {
                link: fileName.val(),
                id: id.val(),
            },
            url: '@Url.Action("LinkWriter", "Interwier")',
            success: function (da) {
                if (da.Result === "Success") {

                    alert("lol");

                } else {

                    alert('Error' + da.Message);
                }
            },
            error: function (da) {
                alert('Error');
            }
        });
    }

Not works this part of code

 function save() {
        $.ajax({
            type: 'Post',
            dataType: 'Json',
            data: {
                link: fileName.val(),
                id: id.val(),
            },
            url: '@Url.Action("LinkWriter", "Interwier")',
            success: function (da) {
                if (da.Result === "Success") {

                    alert("lol");

                } else {

                    alert('Error' + da.Message);
                }
            },
            error: function (da) {
                alert('Error');
            }
        });
    }

Here is code in Controller

[HttpPost]
    public ActionResult LinkWriter(string link, int id) {

        Link link_ = new Link
        {
            Link1 = link,
            Interwier_Id = id,

        };

        db.Link.Add(link_);
        db.SaveChanges();
        return Json(new { Result = "Success", Message = "Saved Successfully" });
    }

I don't understand why it not works

I think I doing all right

Can you help me?

Body:
Try like this. It's more readable:

 function save() {
     $.post("@Url.Action("LinkWriter", "Interwier")",
      {
       link: fileName.val(),
       id: id.val()
      })
      .done(function () {
         alert("lol");
      })
     .fail(function () {
         alert("error");
     });
}

Note: Check that this fileName.val() is string and this id.val() is int .
Check also that your controller name is correctly written: InterwierController

UPDATE:
You can do it also with ViewModels. Check here.


问:
Can Google Cloud Compute connect to Mandrill for SMTP relay?
I'm using Mandrill service, now I want to use this service to replay instance email, you know that instance blocked 25 port, so will use 2525 port for this replay, is Google Cloud Compute support Mandrill ?

Thanks

答: Yes it should work fine as Mandrill does indeed support port 2525 which google compute engine can use.</p>


问:
Using Notepad++ to compile Java code
I've been trying to set up Notepad++ as a little Java environment, mainly for learning Java as I was having some difficulty getting a simple program to work with NetBeans, unfortunately all the advice on setting up Notepad++ to call the Java code is not working.

I guess notepad++ has changed or the Java development Kit has been massively modified because all examples I have used result in errors, even though there is little room for error.

to begin I found this site:
http://blog.sanaulla.info/2008/07/25/using-notepad-to-compile-and-run-java-programs/

this is the code to run Javac to compile the code:

```<code>javac “$(FILE_NAME)”
</code>```

and

```<code>java “$(NAME_PART)”
</code>```

to run the resulted byte code, however this has absolutely no success at all anymore. Java is properly setup and I can call the Java program to do its thing through CMD.

Using a plugin called npp and called through F6 and run with this code (given in the comments) succeeds in compiling the Java program into the correct .class file, however the command failed in running the program

```<code>cd “$(CURRENT_DIRECTORY)”
javac $(FILE_NAME)
java $(NAME_PART)
</code>```

errors from the console in Notepad++ are:

```<code>java.lang.NoClassDefFoundError: first
Caused by: java.lang.ClassNotFoundException: first
  at java.net.URLClassLoader$1.run(Unknown Source)
  at java.security.AccessController.doPrivileged(Native Method)
  at java.net.URLClassLoader.findClass(Unknown Source)
  at java.lang.ClassLoader.loadClass(Unknown Source)
  at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
  at java.lang.ClassLoader.loadClass(Unknown Source)
Could not find the main class: first.  Program will exit.
Exception in thread "main"
</code>```

I figured setting up Notepad++ to compile and run the code would be easy and fun, but its seems all documentation on the internet is outdated as nothing works.

I would like a easy way to compile and run Java code from within Notepad++

I could just used CMD but i'd rather it be more integrated into notepad++

Thanks for any possible help. cheers :)

EDIT: I'm using the latest version of Java, notepad++ and have Windows 7

EDIT 2: the code:

```<code> //A Very Simple Example
 class ExampleProgram {

   public static void main(String[] args){

        System.out.println("I'm a Simple Program");
   }
 }
</code>```

答:
The 'learning curve' associated with IDEs like Eclipse or Netbeans initially mostly involves what you already have above - knowledge of setting class paths, environment variables and so on.  Instead of Notepad++ (which I love, but it's not 'made' for Java), I'd recommend Eclipse especially if you have a grunty PC (it's a bit memory hungry).  Aside from getting the paths setup, after that you'll be ready to rock.

And Eclipse being actively and openly developed is one of the most documented IDEs out there. The tutorials are bound to work correctly for it :). But seriously, it's pretty good. And then when you want to expand to Android development in Java, or some other type of Java programming, you just load up the add-ins required, and you're away laughing. It also supports debugging, the likes of which Notepad++ certainly cannot compete.

ContentLicense: CC BY-SA 2.5

Title: Using Notepad++ to compile Java code

Body:
I've been trying to set up Notepad++ as a little Java environment, mainly for learning Java as I was having some difficulty getting a simple program to work with NetBeans, unfortunately all the advice on setting up Notepad++ to call the Java code is not working.

I guess notepad++ has changed or the Java development Kit has been massively modified because all examples I have used result in errors, even though there is little room for error.

to begin I found this site:
http://blog.sanaulla.info/2008/07/25/using-notepad-to-compile-and-run-java-programs/

this is the code to run Javac to compile the code:

javac “$(FILE_NAME)”

and

java “$(NAME_PART)”

to run the resulted byte code, however this has absolutely no success at all anymore. Java is properly setup and I can call the Java program to do its thing through CMD.

Using a plugin called npp and called through F6 and run with this code (given in the comments) succeeds in compiling the Java program into the correct .class file, however the command failed in running the program

cd “$(CURRENT_DIRECTORY)”
javac $(FILE_NAME)
java $(NAME_PART)

errors from the console in Notepad++ are:

java.lang.NoClassDefFoundError: first
Caused by: java.lang.ClassNotFoundException: first
  at java.net.URLClassLoader$1.run(Unknown Source)
  at java.security.AccessController.doPrivileged(Native Method)
  at java.net.URLClassLoader.findClass(Unknown Source)
  at java.lang.ClassLoader.loadClass(Unknown Source)
  at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
  at java.lang.ClassLoader.loadClass(Unknown Source)
Could not find the main class: first.  Program will exit.
Exception in thread "main"

I figured setting up Notepad++ to compile and run the code would be easy and fun, but its seems all documentation on the internet is outdated as nothing works.

I would like a easy way to compile and run Java code from within Notepad++

I could just used CMD but i'd rather it be more integrated into notepad++

Thanks for any possible help. cheers :)

EDIT: I'm using the latest version of Java, notepad++ and have Windows 7

EDIT 2: the code:

 //A Very Simple Example
 class ExampleProgram {

   public static void main(String[] args){

        System.out.println("I'm a Simple Program");
   }
 }


问:
SAPUI5/Fiori Export to excel -ExportTypeCSV , data formatted prepending a single quote
I am able to export table data to excel dynamically, but some of the data like long numbers and negative values are formatted

Below is the UI Table data
[enter image description here][1]

exported data to CSV
[enter image description here][2]

when I select the long values it showing the proper value on top of excel, and -ve values are appended with '......

Code :

```<code>jQuery.sap.require("sap.ui.core.util.Export");
jQuery.sap.require("sap.ui.core.util.ExportTypeCSV");
sap.ui.define([
'jquery.sap.global',
'sap/ui/core/mvc/Controller',
'sap/ui/model/json/JSONModel'
], function(jQuery, Controller, JSONModel) {
"use strict";
var vSrcMATNR;
var oEvtBus = sap.ui.getCore().getEventBus();
var TableController = Controller.extend("UtilLoad.Util", {
exportToExcel: function(oTable) {
var that = this;
var aColumns = oTable.getColumns();
var aItems = oTable.getItems();
var aTemplate = [];
for (var i = 0; i < aColumns.length; i++) {
var oColumn = {
name: aColumns[i].getHeader().getText(),
template: {
content: {
path: null
}
}
};
if (aItems.length > 0) {
oColumn.template.content.path = aItems[0].getCells()[i].getBinding("text").getPath();
}
aTemplate.push(oColumn);
}
var oExport = new sap.ui.core.util.Export({
// Type that will be used to generate the content. Own ExportType’s can be created to support other formats
exportType: new sap.ui.core.util.ExportTypeCSV({
separatorChar : ",",
                charset : "utf-8"
}),
// Pass in the model created above
models: oTable.getModel(),
// binding information for the rows aggregation
rows: {
path: "/"
},
// column definitions with column name and binding info for the content
columns: aTemplate
});
oExport.saveFile().always(function() {
this.destroy();
});
},
fnDate: function(sDate) {
if (sDate) {
var oDateFormat = sap.ui.core.format.DateFormat.getDateTimeInstance({
pattern: "dd-MM-yyyy"
});
return oDateFormat.format(new Date(sDate));
} else {
return sDate;
}
}
});
return TableController;
});
</code>```

from SAP documentation advicing to use data export functionality , please what is it and how

https://openui5.hana.ondemand.com/#docs/api/symbols/sap.ui.core.util.ExportTypeCSV.html

Thanks
Rajesh

答:
please find below screen shot
 exported excel data</p>

Body:
I am able to export table data to excel dynamically, but some of the data like long numbers and negative values are formatted

Below is the UI Table data
[enter image description here][1]

exported data to CSV
[enter image description here][2]

when I select the long values it showing the proper value on top of excel, and -ve values are appended with '......

Code :

jQuery.sap.require("sap.ui.core.util.Export");
jQuery.sap.require("sap.ui.core.util.ExportTypeCSV");
sap.ui.define([
'jquery.sap.global',
'sap/ui/core/mvc/Controller',
'sap/ui/model/json/JSONModel'
], function(jQuery, Controller, JSONModel) {
"use strict";
var vSrcMATNR;
var oEvtBus = sap.ui.getCore().getEventBus();
var TableController = Controller.extend("UtilLoad.Util", {
exportToExcel: function(oTable) {
var that = this;
var aColumns = oTable.getColumns();
var aItems = oTable.getItems();
var aTemplate = [];
for (var i = 0; i < aColumns.length; i++) {
var oColumn = {
name: aColumns[i].getHeader().getText(),
template: {
content: {
path: null
}
}
};
if (aItems.length > 0) {
oColumn.template.content.path = aItems[0].getCells()[i].getBinding("text").getPath();
}
aTemplate.push(oColumn);
}
var oExport = new sap.ui.core.util.Export({
// Type that will be used to generate the content. Own ExportType’s can be created to support other formats
exportType: new sap.ui.core.util.ExportTypeCSV({
separatorChar : ",",
                charset : "utf-8"
}),
// Pass in the model created above
models: oTable.getModel(),
// binding information for the rows aggregation
rows: {
path: "/"
},
// column definitions with column name and binding info for the content
columns: aTemplate
});
oExport.saveFile().always(function() {
this.destroy();
});
},
fnDate: function(sDate) {
if (sDate) {
var oDateFormat = sap.ui.core.format.DateFormat.getDateTimeInstance({
pattern: "dd-MM-yyyy"
});
return oDateFormat.format(new Date(sDate));
} else {
return sDate;
}
}
});
return TableController;
});

from SAP documentation advicing to use data export functionality , please what is it and how

https://openui5.hana.ondemand.com/#docs/api/symbols/sap.ui.core.util.ExportTypeCSV.html

Thanks
Rajesh


问:
Custom UISlider using UIEdgedInset does not render well
I'm trying to do a custom uislider using images (without a visible knob, i hide it when user can't edit and show it when he can) The problem is that the the side render perfectly but the right part is cute and doesn't seems to use the edges...
Any idea how i can edit it ?

Actual code :

```<code>    let capLeft:CGFloat =  9
    let capRight:CGFloat = 9
    imageMin = imageMinimum?.resizableImage(withCapInsets: UIEdgeInsets(top: 0, left: capLeft, bottom: 0, right: capRight), resizingMode: .stretch)
    imageMax = imageMaximum
    slider.setMaximumTrackImage(imageMax, for: UIControlState())
    slider.setMinimumTrackImage(imageMin, for: UIControlState())
</code>```

How it's rendering :

How it should render :

Minimum track image :

Maximum Tracking Image :

Do you have any idea ?

答:
I think there is a bit of confusion about Min and Max images with UISlider.

The Min image is drawn (and stretched) on the Left side of the Thumb. The Max image is drawn (and stretched) on the Right side of the Thumb.

Create a small, square solid red image - such as 16x16 - and assign it (without insets) to .setMaximumTrackImage. See how that ends up looking, as you go from low to high values.

Edit: I used NO insets on the Min image for this example...

Note: I used a 20x20 clear image for the Thumb in these caps.

Body:
I'm trying to do a custom uislider using images (without a visible knob, i hide it when user can't edit and show it when he can) The problem is that the the side render perfectly but the right part is cute and doesn't seems to use the edges...
Any idea how i can edit it ?

Actual code :

    let capLeft:CGFloat =  9
    let capRight:CGFloat = 9
    imageMin = imageMinimum?.resizableImage(withCapInsets: UIEdgeInsets(top: 0, left: capLeft, bottom: 0, right: capRight), resizingMode: .stretch)
    imageMax = imageMaximum
    slider.setMaximumTrackImage(imageMax, for: UIControlState())
    slider.setMinimumTrackImage(imageMin, for: UIControlState())

How it's rendering :

How it should render :

Minimum track image :

Maximum Tracking Image :

Do you have any idea ?


问:
What is the most efficient algorithm to detect and remove duplicates in a Collection?
What is the most efficient way to detect and remove duplicates in any Collection? I use the following method:

```<code>static class Link{
    Link(Link next1,Object val1){
        next = next1;
        val = val1;
    }
    Link next;
    Object val;
}
public static void removeDuplicates(Collection<?> collection){
    Link link = null;
    Iterator<?> itr = collection.iterator();
    a: while(itr.hasNext()){//Iterate the parameter Collection or corrupted Set
        Object obj = itr.next();
        Link c = link;
        while(c != null){
            if(obj.equals(c.val)){
                itr.remove();//Duplicate found!
                continue a;
            }
            c = c.next;
        }
        link = new Link(link,obj);
    }
}
</code>```

Is there a faster (or better) way to remove duplicates?

答:
If you change an object in a hash-based collection such that the hashcode / equals contract is violated, the behavior of the set is unspecified.  It certainly isn't guaranteed to have "set like" semantics with respect to the API.  Thus, there is no solution to your problem that the specs (i.e. the javadoc) will guarantee to work.

In practice, the most-likely-to-work solution would be to iterate the set entries and add them to a new (empty) set.  Using addAll would be equivalent.  This is (of course) very expensive.

But the real solution is to avoid getting the problem in the first place.  If you put mutable objects into collections that rely on stable equality & hashcodes OR stable ordering, then remove them before you mutate them; e.g.

```<code>set.remove(e);
e.mutate();
set.add(e);
</code>```

Body:
What is the most efficient way to detect and remove duplicates in any Collection? I use the following method:

static class Link{
    Link(Link next1,Object val1){
        next = next1;
        val = val1;
    }
    Link next;
    Object val;
}
public static void removeDuplicates(Collection<?> collection){
    Link link = null;
    Iterator<?> itr = collection.iterator();
    a: while(itr.hasNext()){//Iterate the parameter Collection or corrupted Set
        Object obj = itr.next();
        Link c = link;
        while(c != null){
            if(obj.equals(c.val)){
                itr.remove();//Duplicate found!
                continue a;
            }
            c = c.next;
        }
        link = new Link(link,obj);
    }
}

Is there a faster (or better) way to remove duplicates?

Body:
If you change an object in a hash-based collection such that the hashcode / equals contract is violated, the behavior of the set is unspecified.  It certainly isn't guaranteed to have "set like" semantics with respect to the API.  Thus, there is no solution to your problem that the specs (i.e. the javadoc) will guarantee to work.

In practice, the most-likely-to-work solution would be to iterate the set entries and add them to a new (empty) set.  Using addAll would be equivalent.  This is (of course) very expensive.

But the real solution is to avoid getting the problem in the first place.  If you put mutable objects into collections that rely on stable equality & hashcodes OR stable ordering, then remove them before you mutate them; e.g.

set.remove(e);
e.mutate();
set.add(e);


问:
Visual Studio debugging/loading very slow
I'm at wit's end. Visual Studio is typically painfully slow to debug or just plain load ("start without debugging") my ASP.NET MVC sites. Not always: at first, the projects will load nice and fast, but once they load slow, they'll always load slowly after that. I could be waiting 1-2 minutes or more.

My setup:

I'm using Visual Studio 2012 Express, currently, but I've had the same problem in Visual Studio 2010 Express as well. My solution is stored on a network drive; specifically, it's My Documents redirected to a network drive, if it matters. (It shouldn't. There are times where my site loads very fast under this setup.)

I load in Internet  Explorer 9 usually, but the same problem happens in Firefox.

This can happen in any ASP.NET MVC project I work on, and it seems to revolve around having DisplayTemplates, which all my ASP.NET MVC projects do. And it's all C# and Razor if that mattered.

Symptoms:

The system will load my symbols hundreds of times. Basically, the following, but there are at least 300 such rows, each with ever-so-slightly different DLL files for the same CSHTMLs:

```<code>'iisexpress.exe' (Managed (v4.0.30319)): Loaded 'C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files\root\b63f8236\6775085d\App_Web_contact.cshtml.22013bb9.xighmhow.dll', Symbols loaded.
'iisexpress.exe' (Managed (v4.0.30319)): Loaded 'C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files\root\b63f8236\6775085d\App_Web_contact.cshtml.22013bb9.cv5hktkf.dll', Symbols loaded.
'iisexpress.exe' (Managed (v4.0.30319)): Loaded 'C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files\root\b63f8236\6775085d\App_Web_statuscode.cshtml.22013bb9.1o77hs8i.dll', Symbols loaded.
'iisexpress.exe' (Managed (v4.0.30319)): Loaded 'C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files\root\b63f8236\6775085d\App_Web_statuscode.cshtml.22013bb9.jja-77mw.dll', Symbols loaded.
'iisexpress.exe' (Managed (v4.0.30319)): Loaded 'C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files\root\b63f8236\6775085d\App_Web_location.cshtml.22013bb9.l_e9ev_s.dll', Symbols loaded.
'iisexpress.exe' (Managed (v4.0.30319)): Loaded 'C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files\root\b63f8236\6775085d\App_Web_location.cshtml.22013bb9.b4n59gom.dll', Symbols loaded.
</code>```

In the above, I've got three DisplayTemplates: "Contact", "Location", and "StatusCode". It appears that IIS is loading symbols twice for each time the display template gets called. Thus, if I'm displaying a table of 100 entries that call all three of these display templates, it's 600 separate symbols loaded.

This isn't a fast operation either. The log files that IIS generates take about 200  ms for each symbol to load. Thus, super-long delays.

What I've Tried:

Debug or Release version, it doesn't matter.

Putting my project on a full IIS implementation on a web server runs it super fast with no problems.

Cassini, IIS  Express 7.5, and IIS  Express 8.0 all have the problem.

Delete All Breakpoints does nothing.

Clean Solution, or deleting the .suo also do nothing.

If I repair IIS  Express/ delete the My Docs\IISExpress folder, or repair/reinstall Visual Studio → the issue MAY go away, but only for a while before it comes right back.

Any advice at all is appreciated.

To answer more questions, yes my machine definitely has horsepower. The infuriating thing is that the same project, with NOTHING altered, can sometimes load very quickly, typically after I repair IIS  Express and delete the My Docs\IISExpress folder. Eventually, "something" happens and it's down to 2 minutes to load again. What I'm working on is not a complicated project. No external libraries or dependencies and my VS.NET has no add-ons whatsoever.

Of note, this machine has Symantec Endpoint Protection, which has a history of causing havoc. But disabling it outright (it's good to be an administrator) did not fix the problem.

I have a theory at this point. I'm thinking this is all because I'm working off a redirected folder off a network share. While the debugger was going through its hundreds of "loaded symbols" lines, I paused to see what it was doing. It was in my code, loading the DisplayTemplate I had. Stepping into the template output this:

```<code>Step into: Stepping over non-user code 'System.Threading.WaitHandle.InternalWaitOne'
Step into: Stepping over non-user code 'System.Threading.WaitHandle.WaitOne'
Step into: Stepping over non-user code 'System.CodeDom.Compiler.Executor.ExecWaitWithCaptureUnimpersonated'
Step into: Stepping over non-user code 'System.CodeDom.Compiler.Executor.ExecWaitWithCapture'
Step into: Stepping over non-user code 'Microsoft.CSharp.CSharpCodeGenerator.FromFileBatch'
Step into: Stepping over non-user code 'Microsoft.CSharp.CSharpCodeGenerator.System.CodeDom.Compiler.ICodeCompiler.CompileAssemblyFromFileBatch'
Step into: Stepping over non-user code 'System.Web.Compilation.AssemblyBuilder.Compile'
'iisexpress.exe' (Managed (v4.0.30319)): Loaded 'C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files\root\b63f8236\6775085d\App_Web_statuscode.cshtml.22013bb9.bciuyg14.dll', Symbols loaded.
Step into: Stepping over non-user code 'System.Web.Compilation.BuildManager.CompileWebFile'
Step into: Stepping over non-user code 'System.Web.Compilation.BuildManager.GetVPathBuildResultInternal'
Step into: Stepping over non-user code 'System.Web.Compilation.BuildManager.GetVPathBuildResultWithNoAssert'
Step into: Stepping over non-user code 'System.Web.Compilation.BuildManager.GetVirtualPathObjectFactory'
Step into: Stepping over non-user code 'System.Web.Mvc.BuildManagerWrapper.System.Web.Mvc.IBuildManager.FileExists'
Step into: Stepping over non-user code 'System.Web.Mvc.VirtualPathProviderViewEngine.GetPathFromGeneralName'
Step into: Stepping over non-user code 'System.Web.Mvc.VirtualPathProviderViewEngine.FindPartialView'
Step into: Stepping over non-user code 'System.Web.Mvc.ViewEngineCollection.Find'
Step into: Stepping over non-user code 'System.Web.Mvc.ViewEngineCollection.FindPartialView'
Step into: Stepping over non-user code 'System.Web.Mvc.Html.TemplateHelpers.ActionCacheViewItem.Execute'
'iisexpress.exe' (Managed (v4.0.30319)): Loaded 'C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files\root\b63f8236\6775085d\App_Web_statuscode.cshtml.22013bb9.kwj3uqan.dll', Symbols loaded.
Step into: Stepping over non-user code 'System.RuntimeType.CreateInstanceSlow'
Step into: Stepping over non-user code 'System.Web.Mvc.DependencyResolver.DefaultDependencyResolver.GetService'
Step into: Stepping over non-user code 'System.Web.Mvc.BuildManagerViewEngine.DefaultViewPageActivator.Create'
Step into: Stepping over non-user code 'System.Web.Mvc.BuildManagerCompiledView.Render'
</code>```

It looks like Visual Studio is recompiling my display template every time it's called, which is again, hundreds of times. My theory is that Visual Studio compiles the file, saves it to the network share, then somehow stamps a new time on it, and Visual Studio then thinks the file has changed. Thus, Visual Studio recompiles it yet again. Only a theory though; I really have no clue.

For one, apparently, I have offline files (this is a desktop computer in an office; I couldn't care less). I'm going to disable, reboot, and retry tomorrow.

Plus, moving my project, as is, to the local C: fixes it. It loads very quickly. But this is not ideal in a work environment. I lose Previous Versions, my code isn't backed up at all unless I manually copy it, and it's no longer shared with anyone.

I can make do with copying it back and forth from C to the network share if it comes to it. It's much more annoying to wait two minutes for every page to load.

答:
For me it was that I was debugging in Managed Compatibility Mode. In Tools -> Options -> Debugging -> General at the bottom, un-check 'Use Managed Compatibility Mode'. Debugging became instantaneous where it used to take up to a minute to step through one line. I suspect that's what the 'Managed' means in OP's snippets above.

More on that here: https://blogs.msdn.microsoft.com/visualstudioalm/2013/10/16/switching-to-managed-compatibility-mode-in-visual-studio-2013/

ContentLicense: CC BY-SA 4.0

Body:
I'm at wit's end. Visual Studio is typically painfully slow to debug or just plain load ("start without debugging") my ASP.NET MVC sites. Not always: at first, the projects will load nice and fast, but once they load slow, they'll always load slowly after that. I could be waiting 1-2 minutes or more.

My setup:

I'm using Visual Studio 2012 Express, currently, but I've had the same problem in Visual Studio 2010 Express as well. My solution is stored on a network drive; specifically, it's My Documents redirected to a network drive, if it matters. (It shouldn't. There are times where my site loads very fast under this setup.)

I load in Internet  Explorer 9 usually, but the same problem happens in Firefox.

This can happen in any ASP.NET MVC project I work on, and it seems to revolve around having DisplayTemplates, which all my ASP.NET MVC projects do. And it's all C# and Razor if that mattered.

Symptoms:

The system will load my symbols hundreds of times. Basically, the following, but there are at least 300 such rows, each with ever-so-slightly different DLL files for the same CSHTMLs:

'iisexpress.exe' (Managed (v4.0.30319)): Loaded 'C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files\root\b63f8236\6775085d\App_Web_contact.cshtml.22013bb9.xighmhow.dll', Symbols loaded.
'iisexpress.exe' (Managed (v4.0.30319)): Loaded 'C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files\root\b63f8236\6775085d\App_Web_contact.cshtml.22013bb9.cv5hktkf.dll', Symbols loaded.
'iisexpress.exe' (Managed (v4.0.30319)): Loaded 'C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files\root\b63f8236\6775085d\App_Web_statuscode.cshtml.22013bb9.1o77hs8i.dll', Symbols loaded.
'iisexpress.exe' (Managed (v4.0.30319)): Loaded 'C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files\root\b63f8236\6775085d\App_Web_statuscode.cshtml.22013bb9.jja-77mw.dll', Symbols loaded.
'iisexpress.exe' (Managed (v4.0.30319)): Loaded 'C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files\root\b63f8236\6775085d\App_Web_location.cshtml.22013bb9.l_e9ev_s.dll', Symbols loaded.
'iisexpress.exe' (Managed (v4.0.30319)): Loaded 'C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files\root\b63f8236\6775085d\App_Web_location.cshtml.22013bb9.b4n59gom.dll', Symbols loaded.

In the above, I've got three DisplayTemplates: "Contact", "Location", and "StatusCode". It appears that IIS is loading symbols twice for each time the display template gets called. Thus, if I'm displaying a table of 100 entries that call all three of these display templates, it's 600 separate symbols loaded.

This isn't a fast operation either. The log files that IIS generates take about 200  ms for each symbol to load. Thus, super-long delays.

What I've Tried:

Debug or Release version, it doesn't matter.

Putting my project on a full IIS implementation on a web server runs it super fast with no problems.

Cassini, IIS  Express 7.5, and IIS  Express 8.0 all have the problem.

Delete All Breakpoints does nothing.

Clean Solution, or deleting the .suo also do nothing.

If I repair IIS  Express/ delete the My Docs\IISExpress folder, or repair/reinstall Visual Studio → the issue MAY go away, but only for a while before it comes right back.

Any advice at all is appreciated.

To answer more questions, yes my machine definitely has horsepower. The infuriating thing is that the same project, with NOTHING altered, can sometimes load very quickly, typically after I repair IIS  Express and delete the My Docs\IISExpress folder. Eventually, "something" happens and it's down to 2 minutes to load again. What I'm working on is not a complicated project. No external libraries or dependencies and my VS.NET has no add-ons whatsoever.

Of note, this machine has Symantec Endpoint Protection, which has a history of causing havoc. But disabling it outright (it's good to be an administrator) did not fix the problem.

I have a theory at this point. I'm thinking this is all because I'm working off a redirected folder off a network share. While the debugger was going through its hundreds of "loaded symbols" lines, I paused to see what it was doing. It was in my code, loading the DisplayTemplate I had. Stepping into the template output this:

Step into: Stepping over non-user code 'System.Threading.WaitHandle.InternalWaitOne'
Step into: Stepping over non-user code 'System.Threading.WaitHandle.WaitOne'
Step into: Stepping over non-user code 'System.CodeDom.Compiler.Executor.ExecWaitWithCaptureUnimpersonated'
Step into: Stepping over non-user code 'System.CodeDom.Compiler.Executor.ExecWaitWithCapture'
Step into: Stepping over non-user code 'Microsoft.CSharp.CSharpCodeGenerator.FromFileBatch'
Step into: Stepping over non-user code 'Microsoft.CSharp.CSharpCodeGenerator.System.CodeDom.Compiler.ICodeCompiler.CompileAssemblyFromFileBatch'
Step into: Stepping over non-user code 'System.Web.Compilation.AssemblyBuilder.Compile'
'iisexpress.exe' (Managed (v4.0.30319)): Loaded 'C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files\root\b63f8236\6775085d\App_Web_statuscode.cshtml.22013bb9.bciuyg14.dll', Symbols loaded.
Step into: Stepping over non-user code 'System.Web.Compilation.BuildManager.CompileWebFile'
Step into: Stepping over non-user code 'System.Web.Compilation.BuildManager.GetVPathBuildResultInternal'
Step into: Stepping over non-user code 'System.Web.Compilation.BuildManager.GetVPathBuildResultWithNoAssert'
Step into: Stepping over non-user code 'System.Web.Compilation.BuildManager.GetVirtualPathObjectFactory'
Step into: Stepping over non-user code 'System.Web.Mvc.BuildManagerWrapper.System.Web.Mvc.IBuildManager.FileExists'
Step into: Stepping over non-user code 'System.Web.Mvc.VirtualPathProviderViewEngine.GetPathFromGeneralName'
Step into: Stepping over non-user code 'System.Web.Mvc.VirtualPathProviderViewEngine.FindPartialView'
Step into: Stepping over non-user code 'System.Web.Mvc.ViewEngineCollection.Find'
Step into: Stepping over non-user code 'System.Web.Mvc.ViewEngineCollection.FindPartialView'
Step into: Stepping over non-user code 'System.Web.Mvc.Html.TemplateHelpers.ActionCacheViewItem.Execute'
'iisexpress.exe' (Managed (v4.0.30319)): Loaded 'C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files\root\b63f8236\6775085d\App_Web_statuscode.cshtml.22013bb9.kwj3uqan.dll', Symbols loaded.
Step into: Stepping over non-user code 'System.RuntimeType.CreateInstanceSlow'
Step into: Stepping over non-user code 'System.Web.Mvc.DependencyResolver.DefaultDependencyResolver.GetService'
Step into: Stepping over non-user code 'System.Web.Mvc.BuildManagerViewEngine.DefaultViewPageActivator.Create'
Step into: Stepping over non-user code 'System.Web.Mvc.BuildManagerCompiledView.Render'

It looks like Visual Studio is recompiling my display template every time it's called, which is again, hundreds of times. My theory is that Visual Studio compiles the file, saves it to the network share, then somehow stamps a new time on it, and Visual Studio then thinks the file has changed. Thus, Visual Studio recompiles it yet again. Only a theory though; I really have no clue.

For one, apparently, I have offline files (this is a desktop computer in an office; I couldn't care less). I'm going to disable, reboot, and retry tomorrow.

Plus, moving my project, as is, to the local C: fixes it. It loads very quickly. But this is not ideal in a work environment. I lose Previous Versions, my code isn't backed up at all unless I manually copy it, and it's no longer shared with anyone.

I can make do with copying it back and forth from C to the network share if it comes to it. It's much more annoying to wait two minutes for every page to load.


问:
MySQL - How to search for exact word match in a column of sentence?
I have a MySQL table with a list of sentences such as:

```<code>id | Sentence
---+---------------------------------------------------------------
 1 | Come On Boys, You Can do it my boy.
 2 | Everything is possible, impossible itself says I am possible.
 3 | Boys I know possible solutions are good!
 4 | Possible solutions are all failed its also possible
</code>```

I have to search on Sentence column exact word like possible.

There are some condition :

Searching word can't be prefix or suffix of any word.

Searching word possible , impossible is incorrect.

Punctuation mark can be before or after the word.Ex: !boy or boy,

No case sensitive means for possible Possible is correct.

I try a query but it is not working

```<code>mysql_query("SELECT * FROM products WHERE Sentence LIKE '%".$search."%'");
</code>```

Possible punctuation mark are ,.!?;-

I need a working solution. Thanks in advance !

答:
```<code>CREATE TEMPORARY TABLE tmp (id INTEGER PRIMARY KEY AUTO_INCREMENT, sentence VARCHAR(200));

INSERT INTO tmp (sentence) VALUES ('Come On Boys, You Can do it my boy.');
INSERT INTO tmp (sentence) VALUES ('Everything is possible, impossible itself says I am possible.');
INSERT INTO tmp (sentence) VALUES ('Boys I know possible solutions are good!');
INSERT INTO tmp (sentence) VALUES ('Possible solutions are all failed its also possible');

SELECT * FROM tmp WHERE sentence REGEXP '[[:<:]]impossible[[:>:]]';
</code>```

This is duplicate: Search for "whole word match" in MySQL

Body:
I have a MySQL table with a list of sentences such as:

id | Sentence
---+---------------------------------------------------------------
 1 | Come On Boys, You Can do it my boy.
 2 | Everything is possible, impossible itself says I am possible.
 3 | Boys I know possible solutions are good!
 4 | Possible solutions are all failed its also possible

I have to search on Sentence column exact word like possible.

There are some condition :

Searching word can't be prefix or suffix of any word.

Searching word possible , impossible is incorrect.

Punctuation mark can be before or after the word.Ex: !boy or boy,

No case sensitive means for possible Possible is correct.

I try a query but it is not working

mysql_query("SELECT * FROM products WHERE Sentence LIKE '%".$search."%'");

Possible punctuation mark are ,.!?;-

I need a working solution. Thanks in advance !

Body:
CREATE TEMPORARY TABLE tmp (id INTEGER PRIMARY KEY AUTO_INCREMENT, sentence VARCHAR(200));

INSERT INTO tmp (sentence) VALUES ('Come On Boys, You Can do it my boy.');
INSERT INTO tmp (sentence) VALUES ('Everything is possible, impossible itself says I am possible.');
INSERT INTO tmp (sentence) VALUES ('Boys I know possible solutions are good!');
INSERT INTO tmp (sentence) VALUES ('Possible solutions are all failed its also possible');

SELECT * FROM tmp WHERE sentence REGEXP '[[:<:]]impossible[[:>:]]';

This is duplicate: Search for "whole word match" in MySQL


问:
insertMapObject Function Android Returning 23 code Cartotype
Firstly, Cartotype provides API for providing the Map in Android,iOS and other platforms  as per my knowledge .

from the docs i found a function that meets my need

```<code>native int com.cartotype.Framework.insertMapObject  (   int     aMapHandle,
int     aMapObjectType,
String  aLayerName,
Geometry    aGeometry,
String  aStringAttributes,
int     aIntAttribute,
long    aId,
boolean     aReplace
)
</code>```

But the parameters they refer to i couldn't be successful in getting those and finally got as

```<code>// Second or continuing measurement, add to arrays
// and draw line
iDistanceMeasurementX = extendArray(
iDistanceMeasurementX, thisPoint[0]);
iDistanceMeasurementY = extendArray(
iDistanceMeasurementY, thisPoint[1]);

// _thread.iFramework.deleteMapObjects(0,
// ID_MEASUREMENT_TOOL, ID_MEASUREMENT_TOOL, null);
// _thread.iFramework.addLineOrPolygonObject(
// "measurementtool", iDistanceMeasurementX,
// iDistanceMeasurementY,
// Framework.DEGREE_COORDS, null, 0,
// ID_MEASUREMENT_TOOL, false);

//Drawing line geometry
Geometry geometry = new Geometry(Framework.DEGREE_COORDS);
geometry.appendPoint(thisPoint[0],thisPoint[1]);
geometry.beginContour();

 try {
                                int abc = _thread.iFramework.insertMapObject(0, MapObject.LINE_TYPE, "measurementtool", geometry, null, 0,
                                        ID_MEASUREMENT_TOOL, false);
                                Toast.makeText(getContext(),abc,Toast.LENGTH_SHORT).show();
                            } catch (Exception e) {
                                e.printStackTrace();
                            }

//Drawing line with coordinates
// _thread.iFramework.insertPointMapObject(0,"measurementtool", iDistanceMeasurementX[0],iDistanceMeasurementY[0] ,MapObject.LINE_TYPE, "", 0,
// ID_MEASUREMENT_TOOL, false);
//Toast.makeText(getContext(),"Draw Line ",Toast.LENGTH_SHORT).show();
getMapAndDraw(); // Inefficient, we are drawing
</code>```

Those 'abc' int returns a value 23 and needs to be 0,if success according to the docs.

MY NEED IS DRAW A LINE b\w 2 Coordinates

Any help will be appreciated

答:
Thanks @Graham</p>

```<code>geometry = new Geometry(Framework.DEGREE_COORDS);

   iDistanceMeasurementX = extendArray(
                                    iDistanceMeasurementX, thisPoint[0]);
                            iDistanceMeasurementY = extendArray(
                                    iDistanceMeasurementY, thisPoint[1]);
geometry.appendPoint(iDistanceMeasurementX[iDistanceMeasurementX.length-1], iDistanceMeasurementY[iDistanceMeasurementY.length-1]);

                            //Drawing line geometry

                                _thread.iFramework.insertMapObject(0, MapObject.LINE_TYPE, "measurementtool", geometry, null, 0,
                                        0, false);
</code>```

Body:
Firstly, Cartotype provides API for providing the Map in Android,iOS and other platforms  as per my knowledge .

from the docs i found a function that meets my need

native int com.cartotype.Framework.insertMapObject  (   int     aMapHandle,
int     aMapObjectType,
String  aLayerName,
Geometry    aGeometry,
String  aStringAttributes,
int     aIntAttribute,
long    aId,
boolean     aReplace
)

But the parameters they refer to i couldn't be successful in getting those and finally got as

// Second or continuing measurement, add to arrays
// and draw line
iDistanceMeasurementX = extendArray(
iDistanceMeasurementX, thisPoint[0]);
iDistanceMeasurementY = extendArray(
iDistanceMeasurementY, thisPoint[1]);

// _thread.iFramework.deleteMapObjects(0,
// ID_MEASUREMENT_TOOL, ID_MEASUREMENT_TOOL, null);
// _thread.iFramework.addLineOrPolygonObject(
// "measurementtool", iDistanceMeasurementX,
// iDistanceMeasurementY,
// Framework.DEGREE_COORDS, null, 0,
// ID_MEASUREMENT_TOOL, false);

//Drawing line geometry
Geometry geometry = new Geometry(Framework.DEGREE_COORDS);
geometry.appendPoint(thisPoint[0],thisPoint[1]);
geometry.beginContour();

 try {
                                int abc = _thread.iFramework.insertMapObject(0, MapObject.LINE_TYPE, "measurementtool", geometry, null, 0,
                                        ID_MEASUREMENT_TOOL, false);
                                Toast.makeText(getContext(),abc,Toast.LENGTH_SHORT).show();
                            } catch (Exception e) {
                                e.printStackTrace();
                            }

//Drawing line with coordinates
// _thread.iFramework.insertPointMapObject(0,"measurementtool", iDistanceMeasurementX[0],iDistanceMeasurementY[0] ,MapObject.LINE_TYPE, "", 0,
// ID_MEASUREMENT_TOOL, false);
//Toast.makeText(getContext(),"Draw Line ",Toast.LENGTH_SHORT).show();
getMapAndDraw(); // Inefficient, we are drawing

Those 'abc' int returns a value 23 and needs to be 0,if success according to the docs.

MY NEED IS DRAW A LINE b\w 2 Coordinates

Any help will be appreciated

Body:
Thanks @Graham

geometry = new Geometry(Framework.DEGREE_COORDS);

   iDistanceMeasurementX = extendArray(
                                    iDistanceMeasurementX, thisPoint[0]);
                            iDistanceMeasurementY = extendArray(
                                    iDistanceMeasurementY, thisPoint[1]);
geometry.appendPoint(iDistanceMeasurementX[iDistanceMeasurementX.length-1], iDistanceMeasurementY[iDistanceMeasurementY.length-1]);

                            //Drawing line geometry

                                _thread.iFramework.insertMapObject(0, MapObject.LINE_TYPE, "measurementtool", geometry, null, 0,
                                        0, false);


问:
Can't import MySQL database due to syntax error
But why?
I've imported it in OS X and on another Linux machine,
this one however plain refuses..

Where am I going wrong?

Output:

mysql> mysql -u root -p explore < /tmp/explore.sql;

ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'mysql -u root -p explore < /tmp/explore.sql' at line 1

答:
try to execute this

```<code>source /tmp/explore.sql;
</code>```

after logging in mysql prompt

or

get out from the mysql prompt you are already there and run the command you are trying.
Thanks

Body:
try to execute this

source /tmp/explore.sql;

after logging in mysql prompt

or

get out from the mysql prompt you are already there and run the command you are trying.
Thanks


问:
How do I filter items by email field in Podio API for PHP?
I need to get an item from a collection of items that contains the email address <my-email>

Here is the structure of that part of the object:

```<code>[2] => PodioEmailItemField Object
                            (
                                [__attributes:PodioObject:private] => Array
                                    (
                                        [field_id] => <my-field-id>
                                        [type] => email
                                        [external_id] => email
                                        [label] => Email
                                        [values] => Array
                                            (
                                                [0] => Array
                                                    (
                                                        [type] => work
                                                        [value] => <my-email>
                                                    )

                                            )
</code>```

This is the code I have tried:

```<code>$items = PodioItem::filter($app_id, array('filters'=>
                                    array(
                                          'email'=>
                                           array(
                                                'values'=>
                                                 array(
                                                       array(
                                                             'value'=>'<my-email>'))))));
</code>```

but i keep getting the error:

```<code>Fatal error: Uncaught PodioBadRequestError: "Invalid value {"values": [{"value": "<my-email>"}]} (object): must be array"
</code>```

What am I missing here?

I would prefer to find this item using the external_id rather than the field_id

答:
```<code>$items = \PodioItem::filter($app_id, [
    'filters' => [
        // replace 123456 with field ID for your field with email type
        '123456' => [
            'test1@example.com',
            // 'test2@example.com',
            // 'test3@example.com'
        ]
    ]
]);
</code>```

In the "Developer" section of your app you can find the field ID for your field with email type.

If you will call filter by multiple emails, then Podio will return the result, if one of them will be found.

Body:
I need to get an item from a collection of items that contains the email address <my-email>

Here is the structure of that part of the object:

[2] => PodioEmailItemField Object
                            (
                                [__attributes:PodioObject:private] => Array
                                    (
                                        [field_id] => <my-field-id>
                                        [type] => email
                                        [external_id] => email
                                        [label] => Email
                                        [values] => Array
                                            (
                                                [0] => Array
                                                    (
                                                        [type] => work
                                                        [value] => <my-email>
                                                    )

                                            )

This is the code I have tried:

$items = PodioItem::filter($app_id, array('filters'=>
                                    array(
                                          'email'=>
                                           array(
                                                'values'=>
                                                 array(
                                                       array(
                                                             'value'=>'<my-email>'))))));

but i keep getting the error:

Fatal error: Uncaught PodioBadRequestError: "Invalid value {"values": [{"value": "<my-email>"}]} (object): must be array"

What am I missing here?

I would prefer to find this item using the external_id rather than the field_id

Body:
$items = \PodioItem::filter($app_id, [
    'filters' => [
        // replace 123456 with field ID for your field with email type
        '123456' => [
            'test1@example.com',
            // 'test2@example.com',
            // 'test3@example.com'
        ]
    ]
]);

In the "Developer" section of your app you can find the field ID for your field with email type.

If you will call filter by multiple emails, then Podio will return the result, if one of them will be found.


问:
Bootstrap 3 Tabs - Accessability
Are Bootstrap 3 tabs not accessible according to WAI ?

I found the WAI-ARIA specification for tabs keyboard behavior:

https://www.w3.org/TR/wai-aria-practices-1.1/examples/tabs/tabs.html

https://www.w3.org/TR/wai-aria-practices/#tabpanel

which basically says:

When focus is on a tab element in a horizontal tab list:
  Left Arrow: moves focus to the previous tab. If focus is on the first tab, moves focus to the last tab. Optionally, activates the newly focused tab (See note below).
  Right Arrow: Moves focus to the next tab. If focus is on the last tab element, moves focus to the first tab. Optionally, activates the newly focused tab (See note below).

as it seems Bootstrap 3 tabs documentation samples fail to meet those requirements.
pressing Left and right arrow keys, have no effect what so ever.

```<code><ul class="nav nav-tabs">
  <li role="presentation" class="active"><a href="#">Home</a></li>
  <li role="presentation"><a href="#">Profile</a></li>
  <li role="presentation"><a href="#">Messages</a></li>
</ul>
</code>```

do i have to implement this behavior by myself ? or am i missing a magic attribute\class that does all the hard work for me ?

答:
As there is no official support of WAI-ARAI in Bootstrap 3. As mentioned by @ZimSystem that it could be done using role="tablist", role="tab" etc..

Solution with JS using attributes role="tablist", role="tab", Try this:

Check Demo Here

HTML:

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

  <h2>Bootstrap 3 Tabs - Accessability</h2></div>

<div id="exTab2" class="container">
  <ul class="nav nav-tabs">
    <li class="active">
      <a href="#1" data-toggle="tab">Overview</a>
    </li>
    <li><a href="#2" data-toggle="tab">Without clearfix</a>
    </li>
    <li><a href="#3" data-toggle="tab">Solution</a>
    </li>
  </ul>

  <div class="tab-content ">
    <div class="tab-pane active" id="1">
      <h3>Standard tab panel created on bootstrap using nav-tabs</h3>
    </div>
    <div class="tab-pane" id="2">
      <h3>Notice the gap between the content and tab after applying a background color</h3>
    </div>
    <div class="tab-pane" id="3">
      <h3>add clearfix to tab-content (see the css)</h3>
    </div>
  </div>
</div>
</code>```

JS:

```<code>$(function() {
  var tabs = $("#exTab2");

  // For each individual tab DIV, set class and aria role attributes, and hide it
  $(tabs).find(".tab-content > div.tab-pane").attr({
    "class": "tabPanel",
    "role": "tabpanel",
    "aria-hidden": "true"
  }).hide();

  // Get the list of tab links
  var tabsList = tabs.find("ul:first").attr({
    "role": "tablist"
  });

  // For each item in the tabs list...
  $(tabsList).find("li > a").each(
    function(a) {
      var tab = $(this);

      // Create a unique id using the tab link's href
      var tabId = "tab-" + tab.attr("href").slice(1);

      // Assign tab id, aria and tabindex attributes to the tab control, but do not remove the href
      tab.attr({
        "id": tabId,
        "role": "tab",
        "aria-selected": "false",
        "tabindex": "-1"
      }).parent().attr("role", "presentation");

      // Assign aria attribute to the relevant tab panel
      $(tabs).find(".tabPanel").eq(a).attr("aria-labelledby", tabId);

      // Set the click event for each tab link
      tab.click(
        function(e) {
          // Prevent default click event
          e.preventDefault();

          // Change state of previously selected tabList item
          $(tabsList).find("> li.active").removeClass("active").find("> a").attr({
            "aria-selected": "false",
            "tabindex": "-1"
          });

          // Hide previously selected tabPanel
          $(tabs).find(".tabPanel:visible").attr("aria-hidden", "true").hide();

          // Show newly selected tabPanel
          $(tabs).find(".tabPanel").eq(tab.parent().index()).attr("aria-hidden", "false").show();

          // Set state of newly selected tab list item
          tab.attr({
            "aria-selected": "true",
            "tabindex": "0"
          }).parent().addClass("active");
          tab.focus();
        }
      );
    }
  );

  // Set keydown events on tabList item for navigating tabs
  $(tabsList).delegate("a", "keydown",
    function(e) {
      var tab = $(this);
      switch (e.which) {
        case 37:
          //case 38:
          if (tab.parent().prev().length != 0) {
            tab.parent().prev().find("> a").click();
          } else {
            $(tabsList).find("li:last > a").click();
          }
          break;
        case 39:
          //case 40:
          if (tab.parent().next().length != 0) {
            tab.parent().next().find("> a").click();
          } else {
            $(tabsList).find("li:first > a").click();
          }
          break;
      }
    }
  );

  // Show the first tabPanel
  $(tabs).find(".tabPanel:first").attr("aria-hidden", "false").show();

  // Set state for the first tabsList li
  $(tabsList).find("li:first").addClass("active").find(" > a").attr({
    "aria-selected": "true",
    "tabindex": "0"
  });
});
</code>```

Title: Bootstrap 3 Tabs - Accessability

Body:
Are Bootstrap 3 tabs not accessible according to WAI ?

I found the WAI-ARIA specification for tabs keyboard behavior:

https://www.w3.org/TR/wai-aria-practices-1.1/examples/tabs/tabs.html

https://www.w3.org/TR/wai-aria-practices/#tabpanel

which basically says:

When focus is on a tab element in a horizontal tab list:
  Left Arrow: moves focus to the previous tab. If focus is on the first tab, moves focus to the last tab. Optionally, activates the newly focused tab (See note below).
  Right Arrow: Moves focus to the next tab. If focus is on the last tab element, moves focus to the first tab. Optionally, activates the newly focused tab (See note below).

as it seems Bootstrap 3 tabs documentation samples fail to meet those requirements.
pressing Left and right arrow keys, have no effect what so ever.

Home

Profile

Messages

do i have to implement this behavior by myself ? or am i missing a magic attribute\class that does all the hard work for me ?

Body:
As there is no official support of WAI-ARAI in Bootstrap 3. As mentioned by @ZimSystem that it could be done using role="tablist", role="tab" etc..

Solution with JS using attributes role="tablist", role="tab", Try this:

Check Demo Here

HTML:

<div class="container">

  <h2>Bootstrap 3 Tabs - Accessability</h2></div>

<div id="exTab2" class="container">
  <ul class="nav nav-tabs">
    <li class="active">
      <a href="#1" data-toggle="tab">Overview</a>
    </li>
    <li><a href="#2" data-toggle="tab">Without clearfix</a>
    </li>
    <li><a href="#3" data-toggle="tab">Solution</a>
    </li>
  </ul>

  <div class="tab-content ">
    <div class="tab-pane active" id="1">
      <h3>Standard tab panel created on bootstrap using nav-tabs</h3>
    </div>
    <div class="tab-pane" id="2">
      <h3>Notice the gap between the content and tab after applying a background color</h3>
    </div>
    <div class="tab-pane" id="3">
      <h3>add clearfix to tab-content (see the css)</h3>
    </div>
  </div>
</div>

JS:

$(function() {
  var tabs = $("#exTab2");

  // For each individual tab DIV, set class and aria role attributes, and hide it
  $(tabs).find(".tab-content > div.tab-pane").attr({
    "class": "tabPanel",
    "role": "tabpanel",
    "aria-hidden": "true"
  }).hide();

  // Get the list of tab links
  var tabsList = tabs.find("ul:first").attr({
    "role": "tablist"
  });

  // For each item in the tabs list...
  $(tabsList).find("li > a").each(
    function(a) {
      var tab = $(this);

      // Create a unique id using the tab link's href
      var tabId = "tab-" + tab.attr("href").slice(1);

      // Assign tab id, aria and tabindex attributes to the tab control, but do not remove the href
      tab.attr({
        "id": tabId,
        "role": "tab",
        "aria-selected": "false",
        "tabindex": "-1"
      }).parent().attr("role", "presentation");

      // Assign aria attribute to the relevant tab panel
      $(tabs).find(".tabPanel").eq(a).attr("aria-labelledby", tabId);

      // Set the click event for each tab link
      tab.click(
        function(e) {
          // Prevent default click event
          e.preventDefault();

          // Change state of previously selected tabList item
          $(tabsList).find("> li.active").removeClass("active").find("> a").attr({
            "aria-selected": "false",
            "tabindex": "-1"
          });

          // Hide previously selected tabPanel
          $(tabs).find(".tabPanel:visible").attr("aria-hidden", "true").hide();

          // Show newly selected tabPanel
          $(tabs).find(".tabPanel").eq(tab.parent().index()).attr("aria-hidden", "false").show();

          // Set state of newly selected tab list item
          tab.attr({
            "aria-selected": "true",
            "tabindex": "0"
          }).parent().addClass("active");
          tab.focus();
        }
      );
    }
  );

  // Set keydown events on tabList item for navigating tabs
  $(tabsList).delegate("a", "keydown",
    function(e) {
      var tab = $(this);
      switch (e.which) {
        case 37:
          //case 38:
          if (tab.parent().prev().length != 0) {
            tab.parent().prev().find("> a").click();
          } else {
            $(tabsList).find("li:last > a").click();
          }
          break;
        case 39:
          //case 40:
          if (tab.parent().next().length != 0) {
            tab.parent().next().find("> a").click();
          } else {
            $(tabsList).find("li:first > a").click();
          }
          break;
      }
    }
  );

  // Show the first tabPanel
  $(tabs).find(".tabPanel:first").attr("aria-hidden", "false").show();

  // Set state for the first tabsList li
  $(tabsList).find("li:first").addClass("active").find(" > a").attr({
    "aria-selected": "true",
    "tabindex": "0"
  });
});


问:
Android Studio Project Files are Missing
I was working on app and it was opened in Android Studio. It was all perfect but when after some browsing i clicked on android studio window. it says there are no files opened.

and when I checked in file explorer, all of my project files are removed except .idea folder.I did spend a lot of days on it. I cannot let this happen to me. what possible solutions of this problem?

I tried windows folder recovery, no benefit.

答: File > Invalidate Caches & Restart seems to be the solution for most oddities.


问:
How to ignore unknown namespaces with C# XmlReader?
I'm trying to read string XML snippets from input using the XmlReader, manipulate the XDocument and output the result as a string.

In case there is a reference to unknown XML namespace, I just want this reference to be kept, not modified in any way.

Note I don't know the list of possible namespaces, so creating manually namespace whitelist is not an option.

I'm targeting the UWP platform, so XmlTextReader cannot be used here.

Sample of the input XML document:

```<code><VisualState x:Name="Disabled">
    <Storyboard>
        <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Background" Storyboard.TargetName="RootGrid">
            <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource SystemControlBackgroundBaseLowBrush}" />
        </ObjectAnimationUsingKeyFrames>
        <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Foreground" Storyboard.TargetName="ContentPresenter">
            <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource SystemControlDisabledBaseMediumLowBrush}" />
        </ObjectAnimationUsingKeyFrames>
        <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="BorderBrush" Storyboard.TargetName="ContentPresenter">
            <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource SystemControlDisabledTransparentBrush}" />
        </ObjectAnimationUsingKeyFrames>
    </Storyboard>
</VisualState>
</code>```

Sample of the expected output XML document:

```<code><VisualState x:Name="Disabled">
  <VisualState.Setters>
    <Setter Target="RootGrid.Background" Value="{ThemeResource SystemControlBackgroundBaseLowBrush}" />
    <Setter Target="ContentPresenter.Foreground" Value="{ThemeResource SystemControlDisabledBaseMediumLowBrush}" />
    <Setter Target="ContentPresenter.BorderBrush" Value="{ThemeResource SystemControlDisabledTransparentBrush}" />
  </VisualState.Setters>
</VisualState>
</code>```

My current code for parsing the XML:

```<code>using (StringReader sr = new StringReader(xml))
{
    using (XmlReader xtr = XmlReader.Create(sr))
    {
        return XDocument.Load(xtr);
    }
}
</code>```

答:
Not ignoring them but simply accepting whenever one is present.

```<code>xml.Load(fil);
var ns = new XmlNamespaceManager(xml.NameTable);
var nsNode = xml.DocumentElement.Attributes.GetNamedItem("xmlns");
var nsurl = (nsNode != null) ? nsNode.Value : "";

ns.AddNamespace("ns", nsurl);
</code>```

If you now prefix all your XPaths (if any) with "ns:" and pass the namespace manager as argument, you should be fine:

```<code>var nodeList = xml.SelectNodes("//ns:whatever", ns);
</code>```

Edit: This is using XmlDocument, not XDocument, but should get you going too.

Body:
I'm trying to read string XML snippets from input using the XmlReader, manipulate the XDocument and output the result as a string.

In case there is a reference to unknown XML namespace, I just want this reference to be kept, not modified in any way.

Note I don't know the list of possible namespaces, so creating manually namespace whitelist is not an option.

I'm targeting the UWP platform, so XmlTextReader cannot be used here.

Sample of the input XML document:

<VisualState x:Name="Disabled">
    <Storyboard>
        <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Background" Storyboard.TargetName="RootGrid">
            <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource SystemControlBackgroundBaseLowBrush}" />
        </ObjectAnimationUsingKeyFrames>
        <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Foreground" Storyboard.TargetName="ContentPresenter">
            <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource SystemControlDisabledBaseMediumLowBrush}" />
        </ObjectAnimationUsingKeyFrames>
        <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="BorderBrush" Storyboard.TargetName="ContentPresenter">
            <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource SystemControlDisabledTransparentBrush}" />
        </ObjectAnimationUsingKeyFrames>
    </Storyboard>
</VisualState>

Sample of the expected output XML document:

<VisualState x:Name="Disabled">
  <VisualState.Setters>
    <Setter Target="RootGrid.Background" Value="{ThemeResource SystemControlBackgroundBaseLowBrush}" />
    <Setter Target="ContentPresenter.Foreground" Value="{ThemeResource SystemControlDisabledBaseMediumLowBrush}" />
    <Setter Target="ContentPresenter.BorderBrush" Value="{ThemeResource SystemControlDisabledTransparentBrush}" />
  </VisualState.Setters>
</VisualState>

My current code for parsing the XML:

using (StringReader sr = new StringReader(xml))
{
    using (XmlReader xtr = XmlReader.Create(sr))
    {
        return XDocument.Load(xtr);
    }
}

Body:
Not ignoring them but simply accepting whenever one is present.

xml.Load(fil);
var ns = new XmlNamespaceManager(xml.NameTable);
var nsNode = xml.DocumentElement.Attributes.GetNamedItem("xmlns");
var nsurl = (nsNode != null) ? nsNode.Value : "";

ns.AddNamespace("ns", nsurl);

If you now prefix all your XPaths (if any) with "ns:" and pass the namespace manager as argument, you should be fine:

var nodeList = xml.SelectNodes("//ns:whatever", ns);

Edit: This is using XmlDocument, not XDocument, but should get you going too.


问:
Cannot read property call of undefined at Blockly.Generator.blockToCode
I am trying to add a custom text block. But when i enter any text in the input field, the error comes up.
"Uncaught TypeError: Cannot read property 'call' of undefined"</p>

```<code>Blockly.Blocks['text_input']={
init:function()
 {
 this.appendDummyInput()
 .appendField('Text Input:')
 .appendField(new Blockly.FieldTextInput(''),'INPUT');
 this.setColour(170);
 this.setOutput(true);
 }
};
</code>```

答:
this happens when the language definition for your custom type is missing.</p>

```<code>// Replace "JavaScript" with the language you use.
Blockly.JavaScript['text_input'] = function(block) {
  var value = Blockly.JSON.valueToCode(block, 'INPUT', Blockly.JavaScript.ORDER_NONE);

  // do something useful here
  var code = 'var x= "bananas"';
  return code;
};
</code>```

Body:
I am trying to add a custom text block. But when i enter any text in the input field, the error comes up.
"Uncaught TypeError: Cannot read property 'call' of undefined"

Blockly.Blocks['text_input']={
init:function()
 {
 this.appendDummyInput()
 .appendField('Text Input:')
 .appendField(new Blockly.FieldTextInput(''),'INPUT');
 this.setColour(170);
 this.setOutput(true);
 }
};

Body:
this happens when the language definition for your custom type is missing.

// Replace "JavaScript" with the language you use.
Blockly.JavaScript['text_input'] = function(block) {
  var value = Blockly.JSON.valueToCode(block, 'INPUT', Blockly.JavaScript.ORDER_NONE);

  // do something useful here
  var code = 'var x= "bananas"';
  return code;
};


问:
how do I store value that is returned by the function without executing the function again?
so getBoundedNumber() is to let the user input some numbers and return the input. My other functions base on the return value and do calculations. I tried to assign it to a global variable outside the function(like var=getBoundedNumber(...)),but instead of storing the value from function, it executes the function again and ask for user to input again. How do I fix this?Thank you!

```<code>def getBoundedNumber(qq,ww,ee):

    while True:
        try:
            AA = float(input('Enter chain parameter between %r and %r '%(qq,ww)))
            ee='%r is not between %r and %r'%(AA,qq,ww)
            assert type(AA)==float or int,'not a valid input'
            if qq<= AA <= ww:

                break
            else:
            print(ee)
        except ValueError:
            print(' not a valid input')
    exit

return AA
</code>```

This is my main function:

```<code>def MAIN():

while True:

    xx=menu()

    if xx == 'A':
        aa=getBoundedNumber(0.5,4.5,1)

    elif xx == 'N':
        numpoints=getBoundedNumber(10,100000,1)

    elif xx == 'P':

        print('  Parameter a:%20.3f'%aa,'[m]')#console gives me aa not defined
        print('  Number of points:%20d'%numpoints)#console gives me numpoints not defined
        print('  Length:%20.3f'%chainlength(xs,ys),'[m]')#this function requires value from aa and numpoints so it won't execute.
        print('  Angle with support:%20.3f'%anglewithsupport(g_,dd,aa,numpoints))
        print('  Net force:%20.3f'%netforce(),'[N]')

    elif xx == 'Q':
        break
    else:
        print(' not a valid option')

exit
</code>```

This is my menu function

```<code>def menu():
print('Main menu choices')
print('   A - enter chain parameter a' )
print('   N - enter number of points in chain' )
print('   P - calculate and print chain results')
print('   Q - quit program')
while True:
    try:
        SELECTION = input('Enter your selection: ')

        if SELECTION.upper()== 'A':

            break
        elif SELECTION.upper() == 'N':
            break
        elif SELECTION.upper()=='P':
            break
        elif SELECTION.upper()=='Q':
            break

        else:
            print('%r is not a valid option'%SELECTION)
    except ValueError:
        print('%r is not a valid option'%SELECTION)
    exit
return SELECTION.upper()
</code>```

答:
Here's some modified code. Instead of using recursion in MAINMENU, we're now using a while loop. Now we can maintain state within the lexical scope of the method MAINMENU by using local variables chain_param and num_points, which store the values input by the user.

It's important to realize that each function has its own scope. Variables defined in one function are not going to be defined in another function. If we want to pass chain_param and num_points along to a new function, say do_magic, we have to send them as parameters to the method: i.e. do_magic(chain_param, num_points).

Likewise, we want do_magic to pass the calculated value back to MAINMENU, so we return that value and collect it in a new variable defined by the lexical scope of MAINMENU, called magic_answer

```<code>def getBoundedNumber(qq,ww,ee):

    while True:
        try:
            AA = float(input('Enter chain parameter between %r and %r '%(qq,ww)))
            ee='%r is not between %r and %r'%(AA,qq,ww)
            assert type(AA)==float or int,'not a valid input'
            if qq<= AA <= ww:

                break
            else:
                print(ee)
        except ValueError:
            print(' not a valid input')

    return AA

def do_magic(x,y):
    if x and y:
        return x / y

def MAINMENU():
    print('A - enter chain parameter a' )
    print('N - enter number of points in chain' )
    print('P - calculate and print chain results')
    print('Q - quit program')

    chain_param = None
    num_points = None
    magic_answer = None
    try:
        while True:
            SELECTION = input('Enter your selection: ')

            if SELECTION.upper() == 'A':
                chain_param = getBoundedNumber(0.5,4.5,1)

            elif SELECTION.upper() == 'N':
                num_points = getBoundedNumber(10,100000,1)

            elif SELECTION.upper() == 'P':
                #do something with chain_param and num_points to get magic_answer
                if chain_param and num_points:
                    magic_answer = do_magic(chain_param,num_points)
                print('Magic Answer = ', magic_answer)

            elif SELECTION.upper() == 'Q':
                return 1
            else:
                print('%r is not a valid option'%SELECTION)
    except ValueError:
        print('%r is not a valid option'%SELECTION)
        return -1

MAINMENU()
</code>```

out

```<code>A - enter chain parameter a
N - enter number of points in chain
P - calculate and print chain results
Q - quit program
Enter your selection: A
Enter chain parameter between 0.5 and 4.5 2
Enter your selection: N
Enter chain parameter between 10 and 100000 100
Enter your selection: P
Magic Answer =  0.02
Enter your selection: Q
</code>```

Body:
so getBoundedNumber() is to let the user input some numbers and return the input. My other functions base on the return value and do calculations. I tried to assign it to a global variable outside the function(like var=getBoundedNumber(...)),but instead of storing the value from function, it executes the function again and ask for user to input again. How do I fix this?Thank you!

def getBoundedNumber(qq,ww,ee):

    while True:
        try:
            AA = float(input('Enter chain parameter between %r and %r '%(qq,ww)))
            ee='%r is not between %r and %r'%(AA,qq,ww)
            assert type(AA)==float or int,'not a valid input'
            if qq<= AA <= ww:

                break
            else:
            print(ee)
        except ValueError:
            print(' not a valid input')
    exit

return AA

This is my main function:

def MAIN():

while True:

    xx=menu()

    if xx == 'A':
        aa=getBoundedNumber(0.5,4.5,1)

    elif xx == 'N':
        numpoints=getBoundedNumber(10,100000,1)

    elif xx == 'P':

        print('  Parameter a:%20.3f'%aa,'[m]')#console gives me aa not defined
        print('  Number of points:%20d'%numpoints)#console gives me numpoints not defined
        print('  Length:%20.3f'%chainlength(xs,ys),'[m]')#this function requires value from aa and numpoints so it won't execute.
        print('  Angle with support:%20.3f'%anglewithsupport(g_,dd,aa,numpoints))
        print('  Net force:%20.3f'%netforce(),'[N]')

    elif xx == 'Q':
        break
    else:
        print(' not a valid option')

exit

This is my menu function

def menu():
print('Main menu choices')
print('   A - enter chain parameter a' )
print('   N - enter number of points in chain' )
print('   P - calculate and print chain results')
print('   Q - quit program')
while True:
    try:
        SELECTION = input('Enter your selection: ')

        if SELECTION.upper()== 'A':

            break
        elif SELECTION.upper() == 'N':
            break
        elif SELECTION.upper()=='P':
            break
        elif SELECTION.upper()=='Q':
            break

        else:
            print('%r is not a valid option'%SELECTION)
    except ValueError:
        print('%r is not a valid option'%SELECTION)
    exit
return SELECTION.upper()

Body:
Here's some modified code. Instead of using recursion in MAINMENU, we're now using a while loop. Now we can maintain state within the lexical scope of the method MAINMENU by using local variables chain_param and num_points, which store the values input by the user.

It's important to realize that each function has its own scope. Variables defined in one function are not going to be defined in another function. If we want to pass chain_param and num_points along to a new function, say do_magic, we have to send them as parameters to the method: i.e. do_magic(chain_param, num_points).

Likewise, we want do_magic to pass the calculated value back to MAINMENU, so we return that value and collect it in a new variable defined by the lexical scope of MAINMENU, called magic_answer

def getBoundedNumber(qq,ww,ee):

    while True:
        try:
            AA = float(input('Enter chain parameter between %r and %r '%(qq,ww)))
            ee='%r is not between %r and %r'%(AA,qq,ww)
            assert type(AA)==float or int,'not a valid input'
            if qq<= AA <= ww:

                break
            else:
                print(ee)
        except ValueError:
            print(' not a valid input')

    return AA

def do_magic(x,y):
    if x and y:
        return x / y

def MAINMENU():
    print('A - enter chain parameter a' )
    print('N - enter number of points in chain' )
    print('P - calculate and print chain results')
    print('Q - quit program')

    chain_param = None
    num_points = None
    magic_answer = None
    try:
        while True:
            SELECTION = input('Enter your selection: ')

            if SELECTION.upper() == 'A':
                chain_param = getBoundedNumber(0.5,4.5,1)

            elif SELECTION.upper() == 'N':
                num_points = getBoundedNumber(10,100000,1)

            elif SELECTION.upper() == 'P':
                #do something with chain_param and num_points to get magic_answer
                if chain_param and num_points:
                    magic_answer = do_magic(chain_param,num_points)
                print('Magic Answer = ', magic_answer)

            elif SELECTION.upper() == 'Q':
                return 1
            else:
                print('%r is not a valid option'%SELECTION)
    except ValueError:
        print('%r is not a valid option'%SELECTION)
        return -1

MAINMENU()

out

A - enter chain parameter a
N - enter number of points in chain
P - calculate and print chain results
Q - quit program
Enter your selection: A
Enter chain parameter between 0.5 and 4.5 2
Enter your selection: N
Enter chain parameter between 10 and 100000 100
Enter your selection: P
Magic Answer =  0.02
Enter your selection: Q