问:
UIViewController question for iPhone/iPad
I have an App with one MainWindow.xib file.  Then I have ViewControllerA.xib and ViewControllerB.xib.  My MainWindow.xib have one ViewController that points two ViewControllerA.xib.

On ViewControllerA I have a button and I would like the button, when pressed, to move ViewControllerB onto the screen.  How do I do that?

I tried this code, but I think I am missing something:

```<code>- (IBAction)btMyButton:(id)sender
{
    ViewControllerB * viewController = [[ViewControllerB alloc] initWithNibName:@"ViewControllerB" bundle:nil];
    [[UIApplication sharedApplication].keyWindow addSubview:viewController.view];
    [self.navigationController pushViewController:viewController animated:YES];
}
</code>```

My ViewControllerB does appear, but it is squashed at the top of the screen, over the previous view.  Any help is greatly appreciated.

Thank you

答:
Make sure that the view of controller B has correct hight you should subtract the navigation bar height 44 px and status bar 20 px as well. Those values are for iPhone.

```<code>  - (IBAction)btMyButton:(id)sender
    {
        //you should load from the main app bundle
        ViewControllerB * viewController = [[ViewControllerB alloc] initWithNibName:@"ViewControllerB" bundle:[NSBundle mainBundle]];
        // you don't need the following line
        //[[UIApplication sharedApplication].keyWindow addSubview:viewController.view];
        [self.navigationController pushViewController:viewController animated:YES];
        [viewController release];
    }
</code>```

Update
As the above comment says if you may don't have a navigation controller to push Controller B into. So Add a navigation controller into the main window instead of the view controller and make its root view controller you Controller A.

I hope this helps you,

Body:
I have an App with one MainWindow.xib file.  Then I have ViewControllerA.xib and ViewControllerB.xib.  My MainWindow.xib have one ViewController that points two ViewControllerA.xib.

On ViewControllerA I have a button and I would like the button, when pressed, to move ViewControllerB onto the screen.  How do I do that?

I tried this code, but I think I am missing something:

- (IBAction)btMyButton:(id)sender
{
    ViewControllerB * viewController = [[ViewControllerB alloc] initWithNibName:@"ViewControllerB" bundle:nil];
    [[UIApplication sharedApplication].keyWindow addSubview:viewController.view];
    [self.navigationController pushViewController:viewController animated:YES];
}

My ViewControllerB does appear, but it is squashed at the top of the screen, over the previous view.  Any help is greatly appreciated.

Thank you

Body:
Make sure that the view of controller B has correct hight you should subtract the navigation bar height 44 px and status bar 20 px as well. Those values are for iPhone.

  - (IBAction)btMyButton:(id)sender
    {
        //you should load from the main app bundle
        ViewControllerB * viewController = [[ViewControllerB alloc] initWithNibName:@"ViewControllerB" bundle:[NSBundle mainBundle]];
        // you don't need the following line
        //[[UIApplication sharedApplication].keyWindow addSubview:viewController.view];
        [self.navigationController pushViewController:viewController animated:YES];
        [viewController release];
    }

Update
As the above comment says if you may don't have a navigation controller to push Controller B into. So Add a navigation controller into the main window instead of the view controller and make its root view controller you Controller A.

I hope this helps you,


来源: stackexchange

问:
Saving Matplotlib Output to Blob Storage on Databricks
I'm trying to write matplotlib figures to the Azure blob storage using the method provided here:
Saving Matplotlib Output to DBFS on Databricks.

However, when I replace the path in the code with

```<code>path = 'wasbs://test@someblob.blob.core.windows.net/'
</code>```

I get this error

[Errno 2] No such file or directory: 'wasbs://test@someblob.blob.core.windows.net/'

I don't understand the problem...

答:
As per my research, you cannot save Matplotlib output to Azure Blob Storage directly.

You may follow the below steps to save Matplotlib output to Azure Blob Storage:

Step 1: You need to first save it to the Databrick File System (DBFS) and then copy it to Azure Blob storage.

Saving Matplotlib output to Databricks File System (DBFS): We are using the below command to save the output to DBFS: plt.savefig('/dbfs/myfolder/Graph1.png')

```<code>import pandas as pd
import matplotlib.pyplot as plt

df = pd.DataFrame({'fruits':['apple','banana'], 'count': [1,2]})
plt.close()
df.set_index('fruits',inplace = True)
df.plot.bar()
plt.savefig('/dbfs/myfolder/Graph1.png')
</code>```

Step 2: Copy the file from Databricks File System to Azure Blob Storage.

There are two methods to copy file from DBFS to Azure Blob Stroage.

Method 1: Access Azure Blob storage directly

Access Azure Blob Storage directly by setting "Spark.conf.set" and copy file from DBFS to Blob Storage.

```<code>spark.conf.set("fs.azure.account.key.< Blob Storage Name>.blob.core.windows.net", "<Azure Blob Storage Key>")
</code>```

Use dbutils.fs.cp to copy file from DBFS to Azure Blob Storage:

```<code>dbutils.fs.cp('dbfs:/myfolder/Graph1.png', 'wasbs://<Container>@<Storage Name>.blob.core.windows.net/Azure')
</code>```

Method 2: Mount Azure Blob storage containers to DBFS

You can mount a Blob storage container or a folder inside a container to Databricks File System (DBFS). The mount is a pointer to a Blob storage container, so the data is never synced locally.

```<code>dbutils.fs.mount(
  source = "wasbs://sampledata@chepra.blob.core.windows.net/Azure",
  mount_point = "/mnt/chepra",
  extra_configs = {"fs.azure.sas.sampledata.chepra.blob.core.windows.net":dbutils.secrets.get(scope = "azurestorage", key = "azurestoragekey")})
</code>```

Use dbutils.fs.cp copy the file to Azure Blob Storage Container:

dbutils.fs.cp('dbfs:/myfolder/Graph1.png', '/dbfs/mnt/chepra')

By following Method1 or Method2 you can successfully save the output to Azure Blob Storage.

For more details, refer "Databricks - Azure Blob Storage".

Hope this helps. Do let us know if you any further queries.

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to write matplotlib figures to the Azure blob storage using the method provided here:
Saving Matplotlib Output to DBFS on Databricks.

However, when I replace the path in the code with

path = 'wasbs://test@someblob.blob.core.windows.net/'

I get this error

[Errno 2] No such file or directory: 'wasbs://test@someblob.blob.core.windows.net/'

I don't understand the problem...

Body:
As per my research, you cannot save Matplotlib output to Azure Blob Storage directly.

You may follow the below steps to save Matplotlib output to Azure Blob Storage:

Step 1: You need to first save it to the Databrick File System (DBFS) and then copy it to Azure Blob storage.

Saving Matplotlib output to Databricks File System (DBFS): We are using the below command to save the output to DBFS: plt.savefig('/dbfs/myfolder/Graph1.png')

import pandas as pd
import matplotlib.pyplot as plt

df = pd.DataFrame({'fruits':['apple','banana'], 'count': [1,2]})
plt.close()
df.set_index('fruits',inplace = True)
df.plot.bar()
plt.savefig('/dbfs/myfolder/Graph1.png')

Step 2: Copy the file from Databricks File System to Azure Blob Storage.

There are two methods to copy file from DBFS to Azure Blob Stroage.

Method 1: Access Azure Blob storage directly

Access Azure Blob Storage directly by setting "Spark.conf.set" and copy file from DBFS to Blob Storage.

spark.conf.set("fs.azure.account.key.< Blob Storage Name>.blob.core.windows.net", "<Azure Blob Storage Key>")

Use dbutils.fs.cp to copy file from DBFS to Azure Blob Storage:

dbutils.fs.cp('dbfs:/myfolder/Graph1.png', 'wasbs://<Container>@<Storage Name>.blob.core.windows.net/Azure')

Method 2: Mount Azure Blob storage containers to DBFS

You can mount a Blob storage container or a folder inside a container to Databricks File System (DBFS). The mount is a pointer to a Blob storage container, so the data is never synced locally.

dbutils.fs.mount(
  source = "wasbs://sampledata@chepra.blob.core.windows.net/Azure",
  mount_point = "/mnt/chepra",
  extra_configs = {"fs.azure.sas.sampledata.chepra.blob.core.windows.net":dbutils.secrets.get(scope = "azurestorage", key = "azurestoragekey")})

Use dbutils.fs.cp copy the file to Azure Blob Storage Container:

dbutils.fs.cp('dbfs:/myfolder/Graph1.png', '/dbfs/mnt/chepra')

By following Method1 or Method2 you can successfully save the output to Azure Blob Storage.

For more details, refer "Databricks - Azure Blob Storage".

Hope this helps. Do let us know if you any further queries.


问:
How to group with sequence conditions in MySQL or Google Data Studio?
I have an attendance database where Employee records are stored as below

MySQL version 5.7.26-log (There are no holes in dates, all dates exist but for convenience, I have removed the bulk date data from the insert row statement)

