问:
vtiger how to enable the error reporting?
I installed vtiger, but i am having some problem with it, i asked the help desk team they told me to enable the error reporting

how can i do that please?

答:
Go to .vtigerfolder/modules/Install/views/index.php and change the code as shown in solution

```<code>protected function applyInstallFriendlyEnv() {
        version_compare(PHP_VERSION, '5.5.0') <= 0 ? error_reporting(E_ERROR & ~E_NOTICE & ~E_DEPRECATED) :
               error_reporting(E_ERROR & ~E_NOTICE & ~E_DEPRECATED & ~E_STRICT);
            set_time_limit(0);
    }
</code>```

====Solution:======
The code below shows if your php version is less than 5.5.0 then set error reporting to notice, error and deprecated other wise or else set error reporting to E_error,E_notice,E_deprecated and E_strict which is changing the actual setting you set in php.ini

```<code>  //Change below line
version_compare(PHP_VERSION, '5.5.0') <= 0 ? error_reporting(E_ERROR & ~E_NOTICE & ~E_DEPRECATED) : error_reporting(E_ERROR & ~E_NOTICE & ~E_DEPRECATED & ~E_STRICT);

    //USE This code instead
version_compare(PHP_VERSION, '5.5.0') <= 0 ? error_reporting(E_ERROR & ~E_NOTICE & ~E_DEPRECATED) : error_reporting(~E_NOTICE & ~E_DEPRECATED & ~E_STRICT & E_WARNING);
</code>```

Body:
Go to .vtigerfolder/modules/Install/views/index.php and change the code as shown in solution

protected function applyInstallFriendlyEnv() {
        version_compare(PHP_VERSION, '5.5.0') <= 0 ? error_reporting(E_ERROR & ~E_NOTICE & ~E_DEPRECATED) :
               error_reporting(E_ERROR & ~E_NOTICE & ~E_DEPRECATED & ~E_STRICT);
            set_time_limit(0);
    }

====Solution:======
The code below shows if your php version is less than 5.5.0 then set error reporting to notice, error and deprecated other wise or else set error reporting to E_error,E_notice,E_deprecated and E_strict which is changing the actual setting you set in php.ini

  //Change below line
version_compare(PHP_VERSION, '5.5.0') <= 0 ? error_reporting(E_ERROR & ~E_NOTICE & ~E_DEPRECATED) : error_reporting(E_ERROR & ~E_NOTICE & ~E_DEPRECATED & ~E_STRICT);

    //USE This code instead
version_compare(PHP_VERSION, '5.5.0') <= 0 ? error_reporting(E_ERROR & ~E_NOTICE & ~E_DEPRECATED) : error_reporting(~E_NOTICE & ~E_DEPRECATED & ~E_STRICT & E_WARNING);


来源: stackexchange

问:
Is it possible to solve this situation with JavaScript/jQuery?
I have a code that checks if radio buttons are checked and if they are it set background color.  It's all working fine, my problem is when I want to select another radio button, result is that all my radio buttons are selected on click but it needs to be just one.

$("input[type='radio']").each(function () {
  if ($(this).is(":checked")) {
  $(this).css("background", "yellow");
   }
 });
 ```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="radio">
<input type="radio" checked></code>```

You can test this out. Just try to select another radio button, you will see that radio buttons are selected (2 radio buttons).

What I want to achieve is that when you click on another radio button  it needs to remove this checked class or any other idea. I can't switch between radio buttons.

答:
Radio button can be easily handle with name attribute below code may help you</p>

```<code><input type="radio" name="color">
<input type="radio"  name="color" checked>

$("input[name='color']").each(function () {
    if ($(this).is(":checked")) {
      $(this).css("background", "yellow");
    }
});
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a code that checks if radio buttons are checked and if they are it set background color.  It's all working fine, my problem is when I want to select another radio button, result is that all my radio buttons are selected on click but it needs to be just one.

$("input[type='radio']").each(function () {
  if ($(this).is(":checked")) {
  $(this).css("background", "yellow");
   }
 });

<input type="radio">
<input type="radio" checked>

You can test this out. Just try to select another radio button, you will see that radio buttons are selected (2 radio buttons).

What I want to achieve is that when you click on another radio button  it needs to remove this checked class or any other idea. I can't switch between radio buttons.

Body:
Radio button can be easily handle with name attribute below code may help you

<input type="radio" name="color">
<input type="radio"  name="color" checked>

$("input[name='color']").each(function () {
    if ($(this).is(":checked")) {
      $(this).css("background", "yellow");
    }
});


问:
IOS : fill a tableview with tableviewcell
How can I fill a UITableView with some UITableViewCell (customized)?

答:
follow the tutorials -

http://cocoawithlove.com/2009/04/easy-custom-uitableview-drawing.html

http://adeem.me/blog/2009/05/30/iphone-sdk-tutorial-part-6-creating-custom-uitableviewcell-using-interface-builder-uitableview/

ContentLicense: CC BY-SA 3.0


问:
How do you connect a POST to a different razor page loaded via AJAX into a modal popup?
Edit: Have marked up where the error in the original code was stopping this from working.

I can find plenty of info and examples of this on MVC, but doesn't seem to apply for Razor Pages?

Simple scenario: I have a page (FooList) showing a list of Foo items. Each has an Edit button. This opens a modal popup with the layout (and data) coming from a second page (FooEdit).

The Edit form appears and populates fine, but I can't work out how to get it to post the data back to the FooEdit code behind?

List page, FooList.cshtml

```<code>@page
@model Pages.FooListModel

<table>
    @foreach (var item in Model.FooListVM)
    {
        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.Name)
            </td>
            <td>
                <a onclick="openModal(@item.ID);">Edit</a>
            </td>
        </tr>
    }
</table>

<div class="modal fade" id="editModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg modal-dialog-centered" role="document">
        <div class="modal-content">
            <div class="modal-header border-bottom-0">
                <h5 class="modal-title" id="exampleModalLabel">Edit Foo</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">×</span>
                </button>
            </div>
            <form>   <---- Edit: ** This shouldn't be here **
                <div class="modal-body">
                </div>
            </form>   <---- Edit
        </div>
    </div>
</div>

<script>
    function openModal(i) {
        $.get("FooEdit?id="+i,
            null,
            data => {
                $("#editModal").modal("show");
                $("#editModal .modal-body").html(data);
            });
    };
</script>
</code>```

Code behind, FooList.cshtml.cs

```<code>public class FooListModel : PageModel
{
    public IList<FooListVM> FooListVM { get; set; }

    public void OnGet()
    {
        FooListVM = new List<FooListVM>
        {
            new FooListVM { ID = 1, Name = "Foo 1" },
            new FooListVM { ID = 2, Name = "Foo2" }
        };
    }
}

public class FooListVM
{
    public int ID { get; set; }
    public string Name { get; set; }
}
</code>```

Second page for the popup, FooEdit.cshtml

```<code>@page
@model Pages.FooEditModel

@(Layout=null)

<form method="post">
    <input asp-for="FooEditVM.Name" class="form-control" /><br />
    <input asp-for="FooEditVM.Stuff1" class="form-control" /><br />
    <input asp-for="FooEditVM.Stuff2" class="form-control" /><br />
    <input type="submit" value="Save"/>
</form>
</code>```

And the code behind for the popup, FooEdit.cshtml.cs

```<code>public class FooEditModel : PageModel
{
    [BindProperty]
    public FooEditVM FooEditVM { get; set; }

    public void OnGet(int id)
    {
        FooEditVM = new FooEditVM
        {
            Name = $"This is item {id}",
            Stuff1 = "Stuff1",
            Stuff2 = "Stuff2"
        };
    }

    public void OnPost(int id)
    {
        // How do we get to here???
        var a = FooEditVM.Name;
    }
}

