问:
Using v-for in laravel + vue.js, am trying to display a table containing information of the user but nothing shows
```<code><script>
    export default {
        name: "OutPatient",
        data(){
            return{
                out_patients: {}
            }
        },
        methods: {
                index(){
                        axios.get('/data/out_patient').then(({data}) =>
                                (this.out_patients = data.data));

                },
                update(){}
        },
        created(){
                this.index();
        }

    }
</script>

<tr v-for="out_patient in out_patients" v-bind:key="out_patient.id">
    <td>{{out_patient.id}}</td>
    <td>{{out_patient.first_name}}</td>
    <td></td>
    <td></td>
    <td></td>
    <td></td>
    <td></td>
    <td>
      <a href="#"><i class="fa fa-edit blue"></i></a>
      |
      <a href="#"><i class="fa fa-trash red"></i></a>
    </td>
</tr>

</code>```

This is my code but the data is not showing in the table even though in the XHR the data shows there.

In the inspect element I can see the data but the v-for loop is unable to display the data.

答:
Seems to me like you tried to extract data twice, you have this:

```<code>axios.get('/data/out_patient').then(({data}) =>
                                (this.out_patients = data.data));
</code>```

if you already extract it here: {data} then you don't need data.data, only data below?

Body:
    {{out_patient.id}}
    {{out_patient.first_name}}

      |

This is my code but the data is not showing in the table even though in the XHR the data shows there.

In the inspect element I can see the data but the v-for loop is unable to display the data.

Body:
Seems to me like you tried to extract data twice, you have this:

axios.get('/data/out_patient').then(({data}) =>
                                (this.out_patients = data.data));

if you already extract it here: {data} then you don't need data.data, only data below?


来源: stackexchange

问:
MVC C# Count Records Based on Condition
I am trying to count and display the number of logs conducted by various users from the Admin section.
Each user has a  UserID and through this, I would like to count and display data from a specific table.
I have made of a stored procedure and passed it to the Controller via a ViewBag but it keeps returning 1 as the total for all values.
 the procedure is Below

```<code>CREATE proc [Usp_GetCallCountByUserID]
@UserID int output
AS
BEGIN
SELECT COUNT (*) FROM Customer Where UserID= @UserID
GROUP BY UserID
set @UserID =@@ROWCOUNT
END
GO
</code>```

Controller:

```<code>     public ActionResult Index()
       {
        con.Open();
        SqlCommand comm = new SqlCommand("Usp_GetCallCountByUserID", con);
        comm.CommandType = CommandType.StoredProcedure;
        comm.Parameters.Add("@UserID", SqlDbType.Int).Direction =
            ParameterDirection.Output;
        SqlDataReader reader;
        reader = comm.ExecuteReader();
        reader.Close();
        ViewBag.CountLog = comm.Parameters["@UserID"].Value.ToString();
        con.Close();

        var callCustomers = db.Registrations;
        return View(callCustomers.ToList());
    }
</code>```

答:
Don't use global variable @@ROWCOUNT

you have to save the value of COUNT(*) in your request, look code below,

```<code>CREATE proc [Usp_GetCallCountByUserID]
    @UserID int,
    @RowCount int output
    AS
    BEGIN
    SELECT @RowCount = COUNT (*) FROM Customer Where UserID= @UserID
    GROUP BY UserID
    END
    GO
</code>```

ContentLicense: CC BY-SA 4.0

Title: MVC C# Count Records Based on Condition

Body:
I am trying to count and display the number of logs conducted by various users from the Admin section.
Each user has a  UserID and through this, I would like to count and display data from a specific table.
I have made of a stored procedure and passed it to the Controller via a ViewBag but it keeps returning 1 as the total for all values.
 the procedure is Below

CREATE proc [Usp_GetCallCountByUserID]
@UserID int output
AS
BEGIN
SELECT COUNT (*) FROM Customer Where UserID= @UserID
GROUP BY UserID
set @UserID =@@ROWCOUNT
END
GO

Controller:

     public ActionResult Index()
       {
        con.Open();
        SqlCommand comm = new SqlCommand("Usp_GetCallCountByUserID", con);
        comm.CommandType = CommandType.StoredProcedure;
        comm.Parameters.Add("@UserID", SqlDbType.Int).Direction =
            ParameterDirection.Output;
        SqlDataReader reader;
        reader = comm.ExecuteReader();
        reader.Close();
        ViewBag.CountLog = comm.Parameters["@UserID"].Value.ToString();
        con.Close();

        var callCustomers = db.Registrations;
        return View(callCustomers.ToList());
    }

Body:
Don't use global variable @@ROWCOUNT

you have to save the value of COUNT(*) in your request, look code below,

CREATE proc [Usp_GetCallCountByUserID]
    @UserID int,
    @RowCount int output
    AS
    BEGIN
    SELECT @RowCount = COUNT (*) FROM Customer Where UserID= @UserID
    GROUP BY UserID
    END
    GO


问:
Why my output is 3 i need an explaination
There's my code

```<code>num = 0
for i in range(5, 0 ,-1):
    num += i > num

print(num)
</code>```

and this is the output i got

```<code>3
</code>```

Who's know it please, explain it clearly

答:
adding a print statement in the loop:

```<code>num = 0
for i in range(5, 0, -1):
    print(num, i, i > num, int(i > num))
    num += i > num

print(num)
</code>```

gives:

```<code># num, i, i > num, int(i > num)
  0    5  True     1
  1    4  True     1
  2    3  True     1
  3    2  False    0
  3    1  False    0
</code>```

i > num is a boolean... True is just (a thin wrapper over) 1; False is 0.

Body:
There's my code

num = 0
for i in range(5, 0 ,-1):
    num += i > num

print(num)

and this is the output i got

3

Who's know it please, explain it clearly

Body:
adding a print statement in the loop:

num = 0
for i in range(5, 0, -1):
    print(num, i, i > num, int(i > num))
    num += i > num

print(num)

gives:

# num, i, i > num, int(i > num)
  0    5  True     1
  1    4  True     1
  2    3  True     1
  3    2  False    0
  3    1  False    0

i > num is a boolean... True is just (a thin wrapper over) 1; False is 0.


问:
Why does Eclipse + ADT plugin keep the CPU at 100%
The second I open up layout.xml file from a simple skeleton app in Eclipse example plugin, the cpu usage locks up to 25% IE. 1 full core. and it's been on like this for the last 30minutes I wanted to let him run a longer time because I thought it is working something in the background but it just keeps doing that.

I've tested this on 2computers so far and the setup is
install Android SDK,
install Eclipse IDE for Java Developers,
install ADT plugin: http://dl-ssl.google.com/android/eclipse/
open new project, select a skeleton project for Android 2.3.3
and just open the layout skeleton activity and perhaps change to android 2.3.3 in the upper right corner and maybe setup to theme.black.noTitleBar.Fullscreen.

And now your processor should be hitting 100% ( on one core ) and should be locked like that from now on.

Is there any solution to this issue, because at home I only have 1 core and I can not work on anything.

Does any one have any clue as to why this is happening ?
http://my.jetscreenshot.com/demo/20110517-gbr8-201kb

答:
Start Eclipse with -Dcom.sun.management.jmxremote (put it into eclipse.ini or start eclipse.exe with this option).

When Eclipse runs, start jconsole and look at the thread dump to see which thread hogs the CPU. It's the one which isn't WAITING. File a bug report.

ContentLicense: CC BY-SA 3.0


问:
Magento 2 Category Page Show Error Casue of SKU has " conflict with JS
Bellow Is the code where SKU has the issue, Let me know How to fix this issue. I didn't find any code online to fix it. Magento 2 Category Page Show Error Casue of SKU has " conflict with JS.</p>

```<code> {
            "[data-role=tocart-form], .form.map.checkout": {
                "catalogAddToCart": {
                    "product_sku": "8" Tested Product "
                }
            }
        }
</code>```

答:
$_item replace with you $product or $_product.

```<code><script type="text/x-magento-init">
{
    "[data-role=tocart-form], .form.map.checkout": {
        "catalogAddToCart": {
            "product_sku": "<?php echo  /* @NoEscape */
                    $_item->getSku() ?>"
        }
    }
}
</script>
</code>```

hope this help you. : thankx

Body:
Bellow Is the code where SKU has the issue, Let me know How to fix this issue. I didn't find any code online to fix it. Magento 2 Category Page Show Error Casue of SKU has " conflict with JS.

 {
            "[data-role=tocart-form], .form.map.checkout": {
                "catalogAddToCart": {
                    "product_sku": "8" Tested Product "
                }
            }
        }

Body:
$_item replace with you $product or $_product.

<script type="text/x-magento-init">
{
    "[data-role=tocart-form], .form.map.checkout": {
        "catalogAddToCart": {
            "product_sku": "<?php echo  /* @NoEscape */
                    $_item->getSku() ?>"
        }
    }
}
</script>

hope this help you. : thankx


问:
Adding Gluon UI library to a JavaFX Desktop application
I am working on a desktop application using JavaFX, FXMLs (using Scene Builder) and JDBC on IntelliJ IDEA Ultimate.
I added Gluon library to the Scene Builder successfully but when I exported the FXML file to IntelliJ it did not recognize the Gluon components, the problem obviously is adding Gluon Library to IntelliJ which I couldn't do.
Question is, How to add Gluon library to IntelliJ? I checked several forums and I didn't figure it out.</p>

答:
To use Gluon Mobile classes from the com.gluonhq.charm.glisten.control package, for example, Avatar and AutoCompleteTextField you have to include the Charm Glisten dependency from the Gluon Nexus repository:

```<code><dependencies>
  <dependency>
    <groupId>com.gluonhq</groupId>
    <artifactId>charm-glisten</artifactId>
    <version>6.0.2</version>
  </dependency>
</dependencies>

<repositories>
  <repository>
    <id>gluon-nexus-repository</id>
    <url>http://nexus.gluonhq.com/nexus/content/repositories/releases/</url>
  </repository>
</repositories>
</code>```

Body:
To use Gluon Mobile classes from the com.gluonhq.charm.glisten.control package, for example, Avatar and AutoCompleteTextField you have to include the Charm Glisten dependency from the Gluon Nexus repository:

<dependencies>
  <dependency>
    <groupId>com.gluonhq</groupId>
    <artifactId>charm-glisten</artifactId>
    <version>6.0.2</version>
  </dependency>
</dependencies>

<repositories>
  <repository>
    <id>gluon-nexus-repository</id>
    <url>http://nexus.gluonhq.com/nexus/content/repositories/releases/</url>
  </repository>
</repositories>


问:
How to fill out multi-field activity via other activities?
I have a multi-field activity (MainActivity)
To fill out these fields, I need to switch to another activity (FirstActivity), select some data there and go back (to MainActivity).
Then I need to go to another activity (SecondActivity), select some data there and go back (to MainActivity).
In the end, I should be on the filled MainActivity with the first and second data.

It occurred to me to set static fields, but this is a bad solution.
To drag all the data in Intent through all the activities is also an ugly solution.

Are there any other options how can I do this?

答:
You can user shared preferences to store temporary data on device from every activity and on the final activity retrieve all data from Shared Preferences and fill-out all the fields and at the end after using that data, remove all data from shared preferences.That's it.

You can also use sqlite database for this purpose.

Here is a tutorial for shared preferences :

https://www.tutorialspoint.com/android/android_shared_preferences.htm


问:
Error While running the SSIS Package through Control-M
I have 1 SSIS package with simple Data flow task to read the data from CSV file and load it into the SQL server.
We have 3 servers :
1 unix server for control-M (RedHat Server7.6)
1 windows server for SQL database and SSIS
1 Window server for storing the files.