```<code>CREATE TABLE `stackoverflow` ( `id` int(9) NOT NULL DEFAULT '0',
                               `Date` date NOT NULL,
                               `EmpID` varchar(100) NOT NULL,
                               `name` varchar(100) NOT NULL,
                               `TeamName` varchar(100) NOT NULL,
                               `Status` varchar(100) NOT NULL
                             ) ENGINE=InnoDB DEFAULT CHARSET=latin1;

-- -- Dumping data for table `stackoverflow` --
INSERT INTO `stackoverflow` (`id`, `Date`, `EmpID`, `name`, `TeamName`, `Status`)
VALUES
(5, '2019-03-01', '303016', 'Yatendra Ranawat', 'Computer Vision', 'P'),
(23, '2019-03-01', '303128', 'Nikhat Khan', 'Media - 3D Automation', 'P'),
(193606, '2019-09-02', '303016', 'Yatendra Ranawat', 'Computer Vision', 'P'),
(194631, '2019-09-03', '303016', 'Yatendra Ranawat', 'Noon', '-'),
(222309, '2019-09-30', '303016', 'Yatendra Ranawat', 'Noon', '-'),
(223336, '2019-10-01', '303016', 'Yatendra Ranawat', 'Noon-Indore', 'P'),
(282742, '2019-11-28', '303016', 'Yatendra Ranawat', 'Noon-Indore', '-'),
(283765, '2019-11-29', '303016', 'Yatendra Ranawat', 'Home Depot - Indore', 'P'),
(303251, '2019-12-18', '303128', 'Nikhat Khan', 'Media - 3D Automation', '-'),
(304275, '2019-12-19', '303128', 'Nikhat Khan', 'US Taxonomy - Indore', 'P'),
(309393, '2019-12-24', '303128', 'Nikhat Khan', 'US Taxonomy - Indore', 'P'),
(310416, '2019-12-25', '303128', 'Nikhat Khan', 'Media - 3D Automation', 'PH'),
(354076, '2020-02-06', '303016', 'Yatendra Ranawat', 'Home Depot - Indore', '-'),
(354088, '2020-02-06', '303128', 'Nikhat Khan', 'Media - 3D Automation', 'P');
</code>```

I'm using Google Data Studio to create a report for Employee Duration in a team like below

It works perfectly when the employee moves from one team to another and does not return to the teams he previously worked on. But when an employee returns to the team he previously worked on it masses up max and min logic

What I need to do in MySQL / Google Data Studio to get the result like below with data table like above?

Let me know if you require any details from my side. Any advise or guidance would be greatly appreciated.

答:
Test also the next variant, it is faster:

```<code>SELECT EmpID, name, TeamName, startdate, MAX(enddate) enddate
FROM (
SELECT name,
       CASE WHEN EmpId = @id AND TeamName = @team
            THEN @startdate
            ELSE @startdate := `Date`
            END startdate,
       `Date` enddate,
       @id := EmpID EmpID,
       @team := TeamName TeamName
FROM stackoverflow, (SELECT @id := '', @team := '', @startdate := '') variables
ORDER BY EmpID, `Date`
) t
GROUP BY 1,2,3,4
ORDER BY 1,2,4,5;
</code>```

fiddle

On my system with hot cache it takes 0.03 sec whereas the queries from previous answer - 25.39 sec and 1 min 54.79 sec respectively. On your system with 220k records the difference must be even more impressive.

Body:
I have an attendance database where Employee records are stored as below

MySQL version 5.7.26-log (There are no holes in dates, all dates exist but for convenience, I have removed the bulk date data from the insert row statement)

CREATE TABLE `stackoverflow` ( `id` int(9) NOT NULL DEFAULT '0',
                               `Date` date NOT NULL,
                               `EmpID` varchar(100) NOT NULL,
                               `name` varchar(100) NOT NULL,
                               `TeamName` varchar(100) NOT NULL,
                               `Status` varchar(100) NOT NULL
                             ) ENGINE=InnoDB DEFAULT CHARSET=latin1;

-- -- Dumping data for table `stackoverflow` --
INSERT INTO `stackoverflow` (`id`, `Date`, `EmpID`, `name`, `TeamName`, `Status`)
VALUES
(5, '2019-03-01', '303016', 'Yatendra Ranawat', 'Computer Vision', 'P'),
(23, '2019-03-01', '303128', 'Nikhat Khan', 'Media - 3D Automation', 'P'),
(193606, '2019-09-02', '303016', 'Yatendra Ranawat', 'Computer Vision', 'P'),
(194631, '2019-09-03', '303016', 'Yatendra Ranawat', 'Noon', '-'),
(222309, '2019-09-30', '303016', 'Yatendra Ranawat', 'Noon', '-'),
(223336, '2019-10-01', '303016', 'Yatendra Ranawat', 'Noon-Indore', 'P'),
(282742, '2019-11-28', '303016', 'Yatendra Ranawat', 'Noon-Indore', '-'),
(283765, '2019-11-29', '303016', 'Yatendra Ranawat', 'Home Depot - Indore', 'P'),
(303251, '2019-12-18', '303128', 'Nikhat Khan', 'Media - 3D Automation', '-'),
(304275, '2019-12-19', '303128', 'Nikhat Khan', 'US Taxonomy - Indore', 'P'),
(309393, '2019-12-24', '303128', 'Nikhat Khan', 'US Taxonomy - Indore', 'P'),
(310416, '2019-12-25', '303128', 'Nikhat Khan', 'Media - 3D Automation', 'PH'),
(354076, '2020-02-06', '303016', 'Yatendra Ranawat', 'Home Depot - Indore', '-'),
(354088, '2020-02-06', '303128', 'Nikhat Khan', 'Media - 3D Automation', 'P');

I'm using Google Data Studio to create a report for Employee Duration in a team like below

It works perfectly when the employee moves from one team to another and does not return to the teams he previously worked on. But when an employee returns to the team he previously worked on it masses up max and min logic

What I need to do in MySQL / Google Data Studio to get the result like below with data table like above?

Let me know if you require any details from my side. Any advise or guidance would be greatly appreciated.

Body:
Test also the next variant, it is faster:

SELECT EmpID, name, TeamName, startdate, MAX(enddate) enddate
FROM (
SELECT name,
       CASE WHEN EmpId = @id AND TeamName = @team
            THEN @startdate
            ELSE @startdate := `Date`
            END startdate,
       `Date` enddate,
       @id := EmpID EmpID,
       @team := TeamName TeamName
FROM stackoverflow, (SELECT @id := '', @team := '', @startdate := '') variables
ORDER BY EmpID, `Date`
) t
GROUP BY 1,2,3,4
ORDER BY 1,2,4,5;

fiddle

On my system with hot cache it takes 0.03 sec whereas the queries from previous answer - 25.39 sec and 1 min 54.79 sec respectively. On your system with 220k records the difference must be even more impressive.


问:
Why is CSS style specfiied by the "initial" keyword different from the default style?
I am reading MDN tutorials of CSS inheritance. It says set initial to property reverts the style to the browser's style. I think the browser's style it what it displays with no CSS at all? But it is different. So zero-CSS style is not controlled by the browser?

https://developer.mozilla.org/en-US/docs/Learn/CSS/Building_blocks/Cascade_and_inheritance

答:
The initial value reset the style to its very initial state. the blue color of the link is not it's original style, but this style given it from the browser user agent. but the initial reset it to the original color, which it black;

<img src="https://i.stack.imgur.com/TVkZG.png" alt="the styles given to a from the browser user-agent">

In the image above: The styles given to a from the browser user-agent

Body:
The initial value reset the style to its very initial state. the blue color of the link is not it's original style, but this style given it from the browser user agent. but the initial reset it to the original color, which it black;

In the image above: The styles given to a from the browser user-agent


问:
C# JSON URL get data
Im new to System.Net with C#
I want a way to get info from this website api: https://fn-api.glitch.me/api/aes
from its json to a C# string

I have this so far

I don't know how to get each item and where to put the url (im really new to this).

I want the url in a string:

```<code>public class Data
{
    public string build { get; set; }
    public string netCL { get; set; }
    public string manifestID { get; set; }
    public string aes { get; set; }
}

public class RootObject
{
    public Data data { get; set; }
}
</code>```

答:
Okay, this is how you get about it. I am showing you an example using HttpClient to first read the content from the API and then de-serialize it using Newtonsoft package.

HttpClient class:

```<code>public class HttpClientFactory
{
  private string webServiceUrl = "https://fn-api.glitch.me/";

  public HttpClient CreateClient()
  {
    var client = new HttpClient();
    SetupClientDefaults(client);
    return client;
  }

  protected virtual void SetupClientDefaults(HttpClient client)
  {
    //This is global for all REST web service calls
    client.Timeout = TimeSpan.FromSeconds(60);
    client.BaseAddress = new Uri(webServiceUrl);
  }
}
</code>```

Your Model class:

```<code>public class Data
{
  public string build { get; set; }
  public string netCL { get; set; }
  public string manifestID { get; set; }
  public string aes { get; set; }
}

public class RootObject
{
  public Data data { get; set; }
}
</code>```

Now, you can call this class and create an instance of the HttpClient like this:

```<code>public RootObject InvokeAPI()
{
  RootObject apiresponse = new RootObject();
  string result = string.Empty;
  HttpClientFactory clientFactory = new HttpClientFactory();
  var client = clientFactory.CreateClient();
  HttpResponseMessage response = client.GetAsync("api/aes").Result;
  if (response.IsSuccessStatusCode)
  {
    result = response.Content.ReadAsStringAsync().Result;
    apiresponse = JsonConvert.DeserializeObject<RootObject>(result);
  }
 return apiresponse;
}
</code>```

Hope this helps you out.

EDIT:

As per your code, you need to call the API on your Button click:

```<code>    private void metroButton2_Click_1(object sender, EventArgs e)
    {
        //You need to invoke the API method !!!!
        var apiresponse=InvokeAPI();
        metroTextBox1.Text = apiresponse.data.aes;
    }
</code>```