public class FooEditVM
{
    public string Name { get; set; }
    public string Stuff1 { get; set; }
    public string Stuff2 { get; set; }
}
</code>```

I've been through all the MS Tutorial stuff on Asp.net Core 2.2, but it doesn't seem to cover this.

Also as a side question, although it works, is there a "ASP helper tag" way of doing the ajax bit?

答:
Have realised the problem was the 'form' tag in the Modal Dialog markup that was clashing the 'form' tag from the partial page. Removing it fixed everything using:

In FooEdit.cshtml

```<code><form id="editForm" asp-page="FooEdit">
. . .
</form>
</code>```

In FooEdit.cshtml.cs

```<code>public void OnPost()
{
    // Fires in here
}
</code>```

Body:
Edit: Have marked up where the error in the original code was stopping this from working.

I can find plenty of info and examples of this on MVC, but doesn't seem to apply for Razor Pages?

Simple scenario: I have a page (FooList) showing a list of Foo items. Each has an Edit button. This opens a modal popup with the layout (and data) coming from a second page (FooEdit).

The Edit form appears and populates fine, but I can't work out how to get it to post the data back to the FooEdit code behind?

List page, FooList.cshtml

@page
@model Pages.FooListModel

    @foreach (var item in Model.FooListVM)
    {

                @Html.DisplayFor(modelItem => item.Name)

                Edit

    }

Edit Foo

                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    ×
                </button>

            <form>   <---- Edit: ** This shouldn't be here **

            </form>   <---- Edit

Code behind, FooList.cshtml.cs

public class FooListModel : PageModel
{
    public IList<FooListVM> FooListVM { get; set; }

    public void OnGet()
    {
        FooListVM = new List<FooListVM>
        {
            new FooListVM { ID = 1, Name = "Foo 1" },
            new FooListVM { ID = 2, Name = "Foo2" }
        };
    }
}

public class FooListVM
{
    public int ID { get; set; }
    public string Name { get; set; }
}

Second page for the popup, FooEdit.cshtml

@page
@model Pages.FooEditModel

@(Layout=null)

<form method="post">
    <input asp-for="FooEditVM.Name" class="form-control" />

    <input asp-for="FooEditVM.Stuff1" class="form-control" />

    <input asp-for="FooEditVM.Stuff2" class="form-control" />

    <input type="submit" value="Save"/>
</form>

And the code behind for the popup, FooEdit.cshtml.cs

public class FooEditModel : PageModel
{
    [BindProperty]
    public FooEditVM FooEditVM { get; set; }

    public void OnGet(int id)
    {
        FooEditVM = new FooEditVM
        {
            Name = $"This is item {id}",
            Stuff1 = "Stuff1",
            Stuff2 = "Stuff2"
        };
    }

    public void OnPost(int id)
    {
        // How do we get to here???
        var a = FooEditVM.Name;
    }
}

public class FooEditVM
{
    public string Name { get; set; }
    public string Stuff1 { get; set; }
    public string Stuff2 { get; set; }
}

I've been through all the MS Tutorial stuff on Asp.net Core 2.2, but it doesn't seem to cover this.

Also as a side question, although it works, is there a "ASP helper tag" way of doing the ajax bit?

Body:
Have realised the problem was the 'form' tag in the Modal Dialog markup that was clashing the 'form' tag from the partial page. Removing it fixed everything using:

In FooEdit.cshtml

<form id="editForm" asp-page="FooEdit">
. . .
</form>

In FooEdit.cshtml.cs

public void OnPost()
{
    // Fires in here
}


问:
Namespace 'NodeJS' has no exported member 'Timeout'
When i run code i get this error

```<code>ERROR in node_modules/@wry/context/lib/context.d.ts(6,84): error
TS2694: Namespace 'NodeJS' has no exported member 'Timeout'.
</code>```

I am using angular7

答:
if you're using yarn, just run

```<code>yarn add --dev @types/node
</code>```

to fix your package.json

Body:
When i run code i get this error

ERROR in node_modules/@wry/context/lib/context.d.ts(6,84): error
TS2694: Namespace 'NodeJS' has no exported member 'Timeout'.

I am using angular7

Body:
if you're using yarn, just run

yarn add --dev @types/node

to fix your package.json


问:
Can mango syntax take in two $OR operators in one query?
I have problems putting two $OR operations in one query statement. It ignores the earlier $OR operators and only takes into consideration the last $OR operator in the query. (There is no issue when only one $OR operator is in the query.) Am wondering if I am doing something wrong, if this is possible to achieve using CouchDB, or if there is a way around it. Thank you!

I am running a blockchain on Hyperledger Fabric using CouchDB as the state database. (https://hyperledger-fabric.readthedocs.io/en/release-1.4/couchdb_tutorial.html) I am definitely not seasoned in the workings of CouchDB so I may be slightly ignorant in how it's supposed to behave.

It's sort of complicated but my objects basically "belong" to two owners and companies. I want to perform queries such that when I search for a owner or a company, it searches in two different columns to see the the owner/company exists.

e.g. When I search for Company A, it should search for Company A in both company1_id and company2_id.

Query Statement:

{"selector":{"docType":"object", "owner_id": {"$in": ["owner_id"]},
  "$or": [{"company1_id": { "$in": ["company_id_1", "company_id_2"]}},
  {"company2_id": { "$in": ["company_id_1", "company_id_2"]}}], "$or":
  [{"owner1_id": { "$in": ["owner_id_1", "owner_id_2"]}}, {"owner2_id":
  { "$in": ["owner_id_1", "owner_id_2"]}}],
  "object_id":{"$lt":"99999999999"}}, "sort": [{"object_id": "desc"}]}

Expected: Get results that corresponds to the above query

What happened: I get results which ignored the first query, so it returns results which corresponds to the following query:

{"selector":{"docType":"object", "owner_id": {"$in": ["owner_id"]},
  "$or": [{"owner1_id": { "$in": ["owner_id_1", "owner_id_2"]}},
  {"owner2_id": { "$in": ["owner_id_1", "owner_id_2"]}}],
  "object_id":{"$lt":"99999999999"}}, "sort": [{"object_id": "desc"}]}

答:
Yes, it ignores it because it's a standard JSON object, so each key must be unique. You have the same situation with a simpler example:

```<code>{
    "foo": 123,
    "foo": 345,
}
</code>```

Depending on whether your JSON parser accepts the first or last value, your resulting object will be either { "foo": 123 } or { "foo": 345 }.

The solution is to use another logical layer. In your case, you probably want an $and wrapping your $or conditions:

```<code>"$and": [
    { "$or": [ ... ] },
    { "$or": [ ... ] },
]
</code>```

Body:
Yes, it ignores it because it's a standard JSON object, so each key must be unique. You have the same situation with a simpler example:

{
    "foo": 123,
    "foo": 345,
}

Depending on whether your JSON parser accepts the first or last value, your resulting object will be either { "foo": 123 } or { "foo": 345 }.

The solution is to use another logical layer. In your case, you probably want an $and wrapping your $or conditions:

"$and": [
    { "$or": [ ... ] },
    { "$or": [ ... ] },
]


问:
Microsoft-Graph token using request is to small
I'm trying to get the access token for my Microsoft-Graph application using request to send a POST request.
The problem is that the token i get as a response is only 1188 characters long. While the token i get when i use Postman is 1461 characters long. Every time i send a request it generates a brand new token, but the one i get through request in nodejs is always 1188 and the one in postman is always 1461.

I have tried different things such as generating a new app api id in Microsoft Azure, but it keeps giving the same results.

This is my code, i took out sensitive information though by replacing it with the word CENSORED.
I'm using the EXACT same request parameters in Postman

```<code>const endpoint = "https://login.microsoftonline.com/CENSORED/oauth2/token";
    const requestParams = {
      client_id: "CENSORED",
      client_secret: "CENSORED",
      resource: "https://graph.windows.net",
      grant_type: "client_credentials"
    };

    let accessToken = await

    request.post({
      url: endpoint,
      form: requestParams
    }, function (err, response, body) {
      if (err) {
        console.log("error");
      } else {
        console.log("Body=" + body);
        let parsedBody = JSON.parse(body);
        if (parsedBody.error_description) {
          console.log("Error=" + parsedBody.error_description);
        } else {
          getCalendarEvents(parsedBody.access_token);
        }
      }
    });
