问:
Column width issue with jQuery DataTables and jQuery UI Accordion
I'm using DataTables with a jQuery UI accordion.

I have code which fills the Datatable with data (vis json) when the accordion section is opened, but this doesn't align the header correctly.

Table definition

```<code>        $('#tblSuppContacts').dataTable({
              "autoWidth":false
            , "footer": false
            , "info":false
            , "JQueryUI":true
            , "language": {"emptyTable":"No Contacts For Supplier"}
            , "ordering":true
            , "paging":false
            , "scrollY":"325px"
            , "scrollCollapse": true
            , "columnDefs": [
                        { className: "LeftNoWrap", "targets": [ 1,2,3,4,5,6,7 ] }
                    ,   { className: "RightNoWrap", "targets": [ 0 ] }
                ]
        });
</code>```

This is the code which fires when the accordion section opens which checks if the table has any rows before reading it.

```<code>var table = $('#tblSuppAddress').DataTable();
if ( ! table.data().any() ) {fncSuppAddressRead();}
</code>```

Then this codes loads the data into the table.

```<code>    if ( $.fn.DataTable.isDataTable('#tblSuppContacts') ) {
        $('#tblSuppContacts').DataTable().clear();
    }

    var dTable = $('#tblSuppContacts').DataTable();

    for (var i = 0; i < pData.length; i++) {
        dTable.row.add([
             fncFormatNumber(pData[i].REF,0,"N")
            ,trim(pData[i].NAME)
            ,trim(pData[i].DEPARTMENT)
            ,trim(pData[i].POSITION)
            ,trim(pData[i].PHONE)
            ,trim(pData[i].FAX)
            ,trim(pData[i].COMMENT)
            ,trim(pData[i].EMAIL)
        ]);
    }
    $('#tblSuppContacts').DataTable().draw();
}
</code>```

When i click on the table header, the columns headers then line up correctly with the data columns.

答:
Use the code below to force jQuery DataTables to recalculate column widths for initially hidden table when accordion content becomes visible.

$(".accordion").accordion({
   activate: function( event, ui ) {
      $($.fn.dataTable.tables(true)).DataTable()
         .columns.adjust();
   }
});
```

See jQuery DataTables: Column width issues with Bootstrap tabs for more information, examples and details.

Body:
I'm using DataTables with a jQuery UI accordion.

I have code which fills the Datatable with data (vis json) when the accordion section is opened, but this doesn't align the header correctly.

Table definition

        $('#tblSuppContacts').dataTable({
              "autoWidth":false
            , "footer": false
            , "info":false
            , "JQueryUI":true
            , "language": {"emptyTable":"No Contacts For Supplier"}
            , "ordering":true
            , "paging":false
            , "scrollY":"325px"
            , "scrollCollapse": true
            , "columnDefs": [
                        { className: "LeftNoWrap", "targets": [ 1,2,3,4,5,6,7 ] }
                    ,   { className: "RightNoWrap", "targets": [ 0 ] }
                ]
        });

This is the code which fires when the accordion section opens which checks if the table has any rows before reading it.

var table = $('#tblSuppAddress').DataTable();
if ( ! table.data().any() ) {fncSuppAddressRead();}

Then this codes loads the data into the table.

    if ( $.fn.DataTable.isDataTable('#tblSuppContacts') ) {
        $('#tblSuppContacts').DataTable().clear();
    }

    var dTable = $('#tblSuppContacts').DataTable();

    for (var i = 0; i < pData.length; i++) {
        dTable.row.add([
             fncFormatNumber(pData[i].REF,0,"N")
            ,trim(pData[i].NAME)
            ,trim(pData[i].DEPARTMENT)
            ,trim(pData[i].POSITION)
            ,trim(pData[i].PHONE)
            ,trim(pData[i].FAX)
            ,trim(pData[i].COMMENT)
            ,trim(pData[i].EMAIL)
        ]);
    }
    $('#tblSuppContacts').DataTable().draw();
}

When i click on the table header, the columns headers then line up correctly with the data columns.

Body:
Use the code below to force jQuery DataTables to recalculate column widths for initially hidden table when accordion content becomes visible.

$(".accordion").accordion({
   activate: function( event, ui ) {
      $($.fn.dataTable.tables(true)).DataTable()
         .columns.adjust();
   }
});

See jQuery DataTables: Column width issues with Bootstrap tabs for more information, examples and details.


来源: stackexchange

问:
Task cancellation: while loop not exited properly when ThrowIfCancellationRequested() is called
I've developed a small project (using MVVM) with functionality to upload a file to a FTP-server.

The user can view the uploading progress: percentage completed is shown to the user by vm.Busycontent, which is a property in my viewmodel bound to a UI element in my view.

Here is the code for reading the file and uploading via FTP (which is part of the Task vm.FtpUploadTask)

```<code>   using (FileStream inputStream = File.OpenRead(file))
        {
            using (outputStream = request.GetRequestStream())
            {
                var buffer = new byte[1024 * 1024];
                int totalReadBytesCount = 0;
                int readBytesCount;

                while ((readBytesCount = inputStream.Read(buffer, 0, buffer.Length)) > 0 && (!vm.Token.IsCancellationRequested))
                {
                    vm.Token.ThrowIfCancellationRequested();

                    outputStream.Write(buffer, 0, readBytesCount);
                    totalReadBytesCount += readBytesCount;
                    var progress = totalReadBytesCount * 100.0 / inputStream.Length;
                    vm.BusyContent = ((int)progress).ToString();
                }
            }
        }
</code>```

MainWindow.xaml

I am using WPF extended toolkit BusyIndicator

```<code><xctk:BusyIndicator IsBusy='{Binding IsBusy}'>
  <xctk:BusyIndicator.BusyContentTemplate>
    <DataTemplate>
      <StackPanel>
        <TextBlock Text='{Binding Path=DataContext.BusyContent,
            RelativeSource={RelativeSource AncestorType={x:Type Window}}}' />
      </StackPanel>
    </DataTemplate>
  </xctk:BusyIndicator.BusyContentTemplate>
