问:
How to create report in SQL based on query parameter date and its corresponding weekday
My SQL table is as under

The data is being updated by users on a daily basis and report_date is changed as when data updated by any user. Now I need to generate a report from the above table based on the date as a parameter. For example, If the query parameter (Report_date) is 1-Feb-20 then report should be
Rly, Sum of Trains on weekday corresponding to the query date (sum of trains where Sch_SAT is Y as Saturday is weekday for 1-Feb-20), Sum of trains (where Report_date is equal to query date and Sch_SAT is Y), Sum of Trains where Sch_SAT is Y and Report_date is not equal to query date. The desired Report is as under:

Is it possible to generate the above report? If possible, please help.

答:
Thanks for valuable tips for asking questions in presentable form on this forum. I will keep in mind in future issues. I have achieved the desired results by splitting & rejoining the table. My SQL query (stored procedure) is

```<code>USE [Loco_bank]
GO
 /****** Object:  StoredProcedure [dbo].[HOG_summary]    Script Date: 02/13/2020 10:19:07 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE  [dbo].[HOG_summary] @Sunday varchar(1), @Monday varchar(1), @Tuesday varchar(1), @Wednesday varchar(1), @Thursday varchar(1), @Friday varchar(1), @Saturday varchar(1), @dt DATETIME AS

Begin

SELECT  Zrly as Master_Zrly, COUNT(Train) as Trains_sch INTO #tab1 FROM Hotel_load WHERE ([Saturday] = @Saturday OR @Saturday IS NULL) AND ([Sunday] = @Sunday OR @Sunday IS NULL) AND ([Monday] = @Monday OR @Monday IS NULL) AND ([Tuesday] = @Tuesday OR @Tuesday IS NULL) AND ([Wednesday] = @Wednesday OR @Wednesday IS NULL) AND ([Thursday] = @Thursday OR @Thursday IS NULL) AND ([Friday] = @Friday OR @Friday IS NULL)
GROUP BY Zrly

  SELECT  Zrly, COUNT(updated_on) as Reported, COUNT(HOG_loco_type_master) as HOG_Run, (COUNT(updated_on) - COUNT(HOG_loco_type_master)) as NONHOG_Run  INTO #tab2 FROM Hotel_load WHERE ([Saturday] = @Saturday OR @Saturday IS NULL) AND ([Sunday] = @Sunday OR @Sunday IS NULL) AND ([Monday] = @Monday OR @Monday IS NULL) AND ([Tuesday] = @Tuesday OR @Tuesday IS NULL) AND ([Wednesday] = @Wednesday OR @Wednesday IS NULL) AND ([Thursday] = @Thursday OR @Thursday IS NULL) AND ([Friday] = @Friday OR @Friday IS NULL) AND updated_on = @dt GROUP BY Zrly

SELECT #tab1.Master_Zrly, #tab1.Trains_sch, #tab2.Zrly, #tab2.Reported, #tab2.HOG_Run, #tab2.NONHOG_Run FROM #tab1
LEFT JOIN #tab2 ON #tab1.Master_Zrly = #tab2.Zrly

End
</code>```

My query string is:

```<code> http://127.0.0.1/HOG/HOG_Report_BD.aspx?Wednesday=Y&dt=12-Feb-2020
</code>```

And Output is

```<code>| Master_Zrly | Trains_sch | Reported | HOG_Run | NONHOG_Run |
|-------------|------------|----------|---------|------------|
| SCR         | 25         | 9        | 18      | 2          |
| NCR         | 9          | 2        | 5       | 4          |
| SWR         | 13         | 4        |         |            |
| ER          | 28         | 7        | 22      | 1          |
| WCR         | 13         | 6        | 7       | 5          |
| CR          | 40         | 18       | 21      | 10         |
| KR          | 1          | 1        |         |            |
| NWR         | 17         | 16       |         |            |
| ECoR        | 11         | 2        |         |            |
| NR          | 99         | 30       | 62      | 6          |
</code>```

Body:
Thanks for valuable tips for asking questions in presentable form on this forum. I will keep in mind in future issues. I have achieved the desired results by splitting & rejoining the table. My SQL query (stored procedure) is