Be sure to put try-catch blocks on your code for error handling.

Title: C# JSON URL get data

Body:
Im new to System.Net with C#
I want a way to get info from this website api: https://fn-api.glitch.me/api/aes
from its json to a C# string

I have this so far

I don't know how to get each item and where to put the url (im really new to this).

I want the url in a string:

public class Data
{
    public string build { get; set; }
    public string netCL { get; set; }
    public string manifestID { get; set; }
    public string aes { get; set; }
}

public class RootObject
{
    public Data data { get; set; }
}

Body:
Okay, this is how you get about it. I am showing you an example using HttpClient to first read the content from the API and then de-serialize it using Newtonsoft package.

HttpClient class:

public class HttpClientFactory
{
  private string webServiceUrl = "https://fn-api.glitch.me/";

  public HttpClient CreateClient()
  {
    var client = new HttpClient();
    SetupClientDefaults(client);
    return client;
  }

  protected virtual void SetupClientDefaults(HttpClient client)
  {
    //This is global for all REST web service calls
    client.Timeout = TimeSpan.FromSeconds(60);
    client.BaseAddress = new Uri(webServiceUrl);
  }
}

Your Model class:

public class Data
{
  public string build { get; set; }
  public string netCL { get; set; }
  public string manifestID { get; set; }
  public string aes { get; set; }
}

public class RootObject
{
  public Data data { get; set; }
}

Now, you can call this class and create an instance of the HttpClient like this:

public RootObject InvokeAPI()
{
  RootObject apiresponse = new RootObject();
  string result = string.Empty;
  HttpClientFactory clientFactory = new HttpClientFactory();
  var client = clientFactory.CreateClient();
  HttpResponseMessage response = client.GetAsync("api/aes").Result;
  if (response.IsSuccessStatusCode)
  {
    result = response.Content.ReadAsStringAsync().Result;
    apiresponse = JsonConvert.DeserializeObject<RootObject>(result);
  }
 return apiresponse;
}

Hope this helps you out.

EDIT:

As per your code, you need to call the API on your Button click:

    private void metroButton2_Click_1(object sender, EventArgs e)
    {
        //You need to invoke the API method !!!!
        var apiresponse=InvokeAPI();
        metroTextBox1.Text = apiresponse.data.aes;
    }

Be sure to put try-catch blocks on your code for error handling.


问:
Disable button when another button is been clicked with jquery
I have a form am working on for a project which allows users to upload images, videos and YouTube videos and I will like users not to upload photos, videos and YouTube videos at the same time but am finding it difficult on how to disable the image button when video or YouTube button is been clicked, disable video button when image or YouTube button is been clicked and disable YouTube button when image or video button is been clicked. Below is my form and Jquery code I have written so far

HTML

```<code><form method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"])?>" name="post-box" enctype="multipart/form-data" accept-charset="utf-8">
                    <div class="post_box_cont">
                        <textarea class="form-control" name="post_box" placeholder="Post something..." onkeyup="count_post_box_char(this, 500)"></textarea>

                        <div class="mt-1">
                            <button class="post_box_but">
                                <span class="icon icon-location"></span>
                            </button>

                            <button class="post_box_but" data-placement="bottom" data-toggle="tooltip" title="Mention people by typing @ before their username e.g. @aaron">
                                <span class="icon icon-at"></span>
                            </button>

                            <button class="post_box_but" id="image">
                                <span class="icon icon-image"></span>
                            </button>

                            <button class="post_box_but" id="video">
                                <span class="icon icon-video"></span>
                            </button>

                            <button class="post_box_but" id="youtube">
                                <span class="icon icon-youtube"></span>
                            </button>

                            <button class="post_box_upload_but">
                                <b>Post</b>
                            </button>
                        </div>
                    </div>
                </form>
</code>```

JQUERY

```<code>$(document).ready(function(){
    // var
    var img = $("#image");
    var video = $("#video");
    var youtube = $("#youtube");

    img.click(function(){
        $("#video").attr("disabled='disabled'");
        $("#youtube").attr("disabled='disabled'");
    });

  video.click(function(){
        img.attr("disabled='disabled'");
        youtube.attr("disabled='disabled'");
    });

   youtube.click(function(){
        img.attr("disabled='disabled'");
        video.attr("disabled='disabled'");
    });

});
</code>```

答:
You should listen to event like

```<code>    img.on("click", function(){
</code>```

You can disable button like

```<code>    attr("disabled", true);
</code>```

// var
    var img = $("#image");
    var video = $("#video");
    var youtube = $("#youtube");

    img.on("click", function(){
        video.attr("disabled", true);
        youtube.attr("disabled", true);
    });

  video.on("click", function(){
        img.attr("disabled", true);
        youtube.attr("disabled", true);
    });

   youtube.on("click", function(){
        img.attr("disabled", true);
        video.attr("disabled", true);
    });

    $("#btnReset").on("click", function(){
        img.attr("disabled", false);
        video.attr("disabled", false);
        youtube.attr("disabled", false);
    });```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.post_box_but:disabled{
  background: red;
}</code>```

                        <textarea class="form-control" name="post_box" placeholder="Post something..." onkeyup="count_post_box_char(this, 500)"></textarea>

                            <button class="post_box_but">

                            </button>

                            <button class="post_box_but" data-placement="bottom" data-toggle="tooltip" title="Mention people by typing @ before their username e.g. @aaron">

                            </button>

                            <button class="post_box_but" id="image">

                            </button>

                            <button class="post_box_but" id="video">

                            </button>

                            <button class="post_box_but" id="youtube">

                            </button>
                            <button class="post_box_upload_but" id="btnReset">
                                Reset_Button
                            </button>
                            <button class="post_box_upload_but">
                                Post
                            </button>

```

Body:
I have a form am working on for a project which allows users to upload images, videos and YouTube videos and I will like users not to upload photos, videos and YouTube videos at the same time but am finding it difficult on how to disable the image button when video or YouTube button is been clicked, disable video button when image or YouTube button is been clicked and disable YouTube button when image or video button is been clicked. Below is my form and Jquery code I have written so far

HTML

<form method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"])?>" name="post-box" enctype="multipart/form-data" accept-charset="utf-8">

                        <textarea class="form-control" name="post_box" placeholder="Post something..." onkeyup="count_post_box_char(this, 500)"></textarea>

                            <button class="post_box_but">

                            </button>

                            <button class="post_box_but" data-placement="bottom" data-toggle="tooltip" title="Mention people by typing @ before their username e.g. @aaron">

                            </button>

                            <button class="post_box_but" id="image">

                            </button>

                            <button class="post_box_but" id="video">

                            </button>

                            <button class="post_box_but" id="youtube">

                            </button>

                            <button class="post_box_upload_but">
                                Post
                            </button>

                </form>

JQUERY

$(document).ready(function(){
    // var
    var img = $("#image");
    var video = $("#video");
    var youtube = $("#youtube");

    img.click(function(){
        $("#video").attr("disabled='disabled'");
        $("#youtube").attr("disabled='disabled'");
    });

  video.click(function(){
        img.attr("disabled='disabled'");
        youtube.attr("disabled='disabled'");
    });

   youtube.click(function(){
        img.attr("disabled='disabled'");
        video.attr("disabled='disabled'");
    });

});

Body:
You should listen to event like

    img.on("click", function(){

You can disable button like

    attr("disabled", true);

// var
    var img = $("#image");
    var video = $("#video");
    var youtube = $("#youtube");

    img.on("click", function(){
        video.attr("disabled", true);
        youtube.attr("disabled", true);
    });

  video.on("click", function(){
        img.attr("disabled", true);
        youtube.attr("disabled", true);
    });

   youtube.on("click", function(){
        img.attr("disabled", true);
        video.attr("disabled", true);
    });

    $("#btnReset").on("click", function(){
        img.attr("disabled", false);
        video.attr("disabled", false);
        youtube.attr("disabled", false);
    });

.post_box_but:disabled{
  background: red;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

                    <div class="post_box_cont">
                        <textarea class="form-control" name="post_box" placeholder="Post something..." onkeyup="count_post_box_char(this, 500)"></textarea>

                        <div class="mt-1">
                            <button class="post_box_but">
                                <span class="icon icon-location"></span>
                            </button>

                            <button class="post_box_but" data-placement="bottom" data-toggle="tooltip" title="Mention people by typing @ before their username e.g. @aaron">
                                <span class="icon icon-at"></span>
                            </button>

                            <button class="post_box_but" id="image">
                                <span class="icon icon-image"></span>
                            </button>

                            <button class="post_box_but" id="video">
                                <span class="icon icon-video"></span>
                            </button>

                            <button class="post_box_but" id="youtube">
                                <span class="icon icon-youtube"></span>
                            </button>
                            <button class="post_box_upload_but" id="btnReset">
                                <b>Reset_Button</b>
                            </button>
                            <button class="post_box_upload_but">
                                <b>Post</b>
                            </button>
                        </div>
                    </div>


问:
Adding dictonary with static keys inside another dictonary in python 3
I wanna make a dictonary with another dictonary that have fixed keys e.g

```<code>dic1 = {'filename':'file1','namelen':'5'}
dic2 = {
"file1":dic1,
"file2":dic2,
...
...
}
</code>```

The issue with my code is adding a new dictonary overwrites all the exisitng inner dictonary.

```<code>dic1 ={}
dic2 ={}
file_list = ["file1","file2", "file3"]
for file in file_list:
 dic1["filename"] = file
 dic1["namelen"] = len(file)
 dic2[file] = dic1