When we run the package from Control-M then it is not able to read the files from file server, but when we run the package from SQL Agent in SSIS then it is executing successfully.

I have already given the permission of file server folder to the account that we are using in Control-M connection profile. PFB Error for reference.

Data Flow Task:Error: Cannot open the datafile "Location".

Data Flow Task:Error: Flat File Source failed the pre-execute phase
  and returned error code 0xC020200E.

答: Do you have Control-M for Databases installed on the Agent? That is often a better way to run SSIS.</p>


问:
How to fix the error `found no layout file for "HTML" for "page"` in Hugo CMS?
I recently imported content from my WordPress page into Hugo. When I run hugo serve I get following error messages:

```<code>WARN 2020/02/17 20:51:06 found no layout file for "HTML" for "page": You should create a template file which matches Hugo Layouts Lookup Rules for this combination.
</code>```

The page in question starts like this:

```<code>---
linktitle: "The Title of the Post"
title: "The Title of the Post"
author: "Franz Drollig"
type: post
date: 2020-01-09T14:41:55+00:00
url: /the-title-of-post/
categories:
  - Uncategorized
weight: 10

---

This is the content of the post. This is the second sentence of the post.
</code>```

It is located in mysite/content/posts/YYYY-MM-DD-title.md.

The layouts directory is empty. However, the themes directory contains the book theme. This theme is also configured in the config.toml.

Another post, starting like shown below, is rendered correctly.

```<code>---
author: "Michael Henderson"
date: 2014-09-28
linktitle: Creating a New Theme
menu:
  main:
    parent: tutorials
next: /tutorials/github-pages-blog
prev: /tutorials/automated-deployments
title: Creating a New Theme
weight: 10
---

## Introduction
</code>```

Why is my post not rendered properly? How can I fix it?

答:
I don't have experience with Hugo, but figure I'd comment if it helps to point you in the right direction.

The front matter seems very different between those two documents. I'm thinking the type: post is probably the culprit.

What happens if you remove the post front matter altogether?

These links may also be helfpul:

Front Matter | Hugo

Hugo's Lookup Order | Hugo

Body:
I recently imported content from my WordPress page into Hugo. When I run hugo serve I get following error messages:

WARN 2020/02/17 20:51:06 found no layout file for "HTML" for "page": You should create a template file which matches Hugo Layouts Lookup Rules for this combination.

The page in question starts like this:

---
linktitle: "The Title of the Post"
title: "The Title of the Post"
author: "Franz Drollig"
type: post
date: 2020-01-09T14:41:55+00:00
url: /the-title-of-post/
categories:
  - Uncategorized
weight: 10

---

This is the content of the post. This is the second sentence of the post.

It is located in mysite/content/posts/YYYY-MM-DD-title.md.

The layouts directory is empty. However, the themes directory contains the book theme. This theme is also configured in the config.toml.

Another post, starting like shown below, is rendered correctly.

---
author: "Michael Henderson"
date: 2014-09-28
linktitle: Creating a New Theme
menu:
  main:
    parent: tutorials
next: /tutorials/github-pages-blog
prev: /tutorials/automated-deployments
title: Creating a New Theme
weight: 10
---

## Introduction

Why is my post not rendered properly? How can I fix it?


问:
Convert NSMutableAttributedString to NSString
Can we not convert NSMutableAttributedString to NSString?

I have two NSMutableAttributedStrings and I am appending the 2nd string onto 1st as below:

[string1 appendAttributedString:string2];

Since I have to display string1 on a label I do:

```<code>self.label1.text = (NSString *)string1;
</code>```

I am getting "unrecognized selector sent to instance" error.

Am I doing anything wrong here? Isn't this the correct way to assign a NSMutableAttributedString to text property of a label?

答:
NSAttributtedString have a property string and it is read only property you can not change it. </p>

```<code>NSAttributtedString* attributtedString;
NSString* plainString = attributtedString.string;
</code>```

Body:
Can we not convert NSMutableAttributedString to NSString?

I have two NSMutableAttributedStrings and I am appending the 2nd string onto 1st as below:

[string1 appendAttributedString:string2];

Since I have to display string1 on a label I do:

self.label1.text = (NSString *)string1;

I am getting "unrecognized selector sent to instance" error.

Am I doing anything wrong here? Isn't this the correct way to assign a NSMutableAttributedString to text property of a label?

Body:
NSAttributtedString have a property string and it is read only property you can not change it.

NSAttributtedString* attributtedString;
NSString* plainString = attributtedString.string;


问:
Xcode 11.3 cannot set target for iOS 13.3, i.e. the option doesn't exist
I upgraded to Xcode 11.3 and Catalina 10.15.2 recently. The release note stated

Xcode 11.3 includes SDKs for iOS 13.3

<s>However, the iOS 13.3 deployment target, as well as the simulator, doesn't exist.</s>

Edit:
The iOS 13.3 deployment target doesn't exist.

Is it a bug? Or a problem of my installation? Is there a workaround?

Edit: A Link to the apple developer forum Xcode 11.3: can't select deployment target 13.3 https://forums.developer.apple.com/thread/126948

Additional screenshot:

答:
If you are on Catalina download Xcode Beta11.4, it supports 13.3.1

If you are on Mojave you will not be able to install Xcode Beta11.4 but there's still a way.
You can extract the DeviceSupport + SDK files from Beta11.4 copy them in Xcode 11.3
Do not forget the SDK files, without it it didn't work for me.

-M


问:
Generated begin-end blocks must be named
I am compiling an SNN simulator named "ODIN" in Xilinx. for Generate block I get this error but I think there is nothing wrong with this block. Can you help me with this?

```<code>'''
genvar i;
generate
    for (i=0; i<8; i=i+1) begin

        sdsp_update #(
            .WIDTH(3)
        ) sdsp_update_gen (
            // Inputs
                // General
            .SYN_PRE(CTRL_PRE_EN[i] & (SPI_UPDATE_UNMAPPED_SYN | SYNARRAY_RDATA[(i<<2)+3])),
            .SYN_BIST_REF(CTRL_BIST_REF),
                // From neuron
            .V_UP(NEUR_V_UP_int[i]),
            .V_DOWN(NEUR_V_DOWN_int[i]),
                // From SRAM
            .WSYN_CURR(SYNARRAY_RDATA[(i<<2)+3:(i<<2)]),

            // Output
            .WSYN_NEW(SYNARRAY_WDATA_int[(i<<2)+3:(i<<2)])
        );
    end
endgenerate
</code>```

I get these errors:

Generated begin-end blocks must be named

Illegal redeclaration of ''

答:
Some compilers wants to have a name when generating logic. This name is taken from the name of the begin-end block.
Try this:</p>

```<code>'''
genvar i;
generate
    for (i=0; i<8; i=i+1)
    begin : sdsp_gen // <<< Name for begin/end block

        sdsp_update #(
            .WIDTH(3)
        ) sdsp_update_gen (
            // Inputs
                // General
            .SYN_PRE(CTRL_PRE_EN[i] & (SPI_UPDATE_UNMAPPED_SYN | SYNARRAY_RDATA[(i<<2)+3])),
            .SYN_BIST_REF(CTRL_BIST_REF),
                // From neuron
            .V_UP(NEUR_V_UP_int[i]),
            .V_DOWN(NEUR_V_DOWN_int[i]),
                // From SRAM
            .WSYN_CURR(SYNARRAY_RDATA[(i<<2)+3:(i<<2)]),

            // Output
            .WSYN_NEW(SYNARRAY_WDATA_int[(i<<2)+3:(i<<2)])
        );
    end
endgenerate
</code>```

Body:
I am compiling an SNN simulator named "ODIN" in Xilinx. for Generate block I get this error but I think there is nothing wrong with this block. Can you help me with this?

'''
genvar i;
generate
    for (i=0; i<8; i=i+1) begin

        sdsp_update #(
            .WIDTH(3)
        ) sdsp_update_gen (
            // Inputs
                // General
            .SYN_PRE(CTRL_PRE_EN[i] & (SPI_UPDATE_UNMAPPED_SYN | SYNARRAY_RDATA[(i<<2)+3])),
            .SYN_BIST_REF(CTRL_BIST_REF),
                // From neuron
            .V_UP(NEUR_V_UP_int[i]),
            .V_DOWN(NEUR_V_DOWN_int[i]),
                // From SRAM
            .WSYN_CURR(SYNARRAY_RDATA[(i<<2)+3:(i<<2)]),

            // Output
            .WSYN_NEW(SYNARRAY_WDATA_int[(i<<2)+3:(i<<2)])
        );
    end
endgenerate

I get these errors:

Generated begin-end blocks must be named

Illegal redeclaration of ''

Body:
Some compilers wants to have a name when generating logic. This name is taken from the name of the begin-end block.
Try this:

'''
genvar i;
generate
    for (i=0; i<8; i=i+1)
    begin : sdsp_gen // <<< Name for begin/end block

        sdsp_update #(
            .WIDTH(3)
        ) sdsp_update_gen (
            // Inputs
                // General
            .SYN_PRE(CTRL_PRE_EN[i] & (SPI_UPDATE_UNMAPPED_SYN | SYNARRAY_RDATA[(i<<2)+3])),
            .SYN_BIST_REF(CTRL_BIST_REF),
                // From neuron
            .V_UP(NEUR_V_UP_int[i]),
            .V_DOWN(NEUR_V_DOWN_int[i]),
                // From SRAM
            .WSYN_CURR(SYNARRAY_RDATA[(i<<2)+3:(i<<2)]),

            // Output
            .WSYN_NEW(SYNARRAY_WDATA_int[(i<<2)+3:(i<<2)])
        );
    end
endgenerate


问:
Flow-based programming for windows?

I have been using Automate for Android (picture above) for a while and wonder if Windows has similar software.
I find flowcharts to be really helpful in organising each action for automation.

Currently I use a combination of CMD, Powershell, Autohotkey, AutoIt scripts but would like to know if there is one like Automate.

答:
As mentioned in my comment. Give Node-RED a try.

https://nodered.org/docs/getting-started/windows

https://flows.nodered.org/node/node-red-contrib-powershell
https://flows.nodered.org/node/node-red-contrib-pythonshell

See exec  Node.
And so on.

Title: Flow-based programming for windows?


问:
ngClass directive to use with ngFor
I have some list elements, which I am rendering using *ngFor directive. However, some part of the list items text should be bold according to the specs. I tried to do this with the [ngClass]="'strong'" when strong is the css class I need to add some portion on the text. When I run the application the result was the whole text become bold. Below is the screenshot for your better understanding.

The requirement is to make the dollar part bold only. I am new to the angular development. Any help would be greatly appreciated.

```<code><ul>
      <li *ngFor="let text of income; let i = index" [ngClass]="'strong'">{{text.text}}</li>
    </ul>
income = [
    {text:'Your Annual Income:* $1,316,422'},
    {text:'Your Monthly Income: $109,702'}
  ];
</code>```

答:
As long as you're sure it's only about the first letter, you don't need Angular. Nor even JavaScript. There's a pure CSS solution.