USE [Loco_bank]
GO
 /****** Object:  StoredProcedure [dbo].[HOG_summary]    Script Date: 02/13/2020 10:19:07 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE  [dbo].[HOG_summary] @Sunday varchar(1), @Monday varchar(1), @Tuesday varchar(1), @Wednesday varchar(1), @Thursday varchar(1), @Friday varchar(1), @Saturday varchar(1), @dt DATETIME AS

Begin

SELECT  Zrly as Master_Zrly, COUNT(Train) as Trains_sch INTO #tab1 FROM Hotel_load WHERE ([Saturday] = @Saturday OR @Saturday IS NULL) AND ([Sunday] = @Sunday OR @Sunday IS NULL) AND ([Monday] = @Monday OR @Monday IS NULL) AND ([Tuesday] = @Tuesday OR @Tuesday IS NULL) AND ([Wednesday] = @Wednesday OR @Wednesday IS NULL) AND ([Thursday] = @Thursday OR @Thursday IS NULL) AND ([Friday] = @Friday OR @Friday IS NULL)
GROUP BY Zrly

  SELECT  Zrly, COUNT(updated_on) as Reported, COUNT(HOG_loco_type_master) as HOG_Run, (COUNT(updated_on) - COUNT(HOG_loco_type_master)) as NONHOG_Run  INTO #tab2 FROM Hotel_load WHERE ([Saturday] = @Saturday OR @Saturday IS NULL) AND ([Sunday] = @Sunday OR @Sunday IS NULL) AND ([Monday] = @Monday OR @Monday IS NULL) AND ([Tuesday] = @Tuesday OR @Tuesday IS NULL) AND ([Wednesday] = @Wednesday OR @Wednesday IS NULL) AND ([Thursday] = @Thursday OR @Thursday IS NULL) AND ([Friday] = @Friday OR @Friday IS NULL) AND updated_on = @dt GROUP BY Zrly

SELECT #tab1.Master_Zrly, #tab1.Trains_sch, #tab2.Zrly, #tab2.Reported, #tab2.HOG_Run, #tab2.NONHOG_Run FROM #tab1
LEFT JOIN #tab2 ON #tab1.Master_Zrly = #tab2.Zrly

End

My query string is:

 http://127.0.0.1/HOG/HOG_Report_BD.aspx?Wednesday=Y&dt=12-Feb-2020

And Output is

| Master_Zrly | Trains_sch | Reported | HOG_Run | NONHOG_Run |
|-------------|------------|----------|---------|------------|
| SCR         | 25         | 9        | 18      | 2          |
| NCR         | 9          | 2        | 5       | 4          |
| SWR         | 13         | 4        |         |            |
| ER          | 28         | 7        | 22      | 1          |
| WCR         | 13         | 6        | 7       | 5          |
| CR          | 40         | 18       | 21      | 10         |
| KR          | 1          | 1        |         |            |
| NWR         | 17         | 16       |         |            |
| ECoR        | 11         | 2        |         |            |
| NR          | 99         | 30       | 62      | 6          |


来源: stackexchange

问:
Can GoogleCloudVision API for PDF OCR output to PubSub?
I am using the following code to request an OCR operation on the Google cloud vision API:

```<code>    from google.cloud import vision
    from google.cloud import storage
    from google.protobuf import json_format
    # Supported mime_types are: 'application/pdf' and 'image/tiff'
    mime_type = 'application/pdf'

    # How many pages should be grouped into each json output file.
    batch_size = 2

    client = vision.ImageAnnotatorClient()

    feature = vision.types.Feature(
        type=vision.enums.Feature.Type.DOCUMENT_TEXT_DETECTION)

    gcs_source = vision.types.GcsSource(uri=gcs_source_uri)
    input_config = vision.types.InputConfig(
        gcs_source=gcs_source, mime_type=mime_type)

    gcs_destination = vision.types.GcsDestination(uri=gcs_destination_uri)
    output_config = vision.types.OutputConfig(
        gcs_destination=gcs_destination, batch_size=batch_size)

    async_request = vision.types.AsyncAnnotateFileRequest(
        features=[feature], input_config=input_config,
        output_config=output_config)

    operation = client.async_batch_annotate_files(
        requests=[async_request])
</code>```

When I call the AsyncAnnotateFileRequest operation I am passing a GcsDestination OutputConfig object. With this object I am telling the API to write the result to a GoogleCloudStorage bucket. I wonder if it is possible to write to PubSub instead? I looked around the documentation but it looks like it is not possible, as last resort thought to ask here. Maybe I am missing something?

EDIT:
I am exploring synchronous requests, where I can request the OCR, receive the text as response and then write to PubSub. Like this:

```<code>request = vision.types.AnnotateFileReques(features=[feature], input_config=input_config)

response = vision_client.batch_annotate_files(requests=[request])
</code>```

but I am getting
AttributeError: module 'google.cloud.vision_v1.types' has no attribute 'AnnotateFileReques' but from the doc it should be there.
Suggestions?

答: I kid you not there is a detailed tutorial on how to do this with Python. https://cloud.google.com/functions/docs/tutorials/ocr

ContentLicense: CC BY-SA 4.0

Body:
I am using the following code to request an OCR operation on the Google cloud vision API:

    from google.cloud import vision
    from google.cloud import storage
    from google.protobuf import json_format
    # Supported mime_types are: 'application/pdf' and 'image/tiff'
    mime_type = 'application/pdf'

    # How many pages should be grouped into each json output file.
    batch_size = 2

    client = vision.ImageAnnotatorClient()

    feature = vision.types.Feature(
        type=vision.enums.Feature.Type.DOCUMENT_TEXT_DETECTION)

    gcs_source = vision.types.GcsSource(uri=gcs_source_uri)
    input_config = vision.types.InputConfig(
        gcs_source=gcs_source, mime_type=mime_type)

    gcs_destination = vision.types.GcsDestination(uri=gcs_destination_uri)
    output_config = vision.types.OutputConfig(
        gcs_destination=gcs_destination, batch_size=batch_size)

    async_request = vision.types.AsyncAnnotateFileRequest(
        features=[feature], input_config=input_config,
        output_config=output_config)

    operation = client.async_batch_annotate_files(
        requests=[async_request])

When I call the AsyncAnnotateFileRequest operation I am passing a GcsDestination OutputConfig object. With this object I am telling the API to write the result to a GoogleCloudStorage bucket. I wonder if it is possible to write to PubSub instead? I looked around the documentation but it looks like it is not possible, as last resort thought to ask here. Maybe I am missing something?

EDIT:
I am exploring synchronous requests, where I can request the OCR, receive the text as response and then write to PubSub. Like this:

request = vision.types.AnnotateFileReques(features=[feature], input_config=input_config)

response = vision_client.batch_annotate_files(requests=[request])

but I am getting
AttributeError: module 'google.cloud.vision_v1.types' has no attribute 'AnnotateFileReques' but from the doc it should be there.
Suggestions?


问:
How to check if a number in my contacts is registered to Whatsapp?
But I need this with numbers with country codes (like starting with +123 456 78 90 -that's the way I add the number as a contact)
I need a function/class to check if this number has Whatsapp.
I need this for an .apk I made in Android Studio.  </p>

答:
```<code> private void getAllWhatsappNumbers()
{
    //This class provides applications access to the content model.
    ContentResolver cr = context.getContentResolver();

//RowContacts for filter Account Types
    Cursor contactCursor = cr.query(
            ContactsContract.RawContacts.CONTENT_URI,
            new String[]{ContactsContract.RawContacts._ID,
                    ContactsContract.RawContacts.CONTACT_ID},
            ContactsContract.RawContacts.ACCOUNT_TYPE + "= ?",
            new String[]{"com.whatsapp"},
            null);

    if (contactCursor != null) {
        if (contactCursor.getCount() > 0) {
            if (contactCursor.moveToFirst()) {
                do {
                    //whatsappContactId for get Number,Name,Id ect... from  ContactsContract.CommonDataKinds.Phone
                    String whatsappContactId = contactCursor.getString(contactCursor.getColumnIndex(ContactsContract.RawContacts.CONTACT_ID));

                    if (whatsappContactId != null) {
                        //Get Data from ContactsContract.CommonDataKinds.Phone of Specific CONTACT_ID
                        Cursor whatsAppContactCursor = cr.query(
                                ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                                new String[]{ContactsContract.CommonDataKinds.Phone.CONTACT_ID,
                                        ContactsContract.CommonDataKinds.Phone.NUMBER,
                                        ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME},
                                ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?",
                                new String[]{whatsappContactId}, null);

                        if (whatsAppContactCursor != null) {
                            whatsAppContactCursor.moveToFirst();
                            String id = whatsAppContactCursor.getString(whatsAppContactCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.CONTACT_ID));
                            String name = whatsAppContactCursor.getString(whatsAppContactCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
                            String number = whatsAppContactCursor.getString(whatsAppContactCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                            Log.d("log1","no:"+number+"name:"+name);
                            whatsAppContactCursor.close();

                            //Add Number to ArrayList
                            myWhatsappContactsNumbers.add(number);
                        }
                    }
                } while (contactCursor.moveToNext());
                contactCursor.close();
            }
        }
    }
}
</code>```

With this function provided, we can get contact list on "com.whatsapp"
We put this contact list in to the array list so we need a function to show us we the number we sent is in the list (true) or not (false). How can we achieve that?

Body:
 private void getAllWhatsappNumbers()
{
    //This class provides applications access to the content model.
    ContentResolver cr = context.getContentResolver();

//RowContacts for filter Account Types
    Cursor contactCursor = cr.query(
            ContactsContract.RawContacts.CONTENT_URI,
            new String[]{ContactsContract.RawContacts._ID,
                    ContactsContract.RawContacts.CONTACT_ID},
            ContactsContract.RawContacts.ACCOUNT_TYPE + "= ?",
            new String[]{"com.whatsapp"},
            null);

    if (contactCursor != null) {
        if (contactCursor.getCount() > 0) {
            if (contactCursor.moveToFirst()) {
                do {
                    //whatsappContactId for get Number,Name,Id ect... from  ContactsContract.CommonDataKinds.Phone
                    String whatsappContactId = contactCursor.getString(contactCursor.getColumnIndex(ContactsContract.RawContacts.CONTACT_ID));

                    if (whatsappContactId != null) {
                        //Get Data from ContactsContract.CommonDataKinds.Phone of Specific CONTACT_ID
                        Cursor whatsAppContactCursor = cr.query(
                                ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                                new String[]{ContactsContract.CommonDataKinds.Phone.CONTACT_ID,
                                        ContactsContract.CommonDataKinds.Phone.NUMBER,
                                        ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME},
                                ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?",
                                new String[]{whatsappContactId}, null);

                        if (whatsAppContactCursor != null) {
                            whatsAppContactCursor.moveToFirst();
                            String id = whatsAppContactCursor.getString(whatsAppContactCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.CONTACT_ID));
                            String name = whatsAppContactCursor.getString(whatsAppContactCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
                            String number = whatsAppContactCursor.getString(whatsAppContactCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                            Log.d("log1","no:"+number+"name:"+name);
                            whatsAppContactCursor.close();

                            //Add Number to ArrayList
                            myWhatsappContactsNumbers.add(number);
                        }
                    }
                } while (contactCursor.moveToNext());
                contactCursor.close();
            }
        }
    }
}

With this function provided, we can get contact list on "com.whatsapp"
We put this contact list in to the array list so we need a function to show us we the number we sent is in the list (true) or not (false). How can we achieve that?


问:
C# MVVM ASP.net API implicit conversion error
New to web app API's and trying to build a web app that exposes data from our DWH environment to the application via an API.

My models:

bed_data_dbconnect - context model:

```<code>     using Microsoft.EntityFrameworkCore;

     namespace BED_MGMT_WEBAPP_APIs.Models
       {
         public class bed_data_dbconnect : DbContext
         {
         public bed_data_dbconnect(DbContextOptions options) : base(options)
         { }

         public DbSet<Bed_Data> tblBase_BEDMGMT_BEDS_BY_WARD { get; set; }
     }
 }
</code>```

bed_data model

```<code> using System;

 namespace BED_MGMT_WEBAPP_APIs.Models
 {
     public class Bed_Data
     {
    public string HOSPITAL {get;set;}
    public string WARD_CODE {get;set;}
    public string WARD {get;set;}
    public string REALTIME_BED_STOCK {get;set;}
    public string ACTUAL_BED_STOCK {get;set;}
    public string AVAILABLE_BEDS_M {get;set;}
    public string AVAILABLE_BEDS_F {get;set;}
    public string AVAILABLE_BEDS_C {get;set;}
    public string TOTAL_BEDS_CLOSED {get;set;}
    public string CLOSED_AND_UNOCCUPIED {get;set;}
    public string ESCALATION_BEDS_IN_USE {get;set;}
    public string DISCHARGES_CONFIRMED_M {get;set;}
    public string DISCHARGES_CONFIRMED_F {get;set;}
    public string DISCHARGES_CONFIRMED_C {get;set;}
    public string DISCHARGES_POTENTIAL_M {get;set;}
    public string DISCHARGES_POTENTIAL_F {get;set;}
    public string DISCHARGES_POTENTIAL_C {get;set;}
    public string AWAITING_ADMISSION_AE_M {get;set;}
    public string AWAITING_ADMISSION_AE_F {get;set;}
    public string AWAITING_ADMISSION_AE_C {get;set;}
    public string AWAITING_ADMISSION_INTERNAL_M {get;set;}
    public string AWAITING_ADMISSION_INTERNAL_F {get;set;}
    public string AWAITING_ADMISSION_INTERNAL_C {get;set;}
    public string AWAITING_ADMISSION_EXTERNAL_M {get;set;}
    public string AWAITING_ADMISSION_EXTERNAL_F {get;set;}
    public string AWAITING_ADMISSION_EXTERNAL_C {get;set;}
    public string AWAITING_REPATRIATION_IN {get;set;}
    public string AWAITING_REPATRIATION_OUT {get;set;}
    public string OUTLIERS_MED {get;set;}
    public string OUTLIERS_SURG {get;set;}
    public string OUTLIERS_ORTH {get;set;}
    public string STAFFING_SHORTAGES {get;set;}
    public string USER_CODE {get;set;}
    public string DATETIME_RECORD_INSERTED {get;set;} //= System.Convert.ToDateTime()

    }
 }
</code>```

db connection string in my startup file:

```<code>  public void ConfigureServices(IServiceCollection services)
    {
        string connectionString = Configuration.GetConnectionString("DefaultConnection");
        services.AddDbContext<bed_data_dbconnect>(opt => opt.UseSqlServer(connectionString));
        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_3_0);
    }
</code>```

Controller:

```<code> using Microsoft.AspNetCore.Mvc;
 using System.Collections.Generic;
 using System.Linq;
 using BED_MGMT_WEBAPP_APIs.Models;

 namespace BED_MGMT_WEBAPP_APIs.Controllers
 {
   [Route("api/[Controller]")]
   [ApiController]

    public class bed_data_controller : Controller
    {
    private bed_data_dbconnect _bed_data;

    public bed_data_controller(bed_data_dbconnect context)
    {

    _bed_data = context;

    }

    //Get api/values
    [HttpGet]

    public ActionResult<IEnumerable<bed_data_dbconnect>> Get()
    {

        return _bed_data.tblBase_BEDMGMT_BEDS_BY_WARD.ToList();

    }

    ~bed_data_controller()
    {

        _bed_data.Dispose();

    }

     }
 }
</code>```

I am trying to return the contents of this table to a list to validate the api is working as expected, but the controller above generates an error:

Cannot implicitly convert type
       'System.Collections.Generic.List' to 'Microsoft.AspNetCore.Mvc.ActionResult>' [BED_MGMT_WEBAPP_APIs]

on this line:

```<code> return _bed_data.tblBase_BEDMGMT_BEDS_BY_WARD.ToList();
</code>```

答:
You can try it like this:</p>

```<code>[HttpGet]
public ActionResult Get()
{
    var result=_bed_data.tblBase_BEDMGMT_BEDS_BY_WARD.ToList();
    return Json(result);
}
</code>```

Body:
New to web app API's and trying to build a web app that exposes data from our DWH environment to the application via an API.

My models:

bed_data_dbconnect - context model:

     using Microsoft.EntityFrameworkCore;

     namespace BED_MGMT_WEBAPP_APIs.Models
       {
         public class bed_data_dbconnect : DbContext
         {
         public bed_data_dbconnect(DbContextOptions options) : base(options)
         { }

         public DbSet<Bed_Data> tblBase_BEDMGMT_BEDS_BY_WARD { get; set; }
     }
 }

bed_data model

 using System;

 namespace BED_MGMT_WEBAPP_APIs.Models
 {
     public class Bed_Data
     {
    public string HOSPITAL {get;set;}
    public string WARD_CODE {get;set;}
    public string WARD {get;set;}
    public string REALTIME_BED_STOCK {get;set;}
    public string ACTUAL_BED_STOCK {get;set;}
    public string AVAILABLE_BEDS_M {get;set;}
    public string AVAILABLE_BEDS_F {get;set;}
    public string AVAILABLE_BEDS_C {get;set;}
    public string TOTAL_BEDS_CLOSED {get;set;}
    public string CLOSED_AND_UNOCCUPIED {get;set;}
    public string ESCALATION_BEDS_IN_USE {get;set;}
    public string DISCHARGES_CONFIRMED_M {get;set;}
    public string DISCHARGES_CONFIRMED_F {get;set;}
    public string DISCHARGES_CONFIRMED_C {get;set;}
    public string DISCHARGES_POTENTIAL_M {get;set;}
    public string DISCHARGES_POTENTIAL_F {get;set;}
    public string DISCHARGES_POTENTIAL_C {get;set;}
    public string AWAITING_ADMISSION_AE_M {get;set;}
    public string AWAITING_ADMISSION_AE_F {get;set;}
    public string AWAITING_ADMISSION_AE_C {get;set;}
    public string AWAITING_ADMISSION_INTERNAL_M {get;set;}
    public string AWAITING_ADMISSION_INTERNAL_F {get;set;}
    public string AWAITING_ADMISSION_INTERNAL_C {get;set;}
    public string AWAITING_ADMISSION_EXTERNAL_M {get;set;}
    public string AWAITING_ADMISSION_EXTERNAL_F {get;set;}
    public string AWAITING_ADMISSION_EXTERNAL_C {get;set;}
    public string AWAITING_REPATRIATION_IN {get;set;}
    public string AWAITING_REPATRIATION_OUT {get;set;}
    public string OUTLIERS_MED {get;set;}
    public string OUTLIERS_SURG {get;set;}
    public string OUTLIERS_ORTH {get;set;}
    public string STAFFING_SHORTAGES {get;set;}
    public string USER_CODE {get;set;}
    public string DATETIME_RECORD_INSERTED {get;set;} //= System.Convert.ToDateTime()

    }
 }

db connection string in my startup file:

  public void ConfigureServices(IServiceCollection services)
    {
        string connectionString = Configuration.GetConnectionString("DefaultConnection");
        services.AddDbContext<bed_data_dbconnect>(opt => opt.UseSqlServer(connectionString));
        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_3_0);
    }

Controller:

 using Microsoft.AspNetCore.Mvc;
 using System.Collections.Generic;
 using System.Linq;
 using BED_MGMT_WEBAPP_APIs.Models;

 namespace BED_MGMT_WEBAPP_APIs.Controllers
 {
   [Route("api/[Controller]")]
   [ApiController]

    public class bed_data_controller : Controller
    {
    private bed_data_dbconnect _bed_data;

    public bed_data_controller(bed_data_dbconnect context)
    {

    _bed_data = context;

    }

    //Get api/values
    [HttpGet]

    public ActionResult<IEnumerable<bed_data_dbconnect>> Get()
    {

        return _bed_data.tblBase_BEDMGMT_BEDS_BY_WARD.ToList();

    }

    ~bed_data_controller()
    {

        _bed_data.Dispose();

    }

     }
 }

I am trying to return the contents of this table to a list to validate the api is working as expected, but the controller above generates an error:

Cannot implicitly convert type
       'System.Collections.Generic.List' to 'Microsoft.AspNetCore.Mvc.ActionResult>' [BED_MGMT_WEBAPP_APIs]

on this line:

 return _bed_data.tblBase_BEDMGMT_BEDS_BY_WARD.ToList();

Body:
You can try it like this:

[HttpGet]
public ActionResult Get()
{
    var result=_bed_data.tblBase_BEDMGMT_BEDS_BY_WARD.ToList();
    return Json(result);
}


问:
GIF image not showing up on iphones
I have a gif image that ends in .gif  It shows up correctly on android phones and chrome.  Iphones are unable to show the gif.  An image of what it should look like, and what it shows on an Iphone are below.

The iphone im testing with is Iphone 6 ios 11.4

Image on iphones for the gif, as it is not showing up.

Blinking gif showing up on other browsers and phones.

答:
If you use the SDWebImage library for image loading and caching in your project, you will find a class named FLAnimatedImage. Using this you can easily integrate a GIF.</p>

```<code>FLAnimatedImage *image = [[FLAnimatedImage alloc] initWithAnimatedGIFData:[NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"<your_file_name>" ofType:@"gif"]]];

    [yourImageView setAnimatedImage:image];
    __weak typeof(self) weakself = self;
    yourImageView.loopCompletionBlock = ^(NSUInteger loopCountRemaining) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [weakself.yourImageView startAnimating];
        });
    };
</code>```

Title: GIF image not showing up on iphones

Body:
If you use the SDWebImage library for image loading and caching in your project, you will find a class named FLAnimatedImage. Using this you can easily integrate a GIF.

FLAnimatedImage *image = [[FLAnimatedImage alloc] initWithAnimatedGIFData:[NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"<your_file_name>" ofType:@"gif"]]];

    [yourImageView setAnimatedImage:image];
    __weak typeof(self) weakself = self;
    yourImageView.loopCompletionBlock = ^(NSUInteger loopCountRemaining) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [weakself.yourImageView startAnimating];
        });
    };


问:
Getting java gui to open a webpage in web browser
I am trying to get a java gui to open a web page. So the gui runs some code that does things and then produces a html file.
I then want this file to open in a web browser (preferrably Firefox) as soon as it is created.
How would I go about doing that?</p>

答:
I've used BrowserLauncher2 with success. It'll invoke the default browser on all platforms tested. I use this for demoing software via JNLP. The software downloads, runs and drives the user's browser to information pages/feedback etc.

JDK 1.4 and above, I believe.

OwnerDisplayName: The Special One

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Rich B

OwnerDisplayName: Brian Agnew


问:
When to close the InputStream object used in the constructor of HSSFWorkbook?
I am working with HSSFWorkbook and I wanted to know where should I close the InputStream object that I have used while constructing the HSSFWorkbook object. Does HSSFWorkbook closes the stream in its constructor itself? or do we need to close it manually? And can we close it just after the constructor call? i.e., does HSSFWorkbook object use the InputStream object in its constructor only? or can it also use it in future (in this case we cant close it)? thank you.

```<code>public HSSFWorkbook loadSheet(File file) throws FileNotFoundException, IOException {
    return new HSSFWorkbook(new FileInputStream(file));
}
</code>```

答:
The constructor of HSSFWorkbook doesn't state whether the InputStream will be closed or left open, so at a first glance you shouldn't make assumptions that it's going to be closed. Digging deeper, however, the constructor of a class used within the constructor itself on the other hand does state clearly its behaviour.

At least in Apache POI 4.0.0 the call to new HSSFWorkbook(inputStream) will result in a call to new POIFSFileSystem(inputStream) which, in its implementation, does indeed appear to always close the stream and the constructor documentation confirms it.

This would seem to point to the following answers to your questions:

Does HSSFWorkbook closes the stream in its constructor itself? Yes, indirectly.

Or do we need to close it manually? Apparently not, unless they decide to no longer rely on POIFSFileSystem, which seems unlikely.

And can we close it just after the constructor call? Apparently, yes... but there's no need for it.

i.e. does HSSFWorkbook object use the InputStream object in its constructor only? Apparently so.

Body:
I am working with HSSFWorkbook and I wanted to know where should I close the InputStream object that I have used while constructing the HSSFWorkbook object. Does HSSFWorkbook closes the stream in its constructor itself? or do we need to close it manually? And can we close it just after the constructor call? i.e., does HSSFWorkbook object use the InputStream object in its constructor only? or can it also use it in future (in this case we cant close it)? thank you.

public HSSFWorkbook loadSheet(File file) throws FileNotFoundException, IOException {
    return new HSSFWorkbook(new FileInputStream(file));
}


问:
How to write a generic non-member wrapper around arbitrary member functions?

Problem

Have a template that generates a wrapper for an arbitrary member function that allows to invoke that function on an object, e.g.:

Given bool std::string::empty(), the wrapper to be generated would be bool wrapper(const std::string& str) { return str.empty(); }.

The wrapper function shall not be a lambda (so that it can be passed as function pointer).

My approach (for non-const member functions)

```<code>/* Wrapper (for non-const member functions) */