</xctk:BusyIndicator>
</code>```

UploadToFTPCommand.cs

```<code>try
{
    vm.FtpUploadTask = new Task(() => FTPUpload(file), vm.Token);

    vm.FtpUploadTask.Start();
    vm.FtpUploadTask.Wait(vm.Token);

    vm.BusyContent = "upload done!";

}
catch (OperationCanceledException)
{
    vm.BusyContent = "Canceled";
}
</code>```

CancelCommand.cs

```<code>public class CancelCommand : ICommand
{
    public void Execute(object parameter)
    {
        vm.TokenSource.Cancel();
    }
}
</code>```

The cancel function works but sometimes vm.Busycontent equals to

((int)progress).ToString()

canceled in uploadftpcommand

When pressing the Cancel button, the while loop should be exited and the user should only see the message in the catch (OperationCanceledException).
Any ideas how to solve this?

Notes

I am using .NET 4.0

This program is a part of a larger project, which includes multipe Tasks that should be executed in a synchronous manner. That's why I am using Task.Start() and Task.Wait() methods.

Edit
Problem still remains

```<code>using (FileStream inputStream = File.OpenRead(file))
{
using (outputStream = request.GetRequestStream())
{
    var buffer = new byte[1024 * 1024];
    int totalReadBytesCount = 0;
    int readBytesCount;

    while ((readBytesCount = inputStream.Read(buffer, 0, buffer.Length)) > 0)
    {
        if (vm.Token.IsCancellationRequested)
        {
            break;
        }
        outputStream.Write(buffer, 0, readBytesCount);
        totalReadBytesCount += readBytesCount;
        var progress = totalReadBytesCount * 100.0 / inputStream.Length;
        vm.BusyContent = ((int)progress).ToString();
    }
    if (vm.Token.IsCancellationRequested)
    {

        inputStream.Close();
        outputStream.Close();
        vm.Token.ThrowIfCancellationRequested();
    }
}
</code>```

}

答:
You may have an issue relating to exactly how you've set up your code. Without going through every line of it, it's difficult to tell. But more to the point:

When pressing the Cancel button, the while loop should be exited and the user should only see the message in the catch (OperationCanceledException).

This shows exactly how to exit your while loop and throw an exception you can catch. Note the test asserts TaskCanceledException but you are right in just catching OperationCanceledException.

```<code>using System.Threading.Tasks;
using System.IO;
using System.Threading;

using NUnit.Framework;

namespace CancellationTests {

    [TestFixture]
    public class WhileCancellation {

        [Test]
        public void While_Loop_Is_Canceled_When_Cancel_Is_Requested() {
            var inputFile = new FileInfo("somebigfile.txt");
            var outputFile = new FileInfo("outputFile.txt");
            var cts = new CancellationTokenSource();

            cts.Cancel();

            Assert.ThrowsAsync<TaskCanceledException>(() => TheWhileLoop(inputFile, outputFile, cts.Token));
        }

        private async Task TheWhileLoop(FileInfo inputFile, FileInfo outputFile, CancellationToken token) {

            using (var inputStream = inputFile.OpenRead())
            using (var outputStream = outputFile.OpenWrite()) {
                var buffer = new byte[1024 * 1024];
                var totalReadBytesCount = 0;
                var readBytesCount = 0;

                while ((readBytesCount = await inputStream.ReadAsync(buffer, 0, buffer.Length, token)) > 0) {
                    await outputStream.WriteAsync(buffer, 0, readBytesCount, token);
                    token.ThrowIfCancellationRequested();
                    totalReadBytesCount += readBytesCount;
                    var progress = totalReadBytesCount * 100.0 / inputStream.Length;
                    vm.BusyContent = ((int)progress).ToString();
                }
            }
        }

        private static class vm {
            public static string BusyContent { get; set; }
        }
    }
}
</code>```

Hopefully this gets you on the right track.

ContentLicense: CC BY-SA 3.0

Body:
I've developed a small project (using MVVM) with functionality to upload a file to a FTP-server.

The user can view the uploading progress: percentage completed is shown to the user by vm.Busycontent, which is a property in my viewmodel bound to a UI element in my view.

Here is the code for reading the file and uploading via FTP (which is part of the Task vm.FtpUploadTask)

   using (FileStream inputStream = File.OpenRead(file))
        {
            using (outputStream = request.GetRequestStream())
            {
                var buffer = new byte[1024 * 1024];
                int totalReadBytesCount = 0;
                int readBytesCount;

                while ((readBytesCount = inputStream.Read(buffer, 0, buffer.Length)) > 0 && (!vm.Token.IsCancellationRequested))
                {
                    vm.Token.ThrowIfCancellationRequested();

                    outputStream.Write(buffer, 0, readBytesCount);
                    totalReadBytesCount += readBytesCount;
                    var progress = totalReadBytesCount * 100.0 / inputStream.Length;
                    vm.BusyContent = ((int)progress).ToString();
                }
            }
        }

MainWindow.xaml

I am using WPF extended toolkit BusyIndicator

<xctk:BusyIndicator IsBusy='{Binding IsBusy}'>
  <xctk:BusyIndicator.BusyContentTemplate>
    <DataTemplate>
      <StackPanel>
        <TextBlock Text='{Binding Path=DataContext.BusyContent,
            RelativeSource={RelativeSource AncestorType={x:Type Window}}}' />
      </StackPanel>
    </DataTemplate>
  </xctk:BusyIndicator.BusyContentTemplate>
</xctk:BusyIndicator>

UploadToFTPCommand.cs

try
{
    vm.FtpUploadTask = new Task(() => FTPUpload(file), vm.Token);

    vm.FtpUploadTask.Start();
    vm.FtpUploadTask.Wait(vm.Token);

    vm.BusyContent = "upload done!";

}
catch (OperationCanceledException)
{
    vm.BusyContent = "Canceled";
}

CancelCommand.cs

public class CancelCommand : ICommand
{
    public void Execute(object parameter)
    {
        vm.TokenSource.Cancel();
    }
}

The cancel function works but sometimes vm.Busycontent equals to

((int)progress).ToString()

canceled in uploadftpcommand

When pressing the Cancel button, the while loop should be exited and the user should only see the message in the catch (OperationCanceledException).
Any ideas how to solve this?

Notes

I am using .NET 4.0

This program is a part of a larger project, which includes multipe Tasks that should be executed in a synchronous manner. That's why I am using Task.Start() and Task.Wait() methods.

Edit
Problem still remains

using (FileStream inputStream = File.OpenRead(file))
{
using (outputStream = request.GetRequestStream())
{
    var buffer = new byte[1024 * 1024];
    int totalReadBytesCount = 0;
    int readBytesCount;

    while ((readBytesCount = inputStream.Read(buffer, 0, buffer.Length)) > 0)
    {
        if (vm.Token.IsCancellationRequested)
        {
            break;
        }
        outputStream.Write(buffer, 0, readBytesCount);
        totalReadBytesCount += readBytesCount;
        var progress = totalReadBytesCount * 100.0 / inputStream.Length;
        vm.BusyContent = ((int)progress).ToString();
    }
    if (vm.Token.IsCancellationRequested)
    {

        inputStream.Close();
        outputStream.Close();
        vm.Token.ThrowIfCancellationRequested();
    }
}

}

Body:
You may have an issue relating to exactly how you've set up your code. Without going through every line of it, it's difficult to tell. But more to the point:

When pressing the Cancel button, the while loop should be exited and the user should only see the message in the catch (OperationCanceledException).

This shows exactly how to exit your while loop and throw an exception you can catch. Note the test asserts TaskCanceledException but you are right in just catching OperationCanceledException.

using System.Threading.Tasks;
using System.IO;
using System.Threading;

using NUnit.Framework;

namespace CancellationTests {

    [TestFixture]
    public class WhileCancellation {

        [Test]
        public void While_Loop_Is_Canceled_When_Cancel_Is_Requested() {
            var inputFile = new FileInfo("somebigfile.txt");
            var outputFile = new FileInfo("outputFile.txt");
            var cts = new CancellationTokenSource();

            cts.Cancel();

            Assert.ThrowsAsync<TaskCanceledException>(() => TheWhileLoop(inputFile, outputFile, cts.Token));
        }

        private async Task TheWhileLoop(FileInfo inputFile, FileInfo outputFile, CancellationToken token) {

            using (var inputStream = inputFile.OpenRead())
            using (var outputStream = outputFile.OpenWrite()) {
                var buffer = new byte[1024 * 1024];
                var totalReadBytesCount = 0;
                var readBytesCount = 0;

                while ((readBytesCount = await inputStream.ReadAsync(buffer, 0, buffer.Length, token)) > 0) {
                    await outputStream.WriteAsync(buffer, 0, readBytesCount, token);
                    token.ThrowIfCancellationRequested();
                    totalReadBytesCount += readBytesCount;
                    var progress = totalReadBytesCount * 100.0 / inputStream.Length;
                    vm.BusyContent = ((int)progress).ToString();
                }
            }
        }

        private static class vm {
            public static string BusyContent { get; set; }
        }
    }
}

Hopefully this gets you on the right track.


问:
Oracle INSERT statement with selects on different tables
I have two tables table1 and table2. Those tables have unique name and id columns.

I also have a relation / join table, table1_table2 which has the straight-forward colums table1_id and table2_id.

What I want to do is to insert a new relation into table1_table2 knowing the names of the elements in table1 and table2 I want to create a relation for. But I need to get their ids to insert them into table_table2.

What I want is something like that:

```<code>insert into table1_table2 values ((select id from table1 where name = 'some_name'), (select id from table2 where name = 'another_name'))
</code>```

I also tried using

```<code>insert into table1_table2 values ((select id from (select id from table1 where name = 'some_name') where rownum=1), (select id from (select id from table2 where name = 'another_name') where rownum=1))
</code>```

which also didn't work.

I understand I can first extract the ids if necessary but I'd prefer it to be in one statement.

Edit: I've also tried

```<code>insert into table1_table2 values (select t1.id, t2.id from table1 t1, table2 t2 where t1.name = 'some_name' and t2.name = 'another_name')
</code>```

which also didn't work

Example data:

```<code>table1
id name
1  foo
2  bar

table2
id name
1  some
2  data

table1_table2
table1.id table2.id
1         1
</code>```

and now I want to insert

```<code>table1.id table2.id
2         2
</code>```

into table1_table2, but I do only know that the entry in table1 has the name bar and the entry in table2 has the name data.

答:
This should work:

```<code>INSERT INTO table1_table2 (table1_id, table2_id)
    VALUES ( (SELECT id FROM table1 WHERE name = 'some_name'),
             (SELECT id FROM table2 WHERE name = 'another_name')
           );
</code>```

However, I would write it as:

INSERT INTO table1_table2 (table1_id, table2_id)
    SELECT t1.id, t2.id
    FROM table1 t1 JOIN
         table2 t2
         ON t1.name = 'some_name' AND
            t2.name = 'another_name';

Note in this case if there is no match in either table, then no row is inserted at all.  Using VALUES, a NULL values would be inserted.

Body:
I have two tables table1 and table2. Those tables have unique name and id columns.

I also have a relation / join table, table1_table2 which has the straight-forward colums table1_id and table2_id.

What I want to do is to insert a new relation into table1_table2 knowing the names of the elements in table1 and table2 I want to create a relation for. But I need to get their ids to insert them into table_table2.

What I want is something like that:

insert into table1_table2 values ((select id from table1 where name = 'some_name'), (select id from table2 where name = 'another_name'))

I also tried using

insert into table1_table2 values ((select id from (select id from table1 where name = 'some_name') where rownum=1), (select id from (select id from table2 where name = 'another_name') where rownum=1))

which also didn't work.

I understand I can first extract the ids if necessary but I'd prefer it to be in one statement.

Edit: I've also tried

insert into table1_table2 values (select t1.id, t2.id from table1 t1, table2 t2 where t1.name = 'some_name' and t2.name = 'another_name')

which also didn't work

Example data:

table1
id name
1  foo
2  bar

table2
id name
1  some
2  data

table1_table2
table1.id table2.id
1         1

and now I want to insert

table1.id table2.id
2         2

into table1_table2, but I do only know that the entry in table1 has the name bar and the entry in table2 has the name data.

Body:
This should work:

INSERT INTO table1_table2 (table1_id, table2_id)
    VALUES ( (SELECT id FROM table1 WHERE name = 'some_name'),
             (SELECT id FROM table2 WHERE name = 'another_name')
           );

However, I would write it as:

INSERT INTO table1_table2 (table1_id, table2_id)
    SELECT t1.id, t2.id
    FROM table1 t1 JOIN
         table2 t2
         ON t1.name = 'some_name' AND
            t2.name = 'another_name';

Note in this case if there is no match in either table, then no row is inserted at all.  Using VALUES, a NULL values would be inserted.


问:
Angular 2 form reset() not resetting values _submitted or submitted
Is there a way so form.reset() also resets values form.submitted to false again? This is annoying in my case as I use form.submitted as condition to show validation error in template. This means validation errors show up after form is cleared (reset).

template:

```<code><form ... #f="ngForm" (ngSubmit)="f.form.valid && submitProduct(f)>
  <input type="text" name="productName" [(ngModel)]="product.name" #productName="ngModel" required>
  <div *ngIf="f.submitted && !productName.valid">Product name is required</div>
  <button type="submit" value="true" >Submit Request</button>
</form>
</code>```

component:

```<code>submitProduct(form: NgForm) {
    this.productService.createProduct(this.product).subscribe(data => {
        form.reset();
        // HERE annoyingly validation errors show up on empty form.
      }
    );
}
</code>```

答:
You do not need to have the f.form.valid && submitProduct in the submit.

```<code><form ... #f="ngForm" (ngSubmit)="submitProduct(f)>
...
<button type="submit" value="true" [disabled]="!f.valid">Submit Request</button>
</code>```

Also call resetForm to make it pristine again.

```<code>form.resetForm();
</code>```

Body:
Is there a way so form.reset() also resets values form.submitted to false again? This is annoying in my case as I use form.submitted as condition to show validation error in template. This means validation errors show up after form is cleared (reset).

template:

<form ... #f="ngForm" (ngSubmit)="f.form.valid && submitProduct(f)>
  <input type="text" name="productName" [(ngModel)]="product.name" #productName="ngModel" required>

Product name is required

  <button type="submit" value="true" >Submit Request</button>
</form>

component:

submitProduct(form: NgForm) {
    this.productService.createProduct(this.product).subscribe(data => {
        form.reset();
        // HERE annoyingly validation errors show up on empty form.
      }
    );
}

Body:
You do not need to have the f.form.valid && submitProduct in the submit.

<form ... #f="ngForm" (ngSubmit)="submitProduct(f)>
...
<button type="submit" value="true" [disabled]="!f.valid">Submit Request</button>

Also call resetForm to make it pristine again.

form.resetForm();


问:
How can I make new fields available to the report designer?
I replaced old SP (sp_ReportMonthlySales) in the .rdl file with the new one:

```<code><CommandText>
      set fmtonly off;
      exec sp_ReportMonthlySalesEnhanced @Cyear,@Cmonth</CommandText>
<rd:UseGenericDesigner>true</rd:UseGenericDesigner>
</code>```

This new SP has four additional values that are being returned in the result set; the four "CU" values are new:

```<code>select CY.CSDirector, CY.Category, CY.Segment, CY._Unit,
       CU.New, CU.Assumed, CU.Existing, CU.Organic,
       CY.NumUnits, CY.NumUnitsLast, CY.MonthSales, CY.MonthSalesLast,
       CY.MonthPerc, CY.YTDSales, CY.YTDSalesLast, CY.YTDPerc,
       CY.ProjSales, CY.YTDProjSales, CY.YTDBudgetPerc, CY.NewBiz
from #CombinedYears CY
left join #CategorizedUnits CU on CU.Unit = CY._Unit
</code>```

IOW, these are new:

```<code>CU.New, CU.Assumed, CU.Existing, CU.Organic,
</code>```

But they are not available when I try to assign the field to the corresponding slot on the design surface:

How do I make those fields available for choosing? What sort of refresh or manual adding do I need to do?

UPDATE

I don't see where the "Dataset" is that I need to right-click so that I can refresh the fields; here is what I see in the designer:

Where is the dataset that will afford me a right-click action?

UPDATE 2

When I mash Ctrl+D, it does highlight the name of the OLD stored procedure in a dropdown:

So even though I've replaced the old CommandText value (sp_ReportMonthlySales) with the new one (sp_ReportMonthlySalesEnhanced), the old one is still being referenced. How can I get it to recognize the change/the new SP data source?

UPDATE 3

Richard Hansell's method worked. Using his method, I was able to expand "Datasets" from the ReportData pane, right-click the dataset, select Datatset Properties, and then in that dialog mash the "Refresh Fields" button. The new fields now display in the dataset's list in the Report Data pane.

If you expand your comment into an answer (you can adapt my verbiage above), I will mark it as an answer.

答: Right click the Dataset > Dataset Properties > Refresh fields</p>

Body:
I replaced old SP (sp_ReportMonthlySales) in the .rdl file with the new one:

<CommandText>
      set fmtonly off;
      exec sp_ReportMonthlySalesEnhanced @Cyear,@Cmonth</CommandText>
<rd:UseGenericDesigner>true</rd:UseGenericDesigner>

This new SP has four additional values that are being returned in the result set; the four "CU" values are new:

select CY.CSDirector, CY.Category, CY.Segment, CY._Unit,
       CU.New, CU.Assumed, CU.Existing, CU.Organic,
       CY.NumUnits, CY.NumUnitsLast, CY.MonthSales, CY.MonthSalesLast,
       CY.MonthPerc, CY.YTDSales, CY.YTDSalesLast, CY.YTDPerc,
       CY.ProjSales, CY.YTDProjSales, CY.YTDBudgetPerc, CY.NewBiz
from #CombinedYears CY
left join #CategorizedUnits CU on CU.Unit = CY._Unit

IOW, these are new:

CU.New, CU.Assumed, CU.Existing, CU.Organic,

But they are not available when I try to assign the field to the corresponding slot on the design surface:

How do I make those fields available for choosing? What sort of refresh or manual adding do I need to do?

UPDATE

I don't see where the "Dataset" is that I need to right-click so that I can refresh the fields; here is what I see in the designer:

Where is the dataset that will afford me a right-click action?

UPDATE 2

When I mash Ctrl+D, it does highlight the name of the OLD stored procedure in a dropdown:

So even though I've replaced the old CommandText value (sp_ReportMonthlySales) with the new one (sp_ReportMonthlySalesEnhanced), the old one is still being referenced. How can I get it to recognize the change/the new SP data source?

UPDATE 3

Richard Hansell's method worked. Using his method, I was able to expand "Datasets" from the ReportData pane, right-click the dataset, select Datatset Properties, and then in that dialog mash the "Refresh Fields" button. The new fields now display in the dataset's list in the Report Data pane.

If you expand your comment into an answer (you can adapt my verbiage above), I will mark it as an answer.


问:
Is it possible to map a button and/or a system event to launch an android application?
Good evening I am considering creating an application on the android platform and I want to know if it is possible to launch an application based on a particular system event, like pressing and holding a specific button for a period of time (i.e. 3 secs and launch application)?</p>

答: You can map search + a key to open a particular application.  See keyboard shortcuts to switch between applications.  That is an OS level thing though, I'm not sure what it would have to do with developing your own application.</p>

ContentLicense: CC BY-SA 2.5


问:
Publish Android aar to artifactory
I'm stuck with integrating artifactory 3.0.1 plugin with Gradle. I'm using Android Studio 1.0 so I'm guessing that I'm on Gradle 2.0. Any examples on publishing to artifactory using the 3.0.1 plugin would be highly helpful.

Thanks in advance

答:
Publishing to Artifactory is just a configuration task. You just need to configure two plugins, com.jfrog.artifactory and maven-publish, and run artifactoryPublish Gradle's task. But... let's explain it by code, to ease copypasting :·)

At your library's build.gradle:

```
apply plugin: 'com.jfrog.artifactory'
apply plugin: 'maven-publish'

publishing {
    publications {
        aar(MavenPublication) {
            groupId 'com.fewlaps.something' //put here your groupId
            artifactId 'productname' //put here your artifactId
            version '7.42.0' //put here your library version

            // Tell maven to prepare the generated "*.aar" file for publishing
            artifact("$buildDir/outputs/aar/${project.getName()}-release.aar")
        }
    }
}

artifactory {
    contextUrl = 'https://your-artifactory-host.com/artifactory'
    publish {
        repository {
            repoKey = "libs-release-local"
            username = "username"
            password = "password"
        }
        defaults {
            // Tell the Artifactory Plugin which artifacts should be published to Artifactory.
            publications('aar')
        }
    }
}
```

And then, run ./gradlew artifactoryPublish

In addition, if you want to upload the artifact everytime you push a tag to GitHub, add this code to your .travis.yml

```
deploy:
  - provider: script
    script: ./gradlew artifactoryPublish
    skip_cleanup: true
    on:
      tags: true
```

If it doesn't launch a build for the tag when you push a tag to GitHub, check that you're building vX.X.X tags on Travis:

```
# Build only master and "vX.X.X" tags to prevent flooding Travis machines
branches:
  only:
    - master
    - /^v\d+\.\d+\.\d+$/
```

Title: Publish Android aar to artifactory

Body:
Publishing to Artifactory is just a configuration task. You just need to configure two plugins, com.jfrog.artifactory and maven-publish, and run artifactoryPublish Gradle's task. But... let's explain it by code, to ease copypasting :·)

At your library's build.gradle:

apply plugin: 'com.jfrog.artifactory'
apply plugin: 'maven-publish'

publishing {
    publications {
        aar(MavenPublication) {
            groupId 'com.fewlaps.something' //put here your groupId
            artifactId 'productname' //put here your artifactId
            version '7.42.0' //put here your library version

            // Tell maven to prepare the generated "*.aar" file for publishing
            artifact("$buildDir/outputs/aar/${project.getName()}-release.aar")
        }
    }
}

artifactory {
    contextUrl = 'https://your-artifactory-host.com/artifactory'
    publish {
        repository {
            repoKey = "libs-release-local"
            username = "username"
            password = "password"
        }
        defaults {
            // Tell the Artifactory Plugin which artifacts should be published to Artifactory.
            publications('aar')
        }
    }
}

And then, run ./gradlew artifactoryPublish

In addition, if you want to upload the artifact everytime you push a tag to GitHub, add this code to your .travis.yml

deploy:
  - provider: script
    script: ./gradlew artifactoryPublish
    skip_cleanup: true
    on:
      tags: true

If it doesn't launch a build for the tag when you push a tag to GitHub, check that you're building vX.X.X tags on Travis:

# Build only master and "vX.X.X" tags to prevent flooding Travis machines
branches:
  only:
    - master
    - /^v\d+\.\d+\.\d+$/


问:
Why _mm256_load_pd compiled to MOVUPD instead of MOVAPD?
Why the following code results unaligned AVX instructions ( MOVUPD instead of MOVAPD)? I compiled this on Visual Studio 2015. How can I tell the compiler that my data is indeed aligned?</p>

```<code>    const size_t ALIGN_SIZE = 64;
    const size_t ARRAY_SIZE = 1024;

    double __declspec(align(ALIGN_SIZE)) a[ARRAY_SIZE];
    double __declspec(align(ALIGN_SIZE)) b[ARRAY_SIZE];

    //Calculate the dotproduct
    __m256d ymm0 = _mm256_set1_pd(0.0);
    for (int i = 0; i < ARRAY_SIZE; i += 8)
    {
        __m256d ymm1 = _mm256_load_pd(a + i);
        __m256d ymm2 = _mm256_load_pd(b + i);
        __m256d ymm3 = _mm256_mul_pd(ymm1, ymm2);
        ymm0 = _mm256_add_pd(ymm3, ymm0);

        __m256d ymm4 = _mm256_load_pd(a + i + 4);
        __m256d ymm5 = _mm256_load_pd(b + i + 4);
        __m256d ymm6 = _mm256_mul_pd(ymm4, ymm5);
        ymm0 = _mm256_add_pd(ymm6, ymm0);
    }

Assembly of the loop:
00007FF7AC7A1400  vmovupd     ymm1,ymmword ptr [rbp+rax*8+2020h]
00007FF7AC7A1409  vmulpd      ymm3,ymm1,ymmword ptr [rbp+rax*8+20h]
00007FF7AC7A140F  vmovupd     ymm2,ymmword ptr [rbp+rax*8]
00007FF7AC7A1415  vmulpd      ymm0,ymm2,ymmword ptr b[rax*8]
00007FF7AC7A141E  add         r8d,8
00007FF7AC7A1422  movsxd      rax,r8d
00007FF7AC7A1425  vaddpd      ymm1,ymm0,ymm4
00007FF7AC7A1429  vaddpd      ymm4,ymm1,ymm3
00007FF7AC7A142D  cmp         rax,400h
00007FF7AC7A1433  jb          main+70h (07FF7AC7A1400h)
</code>```

答:
There is the way to solve this problem (it allows to use instruction VMOVDQA (analogue of MOVAPD) instead of MOVUPD):

```<code>inline __m256d Load(const double * p)
{
#ifdef _MSC_VER
    return _mm256_castsi256_pd(_mm256_load_si256((__m256i*)p));
#else
    return _mm256_load_pd(p);
#endif
}
</code>```

Analogous solution for float type:

```<code>inline __m256 Load(const float * p)
{
#ifdef _MSC_VER
    return _mm256_castsi256_ps(_mm256_load_si256((__m256i*)p));
#else
    return _mm256_load_ps(p);
#endif
}
</code>```

But in order to cheat Visual Studio compiler you have to use dynamically allocated pointers. Otherwise compiler doesn't use VMOVDQA instruction.

```<code>#include <immintrin.h>

int main()
{
    float * ps = (float*)_mm_malloc(40, 32);
    double * pd = (double*)_mm_malloc(40, 32);

    __m256 s = Load(ps);
//00007FF79FF81325  vmovdqa     ymm1,ymmword ptr [rdi]
    __m256d d = Load(pd);
//00007FF79FF8132F  vmovdqa     ymm0,ymmword ptr [rax]

    _mm256_storeu_ps(ps, s);
    _mm256_storeu_pd(pd, d);

    _mm_free(ps);
    _mm_free(pd);
}
</code>```

Body:
Why the following code results unaligned AVX instructions ( MOVUPD instead of MOVAPD)? I compiled this on Visual Studio 2015. How can I tell the compiler that my data is indeed aligned?

    const size_t ALIGN_SIZE = 64;
    const size_t ARRAY_SIZE = 1024;

    double __declspec(align(ALIGN_SIZE)) a[ARRAY_SIZE];
    double __declspec(align(ALIGN_SIZE)) b[ARRAY_SIZE];

    //Calculate the dotproduct
    __m256d ymm0 = _mm256_set1_pd(0.0);
    for (int i = 0; i < ARRAY_SIZE; i += 8)
    {
        __m256d ymm1 = _mm256_load_pd(a + i);
        __m256d ymm2 = _mm256_load_pd(b + i);
        __m256d ymm3 = _mm256_mul_pd(ymm1, ymm2);
        ymm0 = _mm256_add_pd(ymm3, ymm0);

        __m256d ymm4 = _mm256_load_pd(a + i + 4);
        __m256d ymm5 = _mm256_load_pd(b + i + 4);
        __m256d ymm6 = _mm256_mul_pd(ymm4, ymm5);
        ymm0 = _mm256_add_pd(ymm6, ymm0);
    }

Assembly of the loop:
00007FF7AC7A1400  vmovupd     ymm1,ymmword ptr [rbp+rax*8+2020h]
00007FF7AC7A1409  vmulpd      ymm3,ymm1,ymmword ptr [rbp+rax*8+20h]
00007FF7AC7A140F  vmovupd     ymm2,ymmword ptr [rbp+rax*8]
00007FF7AC7A1415  vmulpd      ymm0,ymm2,ymmword ptr b[rax*8]
00007FF7AC7A141E  add         r8d,8
00007FF7AC7A1422  movsxd      rax,r8d
00007FF7AC7A1425  vaddpd      ymm1,ymm0,ymm4
00007FF7AC7A1429  vaddpd      ymm4,ymm1,ymm3
00007FF7AC7A142D  cmp         rax,400h
00007FF7AC7A1433  jb          main+70h (07FF7AC7A1400h)

Body:
There is the way to solve this problem (it allows to use instruction VMOVDQA (analogue of MOVAPD) instead of MOVUPD):

inline __m256d Load(const double * p)
{
#ifdef _MSC_VER
    return _mm256_castsi256_pd(_mm256_load_si256((__m256i*)p));
#else
    return _mm256_load_pd(p);
#endif
}

Analogous solution for float type:

inline __m256 Load(const float * p)
{
#ifdef _MSC_VER
    return _mm256_castsi256_ps(_mm256_load_si256((__m256i*)p));
#else
    return _mm256_load_ps(p);
#endif
}

But in order to cheat Visual Studio compiler you have to use dynamically allocated pointers. Otherwise compiler doesn't use VMOVDQA instruction.

#include <immintrin.h>

int main()
{
    float * ps = (float*)_mm_malloc(40, 32);
    double * pd = (double*)_mm_malloc(40, 32);

    __m256 s = Load(ps);
//00007FF79FF81325  vmovdqa     ymm1,ymmword ptr [rdi]
    __m256d d = Load(pd);
//00007FF79FF8132F  vmovdqa     ymm0,ymmword ptr [rax]

    _mm256_storeu_ps(ps, s);
    _mm256_storeu_pd(pd, d);

    _mm_free(ps);
    _mm_free(pd);
}


问:
How can I assign a value to a function call?
I try to build a class named "Point" representing 3d-coordinates (x,y,z).

```<code>class Point(object):

    def __init__(self):
        a = 3
        self.data = [[[bool(False) for x in xrange(a)] for y in xrange(a)] for z in xrange(a)]

    def __call__(self, x, y, z):
       return 'call :'+self.data[x][y][z]'
</code>```

I can easily access a point:

```<code>p = Point()
print p(1 ,1, 1)   # output : False`
</code>```

BUT, I can't assign a value to this point !

```<code>p(1, 1, 0) = True  # SyntaxError: can't assign to function call
</code>```

Any idea ?

答:
Well if you write that, you get the following error:

SyntaxError: can't assign to function call

Note that this is a SyntaxError that means that Python does not even bother to try to evaluate that. It says: that is not in the Python grammar, so it is not supposed to work that way.

A thing that comes a bit close to what you ask is overriding the __setitem__ function so that you can assign with p[1,1,0] (note that these are square brackets). Like:

```<code>class Point(object):

    def __init__(self):
        a = 3
        self.data = [[[bool(False) for x in xrange(a)] for y in xrange(a)] for z in xrange(a)]

    <b>def __setitem__(self,idx,val):
        i,j,k = idx
        self.data[i][j][k] = val</b>

    def __call__(self, x, y, z):
       return 'call :'+<b>str(</b>self.data[x][y][z]<b>)</b></code>```

Now it works like:

```<code>>>> p = Point()
>>> p(1,1,0)
'call :False'
>>> p[1,1,0] = True # note the square brackets
>>> p(1,1,0)
'call :True'
</code>```

Body:
I try to build a class named "Point" representing 3d-coordinates (x,y,z).

class Point(object):

    def __init__(self):
        a = 3
        self.data = [[[bool(False) for x in xrange(a)] for y in xrange(a)] for z in xrange(a)]

    def __call__(self, x, y, z):
       return 'call :'+self.data[x][y][z]'

I can easily access a point:

p = Point()
print p(1 ,1, 1)   # output : False`

BUT, I can't assign a value to this point !

p(1, 1, 0) = True  # SyntaxError: can't assign to function call

Any idea ?

Body:
Well if you write that, you get the following error:

SyntaxError: can't assign to function call

Note that this is a SyntaxError that means that Python does not even bother to try to evaluate that. It says: that is not in the Python grammar, so it is not supposed to work that way.

A thing that comes a bit close to what you ask is overriding the __setitem__ function so that you can assign with p[1,1,0] (note that these are square brackets). Like:

class Point(object):

    def __init__(self):
        a = 3
        self.data = [[[bool(False) for x in xrange(a)] for y in xrange(a)] for z in xrange(a)]

    def __setitem__(self,idx,val):
        i,j,k = idx
        self.data[i][j][k] = val

    def __call__(self, x, y, z):
       return 'call :'+str(self.data[x][y][z])

Now it works like:

>>> p = Point()
>>> p(1,1,0)
'call :False'
>>> p[1,1,0] = True # note the square brackets
>>> p(1,1,0)
'call :True'


问:
cx_Oracle connection by python3.5
I've tried several attempt to connect Oracle DB but still unable to connect. Following is my code to connect. However, I could connect Oracle DB through the terminal like this:

$ sqlplus64 uid/passwd@192.168.0.5:1521/WSVC

My evironment: Ubuntu 16.04 / 64bit / Python3.5

I wish your knowledge and experience associated with this issue to be shared. Thank you.

```<code>import os
os.chdir("/usr/lib/oracle/12.2/client64/lib")
import cx_Oracle

# 1st attempt
ip = '192.168.0.5'
port = 1521
SID = 'WSVC'
dsn_tns = cx_Oracle.makedsn(ip, port, SID)
# dsn_tns = cx_Oracle.makedsn(ip, port, service_name=SID)

db = cx_Oracle.connect('uid', 'passwd', dsn_tns)
cursor = db.cursor()

-------------------------------------------------
# 2nd attempt
conn = "uid/passwd@(DESCRIPTION=(SOURCE_ROUTE=OFF)(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=192.168.0.5)(PORT=1521)))(CONNECT_DATA=(SID=WSVC)(SRVR=DEDICATED)))"

db = cx_Oracle.connect(conn)
cursor = db.cursor()

------------------------------------------------------
# ERROR Description

cx_Oracle.InterfaceError: Unable to acquire Oracle environment handle
</code>```

答:
The error "unable to acquire Oracle environment handle" is due to your Oracle configuration being incorrect. A few things that should help you uncover the source of the problem:

when using Instant Client, do NOT set the environment variable ORACLE_HOME; that should only be set when using a full Oracle Client or Oracle Database installation

the value of LD_LIBRARY_PATH should contain the path which contains libclntsh.so; the value you selected looks like it is incorrect and should be /usr/lib/oracle/12.2/client64/lib instead

you can verify which Oracle Client libraries are being loaded by using the ldd command as in ldd cx_Oracle.cpython-35m-x86_64-linux-gnu.so

Title: cx_Oracle connection by python3.5

Body:
I've tried several attempt to connect Oracle DB but still unable to connect. Following is my code to connect. However, I could connect Oracle DB through the terminal like this:

$ sqlplus64 uid/passwd@192.168.0.5:1521/WSVC

My evironment: Ubuntu 16.04 / 64bit / Python3.5

I wish your knowledge and experience associated with this issue to be shared. Thank you.

import os
os.chdir("/usr/lib/oracle/12.2/client64/lib")
import cx_Oracle

# 1st attempt
ip = '192.168.0.5'
port = 1521
SID = 'WSVC'
dsn_tns = cx_Oracle.makedsn(ip, port, SID)
# dsn_tns = cx_Oracle.makedsn(ip, port, service_name=SID)

db = cx_Oracle.connect('uid', 'passwd', dsn_tns)
cursor = db.cursor()

-------------------------------------------------
# 2nd attempt
conn = "uid/passwd@(DESCRIPTION=(SOURCE_ROUTE=OFF)(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=192.168.0.5)(PORT=1521)))(CONNECT_DATA=(SID=WSVC)(SRVR=DEDICATED)))"

db = cx_Oracle.connect(conn)
cursor = db.cursor()

------------------------------------------------------
# ERROR Description

cx_Oracle.InterfaceError: Unable to acquire Oracle environment handle


问:
what's the meaning of "#define __cdecl" in my C++ code?
I'm working on an existing c++ project with visual studio, and I found out that almost every function declaration gets a __cdecl in front of the function name, like:void __cdecl functionName(). Then I jump to the definition of __cdecl, which locates in the winnt.h file:

```<code>#if (_MSC_VER >= 800) || defined(_STDCALL_SUPPORTED)
#define NTAPI __stdcall
#else
#define _cdecl
#define __cdecl
#define NTAPI
#endif
</code>```

I've searched cdecl and got that it's the default calling convention for C and C++ programs, but code above tells me that __cdecl extends to nothing. So why place a __cdecl before function name as it's just nothing ? or did I misunderstand the code above?

答:
what's the meaning of #define __cdecl”

Lines that begin with # are preprocessor directives. #define is a directive that defines a preprocessor macro. #define __cdecl defines a macro with identifier __cdecl and empty replacement. If such macro is defined, the processor will replace all instances of the __cdecl with an empty string.

So why place a __cdecl before function name as it's just nothing ?

Take a look at the directives at the beginning of the definition in question:

```<code>#if (_MSC_VER >= 800) || defined(_STDCALL_SUPPORTED)
#else
</code>```

The macro is defined conditionally. When the macro is not defined, __cdecl will not expand to nothing. When not expanded to nothing, __cdecl is a microsoft specific function specifier as you have discovered.

The conditionally defined macro allows one to write code that uses __cdecl on systems that allow it, and automatically remove it on systems that do not.

But I'm still confused with the #if (_MSC_VER >= 800) || defined(_STDCALL_SUPPORTED) line, what does it mean?

It is a preprocessor directive that test whether the macro _MSC_VER has greater value than 800, or if macro _STDCALL_SUPPORTED is defined. If the test is false, then the code between #if and #else is removed. If it is true, then the code between #else and #endif is removed.

ContentLicense: CC BY-SA 4.0

Body:
I'm working on an existing c++ project with visual studio, and I found out that almost every function declaration gets a __cdecl in front of the function name, like:void __cdecl functionName(). Then I jump to the definition of __cdecl, which locates in the winnt.h file:

#if (_MSC_VER >= 800) || defined(_STDCALL_SUPPORTED)
#define NTAPI __stdcall
#else
#define _cdecl
#define __cdecl
#define NTAPI
#endif

I've searched cdecl and got that it's the default calling convention for C and C++ programs, but code above tells me that __cdecl extends to nothing. So why place a __cdecl before function name as it's just nothing ? or did I misunderstand the code above?

Body:
what's the meaning of #define __cdecl”

Lines that begin with # are preprocessor directives. #define is a directive that defines a preprocessor macro. #define __cdecl defines a macro with identifier __cdecl and empty replacement. If such macro is defined, the processor will replace all instances of the __cdecl with an empty string.

So why place a __cdecl before function name as it's just nothing ?

Take a look at the directives at the beginning of the definition in question:

#if (_MSC_VER >= 800) || defined(_STDCALL_SUPPORTED)
#else

The macro is defined conditionally. When the macro is not defined, __cdecl will not expand to nothing. When not expanded to nothing, __cdecl is a microsoft specific function specifier as you have discovered.

The conditionally defined macro allows one to write code that uses __cdecl on systems that allow it, and automatically remove it on systems that do not.

But I'm still confused with the #if (_MSC_VER >= 800) || defined(_STDCALL_SUPPORTED) line, what does it mean?

It is a preprocessor directive that test whether the macro _MSC_VER has greater value than 800, or if macro _STDCALL_SUPPORTED is defined. If the test is false, then the code between #if and #else is removed. If it is true, then the code between #else and #endif is removed.


问:
Files not picking up after npm gets npm starts
I am new to angular js. After running npm start the file is in serving from status(serving from :. /)  it's not picking up the file, eventhough. I have mentioned the file name as index.html. Please help me out to remove this issue. </p>

<p>(BS) Serving files from :. /
(BS)  watching files </p>

<p>No results afterwards.... </p>

答:
It's impossible to tell you what's wrong in your code when you didn't show even a single line. You didn't even tell which framework you're using or any other relevant info.

To see how to serve files with Node using 5 different ways with example, see this answer:

How to serve an image using nodejs

It's not only about images, also HTML, CSS, JS etc. Hopefully it will get you on the right track.

Body:
I am new to angular js. After running npm start the file is in serving from status(serving from :. /)  it's not picking up the file, eventhough. I have mentioned the file name as index.html. Please help me out to remove this issue.

(BS) Serving files from :. /
(BS)  watching files

No results afterwards....


问:
Blank cells/rows aren't showing up
I'm trying to find all the blank cells in a spreadsheet I have. I'm using .getDataRange() to get all the cells with data. The problem is, I can't get the empty cells / rows to show up.

For example:

row 1 | test1 test2 test3 test4 test5 test6

row 2 |

row 3 |

row 4 |

If I use .getDataRange here, and do .getNumColumns and .getNumRows, It will return columns = 6, and rows = 1. This is the problem I'm having because I need it to return all the rows...but since the other rows don't have any data in them, it's like they don't exist.

My code is:

```<code>  var spreadsheet = SpreadsheetApp.openById(id);

  var rowCheck = spreadsheet.getActiveSheet().getMaxRows(); //gets all rows
  var data =  spreadsheet.getDataRange(); //gets range of all data in spreadsheet

  //set blank cells to '0'
  var columns = data.getNumColumns();
  var rows = data.getNumRows();
  Logger.log("columns: " + columns + ",,, rows: " + rows);
</code>```

So I guess the question is: How do I get all the rows to show up regardless of if it contains data or not?

答:
Getting the Values

My understanding is that getDataRange() gets the range of all data on the sheet.
So when you say in your code the following:

```<code>var data =  spreadsheet.getDataRange(); //gets range of all data in spreadsheet
</code>```

Let me be sure that you understand that this command does not return any values it only returns a range.  If you want the values then you can do this.

```<code>var dataA = spreadsheet.getDataRange().getValues();
</code>```

In this case you will get values in a 2 dimensional array.

Title: Blank cells/rows aren't showing up

Body:
I'm trying to find all the blank cells in a spreadsheet I have. I'm using .getDataRange() to get all the cells with data. The problem is, I can't get the empty cells / rows to show up.

For example:

row 1 | test1 test2 test3 test4 test5 test6

row 2 |

row 3 |

row 4 |

If I use .getDataRange here, and do .getNumColumns and .getNumRows, It will return columns = 6, and rows = 1. This is the problem I'm having because I need it to return all the rows...but since the other rows don't have any data in them, it's like they don't exist.

My code is:

  var spreadsheet = SpreadsheetApp.openById(id);

  var rowCheck = spreadsheet.getActiveSheet().getMaxRows(); //gets all rows
  var data =  spreadsheet.getDataRange(); //gets range of all data in spreadsheet

  //set blank cells to '0'
  var columns = data.getNumColumns();
  var rows = data.getNumRows();
  Logger.log("columns: " + columns + ",,, rows: " + rows);

So I guess the question is: How do I get all the rows to show up regardless of if it contains data or not?

Body:
Getting the Values

My understanding is that getDataRange() gets the range of all data on the sheet.
So when you say in your code the following:

var data =  spreadsheet.getDataRange(); //gets range of all data in spreadsheet

Let me be sure that you understand that this command does not return any values it only returns a range.  If you want the values then you can do this.

var dataA = spreadsheet.getDataRange().getValues();

In this case you will get values in a 2 dimensional array.


问:
From firebase storage download file to iframe
With below code, I can not download image to iframe. Instead, it downloaded to local drive.

in JS:

```<code>  storageRef.child('images/CopyPerson.jpg').getDownloadURL().then(function(url) {
  var iframe1 = document.getElementById('downloadedCourse');
  iframe1.src = url;
}).catch(function(error) {
  // Handle any errors
});
</code>```

in html:

```<code>  <iframe id="downloadedCourse" width="800" height="500" src=""></iframe>
</code>```

However, if I use img instead of iframe, it works as supposed.  The reason I need use iframe is because I intend to download pdf file. Anyone knows why?

答:
I presume that this is because the content-disposition header is set to attachment instead of inline. Try setting the metadata to change this and see if that works:

```<code>// Obviously you only have to set the metadata once per file
// Not every time you download the URL
storageRef.child('images/CopyPerson.jpg').updateMetadata({
  "contentDisposition": "inline"
}).then(function() {
  return storageRef.child('images/CopyPerson.jpg').getDownloadURL()
}).then(function(url) {
  var iframe1 = document.getElementById('downloadedCourse');
  iframe1.src = url;
});
</code>```

Body:
With below code, I can not download image to iframe. Instead, it downloaded to local drive.

in JS:

  storageRef.child('images/CopyPerson.jpg').getDownloadURL().then(function(url) {
  var iframe1 = document.getElementById('downloadedCourse');
  iframe1.src = url;
}).catch(function(error) {
  // Handle any errors
});

in html:

However, if I use img instead of iframe, it works as supposed.  The reason I need use iframe is because I intend to download pdf file. Anyone knows why?

Body:
I presume that this is because the content-disposition header is set to attachment instead of inline. Try setting the metadata to change this and see if that works:

// Obviously you only have to set the metadata once per file
// Not every time you download the URL
storageRef.child('images/CopyPerson.jpg').updateMetadata({
  "contentDisposition": "inline"
}).then(function() {
  return storageRef.child('images/CopyPerson.jpg').getDownloadURL()
}).then(function(url) {
  var iframe1 = document.getElementById('downloadedCourse');
  iframe1.src = url;
});


问:
multiplying elements in a 3x4 matrix individually in python 3 using loops (no numpy)
Im trying to make a matrix that is 3 rows by 4 columns and includes the numbers 1-12. Would then like to multiply those numbers by a factor to make a new matrix.

```<code>def matrix(x):
    matrix=[[1,2,3],[4,5,6],[7,8,9],[10,11,12]]
    new_matrix=[[x*1,x*2,x*3],[x*4,x*5,x*6],[x*7,x*8,x*9],[x*10,x*11,x*12]]
    print(new_matrix)
</code>```

This approach works, however it does not use loops, I'm looking for an approach that uses loops, something like this:

```<code> def matrix(x):
     for i in range(3):
         matrix.append([])
         for j in range(4):
             matrix[i].append(0)
             return matrix
</code>```

答:
You do not need to use explicit loops for something like this (unless you really want to). List comprehensions are a much more efficient way to generate lists, and have a similar syntax to a for loop:

Here is a comprehension for generating any MxN matrix containing the numbers up to M * N:

```<code>def matrix(m, n):
    return [[x+1 for x in range(row * n, (row + 1) * n)] for row in range(m)]
</code>```

Here is a comprehension for multiplying the nested list returned by matrix by some factor:

```<code>def mult(mat, fact):
    return [[x * fact for x in row] for row in mat]
</code>```

Here is the result for your specific 3x4 case:

```<code>>>> m = matrix(3, 4)
>>> print(m)
[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]
>>> m2 = mult(m, 2)
>>> print(m2)
[[2, 4, 6, 8], [10, 12, 14, 16], [18, 20, 22, 24]]
</code>```

If you want the indices to be swapped as in your original example, just swap the inputs m and n:

```<code>>>> matrix(4, 3)
[[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]
</code>```

mult will work the same for any nested list you pass in.

Body:
Im trying to make a matrix that is 3 rows by 4 columns and includes the numbers 1-12. Would then like to multiply those numbers by a factor to make a new matrix.

def matrix(x):
    matrix=[[1,2,3],[4,5,6],[7,8,9],[10,11,12]]
    new_matrix=[[x*1,x*2,x*3],[x*4,x*5,x*6],[x*7,x*8,x*9],[x*10,x*11,x*12]]
    print(new_matrix)

This approach works, however it does not use loops, I'm looking for an approach that uses loops, something like this:

 def matrix(x):
     for i in range(3):
         matrix.append([])
         for j in range(4):
             matrix[i].append(0)
             return matrix

Body:
You do not need to use explicit loops for something like this (unless you really want to). List comprehensions are a much more efficient way to generate lists, and have a similar syntax to a for loop:

Here is a comprehension for generating any MxN matrix containing the numbers up to M * N:

def matrix(m, n):
    return [[x+1 for x in range(row * n, (row + 1) * n)] for row in range(m)]

Here is a comprehension for multiplying the nested list returned by matrix by some factor:

def mult(mat, fact):
    return [[x * fact for x in row] for row in mat]

Here is the result for your specific 3x4 case:

>>> m = matrix(3, 4)
>>> print(m)
[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]
>>> m2 = mult(m, 2)
>>> print(m2)
[[2, 4, 6, 8], [10, 12, 14, 16], [18, 20, 22, 24]]

If you want the indices to be swapped as in your original example, just swap the inputs m and n:

>>> matrix(4, 3)
[[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]

mult will work the same for any nested list you pass in.


问:
ko.computed property to determine visibility not working
In my KncokoutJS ViewModel, I have the follow computed property:

```<code>self.SelectedUserHasRoles = ko.computed(function () {
  if (self.isLoaded()) {
    return self.selectedUser().roles().length > 0;
  }
  return false;
});
</code>```

And in my HTML, I have the following:

```<code><!-- ko if: isLoaded() -->
  <!-- ko if: !SelectedUserHasRoles -->
  <div>
    <p>User has no Roles.</p>
  </div>
  <!-- /ko -->
  <!-- ko if: SelectedUserHasRoles -->
  <div class="roles-wrapper" data-bind="foreach: $root.selectedUser().roles()">
    <div class="role-token" data-bind="text: Name"></div>
  </div>
  <!-- /ko -->
<!-- /ko -->
</code>```

In my code, I was to say this:

If data from AJAX call has finished loading (isLoaded is true), then for the currently selected user, check and see if he/she has any roles. If yes, then loop through them and show them, if not, show a bit of text saying 'User has no Roles.'

All seems to work, except for the showing User has no Roles text snippet. I've no idea why that isn't showing! I'm putting breakpoints into my computed property and can see that when I select a user with no roles, the expression (in console window) is false, and I'm negating that, so I should see that text snippet!

What am I doing wrong? I've created a screencast to make things easier to understand.

答:
Because you are not binding to a variable but to an expression, you need to add parenthesis here:

```<code><!-- ko if: !SelectedUserHasRoles() -->
                               //^^ here
</code>```

See the following snippet

function CreateVM() {
    var self = this;
    this.isTrue = ko.observable(false);
    this.selectedUser = ko.observable();
    this.isLoaded = ko.observable();
    self.SelectedUserHasRoles = ko.computed(function () {
       if (self.isLoaded()) {
          return self.selectedUser().roles().length > 0;
       }
       return false;
    });
}

var vm = new CreateVM();
ko.applyBindings(vm);

var userWithRoles = { roles: ko.observableArray([1,2]) };
var userWithoutRoles = { roles: ko.observableArray([]) };
vm.selectedUser(userWithoutRoles);
vm.isLoaded(true);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<!-- ko if: isLoaded() -->
  <!-- ko if: !SelectedUserHasRoles() -->
  <div>
    <p>User has no Roles.</p>
  </div>
  <!-- /ko -->
  <!-- ko if: SelectedUserHasRoles -->
  <div class="roles-wrapper" data-bind="foreach: $root.selectedUser().roles()">
    <div class="role-token" data-bind="text: $data"></div>
  </div>
  <!-- /ko -->
  SelectedUserHasRoles: <span class="role-token" data-bind="text: SelectedUserHasRoles"></span>
<!-- /ko --></code>```

See user3297291's answer for more details.

Body:
In my KncokoutJS ViewModel, I have the follow computed property:

self.SelectedUserHasRoles = ko.computed(function () {
  if (self.isLoaded()) {
    return self.selectedUser().roles().length > 0;
  }
  return false;
});

And in my HTML, I have the following:

User has no Roles.

In my code, I was to say this:

If data from AJAX call has finished loading (isLoaded is true), then for the currently selected user, check and see if he/she has any roles. If yes, then loop through them and show them, if not, show a bit of text saying 'User has no Roles.'

All seems to work, except for the showing User has no Roles text snippet. I've no idea why that isn't showing! I'm putting breakpoints into my computed property and can see that when I select a user with no roles, the expression (in console window) is false, and I'm negating that, so I should see that text snippet!

What am I doing wrong? I've created a screencast to make things easier to understand.

Body:
Because you are not binding to a variable but to an expression, you need to add parenthesis here:

<!-- ko if: !SelectedUserHasRoles() -->
                               //^^ here

See the following snippet

function CreateVM() {
    var self = this;
    this.isTrue = ko.observable(false);
    this.selectedUser = ko.observable();
    this.isLoaded = ko.observable();
    self.SelectedUserHasRoles = ko.computed(function () {
       if (self.isLoaded()) {
          return self.selectedUser().roles().length > 0;
       }
       return false;
    });
}

var vm = new CreateVM();
ko.applyBindings(vm);

var userWithRoles = { roles: ko.observableArray([1,2]) };
var userWithoutRoles = { roles: ko.observableArray([]) };
vm.selectedUser(userWithoutRoles);
vm.isLoaded(true);

<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<!-- ko if: isLoaded() -->
  <!-- ko if: !SelectedUserHasRoles() -->
  <div>
    <p>User has no Roles.</p>
  </div>
  <!-- /ko -->
  <!-- ko if: SelectedUserHasRoles -->
  <div class="roles-wrapper" data-bind="foreach: $root.selectedUser().roles()">
    <div class="role-token" data-bind="text: $data"></div>
  </div>
  <!-- /ko -->
  SelectedUserHasRoles: <span class="role-token" data-bind="text: SelectedUserHasRoles"></span>
<!-- /ko -->

See user3297291's answer for more details.


问:
How can write.csv and read.csv preserve the data format?
I have a dataframe which contains majority of the columns as numeric. Then I use this command to write to  csv file

```<code>    write.csv(df, "mydf.csv", row.names=FALSE, na="")
</code>```

Then later I read in the file using:

```<code>    df = read.csv("mydf.csv", header = F, sep = ",", stringsAsFactors=F,dec=".")
</code>```

Then as I checked the data formate using

```<code>   sapply(df, class)
</code>```

all the columns change into character.  If I don't put stringsAsFactors=F,
all the columns change into factor.
I could manually change  columns into  numeric later. I just wonder if there is a method I could preserve  the data format at least for the majority columns while write or read csv file.  Is there better solutions?

答: By default write.csv will include headers, but when you are importing them you are telling R that there are no headers. It's likely that those headers are non-numeric which triggers the switch to character. So either turn off the headers in the write.csv() or set header=TRUE in the read.csv()

Body:
I have a dataframe which contains majority of the columns as numeric. Then I use this command to write to  csv file

    write.csv(df, "mydf.csv", row.names=FALSE, na="")

Then later I read in the file using:

    df = read.csv("mydf.csv", header = F, sep = ",", stringsAsFactors=F,dec=".")

Then as I checked the data formate using

   sapply(df, class)

all the columns change into character.  If I don't put stringsAsFactors=F,
all the columns change into factor.
I could manually change  columns into  numeric later. I just wonder if there is a method I could preserve  the data format at least for the majority columns while write or read csv file.  Is there better solutions?


问:
Add custom text to the output text field in bootstrap datetimepicker
I'm using bootstrap 3 date/time picker here:

https://eonasdan.github.io/bootstrap-datetimepicker/

Is it possible to customise the output text in the date/time text field? I wish to add a string at the start, such as 'Departure:'.

My current set up is very simple, the javascript is simply:

```<code>$('#datetimepicker').datetimepicker({defaultDate:'now',ignoreReadonly: true });
$('#datetimepicker').data("DateTimePicker").format('DD/MM/YYYY HH:mm:ss');
</code>```

The HTML is:

```<code><div class="form-group" style = "margin-bottom:4px;">
    <div class='input-group date' id='datetimepicker'>
        <input type='text' class="form-control" readonly='readonly'/>
        <span class="input-group-addon" style="padding: 6px 11.5px;">
        <span class="glyphicon glyphicon-calendar"></span>
        </span>
    </div>
</div>
</code>```

This will display the date and time as per the formatting given in the code.  How can I add the string Departing: to the beginning of the text field?

答:
```<code>$('input').val('Departing: ' + pickedDate.toString());
</code>```

Body:
I'm using bootstrap 3 date/time picker here:

https://eonasdan.github.io/bootstrap-datetimepicker/

Is it possible to customise the output text in the date/time text field? I wish to add a string at the start, such as 'Departure:'.

My current set up is very simple, the javascript is simply:

$('#datetimepicker').datetimepicker({defaultDate:'now',ignoreReadonly: true });
$('#datetimepicker').data("DateTimePicker").format('DD/MM/YYYY HH:mm:ss');

The HTML is:

        <input type='text' class="form-control" readonly='readonly'/>

This will display the date and time as per the formatting given in the code.  How can I add the string Departing: to the beginning of the text field?


问:
excel multiple on error goto
I am trying to get multiple on error statements to work and can't figure it out.

If pdf can be found in local then open, if not then open network location. If there is no PDF in then return msgbox.

```<code>Sub Cutsheets()
Application.ScreenUpdating = False

Dim finalrow As Integer

finalrow = Cells(Rows.Count, 1).End(xlUp).Row
On Error GoTo net1

If Not Application.Intersect(ActiveCell, Range("A9:A" & finalrow)) Is Nothing Then
    'Local Location
ActiveWorkbook.FollowHyperlink "C:\Local" & ActiveCell & ".pdf"
Application.SendKeys "{ENTER}", True
End If
Exit Sub

net1:
If Not Application.Intersect(ActiveCell, Range("A9:A" & finalrow)) Is Nothing Then
    'Network Location
On Error GoTo whoa
ActiveWorkbook.FollowHyperlink "P:\Network" & ActiveCell & ".pdf"
Application.SendKeys "{ENTER}", True
End If
Exit Sub

whoa:
MsgBox ("No cutsheet can be found for this item.")

Application.ScreenUpdating = True

End Sub
</code>```

Also I don't remember why I put sendkeys in there but it doesn't work without it.

答:
I am trying to get multiple on error statements to work

Don't.

Imagine you're the VBA runtime. You're executing a procedure called Cutsheets, and you come across this instruction:

```<code>On Error GoTo net1
</code>```

From that point on, before you blow up in the user's face, you're going to jump to the net1 label if you ever encounter a run-time error. So you keep running instructions. Eventually you run this line:

```<code>ActiveWorkbook.FollowHyperlink "C:\Local" & ActiveCell & ".pdf"
</code>```

And when the FollowHyperlink method responds with "uh nope, can't do that" and raises a run-time error, your execution context changes.

You're in "error handling" mode.

So you jump to the net1 label. You're in "error handling" mode. There are certain things you can do in "normal execution mode" that you can't (or shouldn't) do in "error handling mode". Raising and handling more errors is one of these things.

```<code>On Error GoTo whoa
</code>```

You're already handling a run-time error: what should you do when you encounter that statement in an error handler subroutine? Jump to the whoa right away?

When the VBA runtime is in "error handling mode", your job as a programmer is to handle runtime errors and do everything you can to get back to "normal execution mode" as soon as possible - and that's normally done with a Resume instruction, or by leaving the current scope.

Copying a chunk of code from the "normal execution path" and trying to run it (slightly altered) in "error handling mode" isn't handling errors and getting back to normal execution mode as soon as possible.

Error handling or not, copy-pasting chunks of code is poorly written code anyway.

Extract a procedure instead:

```<code>Private Sub OpenPortableDocumentFile(ByVal path As String)
    On Error GoTo ErrHandler
    ActiveWorkbook.FollowHyperlink path
    Application.SendKeys "{ENTER}", True
    Exit Sub
ErrHandler:
    MsgBox "Could not open file '" & path & "'."
End Sub
</code>```

Now that that's out of the way, clean up your control flow by verifying if the file exists before you pass an invalid path to the OpenPortableDocumentFile procedure.

The best error handling strategy is to avoid raising run-time errors in the first place.

Title: excel multiple on error goto

Body:
I am trying to get multiple on error statements to work and can't figure it out.

If pdf can be found in local then open, if not then open network location. If there is no PDF in then return msgbox.

Sub Cutsheets()
Application.ScreenUpdating = False

Dim finalrow As Integer

finalrow = Cells(Rows.Count, 1).End(xlUp).Row
On Error GoTo net1

If Not Application.Intersect(ActiveCell, Range("A9:A" & finalrow)) Is Nothing Then
    'Local Location
ActiveWorkbook.FollowHyperlink "C:\Local" & ActiveCell & ".pdf"
Application.SendKeys "{ENTER}", True
End If
Exit Sub

net1:
If Not Application.Intersect(ActiveCell, Range("A9:A" & finalrow)) Is Nothing Then
    'Network Location
On Error GoTo whoa
ActiveWorkbook.FollowHyperlink "P:\Network" & ActiveCell & ".pdf"
Application.SendKeys "{ENTER}", True
End If
Exit Sub

whoa:
MsgBox ("No cutsheet can be found for this item.")

Application.ScreenUpdating = True

End Sub

Also I don't remember why I put sendkeys in there but it doesn't work without it.

Body:
I am trying to get multiple on error statements to work

Don't.

Imagine you're the VBA runtime. You're executing a procedure called Cutsheets, and you come across this instruction:

On Error GoTo net1

From that point on, before you blow up in the user's face, you're going to jump to the net1 label if you ever encounter a run-time error. So you keep running instructions. Eventually you run this line:

ActiveWorkbook.FollowHyperlink "C:\Local" & ActiveCell & ".pdf"

And when the FollowHyperlink method responds with "uh nope, can't do that" and raises a run-time error, your execution context changes.

You're in "error handling" mode.

So you jump to the net1 label. You're in "error handling" mode. There are certain things you can do in "normal execution mode" that you can't (or shouldn't) do in "error handling mode". Raising and handling more errors is one of these things.

On Error GoTo whoa

You're already handling a run-time error: what should you do when you encounter that statement in an error handler subroutine? Jump to the whoa right away?

When the VBA runtime is in "error handling mode", your job as a programmer is to handle runtime errors and do everything you can to get back to "normal execution mode" as soon as possible - and that's normally done with a Resume instruction, or by leaving the current scope.

Copying a chunk of code from the "normal execution path" and trying to run it (slightly altered) in "error handling mode" isn't handling errors and getting back to normal execution mode as soon as possible.

Error handling or not, copy-pasting chunks of code is poorly written code anyway.

Extract a procedure instead:

Private Sub OpenPortableDocumentFile(ByVal path As String)
    On Error GoTo ErrHandler
    ActiveWorkbook.FollowHyperlink path
    Application.SendKeys "{ENTER}", True
    Exit Sub
ErrHandler:
    MsgBox "Could not open file '" & path & "'."
End Sub

Now that that's out of the way, clean up your control flow by verifying if the file exists before you pass an invalid path to the OpenPortableDocumentFile procedure.

The best error handling strategy is to avoid raising run-time errors in the first place.


问:
Session conflict for frontend and backend logins - codeigniter
I have a site which has a front end and a backend section.
The problem is, when I login from the frontend section, and open the admin dashboard, I am logged in automatically, I dont want admin to login unless he enters the username and password.

I am using sessions.

How will I be able to fix that.. ? I am using codeigniter

答:
thanks wolfgang.

for those who have subdirectory to host CI you can use the following method,

```<code>if(isset($_SERVER['HTTPS'])){
    $protocol = ($_SERVER['HTTPS'] && $_SERVER['HTTPS'] != "off") ? "https" : "http";
}else{
    $protocol = 'http';
}

$actual_link = $protocol . "://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
$_SERVER['REQUEST_URI_PATH'] = str_replace($config['base_url'], '', $actual_link);

$segments = explode('/', $_SERVER['REQUEST_URI_PATH']);

$config['sess_driver'] = 'files';

if ($segments[0] == 'admin') {

    $config['sess_cookie_name'] = 'admin_sessions';
    $config['sess_expiration'] = 1440;
    $config['sess_save_path'] = FCPATH .
    'application/cache/session/admin/';

} else {

    $config['sess_cookie_name'] = 'catalog_sessions';
    $config['sess_expiration'] = 7200;
    $config['sess_save_path'] = FCPATH .
    'application/cache/session/catalog/';

}

$config['sess_match_ip'] = TRUE;
$config['sess_time_to_update'] = 300;
$config['sess_regenerate_destroy'] = TRUE;
</code>```

Body:
thanks wolfgang.

for those who have subdirectory to host CI you can use the following method,

if(isset($_SERVER['HTTPS'])){
    $protocol = ($_SERVER['HTTPS'] && $_SERVER['HTTPS'] != "off") ? "https" : "http";
}else{
    $protocol = 'http';
}

$actual_link = $protocol . "://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
$_SERVER['REQUEST_URI_PATH'] = str_replace($config['base_url'], '', $actual_link);

$segments = explode('/', $_SERVER['REQUEST_URI_PATH']);

$config['sess_driver'] = 'files';

if ($segments[0] == 'admin') {

    $config['sess_cookie_name'] = 'admin_sessions';
    $config['sess_expiration'] = 1440;
    $config['sess_save_path'] = FCPATH .
    'application/cache/session/admin/';

} else {

    $config['sess_cookie_name'] = 'catalog_sessions';
    $config['sess_expiration'] = 7200;
    $config['sess_save_path'] = FCPATH .
    'application/cache/session/catalog/';

}

$config['sess_match_ip'] = TRUE;
$config['sess_time_to_update'] = 300;
$config['sess_regenerate_destroy'] = TRUE;


问:
How do I stash only one file out of multiple files that have changed?
How do I stash only one of the multiple changed files on my branch?</p>

答:
Solution

Local changes:

file_A (modified) not staged

file_B (modified) not staged

file_C (modified) not staged

To create a stash "my_stash" with only the changes on file_C:

```<code>1. git add file_C
2. git stash save --keep-index temp_stash
3. git stash save my_stash
4. git stash pop stash@#{1}
</code>```

Done.

Explanation

add file_C to the staging area

create a temporary stash named "temp_stash" and keep the changes on file_C

create the wanted stash ("my_stash") with only the changes on file_C

apply the changes in "temp_stash" (file_A and file_B) on your local code and delete the stash

You can use git status between the steps to see what is going on.

Body:
Solution

Local changes:

file_A (modified) not staged

file_B (modified) not staged

file_C (modified) not staged

To create a stash "my_stash" with only the changes on file_C:

1. git add file_C
2. git stash save --keep-index temp_stash
3. git stash save my_stash
4. git stash pop stash@#{1}

Done.

Explanation

add file_C to the staging area

create a temporary stash named "temp_stash" and keep the changes on file_C

create the wanted stash ("my_stash") with only the changes on file_C

apply the changes in "temp_stash" (file_A and file_B) on your local code and delete the stash

You can use git status between the steps to see what is going on.


问:
Where are the "0" gone?
```<code>str = "Blah00blah001"
str1 = ""
str1 = str.gsub(/[0-9]+$/,'')

print str.chars
puts
print str1.chars
puts

print str.chars - str1.chars
</code>```

output

```<code>["B", "l", "a", "h", "0", "0", "b", "l", "a", "h", "0", "0", "1"]
["B", "l", "a", "h", "0", "0", "b", "l", "a", "h"]
["1"]
</code>```

what I was expecting in the last print

```<code>["0","0","1"]
</code>```

What I got

```<code>["1"]
</code>```

Why is it so?

答:
That's the expected result - - functions like the set difference, removing all elements that appear in the second array.
Check out the documentation.

Title: Where are the "0" gone?

Body:
str = "Blah00blah001"
str1 = ""
str1 = str.gsub(/[0-9]+$/,'')

print str.chars
puts
print str1.chars
puts

print str.chars - str1.chars

output

["B", "l", "a", "h", "0", "0", "b", "l", "a", "h", "0", "0", "1"]
["B", "l", "a", "h", "0", "0", "b", "l", "a", "h"]
["1"]

what I was expecting in the last print

["0","0","1"]

What I got

["1"]

Why is it so?


问:
How can I find the normals for each vertex of an object so that I can apply smooth shading with OpenGL?
I'm loading an object from a .off file. This file format does not define the normals for an object's faces or vertices. I have found the face normals using a vector product. But I'm at a loss about finding the normals for each vertex, any ideas? </p>

答:
Average the normals for all faces that share the vertex.

That is, just add all the adjacent face normals and normalize the result.


问:
How to convert a JSON string to a dictionary?
I want to make one function in my swift project that converts String to Dictionary json format but I got one error:

Cannot convert expression's type (@lvalue NSData,options:IntegerLitralConvertible ...

This is my code:

```<code>func convertStringToDictionary (text:String) -> Dictionary<String,String> {

    var data :NSData = text.dataUsingEncoding(NSUTF8StringEncoding)!
    var json :Dictionary = NSJSONSerialization.JSONObjectWithData(data, options:0, error: nil)
    return json
}
</code>```

I make this function in Objective-C :

```<code>- (NSDictionary*)convertStringToDictionary:(NSString*)string {
  NSError* error;
  //giving error as it takes dic, array,etc only. not custom object.
  NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
  id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
  return json;
}
</code>```

答:
With Swift 3, JSONSerialization has a method called jsonObject(with:options:). jsonObject(with:options:) has the following declaration:

```<code>class func jsonObject(with data: Data, options opt: JSONSerialization.ReadingOptions = []) throws -> Any
</code>```

Returns a Foundation object from given JSON data.

When you use jsonObject(with:options:), you have to deal with error handling (try, try? or try!) and type casting (from Any). Therefore, you can solve your problem with one of the following patterns.

#1. Using a method that throws and returns a non-optional type

```<code>import Foundation

func convertToDictionary(from text: String) throws -> [String: String] {
    guard let data = text.data(using: .utf8) else { return [:] }
    let anyResult: Any = try JSONSerialization.jsonObject(with: data, options: [])
    return anyResult as? [String: String] ?? [:]
}
</code>```

Usage:

```<code>let string1 = "{\"City\":\"Paris\"}"
do {
    let dictionary = try convertToDictionary(from: string1)
    print(dictionary) // prints: ["City": "Paris"]
} catch {
    print(error)
}
</code>```

```<code>let string2 = "{\"Quantity\":100}"
do {
    let dictionary = try convertToDictionary(from: string2)
    print(dictionary) // prints [:]
} catch {
    print(error)
}
</code>```

```<code>let string3 = "{\"Object\"}"
do {
    let dictionary = try convertToDictionary(from: string3)
    print(dictionary)
} catch {
    print(error) // prints: Error Domain=NSCocoaErrorDomain Code=3840 "No value for key in object around character 9." UserInfo={NSDebugDescription=No value for key in object around character 9.}
}
</code>```

#2. Using a method that throws and returns an optional type

```<code>import Foundation

func convertToDictionary(from text: String) throws -> [String: String]? {
    guard let data = text.data(using: .utf8) else { return [:] }
    let anyResult: Any = try JSONSerialization.jsonObject(with: data, options: [])
    return anyResult as? [String: String]
}
</code>```

Usage:

```<code>let string1 = "{\"City\":\"Paris\"}"
do {
    let dictionary = try convertToDictionary(from: string1)
    print(String(describing: dictionary)) // prints: Optional(["City": "Paris"])
} catch {
    print(error)
}
</code>```

```<code>let string2 = "{\"Quantity\":100}"
do {
    let dictionary = try convertToDictionary(from: string2)
    print(String(describing: dictionary)) // prints nil
} catch {
    print(error)
}
</code>```

```<code>let string3 = "{\"Object\"}"
do {
    let dictionary = try convertToDictionary(from: string3)
    print(String(describing: dictionary))
} catch {
    print(error) // prints: Error Domain=NSCocoaErrorDomain Code=3840 "No value for key in object around character 9." UserInfo={NSDebugDescription=No value for key in object around character 9.}
}
</code>```

#3. Using a method that does not throw and returns a non-optional type

```<code>import Foundation

func convertToDictionary(from text: String) -> [String: String] {
    guard let data = text.data(using: .utf8) else { return [:] }
    let anyResult: Any? = try? JSONSerialization.jsonObject(with: data, options: [])
    return anyResult as? [String: String] ?? [:]
}
</code>```

Usage:

```<code>import Foundation

func convertToDictionary(from text: String) throws -> [String: String] {
    guard let data = text.data(using: .utf8) else { return [:] }
    let anyResult: Any = try JSONSerialization.jsonObject(with: data, options: [])
    return anyResult as? [String: String] ?? [:]
}
</code>```0

```<code>import Foundation

func convertToDictionary(from text: String) throws -> [String: String] {
    guard let data = text.data(using: .utf8) else { return [:] }
    let anyResult: Any = try JSONSerialization.jsonObject(with: data, options: [])
    return anyResult as? [String: String] ?? [:]
}
</code>```1

```<code>import Foundation

func convertToDictionary(from text: String) throws -> [String: String] {
    guard let data = text.data(using: .utf8) else { return [:] }
    let anyResult: Any = try JSONSerialization.jsonObject(with: data, options: [])
    return anyResult as? [String: String] ?? [:]
}
</code>```2

#4. Using a method that does not throw and returns an optional type

```<code>import Foundation

func convertToDictionary(from text: String) -> [String: String]? {
    guard let data = text.data(using: .utf8) else { return nil }
    let anyResult = try? JSONSerialization.jsonObject(with: data, options: [])
    return anyResult as? [String: String]
}
</code>```

Usage:

```<code>let string1 = "{\"City\":\"Paris\"}"
let dictionary1 = convertToDictionary(from: string1)
print(String(describing: dictionary1)) // prints: Optional(["City": "Paris"])
</code>```

```<code>let string2 = "{\"Quantity\":100}"
let dictionary2 = convertToDictionary(from: string2)
print(String(describing: dictionary2)) // prints: nil
</code>```

```<code>let string3 = "{\"Object\"}"
let dictionary3 = convertToDictionary(from: string3)
print(String(describing: dictionary3)) // prints: nil
</code>```

Body:
I want to make one function in my swift project that converts String to Dictionary json format but I got one error:

Cannot convert expression's type (@lvalue NSData,options:IntegerLitralConvertible ...

This is my code:

func convertStringToDictionary (text:String) -> Dictionary<String,String> {

    var data :NSData = text.dataUsingEncoding(NSUTF8StringEncoding)!
    var json :Dictionary = NSJSONSerialization.JSONObjectWithData(data, options:0, error: nil)
    return json
}

I make this function in Objective-C :

- (NSDictionary*)convertStringToDictionary:(NSString*)string {
  NSError* error;
  //giving error as it takes dic, array,etc only. not custom object.
  NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
  id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
  return json;
}

Body:
With Swift 3, JSONSerialization has a method called jsonObject(with:options:). jsonObject(with:options:) has the following declaration:

class func jsonObject(with data: Data, options opt: JSONSerialization.ReadingOptions = []) throws -> Any

Returns a Foundation object from given JSON data.

When you use jsonObject(with:options:), you have to deal with error handling (try, try? or try!) and type casting (from Any). Therefore, you can solve your problem with one of the following patterns.

#1. Using a method that throws and returns a non-optional type

import Foundation

func convertToDictionary(from text: String) throws -> [String: String] {
    guard let data = text.data(using: .utf8) else { return [:] }
    let anyResult: Any = try JSONSerialization.jsonObject(with: data, options: [])
    return anyResult as? [String: String] ?? [:]
}

Usage:

let string1 = "{\"City\":\"Paris\"}"
do {
    let dictionary = try convertToDictionary(from: string1)
    print(dictionary) // prints: ["City": "Paris"]
} catch {
    print(error)
}

let string2 = "{\"Quantity\":100}"
do {
    let dictionary = try convertToDictionary(from: string2)
    print(dictionary) // prints [:]
} catch {
    print(error)
}

let string3 = "{\"Object\"}"
do {
    let dictionary = try convertToDictionary(from: string3)
    print(dictionary)
} catch {
    print(error) // prints: Error Domain=NSCocoaErrorDomain Code=3840 "No value for key in object around character 9." UserInfo={NSDebugDescription=No value for key in object around character 9.}
}

#2. Using a method that throws and returns an optional type

import Foundation

func convertToDictionary(from text: String) throws -> [String: String]? {
    guard let data = text.data(using: .utf8) else { return [:] }
    let anyResult: Any = try JSONSerialization.jsonObject(with: data, options: [])
    return anyResult as? [String: String]
}

Usage:

let string1 = "{\"City\":\"Paris\"}"
do {
    let dictionary = try convertToDictionary(from: string1)
    print(String(describing: dictionary)) // prints: Optional(["City": "Paris"])
} catch {
    print(error)
}

let string2 = "{\"Quantity\":100}"
do {
    let dictionary = try convertToDictionary(from: string2)
    print(String(describing: dictionary)) // prints nil
} catch {
    print(error)
}

let string3 = "{\"Object\"}"
do {
    let dictionary = try convertToDictionary(from: string3)
    print(String(describing: dictionary))
} catch {
    print(error) // prints: Error Domain=NSCocoaErrorDomain Code=3840 "No value for key in object around character 9." UserInfo={NSDebugDescription=No value for key in object around character 9.}
}

#3. Using a method that does not throw and returns a non-optional type

import Foundation

func convertToDictionary(from text: String) -> [String: String] {
    guard let data = text.data(using: .utf8) else { return [:] }
    let anyResult: Any? = try? JSONSerialization.jsonObject(with: data, options: [])
    return anyResult as? [String: String] ?? [:]
}

Usage:

let string1 = "{\"City\":\"Paris\"}"
let dictionary1 = convertToDictionary(from: string1)
print(dictionary1) // prints: ["City": "Paris"]

let string2 = "{\"Quantity\":100}"
let dictionary2 = convertToDictionary(from: string2)
print(dictionary2) // prints: [:]

let string3 = "{\"Object\"}"
let dictionary3 = convertToDictionary(from: string3)
print(dictionary3) // prints: [:]

#4. Using a method that does not throw and returns an optional type

import Foundation

func convertToDictionary(from text: String) -> [String: String]? {
    guard let data = text.data(using: .utf8) else { return nil }
    let anyResult = try? JSONSerialization.jsonObject(with: data, options: [])
    return anyResult as? [String: String]
}

Usage:

let string1 = "{\"City\":\"Paris\"}"
let dictionary1 = convertToDictionary(from: string1)
print(String(describing: dictionary1)) // prints: Optional(["City": "Paris"])

let string2 = "{\"Quantity\":100}"
let dictionary2 = convertToDictionary(from: string2)
print(String(describing: dictionary2)) // prints: nil

let string3 = "{\"Object\"}"
let dictionary3 = convertToDictionary(from: string3)
print(String(describing: dictionary3)) // prints: nil


答:
A quick quote from the documentation of Array#-:

ary - other_ary → new_ary

Returns a new array that is a copy of the original array, removing any items that also appear in other_ary. The order is preserved from the original array.

The example posted after the description shows how it works (the same as it works with your arrays):

```<code>[ 1, 1, 2, 2, 3, 3, 4, 5 ] - [ 1, 2, 4 ]  #=>  [ 3, 3, 5 ]
</code>```

Title: Where are the "0" gone?

Body:
A quick quote from the documentation of Array#-:

ary - other_ary → new_ary

Returns a new array that is a copy of the original array, removing any items that also appear in other_ary. The order is preserved from the original array.

The example posted after the description shows how it works (the same as it works with your arrays):

[ 1, 1, 2, 2, 3, 3, 4, 5 ] - [ 1, 2, 4 ]  #=>  [ 3, 3, 5 ]


问:
How to import html text in a leaflet popup
I have a pretty map with a cool event that trigger a map.onclick event like that :

```<code>function onMapClick(e) {
    L.popup()
        .setLatLng(e.latlng)
        .setContent('<link rel="import" href="./pages/myPopup.html">')
        .openOn(mymap);
    }
mymap.on('click', onMapClick);
</code>```

And i'm trying to import html text in my leaflet popup.
I'm using bootstrap+JQuery and I already saw bootstrap3-dialog but I think there is something to try with HTML5 or with jquery, but I don't know how !

I also found some explanations for having a click link inside leaflet popup that help for the start ! (JSFiddle here)

答:
You sound to be looking for a simple  (instead of your strange <link> tag which is for the page ) embedded in a Leaflet popup.

```

This is extremely simple and does not present any particular issue. Do not forget to set height and width on your iframe.

Demo: https://plnkr.co/edit/m94za7fHpGakqouMmwO2?p=preview

Body:
I have a pretty map with a cool event that trigger a map.onclick event like that :

function onMapClick(e) {
    L.popup()
        .setLatLng(e.latlng)
        .setContent('<link rel="import" href="./pages/myPopup.html">')
        .openOn(mymap);
    }
mymap.on('click', onMapClick);

And i'm trying to import html text in my leaflet popup.
I'm using bootstrap+JQuery and I already saw bootstrap3-dialog but I think there is something to try with HTML5 or with jquery, but I don't know how !

I also found some explanations for having a click link inside leaflet popup that help for the start ! (JSFiddle here)

Body:
You sound to be looking for a simple <iframe> (instead of your strange <link> tag which is for the page <head>) embedded in a Leaflet popup.

<iframe src="./myPopup.html"></iframe>

This is extremely simple and does not present any particular issue. Do not forget to set height and width on your iframe.

Demo: https://plnkr.co/edit/m94za7fHpGakqouMmwO2?p=preview


问:
How to deal with losing deep imports in Angular 4
I have just updated to Angular 4 and learned that it no longer supports deep imports.

So I was using VALID to help validate forms. But now that the I can't import it with the deep import

```<code>import { VALID } from '@angular/forms/src/model
</code>```

And since this does not work,

```<code>import { VALID } from '@angular/forms/'
</code>```

What are we expected to do to access it? Or anything for that matter that was previously accessed with a deep import?

答:
Angular 4  no longer supports deep imports . In Angular 2  you could do this,

```<code>import { VALID } from '@angular/forms/src/model'
</code>```

but now in Angular 4  you can only go to the first level,

```<code>import { VALID } from '@angular/forms'
</code>```

So basically anything you were accessing by deep import is no longer useable if it is not exported, which would make it available so you can access it from that first level.

So in my case VALID  was not reachable. So in order to validate I just validated it with the string response from checking the validation of the input field on blur instead of the bool.

```<code>formInputValidate(inputField: string, ErrorTitle: string, ErrorMessage: string) {
  if (this.profileForm.get(inputField).status === 'VALID') {
    this.toastSuccess(inputField, ' entered correctly');
  } else {
    this.toastWarning(ErrorTitle, ErrorMessage);
  }
}
</code>```

Which raises a new question,

In my case this was an easy fix. But if the situation is more complicated and the deep import  helper was critical, how do we get around this?

I asked the contributors of Angular on git here and they said,

So it appears that if there is someone we need we can request it and they will consider it!

Body:
I have just updated to Angular 4 and learned that it no longer supports deep imports.

So I was using VALID to help validate forms. But now that the I can't import it with the deep import

import { VALID } from '@angular/forms/src/model

And since this does not work,

import { VALID } from '@angular/forms/'

What are we expected to do to access it? Or anything for that matter that was previously accessed with a deep import?

Body:
Angular 4  no longer supports deep imports . In Angular 2  you could do this,

import { VALID } from '@angular/forms/src/model'

but now in Angular 4  you can only go to the first level,

import { VALID } from '@angular/forms'

So basically anything you were accessing by deep import is no longer useable if it is not exported, which would make it available so you can access it from that first level.

So in my case VALID  was not reachable. So in order to validate I just validated it with the string response from checking the validation of the input field on blur instead of the bool.

formInputValidate(inputField: string, ErrorTitle: string, ErrorMessage: string) {
  if (this.profileForm.get(inputField).status === 'VALID') {
    this.toastSuccess(inputField, ' entered correctly');
  } else {
    this.toastWarning(ErrorTitle, ErrorMessage);
  }
}

Which raises a new question,

In my case this was an easy fix. But if the situation is more complicated and the deep import  helper was critical, how do we get around this?

I asked the contributors of Angular on git here and they said,

So it appears that if there is someone we need we can request it and they will consider it!