</code>```

Postman returns an 1461 characters long access token and nodejs request only returns a 1188 characters long access token.

This is what i'm using in Nodejs: https://www.npmjs.com/package/request

答: Apparently the resource parameter should be https://graph.microsoft.com instead of https://graph.windows.net.</p>

Body:
I'm trying to get the access token for my Microsoft-Graph application using request to send a POST request.
The problem is that the token i get as a response is only 1188 characters long. While the token i get when i use Postman is 1461 characters long. Every time i send a request it generates a brand new token, but the one i get through request in nodejs is always 1188 and the one in postman is always 1461.

I have tried different things such as generating a new app api id in Microsoft Azure, but it keeps giving the same results.

This is my code, i took out sensitive information though by replacing it with the word CENSORED.
I'm using the EXACT same request parameters in Postman

const endpoint = "https://login.microsoftonline.com/CENSORED/oauth2/token";
    const requestParams = {
      client_id: "CENSORED",
      client_secret: "CENSORED",
      resource: "https://graph.windows.net",
      grant_type: "client_credentials"
    };

    let accessToken = await

    request.post({
      url: endpoint,
      form: requestParams
    }, function (err, response, body) {
      if (err) {
        console.log("error");
      } else {
        console.log("Body=" + body);
        let parsedBody = JSON.parse(body);
        if (parsedBody.error_description) {
          console.log("Error=" + parsedBody.error_description);
        } else {
          getCalendarEvents(parsedBody.access_token);
        }
      }
    });

Postman returns an 1461 characters long access token and nodejs request only returns a 1188 characters long access token.

This is what i'm using in Nodejs: https://www.npmjs.com/package/request


问:
Attemping to parallelize a nested loop in Scala
I am comparing 2 dataframes in scala/spark using a nested loop and an external jar.

```<code>for (nrow <- dfm.rdd.collect) {
  var mid = nrow.mkString(",").split(",")(0)
  var mfname = nrow.mkString(",").split(",")(1)
  var mlname = nrow.mkString(",").split(",")(2)
  var mlssn = nrow.mkString(",").split(",")(3)

  for (drow <- dfn.rdd.collect) {
    var nid = drow.mkString(",").split(",")(0)
    var nfname = drow.mkString(",").split(",")(1)
    var nlname = drow.mkString(",").split(",")(2)
    var nlssn = drow.mkString(",").split(",")(3)

    val fNameArray = Array(mfname,nfname)
    val lNameArray = Array (mlname,nlname)
    val ssnArray = Array (mlssn,nlssn)

    val fnamescore = Main.resultSet(fNameArray)
    val lnamescore = Main.resultSet(lNameArray)
    val ssnscore =  Main.resultSet(ssnArray)

    val overallscore = (fnamescore +lnamescore +ssnscore) /3

    if(overallscore >= .95) {
       println("MeditechID:".concat(mid)
         .concat(" MeditechFname:").concat(mfname)
         .concat(" MeditechLname:").concat(mlname)
         .concat(" MeditechSSN:").concat(mlssn)
         .concat(" NextGenID:").concat(nid)
         .concat(" NextGenFname:").concat(nfname)
         .concat(" NextGenLname:").concat(nlname)
         .concat(" NextGenSSN:").concat(nlssn)
         .concat(" FnameScore:").concat(fnamescore.toString)
         .concat(" LNameScore:").concat(lnamescore.toString)
         .concat(" SSNScore:").concat(ssnscore.toString)
         .concat(" OverallScore:").concat(overallscore.toString))
    }
  }
}
</code>```

What I'm hoping to do is add some parallelism to the outer loop so that I can create a threadpool of 5 and pull 5 records from the collection of the outerloop and compare them to the collection of the inner loop, rather than doing this serially. So the outcome would be I can specify the number of threads, have 5 records from the outerloop's collection processing at any given time against the collection in the inner loop. How would I go about doing this?

答:
This is not a right way of iterating over spark dataframe. The major concern is the dfm.rdd.collect. If the dataframe is arbitrarily large, you would end up exception. This due to the fact that the collect function essentially brings all the data into the master node.

Alternate way would be use the foreach or map construct of the rdd.

```<code>dfm.rdd.foreach(x => {
    // your logic
}
</code>```

Now you are trying to iterate the second dataframe here. I am afraid that won't be possible. The elegant way is to join the dfm and dfn and iterate over the resulting dataset to compute your function.

Body:
I am comparing 2 dataframes in scala/spark using a nested loop and an external jar.

for (nrow <- dfm.rdd.collect) {
  var mid = nrow.mkString(",").split(",")(0)
  var mfname = nrow.mkString(",").split(",")(1)
  var mlname = nrow.mkString(",").split(",")(2)
  var mlssn = nrow.mkString(",").split(",")(3)

  for (drow <- dfn.rdd.collect) {
    var nid = drow.mkString(",").split(",")(0)
    var nfname = drow.mkString(",").split(",")(1)
    var nlname = drow.mkString(",").split(",")(2)
    var nlssn = drow.mkString(",").split(",")(3)

    val fNameArray = Array(mfname,nfname)
    val lNameArray = Array (mlname,nlname)
    val ssnArray = Array (mlssn,nlssn)

    val fnamescore = Main.resultSet(fNameArray)
    val lnamescore = Main.resultSet(lNameArray)
    val ssnscore =  Main.resultSet(ssnArray)

    val overallscore = (fnamescore +lnamescore +ssnscore) /3

    if(overallscore >= .95) {
       println("MeditechID:".concat(mid)
         .concat(" MeditechFname:").concat(mfname)
         .concat(" MeditechLname:").concat(mlname)
         .concat(" MeditechSSN:").concat(mlssn)
         .concat(" NextGenID:").concat(nid)
         .concat(" NextGenFname:").concat(nfname)
         .concat(" NextGenLname:").concat(nlname)
         .concat(" NextGenSSN:").concat(nlssn)
         .concat(" FnameScore:").concat(fnamescore.toString)
         .concat(" LNameScore:").concat(lnamescore.toString)
         .concat(" SSNScore:").concat(ssnscore.toString)
         .concat(" OverallScore:").concat(overallscore.toString))
    }
  }
}

What I'm hoping to do is add some parallelism to the outer loop so that I can create a threadpool of 5 and pull 5 records from the collection of the outerloop and compare them to the collection of the inner loop, rather than doing this serially. So the outcome would be I can specify the number of threads, have 5 records from the outerloop's collection processing at any given time against the collection in the inner loop. How would I go about doing this?

Body:
This is not a right way of iterating over spark dataframe. The major concern is the dfm.rdd.collect. If the dataframe is arbitrarily large, you would end up exception. This due to the fact that the collect function essentially brings all the data into the master node.

Alternate way would be use the foreach or map construct of the rdd.

dfm.rdd.foreach(x => {
    // your logic
}

Now you are trying to iterate the second dataframe here. I am afraid that won't be possible. The elegant way is to join the dfm and dfn and iterate over the resulting dataset to compute your function.


问:
Install ssl certificate from azure key vault with Automation Accounts
i have some issues.
I have in key vault some SSL certs from LetsEncrypt,and i want to automate installing certificates to VM in azure. I create runbook with some code:

```<code>$connectionName = "AzureRunAsConnection"
try
{# Get the connection "AzureRunAsConnection "
    $servicePrincipalConnection=Get-AutomationConnection -Name $connectionName
    "Logging in to Azure..."
    Add-AzureRmAccount `
        -ServicePrincipal `
        -TenantId $servicePrincipalConnection.TenantId `
        -ApplicationId $servicePrincipalConnection.ApplicationId `
        -CertificateThumbprint $servicePrincipalConnection.CertificateThumbprint
}
catch {if (!$servicePrincipalConnection)
    {
        $ErrorMessage = "Connection $connectionName not found."
        throw $ErrorMessage
    } else{
        Write-Error -Message $_.Exception
        throw $_.Exception
    }
}$certUrl = (Get-AzureKeyVaultSecret -VaultName "MyVault" -Name "letsecrypt-my-cert").Id;
$vm=Get-AzureRmVM -ResourceGroupName "MyRS" -Name "MyVm"
$vaultId=(Get-AzureRmKeyVault -VaultName "MyVault").ResourceId
$certStore = "MySSL"
$vm = Add-AzureRmVMSecret -VM $vm -SourceVaultId $vaultId -CertificateStore $certStore -CertificateUrl $certURL
Update-AzureRmVM -ResourceGroupName "MyRS" -VM $vm
</code>```

It install ssl to my VM, but i want to check some parameters of certificate and run this script, for example: if certificate updated run install to vm and if not do nothing. What parameters i must use and how check them. Maybe someone do similar task?

答:
I solve this issues with these code modification:

```<code>$connectionName = "AzureRunAsConnection"
try
{
    # Get the connection "AzureRunAsConnection "
    $servicePrincipalConnection=Get-AutomationConnection -Name $connectionName

    "Logging in to Azure..."
    Add-AzureRmAccount `
        -ServicePrincipal `
        -TenantId $servicePrincipalConnection.TenantId `
        -ApplicationId $servicePrincipalConnection.ApplicationId `
        -CertificateThumbprint $servicePrincipalConnection.CertificateThumbprint
}
catch {
    if (!$servicePrincipalConnection)
    {
        $ErrorMessage = "Connection $connectionName not found."
        throw $ErrorMessage
    } else{
        Write-Error -Message $_.Exception
        throw $_.Exception
    }
}
$certUrl = (Get-AzureKeyVaultSecret -VaultName "MyVault" -Name "letsecrypt-MyCert").Id
$vm=Get-AzureRmVM -ResourceGroupName "MyRG" -Name "MyVm"
$certUrlOnVM=$vm.osProfile.secrets.vaultCertificates.certificateUrl
$vaultId=(Get-AzureRmKeyVault -VaultName "MyVault").ResourceId
$curentDate = Get-Date
$d = $curentDate.day
$m = $curentDate.month
$y = $curentDate.year
$curentDateStr = "$d/$m/$y"
$certStore = "MySSL_"+$curentDateStr
if ($certUrl.equals($certUrlOnVM)){
    "Certificate already installed on VM"
} else {
Get-AzureRmVM -ResourceGroupName "MyRG" -Name "MyVm" | Remove-AzureRmVMSecret | Update-AzureRmVM
$vm = Add-AzureRmVMSecret -VM $vm -SourceVaultId $vaultId -CertificateStore $certStore -CertificateUrl $certURL
Update-AzureRmVM -ResourceGroupName "MyRG" -VM $vm
"Certificate installed on VM successfully"
}
</code>```

I add some variables for get certificate url in key vault and section certificateUrl from OSProfile on vm. I check if cert in keyvault and vm are identical, i do nothing, if not i do remove old section on vm and install new cert.

Body:
i have some issues.
I have in key vault some SSL certs from LetsEncrypt,and i want to automate installing certificates to VM in azure. I create runbook with some code:

$connectionName = "AzureRunAsConnection"
try
{# Get the connection "AzureRunAsConnection "
    $servicePrincipalConnection=Get-AutomationConnection -Name $connectionName
    "Logging in to Azure..."
    Add-AzureRmAccount `
        -ServicePrincipal `
        -TenantId $servicePrincipalConnection.TenantId `
        -ApplicationId $servicePrincipalConnection.ApplicationId `
        -CertificateThumbprint $servicePrincipalConnection.CertificateThumbprint
}
catch {if (!$servicePrincipalConnection)
    {
        $ErrorMessage = "Connection $connectionName not found."
        throw $ErrorMessage
    } else{
        Write-Error -Message $_.Exception
        throw $_.Exception
    }
}$certUrl = (Get-AzureKeyVaultSecret -VaultName "MyVault" -Name "letsecrypt-my-cert").Id;
$vm=Get-AzureRmVM -ResourceGroupName "MyRS" -Name "MyVm"
$vaultId=(Get-AzureRmKeyVault -VaultName "MyVault").ResourceId
$certStore = "MySSL"
$vm = Add-AzureRmVMSecret -VM $vm -SourceVaultId $vaultId -CertificateStore $certStore -CertificateUrl $certURL
Update-AzureRmVM -ResourceGroupName "MyRS" -VM $vm

It install ssl to my VM, but i want to check some parameters of certificate and run this script, for example: if certificate updated run install to vm and if not do nothing. What parameters i must use and how check them. Maybe someone do similar task?

Body:
I solve this issues with these code modification:

$connectionName = "AzureRunAsConnection"
try
{
    # Get the connection "AzureRunAsConnection "
    $servicePrincipalConnection=Get-AutomationConnection -Name $connectionName

    "Logging in to Azure..."
    Add-AzureRmAccount `
        -ServicePrincipal `
        -TenantId $servicePrincipalConnection.TenantId `
        -ApplicationId $servicePrincipalConnection.ApplicationId `
        -CertificateThumbprint $servicePrincipalConnection.CertificateThumbprint
}
catch {
    if (!$servicePrincipalConnection)
    {
        $ErrorMessage = "Connection $connectionName not found."
        throw $ErrorMessage
    } else{
        Write-Error -Message $_.Exception
        throw $_.Exception
    }
}
$certUrl = (Get-AzureKeyVaultSecret -VaultName "MyVault" -Name "letsecrypt-MyCert").Id
$vm=Get-AzureRmVM -ResourceGroupName "MyRG" -Name "MyVm"
$certUrlOnVM=$vm.osProfile.secrets.vaultCertificates.certificateUrl
$vaultId=(Get-AzureRmKeyVault -VaultName "MyVault").ResourceId
$curentDate = Get-Date
$d = $curentDate.day
$m = $curentDate.month
$y = $curentDate.year
$curentDateStr = "$d/$m/$y"
$certStore = "MySSL_"+$curentDateStr
if ($certUrl.equals($certUrlOnVM)){
    "Certificate already installed on VM"
} else {
Get-AzureRmVM -ResourceGroupName "MyRG" -Name "MyVm" | Remove-AzureRmVMSecret | Update-AzureRmVM
$vm = Add-AzureRmVMSecret -VM $vm -SourceVaultId $vaultId -CertificateStore $certStore -CertificateUrl $certURL
Update-AzureRmVM -ResourceGroupName "MyRG" -VM $vm
"Certificate installed on VM successfully"
}

I add some variables for get certificate url in key vault and section certificateUrl from OSProfile on vm. I check if cert in keyvault and vm are identical, i do nothing, if not i do remove old section on vm and install new cert.


问:
Regex to replace multiple patterns with single not working
I am working on replacing multiple occurance of string 0000 with single random number in HANA SQL

I have used these patterns

'(\w+)\s+\1'

'([0000 ]+) \1'

but all occurrences are replaced except the last occurrence of the pattern

```<code>SELECT REPLACE_REGEXPR('(\w+)\s+\1' IN '0000 0000 0000' WITH ROUND(RAND()*1000) OCCURRENCE ALL) AS a2
FROM DUMMY;
</code>```

Current output is

```<code>RANDOM 0000
</code>```

expected output is

```<code>RANDOM
</code>```

答:
Try this regex:

```<code>((0000) +)+(0000)
</code>```

Look Here

And if it's OK to use any digit and more \ less times then 4:

```<code>(\d+ +)+\d+
</code>```

Good Luck!

Body:
I am working on replacing multiple occurance of string 0000 with single random number in HANA SQL

I have used these patterns

'(\w+)\s+\1'

'([0000 ]+) \1'

but all occurrences are replaced except the last occurrence of the pattern

SELECT REPLACE_REGEXPR('(\w+)\s+\1' IN '0000 0000 0000' WITH ROUND(RAND()*1000) OCCURRENCE ALL) AS a2
FROM DUMMY;

Current output is

RANDOM 0000

expected output is

RANDOM

Body:
Try this regex:

((0000) +)+(0000)

Look Here

And if it's OK to use any digit and more \ less times then 4:

(\d+ +)+\d+

Good Luck!


问:
UIView setting constraints
I am having trouble creating a UIView instance programmatically. I have a function that returns the view so that I can use it in an NSAttachment inside a UITextView.

This is what I am trying to achieve:

This is what I am getting in the simulator:

Code Below:

```<code>let fullView = UIView()
    let firstButton = UIButton()
    let secondButton = UIButton()
    let thirdTextView = UITextView()

    fullView.frame = CGRect(x: 0, y: 0, width: textView.frame.width, height: 90)
    fullView.backgroundColor = UIColor(red:0.82, green:0.83, blue:0.85, alpha:1.0)

    firstButton.setTitle(text1, for: .normal)
    firstButton.setTitleColor(.black, for: .normal)
    firstButton.titleLabel?.font = UIFont.systemFont(ofSize: 15, weight: UIFont.Weight.medium)
    firstButton.contentHorizontalAlignment = .left

    secondButton.setTitle("Button2", for: .normal)
    secondButton.setTitleColor(.black, for: .normal)
    secondButton.titleLabel?.font = UIFont.systemFont(ofSize: 15, weight: UIFont.Weight.medium)
    secondButton.contentHorizontalAlignment = .right

    thirdTextView.text = text2

    let descriptionBarStackView = UIStackView()
    descriptionBarStackView.axis = .horizontal
    descriptionBarStackView.alignment = .fill
    descriptionBarStackView.distribution = .fillProportionally

    descriptionBarStackView.addArrangedSubview(firstButton)
    descriptionBarStackView.addArrangedSubview(secondButton)

    let viewWithStackViews = UIStackView()
    viewWithStackViews.axis = .vertical
    viewWithStackViews.alignment = .fill // .leading .firstBaseline .center .trailing .lastBaseline
    viewWithStackViews.distribution = .fillEqually
    viewWithStackViews.addArrangedSubview(descriptionBarStackView)
    viewWithStackViews.addArrangedSubview(thirdTextView)

    fullView.addSubview(viewWithStackViews)

    descriptionBarStackView.translatesAutoresizingMaskIntoConstraints = false
    thirdTextView.translatesAutoresizingMaskIntoConstraints = false
    viewWithStackViews.translatesAutoresizingMaskIntoConstraints = false

    NSLayoutConstraint.activate([
    viewWithStackViews.topAnchor.constraint(equalTo: fullView.topAnchor, constant: 5),
    viewWithStackViews.leadingAnchor.constraint(equalTo: fullView.leadingAnchor, constant: 5),
    viewWithStackViews.trailingAnchor.constraint(equalTo: fullView.trailingAnchor, constant: 5),
    viewWithStackViews.bottomAnchor.constraint(equalTo: fullView.bottomAnchor, constant: 5),
    ])
</code>```

Edit:

答:
Tried to preserve your layout structure

```<code>class VisualTestViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .white

        let fullView = UIView()
        fullView.backgroundColor = UIColor(red:0.82, green:0.83, blue:0.85, alpha:1.0)
        fullView.translatesAutoresizingMaskIntoConstraints = false

        let firstButton = UIButton()
        firstButton.translatesAutoresizingMaskIntoConstraints = false
        let secondButton = UIButton()
        secondButton.translatesAutoresizingMaskIntoConstraints = false
        let thirdTextView = UITextView()
        thirdTextView.translatesAutoresizingMaskIntoConstraints = false

        thirdTextView.text = "lorem ipsumlorem ipsumlorem ipsumlorem ipsumlorem ipsumlorem ipsumlorem ipsumlorem ipsumlorem ipsum"

        let text1 = "Button1"
        firstButton.setTitle(text1, for: .normal)
        firstButton.setTitleColor(.black, for: .normal)
        firstButton.titleLabel?.font = UIFont.systemFont(ofSize: 15, weight: UIFont.Weight.medium)
        firstButton.contentHorizontalAlignment = .left

        secondButton.setTitle("Button2", for: .normal)
        secondButton.setTitleColor(.black, for: .normal)
        secondButton.titleLabel?.font = UIFont.systemFont(ofSize: 15, weight: UIFont.Weight.medium)
        secondButton.contentHorizontalAlignment = .right

        let descriptionBarStackView = UIStackView(arrangedSubviews: [firstButton, UIView() ,secondButton])
        descriptionBarStackView.translatesAutoresizingMaskIntoConstraints = false
        descriptionBarStackView.axis = .horizontal
        descriptionBarStackView.alignment = .center

        let viewWithStackViews = UIStackView(arrangedSubviews: [descriptionBarStackView, thirdTextView])
        viewWithStackViews.translatesAutoresizingMaskIntoConstraints = false
        viewWithStackViews.axis = .vertical
        viewWithStackViews.layoutMargins = UIEdgeInsets(top: 5, left: 5, bottom: 5, right: 5)
        viewWithStackViews.isLayoutMarginsRelativeArrangement = true

        fullView.addSubview(viewWithStackViews)

        fullView.leadingAnchor.constraint(equalTo: viewWithStackViews.leadingAnchor).isActive = true
        fullView.trailingAnchor.constraint(equalTo: viewWithStackViews.trailingAnchor).isActive = true
        fullView.topAnchor.constraint(equalTo: viewWithStackViews.topAnchor).isActive = true
        fullView.bottomAnchor.constraint(equalTo: viewWithStackViews.bottomAnchor).isActive = true

        view.addSubview(fullView)
        fullView.widthAnchor.constraint(equalTo: view.widthAnchor, constant: -10).isActive = true
        fullView.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
        fullView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true

        thirdTextView.isScrollEnabled = false

        thirdTextView.backgroundColor = .clear
    }

}
</code>```

Title: UIView setting constraints

Body:
I am having trouble creating a UIView instance programmatically. I have a function that returns the view so that I can use it in an NSAttachment inside a UITextView.

This is what I am trying to achieve:

This is what I am getting in the simulator:

Code Below:

let fullView = UIView()
    let firstButton = UIButton()
    let secondButton = UIButton()
    let thirdTextView = UITextView()

    fullView.frame = CGRect(x: 0, y: 0, width: textView.frame.width, height: 90)
    fullView.backgroundColor = UIColor(red:0.82, green:0.83, blue:0.85, alpha:1.0)

    firstButton.setTitle(text1, for: .normal)
    firstButton.setTitleColor(.black, for: .normal)
    firstButton.titleLabel?.font = UIFont.systemFont(ofSize: 15, weight: UIFont.Weight.medium)
    firstButton.contentHorizontalAlignment = .left

    secondButton.setTitle("Button2", for: .normal)
    secondButton.setTitleColor(.black, for: .normal)
    secondButton.titleLabel?.font = UIFont.systemFont(ofSize: 15, weight: UIFont.Weight.medium)
    secondButton.contentHorizontalAlignment = .right

    thirdTextView.text = text2

    let descriptionBarStackView = UIStackView()
    descriptionBarStackView.axis = .horizontal
    descriptionBarStackView.alignment = .fill
    descriptionBarStackView.distribution = .fillProportionally

    descriptionBarStackView.addArrangedSubview(firstButton)
    descriptionBarStackView.addArrangedSubview(secondButton)

    let viewWithStackViews = UIStackView()
    viewWithStackViews.axis = .vertical
    viewWithStackViews.alignment = .fill // .leading .firstBaseline .center .trailing .lastBaseline
    viewWithStackViews.distribution = .fillEqually
    viewWithStackViews.addArrangedSubview(descriptionBarStackView)
    viewWithStackViews.addArrangedSubview(thirdTextView)

    fullView.addSubview(viewWithStackViews)

    descriptionBarStackView.translatesAutoresizingMaskIntoConstraints = false
    thirdTextView.translatesAutoresizingMaskIntoConstraints = false
    viewWithStackViews.translatesAutoresizingMaskIntoConstraints = false

    NSLayoutConstraint.activate([
    viewWithStackViews.topAnchor.constraint(equalTo: fullView.topAnchor, constant: 5),
    viewWithStackViews.leadingAnchor.constraint(equalTo: fullView.leadingAnchor, constant: 5),
    viewWithStackViews.trailingAnchor.constraint(equalTo: fullView.trailingAnchor, constant: 5),
    viewWithStackViews.bottomAnchor.constraint(equalTo: fullView.bottomAnchor, constant: 5),
    ])

Edit:

Body:
Tried to preserve your layout structure

class VisualTestViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .white

        let fullView = UIView()
        fullView.backgroundColor = UIColor(red:0.82, green:0.83, blue:0.85, alpha:1.0)
        fullView.translatesAutoresizingMaskIntoConstraints = false

        let firstButton = UIButton()
        firstButton.translatesAutoresizingMaskIntoConstraints = false
        let secondButton = UIButton()
        secondButton.translatesAutoresizingMaskIntoConstraints = false
        let thirdTextView = UITextView()
        thirdTextView.translatesAutoresizingMaskIntoConstraints = false

        thirdTextView.text = "lorem ipsumlorem ipsumlorem ipsumlorem ipsumlorem ipsumlorem ipsumlorem ipsumlorem ipsumlorem ipsum"

        let text1 = "Button1"
        firstButton.setTitle(text1, for: .normal)
        firstButton.setTitleColor(.black, for: .normal)
        firstButton.titleLabel?.font = UIFont.systemFont(ofSize: 15, weight: UIFont.Weight.medium)
        firstButton.contentHorizontalAlignment = .left

        secondButton.setTitle("Button2", for: .normal)
        secondButton.setTitleColor(.black, for: .normal)
        secondButton.titleLabel?.font = UIFont.systemFont(ofSize: 15, weight: UIFont.Weight.medium)
        secondButton.contentHorizontalAlignment = .right

        let descriptionBarStackView = UIStackView(arrangedSubviews: [firstButton, UIView() ,secondButton])
        descriptionBarStackView.translatesAutoresizingMaskIntoConstraints = false
        descriptionBarStackView.axis = .horizontal
        descriptionBarStackView.alignment = .center

        let viewWithStackViews = UIStackView(arrangedSubviews: [descriptionBarStackView, thirdTextView])
        viewWithStackViews.translatesAutoresizingMaskIntoConstraints = false
        viewWithStackViews.axis = .vertical
        viewWithStackViews.layoutMargins = UIEdgeInsets(top: 5, left: 5, bottom: 5, right: 5)
        viewWithStackViews.isLayoutMarginsRelativeArrangement = true

        fullView.addSubview(viewWithStackViews)

        fullView.leadingAnchor.constraint(equalTo: viewWithStackViews.leadingAnchor).isActive = true
        fullView.trailingAnchor.constraint(equalTo: viewWithStackViews.trailingAnchor).isActive = true
        fullView.topAnchor.constraint(equalTo: viewWithStackViews.topAnchor).isActive = true
        fullView.bottomAnchor.constraint(equalTo: viewWithStackViews.bottomAnchor).isActive = true

        view.addSubview(fullView)
        fullView.widthAnchor.constraint(equalTo: view.widthAnchor, constant: -10).isActive = true
        fullView.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
        fullView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true

        thirdTextView.isScrollEnabled = false

        thirdTextView.backgroundColor = .clear
    }

}


问:
Laravel migration with SQLite 'Cannot add a NOT NULL column with default value NULL'
Why am I getting this warning when using the SQLite driver? I have no problems with the MySQL driver but SQLite is throwing this error.

It does not make sense to me since I understood the seeding happens after all the migrations are completed so why is it complaining about this issue which would only arise if data was already present in the database.

My two migrations are

FIRST MIGRATION

```<code>  public function up() {
    Schema::create('users', function($table) {
      $table->increments('id');
      $table->string('username');
      $table->string('email');
      $table->string('password');
    });
  }