template<typename T, typename R, typename... ARGS>
struct staticWrapperHelper
{
    using fType = R (T::*)(ARGS...);
    template<fType FUNCTION>
    static R wrapper(T& object, ARGS... args) { return object.*FUNCTION(args...); }
};

template<typename T, typename R, typename... ARGS>
auto staticWrapper(R (T::*memberFunction)(ARGS...))
{
    //auto function = [memberFunction] (T& object, ARGS... args) -> R { return (object.*memberFunction)(args...); };
    using Helper = staticWrapperHelper<T, R, ARGS...>;

    R (*wrapper)(T&, ARGS...) = &Helper::template wrapper<R (T::*)(ARGS...)>;
    return wrapper;
}

/* Example */

class A
{
public:
    void member() {}
};

int main()
{
    A a;
    auto f = staticWrapper<A>(&A::member);
    f(a);

    return 0;
}

</code>```

Issue with my approach

It does not compile. It seems like the returned wrapper is still a template: http://coliru.stacked-crooked.com/a/d4c0dd9ab631aa1f

```
g++ -std=c++14 -O2 -Wall -pedantic -pthread main.cpp && ./a.out
main.cpp: In instantiation of 'auto staticWrapper(R (T::*)(ARGS ...)) [with T = A; R = void; ARGS = {}]':
main.cpp:32:41:   required from here
main.cpp:17:9: error: no matches converting function 'wrapper' to type 'void (*)(class A&)'
   17 |     R (*wrapper)(T&, ARGS...) = &Helper::template wrapper;
      |         ^~~~~~~
main.cpp:8:14: note: candidate is: 'template static R staticWrapperHelper::wrapper(T&, ARGS ...) [with R (T::* FUNCTION)(ARGS ...) = FUNCTION; T = A; R = void; ARGS = {}]'
    8 |     static R wrapper(T& object, ARGS... args) { return object.*FUNCTION(args...); }
      |              ^~~~~~~