.first-letter-bold::first-letter {
  font-weight: 900;
  font-size: 110%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul>
  <li class="first-letter-bold">$1,316,422</li>
  <li class="first-letter-bold">$1,316,422</li>
</ul></code>```

Title: ngClass directive to use with ngFor

Body:
I have some list elements, which I am rendering using *ngFor directive. However, some part of the list items text should be bold according to the specs. I tried to do this with the [ngClass]="'strong'" when strong is the css class I need to add some portion on the text. When I run the application the result was the whole text become bold. Below is the screenshot for your better understanding.

The requirement is to make the dollar part bold only. I am new to the angular development. Any help would be greatly appreciated.

{{text.text}}

income = [
    {text:'Your Annual Income:* $1,316,422'},
    {text:'Your Monthly Income: $109,702'}
  ];

Body:
As long as you're sure it's only about the first letter, you don't need Angular. Nor even JavaScript. There's a pure CSS solution.

.first-letter-bold::first-letter {
  font-weight: 900;
  font-size: 110%;
}

<ul>
  <li class="first-letter-bold">$1,316,422</li>
  <li class="first-letter-bold">$1,316,422</li>
</ul>


问:
Why do I see jerky animation when using this UIView animation block?
I have a a tab bar that is made in the application delegate. By calling an action form a button click from one of the views loaded from the tab bar, I open the help screen but there is a jerking motion after loading.

forgive me for speaking informally..I have been picking my brain for the past few hours trying to figure this out..

```<code>-(void)flipToHelp {
 HelpViewController *helpVariable = [[HelpViewController alloc] initWithNibName:@"HelpView" bundle:nil];
 [self setHelpViewController:helpVariable];
 [UIView beginAnimations:@"flipview" context:nil];
 [UIView setAnimationDuration:0.5];
 [UIView setAnimationCurve:UIViewAnimationCurveLinear];
 [UIView setAnimationTransition:UIViewAnimationTransitionFlipFromLeft
 forView:_window cache:YES];

[_window removeFromSuperview];
[helpVariable release];
self.window.rootViewController = self.HelpViewController;
[UIView commitAnimations];
}
</code>```

答:
Just to reiterate from the comment thread, you shouldn't be removing the window from its superview (it doesn't technically have a superview, so it's probably causing problems).  <s>And setting the window's rootViewController property should swap out the view hierarchies,</s> Apparently the jerkiness comes from changing the window's rootViewController property, so maybe the solution is to avoid using that property.  Here's what I think should be enough to accomplish this:

```<code>-(void)flipToHelp {
     HelpViewController *helpVariable = [[HelpViewController alloc] initWithNibName:@"HelpView" bundle:nil];
     [UIView beginAnimations:@"flipview" context:nil];
     [UIView setAnimationDuration:0.5];
     [UIView setAnimationTransition:UIViewAnimationTransitionFlipFromLeft forView:_window cache:YES];
    [self.tabBarController removeFromSuperview];
    [_window addSubview:helpVariable];
    [UIView commitAnimations];
}
</code>```

Body:
I have a a tab bar that is made in the application delegate. By calling an action form a button click from one of the views loaded from the tab bar, I open the help screen but there is a jerking motion after loading.

forgive me for speaking informally..I have been picking my brain for the past few hours trying to figure this out..

-(void)flipToHelp {
 HelpViewController *helpVariable = [[HelpViewController alloc] initWithNibName:@"HelpView" bundle:nil];
 [self setHelpViewController:helpVariable];
 [UIView beginAnimations:@"flipview" context:nil];
 [UIView setAnimationDuration:0.5];
 [UIView setAnimationCurve:UIViewAnimationCurveLinear];
 [UIView setAnimationTransition:UIViewAnimationTransitionFlipFromLeft
 forView:_window cache:YES];

[_window removeFromSuperview];
[helpVariable release];
self.window.rootViewController = self.HelpViewController;
[UIView commitAnimations];
}

Body:
Just to reiterate from the comment thread, you shouldn't be removing the window from its superview (it doesn't technically have a superview, so it's probably causing problems).  <s>And setting the window's rootViewController property should swap out the view hierarchies,</s> Apparently the jerkiness comes from changing the window's rootViewController property, so maybe the solution is to avoid using that property.  Here's what I think should be enough to accomplish this:

-(void)flipToHelp {
     HelpViewController *helpVariable = [[HelpViewController alloc] initWithNibName:@"HelpView" bundle:nil];
     [UIView beginAnimations:@"flipview" context:nil];
     [UIView setAnimationDuration:0.5];
     [UIView setAnimationTransition:UIViewAnimationTransitionFlipFromLeft forView:_window cache:YES];
    [self.tabBarController removeFromSuperview];
    [_window addSubview:helpVariable];
    [UIView commitAnimations];
}


问:
window.WebChat.createCognitiveServicesSpeechServicesPonyfillFactory(...).then is not a function
I'm using webchat-es5.js and its throwing error like window.WebChat.createCognitiveServicesSpeechServicesPonyfillFactory(...).then is not a function. Need IE support also using es5.js.

window.fetch('https://webchat-mockbot.azurewebsites.net/directline/token', { method: 'POST' })
    .then(function (res) {
      return res.json();
    })
  .then(function (json) {
  const token = json.token;

  window.fetch('https://webchat-mockbot.azurewebsites.net/speechservices/token', { method: 'POST' })
    .then(function (res) {
    return res.json();
  })
    .then(function (json) {
    const region = json.region;
    const authorizationToken = json.token;

    window.WebChat.createCognitiveServicesSpeechServicesPonyfillFactory({ authorizationToken: authorizationToken , region: region })
      .then(function (webSpeechPonyfillFactory) {
      window.WebChat.renderWebChat({
        directLine: window.WebChat.createDirectLine({ token: token }),
        webSpeechPonyfillFactory: webSpeechPonyfillFactory
      }, document.getElementById('webchat'));

      document.querySelector('#webchat > *').focus();
    });
  });
});
```

Thanks in advance.

答:
This is the setup that is working for me. I run a server locally to fetch the actual tokens. This way I don't need to include any secrets in the client.

window.fetch( 'http://localhost:3500/directline/token', { method: 'POST' } )
    .then( function ( res ) {
      return res.json();
    } )
    .then( function ( res ) {
      let token = res.token;
      window.fetch( 'http://localhost:3500/speechservices/token', { method: 'POST' } )
        .then( function ( res ) {
          return res.json();
        } )
        .then( function ( res ) {
          let authorizationToken = res.authorizationToken;
          window.WebChat.renderWebChat( {
            directLine: window.WebChat.createDirectLine( {
              token: token,
              webSocket: true
            } ),
            webSpeechPonyfillFactory: window.WebChat.createCognitiveServicesSpeechServicesPonyfillFactory( {
              region: 'westus2',
              authorizationToken: authorizationToken
            } )
          }, document.getElementById( 'webchat' ) );
        });
    } );
```

Hope of help!

Body:
I'm using webchat-es5.js and its throwing error like window.WebChat.createCognitiveServicesSpeechServicesPonyfillFactory(...).then is not a function. Need IE support also using es5.js.

window.fetch('https://webchat-mockbot.azurewebsites.net/directline/token', { method: 'POST' })
    .then(function (res) {
      return res.json();
    })
  .then(function (json) {
  const token = json.token;

  window.fetch('https://webchat-mockbot.azurewebsites.net/speechservices/token', { method: 'POST' })
    .then(function (res) {
    return res.json();
  })
    .then(function (json) {
    const region = json.region;
    const authorizationToken = json.token;

    window.WebChat.createCognitiveServicesSpeechServicesPonyfillFactory({ authorizationToken: authorizationToken , region: region })
      .then(function (webSpeechPonyfillFactory) {
      window.WebChat.renderWebChat({
        directLine: window.WebChat.createDirectLine({ token: token }),
        webSpeechPonyfillFactory: webSpeechPonyfillFactory
      }, document.getElementById('webchat'));

      document.querySelector('#webchat > *').focus();
    });
  });
});

Thanks in advance.

Body:
This is the setup that is working for me. I run a server locally to fetch the actual tokens. This way I don't need to include any secrets in the client.

window.fetch( 'http://localhost:3500/directline/token', { method: 'POST' } )
    .then( function ( res ) {
      return res.json();
    } )
    .then( function ( res ) {
      let token = res.token;
      window.fetch( 'http://localhost:3500/speechservices/token', { method: 'POST' } )
        .then( function ( res ) {
          return res.json();
        } )
        .then( function ( res ) {
          let authorizationToken = res.authorizationToken;
          window.WebChat.renderWebChat( {
            directLine: window.WebChat.createDirectLine( {
              token: token,
              webSocket: true
            } ),
            webSpeechPonyfillFactory: window.WebChat.createCognitiveServicesSpeechServicesPonyfillFactory( {
              region: 'westus2',
              authorizationToken: authorizationToken
            } )
          }, document.getElementById( 'webchat' ) );
        });
    } );

Hope of help!


问:
R function/loop to get column wise values
```<code>GT  VB  WM
23  34  28
34  27  33
    44  46
    54
</code>```

I have a data like above in a csv file.I need a R script to retrieve by column wise values either by loop or function when passing arguments as a variable name.Ex. When I type GT I should get relevant values without NA like

```<code>GT
23 34
</code>```

答:
Based on all the information you have given, the following R commands (an "R script") will do this for you. I'm assuming that the CSV file contains 3 columns called GT, VB and WM in the first row and there are 4 rows of data starting in row 2. I'm also assuming that the file is in fact a comma separated file format, meaning that the columns (including the header row) is separated by commas.

```<code>df <- read.csv("myfile.csv")
</code>```

If you don't want NA values to appear whenever you type the name of the column, you'll have to remove the NA from each element of the data frame, saving the results as a list (since a data frame cannot have columns of unequal length), using either lapply or sapply.

```<code>df.list <- sapply(df, FUN=function(x) x[!is.na(x)])
</code>```

And then attach to it:

```<code>attach(df.list)
</code>```

Typing the names of the columns should return the original values with NA omitted.

```<code>GT
[1] 23 34

VB
[1] 34 27 44 54

WM
[1] 28 33 46
</code>```

When you are finished, detach from this modified R object as it is good practice to do so.

```<code>detach(df.list) # Good practice
</code>```

And this does exactly what you said. No more and no less.

data

```<code>library(tibble)
df <- tribble(~GT,  ~VB,  ~WM,
23,  34,  28,
34,  27,  33,
NA,  44,  46,
NA,  54,  NA)
</code>```

Body:
GT  VB  WM
23  34  28
34  27  33
    44  46
    54

I have a data like above in a csv file.I need a R script to retrieve by column wise values either by loop or function when passing arguments as a variable name.Ex. When I type GT I should get relevant values without NA like

GT
23 34

Body:
Based on all the information you have given, the following R commands (an "R script") will do this for you. I'm assuming that the CSV file contains 3 columns called GT, VB and WM in the first row and there are 4 rows of data starting in row 2. I'm also assuming that the file is in fact a comma separated file format, meaning that the columns (including the header row) is separated by commas.

df <- read.csv("myfile.csv")

If you don't want NA values to appear whenever you type the name of the column, you'll have to remove the NA from each element of the data frame, saving the results as a list (since a data frame cannot have columns of unequal length), using either lapply or sapply.

df.list <- sapply(df, FUN=function(x) x[!is.na(x)])

And then attach to it:

attach(df.list)

Typing the names of the columns should return the original values with NA omitted.

GT
[1] 23 34

VB
[1] 34 27 44 54

WM
[1] 28 33 46

When you are finished, detach from this modified R object as it is good practice to do so.

detach(df.list) # Good practice

And this does exactly what you said. No more and no less.

data

library(tibble)
df <- tribble(~GT,  ~VB,  ~WM,
23,  34,  28,
34,  27,  33,
NA,  44,  46,
NA,  54,  NA)


问:
jquery dialog: confirm the click on a submit button
I'm trying to do a confirm dialog using jquery, but the form doesn't get submitted at all, this is what I got:</p>

```<code>    <script type="text/javascript">
    var currentForm;
    $(function() {
        $("#dialog-confirm").dialog({
            resizable: false,
            height: 140,
            modal: true,
            autoOpen: false,
            buttons: {
                'Delete all items': function() {
                    currentForm.submit();
                    $(this).dialog('close');
                },
                Cancel: function() {
                    $(this).dialog('close');
                }
            }
        });
    });

    function ask() {
        currentForm = $(this).closest('form');
        $("#dialog-confirm").dialog('open');
    }
</script>
<form ... >
    <input type="submit" value="delete" onclick="ask();return false;" />
</form>
</code>```

答:
For a form with GET method as I need also button's value in query string and avoid to lost it at form submit

I used event.preventDefault() and added button's name and value as  hidden <input> field in JS script

JS script

```<code>$( function() {
  //Add function to all document's html tag with class="delete"
  $(document).on("click", ".delete", function(event) {

    event.preventDefault(); //Stop submitting form and wait for a "yes" or "no"

    $( "#dialog-confirm" ).dialog({
      draggable: false,
      resizable: false,
      height: "auto",
      width: 400,
      modal: true,
      buttons: {
        "Delete items": function() {
          $( this ).dialog( "close" );

          //Prevent to lost button's value in query string at form submit
          //Need to add a hidden <input> field with the same button's name and value
          $('<input />').attr('type', 'hidden')
                        .attr('name', 'action')
                        .attr('value', 'delete')
                        .appendTo('#myform');

          $('#myform').submit(); //Ok proceed with form submit

        },
        Cancel: function() {
          $( this ).dialog( "close" ); //Do nothing, close window.
        }
      }
    });
  });
});
</code>```

Form template

```<code><div style="display:none" id="dialog-confirm" title="Empty the recycle bin?">
  <p><span class="ui-icon ui-icon-alert" style="float:left; margin:12px 12px 20px 0;"></span>These items will be permanently deleted and cannot be recovered. Are you sure?</p>
</div>

<form id="myform" action="#myurl" method="get">
  <label for="fname">First name:</label><br>
  <input type="text" id="fname" name="fname" value="John"><br>
  <label for="lname">Last name:</label><br>
  <input type="text" id="lname" name="lname" value="Doe"><br><br>
  <input class="delete" type="submit" name="action" value="delete">
</form>
</code>```

<!doctype html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>jQuery UI Dialog - Modal confirmation</title>
  <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
  <link rel="stylesheet" href="/resources/demos/style.css">

These items will be permanently deleted and cannot be recovered. Are you sure?

<form id="myform" action="#myurl" method="get">
  First name:

  <input type="text" id="fname" name="fname" value="John">

  Last name:

  <input type="text" id="lname" name="lname" value="Doe">

  <input class="delete" type="submit" name="action" value="delete">
</form>

```

ContentLicense: CC BY-SA 2.5

Body:
I'm trying to do a confirm dialog using jquery, but the form doesn't get submitted at all, this is what I got:

<form ... >
    <input type="submit" value="delete" onclick="ask();return false;" />
</form>

Body:
For a form with GET method as I need also button's value in query string and avoid to lost it at form submit

I used event.preventDefault() and added button's name and value as  hidden <input> field in JS script

JS script

$( function() {
  //Add function to all document's html tag with class="delete"
  $(document).on("click", ".delete", function(event) {

    event.preventDefault(); //Stop submitting form and wait for a "yes" or "no"

    $( "#dialog-confirm" ).dialog({
      draggable: false,
      resizable: false,
      height: "auto",
      width: 400,
      modal: true,
      buttons: {
        "Delete items": function() {
          $( this ).dialog( "close" );

          //Prevent to lost button's value in query string at form submit
          //Need to add a hidden <input> field with the same button's name and value
          $('<input />').attr('type', 'hidden')
                        .attr('name', 'action')
                        .attr('value', 'delete')
                        .appendTo('#myform');

          $('#myform').submit(); //Ok proceed with form submit

        },
        Cancel: function() {
          $( this ).dialog( "close" ); //Do nothing, close window.
        }
      }
    });
  });
});

Form template

<div style="display:none" id="dialog-confirm" title="Empty the recycle bin?">
  <p><span class="ui-icon ui-icon-alert" style="float:left; margin:12px 12px 20px 0;"></span>These items will be permanently deleted and cannot be recovered. Are you sure?</p>
</div>

<form id="myform" action="#myurl" method="get">
  <label for="fname">First name:</label><br>
  <input type="text" id="fname" name="fname" value="John"><br>
  <label for="lname">Last name:</label><br>
  <input type="text" id="lname" name="lname" value="Doe"><br><br>
  <input class="delete" type="submit" name="action" value="delete">
</form>

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>jQuery UI Dialog - Modal confirmation</title>
  <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
  <link rel="stylesheet" href="/resources/demos/style.css">
  <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
  <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
  <script>
    $( function() {
      $(document).on("click", ".delete", function(event) {

        event.preventDefault(); //Stop submitting form and wait for a "yes" or "no"

        $( "#dialog-confirm" ).dialog({
          draggable: false,
          resizable: false,
          height: "auto",
          width: 400,
          modal: true,
          buttons: {
            "Delete items": function() {
              $( this ).dialog( "close" );

              //Prevent to lost button's value in query string at form submit
              //Need to add a hidden <input> field with the same button's name and value
              $('<input />').attr('type', 'hidden')
                            .attr('name', 'action')
                            .attr('value', 'delete')
                            .appendTo('#myform');

              $('#myform').submit(); //Ok proceed with form submit

            },
            Cancel: function() {
              $( this ).dialog( "close" ); //Do nothing, close window.
            }
          }
        });
      });
    });
  </script>
</head>
<body>

<div style="display:none" id="dialog-confirm" title="Empty the recycle bin?">
  <p><span class="ui-icon ui-icon-alert" style="float:left; margin:12px 12px 20px 0;"></span>These items will be permanently deleted and cannot be recovered. Are you sure?</p>
</div>

<form id="myform" action="#myurl" method="get">
  <label for="fname">First name:</label><br>
  <input type="text" id="fname" name="fname" value="John"><br>
  <label for="lname">Last name:</label><br>
  <input type="text" id="lname" name="lname" value="Doe"><br><br>
  <input class="delete" type="submit" name="action" value="delete">
</form>

</body>
</html>


问:
Select Text in DIV with specific range using JavaScript
I want to select the text inside
 with a specific range ex.

```<code><div>This is a sample text.</div>
selectText(3, 12);
</code>```

it will select text from s to m(s is a sam) inside div and the user can copy the text by pressing ctrl + c

答:
let element = document.querySelector('div');

selectText(element, 20, 35);

function selectText(node, start, end) {
  let text = node.childNodes[0];
  let range = new Range();
  let selection = document.getSelection();
  range.setStart(text, start);
  range.setEnd(text, end);
  selection.removeAllRanges();
  selection.addRange(range);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>Text not to select. Text to select. Text not to select.</div></code>```

Body:
I want to select the text inside
 with a specific range ex.

This is a sample text.

selectText(3, 12);

it will select text from s to m(s is a sam) inside div and the user can copy the text by pressing ctrl + c

Body:
let element = document.querySelector('div');

selectText(element, 20, 35);

function selectText(node, start, end) {
  let text = node.childNodes[0];
  let range = new Range();
  let selection = document.getSelection();
  range.setStart(text, start);
  range.setEnd(text, end);
  selection.removeAllRanges();
  selection.addRange(range);
}

<div>Text not to select. Text to select. Text not to select.</div>


问:
What is the equivalent of ActionBar in earlier sdk versions?
Since the ActionBar is available only in Android 3.0 and later, what is a good way to implement ActionBar-like widget in earlier sdk versions? I am looking to do this programmatically, if that helps. </p>

答: Use android-actionbar or GreenDroid.</p>

Body: Use android-actionbar or GreenDroid.


问:
Pandas parallel apply with koalas (pyspark)
I'm new to Koalas (pyspark), and I was trying to utilize Koalas for parallel apply, but it seemed like it was using a single core for the whole operation (correct me if I'm wrong) and ended up using dask for parallel apply (using map_partition) which worked pretty well.

However, I would like to know if there's a way to utilize Koalas for parallel apply.

I used basic codes for operation like below.

```<code>import pandas as pd
import databricks.koalas as ks

my_big_data = ks.read_parquet('my_big_file') # file is single partitioned parquet file

my_big_data['new_column'] = my_big_data['string_column'].apply(my_prep) # my_prep does stirng operations

my_big_data.to_parquet('my_big_file_modified') # for Koalas does lazy evaluation

</code>```

答:
I found a link that discuss this problem. https://github.com/databricks/koalas/issues/1280

If the number of rows that are being applied by function is less than 1,000 (default value), then pandas dataframe will be called to do the operation.

The user defined function above my_prep is applied to each row, so single core pandas was being used.

In order to force it to work in pyspark (parallel) manner, user should modify the configuration as below.

```<code>import databricks.koalas as ks
ks.set_option('compute.default_index_type','distributed') # when .head() call is too slow
ks.set_option('compute.shortcut_limit',1) # Koalas will apply pyspark
</code>```

Also, explicitly specifying type (type hint) in the user defined function will make Koalas not to go shortcut path and will make parallel.

```<code>def my_prep(row) -> string:
  return row

kdf['my_column'].apply(my_prep)
</code>```

Body:
I'm new to Koalas (pyspark), and I was trying to utilize Koalas for parallel apply, but it seemed like it was using a single core for the whole operation (correct me if I'm wrong) and ended up using dask for parallel apply (using map_partition) which worked pretty well.

However, I would like to know if there's a way to utilize Koalas for parallel apply.

I used basic codes for operation like below.

import pandas as pd
import databricks.koalas as ks

my_big_data = ks.read_parquet('my_big_file') # file is single partitioned parquet file

my_big_data['new_column'] = my_big_data['string_column'].apply(my_prep) # my_prep does stirng operations

my_big_data.to_parquet('my_big_file_modified') # for Koalas does lazy evaluation

Body:
I found a link that discuss this problem. https://github.com/databricks/koalas/issues/1280

If the number of rows that are being applied by function is less than 1,000 (default value), then pandas dataframe will be called to do the operation.

The user defined function above my_prep is applied to each row, so single core pandas was being used.

In order to force it to work in pyspark (parallel) manner, user should modify the configuration as below.

import databricks.koalas as ks
ks.set_option('compute.default_index_type','distributed') # when .head() call is too slow
ks.set_option('compute.shortcut_limit',1) # Koalas will apply pyspark

Also, explicitly specifying type (type hint) in the user defined function will make Koalas not to go shortcut path and will make parallel.

def my_prep(row) -> string:
  return row

kdf['my_column'].apply(my_prep)


问:
Can't query data from Druid Datasource on a Hive External table
Druid cluster and Hive/Hadoop cluster are running ok individually.
We are creating a table in Hive that reads data from Druid (for ETL) purposes, however, on initial tests, we found we can't do a simple SELECT * from it followed by this error:

```<code>hive> select * from druid_hive_table;
OK
druid_hive_table.__time druid_hive_table.op_ts  druid_hive_table.op_type    druid_hive_table.pos    druid_hive_table.table
Failed with exception java.io.IOException:org.apache.hive.druid.com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of java.util.ArrayList out of START_OBJECT token
 at [Source: org.apache.hive.druid.com.metamx.http.client.io.AppendableByteArrayInputStream@656c5818; line: -1, column: 4]
Time taken: 0.449 seconds
</code>```

However, a SELECT COUNT(*) works fine!

```<code>hive> select count(*) from druid_hive_table;
OK
$f0
21409
Time taken: 0.199 seconds, Fetched: 1 row(s)
</code>```

SPECS:

DRUID EXTERNAL TABLE

```<code>SET hive.druid.broker.address.default=<host>:8082;

CREATE EXTERNAL TABLE druid_hive_table
STORED BY 'org.apache.hadoop.hive.druid.DruidStorageHandler'
TBLPROPERTIES ("druid.datasource" = "druid_datasource_name");

hive> DESCRIBE FORMATTED druid_hive_table;
OK
col_name    data_type   comment
# col_name              data_type               comment

__time                  timestamp               from deserializer
op_ts                   string                  from deserializer
op_type                 string                  from deserializer
pos                     string                  from deserializer
table                   string                  from deserializer

# Detailed Table Information
Database:               tests
Owner:                  OWNER
CreateTime:             Mon Feb 10 13:52:13 UTC 2020
LastAccessTime:         UNKNOWN
Retention:              0
Location:               <LOCATION>
Table Type:             EXTERNAL_TABLE
Table Parameters:
    COLUMN_STATS_ACCURATE   {\"BASIC_STATS\":\"true\"}
    EXTERNAL                TRUE
    druid.datasource        druid_datasource_name
    numFiles                0
    numRows                 0
    rawDataSize             0
    storage_handler         org.apache.hadoop.hive.druid.DruidStorageHandler
    totalSize               0
    transient_lastDdlTime   1581342733

# Storage Information
SerDe Library:          org.apache.hadoop.hive.druid.serde.DruidSerDe
InputFormat:            null
OutputFormat:           null
Compressed:             No
Num Buckets:            -1
Bucket Columns:         []
Sort Columns:           []
Storage Desc Params:
    serialization.format    1
Time taken: 0.144 seconds, Fetched: 37 row(s)
</code>```

For reference - Druid Supervisor Spec:

```<code>{
  "dataSchema": {
    "dataSource": "druid_datasource_name",
    "timestampSpec": {
      "column": "current_ts",
      "format": "iso",
      "missingValue": null
    },
    "dimensionsSpec": {
      "dimensions": [],
      "dimensionExclusions": [
        "current_ts"
      ]
    },
    "metricsSpec": [],
    "granularitySpec": {
      "type": "uniform",
      "segmentGranularity": "HOUR",
      "queryGranularity": {
        "type": "none"
      },
      "rollup": false,
      "intervals": null
    },
    "transformSpec": {
      "filter": null,
      "transforms": []
    }
  },
  "ioConfig": {
    "topic": "<kafka_topic>",
    "inputFormat": {
      "type": "json",
      "flattenSpec": {
        "useFieldDiscovery": true,
        "fields": []
      },
      "featureSpec": {}
    },
    "replicas": 1,
    "taskCount": 1,
    "taskDuration": "PT3600S",
    "consumerProperties": {
      "bootstrap.servers": "<bootstrap_servers>",
      "group.id": "<group_name>",
      "security.protocol": "SASL_SSL",
      "ssl.truststore.location": "<location>",
      "ssl.truststore.password": "<pass>",
      "sasl.jaas.config": "<config>",
      "sasl.mechanism": "SCRAM-SHA-512"
    },
    "pollTimeout": 100,
    "startDelay": "PT5S",
    "period": "PT30S",
    "useEarliestOffset": true,
    "completionTimeout": "PT1800S",
    "lateMessageRejectionPeriod": null,
    "earlyMessageRejectionPeriod": null,
    "lateMessageRejectionStartDateTime": null,
    "stream": "<kafka_topic>",
    "useEarliestSequenceNumber": true,
    "type": "kafka"
  },
  "tuningConfig": {
    "type": "kafka",
    "maxRowsInMemory": 1000000,
    "maxBytesInMemory": 0,
    "maxRowsPerSegment": 5000000,
    "maxTotalRows": null,
    "intermediatePersistPeriod": "PT10M",
    "basePersistDirectory": "/opt/apache-druid-0.17.0/var/tmp/druid-realtime-persist7801461398656096281",
    "maxPendingPersists": 0,
    "indexSpec": {
      "bitmap": {
        "type": "concise"
      },
      "dimensionCompression": "lz4",
      "metricCompression": "lz4",
      "longEncoding": "longs"
    },
    "indexSpecForIntermediatePersists": {
      "bitmap": {
        "type": "concise"
      },
      "dimensionCompression": "lz4",
      "metricCompression": "lz4",
      "longEncoding": "longs"
    },
    "buildV9Directly": true,
    "reportParseExceptions": false,
    "handoffConditionTimeout": 0,
    "resetOffsetAutomatically": false,
    "segmentWriteOutMediumFactory": null,
    "workerThreads": null,
    "chatThreads": null,
    "chatRetries": 8,
    "httpTimeout": "PT10S",
    "shutdownTimeout": "PT80S",
    "offsetFetchPeriod": "PT30S",
    "intermediateHandoffPeriod": "P2147483647D",
    "logParseExceptions": false,
    "maxParseExceptions": 2147483647,
    "maxSavedParseExceptions": 0,
    "skipSequenceNumberAvailabilityCheck": false,
    "repartitionTransitionDuration": "PT120S"
  },
  "type": "kafka"
}
</code>```

Thank you for the helping on resolving this issue.

答:
I've managed to solve this issue.
Updating Hive and Hadoop to version 3+ solved the issue.

It was as easy as buttering a piece of bread by using with this code:

```<code>SET hive.druid.broker.address.default=<host>:8082;

CREATE EXTERNAL TABLE druid_hive_table
STORED BY 'org.apache.hadoop.hive.druid.DruidStorageHandler'
TBLPROPERTIES ("druid.datasource" = "druid_datasource_name");
</code>```

Body:
Druid cluster and Hive/Hadoop cluster are running ok individually.
We are creating a table in Hive that reads data from Druid (for ETL) purposes, however, on initial tests, we found we can't do a simple SELECT * from it followed by this error:

hive> select * from druid_hive_table;
OK
druid_hive_table.__time druid_hive_table.op_ts  druid_hive_table.op_type    druid_hive_table.pos    druid_hive_table.table
Failed with exception java.io.IOException:org.apache.hive.druid.com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of java.util.ArrayList out of START_OBJECT token
 at [Source: org.apache.hive.druid.com.metamx.http.client.io.AppendableByteArrayInputStream@656c5818; line: -1, column: 4]
Time taken: 0.449 seconds

However, a SELECT COUNT(*) works fine!

hive> select count(*) from druid_hive_table;
OK
$f0
21409
Time taken: 0.199 seconds, Fetched: 1 row(s)

SPECS:

DRUID EXTERNAL TABLE

SET hive.druid.broker.address.default=<host>:8082;

CREATE EXTERNAL TABLE druid_hive_table
STORED BY 'org.apache.hadoop.hive.druid.DruidStorageHandler'
TBLPROPERTIES ("druid.datasource" = "druid_datasource_name");

hive> DESCRIBE FORMATTED druid_hive_table;
OK
col_name    data_type   comment
# col_name              data_type               comment

__time                  timestamp               from deserializer
op_ts                   string                  from deserializer
op_type                 string                  from deserializer
pos                     string                  from deserializer
table                   string                  from deserializer

# Detailed Table Information
Database:               tests
Owner:                  OWNER
CreateTime:             Mon Feb 10 13:52:13 UTC 2020
LastAccessTime:         UNKNOWN
Retention:              0
Location:               <LOCATION>
Table Type:             EXTERNAL_TABLE
Table Parameters:
    COLUMN_STATS_ACCURATE   {\"BASIC_STATS\":\"true\"}
    EXTERNAL                TRUE
    druid.datasource        druid_datasource_name
    numFiles                0
    numRows                 0
    rawDataSize             0
    storage_handler         org.apache.hadoop.hive.druid.DruidStorageHandler
    totalSize               0
    transient_lastDdlTime   1581342733

# Storage Information
SerDe Library:          org.apache.hadoop.hive.druid.serde.DruidSerDe
InputFormat:            null
OutputFormat:           null
Compressed:             No
Num Buckets:            -1
Bucket Columns:         []
Sort Columns:           []
Storage Desc Params:
    serialization.format    1
Time taken: 0.144 seconds, Fetched: 37 row(s)

For reference - Druid Supervisor Spec:

{
  "dataSchema": {
    "dataSource": "druid_datasource_name",
    "timestampSpec": {
      "column": "current_ts",
      "format": "iso",
      "missingValue": null
    },
    "dimensionsSpec": {
      "dimensions": [],
      "dimensionExclusions": [
        "current_ts"
      ]
    },
    "metricsSpec": [],
    "granularitySpec": {
      "type": "uniform",
      "segmentGranularity": "HOUR",
      "queryGranularity": {
        "type": "none"
      },
      "rollup": false,
      "intervals": null
    },
    "transformSpec": {
      "filter": null,
      "transforms": []
    }
  },
  "ioConfig": {
    "topic": "<kafka_topic>",
    "inputFormat": {
      "type": "json",
      "flattenSpec": {
        "useFieldDiscovery": true,
        "fields": []
      },
      "featureSpec": {}
    },
    "replicas": 1,
    "taskCount": 1,
    "taskDuration": "PT3600S",
    "consumerProperties": {
      "bootstrap.servers": "<bootstrap_servers>",
      "group.id": "<group_name>",
      "security.protocol": "SASL_SSL",
      "ssl.truststore.location": "<location>",
      "ssl.truststore.password": "<pass>",
      "sasl.jaas.config": "<config>",
      "sasl.mechanism": "SCRAM-SHA-512"
    },
    "pollTimeout": 100,
    "startDelay": "PT5S",
    "period": "PT30S",
    "useEarliestOffset": true,
    "completionTimeout": "PT1800S",
    "lateMessageRejectionPeriod": null,
    "earlyMessageRejectionPeriod": null,
    "lateMessageRejectionStartDateTime": null,
    "stream": "<kafka_topic>",
    "useEarliestSequenceNumber": true,
    "type": "kafka"
  },
  "tuningConfig": {
    "type": "kafka",
    "maxRowsInMemory": 1000000,
    "maxBytesInMemory": 0,
    "maxRowsPerSegment": 5000000,
    "maxTotalRows": null,
    "intermediatePersistPeriod": "PT10M",
    "basePersistDirectory": "/opt/apache-druid-0.17.0/var/tmp/druid-realtime-persist7801461398656096281",
    "maxPendingPersists": 0,
    "indexSpec": {
      "bitmap": {
        "type": "concise"
      },
      "dimensionCompression": "lz4",
      "metricCompression": "lz4",
      "longEncoding": "longs"
    },
    "indexSpecForIntermediatePersists": {
      "bitmap": {
        "type": "concise"
      },
      "dimensionCompression": "lz4",
      "metricCompression": "lz4",
      "longEncoding": "longs"
    },
    "buildV9Directly": true,
    "reportParseExceptions": false,
    "handoffConditionTimeout": 0,
    "resetOffsetAutomatically": false,
    "segmentWriteOutMediumFactory": null,
    "workerThreads": null,
    "chatThreads": null,
    "chatRetries": 8,
    "httpTimeout": "PT10S",
    "shutdownTimeout": "PT80S",
    "offsetFetchPeriod": "PT30S",
    "intermediateHandoffPeriod": "P2147483647D",
    "logParseExceptions": false,
    "maxParseExceptions": 2147483647,
    "maxSavedParseExceptions": 0,
    "skipSequenceNumberAvailabilityCheck": false,
    "repartitionTransitionDuration": "PT120S"
  },
  "type": "kafka"
}

Thank you for the helping on resolving this issue.

Body:
I've managed to solve this issue.
Updating Hive and Hadoop to version 3+ solved the issue.

It was as easy as buttering a piece of bread by using with this code:

SET hive.druid.broker.address.default=<host>:8082;

CREATE EXTERNAL TABLE druid_hive_table
STORED BY 'org.apache.hadoop.hive.druid.DruidStorageHandler'
TBLPROPERTIES ("druid.datasource" = "druid_datasource_name");


问:
How to connect login API in reactjs
I am creating login form for practice. I need to connect online API. I have no idea hot connect login API . I Just connect only fetch data API and not able to connect login API. I have design but not able to connect API .I am working in "react": "^16.12.0". using react hooks </p>

```<code>enter code here

import React, { useState } from "react";
import { Wrapper } from "./vehiclesTableStyles";
import { PostData } from "./postData";

function VehiclesTable() {
const [username, setUsername] = useState("");
const [password, setPassword] = useState("");

const submitForm = e => {
e.preventDefault();

PostData(username, password).then(result => {
  console.log(result);
});
console.log("username", username);
console.log("password", password);
};
return (

<Wrapper>
  <div className="search_box">
    <form onSubmit={submitForm}>
      <input
        name="name"
        type="text"
        placeholder="username"
        onChange={e => setUsername(e.target.value)}
      />
      <input
        name="password"
        type="password"
        placeholder="search"
        onChange={e => setPassword(e.target.value)}
      />
      <input type="submit" value="login" />
    </form>
  </div>
</Wrapper>
);
}

export default VehiclesTable;

export function PostData(userData) {
let BaseUrl = "https://reqres.in//api/login";
console.log("userData", userData);
return new Promise((resolve, reject) => {
fetch(BaseUrl, {
  method: "POST",
  headers: {
    "Content-Type": "application/json",
    Accept: "application/json"
  }
  // body: JSON.stringify(userData)
})
  .then(response => response.json())
  .then(responseJson => {
    resolve(responseJson);
  })
  .catch(error => {
    reject(error);
  });
});
}
</code>```

答:
I also have the same problem. check the code below. You are making some mistake in code while calling api. You need to call in React life cycle hooks that is the best way.

enter code here

import React, { useState } from "react";
import { Wrapper } from "./vehiclesTableStyles";
import { PostData } from "./postData";

function VehiclesTable() {
const [username, setUsername] = useState("");
const [password, setPassword] = useState("");

const submitForm = e => {
e.preventDefault();

PostData(username, password).then(result => {
  console.log(result);
});
console.log("username", username);
console.log("password", password);
};
return (

<Wrapper>

    <form onSubmit={submitForm}>
      <input
        name="name"
        type="text"
        placeholder="username"
        onChange={e => setUsername(e.target.value)}
      />
      <input
        name="password"
        type="password"
        placeholder="search"
        onChange={e => setPassword(e.target.value)}
      />
      <input type="submit" value="login" />
    </form>

</Wrapper>
);
}

export default VehiclesTable;

export function PostData(userData) {
let BaseUrl = "https://reqres.in//api/login";
console.log("userData", userData);
return new Promise((resolve, reject) => {
fetch(BaseUrl, {
  method: "POST",
  headers: {
    "Content-Type": "application/json",
    Accept: "application/json"
  }
  // body: JSON.stringify(userData)
})
  .then(response => response.json())
  .then(responseJson => {
    resolve(responseJson);
  })
  .catch(error => {
    reject(error);
  });
});```

Title: How to connect login API in reactjs

Body:
I am creating login form for practice. I need to connect online API. I have no idea hot connect login API . I Just connect only fetch data API and not able to connect login API. I have design but not able to connect API .I am working in "react": "^16.12.0". using react hooks

enter code here

import React, { useState } from "react";
import { Wrapper } from "./vehiclesTableStyles";
import { PostData } from "./postData";

function VehiclesTable() {
const [username, setUsername] = useState("");
const [password, setPassword] = useState("");

const submitForm = e => {
e.preventDefault();

PostData(username, password).then(result => {
  console.log(result);
});
console.log("username", username);
console.log("password", password);
};
return (

<Wrapper>

    <form onSubmit={submitForm}>
      <input
        name="name"
        type="text"
        placeholder="username"
        onChange={e => setUsername(e.target.value)}
      />
      <input
        name="password"
        type="password"
        placeholder="search"
        onChange={e => setPassword(e.target.value)}
      />
      <input type="submit" value="login" />
    </form>

</Wrapper>
);
}

export default VehiclesTable;

export function PostData(userData) {
let BaseUrl = "https://reqres.in//api/login";
console.log("userData", userData);
return new Promise((resolve, reject) => {
fetch(BaseUrl, {
  method: "POST",
  headers: {
    "Content-Type": "application/json",
    Accept: "application/json"
  }
  // body: JSON.stringify(userData)
})
  .then(response => response.json())
  .then(responseJson => {
    resolve(responseJson);
  })
  .catch(error => {
    reject(error);
  });
});
}

Body:
I also have the same problem. check the code below. You are making some mistake in code while calling api. You need to call in React life cycle hooks that is the best way.

enter code here

import React, { useState } from "react";
import { Wrapper } from "./vehiclesTableStyles";
import { PostData } from "./postData";

function VehiclesTable() {
const [username, setUsername] = useState("");
const [password, setPassword] = useState("");

const submitForm = e => {
e.preventDefault();

PostData(username, password).then(result => {
  console.log(result);
});
console.log("username", username);
console.log("password", password);
};
return (

<Wrapper>
  <div className="search_box">
    <form onSubmit={submitForm}>
      <input
        name="name"
        type="text"
        placeholder="username"
        onChange={e => setUsername(e.target.value)}
      />
      <input
        name="password"
        type="password"
        placeholder="search"
        onChange={e => setPassword(e.target.value)}
      />
      <input type="submit" value="login" />
    </form>
  </div>
</Wrapper>
);
}

export default VehiclesTable;

export function PostData(userData) {
let BaseUrl = "https://reqres.in//api/login";
console.log("userData", userData);
return new Promise((resolve, reject) => {
fetch(BaseUrl, {
  method: "POST",
  headers: {
    "Content-Type": "application/json",
    Accept: "application/json"
  }
  // body: JSON.stringify(userData)
})
  .then(response => response.json())
  .then(responseJson => {
    resolve(responseJson);
  })
  .catch(error => {
    reject(error);
  });
});


问:
COM & Late binding in Excel/VBA: ActiveX component can't create object
I have built a .NET COM wrapper which I use in VBA to run a .NET assembly in Excel.

For some reason I can't use late-binding to create objects from the .NET COM dll.

```<code>Set obj = CreateObject("COMwrapper.MyClass")
</code>```

This throws

Error 429: ActiveX component can't create object

It works however if I:

Use early-binding and reference the COMwrapper.tlb

Run Excel with admin rights

The COMwrapper .NET project and it's dependencies .NET DLLs are built with Visual Studio 2019 elevated to admin mode, so that it can register the COMwrapper in the build process.

I have also tried to build the solution with VS as normal user, without registering the COM wrapper. Later manually I have run regasm.exe with admin rights. But it has been the same result.

If I peek into the registry with RegDllView.exe (https://www.nirsoft.net/utils/registered_dll_view.html), the COMwrapper DLL seems to be registered and with the right path.

This is how I have set up the COM part

The class file

```<code>namespace COMwrapper
{
    [ComVisible(true)]
    [ClassInterface(ClassInterfaceType.None)]
    [Guid("904EBB3C-7A28-490E-B2E5-0CC0C66E907A")]
    public class MyClass : IMyClass
</code>```

The interface file

```<code>namespace COMwrapper
{
    [Guid("540D119F-6676-4CE9-B763-50F4F2976E1E")]
    [ComVisible(true)]
    [InterfaceType(ComInterfaceType.InterfaceIsDual)]
    public interface IMyClass
</code>```

This has previously worked fine! If I distribute the DLLs to another computer and register the wrapper, it works fine with late binding.

答: Not an answer, just supporting my comment.  I created a DLL in Admin rights on VS2019, and was able to access via both early and late binding.  This is how i set it up

Body:
I have built a .NET COM wrapper which I use in VBA to run a .NET assembly in Excel.

For some reason I can't use late-binding to create objects from the .NET COM dll.

Set obj = CreateObject("COMwrapper.MyClass")

This throws

Error 429: ActiveX component can't create object

It works however if I:

Use early-binding and reference the COMwrapper.tlb

Run Excel with admin rights

The COMwrapper .NET project and it's dependencies .NET DLLs are built with Visual Studio 2019 elevated to admin mode, so that it can register the COMwrapper in the build process.

I have also tried to build the solution with VS as normal user, without registering the COM wrapper. Later manually I have run regasm.exe with admin rights. But it has been the same result.

If I peek into the registry with RegDllView.exe (https://www.nirsoft.net/utils/registered_dll_view.html), the COMwrapper DLL seems to be registered and with the right path.

This is how I have set up the COM part

The class file

namespace COMwrapper
{
    [ComVisible(true)]
    [ClassInterface(ClassInterfaceType.None)]
    [Guid("904EBB3C-7A28-490E-B2E5-0CC0C66E907A")]
    public class MyClass : IMyClass

The interface file

namespace COMwrapper
{
    [Guid("540D119F-6676-4CE9-B763-50F4F2976E1E")]
    [ComVisible(true)]
    [InterfaceType(ComInterfaceType.InterfaceIsDual)]
    public interface IMyClass

This has previously worked fine! If I distribute the DLLs to another computer and register the wrapper, it works fine with late binding.


问:
Got "Fatal error: Index out of range" : show index in list item for swiftui
Updated: error: Type '_' has no member '1', if put a if closure(if !self.showMarkedOnly || name.marked {}) inside list-foreach, why?

Code version 4:

```<code>struct Name: Identifiable, Hashable {
    var id: String = UUID().uuidString
    var name: String
    var marked: Bool
    init(_ name: String, marked: Bool = false) { self.name = name; self.marked = marked }
}

struct TestView: View {
    @State private var list: [Name] = [Name("test1"), Name("test2"), Name("test3", marked: true), Name("test4"), Name("test5", marked: true), Name("test6"), Name("test7"), Name("test8")]
    @State private var showMarkedOnly = false

    var body: some View {
        VStack{
            Toggle(isOn: $showMarkedOnly) { Text("show marked only") }
            List {
                ForEach(Array(zip(0..., list)), id: \.1.id) { index, name in
//                    if !self.showMarkedOnly || name.marked {
                        HStack {
                            Text("\(index)").foregroundColor(name.marked ? .red : .gray)
                            Spacer()
                            Text("\(name.name)")
                        }
                        .background(Color.gray.opacity(0.001))
                        .onTapGesture {
                            self.list.remove(at: index)
                        }
//                    }
                }
            }
        }
    }
}
</code>```

=========

Updated: I found the issue of Code version 2, I must provide a id for ForEach. And Code version 2 updated.

I found a graceful way to show index, It avoids self.list[index]. But I found an error "Type '_' has no member '1'" occurred in some complex code.

Code version 3:

```<code>var body: some View {
        List {
            ForEach(Array(zip(0..., list)), id: \.1.id) { index, name in // a error occurs in some complex code: "Type '_' has no member '1'"
                HStack {
                    Text("\(index)")
                    Spacer()
                    Text("\(name.name)")
                }
                .background(Color.gray.opacity(0.001))
                .onTapGesture {
                    self.list.remove(at: index)
                }
            }
        }
    }
</code>```

I show a list, and remove the item I tapped. It's Code version 1, it works fine.
When I add index into the list item using indices(Code veriosn 2), got "Fatal error: Index out of range" after tapping.

Code version 1:

```<code>struct Name: Identifiable, Hashable {
    var id: String = UUID().uuidString
    var name: String
    init(_ name: String) { self.name = name }
}

struct TestView: View {
    @State private var list: [Name] = [Name("test1"), Name("test2"), Name("test3"), Name("test4"), Name("test5"), Name("test6"), Name("test7"), Name("test8")]

    var body: some View {
        List {
            ForEach(list) { name in
                HStack {
                    Text("\(0)")
                    Spacer()
                    Text("\(name.name)")
                }
                .background(Color.gray.opacity(0.001))
                .onTapGesture {
                    self.list = self.list.filter { $0 != name }
                }
            }
        }
    }
}
</code>```

Code version 2:

```<code>struct TestView: View {
    @State private var list: [Name] = [Name("test1"), Name("test2"), Name("test3"), Name("test4"), Name("test5"), Name("test6"), Name("test7"), Name("test8")]

    var body: some View {
        List {
            //ForEach(list.indices) { index in
            ForEach(list.indices, id: \.self) { index in
                HStack {
                    Text("\(index)")
                    Spacer()
                    Text("\(self.list[index].name)")
                }
                .background(Color.gray.opacity(0.001))
                .onTapGesture {
                    self.list.remove(at: index)
                }
            }
        }
    }
}
</code>```

答:
@State is property wrapper, which will force the View in which it is defined to recalculate its body.

In your case, if you remove the item at index,

```<code>HStack {
    Text("\(index)")
    Spacer()
    Text("\(self.list[index].name)")
}
.background(Color.gray.opacity(0.001))
.onTapGesture {
     self.list.remove(at: index)
 }
</code>```

the Text inside HStack

```<code>Text("\(self.list[index].name)")
</code>```

crash, just because list[index] doesn't exist any more.

Using

```<code>ForEach(list.indices, id:\.self) { index in ... }
</code>```

instead of

```<code>ForEach(list.indices) { index in ... }
</code>```

will force SwiftUI to recreate TestView (see the id:\.self in ForEach constructor)

SwiftUI will make fresh copy of TestView while using fresh value of property wrapped in @State property wrapper.

UPDATE

Please, don't update your question  ...

Your last code version 4 is total mess, so I rewrote it to something you able to copy - paste - run

```<code>import SwiftUI

struct Name: Identifiable, Hashable {
    var id: String = UUID().uuidString
    var name: String
    var marked: Bool
    init(_ name: String, marked: Bool = false) { self.name = name; self.marked = marked }
}

struct ContentView: View {
    @State private var list: [Name] = [Name("test1"), Name("test2"), Name("test3", marked: true), Name("test4"), Name("test5", marked: true), Name("test6"), Name("test7"), Name("test8")]
    @State private var showMarkedOnly = false

    var body: some View {
        VStack{
            Toggle(isOn: $showMarkedOnly) {
                Text("show marked only")
            }.padding(.horizontal)
            List {
                ForEach(Array(zip(0..., list)).filter({!self.showMarkedOnly || $0.1.marked}), id: \.1.id) { index, name in
                    HStack {
                        Text("\(index)").foregroundColor(name.marked ? .red : .gray)
                        Spacer()
                        Text("\(name.name)")
                    }
                    .background(Color.gray.opacity(0.001))
                    .onTapGesture {
                        self.list.remove(at: index)
                    }
                }
            }
        }
    }
}
struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}
</code>```

it should looks like

UPDATE based on discussion

ForEach different versions of constructors use internally different functionality of ViewBuilder

```<code>@available(iOS 13.0, OSX 10.15, tvOS 13.0, watchOS 6.0, *)
extension ViewBuilder {

    /// Provides support for "if" statements in multi-statement closures, producing an `Optional` view
    /// that is visible only when the `if` condition evaluates `true`.
    public static func buildIf<Content>(_ content: Content?) -> Content? where Content : View

    /// Provides support for "if" statements in multi-statement closures, producing
    /// ConditionalContent for the "then" branch.
    public static func buildEither<TrueContent, FalseContent>(first: TrueContent) -> _ConditionalContent<TrueContent, FalseContent> where TrueContent : View, FalseContent : View

    /// Provides support for "if-else" statements in multi-statement closures, producing
    /// ConditionalContent for the "else" branch.
    public static func buildEither<TrueContent, FalseContent>(second: FalseContent) -> _ConditionalContent<TrueContent, FalseContent> where TrueContent : View, FalseContent : View
}
</code>```

This is about "implementation details" and hopefully it will be documented in next release. SwiftUI is still in very early stage of development, we have to be careful.

Lets try to force SwiftUI to follow our own way!
First separate RowView

```<code>struct RowView: View {
    var showMarkedOnly: Bool
    var index: Int
    var name: Name
    //@ViewBuilder
    var body: some View {
        if !self.showMarkedOnly || name.marked {
            HStack {
                Text(verbatim: index.description).foregroundColor(name.marked ? .red : .gray)
                Spacer()
                Text(verbatim: name.name)
            }
            .background(Color.gray.opacity(0.001))

        }
    }
}
</code>```

Compiler complains with

```<code>Function declares an opaque return type, but has no return statements in its body from which to infer an underlying type
</code>```

Uncomment the line to wrap our body

```<code>struct RowView: View {
    var showMarkedOnly: Bool
    var index: Int
    var name: Name
    @ViewBuilder
    var body: some View {
        if !self.showMarkedOnly || name.marked {
            HStack {
                Text(verbatim: index.description).foregroundColor(name.marked ? .red : .gray)
                Spacer()
                Text(verbatim: name.name)
            }
            .background(Color.gray.opacity(0.001))

        }
    }
}
</code>```

Now we can use the code the way you like :-)

```<code>struct ContentView: View {
    @State private var list: [Name] = [Name("test1"), Name("test2"), Name("test3", marked: true), Name("test4"), Name("test5", marked: true), Name("test6"), Name("test7"), Name("test8")]
    @State private var showMarkedOnly = false

    var body: some View {
        VStack{
            Toggle(isOn: $showMarkedOnly) {
                Text("show marked only")
            }.padding(.horizontal)
            List {
                ForEach(Array(zip(0..., list)), id: \.1.id) { (index, name) in
                    RowView(showMarkedOnly: self.showMarkedOnly, index: index, name: name).onTapGesture {
                    self.list.remove(at: index)
                }
                }
            }
        }
    }
}
</code>```

The final result uses now buildIf<Content> construct and all code works again (the result looks exactly the same as shown above)

Body:
Updated: error: Type '_' has no member '1', if put a if closure(if !self.showMarkedOnly || name.marked {}) inside list-foreach, why?

Code version 4:

struct Name: Identifiable, Hashable {
    var id: String = UUID().uuidString
    var name: String
    var marked: Bool
    init(_ name: String, marked: Bool = false) { self.name = name; self.marked = marked }
}

struct TestView: View {
    @State private var list: [Name] = [Name("test1"), Name("test2"), Name("test3", marked: true), Name("test4"), Name("test5", marked: true), Name("test6"), Name("test7"), Name("test8")]
    @State private var showMarkedOnly = false

    var body: some View {
        VStack{
            Toggle(isOn: $showMarkedOnly) { Text("show marked only") }
            List {
                ForEach(Array(zip(0..., list)), id: \.1.id) { index, name in
//                    if !self.showMarkedOnly || name.marked {
                        HStack {
                            Text("\(index)").foregroundColor(name.marked ? .red : .gray)
                            Spacer()
                            Text("\(name.name)")
                        }
                        .background(Color.gray.opacity(0.001))
                        .onTapGesture {
                            self.list.remove(at: index)
                        }
//                    }
                }
            }
        }
    }
}

=========

Updated: I found the issue of Code version 2, I must provide a id for ForEach. And Code version 2 updated.

I found a graceful way to show index, It avoids self.list[index]. But I found an error "Type '_' has no member '1'" occurred in some complex code.

Code version 3:

var body: some View {
        List {
            ForEach(Array(zip(0..., list)), id: \.1.id) { index, name in // a error occurs in some complex code: "Type '_' has no member '1'"
                HStack {
                    Text("\(index)")
                    Spacer()
                    Text("\(name.name)")
                }
                .background(Color.gray.opacity(0.001))
                .onTapGesture {
                    self.list.remove(at: index)
                }
            }
        }
    }

I show a list, and remove the item I tapped. It's Code version 1, it works fine.
When I add index into the list item using indices(Code veriosn 2), got "Fatal error: Index out of range" after tapping.

Code version 1:

struct Name: Identifiable, Hashable {
    var id: String = UUID().uuidString
    var name: String
    init(_ name: String) { self.name = name }
}

struct TestView: View {
    @State private var list: [Name] = [Name("test1"), Name("test2"), Name("test3"), Name("test4"), Name("test5"), Name("test6"), Name("test7"), Name("test8")]

    var body: some View {
        List {
            ForEach(list) { name in
                HStack {
                    Text("\(0)")
                    Spacer()
                    Text("\(name.name)")
                }
                .background(Color.gray.opacity(0.001))
                .onTapGesture {
                    self.list = self.list.filter { $0 != name }
                }
            }
        }
    }
}

Code version 2:

struct TestView: View {
    @State private var list: [Name] = [Name("test1"), Name("test2"), Name("test3"), Name("test4"), Name("test5"), Name("test6"), Name("test7"), Name("test8")]

    var body: some View {
        List {
            //ForEach(list.indices) { index in
            ForEach(list.indices, id: \.self) { index in
                HStack {
                    Text("\(index)")
                    Spacer()
                    Text("\(self.list[index].name)")
                }
                .background(Color.gray.opacity(0.001))
                .onTapGesture {
                    self.list.remove(at: index)
                }
            }
        }
    }
}

Body:
@State is property wrapper, which will force the View in which it is defined to recalculate its body.

In your case, if you remove the item at index,

HStack {
    Text("\(index)")
    Spacer()
    Text("\(self.list[index].name)")
}
.background(Color.gray.opacity(0.001))
.onTapGesture {
     self.list.remove(at: index)
 }

the Text inside HStack

Text("\(self.list[index].name)")

crash, just because list[index] doesn't exist any more.

Using

ForEach(list.indices, id:\.self) { index in ... }

instead of

ForEach(list.indices) { index in ... }

will force SwiftUI to recreate TestView (see the id:\.self in ForEach constructor)

SwiftUI will make fresh copy of TestView while using fresh value of property wrapped in @State property wrapper.

UPDATE

Please, don't update your question  ...

Your last code version 4 is total mess, so I rewrote it to something you able to copy - paste - run

import SwiftUI

struct Name: Identifiable, Hashable {
    var id: String = UUID().uuidString
    var name: String
    var marked: Bool
    init(_ name: String, marked: Bool = false) { self.name = name; self.marked = marked }
}

struct ContentView: View {
    @State private var list: [Name] = [Name("test1"), Name("test2"), Name("test3", marked: true), Name("test4"), Name("test5", marked: true), Name("test6"), Name("test7"), Name("test8")]
    @State private var showMarkedOnly = false

    var body: some View {
        VStack{
            Toggle(isOn: $showMarkedOnly) {
                Text("show marked only")
            }.padding(.horizontal)
            List {
                ForEach(Array(zip(0..., list)).filter({!self.showMarkedOnly || $0.1.marked}), id: \.1.id) { index, name in
                    HStack {
                        Text("\(index)").foregroundColor(name.marked ? .red : .gray)
                        Spacer()
                        Text("\(name.name)")
                    }
                    .background(Color.gray.opacity(0.001))
                    .onTapGesture {
                        self.list.remove(at: index)
                    }
                }
            }
        }
    }
}
struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

it should looks like

UPDATE based on discussion

ForEach different versions of constructors use internally different functionality of ViewBuilder

@available(iOS 13.0, OSX 10.15, tvOS 13.0, watchOS 6.0, *)
extension ViewBuilder {

    /// Provides support for "if" statements in multi-statement closures, producing an `Optional` view
    /// that is visible only when the `if` condition evaluates `true`.
    public static func buildIf<Content>(_ content: Content?) -> Content? where Content : View

    /// Provides support for "if" statements in multi-statement closures, producing
    /// ConditionalContent for the "then" branch.
    public static func buildEither<TrueContent, FalseContent>(first: TrueContent) -> _ConditionalContent<TrueContent, FalseContent> where TrueContent : View, FalseContent : View

    /// Provides support for "if-else" statements in multi-statement closures, producing
    /// ConditionalContent for the "else" branch.
    public static func buildEither<TrueContent, FalseContent>(second: FalseContent) -> _ConditionalContent<TrueContent, FalseContent> where TrueContent : View, FalseContent : View
}

This is about "implementation details" and hopefully it will be documented in next release. SwiftUI is still in very early stage of development, we have to be careful.

Lets try to force SwiftUI to follow our own way!
First separate RowView

struct RowView: View {
    var showMarkedOnly: Bool
    var index: Int
    var name: Name
    //@ViewBuilder
    var body: some View {
        if !self.showMarkedOnly || name.marked {
            HStack {
                Text(verbatim: index.description).foregroundColor(name.marked ? .red : .gray)
                Spacer()
                Text(verbatim: name.name)
            }
            .background(Color.gray.opacity(0.001))

        }
    }
}

Compiler complains with

Function declares an opaque return type, but has no return statements in its body from which to infer an underlying type

Uncomment the line to wrap our body

struct RowView: View {
    var showMarkedOnly: Bool
    var index: Int
    var name: Name
    @ViewBuilder
    var body: some View {
        if !self.showMarkedOnly || name.marked {
            HStack {
                Text(verbatim: index.description).foregroundColor(name.marked ? .red : .gray)
                Spacer()
                Text(verbatim: name.name)
            }
            .background(Color.gray.opacity(0.001))

        }
    }
}

Now we can use the code the way you like :-)

struct ContentView: View {
    @State private var list: [Name] = [Name("test1"), Name("test2"), Name("test3", marked: true), Name("test4"), Name("test5", marked: true), Name("test6"), Name("test7"), Name("test8")]
    @State private var showMarkedOnly = false

    var body: some View {
        VStack{
            Toggle(isOn: $showMarkedOnly) {
                Text("show marked only")
            }.padding(.horizontal)
            List {
                ForEach(Array(zip(0..., list)), id: \.1.id) { (index, name) in
                    RowView(showMarkedOnly: self.showMarkedOnly, index: index, name: name).onTapGesture {
                    self.list.remove(at: index)
                }
                }
            }
        }
    }
}

The final result uses now buildIf<Content> construct and all code works again (the result looks exactly the same as shown above)


问:
Splitting a data frame into equal parts
I have an example data frame:

```<code>df <- data.frame(x = 1:112, y = runif(112))
</code>```

Is there a way to print a list of data frames with the first part of the list containing rows 1:10, the second 11:20, etc. up until the end (111:112)?

答:
This can be solved with nesting using tidyr/dplyr</p>

```<code>require(dplyr)
require(tidyr)

num_groups = 10

iris %>%
   group_by((row_number()-1) %/% (n()/num_groups)) %>%
   nest %>% pull(data)
</code>```

Title: Splitting a data frame into equal parts

Body:
I have an example data frame:

df <- data.frame(x = 1:112, y = runif(112))

Is there a way to print a list of data frames with the first part of the list containing rows 1:10, the second 11:20, etc. up until the end (111:112)?

Body:
This can be solved with nesting using tidyr/dplyr

require(dplyr)
require(tidyr)

num_groups = 10

iris %>%
   group_by((row_number()-1) %/% (n()/num_groups)) %>%
   nest %>% pull(data)


问:
Bitwise operations on elements from array of chars
I have made array of hexadecimal numbers that I would like to add together bitwise. In my program I want to add 0xFF with 0x7F00. Here is my approach

```<code>#include <iostream>

using namespace std;

int main() {

    char data[2] = {0xFF, 0x7F};

    cout << (data[0] | (data[1] << 8)) << endl;

    system("pause");
    return 0;
}
</code>```

I expect the result to be 0x7FFF which is 32767 in decimal, but I get -1 (0xFF in hex).

答:
The problem you're having stems from two facts:

The bitwise operators requires integral promotion of both operands.

char can be either signed or unsigned

Promotion will convert values of smaller types (like char or short) to int, and as part of that signed values will be sign-extended. If char is signed, then the value 0xff will be converted to the (32-bit) int value 0xffffffff, which is -1.

It doesn't matter what value you use in the bitwise OR, the result will still be 0xffffffff.

The simple solution is to explicitly use unsigned char (or even better uint8_t) as the type for the array elements:

```<code>uint8_t data[2] = {0xFF, 0x7F};
</code>```

Body:
I have made array of hexadecimal numbers that I would like to add together bitwise. In my program I want to add 0xFF with 0x7F00. Here is my approach

#include <iostream>

using namespace std;

int main() {

    char data[2] = {0xFF, 0x7F};

    cout << (data[0] | (data[1] << 8)) << endl;

    system("pause");
    return 0;
}

I expect the result to be 0x7FFF which is 32767 in decimal, but I get -1 (0xFF in hex).

Body:
The problem you're having stems from two facts:

The bitwise operators requires integral promotion of both operands.

char can be either signed or unsigned

Promotion will convert values of smaller types (like char or short) to int, and as part of that signed values will be sign-extended. If char is signed, then the value 0xff will be converted to the (32-bit) int value 0xffffffff, which is -1.

It doesn't matter what value you use in the bitwise OR, the result will still be 0xffffffff.

The simple solution is to explicitly use unsigned char (or even better uint8_t) as the type for the array elements:

uint8_t data[2] = {0xFF, 0x7F};


问:
Xamarin.Forms: Disabled entry has white TextColor when Dark Mode is enabled on iOS
I seem to have some troubles with the TextColor of my Entry on iOS when Dark Mode is enabled.
Whenever I set the Entry's Enabled state to false, the TextColor turns white and it's not possible to change.
I used the following simple code to reproduce this.

```<code>Page.xaml

    <Entry x:Name="TestEntry" />
</code>```

```<code>Page.xaml.cs

    public OnboardingPage()
    {
        InitializeComponent();

        TestEntry.Text = "Testo";
        TestEntry.TextColor = Color.Blue;
        TestEntry.IsEnabled = false;
    }
</code>```

I am currently using the latest version of Xamarin.Forms. (4.4.0.991640)

Does anybody have an idea what's going wrong here? I don't think this is expected behavior..

Thanks in advance!

答:
In the meanwhile I have found the fix necessary to my question.

Apparently the EntryRenderer on iOS uses uses the default color when legacy color management is enabled and the Entry is disabled. Setting the legacyColorManagement to False on the Entry solves this issue.

XF check for legacycolormanagement
https://github.com/xamarin/Xamarin.Forms/blob/master/Xamarin.Forms.Platform.iOS/Extensions/VisualElementExtensions.cs#L15

XF check for TextColor of the Entry
https://github.com/xamarin/Xamarin.Forms/blob/master/Xamarin.Forms.Platform.iOS/Renderers/EntryRenderer.cs#L272

I've added following code to my *Page.xaml and now the colors are rendering correctly:

```<code>*Page.xaml

<ContentPage xmlns:ios="clr-namespace:Xamarin.Forms.PlatformConfiguration.iOSSpecific;assembly=Xamarin.Forms.Core"
             ...>

<Entry ios:VisualElement.IsLegacyColorModeEnabled="False"
       .../>

</code>```

Body:
I seem to have some troubles with the TextColor of my Entry on iOS when Dark Mode is enabled.
Whenever I set the Entry's Enabled state to false, the TextColor turns white and it's not possible to change.
I used the following simple code to reproduce this.

Page.xaml

    <Entry x:Name="TestEntry" />

Page.xaml.cs

    public OnboardingPage()
    {
        InitializeComponent();

        TestEntry.Text = "Testo";
        TestEntry.TextColor = Color.Blue;
        TestEntry.IsEnabled = false;
    }

I am currently using the latest version of Xamarin.Forms. (4.4.0.991640)

Does anybody have an idea what's going wrong here? I don't think this is expected behavior..

Thanks in advance!

Body:
In the meanwhile I have found the fix necessary to my question.

Apparently the EntryRenderer on iOS uses uses the default color when legacy color management is enabled and the Entry is disabled. Setting the legacyColorManagement to False on the Entry solves this issue.

XF check for legacycolormanagement
https://github.com/xamarin/Xamarin.Forms/blob/master/Xamarin.Forms.Platform.iOS/Extensions/VisualElementExtensions.cs#L15

XF check for TextColor of the Entry
https://github.com/xamarin/Xamarin.Forms/blob/master/Xamarin.Forms.Platform.iOS/Renderers/EntryRenderer.cs#L272

I've added following code to my *Page.xaml and now the colors are rendering correctly:

*Page.xaml

<ContentPage xmlns:ios="clr-namespace:Xamarin.Forms.PlatformConfiguration.iOSSpecific;assembly=Xamarin.Forms.Core"
             ...>

<Entry ios:VisualElement.IsLegacyColorModeEnabled="False"
       .../>


问:
Drawing a huge graph with networkX and matplotlib
I am drawing a graph with around 5K nodes in it using networkX and matplotlib. The GTK window by matplotlib has tools to zoom and visualise the graph.
Is there any way, I can save a magnified version for proper visualisation later?</p>

```<code>import matplotlib.pyplot as plt
import networkx as nx

pos=nx.spring_layout(G)   #G is my graph

nx.draw(G,pos,node_color='#A0CBE2',edge_color='#BB0000',width=2,edge_cmap=plt.cm.Blues,with_labels=True)
#plt.show()
plt.savefig("graph.png", dpi=500, facecolor='w', edgecolor='w',orientation='portrait', papertype=None, format=None,transparent=False, bbox_inches=None, pad_inches=0.1)
</code>```

答:
You may want to check this out:

```<code>plt.savefig("name.svg")
</code>```

the quality is magnificent. although the dpi option is still alive.

Body:
I am drawing a graph with around 5K nodes in it using networkX and matplotlib. The GTK window by matplotlib has tools to zoom and visualise the graph.
Is there any way, I can save a magnified version for proper visualisation later?

import matplotlib.pyplot as plt
import networkx as nx

pos=nx.spring_layout(G)   #G is my graph

nx.draw(G,pos,node_color='#A0CBE2',edge_color='#BB0000',width=2,edge_cmap=plt.cm.Blues,with_labels=True)
#plt.show()
plt.savefig("graph.png", dpi=500, facecolor='w', edgecolor='w',orientation='portrait', papertype=None, format=None,transparent=False, bbox_inches=None, pad_inches=0.1)

Body:
You may want to check this out:

plt.savefig("name.svg")

the quality is magnificent. although the dpi option is still alive.