</code>```

SECOND MIGRATION

```<code>public function up() {
    Schema::table('users', function(Blueprint $table) {
        $table->date('birthday')->after('id');
        $table->string('last_name')->after('id');
        $table->string('first_name')->after('id');
    });
}
</code>```

ERROR

```<code>Exception: SQLSTATE[HY000]: General error: 1 Cannot add a NOT NULL column with default value NULL (SQL: alter table "users" add column "birthday" date not null)
</code>```

答:
Another work around for this issue is to first create the fields as nullable and then later change the fields to be not null. So for example in this case we will do something like the following:</p>

```<code>public function up() {
    // Create fields first as nullable
    Schema::table('users', function(Blueprint $table) {
        $table->date('birthday')->after('id')->nullable();
        $table->string('last_name')->after('id')->nullable();
        $table->string('first_name')->after('id')->nullable();
    });

    // Either truncate existing records or assign a value to new fields
    if (true) {
        DB::table('users')->truncate();
    } else {
        DB::table('users')->update([
            'birthday' => '2019-05-01',
            'last_name' => 'last name',
            'first_name' => 'first name',
        ]);
    }

    // Change the fields to not be null
    Schema::table('users', function(Blueprint $table) {
        $table->date('birthday')->nullable(false)->change();
        $table->string('last_name')->nullable(false)->change();
        $table->string('first_name')->nullable(false)->change();
    });
}
</code>```

Body:
Why am I getting this warning when using the SQLite driver? I have no problems with the MySQL driver but SQLite is throwing this error.

It does not make sense to me since I understood the seeding happens after all the migrations are completed so why is it complaining about this issue which would only arise if data was already present in the database.

My two migrations are

FIRST MIGRATION

  public function up() {
    Schema::create('users', function($table) {
      $table->increments('id');
      $table->string('username');
      $table->string('email');
      $table->string('password');
    });
  }

SECOND MIGRATION

public function up() {
    Schema::table('users', function(Blueprint $table) {
        $table->date('birthday')->after('id');
        $table->string('last_name')->after('id');
        $table->string('first_name')->after('id');
    });
}

ERROR

Exception: SQLSTATE[HY000]: General error: 1 Cannot add a NOT NULL column with default value NULL (SQL: alter table "users" add column "birthday" date not null)

Body:
Another work around for this issue is to first create the fields as nullable and then later change the fields to be not null. So for example in this case we will do something like the following:

public function up() {
    // Create fields first as nullable
    Schema::table('users', function(Blueprint $table) {
        $table->date('birthday')->after('id')->nullable();
        $table->string('last_name')->after('id')->nullable();
        $table->string('first_name')->after('id')->nullable();
    });

    // Either truncate existing records or assign a value to new fields
    if (true) {
        DB::table('users')->truncate();
    } else {
        DB::table('users')->update([
            'birthday' => '2019-05-01',
            'last_name' => 'last name',
            'first_name' => 'first name',
        ]);
    }

    // Change the fields to not be null
    Schema::table('users', function(Blueprint $table) {
        $table->date('birthday')->nullable(false)->change();
        $table->string('last_name')->nullable(false)->change();
        $table->string('first_name')->nullable(false)->change();
    });
}


问:
How to calculating time difference
I'm trying to make a program where i put in to different times and get the difference in minute after clicking the "calculate" button. I'm not sure if my approach is correct, there may be some typo's.

I'v tried to make the different input values to number but it seems like there is another underlying problem which I can't see.

var hour1=document.getElementById("hour1");
var min1=document.getElementById("min1");
var hour2=document.getElementById("hour2");
var min2=document.getElementById("min2");

function calc(){
    var minutt1=Number(hour1)*60+Number(min1);
    var minutt2=Number(hour2)*60+Number(min2);
    var resultat=0;
    resultat = Number(minutt1) - Number(minutt2);
    document.getElementById("result").innerHTML="Time differance is:" + Number(resultat);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="number" id="hour1">:
<input type="number" id="min1"> -
<input type="number" id="hour2">:
<input type="number" id="min1">
<button type="button" onclick="calc()">Regn ut</button>

<div id="result"></div></code>```