print(dic2)
</code>```

My dictonary looks like this

```<code>    dic2 =
{
'file1': {'namelen': 5, 'filename': 'file3'},
'file3': {'namelen': 5, 'filename': 'file3'},
'file2': {'namelen': 5, 'filename': 'file3'}
}
</code>```

How to prevent the overwrite, without switching to list ?

答:
Add a copy of dictionary instead of the dictionary itself.

This line:

```<code>dic2[file] = dic1
</code>```

changes to:

```<code>dic2[file] = dic1.copy()
</code>```

Body:
I wanna make a dictonary with another dictonary that have fixed keys e.g

dic1 = {'filename':'file1','namelen':'5'}
dic2 = {
"file1":dic1,
"file2":dic2,
...
...
}

The issue with my code is adding a new dictonary overwrites all the exisitng inner dictonary.

dic1 ={}
dic2 ={}
file_list = ["file1","file2", "file3"]
for file in file_list:
 dic1["filename"] = file
 dic1["namelen"] = len(file)
 dic2[file] = dic1
print(dic2)

My dictonary looks like this

    dic2 =
{
'file1': {'namelen': 5, 'filename': 'file3'},
'file3': {'namelen': 5, 'filename': 'file3'},
'file2': {'namelen': 5, 'filename': 'file3'}
}

How to prevent the overwrite, without switching to list ?

Body:
Add a copy of dictionary instead of the dictionary itself.

This line:

dic2[file] = dic1

changes to:

dic2[file] = dic1.copy()


问:
3 floated divs in a fixed width container, div jumps down when the three are same size as fixed div woth border
Messy headline, but i had no other way to descibe it.
what im trying to do is i have 3 boex in a line with only 1 px border at each side, but cant get it to work, it is always 2 px at the far right one. How to solve this?

Check the code:

```<code>#content {
  width: 1016px;
  min-height: 664px;
  height: auto;
  border: 1px solid #232323;
  background-color: #12100e;
  float: left;
  padding: 0px;
}

#imagebox {
  Width: 338px;
  height: 221px;
  padding-right: 0px;
  padding-left: 0px;
  border-right: 1px solid #232323;
  border-bottom: 1px solid #232323;
}

<html>
  <head>
    <link rel="StyleSheet" href="Main.css" type="text/css">
    <title></title>
  </head>
  <body>
    <div id="mainbody">
      <div id="menu"></div>
      <div id="content">
        <div id="imagebox"></div>
        <div id="imagebox"></div>
        <div id="imagebox"></div>
        <div id="imagebox"></div>
        <div id="imagebox"></div>
        <div id="imagebox"></div>
        <div id="imagebox"></div>
        <div id="imagebox"></div>
        <div id="imagebox"></div>
      </div>
    </div>
  </body>
</html>
</code>```

答:
Closest you can get:

http://jsfiddle.net/CGEWC/2/

Several thing you have to keep in mind:

Use classes in stead of id's if you need to assign a style multiple times.

In your CSS you use Width with a capital. Although CSS is not case sensitive it's cleaner to just write it all lowercase.

I've added a float: left; to your imageboxes

I've added first and last classes to your div. Not the cleanest code, but it should word.

ContentLicense: CC BY-SA 3.0

Body:
Messy headline, but i had no other way to descibe it.
what im trying to do is i have 3 boex in a line with only 1 px border at each side, but cant get it to work, it is always 2 px at the far right one. How to solve this?

Check the code:

#content {
  width: 1016px;
  min-height: 664px;
  height: auto;
  border: 1px solid #232323;
  background-color: #12100e;
  float: left;
  padding: 0px;
}

#imagebox {
  Width: 338px;
  height: 221px;
  padding-right: 0px;
  padding-left: 0px;
  border-right: 1px solid #232323;
  border-bottom: 1px solid #232323;
}

    <link rel="StyleSheet" href="Main.css" type="text/css">
    <title></title>


答:
Try this way:

```<code>dic2 ={}
file_list = ["file1","file2", "file3"]
for f in file_list:
 dic1 ={}

 dic1["filename"] = f
 dic1["namelen"] = len(f)
 dic2[f] = dic1
print(dic2)
</code>```

each and every iteration try creating a new dict1={} inside the loop

Otherwise,if you do outside the loop,it will reference the same dictionary again and again

Title: Adding dictonary with static keys inside another dictonary in python 3

Body:
Try this way:

dic2 ={}
file_list = ["file1","file2", "file3"]
for f in file_list:
 dic1 ={}

 dic1["filename"] = f
 dic1["namelen"] = len(f)
 dic2[f] = dic1
print(dic2)

each and every iteration try creating a new dict1={} inside the loop

Otherwise,if you do outside the loop,it will reference the same dictionary again and again


问:
Scrapy - pymongo not inserting items to DB
So im playing about with scrapy trying to learn, and using MongoDB as my DB ive come to a dead end.
Basically the scraping works as the items im fetching are showing in the terminal log, but i cant get the data to publish on my DB. The MONGO_URI is correct as i tried it in the python shell where i can create and store data..

Here are my files

items.py

```<code>
import scrapy

class MaterialsItem(scrapy.Item):
    # define the fields for your item here like:
    # name = scrapy.Field()
    title = scrapy.Field()
    price = scrapy.Field()
   ## url = scrapy.Field()
    pass
</code>```

spider.py

```<code>import scrapy
from scrapy.selector import Selector

from ..items import MaterialsItem

class mySpider(scrapy.Spider):
    name = "<placeholder for post>"
    allowed_domains = ["..."]
    start_urls = [
   ...
    ]

    def parse(self, response):
        products = Selector(response).xpath('//div[@class="content"]')

        for product in products:
                item = MaterialsItem()
                item['title'] = product.xpath("//a[@class='product-card__title product-card__title-v2']/text()").extract(),
                item['price'] = product.xpath("//div[@class='product-card__price-value ']/text()").extract()
               ## product['url'] =
                yield item
</code>```

settings.py

```<code>MONGO_PIPELINES = {
    'materials.pipelines.MongoPipeline': 300,
}

#setup mongo DB
MONGO_URI = "my MongoDB Atlas address"
MONGO_DB = "materials"

</code>```

pipelines.py

```<code>import pymongo

class MongoPipeline(object):

    collection_name = 'my-prices'

    def __init__(self, mongo_uri, mongo_db):
        self.mongo_uri = mongo_uri
        self.mongo_db = mongo_db

    @classmethod
    def from_crawler(cls, crawler):
        ## pull in information from settings.py
        return cls(
            mongo_uri=crawler.settings.get('MONGO_URI'),
            mongo_db=crawler.settings.get('MONGO_DB', ', <placeholder-spider name>')

        )

    def open_spider(self, spider):
        ## initializing spider
        ## opening db connection
        self.client = pymongo.MongoClient(self.mongo_uri)
        self.db = self.client[self.mongo_db]

    def close_spider(self, spider):
        ## clean up when spider is closed
        self.client.close()

    def process_item(self, item, spider):
        ## how to handle each post
        self.db[self.collection_name].insert(dict(item))
        logging.debug("Post added to MongoDB")
        return item
</code>```

Any help would be great!

**Edit

file structure

```<code>materials
  spiders
  my-spider