```

Any ideas?

答:
I found a solution I can accept by passing the member function pointer as template argument, which -- unfortunately -- requires the type to be explicitly mentioned in C++14 (a helper macro can help here). The signature of the function pointer is then broken down by a helper function in order to create the wrapper.

```<code>#include <iostream>

/* Wrapper (for non-const member functions) */

template<typename PTM, PTM ptm>
struct staticWrapper
{
    constexpr static auto make()
    {
        return breakDownAndWrap(ptm);
    }

private:
    template<typename C, typename R, typename... ARGS>
    constexpr static auto breakDownAndWrap(R (C::*)(ARGS...))
    {
        R (*wrapper)(C&, ARGS...) = &Wrapper<C, R, ARGS...>::get;
        return wrapper;
    }

    template<typename C, typename R, typename... ARGS>
    struct Wrapper
    {
        constexpr static R get(C& obj, ARGS... args)
        {
            return (obj.*ptm)(args...);
        }
    };
};

/* Optional helper macro */

#define AUTO_T(val) decltype(val), val

/* Example */

class A
{
public:
    int number;

    void member() { std::cout << number << std::endl; }
};

int main()
{
    A a {2};
    auto f = staticWrapper<decltype(&A::member), &A::member>::make();
    auto g = staticWrapper<AUTO_T(&A::member)>::make();
    f(a);
    g(a);

    return 0;
}
</code>```

Working example: http://coliru.stacked-crooked.com/a/4c5cb1d98437c789

Body:
Problem

Have a template that generates a wrapper for an arbitrary member function that allows to invoke that function on an object, e.g.:

Given bool std::string::empty(), the wrapper to be generated would be bool wrapper(const std::string& str) { return str.empty(); }.

The wrapper function shall not be a lambda (so that it can be passed as function pointer).

My approach (for non-const member functions)

/* Wrapper (for non-const member functions) */

template<typename T, typename R, typename... ARGS>
struct staticWrapperHelper
{
    using fType = R (T::*)(ARGS...);
    template<fType FUNCTION>
    static R wrapper(T& object, ARGS... args) { return object.*FUNCTION(args...); }
};

template<typename T, typename R, typename... ARGS>
auto staticWrapper(R (T::*memberFunction)(ARGS...))
{
    //auto function = [memberFunction] (T& object, ARGS... args) -> R { return (object.*memberFunction)(args...); };
    using Helper = staticWrapperHelper<T, R, ARGS...>;

    R (*wrapper)(T&, ARGS...) = &Helper::template wrapper<R (T::*)(ARGS...)>;
    return wrapper;
}

/* Example */

class A
{
public:
    void member() {}
};

int main()
{
    A a;
    auto f = staticWrapper(&A::member);
    f(a);

    return 0;
}

Issue with my approach

It does not compile. It seems like the returned wrapper is still a template: http://coliru.stacked-crooked.com/a/d4c0dd9ab631aa1f

g++ -std=c++14 -O2 -Wall -pedantic -pthread main.cpp && ./a.out
main.cpp: In instantiation of 'auto staticWrapper(R (T::*)(ARGS ...)) [with T = A; R = void; ARGS = {}]':
main.cpp:32:41:   required from here
main.cpp:17:9: error: no matches converting function 'wrapper' to type 'void (*)(class A&)'
   17 |     R (*wrapper)(T&, ARGS...) = &Helper::template wrapper;
      |         ^~~~~~~
main.cpp:8:14: note: candidate is: 'template static R staticWrapperHelper::wrapper(T&, ARGS ...) [with R (T::* FUNCTION)(ARGS ...) = FUNCTION; T = A; R = void; ARGS = {}]'
    8 |     static R wrapper(T& object, ARGS... args) { return object.*FUNCTION(args...); }
      |              ^~~~~~~

Any ideas?

Body:
I found a solution I can accept by passing the member function pointer as template argument, which -- unfortunately -- requires the type to be explicitly mentioned in C++14 (a helper macro can help here). The signature of the function pointer is then broken down by a helper function in order to create the wrapper.

#include <iostream>

/* Wrapper (for non-const member functions) */

template<typename PTM, PTM ptm>
struct staticWrapper
{
    constexpr static auto make()
    {
        return breakDownAndWrap(ptm);
    }

private:
    template<typename C, typename R, typename... ARGS>
    constexpr static auto breakDownAndWrap(R (C::*)(ARGS...))
    {
        R (*wrapper)(C&, ARGS...) = &Wrapper<C, R, ARGS...>::get;
        return wrapper;
    }

    template<typename C, typename R, typename... ARGS>
    struct Wrapper
    {
        constexpr static R get(C& obj, ARGS... args)
        {
            return (obj.*ptm)(args...);
        }
    };
};

/* Optional helper macro */

#define AUTO_T(val) decltype(val), val

/* Example */

class A
{
public:
    int number;

    void member() { std::cout << number << std::endl; }
};

int main()
{
    A a {2};
    auto f = staticWrapper<decltype(&A::member), &A::member>::make();
    auto g = staticWrapper<AUTO_T(&A::member)>::make();
    f(a);
    g(a);

    return 0;
}

Working example: http://coliru.stacked-crooked.com/a/4c5cb1d98437c789


问:
Mark a WebApi method's parameter as obsolete / deprecated for Swashbuckle / Swagger
As per my understanding of the Swagger Specification, it's possible to mark a parameter as obsolete:

Deprecated Parameters

Use deprecated: true to mark a parameter as deprecated.

  ```<code>        - in: query
          name: format
          required: true
          schema:
            type: string
            enum: [json, xml, yaml]
          deprecated: true
          description: Deprecated, use the appropriate `Accept` header instead.```
```
</blockquote>

<p>How can I have Swashbuckle generate this for a parameter?</p>

<h1>Why?</h1>

<p>I have a controller method something like the following:</p>

<pre class="lang-cs prettyprint-override"><code>[HttpGet]
public async Task<IActionResult> Execute(bool? someName)
{
}
</code>```

And I want to change the querystring parameter name while temporarily remaining backwards compatible, so
I want to do something like:

[HttpGet]
public async Task<IActionResult> Execute([Obsolete("Use someNewName instead.")] bool? someName, bool? someNewName)
{
    someNewName = someNewName ?? someName;
}
```

However, Obsolete cannot be applied to a parameter. I expected that Swashbuckle.AspNetCore.Annotations might be a place to find this kind of functionality, but it doesn't seem to have it.

答:
You don't mark a parameter as obsolete, if a parameter becomes obsolete, the whole method becomes obsolete. You'll need to declare a new method, with a new method signature, and mark the old method as obsolete. Like so

[HttpGet]
[Obsolete("Use Execute with bool? someNewName instead.")]
public async Task<IActionResult> Execute(bool? someName)
{
}

[HttpGet]
public async Task<IActionResult> Execute(bool? someNewName)
{
}
```

<p>If you only changed the name of the parameter, you can instead use the <code>Bind</code> attribute to bind a URI element to a differently named variable, like so:</p>

<pre class="lang-cs prettyprint-override"><code>[HttpGet]
public async Task<IActionResult> Execute([Bind(Prefix = "someNewName")] bool? someName)
{
}
</code>```

This would allow you to continue to use the same method, without having to forcibly change all your clients. But, if more than just the name of the parameter changed, for example the type, you'll need a new method

Body:
As per my understanding of the Swagger Specification, it's possible to mark a parameter as obsolete:

Deprecated Parameters