I expect getting a number which represents the time difference in minutes, but the actual output is "NaN".

答:
Other answers are close, but you need to get the value of the inputs after you click the button

var hour1 = document.getElementById("hour1");
var min1 = document.getElementById("min1");
var hour2 = document.getElementById("hour2");
var min2 = document.getElementById("min2");

window.calc = function () {
  var minutt1 = parseInt(hour1.value) * 60 + parseInt(min1.value);
  var minutt2 = parseInt(hour2.value) * 60 + parseInt(min2.value);
  var resultat = minutt1 - minutt2;
  document.getElementById("result").innerHTML = "Time differance is:" + resultat;

  console.log({minutt1:minutt1,minutt2:minutt2,resultat:resultat,
  hour1:hour1,min1:min1,
  hour2:hour2,min2:min2
  })
};```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="number" id="hour1">:
<input type="number" id="min1"> -
<input type="number" id="hour2">:
<input type="number" id="min2">
<button type="button" onclick="calc()">Regn ut</button>

<div id="result"></div></code>```

Title: How to calculating time difference

Body:
I'm trying to make a program where i put in to different times and get the difference in minute after clicking the "calculate" button. I'm not sure if my approach is correct, there may be some typo's.

I'v tried to make the different input values to number but it seems like there is another underlying problem which I can't see.

var hour1=document.getElementById("hour1");
var min1=document.getElementById("min1");
var hour2=document.getElementById("hour2");
var min2=document.getElementById("min2");

function calc(){
    var minutt1=Number(hour1)*60+Number(min1);
    var minutt2=Number(hour2)*60+Number(min2);
    var resultat=0;
    resultat = Number(minutt1) - Number(minutt2);
    document.getElementById("result").innerHTML="Time differance is:" + Number(resultat);
}

<input type="number" id="hour1">:
<input type="number" id="min1"> -
<input type="number" id="hour2">:
<input type="number" id="min1">
<button type="button" onclick="calc()">Regn ut</button>

I expect getting a number which represents the time difference in minutes, but the actual output is "NaN".

Body:
Other answers are close, but you need to get the value of the inputs after you click the button

var hour1 = document.getElementById("hour1");
var min1 = document.getElementById("min1");
var hour2 = document.getElementById("hour2");
var min2 = document.getElementById("min2");

window.calc = function () {
  var minutt1 = parseInt(hour1.value) * 60 + parseInt(min1.value);
  var minutt2 = parseInt(hour2.value) * 60 + parseInt(min2.value);
  var resultat = minutt1 - minutt2;
  document.getElementById("result").innerHTML = "Time differance is:" + resultat;

  console.log({minutt1:minutt1,minutt2:minutt2,resultat:resultat,
  hour1:hour1,min1:min1,
  hour2:hour2,min2:min2
  })
};

<input type="number" id="hour1">:
<input type="number" id="min1"> -
<input type="number" id="hour2">:
<input type="number" id="min2">
<button type="button" onclick="calc()">Regn ut</button>

<div id="result"></div>


问:
How to use Selenium select class on HTML DOM which has "ul" / "li" tags in it
I assume the developers are using latest HTML version where in the drop down are handled more dynamically and the usage of "ul" and "li" have become more common than the traditional "select".
How do we use Seleniums select class to select by visible text / index on ul / li elements?

The only solution I see:
1. Click on the drop down.
2. Click the option / text.

Is there any other way?