items.py
pipelines.py
settings.py
</code>```

答:
I figured it out, with a fresh head i looked over everything again. Turns out in settings i had to edit the

```<code>MONGO_PIPELINES = {
    'materials.pipelines.MongoPipeline': 300,
}
</code>```

to

```<code>ITEM_PIPELINES = {
    'materials.pipelines.MongoPipeline': 300,
}
</code>```

I guess i shouldnt have changed the naming format, from ITEM_PIPELINES to MONGO_PIPELINES.

Body:
So im playing about with scrapy trying to learn, and using MongoDB as my DB ive come to a dead end.
Basically the scraping works as the items im fetching are showing in the terminal log, but i cant get the data to publish on my DB. The MONGO_URI is correct as i tried it in the python shell where i can create and store data..

Here are my files

items.py

import scrapy

class MaterialsItem(scrapy.Item):
    # define the fields for your item here like:
    # name = scrapy.Field()
    title = scrapy.Field()
    price = scrapy.Field()
   ## url = scrapy.Field()
    pass

spider.py

import scrapy
from scrapy.selector import Selector

from ..items import MaterialsItem

class mySpider(scrapy.Spider):
    name = "<placeholder for post>"
    allowed_domains = ["..."]
    start_urls = [
   ...
    ]

    def parse(self, response):
        products = Selector(response).xpath('//div[@class="content"]')

        for product in products:
                item = MaterialsItem()
                item['title'] = product.xpath("//a[@class='product-card__title product-card__title-v2']/text()").extract(),
                item['price'] = product.xpath("//div[@class='product-card__price-value ']/text()").extract()
               ## product['url'] =
                yield item

settings.py

MONGO_PIPELINES = {
    'materials.pipelines.MongoPipeline': 300,
}

#setup mongo DB
MONGO_URI = "my MongoDB Atlas address"
MONGO_DB = "materials"

pipelines.py

import pymongo

class MongoPipeline(object):

    collection_name = 'my-prices'

    def __init__(self, mongo_uri, mongo_db):
        self.mongo_uri = mongo_uri
        self.mongo_db = mongo_db

    @classmethod
    def from_crawler(cls, crawler):
        ## pull in information from settings.py
        return cls(
            mongo_uri=crawler.settings.get('MONGO_URI'),
            mongo_db=crawler.settings.get('MONGO_DB', ', <placeholder-spider name>')

        )

    def open_spider(self, spider):
        ## initializing spider
        ## opening db connection
        self.client = pymongo.MongoClient(self.mongo_uri)
        self.db = self.client[self.mongo_db]

    def close_spider(self, spider):
        ## clean up when spider is closed
        self.client.close()

    def process_item(self, item, spider):
        ## how to handle each post
        self.db[self.collection_name].insert(dict(item))
        logging.debug("Post added to MongoDB")
        return item

Any help would be great!

**Edit

file structure

materials
  spiders
  my-spider
items.py
pipelines.py
settings.py

Body:
I figured it out, with a fresh head i looked over everything again. Turns out in settings i had to edit the

MONGO_PIPELINES = {
    'materials.pipelines.MongoPipeline': 300,
}

to

ITEM_PIPELINES = {
    'materials.pipelines.MongoPipeline': 300,
}

I guess i shouldnt have changed the naming format, from ITEM_PIPELINES to MONGO_PIPELINES.


问:
$($(elContainer).find('.image-wrapper').eq(index)[0]).find(' > img').remove();
I want convert this jquery code:

```<code>$($(elContainer).find('.image-wrapper').eq(index)[0]).find(' > img').remove();
$(elContainer).find('.image-wrapper').eq(index)[0].appendChild(img);
</code>```

to Javascript. Pls help me!!!

答:
Try this:</p>

```<code>document.querySelector('elContainerSelector .image-wrapper > img').remove()
const node = document.createElement("img")
document.querySelector('elContainerSelector .image-wrapper').appendChild(node)
</code>```

Body:
I want convert this jquery code:

$($(elContainer).find('.image-wrapper').eq(index)[0]).find(' > img').remove();
$(elContainer).find('.image-wrapper').eq(index)[0].appendChild(img);

to Javascript. Pls help me!!!

Body:
Try this:

document.querySelector('elContainerSelector .image-wrapper > img').remove()
const node = document.createElement("img")
document.querySelector('elContainerSelector .image-wrapper').appendChild(node)


问:
C/C++: goto into the for loop
I have a bit unusual situation - I want to use goto statement to jump into the loop, not to jump out from it.

There are strong reasons to do so - this code must be part of some function which makes some calculations after the first call, returns with request for new data and needs one more call to continue. Function pointers (obvious solution) can't be used because we need interoperability with code which does not support function pointers.

I want to know whether code below is safe, i.e. it will be correctly compiled by all standard-compliant C/C++ compilers (we need both C and C++).

```<code>function foo(int not_a_first_call, int *data_to_request, ...other parameters... )
{
    if( not_a_first_call )
        goto request_handler;
    for(i=0; i<n; i++)
    {
        *data_to_request = i;
        return;
request_handler:
        ...process data...
    }
}
</code>```

I've studied standards, but there isn't much information about such use case. I also wonder whether replacing for by equivalent while will be beneficial from the portability point of view.

Thanks in advance.

UPD: Thanks to all who've commented!

to all commenters :) yes, I understand that I can't jump over initializers of local variables and that I have to save/restore i on each call.

about strong reasons :) This code must implement reverse communication interface. Reverse communication is a coding pattern which tries to avoid using function pointers. Sometimes it have to be used because of legacy code which expects that you will use it.

Unfortunately, r-comm-interface can't be implemented in a nice way. You can't use function pointers and you can't easily split work into several functions.

答:
The initialisation part of the for loop will not occur, which makes it somewhat redundant.  You need to initialise i before the goto.

```<code>int i = 0 ;
if( not_a_first_call )
    goto request_handler;
for( ; i<n; i++)
{
    *data_to_request = i;
    return;
request_handler:
    ...process data...
}
</code>```

However, this is really not a good idea!

The code is flawed in any case, the return statment circumvents the loop. As it stands it is equivalent to:

```<code>int i = 0 ;

if( not_a_first_call )
    \\...process_data...

i++ ;
if( i < n )
{
    *data_to_request = i;
}
</code>```

In the end, if you think you need to do this then your design is flawed, and from the fragment posted your logic also.

Title: C/C++: goto into the for loop

Body:
I have a bit unusual situation - I want to use goto statement to jump into the loop, not to jump out from it.

There are strong reasons to do so - this code must be part of some function which makes some calculations after the first call, returns with request for new data and needs one more call to continue. Function pointers (obvious solution) can't be used because we need interoperability with code which does not support function pointers.

I want to know whether code below is safe, i.e. it will be correctly compiled by all standard-compliant C/C++ compilers (we need both C and C++).

function foo(int not_a_first_call, int *data_to_request, ...other parameters... )
{
    if( not_a_first_call )
        goto request_handler;
    for(i=0; i<n; i++)
    {
        *data_to_request = i;
        return;
request_handler:
        ...process data...
    }
}

I've studied standards, but there isn't much information about such use case. I also wonder whether replacing for by equivalent while will be beneficial from the portability point of view.

Thanks in advance.

UPD: Thanks to all who've commented!

to all commenters :) yes, I understand that I can't jump over initializers of local variables and that I have to save/restore i on each call.

about strong reasons :) This code must implement reverse communication interface. Reverse communication is a coding pattern which tries to avoid using function pointers. Sometimes it have to be used because of legacy code which expects that you will use it.

Unfortunately, r-comm-interface can't be implemented in a nice way. You can't use function pointers and you can't easily split work into several functions.

Body:
The initialisation part of the for loop will not occur, which makes it somewhat redundant.  You need to initialise i before the goto.

int i = 0 ;
if( not_a_first_call )
    goto request_handler;
for( ; i<n; i++)
{
    *data_to_request = i;
    return;
request_handler:
    ...process data...
}

However, this is really not a good idea!

The code is flawed in any case, the return statment circumvents the loop. As it stands it is equivalent to:

int i = 0 ;

if( not_a_first_call )
    \\...process_data...

i++ ;
if( i < n )
{
    *data_to_request = i;
}

In the end, if you think you need to do this then your design is flawed, and from the fragment posted your logic also.


问:
Flask blocking on endpoint without allowing another endpoint calls
One of the endpoints of my flask API makes a long request to a Live Stream. Here is an example of the code:

```<code>@app.route('/stream')
def live_stream(sensor_id):
    stream = requests.get('stream_url', stream=True)
    return Response(stream_with_context(stream.iter_content(chunk_size=2048)),
                content_type=stream.headers['content-type'])
</code>```

This route is working fine and the stream goes well. However, when I try to make requests to another routes it seems like the server get stucked at this endpoint.

I'm using a gevent WSGI server:

```<code> http_server = WSGIServer(('0.0.0.0', 5000), app).serve_forever()
</code>```

And I'm making the requests from a template already returned by a Flask route.

How can I make parallel requests to the API without get stucked on that?

答:
I have never used gevent, but if I understand correctly, it has a single-threaded event loop (like asyncio). But my understanding might be wrong.

Have a look at this answer https://stackoverflow.com/a/19153826/

When you have a piece of python code that takes a long time to run (for seconds) and does not cause switching of greenlets, all other greenlets / gevent jobs will 'starve' and have no computation time and it will look like your application 'hangs'.

I suggest to do one of the following:

Either, run your web app in a threaded WSGI server

Or, research if gevent has a network client that you can use instead of requests that is based on greelets

Or, run the blocking part of your code in a thread tool

Or, invoke from gevent import monkey; monkey.patch_all() as the very first thing in you server code, and see if that makes requests behave non-blocking.

Body:
One of the endpoints of my flask API makes a long request to a Live Stream. Here is an example of the code:

@app.route('/stream')
def live_stream(sensor_id):
    stream = requests.get('stream_url', stream=True)
    return Response(stream_with_context(stream.iter_content(chunk_size=2048)),
                content_type=stream.headers['content-type'])

This route is working fine and the stream goes well. However, when I try to make requests to another routes it seems like the server get stucked at this endpoint.

I'm using a gevent WSGI server:

 http_server = WSGIServer(('0.0.0.0', 5000), app).serve_forever()

And I'm making the requests from a template already returned by a Flask route.

How can I make parallel requests to the API without get stucked on that?


问:
Node Js Error uploading to S3 : TypeError [ERR_INVALID_ARG_TYPE]
I'm trying to get an image uploaded to my amazon s3 bucket, but I keep getting the error

TypeError [ERR_INVALID_ARG_TYPE]: The first argument must be one of type string, Buffer, ArrayBuffer, Array,
or Array-like Object.

So basically I know I have to change it to a buffer, after some searching i tried a few solutions but non of them are working, can someone help point out to me what I'm going wrong?

```<code>  const s3Client = s3.s3Client;
  const params = s3.uploadParams;

  //const fileContent = fs.readFileSync(req.file); <-- tried this and still gave the same error
  var fileContent = Buffer.from(req.file, 'base64')

  params.Key = req.file.filename
  params.Body = fileContent

  console.log(req.file)

  s3Client.upload(params, (err, data) => {
    if (err) {
      res.status(500).json({error:"Error -> " + err});
    }
    res.json({message: 'File uploaded successfully! -> keyname = ' + req.file.originalname});
  });