Use deprecated: true to mark a parameter as deprecated.

        - in: query
          name: format
          required: true
          schema:
            type: string
            enum: [json, xml, yaml]
          deprecated: true
          description: Deprecated, use the appropriate `Accept` header instead.```

How can I have Swashbuckle generate this for a parameter?

Why?

I have a controller method something like the following:

[HttpGet]
public async Task<IActionResult> Execute(bool? someName)
{
}

And I want to change the querystring parameter name while temporarily remaining backwards compatible, so
I want to do something like:

[HttpGet]
public async Task<IActionResult> Execute([Obsolete("Use someNewName instead.")] bool? someName, bool? someNewName)
{
    someNewName = someNewName ?? someName;
}

However, Obsolete cannot be applied to a parameter. I expected that Swashbuckle.AspNetCore.Annotations might be a place to find this kind of functionality, but it doesn't seem to have it.

Body:
You don't mark a parameter as obsolete, if a parameter becomes obsolete, the whole method becomes obsolete. You'll need to declare a new method, with a new method signature, and mark the old method as obsolete. Like so

[HttpGet]
[Obsolete("Use Execute with bool? someNewName instead.")]
public async Task<IActionResult> Execute(bool? someName)
{
}

[HttpGet]
public async Task<IActionResult> Execute(bool? someNewName)
{
}

If you only changed the name of the parameter, you can instead use the Bind attribute to bind a URI element to a differently named variable, like so:

[HttpGet]
public async Task<IActionResult> Execute([Bind(Prefix = "someNewName")] bool? someName)
{
}

This would allow you to continue to use the same method, without having to forcibly change all your clients. But, if more than just the name of the parameter changed, for example the type, you'll need a new method


问:
Jenkins fails to compile Maven for my Selenium Project
I am trying to schedule my project on Maven. It uses Apache POI. Project works fine on my Laptop but it fails to compile Maven on Jenkins that is on a remote machine in our office. The error I face is:

```<code>[ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.1:testCompile** (default-testCompile) on project GunAV-test-automation: Compilation failure: Compilation failure:
[ERROR] /C:/Program Files (x86)/Jenkins/workspace/Mytest/-42/src/test/java/utilities/ReadExcel.java:[11,37] **package org.apache.poi.xssf.usermodel does not exist**

[ERROR] /C:/Program Files (x86)/Jenkins/workspace/Mytest/-42/src/test/java/utilities/ReadExcel.java:[12,37] package org.apache.poi.xssf.usermodel does not exist**

[ERROR] -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoFailureException
</code>```

How could I fix this issue?

答:
To fix a compilation error

```<code>package org.apache.poi.xssf.usermodel does not exist
</code>```

you should add a poi-ooxml maven dependency:

```<code><dependency>
  <groupId>org.apache.poi</groupId>
  <artifactId>poi-ooxml</artifactId>
  <version>4.1.2</version>
</dependency>
</code>```

This dependency contains org.apache.poi.xssf.usermodel package.

Body:
I am trying to schedule my project on Maven. It uses Apache POI. Project works fine on my Laptop but it fails to compile Maven on Jenkins that is on a remote machine in our office. The error I face is:

[ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.1:testCompile** (default-testCompile) on project GunAV-test-automation: Compilation failure: Compilation failure:
[ERROR] /C:/Program Files (x86)/Jenkins/workspace/Mytest/-42/src/test/java/utilities/ReadExcel.java:[11,37] **package org.apache.poi.xssf.usermodel does not exist**

[ERROR] /C:/Program Files (x86)/Jenkins/workspace/Mytest/-42/src/test/java/utilities/ReadExcel.java:[12,37] package org.apache.poi.xssf.usermodel does not exist**

[ERROR] -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoFailureException

How could I fix this issue?

Body:
To fix a compilation error

package org.apache.poi.xssf.usermodel does not exist

you should add a poi-ooxml maven dependency:

<dependency>
  <groupId>org.apache.poi</groupId>
  <artifactId>poi-ooxml</artifactId>
  <version>4.1.2</version>
</dependency>

This dependency contains org.apache.poi.xssf.usermodel package.


问:
How can I recursively print a File Array?
I would like to know how to recursively print a File[]. I have made a program but it seems that the program is going out of bounds and I don't know how to fix it. Can someone please give me a few pointers or hints on how to solve this problem? Thanks.

```<code>import java.io.*;

public class RecursiveDir {

static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

public static void main(String[]args) throws IOException {
    System.out.print("Please enter a directory name: ");
    File f = new File(br.readLine());

    FileFilter filter = new FileFilter() {

        public boolean accept(File f) {
            if(f.isDirectory()) {
                return true;
            }
            return false;
        }

    };

    File[] list = f.listFiles(filter);
    System.out.println(returnDir(list,list.length));
}

public static File returnDir(File[] file,int counter) {
    File f = file[counter];
    if(counter == 0) {
        return file[0];
    }else {
        return f = returnDir(file,counter--);
    }
}
}
</code>```

EDIT: I followed the comments below and changed return f = returnDir(file,counter--); to
return f = returnDir(file,--counter); and also changed returnDir(list,list.length); to
returnDir(list,list.length-1);, my code runs fine but now nothing is printing.

答:
You are indeed going out of bounds. You need to change </p>

```<code>returnDir(list,list.length);
</code>```

<p>to </p>

```<code>returnDir(list,list.length - 1 );
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I would like to know how to recursively print a File[]. I have made a program but it seems that the program is going out of bounds and I don't know how to fix it. Can someone please give me a few pointers or hints on how to solve this problem? Thanks.

import java.io.*;

public class RecursiveDir {

static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

public static void main(String[]args) throws IOException {
    System.out.print("Please enter a directory name: ");
    File f = new File(br.readLine());

    FileFilter filter = new FileFilter() {

        public boolean accept(File f) {
            if(f.isDirectory()) {
                return true;
            }
            return false;
        }

    };

    File[] list = f.listFiles(filter);
    System.out.println(returnDir(list,list.length));
}

public static File returnDir(File[] file,int counter) {
    File f = file[counter];
    if(counter == 0) {
        return file[0];
    }else {
        return f = returnDir(file,counter--);
    }
}
}

EDIT: I followed the comments below and changed return f = returnDir(file,counter--); to
return f = returnDir(file,--counter); and also changed returnDir(list,list.length); to
returnDir(list,list.length-1);, my code runs fine but now nothing is printing.

Body:
You are indeed going out of bounds. You need to change

returnDir(list,list.length);

to

returnDir(list,list.length - 1 );


问:
Use value of an Input in a function
I'm a bit ashamed to write this topic because even if I got a HTML formation (4 years ago) I can't resolve my problem :

I can't use the value of an input type text in a function, this is my code:

import React from 'react'
//import db from '../../constants/FirebaseConfig'

class Account extends React.Component {

    state = {
        name: '',
        content: ''
    }

    _formSubmit(e) {
        e.preventDefault()
        var name = document.getElementsByName('name')
        console.log(name)

    }

    render(){
        return(

Account

                <form id="form">

                    Titre
                    <input type="text" name="name" placeholder="Ici le nom de l'Article"/>

                    Contenue
                    <input type="text" name="content" placeholder="Ici le contenue de l'article"/>

                    <input type="button" value="suivant" onClick={(e) =>this._formSubmit(e)}/>

                </form>

        )
    }
}

export default Account```

After attempting to debug a few times I think the problem is with the var name object which is a  NodeList<input> type.
My goal is to stock the 'name' and 'content' value in a firebase db.

Thank You

答:
Two things:

getElementsByName is plural -- note the 's' in 'Elements'. So it doesn't just return one element, it returns a list, even if there's just one.

Since you are using React, you don't need to pull the value of the input that way at all. Instead, on the input itself, just add a value and onChange property, and then track the value being typed in there as state.

You already have a spot for them in your state, so just go ahead and use that. You'll track it live as they type, not just at form submission.

```<code>class Account extends React.Component {

    state = {
        name: '',
        content: ''
    }

    _formSubmit(e) {
        //just process your form _submission_ here
    }

    onChangeName = (e) => {
        this.setState({
           name: e.target.value
        });
    }

    render(){
        return(
            <div className="container">
                <br></br>
                <h3 className="title">Account</h3>
                <form id="form">
                    <br></br>
                    <label>Titre</label>
                    <input type="text" name="name" placeholder="Ici le nom de l'Article" value={this.state.name} onChange={this.onChangeName} />
</code>```

Title: Use value of an Input in a function

Body:
I'm a bit ashamed to write this topic because even if I got a HTML formation (4 years ago) I can't resolve my problem :

I can't use the value of an input type text in a function, this is my code:

import React from 'react'
//import db from '../../constants/FirebaseConfig'

class Account extends React.Component {

    state = {
        name: '',
        content: ''
    }

    _formSubmit(e) {
        e.preventDefault()
        var name = document.getElementsByName('name')
        console.log(name)

    }

    render(){
        return(

Account

                <form id="form">

                    Titre
                    <input type="text" name="name" placeholder="Ici le nom de l'Article"/>

                    Contenue
                    <input type="text" name="content" placeholder="Ici le contenue de l'article"/>

                    <input type="button" value="suivant" onClick={(e) =>this._formSubmit(e)}/>

                </form>

        )
    }
}

export default Account

After attempting to debug a few times I think the problem is with the var name object which is a  NodeList<input> type.
My goal is to stock the 'name' and 'content' value in a firebase db.

Thank You

Body:
Two things:

getElementsByName is plural -- note the 's' in 'Elements'. So it doesn't just return one element, it returns a list, even if there's just one.

Since you are using React, you don't need to pull the value of the input that way at all. Instead, on the input itself, just add a value and onChange property, and then track the value being typed in there as state.

You already have a spot for them in your state, so just go ahead and use that. You'll track it live as they type, not just at form submission.

class Account extends React.Component {

    state = {
        name: '',
        content: ''
    }

    _formSubmit(e) {
        //just process your form _submission_ here
    }

    onChangeName = (e) => {
        this.setState({
           name: e.target.value
        });
    }

    render(){
        return(
            <div className="container">
                <br></br>
                <h3 className="title">Account</h3>
                <form id="form">
                    <br></br>
                    <label>Titre</label>
                    <input type="text" name="name" placeholder="Ici le nom de l'Article" value={this.state.name} onChange={this.onChangeName} />


问:
Pandas Check Multiple Conditions
I have a small excel file that contains prices for our online store & I am trying to automate this process, however, I don't fully trust the stuff to properly qualify the data, so I wanted to use Pandas to quickly check over certain fields, I have managed to achieve everything I need so far, however, I am only a beginner and I cannot think of the proper way for the next part.

So basically I need to qualify 2 columns on the same row, we have one column MARGIN, if this column is >60, then I need to check that the MARKDOWN column on the same row is populated == YES.

So my question is, how can I code it to basically say-

Below is an example of the way I have been doing my other checks, I realise it is quite beginner-ish, but I am only a beginner.

```<code>sku2 = df['SKU_2']
comp_at = df['COMPARE AT PRICE']
sales_price = df['SALES PRICE']
dni_act = df['DO NOT IMPORT - action']
dni_fur = df['DO NOT IMPORT - further details']
promo = df['PROMO']
replacement = df['REPLACEMENT']
go_live_date = df['go live date']
markdown = df['markdown']

# sales price not blank check
for item in sales_price:
    if pd.isna(item):
        with open('document.csv', 'a', newline="") as fd:
            writer = csv.writer(fd)
            writer.writerow(['It seems there is a blank sales price in here', str(file_name)])
            fd.close
            break
</code>```

Title: Pandas Check Multiple Conditions

Body:
I have a small excel file that contains prices for our online store & I am trying to automate this process, however, I don't fully trust the stuff to properly qualify the data, so I wanted to use Pandas to quickly check over certain fields, I have managed to achieve everything I need so far, however, I am only a beginner and I cannot think of the proper way for the next part.

So basically I need to qualify 2 columns on the same row, we have one column MARGIN, if this column is >60, then I need to check that the MARKDOWN column on the same row is populated == YES.

So my question is, how can I code it to basically say-

Below is an example of the way I have been doing my other checks, I realise it is quite beginner-ish, but I am only a beginner.

sku2 = df['SKU_2']
comp_at = df['COMPARE AT PRICE']
sales_price = df['SALES PRICE']
dni_act = df['DO NOT IMPORT - action']
dni_fur = df['DO NOT IMPORT - further details']
promo = df['PROMO']
replacement = df['REPLACEMENT']
go_live_date = df['go live date']
markdown = df['markdown']

# sales price not blank check
for item in sales_price:
    if pd.isna(item):
        with open('document.csv', 'a', newline="") as fd:
            writer = csv.writer(fd)
            writer.writerow(['It seems there is a blank sales price in here', str(file_name)])
            fd.close
            break

Body:
Example:

df = pd.DataFrame([
    ['a',1,2],
    ['b',3,4],
    ['a',5,6]],
    columns=['f1','f2','f3'])

# | represents or
print(df[(df['f1'] == 'a') & (df['f2'] > 1)])

Output:

  f1  f2  f3
2  a   5   6


问:
Useful data structure for the following case
Which can be the beste data structures for the following case.

1.Should have operations like search, insert and delete. Mostly searching activities will be there.Around 90% of the operations will be search and rest are delete and insert.

2 Insertion,deletion and searching will  be based on the  key of the objects. Each key will point to a object. The keys will be sorted.

Any suggestion for optimal data structure will be highly appreciated.

答: My guess is that you want to optimize time. Overall, a red-black tree will have logarithmic-time performance in all three operations. It will probably be your best overall bet on execution time; however, red-black trees are complex to implement and require a node structure meaning they will be stored using more memory than the contained data itself requires.</p>


问:
Default Durable Function errors out with Microsoft.Azure.WebJobs.Host: Cannot bind parameter 'starter'
I just started to work with Azure functions, specifically durable functions.

I'm working off of https://learn.microsoft.com/en-us/azure/azure-functions/durable/durable-functions-create-first-csharp

I added a new azure durable function and the default code showed up below.

I saw that my libraries are durable function version 2 so I had to make a couple of changes to class names for it to resolve (link is in the above link that discusses the changes):

```<code>    [FunctionName("TestFunction")]
    public static async Task<List<string>> RunOrchestrator(
        [OrchestrationTrigger] IDurableOrchestrationContext context)
    {
        var outputs = new List<string>();

        // Replace "hello" with the name of your Durable Activity Function.
        outputs.Add(await context.CallActivityAsync<string>("TestFunction_Hello", "Tokyo"));
        outputs.Add(await context.CallActivityAsync<string>("TestFunction_Hello", "Seattle"));
        outputs.Add(await context.CallActivityAsync<string>("TestFunction_Hello", "London"));

        // returns ["Hello Tokyo!", "Hello Seattle!", "Hello London!"]
        return outputs;
    }

    [FunctionName("TestFunction_Hello")]
    public static string SayHello([ActivityTrigger] string name, ILogger log)
    {
        log.LogInformation($"Saying hello to {name}.");
        return $"Hello {name}!";
    }

    [FunctionName("TestFunction_HttpStart")]
    public static async Task<HttpResponseMessage> HttpStart(
        [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post")]HttpRequestMessage req,
        [OrchestrationClient]IDurableOrchestrationClient starter, ILogger log)
    {
        // Function input comes from the request content.
        string instanceId = await starter.StartNewAsync("TestFunction", null);

        log.LogInformation($"Started orchestration with ID = '{instanceId}'.");

        return starter.CreateCheckStatusResponse(req, instanceId);
    }
</code>```

When I run this locally it starts the storage emulator but then I get a couple of errors:

Microsoft.Azure.WebJobs.Host: Error indexing method 'TestFunction_HttpStart'. Microsoft.Azure.WebJobs.Host: Cannot bind parameter 'starter' to type IDurableOrchestrationClient. Make sure the parameter Type is supported by the binding. If you're using binding extensions (e.g. Azure Storage, ServiceBus, Timers, etc.) make sure you've called the registration method for the extension(s) in your startup code (e.g. builder.AddAzureStorage(), builder.AddServiceBus(), builder.AddTimers(), etc.).

and

Microsoft.Azure.WebJobs.Host: Error indexing method 'TestFunction_HttpStart'. Microsoft.Azure.WebJobs.Host: Cannot bind parameter 'starter' to type IDurableOrchestrationClient. Make sure the parameter Type is supported by the binding. If you're using binding extensions (e.g. Azure Storage, ServiceBus, Timers, etc.) make sure you've called the registration method for the extension(s) in your startup code (e.g. builder.AddAzureStorage(), builder.AddServiceBus(), builder.AddTimers(), etc.).

Why are these errors showing up from the default test code and how do I fix it?

答: You missed changing the OrchestrationClient attribute to DurableClient as mentioned in the migration doc --- OrchestrationClientAttribute in 1.x to DurableClientAttribute in 2.x

Body:
I just started to work with Azure functions, specifically durable functions.

I'm working off of https://learn.microsoft.com/en-us/azure/azure-functions/durable/durable-functions-create-first-csharp

I added a new azure durable function and the default code showed up below.

I saw that my libraries are durable function version 2 so I had to make a couple of changes to class names for it to resolve (link is in the above link that discusses the changes):

    [FunctionName("TestFunction")]
    public static async Task<List<string>> RunOrchestrator(
        [OrchestrationTrigger] IDurableOrchestrationContext context)
    {
        var outputs = new List<string>();

        // Replace "hello" with the name of your Durable Activity Function.
        outputs.Add(await context.CallActivityAsync<string>("TestFunction_Hello", "Tokyo"));
        outputs.Add(await context.CallActivityAsync<string>("TestFunction_Hello", "Seattle"));
        outputs.Add(await context.CallActivityAsync<string>("TestFunction_Hello", "London"));

        // returns ["Hello Tokyo!", "Hello Seattle!", "Hello London!"]
        return outputs;
    }

    [FunctionName("TestFunction_Hello")]
    public static string SayHello([ActivityTrigger] string name, ILogger log)
    {
        log.LogInformation($"Saying hello to {name}.");
        return $"Hello {name}!";
    }

    [FunctionName("TestFunction_HttpStart")]
    public static async Task<HttpResponseMessage> HttpStart(
        [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post")]HttpRequestMessage req,
        [OrchestrationClient]IDurableOrchestrationClient starter, ILogger log)
    {
        // Function input comes from the request content.
        string instanceId = await starter.StartNewAsync("TestFunction", null);

        log.LogInformation($"Started orchestration with ID = '{instanceId}'.");

        return starter.CreateCheckStatusResponse(req, instanceId);
    }

When I run this locally it starts the storage emulator but then I get a couple of errors:

Microsoft.Azure.WebJobs.Host: Error indexing method 'TestFunction_HttpStart'. Microsoft.Azure.WebJobs.Host: Cannot bind parameter 'starter' to type IDurableOrchestrationClient. Make sure the parameter Type is supported by the binding. If you're using binding extensions (e.g. Azure Storage, ServiceBus, Timers, etc.) make sure you've called the registration method for the extension(s) in your startup code (e.g. builder.AddAzureStorage(), builder.AddServiceBus(), builder.AddTimers(), etc.).

and

Microsoft.Azure.WebJobs.Host: Error indexing method 'TestFunction_HttpStart'. Microsoft.Azure.WebJobs.Host: Cannot bind parameter 'starter' to type IDurableOrchestrationClient. Make sure the parameter Type is supported by the binding. If you're using binding extensions (e.g. Azure Storage, ServiceBus, Timers, etc.) make sure you've called the registration method for the extension(s) in your startup code (e.g. builder.AddAzureStorage(), builder.AddServiceBus(), builder.AddTimers(), etc.).

Why are these errors showing up from the default test code and how do I fix it?


问:
Prepend or append PI before / after the root element with lxml
With lxml, how can I prepend processing instructions before the root element or append PIs after de root element with lxml.

Currently, the following example doesn't work:

from lxml import etree

root = etree.XML("<ROOT/>")
root.addprevious(etree.ProcessingInstruction("foo"))
print(etree.tounicode(root))
```

<p>I get:</p>

<pre class="lang-xml prettyprint-override"><code><ROOT/>
</code>```

Instead of:

<?foo?><ROOT/>
```

答:
Actually, an Element is always attached to a ElementTree even if it looks "detached":

root = etree.XML("<ROOT/>")
assert root.getroottree() is not None
```

<p>When we use <code>addprevious</code>/<code>addnext</code> to insert a processing instruction before/after a root element, the PIs are not attached to a parent element (there isn't any) but they are attached to the root tree instead.</p>

<p>So, the problem lies in the usage of <code>tounicode</code> (or <code>tostring</code>). The best practice is to print the XML of the root tree, not the root element.</p>

<pre class="lang-py prettyprint-override"><code>from lxml import etree

root = etree.XML("<ROOT/>")
root.addprevious(etree.ProcessingInstruction("foo"))
root.addnext(etree.ProcessingInstruction("bar"))

print(etree.tounicode(root))
# => "<ROOT/>"

print(etree.tounicode(root.getroottree()))
# => "<?foo ?><ROOT/><?bar ?>"
</code>```

Body:
With lxml, how can I prepend processing instructions before the root element or append PIs after de root element with lxml.

Currently, the following example doesn't work:

from lxml import etree

root = etree.XML("<ROOT/>")
root.addprevious(etree.ProcessingInstruction("foo"))
print(etree.tounicode(root))

I get:

<ROOT/>

Instead of:

<?foo?><ROOT/>

Body:
Actually, an Element is always attached to a ElementTree even if it looks "detached":

root = etree.XML("<ROOT/>")
assert root.getroottree() is not None

When we use addprevious/addnext to insert a processing instruction before/after a root element, the PIs are not attached to a parent element (there isn't any) but they are attached to the root tree instead.

So, the problem lies in the usage of tounicode (or tostring). The best practice is to print the XML of the root tree, not the root element.

from lxml import etree

root = etree.XML("<ROOT/>")
root.addprevious(etree.ProcessingInstruction("foo"))
root.addnext(etree.ProcessingInstruction("bar"))

print(etree.tounicode(root))
# => "<ROOT/>"

print(etree.tounicode(root.getroottree()))
# => "<?foo ?><ROOT/><?bar ?>"


问:
Image Viewer and Include File
I am working on a project that is an imageviewer for a website. I have a question on the best methodology for making what I want to work.

What I am Doing

Basically, I am using an image viewer called "Prometeus" (Written by Gerard Ferrandez - http://www.dhteumeuleu.com - Feb 2005) and in the one block of code for the html page you must put the format:

Tag for image

The file must be .jpg, a certain size.

This all works fine, I have a separate page that lets you upload the picture on the server in the /images folder, and everytime a client wants to put a new picture up on the image wall, I have to add another line of code in the html file of the image viewer to show this.

Basically, my image viewer page will look like this in the part that displays the pictures:

image1description

image2description

image3description

image4description

...and so on.

The Problem

I want to make this easy to use for anyone who wants to upload the pictures. Having to individually type up each line of code in the html file is risky: Having anyone have to log into the server and edit an HTML file has a big possibility for breaking the code and messing up the page. I want this to be automatic: A user should be able to go to the upload page, upload the picture, and the image viewer should have that line of code accessible so basically it is an easy to use front-end. Also it is time consuming, there has to be a way for this to happen automatically.

Possible Solution

I'm thinking that the best way to do this is by, when the client uses the uploader to upload the file to the server, the uploader will also add a line into another file, so that the file is just a list of images with the format:

image1description

image2description

image3description

image4description

I want to do this and have the image viewer include the code in the file that is the list of images, but I dont know how to do it. What is the best way for this to work?

I am somewhat new to HTML and web design, so if there is any easier ways to do this, please let me know.

答:
If I get it right you want to upload images and add them into html dynamically without editing the html? If that is the case then you have to add an upload section for your images.
You can find an upload example here : http://www.reconn.us/content/view/30/51/

You have to create a database where you will write the image name and then write a script that will read the database and loop through the result and printing the img tag on the html file that will be generated. I hope I helped.

Nick.

Title: Image Viewer and Include File


问:
How to calculate the distance between two points, for many consequent points, within groups in python
I have the following df

```<code>       id             xx            yy  time
0       1  553343.041098  4.178420e+06     1
1       1  553343.069815  4.178415e+06     2
2       1  553343.069815  4.178415e+06     3
3       2  553343.950755  4.178415e+06     1
4       2  553341.343829  4.178410e+06     6
</code>```

The xx and yy is the position of each id at a certain point in time.

I would like to create an extra column in this df, which will be the difference in distance from one point of time to another (going from the smallest value of time to the next bigger, to the next bigger one etc), within the id group.

Is there a Pythonic way of doing so ?

答:
Try This:

```<code>import pandas as pd
import math

def calc_distance(values):
    values.sort_values('id', inplace = True)
    values['distance_diff'] = 0
    values.reset_index(drop=True, inplace=True)
    for i in range(values.shape[0]-1):
        p1 = list(values.loc[i, ['xx', 'yy']])
        p2 = list(values.loc[i+1, ['xx', 'yy']])
        values.loc[i,'distance_diff'] = math.sqrt( ((p1[0]-p2[0])**2)+((p1[1]-p2[1])**2))
    return values

lt = []
lt.append(df.groupby(['id']).apply(calc_distance))
print(pd.concat(lt, ignore_index=True))
</code>```

Output:

```<code>   id             xx         yy  time  distance_diff
0   1  553343.041098  4178420.0     1       5.000082
1   1  553343.069815  4178415.0     2       0.000000
2   1  553343.069815  4178415.0     3       0.000000
3   2  553343.950755  4178415.0     1       5.638800
4   2  553341.343829  4178410.0     6       0.000000
</code>```

Body:
I have the following df

       id             xx            yy  time
0       1  553343.041098  4.178420e+06     1
1       1  553343.069815  4.178415e+06     2
2       1  553343.069815  4.178415e+06     3
3       2  553343.950755  4.178415e+06     1
4       2  553341.343829  4.178410e+06     6

The xx and yy is the position of each id at a certain point in time.

I would like to create an extra column in this df, which will be the difference in distance from one point of time to another (going from the smallest value of time to the next bigger, to the next bigger one etc), within the id group.

Is there a Pythonic way of doing so ?

Body:
Try This:

import pandas as pd
import math

def calc_distance(values):
    values.sort_values('id', inplace = True)
    values['distance_diff'] = 0
    values.reset_index(drop=True, inplace=True)
    for i in range(values.shape[0]-1):
        p1 = list(values.loc[i, ['xx', 'yy']])
        p2 = list(values.loc[i+1, ['xx', 'yy']])
        values.loc[i,'distance_diff'] = math.sqrt( ((p1[0]-p2[0])**2)+((p1[1]-p2[1])**2))
    return values

lt = []
lt.append(df.groupby(['id']).apply(calc_distance))
print(pd.concat(lt, ignore_index=True))

Output:

   id             xx         yy  time  distance_diff
0   1  553343.041098  4178420.0     1       5.000082
1   1  553343.069815  4178415.0     2       0.000000
2   1  553343.069815  4178415.0     3       0.000000
3   2  553343.950755  4178415.0     1       5.638800
4   2  553341.343829  4178410.0     6       0.000000


问:
Changing NA value if matching a defined length
I have this kind of data :

```<code>daynight
[1] NA NA NA NA  2  1 NA NA
</code>```

I want R to detect if there is a series of at least x NA and replace these by another value.
For example if x=3 and the replacement value is 3 I want R to give me in output :

```<code>daynight
[1] 3 3 3 3 2 1 NA NA
</code>```

Would you have any ideas?

答:
We can use rle

```<code>daynight <- c(NA, NA, NA, NA  ,2  ,1, NA, NA)
x <- 3
r <- 3
daynight[with(rle(is.na(daynight)), rep(lengths >= x & values, lengths))] <- r
daynight
#[1]  3  3  3  3  2  1 NA NA
</code>```

Taking another example :

```<code>daynight <- c(NA, NA, NA, 3,2,1, NA, NA, 1, NA, NA, NA, 1, NA, NA)
daynight[with(rle(is.na(daynight)), rep(lengths >= x & values, lengths))] <- r
#[1]  3  3  3  3  2  1 NA NA  1  3  3  3  1 NA NA
</code>```

Body:
I have this kind of data :

daynight
[1] NA NA NA NA  2  1 NA NA

I want R to detect if there is a series of at least x NA and replace these by another value.
For example if x=3 and the replacement value is 3 I want R to give me in output :

daynight
[1] 3 3 3 3 2 1 NA NA

Would you have any ideas?

Body:
We can use rle

daynight <- c(NA, NA, NA, NA  ,2  ,1, NA, NA)
x <- 3
r <- 3
daynight[with(rle(is.na(daynight)), rep(lengths >= x & values, lengths))] <- r
daynight
#[1]  3  3  3  3  2  1 NA NA

Taking another example :

daynight <- c(NA, NA, NA, 3,2,1, NA, NA, 1, NA, NA, NA, 1, NA, NA)
daynight[with(rle(is.na(daynight)), rep(lengths >= x & values, lengths))] <- r
#[1]  3  3  3  3  2  1 NA NA  1  3  3  3  1 NA NA


问:
SwiftUI - deletion of elements in Binding Array causes errors
I'm developing an App (using Xcode 11.3.1, target device: iPad) for our company's engineers to report on work they do. Part of the app needs to be an editable list of parts they've used.

I've replicated the mechanisms I'm trying to implement (Observed Object/@Binding etc) in a simple 'Person List' test project (full project code below).

I'm still trying to learn SWiftUI so I've probably done something stupid in my code.

The objective here is to create a dynamic list with editable fields. When the code is previewed it seems to work perfectly, however, things start to go wrong after elements are deleted. (Deleting the last element causes "Fatal error: Index out of range".

If you add new elements after deleting some, the new elements have blank textFields and are un-editable.

I would very much appreciate any help anyone can offer.

import SwiftUI

struct EditView: View {
    @Binding var person:Person
    var body: some View {
        HStack{
            Group{
                TextField("name1", text: $person.name1)
                TextField("name2", text: $person.name2)
            }.frame(width:150)
            .font(.headline)
                .padding(.all, 3)
                .overlay(RoundedRectangle(cornerRadius: 4).stroke(Color.blue, lineWidth: 1))
        }
    }
}
struct Person:Identifiable, Equatable{
    var id:UUID
    var name1:String
    var name2:String
}
class PersonList: ObservableObject {
    @Published var individuals = [Person]()// Array of Person structs
}
struct ContentView: View {
    @ObservedObject var people = PersonList()// people.individuals = [Person] array
    @State private var edName1:String = "" //temporary storage for adding new member
    @State private var edName2:String = "" //temporary storage for adding new member
    var elementCount:Int{
        let c = people.individuals.count
        return c
    }
    // arrays for testing - adds random names from these (if input field '1st name' is empty)...
    var firstNames = ["Nick","Hermes","John","Hattie","Nicola","Alan", "Dwight", "Richard"]
    var surnames = ["Fury","Smith","Jones","Hargreaves","Bennylinch", "Davidson","Lucas","Partridge"]
    var body: some View {
        NavigationView{
            VStack{
                HStack{
                    Text("Add person:")
                        .padding(.all, 5)
                        .frame(alignment: .leading)
                    TextField("1st name", text: $edName1)
                        .frame(width:150)
                        .padding(.all, 5)
                        .overlay(RoundedRectangle(cornerRadius: 8).stroke(Color.blue, lineWidth: 2))
                    TextField("2nd name", text: $edName2)
                        .frame(width:150)
                        .padding(.all, 5)
                        .overlay(RoundedRectangle(cornerRadius: 8)
                            .stroke(Color.blue, lineWidth: 2))
                    //  Button...
                    Image(systemName: "plus.square")
                        .font(.title)
                        .foregroundColor(.orange)
                        .onTapGesture {
                            if self.edName1 == ""{
                                self.edName1 = self.firstNames.randomElement() ?? "⁉"
                                self.edName2 = self.surnames.randomElement() ?? "⁉"
                            }
                            self.people.individuals.append(Person(id: UUID(), name1: self.edName1, name2: self.edName2))
                            self.edName1 = ""
                            self.edName2 = ""
                            print("Element count: \(self.elementCount)")
                    }
                    Spacer()
                    //  Button...sort
                    Image(systemName: "arrow.up.arrow.down.square")
                        .font(.title)
                        .padding(.all,4)
                        .foregroundColor(.blue)
                        .onTapGesture {
                            self.people.individuals.sort{ // sort list alphabetically by name2
                                $0.name2 < $1.name2
                            }
                    }
                    //  Button...reverse order
                    Image(systemName: "arrow.uturn.up.square")
                        .font(.title)
                        .padding(.all,8)
                        .foregroundColor(.blue)
                        .onTapGesture {
                            self.people.individuals.reverse()
                    }
                }.padding(.all,8)
                    .overlay(RoundedRectangle(cornerRadius: 12)
                        .stroke(Color.orange, lineWidth: 2))
                List{
                    ForEach(people.individuals){individual in
                        HStack{
                          EditView(person: self.$people.individuals[self.people.individuals.firstIndex(of:individual)!])

                            Text("\(individual.name1) \(individual.name2)")
                                .frame(width: 200, alignment: .leading)
                                .padding(.all, 3)
                            Text("\(self.people.individuals.firstIndex(of: individual)!)")
                            Spacer()

                            Image(systemName: "xmark.circle.fill").font(.title).foregroundColor(.red)//❌
                                .onTapGesture {
                                    let deletedElement = self.people.individuals.remove(at: self.people.individuals.firstIndex(of: individual)!)
                                    print("Deleted element:\(deletedElement) Element count: \(self.elementCount)")
                            }
                        }
                    }//.onDelete(perform: deleteRow)// an alternative to the red xmark circle
                }
            }.navigationBarTitle("People List (\(elementCount))")
        }.navigationViewStyle(StackNavigationViewStyle())
    }
    func deleteRow(at offsets: IndexSet){
        self.people.individuals.remove(atOffsets: offsets)
    }

}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
          .environment(\.colorScheme, .dark)
    }
}
```

答:
Thanks to KRJW and Natalia Panferova for help with different aspects of this code. There are no 'index out of range' errors now and also it is possible to delete rows without causing problems with adding items.
I'm sharing this answer because I believe it's a very useful mechanism to create editable lists.

```<code>import SwiftUI

class Person: ObservableObject, Identifiable, Equatable {
    static func == (lhs: Person, rhs: Person) -> Bool {
        return lhs.id == rhs.id
    }

    @Published var id:UUID
    @Published var name1:String
    @Published var name2:String

    init(id: UUID, name1: String, name2: String, isEditable: Bool){
        self.id = id
        self.name1 = name1
        self.name2 = name2
    }
}

struct EditView: View {
    @ObservedObject var person: Person
    var body: some View {
        VStack{
            HStack{
                Group{
                    TextField("name1", text: $person.name1)
                    TextField("name2", text: $person.name2)
                }//.frame(width:200)
                    .font(.headline)
                    .padding(.all, 3)
                    .overlay(RoundedRectangle(cornerRadius: 4).stroke(Color.blue, lineWidth: 1))
            }.id(person.id)
        }
    }
}

struct ContentView: View {
    @State var people = [Person]()//try! ObservableArray<Person>(array: []).observeChildrenChanges(Person.self)// people.individuals = [Person] array

    @State private var edName1:String = "" //temporary storage for adding new member
    @State private var edName2:String = "" //temporary storage for adding new member

    // arrays for testing - adds random names from these (if input field '1st name' is empty)...
    var firstNames = ["Nick","Hermes","John","Hattie","Nicola","Alan", "Dwight", "Richard","Turanga", "Don","Joey"]
    var surnames = ["Farnsworth","Fry","Wong","Zoidberg","Conrad","McDougal","Power","Clampazzo","Brannigan","Kroker","Leela"]

    var body: some View {
        NavigationView{
            VStack{
                HStack{
                    Text("Add person:")
                        .padding(.all, 5)
                        .frame(alignment: .leading)
                    TextField("1st name", text: $edName1)
                        //.frame(width:150)
                        .padding(.all, 5)
                        .overlay(RoundedRectangle(cornerRadius: 8).stroke(Color.blue, lineWidth: 2))
                    TextField("2nd name", text: $edName2)
                        //.frame(width:150)
                        .padding(.all, 5)
                        .overlay(RoundedRectangle(cornerRadius: 8)
                            .stroke(Color.blue, lineWidth: 2))
                    //  Button...
                    Image(systemName: "plus.circle")
                        .font(.largeTitle)
                        .foregroundColor(.orange)
                        .onTapGesture {
                            if self.edName1 == ""{
                                self.edName1 = self.firstNames.randomElement() ?? "⁉"
                                self.edName2 = self.surnames.randomElement() ?? "⁉"
                            }
                            self.people.append(Person(id: UUID(), name1: self.edName1, name2: self.edName2, isEditable: false))
                            self.edName1 = ""
                            self.edName2 = ""
                            print("Element count: \(self.people.count)")
                    }
                    Spacer()
                    //  Button...sort
                    Image(systemName: "arrow.up.arrow.down.square")
                        .font(.title)
                        .padding(.all,4)
                        .foregroundColor(.blue)
                        .onTapGesture {
                            self.people.sort{ // sort list alphabetically by name2
                                $0.name2 < $1.name2
                            }
                    }
                    //  Button...reverse order
                    Image(systemName: "arrow.uturn.up.square")
                        .font(.title)
                        .padding(.all,8)
                        .foregroundColor(.blue)
                        .onTapGesture {
                            self.people.reverse()
                    }
                }.padding(.all,8)
                    .overlay(RoundedRectangle(cornerRadius: 12)
                        .stroke(Color.orange, lineWidth: 2))

                List {
                    ForEach(self.people) { person in
                        EditView(person: person)
                    }.onDelete(perform: deleteRow)
                }

            }.navigationBarTitle("People List (\(self.people.count))")
        }.navigationViewStyle(StackNavigationViewStyle())
    }

    func deleteRow(at offsets: IndexSet){
        self.people.remove(atOffsets: offsets)
        print(self.people.count)
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
           // .environment(\.colorScheme, .dark)
    }
}
</code>```

The code is all bundled together for convenience. Feel free to copy and paste and play around.

Body:
Thanks to KRJW and Natalia Panferova for help with different aspects of this code. There are no 'index out of range' errors now and also it is possible to delete rows without causing problems with adding items.
I'm sharing this answer because I believe it's a very useful mechanism to create editable lists.

import SwiftUI

class Person: ObservableObject, Identifiable, Equatable {
    static func == (lhs: Person, rhs: Person) -> Bool {
        return lhs.id == rhs.id
    }

    @Published var id:UUID
    @Published var name1:String
    @Published var name2:String

    init(id: UUID, name1: String, name2: String, isEditable: Bool){
        self.id = id
        self.name1 = name1
        self.name2 = name2
    }
}

struct EditView: View {
    @ObservedObject var person: Person
    var body: some View {
        VStack{
            HStack{
                Group{
                    TextField("name1", text: $person.name1)
                    TextField("name2", text: $person.name2)
                }//.frame(width:200)
                    .font(.headline)
                    .padding(.all, 3)
                    .overlay(RoundedRectangle(cornerRadius: 4).stroke(Color.blue, lineWidth: 1))
            }.id(person.id)
        }
    }
}

struct ContentView: View {
    @State var people = [Person]()//try! ObservableArray<Person>(array: []).observeChildrenChanges(Person.self)// people.individuals = [Person] array

    @State private var edName1:String = "" //temporary storage for adding new member
    @State private var edName2:String = "" //temporary storage for adding new member

    // arrays for testing - adds random names from these (if input field '1st name' is empty)...
    var firstNames = ["Nick","Hermes","John","Hattie","Nicola","Alan", "Dwight", "Richard","Turanga", "Don","Joey"]
    var surnames = ["Farnsworth","Fry","Wong","Zoidberg","Conrad","McDougal","Power","Clampazzo","Brannigan","Kroker","Leela"]

    var body: some View {
        NavigationView{
            VStack{
                HStack{
                    Text("Add person:")
                        .padding(.all, 5)
                        .frame(alignment: .leading)
                    TextField("1st name", text: $edName1)
                        //.frame(width:150)
                        .padding(.all, 5)
                        .overlay(RoundedRectangle(cornerRadius: 8).stroke(Color.blue, lineWidth: 2))
                    TextField("2nd name", text: $edName2)
                        //.frame(width:150)
                        .padding(.all, 5)
                        .overlay(RoundedRectangle(cornerRadius: 8)
                            .stroke(Color.blue, lineWidth: 2))
                    //  Button...
                    Image(systemName: "plus.circle")
                        .font(.largeTitle)
                        .foregroundColor(.orange)
                        .onTapGesture {
                            if self.edName1 == ""{
                                self.edName1 = self.firstNames.randomElement() ?? "⁉"
                                self.edName2 = self.surnames.randomElement() ?? "⁉"
                            }
                            self.people.append(Person(id: UUID(), name1: self.edName1, name2: self.edName2, isEditable: false))
                            self.edName1 = ""
                            self.edName2 = ""
                            print("Element count: \(self.people.count)")
                    }
                    Spacer()
                    //  Button...sort
                    Image(systemName: "arrow.up.arrow.down.square")
                        .font(.title)
                        .padding(.all,4)
                        .foregroundColor(.blue)
                        .onTapGesture {
                            self.people.sort{ // sort list alphabetically by name2
                                $0.name2 < $1.name2
                            }
                    }
                    //  Button...reverse order
                    Image(systemName: "arrow.uturn.up.square")
                        .font(.title)
                        .padding(.all,8)
                        .foregroundColor(.blue)
                        .onTapGesture {
                            self.people.reverse()
                    }
                }.padding(.all,8)
                    .overlay(RoundedRectangle(cornerRadius: 12)
                        .stroke(Color.orange, lineWidth: 2))

                List {
                    ForEach(self.people) { person in
                        EditView(person: person)
                    }.onDelete(perform: deleteRow)
                }

            }.navigationBarTitle("People List (\(self.people.count))")
        }.navigationViewStyle(StackNavigationViewStyle())
    }

    func deleteRow(at offsets: IndexSet){
        self.people.remove(atOffsets: offsets)
        print(self.people.count)
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
           // .environment(\.colorScheme, .dark)
    }
}

The code is all bundled together for convenience. Feel free to copy and paste and play around.


问:
Turn row with 2 different value into 2 column oracle
I'm having trouble tunring a row with only 2 possible value (heads or tails for example ) into 2 column. I found Pivot but it doesn't seems to fit the problem.
Here's a little shema to help you understand what i'm trying to do :

Into this :

It's probably not very complicated yet I can't find the good words to explain my problem to google so he give's me the right solution !

答:
You can use aggregation:</p>

```<code>select name, date,
       sum(case when type = 'Heads' then result else 0 end) as heads,
       sum(case when type = 'Tails' then result else 0 end) as tails
from t
group by name, date;
</code>```

Body:
You can use aggregation:

select name, date,
       sum(case when type = 'Heads' then result else 0 end) as heads,
       sum(case when type = 'Tails' then result else 0 end) as tails
from t
group by name, date;


问:
Where does ipython store the current session history?
I use vim with a couple of plugins as a python ide. Along with an open vim session, I run an ipython session in a split console. I've found their combination is a great productivity tool for programming data analysis scripts.

What I'm missing is a way to show all current session history in a side panel, so that I could easily do some copy-pasting from there to the vim session to create a script. Something similar to 'tail -f' would do, if only I knew where ipython stores the current session history.

I already know:

ipython has '%history' and 'hist' commands, BUT I'm looking for a way to display the history in a panel outside of the ipython session.

history is stored in a sqlite file under .ipython/(profile), BUT I don't know how to access that file.

I hope I've been clear about my question.
Thanks in advance for all your help.

答:
On windows, it is stored in a sqlite database, in

```<code>%Home%\.ipython\profile_default\history.sqlite
</code>```

If the %home% variable is not set, try %userprofile% instead.

As an example, if you'd like to look back at your very first ipython session, you could run

```<code>select source from history where session = 1
</code>```

Body:
On windows, it is stored in a sqlite database, in

%Home%\.ipython\profile_default\history.sqlite

If the %home% variable is not set, try %userprofile% instead.

As an example, if you'd like to look back at your very first ipython session, you could run

select source from history where session = 1