答:
Selenium's Select class is only capable of working with HTML <select> tag, it will not be able to deal with custom representations which look like a dropdown but in reality they're just hyperlinks so you will have to do what real user does, i.e. click at the dropdown followed by the click at the desired option.

The good practice is introducing an abstraction layer via i.e. Page Object Model design pattern so you would be able to operate code blocks like:

```<code>myPage.selectFromSomeDropDown("someValue");
</code>```

where selectFromSomeDropDown function will contain the relevant implementation.

Body:
Selenium's Select class is only capable of working with HTML <select> tag, it will not be able to deal with custom representations which look like a dropdown but in reality they're just hyperlinks so you will have to do what real user does, i.e. click at the dropdown followed by the click at the desired option.

The good practice is introducing an abstraction layer via i.e. Page Object Model design pattern so you would be able to operate code blocks like:

myPage.selectFromSomeDropDown("someValue");

where selectFromSomeDropDown function will contain the relevant implementation.


问:
Set Custom Coordinates to a function, Waze Integration
I'm trying to implement navigation using Waze in my App, using their own API: here.

I want to set in custom coordinates that are set in an array
and then fit them in this code:

```<code>func navigate(toLatitude latitude: Double , longitude: Double) {
                if UIApplication.shared.canOpenURL(URL(string: "waze://")!) {
                    // Waze is installed. Launch Waze and start navigation
                    let urlStr: String = "waze://?ll=\(latitude),\(longitude)&navigate=yes"
                    UIApplication.shared.openURL(URL(string: urlStr)!)
                }
                else {
                    // Waze is not installed. Launch AppStore to install Waze app
                    UIApplication.shared.openURL(URL(string: "http://itunes.apple.com/us/app/id323229106")!)
                }
            }
</code>```

i have tried settings up different type of arrays but didn't succeed to make it work . So if you could help me out set custom array holding latitude and longitude that would work properly with the code, that would be awesome

your help will be very much helpful,

Thank you in advance.

答:
When compiling with iOS SDK 9.0 and later, you must update your application's property list file with the following to include Waze:

<key>LSApplicationQueriesSchemes</key>
<array>
  <string>waze</string>
</array>```

Body:
I'm trying to implement navigation using Waze in my App, using their own API: here.

I want to set in custom coordinates that are set in an array
and then fit them in this code:

func navigate(toLatitude latitude: Double , longitude: Double) {
                if UIApplication.shared.canOpenURL(URL(string: "waze://")!) {
                    // Waze is installed. Launch Waze and start navigation
                    let urlStr: String = "waze://?ll=\(latitude),\(longitude)&navigate=yes"
                    UIApplication.shared.openURL(URL(string: urlStr)!)
                }
                else {
                    // Waze is not installed. Launch AppStore to install Waze app
                    UIApplication.shared.openURL(URL(string: "http://itunes.apple.com/us/app/id323229106")!)
                }
            }

i have tried settings up different type of arrays but didn't succeed to make it work . So if you could help me out set custom array holding latitude and longitude that would work properly with the code, that would be awesome

your help will be very much helpful,

Thank you in advance.


问:
How to get product availability with product id in magento?
Is it possible to get product availability by passing a product ID to the Magento system?</p>

答:
To fetch the quantity (in stock) for any given product</p>

```<code>$model = Mage::getModel('catalog/product');
$_product = $model->load($product_id);
$stocklevel = (int)Mage::getModel('cataloginventory/stock_item')
                ->loadByProduct($_product)->getQty();
</code>```

Body:
To fetch the quantity (in stock) for any given product

$model = Mage::getModel('catalog/product');
$_product = $model->load($product_id);
$stocklevel = (int)Mage::getModel('cataloginventory/stock_item')
                ->loadByProduct($_product)->getQty();


问:
Azure Databricks - Unable to read simple blob storage file from notebook
I've set up a cluster with databricks runtime version 5.1 (includes Apache Spark 2.4.0, Scala 2.11) and Python 3. I also installed hadoop azure library (hadoop-azure-3.2.0) to the cluster.

I'm trying to read a blob stored in my blob storage account which is just a text file containing some numeric data delimited by spaces for example. I used the template generated by databricks for reading blob data

```<code>    spark.conf.set(
      "fs.azure.account.key."+storage_account_name+".blob.core.windows.net",
      storage_account_access_key)
    df = spark.read.format(file_type).option("inferSchema", "true").load(file_location)
</code>```

where file_location is my blob file (https://xxxxxxxxxx.blob.core.windows.net).

I get the following error:

No filesystem named https

I tried using sc.textFile(file_location) to read in an rdd and get the same error.

答:
You need to mount the blob with external location to access it via Azure Databricks.

Reference: https://docs.databricks.com/spark/latest/data-sources/azure/azure-storage.html#mount-azure-blob-storage-containers-with-dbfs

Body:
I've set up a cluster with databricks runtime version 5.1 (includes Apache Spark 2.4.0, Scala 2.11) and Python 3. I also installed hadoop azure library (hadoop-azure-3.2.0) to the cluster.

I'm trying to read a blob stored in my blob storage account which is just a text file containing some numeric data delimited by spaces for example. I used the template generated by databricks for reading blob data

    spark.conf.set(
      "fs.azure.account.key."+storage_account_name+".blob.core.windows.net",
      storage_account_access_key)
    df = spark.read.format(file_type).option("inferSchema", "true").load(file_location)

where file_location is my blob file (https://xxxxxxxxxx.blob.core.windows.net).

I get the following error:

No filesystem named https

I tried using sc.textFile(file_location) to read in an rdd and get the same error.


问:
My Bootstrap CSS link doesn't work for me?
I have a problem with the Bootstrap link which usually goes into the HTML file:

```<code><link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
</code>```

It makes my navbar looks like:

(I need at least 10 reputation to post images, so I have to post the direct link)
https://i.imgur.com/dANnzzG.png

and after I remove the link:

(I need at least 10 reputation to post images, so I have to post the direct link)
 https://i.imgur.com/EpnZCeK.png

But as you can see on the 2 picture, if I dont have the link, the stuff down the navbar ins't in the right position anymore. Please Help.

EDIT:

```<code><link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<div class="row">
  <div class="col-6">
      <app-list-employees></app-list-employees>
</div>
  <div class="col-6">
     <div><app-book-employee></app-book-employee></div>
     <p></p>
    <div><app-calendar-books></app-calendar-books></div>
  </div>
</div>
</code>```

That's the code for the component.

答:
If you are using angular 6+ in your application it is best advised if you install bootstrap through npm as follows:

```<code>npm install --save bootstrap
</code>```

After installing bootstrap add this line in your src/style.css file:

```<code>@import 'bootstrap/dist/css/bootstrap.min.css';
</code>```

This will give you all the bootstrap styles so adding it in your index.html file or angular.json file is not needed

Body:
I have a problem with the Bootstrap link which usually goes into the HTML file:

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">

It makes my navbar looks like:

(I need at least 10 reputation to post images, so I have to post the direct link)
https://i.imgur.com/dANnzzG.png

and after I remove the link:

(I need at least 10 reputation to post images, so I have to post the direct link)
 https://i.imgur.com/EpnZCeK.png

But as you can see on the 2 picture, if I dont have the link, the stuff down the navbar ins't in the right position anymore. Please Help.

EDIT:

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">

      <app-list-employees></app-list-employees>

<app-book-employee></app-book-employee>

<app-calendar-books></app-calendar-books>

That's the code for the component.

Body:
If you are using angular 6+ in your application it is best advised if you install bootstrap through npm as follows:

npm install --save bootstrap

After installing bootstrap add this line in your src/style.css file:

@import 'bootstrap/dist/css/bootstrap.min.css';

This will give you all the bootstrap styles so adding it in your index.html file or angular.json file is not needed


问:
How to pass data from VUEX Store to serverMiddleware API?
Is it possible to pass data from Vuex Store to serverMiddleware in Nuxt.js?

```<code>  async SET_DATA({commit}, payload) {
    await this.$axios.$post('/api', { data: payload.data})
    commit('SET_DATA', payload.data)
  }
</code>```

In nuxt.config

```<code>  serverMiddleware: [
    { path: '/api', handler: '~/api/index' }
  ]
</code>```

Then how do I access the data in api/index.js ?

```<code>export default function (req, res, next) {
  // Get data from Store here

  next()
}
</code>```

答:
The only way I found is;

readFile & writeFile functions.

In nuxt.config

modules: ['~/api/api.js'],

In api/api.js

I use this method, because of servermiddleware causes bug when you try to build app.

```<code>module.exports = function (moduleOptions) {
//Add middleware only with `nuxt dev` or `nuxt start`
var fs = require('fs');

// Save file from env or vuex anything comes with this
fs.writeFile('envTransfer.txt',  JSON.stringify(this.options.env), function (err) {
  if (err) throw err;
  console.log('Saved!');
});

// Then call addServermiddleware
 //Add middleware only with `nuxt dev` or `nuxt start`
if (this.options.dev || this.options._start) {
  this.addServerMiddleware('~/api/index.js')
}
}
</code>```

In the part api/index.js (  node & express )

```<code>const fs        = require('fs');
const express = require('express');
const app = express()
....
let content="";
fs.readFile('envTransfer.txt',  function(err, data) {
if (err) throw err;
content = data;
var obj = JSON.parse(content);

 // do it what ever you want

app.get('/', (req, res, next) => {
     // res.send('API root')
})

// export the server middleware
    module.exports = {
      path: '/api',
      handler: app
   }
});
</code>```

Body:
Is it possible to pass data from Vuex Store to serverMiddleware in Nuxt.js?

  async SET_DATA({commit}, payload) {
    await this.$axios.$post('/api', { data: payload.data})
    commit('SET_DATA', payload.data)
  }

In nuxt.config

  serverMiddleware: [
    { path: '/api', handler: '~/api/index' }
  ]

Then how do I access the data in api/index.js ?

export default function (req, res, next) {
  // Get data from Store here

  next()
}

Body:
The only way I found is;

readFile & writeFile functions.

In nuxt.config

modules: ['~/api/api.js'],

In api/api.js

I use this method, because of servermiddleware causes bug when you try to build app.

module.exports = function (moduleOptions) {
//Add middleware only with `nuxt dev` or `nuxt start`
var fs = require('fs');

// Save file from env or vuex anything comes with this
fs.writeFile('envTransfer.txt',  JSON.stringify(this.options.env), function (err) {
  if (err) throw err;
  console.log('Saved!');
});

// Then call addServermiddleware
 //Add middleware only with `nuxt dev` or `nuxt start`
if (this.options.dev || this.options._start) {
  this.addServerMiddleware('~/api/index.js')
}
}

In the part api/index.js (  node & express )

const fs        = require('fs');
const express = require('express');
const app = express()
....
let content="";
fs.readFile('envTransfer.txt',  function(err, data) {
if (err) throw err;
content = data;
var obj = JSON.parse(content);

 // do it what ever you want

app.get('/', (req, res, next) => {
     // res.send('API root')
})

// export the server middleware
    module.exports = {
      path: '/api',
      handler: app
   }
});


问:
Given a list of elements, replicate each element N times
I have to replicate each element n times like this:
?- replicate([a,b,c],2,X).  -> X = [a,a,b,b,c,c]
?- replicate([a,b,c],3,X).  -> X = [a,a,a,b,b,b,c,c,c]

I have tried everything with the information I have so far, the only thing I have been able to do is to determine which is the most repeating element like this:

```<code>%List of tuples, keeps track of the number of repetitions.
modify([],X,[(X,1)]).
modify([(X,Y)|Xs],X,[(X,K)|Xs]):- K is Y+1.
modify([(Z,Y)|Xs],X,[(Z,Y)|K]):- Z =\= X, modify(Xs,X,K).