</code>```

This is the image itself, maybe I'm converting it wrongly? The details are taken from the req.file console log

```<code>{
  fieldname: 'image',
  originalname: 'Kimmi.jpg',
  encoding: '7bit',
  mimetype: 'image/jpeg',
  destination: './images/',
  filename: 'c6b46e20-4efc-11ea-8b6a-1b4d698f6335.jpeg',
  path: 'images\\c6b46e20-4efc-11ea-8b6a-1b4d698f6335.jpeg',
  size: 35920
}
</code>```

答:
I am not quite sure, but I think that you are using multer ?
If you are using multer you can basically use req.file.buffer.

My advice is to use stream instead of buffer if images are big
Stream example

Body:
I'm trying to get an image uploaded to my amazon s3 bucket, but I keep getting the error

TypeError [ERR_INVALID_ARG_TYPE]: The first argument must be one of type string, Buffer, ArrayBuffer, Array,
or Array-like Object.

So basically I know I have to change it to a buffer, after some searching i tried a few solutions but non of them are working, can someone help point out to me what I'm going wrong?

  const s3Client = s3.s3Client;
  const params = s3.uploadParams;

  //const fileContent = fs.readFileSync(req.file); <-- tried this and still gave the same error
  var fileContent = Buffer.from(req.file, 'base64')

  params.Key = req.file.filename
  params.Body = fileContent

  console.log(req.file)

  s3Client.upload(params, (err, data) => {
    if (err) {
      res.status(500).json({error:"Error -> " + err});
    }
    res.json({message: 'File uploaded successfully! -> keyname = ' + req.file.originalname});
  });

This is the image itself, maybe I'm converting it wrongly? The details are taken from the req.file console log

{
  fieldname: 'image',
  originalname: 'Kimmi.jpg',
  encoding: '7bit',
  mimetype: 'image/jpeg',
  destination: './images/',
  filename: 'c6b46e20-4efc-11ea-8b6a-1b4d698f6335.jpeg',
  path: 'images\\c6b46e20-4efc-11ea-8b6a-1b4d698f6335.jpeg',
  size: 35920
}


问:
C Linked-list Destroy Function
I am trying to learn C, and as many people, I have been a little stuck with pointers. Anyways, I made a recursive function that destroys my linked list, but as I have debugged, when I am back from the function the head of the list is not null as it should be, so I'm guessing it's some basic misunderstanding with pointers. Here's the function:</p>

```<code>void destroy(struct node *n) {
   if (!n) return;
   destroy(n->next);
   free(n);
   n = NULL;
}
</code>```

答:
Your recursive destroy function cannot modify the head variable in the caller's frame.

The statement n = NULL only affects the function argument, which is a local variable of the destroy function. It actually has no effect, so you can remove this statement.

You should set the head to NULL after the call to destroy in the caller function if it is needed there.

Title: C Linked-list Destroy Function

Body:
I am trying to learn C, and as many people, I have been a little stuck with pointers. Anyways, I made a recursive function that destroys my linked list, but as I have debugged, when I am back from the function the head of the list is not null as it should be, so I'm guessing it's some basic misunderstanding with pointers. Here's the function:

void destroy(struct node *n) {
   if (!n) return;
   destroy(n->next);
   free(n);
   n = NULL;
}


问:
Can't create a Flutter/Firebase non-authenticated user favorite list in ListTile
I am trying to create a NON-authenticated user icon 'select favorite' option where if an icon is clicked ( on a list of titles in a ListView of Firestore data(book titles)) it saves the data to be routed to a new favorites page. I can not find information on how top do this in the Firestore docs, but I found a youtube tutorial that does this for a popular flutter WordPair app. Here is the string used to store their WordPair data:

```<code>final _randomWordPairs = <WordPair>[];
</code>```

and another variable to check to see if WordPair lists were already saved is:

```<code>final _savedWordPairs = Set<WordPair>[];
</code>```

If my Firebase data string is

```<code>Firestore.instance.collection("titles").snapshots()
</code>```

what is the equivalent to the above WordPair variables so I can create this favorites list with a list of my titles

```<code>snapshot.data.documents[index]['title']
</code>```

Nothing works. Still trying to figure it out: variables:

```<code>final savedDb = Firestore.instance.collection("books").document('title');
</code>```

final alreadySaved = Firestore.instance.collection("books").document('title');

ListTile code to call it:

```<code>trailing: Icon( alreadySaved ?  Icons.favorite :
                        Icons.favorite_border,
                        color: alreadySaved ? Colors.red : null),

                          onTap: () {
                          setState(() {
                            if(alreadySaved) {
                              savedDb.remove('title');
                            }else{
                              savedDb.add('title');
                            }
                          });
                        }
</code>```

I tried this but now it just crashes that page;

```<code>final alreadySaved = Firestore.instance.collection("books").where((item) => item.contains("title"));

List<String> savedDb = ['Firestore.instance.collection("books").document(title)'];
</code>```

```<code>                              trailing: Icon( alreadySaved == null ?  Icons.favorite :
                          Icons.favorite_border,
                              color: alreadySaved != null ? Colors.red : null),

                          onTap: () {
                            setState(() {
                              savedDb.add('title');
                            });
                          },
</code>```

Last attempt:

bool alreadySaved = false;

```<code>savedDb() async{
    DocumentSnapshot ds = await
Firestore.instance.collection("books").document('title').get();
    this.setState(() {
      alreadySaved = ds.exists;
    });
  }

  @override
  void initState() {
    super.initState();
    savedDb();
  }
</code>```

and onTap says .remove and .add isn't defined for type Function,  and my icons won't even change color. This is impossible

```<code>                            onTap: () {
                          setState(() {
                            if(alreadySaved) {
                              savedDb.remove('Firestore.instance.collection("books")');
                            }else{
                              savedDb.add(Firestore.instance.collection("books"));
                            }
                          });
                        },
</code>```

Returns .remove and .add isn't defined for type Function

答:
All information about datatypes in Firestore you can find in this doc.

For _randomWordPairs which is actually an array -  you can just use the same type. Array is one of supported field types in Firestore. So there shouldn't be any problem with that.

When it comes to _savedWordPairs its more complicated as this is a set which means it cannot contain duplicate values. So during the update of the field that contain this list you  have to add logic which will check if the particular value already exits before adding to the list.

Of course there is no custom type WordPair possible to be stored in Firestore, but you can store its string object and there are a lot of possibilities to do this: as list, as map or just as String or even as some nested object. Firestore is generally NoSQL database based on documents so you can do everything there. If you need more about Firestore data model check here. Or just take a look on general reference for "NoSQL based on documents database" , as Firestore implements all standard concepts of these db types.

I hope it will help!

Body:
I am trying to create a NON-authenticated user icon 'select favorite' option where if an icon is clicked ( on a list of titles in a ListView of Firestore data(book titles)) it saves the data to be routed to a new favorites page. I can not find information on how top do this in the Firestore docs, but I found a youtube tutorial that does this for a popular flutter WordPair app. Here is the string used to store their WordPair data:

final _randomWordPairs = <WordPair>[];

and another variable to check to see if WordPair lists were already saved is:

final _savedWordPairs = Set<WordPair>[];

If my Firebase data string is

Firestore.instance.collection("titles").snapshots()

what is the equivalent to the above WordPair variables so I can create this favorites list with a list of my titles

snapshot.data.documents[index]['title']

Nothing works. Still trying to figure it out: variables:

final savedDb = Firestore.instance.collection("books").document('title');

final alreadySaved = Firestore.instance.collection("books").document('title');

ListTile code to call it:

trailing: Icon( alreadySaved ?  Icons.favorite :
                        Icons.favorite_border,
                        color: alreadySaved ? Colors.red : null),

                          onTap: () {
                          setState(() {
                            if(alreadySaved) {
                              savedDb.remove('title');
                            }else{
                              savedDb.add('title');
                            }
                          });
                        }

I tried this but now it just crashes that page;

final alreadySaved = Firestore.instance.collection("books").where((item) => item.contains("title"));

List<String> savedDb = ['Firestore.instance.collection("books").document(title)'];

                              trailing: Icon( alreadySaved == null ?  Icons.favorite :
                          Icons.favorite_border,
                              color: alreadySaved != null ? Colors.red : null),

                          onTap: () {
                            setState(() {
                              savedDb.add('title');
                            });
                          },

Last attempt:

bool alreadySaved = false;

savedDb() async{
    DocumentSnapshot ds = await
Firestore.instance.collection("books").document('title').get();
    this.setState(() {
      alreadySaved = ds.exists;
    });
  }

  @override
  void initState() {
    super.initState();
    savedDb();
  }

and onTap says .remove and .add isn't defined for type Function,  and my icons won't even change color. This is impossible

                            onTap: () {
                          setState(() {
                            if(alreadySaved) {
                              savedDb.remove('Firestore.instance.collection("books")');
                            }else{
                              savedDb.add(Firestore.instance.collection("books"));
                            }
                          });
                        },

Returns .remove and .add isn't defined for type Function


问:
How to write a custom powershell host
Similar to nuget

Looking for any starter material hopefully before delving into the debugger

答:
MSDN has a section devoted to writing a PowerShell host in the PowerShell SDK documentation, which is a nice starting point.

Besides that a search returns the following:

http://powershellstation.com/2009/10/12/writing-your-own-powershell-hosting-app-part-1-introduction/

http://dougfinke.com/blog/index.php/2009/09/02/how-to-host-powershell-in-a-wpf-application/

Title: How to write a custom powershell host


问:
azure logic app: Write data to a local excel file
We have options to write data to Excel Online (Business and OneDrive).
But i need to write data to a local excel file in my system. I didnt find any connector for the same. Any workarounds please?</p>

答:
With the File System connector and Azure Logic Apps, you can create automated tasks and workflows that create and manage files on an on-premises file share.

Before you can connect logic apps to on-premises systems such as your file system server, you need to install and set up an on-premises data gateway. That way, you can specify to use your gateway installation when you create the file system connection from your logic app.

Configure the connector to on premise path and you could go on.


问:
Error CS1705: "which has a higher version than referenced assembly"
I've been looking into this for a bit now and haven't gotten it resolved. I get the following error message:

```<code>Compiler Error Message: CS1705: Assembly 'My.Model, Version=1.1.4422.23773, Culture=neutral,
PublicKeyToken=bfde95ba233094b2' uses
'Common, Version=3.3.4273.24368, Culture=neutral, PublicKeyToken=bfde95ba233094b2'
which has a higher version than referenced assembly
'Common, Version=3.3.4269.17112, Culture=neutral, PublicKeyToken=bfde95ba233094b2'

c:\WINDOWS\assembly\GAC_MSIL\Common\3.3.4269.17112__bfde95ba233094b2\Common.dll:
(Location of symbol related to previous error)
</code>```

The web server is running Server 2003. I went to c:\windows\assembly and did in fact notice that there were 3 versions of Common.dll listed. The highest version listed was 3.3.4269.17112

I copied the dll with version: 3.3.4273.24368 into the assembly directory. I then re-compiled and re-deployed my code (probably overkill but oh well). When I opened my browser in  a new session and went to the site URL again I still got the same message.

I can use windows explorer and verify the higher-versioned Common.dll is now listed as well.

What more can I look into to resolve this issue? I don't want to change the reference in my assembly to point to the older version.

答:
In my scenario, I edited the .csproj file for my dotnetCore app.  I noticed that the TargetFramework tag had a value of netcoreapp2.1 and the RuntimeFrameworkVersion tag a value of 2.0.0. So I changed the RuntimeFrameworkVersion to 2.1.0, saved, restarted VS and rebuilt and then it resolved the errors.

Hope this will help you ...

Good Luck,

Sugeshan

Body:
I've been looking into this for a bit now and haven't gotten it resolved. I get the following error message:

Compiler Error Message: CS1705: Assembly 'My.Model, Version=1.1.4422.23773, Culture=neutral,
PublicKeyToken=bfde95ba233094b2' uses
'Common, Version=3.3.4273.24368, Culture=neutral, PublicKeyToken=bfde95ba233094b2'
which has a higher version than referenced assembly
'Common, Version=3.3.4269.17112, Culture=neutral, PublicKeyToken=bfde95ba233094b2'

c:\WINDOWS\assembly\GAC_MSIL\Common\3.3.4269.17112__bfde95ba233094b2\Common.dll:
(Location of symbol related to previous error)

The web server is running Server 2003. I went to c:\windows\assembly and did in fact notice that there were 3 versions of Common.dll listed. The highest version listed was 3.3.4269.17112

I copied the dll with version: 3.3.4273.24368 into the assembly directory. I then re-compiled and re-deployed my code (probably overkill but oh well). When I opened my browser in  a new session and went to the site URL again I still got the same message.

I can use windows explorer and verify the higher-versioned Common.dll is now listed as well.

What more can I look into to resolve this issue? I don't want to change the reference in my assembly to point to the older version.


问:
Moving files between folders when folder names match partially (in R or VBA)
I'm trying to solve the following problem

I have 9 folders titled PROS_2010 to PROS_2019. Each of them has about 500 subfolders with names structured as follows e.g. PROS_201001211_FIRM NAME_number. Each subfolder has a variety of pdf files with different names.

I have created in VBA another folder called sample with about 400 subfolders, each of which is named a specific FIRM NAME. For this I used the following code:

```<code>    Sub MakeFolders()
Dim Rng As Range
Dim maxRows, maxCols, r, c As Integer
Set Rng = Selection
maxRows = Rng.Rows.Count
maxCols = Rng.Columns.Count
For c = 1 To maxCols
r = 1
Do While r <= maxRows
If Len(Dir(ActiveWorkbook.Path & "\" & Rng(r, c), vbDirectory)) = 0 Then
MkDir (ActiveWorkbook.Path & "\" & Rng(r, c))
On Error Resume Next
End If
r = r + 1
Loop
Next c
End Sub
</code>```

I now want to move all the pdf files that are in the original subfolders PROS_201001211_FIRM NAME_number to the folders titled FIRM NAME only.
Basically, each original subfolder contains a report about a firm for a specific year (2010 to 2019) and I want to get all the firm reports for all years in a single folder titled FIRM NAME

To make it easier I already have an excel file that basically has the complete list of subfolders that looks like this:

Data structure: Company name is the name of the folder in which I want to move the files that are currently in "attachment folder". attachment1 is the pdf file name (which always changes so ideally the code would pluck all the files in attachment folder and move them to the file with company name

Thanks in advance,

Simon

答:
OK
So thanks to the help of a mate I found it is super easy to solve this problem using the "command" command in windows

Basically create a text file (in notepad) that has the following structure

move "original pdf file directory" "new pdf file location\"
...

Repeat the structure for each file (which requires some basic excel string manipulations)

Then save the .txt file as a .cmd file and open it.
Done

Body:
I'm trying to solve the following problem

I have 9 folders titled PROS_2010 to PROS_2019. Each of them has about 500 subfolders with names structured as follows e.g. PROS_201001211_FIRM NAME_number. Each subfolder has a variety of pdf files with different names.

I have created in VBA another folder called sample with about 400 subfolders, each of which is named a specific FIRM NAME. For this I used the following code:

    Sub MakeFolders()
Dim Rng As Range
Dim maxRows, maxCols, r, c As Integer
Set Rng = Selection
maxRows = Rng.Rows.Count
maxCols = Rng.Columns.Count
For c = 1 To maxCols
r = 1
Do While r <= maxRows
If Len(Dir(ActiveWorkbook.Path & "\" & Rng(r, c), vbDirectory)) = 0 Then
MkDir (ActiveWorkbook.Path & "\" & Rng(r, c))
On Error Resume Next
End If
r = r + 1
Loop
Next c
End Sub

I now want to move all the pdf files that are in the original subfolders PROS_201001211_FIRM NAME_number to the folders titled FIRM NAME only.
Basically, each original subfolder contains a report about a firm for a specific year (2010 to 2019) and I want to get all the firm reports for all years in a single folder titled FIRM NAME

To make it easier I already have an excel file that basically has the complete list of subfolders that looks like this:

Data structure: Company name is the name of the folder in which I want to move the files that are currently in "attachment folder". attachment1 is the pdf file name (which always changes so ideally the code would pluck all the files in attachment folder and move them to the file with company name

Thanks in advance,

Simon


问:
When calling batch script inside Jenkins file doesn't get the values after asterisk
When calling a batch script inside Jenkins file it doesn't catch/read the value after asterik *.

Below are the few lines of my batch code:

```<code>SET HOUSE=GREENVILLA
SET NUMBER=10
SET HOUSE_NAME=%HOUSE%-%NUMBER%.*.y
</code>```

I only see that HOUSE_NAME is set to GREENVILLA-10.*.y instead of GREENVILLA-10.44.6.y.

The actual path is \\servername\c\house\name containing the particular file greenvilla-10.44.6.y. I expect greenvilla-10.44.6.y being assigned to environment variable HOUSE_NAME.

Batch file coding is a new thing for me. I'm not sure about missing some basic things here.

答:
The Windows command processor cmd.exe processing a batch file does not replace argument strings containing a wildcard by all files/folders found in file system matching the wildcard pattern as Linux shell interpreters do, except the argument string containing the wildcard is enclosed in '. There must be used code in batch file to get file/folder names matching a wildcard pattern.

```<code>set "HOUSE=GREENVILLA"
set "NUMBER=10"
set "HOUSE_NAME="
for %%I in ("\\servername\c\house\name\%HOUSE%-%NUMBER%.*.y") do set "HOUSE_NAME=%%I"
if defined HOUSE_NAME echo "%HOUSE_NAME%"
</code>```

The last found non-hidden file in directory \\servername\c\house\name matching the wildcard pattern GREENVILLA-10.*.y is assigned to environment variable HOUSE_NAME with full path because of having specified the wildcard pattern with a folder path.

What is the last found file matching the wildcard pattern is determined by the file system. NTFS returns a list of files matching a pattern different to FAT16, FAT32 and exFAT drives. However, I suppose the directory contains always only one file matching the wildcard pattern.

For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.

echo /?

for /?

if /?

set /?

Body:
When calling a batch script inside Jenkins file it doesn't catch/read the value after asterik *.

Below are the few lines of my batch code:

SET HOUSE=GREENVILLA
SET NUMBER=10
SET HOUSE_NAME=%HOUSE%-%NUMBER%.*.y

I only see that HOUSE_NAME is set to GREENVILLA-10.*.y instead of GREENVILLA-10.44.6.y.

The actual path is \\servername\c\house\name containing the particular file greenvilla-10.44.6.y. I expect greenvilla-10.44.6.y being assigned to environment variable HOUSE_NAME.

Batch file coding is a new thing for me. I'm not sure about missing some basic things here.

Body:
The Windows command processor cmd.exe processing a batch file does not replace argument strings containing a wildcard by all files/folders found in file system matching the wildcard pattern as Linux shell interpreters do, except the argument string containing the wildcard is enclosed in '. There must be used code in batch file to get file/folder names matching a wildcard pattern.

set "HOUSE=GREENVILLA"
set "NUMBER=10"
set "HOUSE_NAME="
for %%I in ("\\servername\c\house\name\%HOUSE%-%NUMBER%.*.y") do set "HOUSE_NAME=%%I"
if defined HOUSE_NAME echo "%HOUSE_NAME%"

The last found non-hidden file in directory \\servername\c\house\name matching the wildcard pattern GREENVILLA-10.*.y is assigned to environment variable HOUSE_NAME with full path because of having specified the wildcard pattern with a folder path.

What is the last found file matching the wildcard pattern is determined by the file system. NTFS returns a list of files matching a pattern different to FAT16, FAT32 and exFAT drives. However, I suppose the directory contains always only one file matching the wildcard pattern.

For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.

echo /?

for /?

if /?

set /?


问:
Is there a way to include data-* as a script attribute in custom Google Tag Manager
I'm including a Custom script in GTM that makes a call to an external resource. The script looks like this

```<code><script type="text/javascript" id="some-key" data-key="xxxxxxxxxxxxxxxxxx" src="link-to-external-resource"></script>

</code>```

I've set its triggering to All pages which currently triggers fine But the problem is, the script renders without the data-key attribute in the DOM. It's rendering in the DOM looks like this

```<code><script type="text/javascript" id="some-key" src="link-to-external-resource"></script>
</code>```

Am I missing something? Is there a way to include data-* attributes in Google Tag Manager?

答:
I can confirm that for unknown reasons GTM strips the data attributes from appended script elements. Other elements like img seems to keep data attributes.
I've tested some workaround that preserves the data attributes but it's necessary to test if the appended script behaves properly when added in this way:

```<code><script>
  var script = document.createElement('script');
  script.id = 'Gdf234ds'
  script.dataset.key = 'xxxxxxxxxxxxxxxxxx'
  script.src = "https://link-to-external-resource.js"

  // use another target than head if necessary
  document.getElementsByTagName('head')[0].appendChild(script)
</script>
</code>```

Body:
I'm including a Custom script in GTM that makes a call to an external resource. The script looks like this

I've set its triggering to All pages which currently triggers fine But the problem is, the script renders without the data-key attribute in the DOM. It's rendering in the DOM looks like this

Am I missing something? Is there a way to include data-* attributes in Google Tag Manager?

Body:
I can confirm that for unknown reasons GTM strips the data attributes from appended script elements. Other elements like img seems to keep data attributes.
I've tested some workaround that preserves the data attributes but it's necessary to test if the appended script behaves properly when added in this way:

<script>
  var script = document.createElement('script');
  script.id = 'Gdf234ds'
  script.dataset.key = 'xxxxxxxxxxxxxxxxxx'
  script.src = "https://link-to-external-resource.js"

  // use another target than head if necessary
  document.getElementsByTagName('head')[0].appendChild(script)
</script>


问:
Compare multiple values at a time
I need to check if N values are equals.

```<code>var
  A, B, C, D : Integer;
begin
  ...
  if(A = B) and (B = C) and (C = D) then
    ShowMessage('Same value');
end;
</code>```

Is there a shorter way to compare N values?
I mean something like:

```<code>var
  A, B, C, D : Integer;
begin
  ...
  if SameValue([A, B, C, D]) then
    ShowMessage('Same value');
end;
</code>```

答:
There is quite simple and very fast equality comparison approach for ints without a need of additional method and stuff like this - it's Bitwise Operators
And of course, this could be put in a method with open array or so.

There are even 2 options (or maybe more), with second you also can replace "or" to "+" , OR (not both, it will ruin equality-test logic) you can replace "xor" to "-" (last case)

BUT the resulting condition length is not shorter than original (only the last case is same and all brackets/parenthesis are vital, except first xor/-), here is the testing code:

```<code>program Project1;{$APPTYPE CONSOLE}
uses Math; var a, b, c, d, x : Integer; s: string;
begin
  Randomize;
  repeat
    x := Random(10) - 5;
    a := x + Sign(Random() - 0.5);
    b := x + Sign(Random() - 0.5);
    c := x + Sign(Random() - 0.5);
    d := x + Sign(Random() - 0.5);
    Writeln(a, ' ', b, ' ', c, ' ', d);
    Writeln((A = B) and (B = C) and (C = D));
    Writeln(a or b or c or d = a and b and c and d);
    Writeln(a xor b or (b xor c) or (c xor d) = 0);
    Writeln(a - b or (b - c) or (c - d) = 0);
    Readln(s);
  until s <> '';
end.
</code>```

Title: Compare multiple values at a time

Body:
I need to check if N values are equals.

var
  A, B, C, D : Integer;
begin
  ...
  if(A = B) and (B = C) and (C = D) then
    ShowMessage('Same value');
end;

Is there a shorter way to compare N values?
I mean something like:

var
  A, B, C, D : Integer;
begin
  ...
  if SameValue([A, B, C, D]) then
    ShowMessage('Same value');
end;

Body:
There is quite simple and very fast equality comparison approach for ints without a need of additional method and stuff like this - it's Bitwise Operators
And of course, this could be put in a method with open array or so.

There are even 2 options (or maybe more), with second you also can replace "or" to "+" , OR (not both, it will ruin equality-test logic) you can replace "xor" to "-" (last case)

BUT the resulting condition length is not shorter than original (only the last case is same and all brackets/parenthesis are vital, except first xor/-), here is the testing code:

program Project1;{$APPTYPE CONSOLE}
uses Math; var a, b, c, d, x : Integer; s: string;
begin
  Randomize;
  repeat
    x := Random(10) - 5;
    a := x + Sign(Random() - 0.5);
    b := x + Sign(Random() - 0.5);
    c := x + Sign(Random() - 0.5);
    d := x + Sign(Random() - 0.5);
    Writeln(a, ' ', b, ' ', c, ' ', d);
    Writeln((A = B) and (B = C) and (C = D));
    Writeln(a or b or c or d = a and b and c and d);
    Writeln(a xor b or (b xor c) or (c xor d) = 0);
    Writeln(a - b or (b - c) or (c - d) = 0);
    Readln(s);
  until s <> '';
end.


问:
Update/insert only a column of database table in PHP
I WordPress table named wp_fes_vendors, there is a total of 12 columns.

Out of these 12 columns, I want to only update the data of column name requests

The data i am getting for this column is from a custom form in backend stored in $_POST['getval']

Here is code i tried

```<code> if (!empty(isset($_POST['getval'])))
    {
            global $wpdb;
            $table_name=$wpdb->prefix.'fes_vendors';

            $data_array = array(

            'requests' => $_POST['getval']

            );

            $data_where = array('requests' => $_POST['getval']);

            $wpdb->update($table_name,$data_array,$data_where);

    }
</code>```

Html

```<code><form id="myForm" name="myform" action="" method="POST" style="padding:20px;">
  <label> Select if this Vendor wishes to receive customer requests or not: </label>
  <select name="getval" id="brandSel" size="1">
      <option selected="selected" disbaled value="">-- Select status --</option>
      <option value="1">Enable</option>
      <option value="0">Disable</option>
  </select>

  <?php submit_button('submit'); ?>
</form>
</code>```

I tried several times but the data is not being saved /updated.
Here is picture of db

答:
Your condition doesn't make sense.

Lets say that the user picked enable -> $_POST['getval'] = 1;

Your query would be:

Update {table} SET requests = 1 WHERE requests = 1

Since none of the records have a value of 1 in the requests column, that condition would never exist and the update won't happen.

Even if there were rows with "requests = 1", the update won't really change them as their value is already 1.

The same goes for the case where the user picks "disable" (0)

I believe you should update your condition to a specific row.
You can do it by adding a hidden input to the form with the specific row you wish to update. And update your condition to so it would be something like:

```<code>"id" => $_POST['row_id']
</code>```

Body:
I WordPress table named wp_fes_vendors, there is a total of 12 columns.

Out of these 12 columns, I want to only update the data of column name requests

The data i am getting for this column is from a custom form in backend stored in $_POST['getval']

Here is code i tried

 if (!empty(isset($_POST['getval'])))
    {
            global $wpdb;
            $table_name=$wpdb->prefix.'fes_vendors';

            $data_array = array(

            'requests' => $_POST['getval']

            );

            $data_where = array('requests' => $_POST['getval']);

            $wpdb->update($table_name,$data_array,$data_where);

    }

Html

<form id="myForm" name="myform" action="" method="POST" style="padding:20px;">
   Select if this Vendor wishes to receive customer requests or not:
  <select name="getval" id="brandSel" size="1">
      <option selected="selected" disbaled value="">-- Select status --</option>
      <option value="1">Enable</option>
      <option value="0">Disable</option>
  </select>

  <?php submit_button('submit'); ?>
</form>

I tried several times but the data is not being saved /updated.
Here is picture of db

Body:
Your condition doesn't make sense.

Lets say that the user picked enable -> $_POST['getval'] = 1;

Your query would be:

Update {table} SET requests = 1 WHERE requests = 1

Since none of the records have a value of 1 in the requests column, that condition would never exist and the update won't happen.

Even if there were rows with "requests = 1", the update won't really change them as their value is already 1.

The same goes for the case where the user picks "disable" (0)

I believe you should update your condition to a specific row.
You can do it by adding a hidden input to the form with the specific row you wish to update. And update your condition to so it would be something like:

"id" => $_POST['row_id']