highest((X1,Y1),(_,Y2),(X1,Y1)):- Y1 >= Y2.
highest((_,Y1),(X2,Y2),(X2,Y2)):- Y2 > Y1.

maxR([X],X).
maxR([X|Xs],K):- maxR(Xs,Z),highest(X,Z,K).

rep([],R,R).
rep([X|Xs],R,R1):-modify(R,X,R2),rep(Xs,R2,R1).

maxRepeated(X,R):- rep(X,[],K),maxR(K,R).

?- maxRepeated([1,3,3,4,3,2] ,X).
X = (3, 3) .

?- maxRepeated([1,2,3,4,5,6] ,X).
X = (1, 1) .
</code>```

答:
What do you want to do ?
Take each element X of the list, get a list of N X and create a new list with the process of the rest of the list !
How to get a list of N elements X ?

```<code>replicate_one(X, N, Out) :-
    length(Out, N),
    maplist(=(X),Out).
</code>```

Now, how to work with each element of the input, it can be easily done with the pattern [Head|Tail] :

```<code>replicate([Head|Tail], N, Out) :-
    % I replicate the rest of the list
    replicate(Tail, N, Tmp1),
    % I replicate the first element of the list
    replicate_one(Head, N, Tmp2),
    % I concatenate the 2 results
    append(Tmp2, Tmp1, Out).
</code>```

When you work with replicate, the input looses an element each time, so you must have a process for the empty list :

```<code>replicate([], _N, []).
</code>```

Now :

```<code>  ?- replicate([a,b,c],3,X).
X = [a, a, a, b, b, b, c, c, c].
</code>```

Body:
I have to replicate each element n times like this:
?- replicate([a,b,c],2,X).  -> X = [a,a,b,b,c,c]
?- replicate([a,b,c],3,X).  -> X = [a,a,a,b,b,b,c,c,c]

I have tried everything with the information I have so far, the only thing I have been able to do is to determine which is the most repeating element like this:

%List of tuples, keeps track of the number of repetitions.
modify([],X,[(X,1)]).
modify([(X,Y)|Xs],X,[(X,K)|Xs]):- K is Y+1.
modify([(Z,Y)|Xs],X,[(Z,Y)|K]):- Z =\= X, modify(Xs,X,K).

highest((X1,Y1),(_,Y2),(X1,Y1)):- Y1 >= Y2.
highest((_,Y1),(X2,Y2),(X2,Y2)):- Y2 > Y1.

maxR([X],X).
maxR([X|Xs],K):- maxR(Xs,Z),highest(X,Z,K).

rep([],R,R).
rep([X|Xs],R,R1):-modify(R,X,R2),rep(Xs,R2,R1).

maxRepeated(X,R):- rep(X,[],K),maxR(K,R).

?- maxRepeated([1,3,3,4,3,2] ,X).
X = (3, 3) .

?- maxRepeated([1,2,3,4,5,6] ,X).
X = (1, 1) .

Body:
What do you want to do ?
Take each element X of the list, get a list of N X and create a new list with the process of the rest of the list !
How to get a list of N elements X ?

replicate_one(X, N, Out) :-
    length(Out, N),
    maplist(=(X),Out).

Now, how to work with each element of the input, it can be easily done with the pattern [Head|Tail] :

replicate([Head|Tail], N, Out) :-
    % I replicate the rest of the list
    replicate(Tail, N, Tmp1),
    % I replicate the first element of the list
    replicate_one(Head, N, Tmp2),
    % I concatenate the 2 results
    append(Tmp2, Tmp1, Out).

When you work with replicate, the input looses an element each time, so you must have a process for the empty list :

replicate([], _N, []).

Now :

  ?- replicate([a,b,c],3,X).
X = [a, a, a, b, b, b, c, c, c].


问:
Kendo Grid Server side filtering with a array type column
I have this kendo grid blinded to my web service. One of the columns has a custom filter with a kendo multiselector array so the client can choose multiple ItemTypes. The grid is displaying data correctly but my costume filters are not working for this particular column. I got this error from the service: "A binary operator with incompatible types was detected. Found operand types 'Telerik.Sitefinity.DynamicTypes.Model.ClinicFinder.Clinic.ItemType.ItemType' and 'Edm.Int32' for operator kind 'Equal'."

My grid definition

```<code>$("#grid").kendoGrid({
dataSource: {
    type: "odata-v4",
    transport: {
        read: {
            url: function () {
                return "//myservice/api/clinics?$select=Id,Title,Address,ItemType,productsystems&top=20";
            }
        }
    },
    schema: {
        model: {
            fields: {
                Title: { type: "string" },
                CountryCode: { type: "string" },
                Street: { type: "string" },
                City: { type: "string" },
                Zip: { type: "string" },
                ItemType: { type: "" }

            }
        }
    },
    serverPaging: true,
    serverFiltering: true,
    serverSorting: false,
    pageSize: 20
},
pageable: true,
filterable: {
    mode: "row",
    extra: false,
    showOperators: false,
    operators: {
        string: {
            contains: "contains"
        }
    }
},
sortable: false,
columns: [
    { field: "Title", title: "Clinic" },
    { field: "CountryCode", title: "Country" },
    { field: "Street", title: "Address" },
    { field: "City", title: "City"  },
    { field: "Zip", title: "Zip",  filterable: false },
    { field: "ItemType", title: "Clinic Type", filterable: { multi: true } }
],
rowTemplate: kendo.template($("#template").html())

});
</code>```

My Filter function

```<code>function filterByclinicCategory() {
var filter = { logic: "or", filters: [] };
var grid = $('#grid').data('kendoGrid');
var filterValue = $("#clinicTypeFilter").data("kendoMultiSelect").value();
var clinicCode = [];
if (filterValue.length > 0) {
    $.each(filterValue, function (i, v) {
        clinicCode.push(convertClinicTypesInCodes(v));
        filter.filters.push({
            field: "ItemType", operator: "eq", value: clinicCode, logic: "or"
        });
        grid.dataSource.filter(filter);
    });

} else {
    $("#grid").data("kendoGrid").dataSource.filter({});
}

}
</code>```

ItemType is the column I can´t filter.

My webservice data

```<code>{
"@odata.context": "https://sf-admin-local.medel.com/api/wstest/$metadata#clinics(*)",
"value": [
{
"Id": "896aa08b-2f17-64e6-80bd-ff09000c6e28",
"LastModified": "2019-05-13T09:28:04Z",
"PublicationDate": "2018-06-19T14:19:13Z",
"DateCreated": "2018-06-19T14:19:13Z",
"UrlName": "??",
"Email": "",
"URL": "",
"Telephone": "",
"Title": "????????",
"officeregions": [],
"salespartnerregions": [],
"productsystems": [
"b8ec2a8b-2f17-64e6-80bd-ff09000c6e28",
"1878cb61-ac79-69d9-867b-ff01007297b6",
"1b78cb61-ac79-69d9-867b-ff01007297b6",
"36d8938b-2f17-64e6-80bd-ff09000c6e28"
],
"Area": "",
"Order": 0,
"Tags": [],
"AdditionalInformation": "",
"ImportID": 1,
"Featured": false,
"ItemType": "2",
"Address": {
"Id": "d76aa08b-2f17-64e6-80bd-ff09000c6e28",
"CountryCode": "AT",
"StateCode": "",
"City": "????",
"Zip": "6800",
"Street": "Carinagasse ?????",
"Latitude": 47.2311043,
"Longitude": 9.580079999999953,
"MapZoomLevel": 8
}
}
]
}
</code>```

答:
I manage to fix it using parameterMap https://docs.telerik.com/kendo-ui/api/javascript/data/datasource/configuration/transport.parametermap.

I add a parameterMap: functiondata, type) function, with that I was able to intercept and change the call made by the filters.

```<code> parameterMap: function (data, type) {
     var c = kendo.data.transports["odata-v4"].parameterMap(data, type);
     if (c.$filter) {
     //my transformation
     c = myTransformation;
     return c;
     } else{
     return c; //not apply transformation loading the data
     }

 }
</code>```

Body:
I have this kendo grid blinded to my web service. One of the columns has a custom filter with a kendo multiselector array so the client can choose multiple ItemTypes. The grid is displaying data correctly but my costume filters are not working for this particular column. I got this error from the service: "A binary operator with incompatible types was detected. Found operand types 'Telerik.Sitefinity.DynamicTypes.Model.ClinicFinder.Clinic.ItemType.ItemType' and 'Edm.Int32' for operator kind 'Equal'."

My grid definition

$("#grid").kendoGrid({
dataSource: {
    type: "odata-v4",
    transport: {
        read: {
            url: function () {
                return "//myservice/api/clinics?$select=Id,Title,Address,ItemType,productsystems&top=20";
            }
        }
    },
    schema: {
        model: {
            fields: {
                Title: { type: "string" },
                CountryCode: { type: "string" },
                Street: { type: "string" },
                City: { type: "string" },
                Zip: { type: "string" },
                ItemType: { type: "" }

            }
        }
    },
    serverPaging: true,
    serverFiltering: true,
    serverSorting: false,
    pageSize: 20
},
pageable: true,
filterable: {
    mode: "row",
    extra: false,
    showOperators: false,
    operators: {
        string: {
            contains: "contains"
        }
    }
},
sortable: false,
columns: [
    { field: "Title", title: "Clinic" },
    { field: "CountryCode", title: "Country" },
    { field: "Street", title: "Address" },
    { field: "City", title: "City"  },
    { field: "Zip", title: "Zip",  filterable: false },
    { field: "ItemType", title: "Clinic Type", filterable: { multi: true } }
],
rowTemplate: kendo.template($("#template").html())

});

My Filter function

function filterByclinicCategory() {
var filter = { logic: "or", filters: [] };
var grid = $('#grid').data('kendoGrid');
var filterValue = $("#clinicTypeFilter").data("kendoMultiSelect").value();
var clinicCode = [];
if (filterValue.length > 0) {
    $.each(filterValue, function (i, v) {
        clinicCode.push(convertClinicTypesInCodes(v));
        filter.filters.push({
            field: "ItemType", operator: "eq", value: clinicCode, logic: "or"
        });
        grid.dataSource.filter(filter);
    });

} else {
    $("#grid").data("kendoGrid").dataSource.filter({});
}

}

ItemType is the column I can´t filter.

My webservice data

{
"@odata.context": "https://sf-admin-local.medel.com/api/wstest/$metadata#clinics(*)",
"value": [
{
"Id": "896aa08b-2f17-64e6-80bd-ff09000c6e28",
"LastModified": "2019-05-13T09:28:04Z",
"PublicationDate": "2018-06-19T14:19:13Z",
"DateCreated": "2018-06-19T14:19:13Z",
"UrlName": "??",
"Email": "",
"URL": "",
"Telephone": "",
"Title": "????????",
"officeregions": [],
"salespartnerregions": [],
"productsystems": [
"b8ec2a8b-2f17-64e6-80bd-ff09000c6e28",
"1878cb61-ac79-69d9-867b-ff01007297b6",
"1b78cb61-ac79-69d9-867b-ff01007297b6",
"36d8938b-2f17-64e6-80bd-ff09000c6e28"
],
"Area": "",
"Order": 0,
"Tags": [],
"AdditionalInformation": "",
"ImportID": 1,
"Featured": false,
"ItemType": "2",
"Address": {
"Id": "d76aa08b-2f17-64e6-80bd-ff09000c6e28",
"CountryCode": "AT",
"StateCode": "",
"City": "????",
"Zip": "6800",
"Street": "Carinagasse ?????",
"Latitude": 47.2311043,
"Longitude": 9.580079999999953,
"MapZoomLevel": 8
}
}
]
}

Body:
I manage to fix it using parameterMap https://docs.telerik.com/kendo-ui/api/javascript/data/datasource/configuration/transport.parametermap.

I add a parameterMap: functiondata, type) function, with that I was able to intercept and change the call made by the filters.

 parameterMap: function (data, type) {
     var c = kendo.data.transports["odata-v4"].parameterMap(data, type);
     if (c.$filter) {
     //my transformation
     c = myTransformation;
     return c;
     } else{
     return c; //not apply transformation loading the data
     }

 }


问:
Tflite TOCO conversion failed for K.random_normal(shape=(batch, dim))
I am using toco_convert of tensorflow lite for some old work.
These are the errors I am getting for the following commands.

```<code>toco\
--graph_def_file=6-graphmh-55epoc.pb \
--input_format=TENSORFLOW_GRAPHDEF \
--output_format=TFLITE \
--output_file=/leaves.tflite \
--inference_type=FLOAT \
--input_type=FLOAT \
--input_arrays=ImageTensor \
--output_arrays=SemanticPredictions \
--input_shapes=1,113,3 \
</code>```

The error I am getting is:

```<code>Traceback (most recent call last):
  File "C:\Users\ash\AppData\Local\Continuum\anaconda3\envs\diec\Scripts\toco_from_protos-script.py", line 10, in <module>
    sys.exit(main())
  File "C:\Users\ash\AppData\Local\Continuum\anaconda3\envs\diec\lib\site-packages\tensorflow\lite\toco\python\toco_from_protos.py", line 59, in main
    app.run(main=execute, argv=[sys.argv[0]] + unparsed)
  File "C:\Users\ash\AppData\Local\Continuum\anaconda3\envs\diec\lib\site-packages\tensorflow\python\platform\app.py", line 125, in run
    _sys.exit(main(argv))
  File "C:\Users\ash\AppData\Local\Continuum\anaconda3\envs\diec\lib\site-packages\tensorflow\lite\toco\python\toco_from_protos.py", line 33, in execute
    output_str = tensorflow_wrap_toco.TocoConvert(model_str, toco_str, input_str)
Exception: We are continually in the process of adding support to TensorFlow Lite for more ops. It would be helpful if you could inform us of how this conversion went by opening a github issue at https://github.com/tensorflow/tensorflow/issues/new?template=40-tflite-op-request.md
 and pasting the following:

Some of the operators in the model are not supported by the standard TensorFlow Lite runtime. If those are native TensorFlow operators, you might be able to use the extended runtime by passing --enable_select_tf_ops, or by setting target_ops=TFLITE_BUILTINS,SELECT_TF_OPS when calling tf.lite.TFLiteConverter(). Otherwise, if you have a custom implementation for them you can disable this error with --allow_custom_ops, or by setting allow_custom_ops=True when calling tf.lite.TFLiteConverter(). Here is a list of builtin operators you are using: ADD, EXP, FULLY_CONNECTED, LOGISTIC, MUL. Here is a list of operators for which you will need custom implementations: RandomStandardNormal.
</code>```

I know that tf.lite.toco_convert is depricated, but I need it for old works.
I think it is due to the following line
epsilon = K.random_normal(shape=(batch, dim))
return z_mean + K.exp(0.5 * z_log_var) * epsilon.
I am not sure why is this happening, cuz the old tensorflow keras.backend has random_normal attribute.
It would be helpful if you can debug or point to some resources to circumvent this error.

答:
Found the solution from here : https://www.tensorflow.org/lite/guide/ops_select

```<code>import tensorflow as tf

converter = tf.lite.TFLiteConverter.from_saved_model(saved_model_dir)
converter.target_ops = [tf.lite.OpsSet.TFLITE_BUILTINS,
                        tf.lite.OpsSet.SELECT_TF_OPS]
tflite_model = converter.convert()
open("converted_model.tflite", "wb").write(tflite_model)
</code>```

It is because RandomStandardNormal is not part of TensorFlow lite, so we need to use tf.lite.OpsSet to include it

Body:
I am using toco_convert of tensorflow lite for some old work.
These are the errors I am getting for the following commands.

toco\
--graph_def_file=6-graphmh-55epoc.pb \
--input_format=TENSORFLOW_GRAPHDEF \
--output_format=TFLITE \
--output_file=/leaves.tflite \
--inference_type=FLOAT \
--input_type=FLOAT \
--input_arrays=ImageTensor \
--output_arrays=SemanticPredictions \
--input_shapes=1,113,3 \

The error I am getting is:

Traceback (most recent call last):
  File "C:\Users\ash\AppData\Local\Continuum\anaconda3\envs\diec\Scripts\toco_from_protos-script.py", line 10, in <module>
    sys.exit(main())
  File "C:\Users\ash\AppData\Local\Continuum\anaconda3\envs\diec\lib\site-packages\tensorflow\lite\toco\python\toco_from_protos.py", line 59, in main
    app.run(main=execute, argv=[sys.argv[0]] + unparsed)
  File "C:\Users\ash\AppData\Local\Continuum\anaconda3\envs\diec\lib\site-packages\tensorflow\python\platform\app.py", line 125, in run
    _sys.exit(main(argv))
  File "C:\Users\ash\AppData\Local\Continuum\anaconda3\envs\diec\lib\site-packages\tensorflow\lite\toco\python\toco_from_protos.py", line 33, in execute
    output_str = tensorflow_wrap_toco.TocoConvert(model_str, toco_str, input_str)
Exception: We are continually in the process of adding support to TensorFlow Lite for more ops. It would be helpful if you could inform us of how this conversion went by opening a github issue at https://github.com/tensorflow/tensorflow/issues/new?template=40-tflite-op-request.md
 and pasting the following:

Some of the operators in the model are not supported by the standard TensorFlow Lite runtime. If those are native TensorFlow operators, you might be able to use the extended runtime by passing --enable_select_tf_ops, or by setting target_ops=TFLITE_BUILTINS,SELECT_TF_OPS when calling tf.lite.TFLiteConverter(). Otherwise, if you have a custom implementation for them you can disable this error with --allow_custom_ops, or by setting allow_custom_ops=True when calling tf.lite.TFLiteConverter(). Here is a list of builtin operators you are using: ADD, EXP, FULLY_CONNECTED, LOGISTIC, MUL. Here is a list of operators for which you will need custom implementations: RandomStandardNormal.

I know that tf.lite.toco_convert is depricated, but I need it for old works.
I think it is due to the following line
epsilon = K.random_normal(shape=(batch, dim))
return z_mean + K.exp(0.5 * z_log_var) * epsilon.
I am not sure why is this happening, cuz the old tensorflow keras.backend has random_normal attribute.
It would be helpful if you can debug or point to some resources to circumvent this error.

Body:
Found the solution from here : https://www.tensorflow.org/lite/guide/ops_select

import tensorflow as tf

converter = tf.lite.TFLiteConverter.from_saved_model(saved_model_dir)
converter.target_ops = [tf.lite.OpsSet.TFLITE_BUILTINS,
                        tf.lite.OpsSet.SELECT_TF_OPS]
tflite_model = converter.convert()
open("converted_model.tflite", "wb").write(tflite_model)

It is because RandomStandardNormal is not part of TensorFlow lite, so we need to use tf.lite.OpsSet to include it