问:
Compiler adding unexpected artifacts to build folder
I am following along with this Getting Started guide to install tsoa Per their instruction, I generate a routes.ts folder which is placed under /build:

```<code>/build
  /routes.ts
</code>```

Now, in /src/app.tsx, I reference it:

import { RegisterRoutes } from "/build/routes"

I am now getting an unexpected directory structure in /build when I run yarn run tsc --outDir build --experimentalDecorators:

```<code>/build
  /build
  /src
    server.js
  routes.ts
</code>```

It appears because of my reference to "/build/routes", I am getting /build and /src copied into /build. What I want are just the contents of /src copied into build.

```<code>/build
  routes.ts
  server.js
</code>```

I added includes: ["src"] into my tsconfig.json, but that doesn't work.

Is there something local I may have done to effect this behaviour?

答:
TypeScript outputs files according to the rootDir directory in tsconfig.json. If that isn't set, TypeScript by default figures it out by finding the common path of all input files. Since you have files in both the build and src directories, the common path is the directory which encompasses both of those folders and which also contains the tsconfig.json file.

You can't import files outside of that rootDir so manually setting it to src in tsconfig.json won't work in this case.

Solution:

If you set the routes files to output to the src directory by modifying tsoa.json and then importing from that route file, that will automatically set the rootDir to what you likely want it to be. That change in tsoa.json would be:

```<code>"routes": {
    "routesDir": "src"
  }
</code>```

and the corresponding import in your app.ts file (after running yarn run tsoa routes) would be:

import { RegisterRoutes } from './routes';
```

Alternatively:

In case you specifically want the routes file in the build directory, one other option would be to create a symbolic link from the routes.ts file into the src directory. You would then still import from ./routes in your app.ts.

Further reading:

https://www.typescriptlang.org/v2/en/tsconfig#rootDir

Body:
I am following along with this Getting Started guide to install tsoa Per their instruction, I generate a routes.ts folder which is placed under /build:

/build
  /routes.ts

Now, in /src/app.tsx, I reference it:

import { RegisterRoutes } from "/build/routes"

I am now getting an unexpected directory structure in /build when I run yarn run tsc --outDir build --experimentalDecorators:

/build
  /build
  /src
    server.js
  routes.ts

It appears because of my reference to "/build/routes", I am getting /build and /src copied into /build. What I want are just the contents of /src copied into build.

/build
  routes.ts
  server.js

I added includes: ["src"] into my tsconfig.json, but that doesn't work.

Is there something local I may have done to effect this behaviour?

Body:
TypeScript outputs files according to the rootDir directory in tsconfig.json. If that isn't set, TypeScript by default figures it out by finding the common path of all input files. Since you have files in both the build and src directories, the common path is the directory which encompasses both of those folders and which also contains the tsconfig.json file.

You can't import files outside of that rootDir so manually setting it to src in tsconfig.json won't work in this case.

Solution:

If you set the routes files to output to the src directory by modifying tsoa.json and then importing from that route file, that will automatically set the rootDir to what you likely want it to be. That change in tsoa.json would be:

"routes": {
    "routesDir": "src"
  }

and the corresponding import in your app.ts file (after running yarn run tsoa routes) would be:

import { RegisterRoutes } from './routes';

Alternatively:

In case you specifically want the routes file in the build directory, one other option would be to create a symbolic link from the routes.ts file into the src directory. You would then still import from ./routes in your app.ts.

Further reading:

https://www.typescriptlang.org/v2/en/tsconfig#rootDir


来源: stackexchange

问:
Elasticsearch: Sort the Documents on the index value of the search string in a text field
I have Elasticsearch data like this-

```<code>PUT /text/_doc/1
{
  "name": "pdf1",
  "text":"For the past six weeks. The unemployment crisis has unfolded so suddenly and rapidly."
}
PUT /text/_doc/2
{
  "name": "pdf2",
  "text":"The unemployment crisis has unfolded so suddenly and rapidly."
}
</code>```

In this example I am making a full text search, I am searching for all the documents that have "unemployment" sub-string in the "text" field. And in the end i want all the documents sorted in the ascending order of the index value of "unemployment" string in the "text" field. For eg - the sub-string "unemployment" comes first in the doc2 at index "4" so i want this document to be returned first in the results.

```<code>GET /text/_search?pretty
{
  "query": {
    "match": {
      "text": "unemployment"
    }
  }
}
</code>```

I have tried few things like term_vector, here is the mapping that i used but it didn't help.

```<code>PUT text/_mapping
{
    "properties": {
        "name" : {
          "type" : "text",
          "fields" : {
            "keyword" : {
              "type" : "keyword"
            }
          }
        },
        "text" : {
          "type" : "text",
          "term_vector": "with_positions_offsets"
        }
      }
}
</code>```

Can anyone please help me in making the right mapping and search Query?

Thanks in Advance!

答:
Try this query

```<code>GET text/_search
{
  "query": {
    "function_score": {
      "query": {
        "match": {
          "text": "unemployment"
        }
      },
      "functions": [
        {
          "script_score": {
            "script": {
              "source": """
                def docval = doc['text.keyword'].value;
                def length = docval.length();
                def index = (float) docval.indexOf('unemployment');

                // the sooner the word appears the better so 'invert' the 'index'
                return index > -1 ? (1 / index) : 0;
              """
            }
          }
        }
      ],
      "boost_mode": "sum"
    }
  }
}
</code>```

using the auto-generated mapping

```<code>{
  "text" : {
    "mappings" : {
      "properties" : {
        "name" : {
          "type" : "text",
          "fields" : {
            "keyword" : {
              "type" : "keyword",
              "ignore_above" : 256
            }
          }
        },
        "text" : {
          "type" : "text",
          "fields" : {
            "keyword" : {
              "type" : "keyword",
              "ignore_above" : 256
            }
          }
        }
      }
    }
  }
}
</code>```

Note that this is case-sensitive so it'd be reasonable to have a lowercase-normalized keyword field too and then access it in the script score script. This might get you on the right path.

ContentLicense: CC BY-SA 4.0

Body:
I have Elasticsearch data like this-

PUT /text/_doc/1
{
  "name": "pdf1",
  "text":"For the past six weeks. The unemployment crisis has unfolded so suddenly and rapidly."
}
PUT /text/_doc/2
{
  "name": "pdf2",
  "text":"The unemployment crisis has unfolded so suddenly and rapidly."
}

In this example I am making a full text search, I am searching for all the documents that have "unemployment" sub-string in the "text" field. And in the end i want all the documents sorted in the ascending order of the index value of "unemployment" string in the "text" field. For eg - the sub-string "unemployment" comes first in the doc2 at index "4" so i want this document to be returned first in the results.

GET /text/_search?pretty
{
  "query": {
    "match": {
      "text": "unemployment"
    }
  }
}

I have tried few things like term_vector, here is the mapping that i used but it didn't help.

PUT text/_mapping
{
    "properties": {
        "name" : {
          "type" : "text",
          "fields" : {
            "keyword" : {
              "type" : "keyword"
            }
          }
        },
        "text" : {
          "type" : "text",
          "term_vector": "with_positions_offsets"
        }
      }
}

Can anyone please help me in making the right mapping and search Query?

Thanks in Advance!

Body:
Try this query

GET text/_search
{
  "query": {
    "function_score": {
      "query": {
        "match": {
          "text": "unemployment"
        }
      },
      "functions": [
        {
          "script_score": {
            "script": {
              "source": """
                def docval = doc['text.keyword'].value;
                def length = docval.length();
                def index = (float) docval.indexOf('unemployment');

                // the sooner the word appears the better so 'invert' the 'index'
                return index > -1 ? (1 / index) : 0;
              """
            }
          }
        }
      ],
      "boost_mode": "sum"
    }
  }
}

using the auto-generated mapping

{
  "text" : {
    "mappings" : {
      "properties" : {
        "name" : {
          "type" : "text",
          "fields" : {
            "keyword" : {
              "type" : "keyword",
              "ignore_above" : 256
            }
          }
        },
        "text" : {
          "type" : "text",
          "fields" : {
            "keyword" : {
              "type" : "keyword",
              "ignore_above" : 256
            }
          }
        }
      }
    }
  }
}

Note that this is case-sensitive so it'd be reasonable to have a lowercase-normalized keyword field too and then access it in the script score script. This might get you on the right path.


问:
Can't retrieve localized strings from Localizable.strings file
I'm unable to get the correct localized german strings from the Localizable.strings file. My app setup looks like this

Main.storyboard

Main.storyboard (Base)

Main.strings (German)  -> these strings are translated correctly

Localizable.strings

Localizable.strings (English)

Localizable.strings (German) -> can't get these strings

Inside the app I'm trying to get the string like this

```<code>NSString *item = NSLocalizedString(@"Group expenses", @"Menu item");
</code>```

The Localizable.strings (German) file looks like this

```<code>/* Menu item */
"Group expenses" = "Gruppenausgaben";
</code>```

When I set a breakpoint after item I always get the English string back, however the path for the resource seems correct NSString *path = [[NSBundle mainBundle] pathForResource:[[NSLocale preferredLanguages] objectAtIndex:0] ofType:@"lproj"];
gives me: /data/Containers/Bundle/Application/5E3ED6BF-71E1-4C60-9EDA-610C9A32B8EF/MyApp.app/de.lproj

I also have localized the string file

It's also included in Copy Bundle Resources

I tried several answers from different questions here on stackoverflow, like deleting app and do a clean (shift+cmd+k), setting application language under
Edit Scheme, ...

答:
Just had a similar issue was cracking my head, do a search of the xx.strings file I had an old copy of the bloody file messing me up.

```<code>find ./ -name "xx.strings" -print
</code>```

double check your string file is proper

```<code>plutil -lint  xx.strings
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm unable to get the correct localized german strings from the Localizable.strings file. My app setup looks like this

Main.storyboard

Main.storyboard (Base)

Main.strings (German)  -> these strings are translated correctly

Localizable.strings

Localizable.strings (English)

Localizable.strings (German) -> can't get these strings

Inside the app I'm trying to get the string like this

NSString *item = NSLocalizedString(@"Group expenses", @"Menu item");

The Localizable.strings (German) file looks like this

/* Menu item */
"Group expenses" = "Gruppenausgaben";

When I set a breakpoint after item I always get the English string back, however the path for the resource seems correct NSString *path = [[NSBundle mainBundle] pathForResource:[[NSLocale preferredLanguages] objectAtIndex:0] ofType:@"lproj"];
gives me: /data/Containers/Bundle/Application/5E3ED6BF-71E1-4C60-9EDA-610C9A32B8EF/MyApp.app/de.lproj

I also have localized the string file

It's also included in Copy Bundle Resources

I tried several answers from different questions here on stackoverflow, like deleting app and do a clean (shift+cmd+k), setting application language under
Edit Scheme, ...

Body:
Just had a similar issue was cracking my head, do a search of the xx.strings file I had an old copy of the bloody file messing me up.

find ./ -name "xx.strings" -print

double check your string file is proper

plutil -lint  xx.strings


问:
Why doesn't C# have support for first pass exception filtering?
Note: this is not a duplicate of Jeff's question.

That question asked "Is an equivalent?" I know there isn't, and I want to know why!

The reason I ask is that I've only just become clear on how important it is, and the conclusion seems very strange to me.

The Exception Handling block of Microsoft's Enterprise Library advises us to use this pattern:

```<code>catch (Exception x)
{
    if (ExceptionPolicy.HandleException(x, ExceptionPolicies.MyPolicy))
        throw;

    // recover from x somehow
}
</code>```

The policy is defined in an XML file, so that means that if a customer has an issue, we can modify the policy to assist with tracking down (or perhaps papering over) the problem to give them a fast resolution until we deal with it properly - which may involve arguing with 3rd parties, about whose fault it all is.

This is basically an acknowledgement of the simple fact that in real applications the number of exception types and their "recoverability" status is practically impossible to manage without a facility like this.

Meanwhile, the CLR team at MS says this is not an option, and it turns out those guys know what they're talking about! The problem is that right before the catch block runs, any finally blocks nested inside the try block will be executed. So those finally blocks may do any of the following:

Harmlessly modify the program state (phew, lucky).

Trash something important in the customer's data, because the program state is screwed up to an unknown degree.

Disguise or destroy important evidence that we need to diagnose an issue - especially if we're talking about calls into native code.

Throw another exception, adding to the general confusion and misery.

Note that the using statement and C++/CLI destructors are built on try/finally, so they're affected too.

So clearly the catch/throw pattern for filtering exceptions is no good. What is actually needed is a way to filter exceptions, via a policy, without actually catching them and so triggering the execution of finally blocks, unless we find a policy that tells us the exception is safe to recover from.

The CLR team blogged about this recently:

Catch, Rethrow and Filters - Why should you care?

Why catch(Exception)/empty catch is bad

The outcome is that we have to write a helper function in VB.NET to allow us to access this vital capability from C#. The big clue that there is a problem is that there is code in the BCL that does this. Lots of people have blogged about doing it, but they rarely if ever mention the thing about try/finally blocks, which is the killer.

What I would like to know is:

Are there any public statements or direct emails people have received from the C# team on this subject?

Are there any existing Microsoft Connect suggestions asking for this? I've heard rumours of them but none of the likely keywords turned up anything.

Update: as noted above, I have already searched on Microsoft Connect without finding anything. I have also (unsurprisingly) Googled. I've only found people explaining why they need this feature, or pointing out the advantages of it in VB.NET, or fruitlessly hoping that it will be added in a future version of C#, or working around it, And plenty of misleading advice. But no statement on the rationale for omitting it from all current versions of C#. And the reason I'm asking about existing Connect issues is so that (a) I don't create an unnecessary duplicate and (b) I can tell interested people if I have to create one.

Update 2: Found an interesting old blog post from Eric Gunnerson, formerly of the C# team:

"Yes, being able to put a condition on
  a catch is somewhat more convenient
  than having to write the test
  yourself, but it doesn't really enable
  you to do anything new."

That was the same assumption I had until it was properly explained to me!

答:
Using Exception Filter Inject may be simpler than using the delegate workaround.

For a real answer to your question you will need a response from Anders Hejlsberg, or someone who was in the original design meetings.  You might try seeing if you can get it asked by the Channel 9 interviewer next time the C# design team is interviewed.

I'd guess that when the original decision was made, exception filters were seen as an unnecessary complication that might do more harm than good.  You can certainly see a desire to remain 'silent' about unproven features in this interview about the decision not to support checked exceptions: The Trouble with Checked Exceptions
.

I think the postmoterm diagnostic scenarios argue strongly for providing access to exception filters in the language.  However those scenarios may not have been articulated at the time. Also those scenarios really need proper tooling support, which certainly wasn't available in V1.  Finally there may be big negatives about adding this feature that we are not considering.

If there isn't a connect bug on this you should enter one and encourage others to vote it up.  [I'd recommend asking for access to the CLR feature rather than attempting to design how it fits in the language.]

OwnerDisplayName: Earwicker

ContentLicense: CC BY-SA 2.5

Body:
Note: this is not a duplicate of Jeff's question.

That question asked "Is an equivalent?" I know there isn't, and I want to know why!

The reason I ask is that I've only just become clear on how important it is, and the conclusion seems very strange to me.

The Exception Handling block of Microsoft's Enterprise Library advises us to use this pattern:

catch (Exception x)
{
    if (ExceptionPolicy.HandleException(x, ExceptionPolicies.MyPolicy))
        throw;

    // recover from x somehow
}

The policy is defined in an XML file, so that means that if a customer has an issue, we can modify the policy to assist with tracking down (or perhaps papering over) the problem to give them a fast resolution until we deal with it properly - which may involve arguing with 3rd parties, about whose fault it all is.

This is basically an acknowledgement of the simple fact that in real applications the number of exception types and their "recoverability" status is practically impossible to manage without a facility like this.

Meanwhile, the CLR team at MS says this is not an option, and it turns out those guys know what they're talking about! The problem is that right before the catch block runs, any finally blocks nested inside the try block will be executed. So those finally blocks may do any of the following:

Harmlessly modify the program state (phew, lucky).

Trash something important in the customer's data, because the program state is screwed up to an unknown degree.

Disguise or destroy important evidence that we need to diagnose an issue - especially if we're talking about calls into native code.

Throw another exception, adding to the general confusion and misery.

Note that the using statement and C++/CLI destructors are built on try/finally, so they're affected too.

So clearly the catch/throw pattern for filtering exceptions is no good. What is actually needed is a way to filter exceptions, via a policy, without actually catching them and so triggering the execution of finally blocks, unless we find a policy that tells us the exception is safe to recover from.

The CLR team blogged about this recently:

Catch, Rethrow and Filters - Why should you care?

Why catch(Exception)/empty catch is bad

The outcome is that we have to write a helper function in VB.NET to allow us to access this vital capability from C#. The big clue that there is a problem is that there is code in the BCL that does this. Lots of people have blogged about doing it, but they rarely if ever mention the thing about try/finally blocks, which is the killer.

What I would like to know is:

Are there any public statements or direct emails people have received from the C# team on this subject?

Are there any existing Microsoft Connect suggestions asking for this? I've heard rumours of them but none of the likely keywords turned up anything.

Update: as noted above, I have already searched on Microsoft Connect without finding anything. I have also (unsurprisingly) Googled. I've only found people explaining why they need this feature, or pointing out the advantages of it in VB.NET, or fruitlessly hoping that it will be added in a future version of C#, or working around it, And plenty of misleading advice. But no statement on the rationale for omitting it from all current versions of C#. And the reason I'm asking about existing Connect issues is so that (a) I don't create an unnecessary duplicate and (b) I can tell interested people if I have to create one.

Update 2: Found an interesting old blog post from Eric Gunnerson, formerly of the C# team:

"Yes, being able to put a condition on
  a catch is somewhat more convenient
  than having to write the test
  yourself, but it doesn't really enable
  you to do anything new."

That was the same assumption I had until it was properly explained to me!

LastEditorDisplayName: Earwicker

OwnerDisplayName: Steve Steiner


问:
In numbers with range of values, how to move the decimal point left until a single digit integer remains in Python
I'd like to take a number like: 12345678 and turn it into 1.2345678, leaving only a single digit integer and whatever decimal.

Multiplying 12345678 by 0.0000001 works for the above example, but not if the number is 1234. The numbers change so a static multiplier will not work.

Is there a method available that would help? Bonus if it can be done within a pandas dataframe.

答:
Take below dataframe for example:

```<code>In [1192]: df
Out[1192]:
          a
0  12345678
1      1234
</code>```

You can use Python's basic string slicing:

```<code>In [1190]: df = df['a'].astype(str).str[0] + '.' + df['a'].astype(str).str[1:]

In [1191]: df
Out[1191]:
             a
0    1.2345678
1        1.234
Name: a, dtype: object
</code>```

Body:
Take below dataframe for example:

In [1192]: df
Out[1192]:
          a
0  12345678
1      1234

You can use Python's basic string slicing:

In [1190]: df = df['a'].astype(str).str[0] + '.' + df['a'].astype(str).str[1:]

In [1191]: df
Out[1191]:
             a
0    1.2345678
1        1.234
Name: a, dtype: object


问:
How to create a non-clustered index on a computed column in Entity Framework?
I'm calculating value of a column from another column and I need to create a non-clustered index on the calculated column.

When I try to specify index on the calculated column using Entity Framework, system throws an exception

An exception of type 'System.Data.SqlClient.SqlException' occurred in Microsoft.EntityFrameworkCore.Relational.dll but was not handled in user code

Additional information: Filtered index 'UK_ProdBarCode_BarCodeNumber' cannot be created on table 'ProdBarCode' because the column 'BarCodeNumber' in the filter expression is a computed column. Rewrite the filter expression so that it does not include this column.

```<code>prodbarcode.Property<long>(ProdBarCode =>
       ProdBarCode.BarCodeNumber).HasComputedColumnSql("CAST(BarCode AS Bigint)");

prodbarcode.HasIndex(ProdBarCode =>
       new { ProdBarCode.BarCodeNumber })
      .HasName("UK_ProdBarCode_BarCodeNumber")
      .IsUnique(true)
      .ForSqlServerIsClustered(false);
</code>```

答:
I ran into this problem today. Unfortunately, I wasn't able to find any information on this from Entity Framework or Microsoft. However, I did find a workaround for my situation.

If you add a filter yourself, and target the source column or columns, it should accomplish the same effect and it is valid SQL. See updated code below...

```<code>prodbarcode.Property<long>(ProdBarCode =>
       ProdBarCode.BarCodeNumber)
       .HasComputedColumnSql("CAST(BarCode AS Bigint)");

prodbarcode.HasIndex(ProdBarCode =>
       new { ProdBarCode.BarCodeNumber })
      .HasName("UK_ProdBarCode_BarCodeNumber")
      .IsUnique(true)
      .HasFilter($"{nameof(ProdBarCode.BarCode)} IS NOT NULL") // <-- filter on source field
      .ForSqlServerIsClustered(false);
</code>```

Body:
I'm calculating value of a column from another column and I need to create a non-clustered index on the calculated column.

When I try to specify index on the calculated column using Entity Framework, system throws an exception

An exception of type 'System.Data.SqlClient.SqlException' occurred in Microsoft.EntityFrameworkCore.Relational.dll but was not handled in user code

Additional information: Filtered index 'UK_ProdBarCode_BarCodeNumber' cannot be created on table 'ProdBarCode' because the column 'BarCodeNumber' in the filter expression is a computed column. Rewrite the filter expression so that it does not include this column.

prodbarcode.Property<long>(ProdBarCode =>
       ProdBarCode.BarCodeNumber).HasComputedColumnSql("CAST(BarCode AS Bigint)");

prodbarcode.HasIndex(ProdBarCode =>
       new { ProdBarCode.BarCodeNumber })
      .HasName("UK_ProdBarCode_BarCodeNumber")
      .IsUnique(true)
      .ForSqlServerIsClustered(false);

Body:
I ran into this problem today. Unfortunately, I wasn't able to find any information on this from Entity Framework or Microsoft. However, I did find a workaround for my situation.

If you add a filter yourself, and target the source column or columns, it should accomplish the same effect and it is valid SQL. See updated code below...

prodbarcode.Property<long>(ProdBarCode =>
       ProdBarCode.BarCodeNumber)
       .HasComputedColumnSql("CAST(BarCode AS Bigint)");

prodbarcode.HasIndex(ProdBarCode =>
       new { ProdBarCode.BarCodeNumber })
      .HasName("UK_ProdBarCode_BarCodeNumber")
      .IsUnique(true)
      .HasFilter($"{nameof(ProdBarCode.BarCode)} IS NOT NULL") // <-- filter on source field
      .ForSqlServerIsClustered(false);


问:
Select one value from XML Document
I just want ONE value from an XML file using VB. The XML file is this

```<code><?xml version="1.0" encoding="utf-8"?>
<Books>
    <Book ID="12345">
        <Name>One Flew Over The Cuckoo's Nest</Name>
        <ISBN>Some cataloging ID</ISBN>
        <Author>Ken Kesey</Author>
        <More>Something here</More>
    </Book>
</Books>
</code>```

In this example, I just want to get the ISBN number of the book with the Author "Ken Kesey." I tried this;

```<code>        Dim xl As XElement = XElement.Load(AppDomain.CurrentDomain.BaseDirectory + "\Books.xml")
        Dim Auth As String = From elem In xl.Elements("Books").Elements("Book")
                             Where elem.Element("ISBN").Value = "Some cataloging ID"
                             Select elem.Element("Author").Value
</code>```

And many variations of the same, to no effect.

Thank you for looking.

答:
More concise form (leverage VB.NET XML Literals):

Dim books =
    <?xml version="1.0" encoding="utf-8"?>
    <Books>
        <Book ID="12345">
            <Name>One Flew Over The Cuckoo's Nest</Name>
            <ISBN>Some cataloging ID</ISBN>
            <Author>Ken Kesey</Author>
            <More>Something here</More>
        </Book>
    </Books>
Dim isbn = books.<Books>.<Book>.Where(Function(b) b.<Author>.Value = "Ken Kesey").<ISBN>.Value
```

Title: Select one value from XML Document

Body:
I just want ONE value from an XML file using VB. The XML file is this

<?xml version="1.0" encoding="utf-8"?>
<Books>
    <Book ID="12345">
        <Name>One Flew Over The Cuckoo's Nest</Name>
        <ISBN>Some cataloging ID</ISBN>
        <Author>Ken Kesey</Author>
        <More>Something here</More>
    </Book>
</Books>

In this example, I just want to get the ISBN number of the book with the Author "Ken Kesey." I tried this;

        Dim xl As XElement = XElement.Load(AppDomain.CurrentDomain.BaseDirectory + "\Books.xml")
        Dim Auth As String = From elem In xl.Elements("Books").Elements("Book")
                             Where elem.Element("ISBN").Value = "Some cataloging ID"
                             Select elem.Element("Author").Value

And many variations of the same, to no effect.

Thank you for looking.


问:
A better method to clone original node element

          <button id="li"><button id="ol">

```

Button clones the parent element i.e li and appendChild() to
 and another one clones
 and appendChild() to .

I'm using innerHTML method to clone
 but I want only one
 element to be present in next child of body and it's not working What should be the method to get the result?-->

答: You can use Node.cloneNode() method, just don't forget to modify the id property ( you can remove it) so you don't end up with duplicate id's.

Body:
          <button id="li"><button id="ol">

Button clones the parent element i.e li and appendChild() to
 and another one clones
 and appendChild() to .

I'm using innerHTML method to clone
 but I want only one
 element to be present in next child of body and it's not working What should be the method to get the result?-->


问:
Google+ and LinkedIn share link for mobile application
I am trying to an implement stack of social buttons for mobile application. I got mobile links for Facebook and Twitter but I am not getting right link for LinkedIn and Google+ apps. Currently I have link http://m.linkedin.com/shareArticle?mini=true&url=www.example.com  but I think this links does not work properly and it shows webpage instead of big login box like twitter and facebook. Can someone please help me to get correct links for google+ and Linkedln?</p>

答:
LinkedIn URL Format:

```<code>https://www.linkedin.com/sharing/share-offsite/?url={url}
</code>```

Source: Official LinkedIn Documentation for Sharing.

Google+ Format:

Probably not useful anymore.  Google+ has discontinued.  Source: Google+ Blog.

Body:
LinkedIn URL Format:

https://www.linkedin.com/sharing/share-offsite/?url={url}

Source: Official LinkedIn Documentation for Sharing.

Google+ Format:

Probably not useful anymore.  Google+ has discontinued.  Source: Google+ Blog.


问:
Iterate through resource string table
I have a string table defined like this in my Win32 app:

```<code>STRINGTABLE
BEGIN
    IDS_STRING101           "myString1"
    IDS_STRING102           "myString2"
    IDS_STRING103           "myString3"
END
</code>```

Since I want all of these strings to be part of an array, is it possible to iterate through this table? Since LoadStringA() requires the macros IDS_STRING101 etc., it seems impossible to iterate through it.

For a practical example, how would I programatically move these strings to an array of strings (char* array in C, std::string array in C++) without using the obvious way of writing a long repetitive code of LoadStringA() calls with the second parameter IDS_STRINGXXX? If possible, I want to be able to add more strings to this table in the future without modifying anything in the code.

答:
how would I programatically move these strings to an array of strings

You could hide the tedious repetitions in a function or class.

Class example:

```<code>#include <stdexcept>
#include <string>
#include <unordered_map>

class StringLoader {
public:
    StringLoader(HINSTANCE inst) : hInstance(inst) {}

    std::pair<UINT,std::string> operator()(UINT uID) {
        const char* resptr;
        UINT len = LoadStringA(hInstance, uID, reinterpret_cast<LPSTR>(&resptr), 0);
        if(len==0) throw std::runtime_error("resource not found: "+std::to_string(uID));
        return {uID, {resptr, resptr+len}};
    }
private:
    HINSTANCE hInstance;
};

//... then use it:

    StringLoader l(the_instance);
    std::unordered_map<UINT, std::string> resources {
        l(IDS_STRING101),
        l(IDS_STRING102),
        l(IDS_STRING103)
    };
</code>```

You'll now have a map that you can iterate over, or use as a lookup table. If you only need the strings, you can replace the map with a vector and adjust StringLoader accordingly.

Title: Iterate through resource string table

Body:
I have a string table defined like this in my Win32 app:

STRINGTABLE
BEGIN
    IDS_STRING101           "myString1"
    IDS_STRING102           "myString2"
    IDS_STRING103           "myString3"
END

Since I want all of these strings to be part of an array, is it possible to iterate through this table? Since LoadStringA() requires the macros IDS_STRING101 etc., it seems impossible to iterate through it.

For a practical example, how would I programatically move these strings to an array of strings (char* array in C, std::string array in C++) without using the obvious way of writing a long repetitive code of LoadStringA() calls with the second parameter IDS_STRINGXXX? If possible, I want to be able to add more strings to this table in the future without modifying anything in the code.

Body:
how would I programatically move these strings to an array of strings

You could hide the tedious repetitions in a function or class.

Class example:

#include <stdexcept>
#include <string>
#include <unordered_map>

class StringLoader {
public:
    StringLoader(HINSTANCE inst) : hInstance(inst) {}

    std::pair<UINT,std::string> operator()(UINT uID) {
        const char* resptr;
        UINT len = LoadStringA(hInstance, uID, reinterpret_cast<LPSTR>(&resptr), 0);
        if(len==0) throw std::runtime_error("resource not found: "+std::to_string(uID));
        return {uID, {resptr, resptr+len}};
    }
private:
    HINSTANCE hInstance;
};

//... then use it:

    StringLoader l(the_instance);
    std::unordered_map<UINT, std::string> resources {
        l(IDS_STRING101),
        l(IDS_STRING102),
        l(IDS_STRING103)
    };

You'll now have a map that you can iterate over, or use as a lookup table. If you only need the strings, you can replace the map with a vector and adjust StringLoader accordingly.


问:
How can I display the results of arithetics operations in my calculator?
Currently, I am doing a calculator. I have run into some problems trying to get it to display the result. So far I have gotten it to store the numbers clicked into separate variables, but I can't get the correct result to display.

let numIni = "";
let numSub = "";
let op = "";
let calcResult = false;
//const text = display.innerText;
let result = 0;
clr();

//basic addition
function addition(numIni, numSub) {
  return parseFloat(numIni) + parseFloat(numSub);

}

//basic subtraction
function subtraction(numIni, numIni) {
  parseFloat(numIni) - parseFloat(numIni);
}

//basic Multiplication
function multiply(numIni, numIni) {
  parseFloat(numIni) * parseFloat(numIni);
}

//basic division
function divide(numIni, numIni) {
  parseFloat(numIni) / parseFloat(numIni);
}

//operator function
function operate(op) {
  let result;
  switch (op) {
    case "+":
      result = addition(numIni, numSub);
      break;
    case "-":
      result = subtraction(numIni, numIni);
      break;
    case "*":
      result = multiply(numIni, numIni);
      break;
    case "/":
      if (numSub == 0) {
        return "Can't do that";
      } else {
        result = divide(numIni, numIni);
      }
    default:
      return "Null";
  }
}
//button display functions
function disNum(val) {
  if (numIni == "") {
    parseFloat(document.getElementById("display").value += val);
    numIni = parseFloat(val);
  } else {
    parseFloat(document.getElementById("display").value += val);
    numSub = parseFloat(val);
  }

}

function disOp(val) {
  document.getElementById("display").value += val;
  return op = val;
}

function clr() {
  return document.getElementById("display").value = "";
}

function equal() {
  operate(numIni, numSub);
  document.getElementById("display").value = result;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><head>Calc</head>
<div>
  <input type="text" id="display">
</div>

<input type="button" value="0" onClick="disNum('0')">
<input type="button" value="1" onClick="disNum('1')">
<input type="button" value="2" onClick="disNum('2')">
<input type="button" value="3" onClick="disNum('3')">
<input type="button" value="4" onClick="disNum('4')">
<input type="button" value="5" onClick="disNum('5')">
<input type="button" value="6" onClick="disNum('6')">
<input type="button" value="7" onClick="disNum('7')">
<input type="button" value="8" onClick="disNum('8')">
<input type="button" value="9" onClick="disNum('9')">
<input type="button" value="+" onClick="disOp('+')">
<input type="button" value="-" onClick="disOp('-')">
<input type="button" value="*" onClick="disOp('*')">
<input type="button" value="/" onClick="disOp('/')">
<input type="button" value="=" onClick="equal()">
<input type="button" value="Clr" onClick="clr()"></code>```

答:
I've added a new input to store last result to hold numIni and previous operator. I've removed almost all variables from global scope to avoid unwanted changes.

Everytime that operator is clicked, check if there's previous result and operator, then get numSub from display input, do the math and save result, along with current operator if any.

I've tested it, but maybe there'll be some bugs.

let display = document.querySelector('#display');
let res = document.querySelector('#result');
clr();

//basic addition
function addition(numIni, numSub) {
  return parseFloat(numIni) + parseFloat(numSub);
}

//basic subtraction
function subtraction(numIni, numSub) {
  return parseFloat(numIni) - parseFloat(numSub);
}

//basic Multiplication
function multiply(numIni, numSub) {
  return parseFloat(numIni) * parseFloat(numSub);
}

//basic division
function divide(numIni, numSub) {
  return parseFloat(numIni) / parseFloat(numSub);
}

//operator function
function operate(op, numIni, numSub) {
  let result = 0;
  switch (op) {
    case "+":
      result = addition(numIni, numSub);
      break;
    case "-":
      result = subtraction(numIni, numSub);
      break;
    case "*":
      result = multiply(numIni, numSub);
      break;
    case "/":
      if (numSub == 0) {
        result = "Can't do that";
      } else {
        result = divide(numIni, numSub);
      }
      break;
    default:
      result = "Null";
  }
  return result;
}
//button display functions
function disNum(val) {
  parseFloat(display.value += val);
}

function disOp(val) {
  // Get last result
  let value = (res.value == '') ? '0' : res.value;
  // Search for valid operator stored previously
  let tmp = value.split('').pop();
  // Is it a valid previous operator?
  op = (['+', '-', '*', '/'].indexOf(tmp) == -1) ? '' : tmp;
  let numIni = parseFloat(value) || 0;
  let numSub = parseFloat(display.value) || 0;

  if(op == '') {
      // No previous operator
      if(res.value == "Can't do that" || res.value == 'Null') {
          res.value = '';
      } else if(display.value != '') {
          // Only if we have a value to show
          res.value = numSub;
      }
      // Don't add = as previous operator
      if(val != '=') {
          res.value += val;
      }
  } else if(display.value != '') {
      // Only do math if we have a value
      res.value = operate(op, numIni, numSub);
      // Don't add = as previous operator
      if(val != '=') {
          res.value += val;
      }
  }
  // Clear display, numIni will be taken from result
  display.value = '';
}

function clr() {
  res.value = '';
  display.value = '';
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>input[type=text] {
  text-align: right;
}</code>```

Calc

  <input type="text" id="result" disabled placeholder="Result">

  <input type="text" id="display">

<input type="button" value="1" onClick="disNum('1')">
<input type="button" value="2" onClick="disNum('2')">
<input type="button" value="3" onClick="disNum('3')">
<input type="button" value="+" onClick="disOp('+')">

<input type="button" value="4" onClick="disNum('4')">
<input type="button" value="5" onClick="disNum('5')">
<input type="button" value="6" onClick="disNum('6')">
<input type="button" value="-" onClick="disOp('-')">

<input type="button" value="7" onClick="disNum('7')">
<input type="button" value="8" onClick="disNum('8')">
<input type="button" value="9" onClick="disNum('9')">
<input type="button" value="*" onClick="disOp('*')">

<input type="button" value="     0     " onClick="disNum('0')">
<input type="button" value="/" onClick="disOp('/')">
<input type="button" value="=" onClick="disOp('=')">

<input type="button" value="Clear" onClick="clr()">```

Body:
Currently, I am doing a calculator. I have run into some problems trying to get it to display the result. So far I have gotten it to store the numbers clicked into separate variables, but I can't get the correct result to display.

let numIni = "";
let numSub = "";
let op = "";
let calcResult = false;
//const text = display.innerText;
let result = 0;
clr();

//basic addition
function addition(numIni, numSub) {
  return parseFloat(numIni) + parseFloat(numSub);

}

//basic subtraction
function subtraction(numIni, numIni) {
  parseFloat(numIni) - parseFloat(numIni);
}

//basic Multiplication
function multiply(numIni, numIni) {
  parseFloat(numIni) * parseFloat(numIni);
}

//basic division
function divide(numIni, numIni) {
  parseFloat(numIni) / parseFloat(numIni);
}

//operator function
function operate(op) {
  let result;
  switch (op) {
    case "+":
      result = addition(numIni, numSub);
      break;
    case "-":
      result = subtraction(numIni, numIni);
      break;
    case "*":
      result = multiply(numIni, numIni);
      break;
    case "/":
      if (numSub == 0) {
        return "Can't do that";
      } else {
        result = divide(numIni, numIni);
      }
    default:
      return "Null";
  }
}
//button display functions
function disNum(val) {
  if (numIni == "") {
    parseFloat(document.getElementById("display").value += val);
    numIni = parseFloat(val);
  } else {
    parseFloat(document.getElementById("display").value += val);
    numSub = parseFloat(val);
  }

}

function disOp(val) {
  document.getElementById("display").value += val;
  return op = val;
}

function clr() {
  return document.getElementById("display").value = "";
}

function equal() {
  operate(numIni, numSub);
  document.getElementById("display").value = result;
}

Calc

  <input type="text" id="display">

<input type="button" value="0" onClick="disNum('0')">
<input type="button" value="1" onClick="disNum('1')">
<input type="button" value="2" onClick="disNum('2')">
<input type="button" value="3" onClick="disNum('3')">
<input type="button" value="4" onClick="disNum('4')">
<input type="button" value="5" onClick="disNum('5')">
<input type="button" value="6" onClick="disNum('6')">
<input type="button" value="7" onClick="disNum('7')">
<input type="button" value="8" onClick="disNum('8')">
<input type="button" value="9" onClick="disNum('9')">
<input type="button" value="+" onClick="disOp('+')">
<input type="button" value="-" onClick="disOp('-')">
<input type="button" value="*" onClick="disOp('*')">
<input type="button" value="/" onClick="disOp('/')">
<input type="button" value="=" onClick="equal()">
<input type="button" value="Clr" onClick="clr()">

Body:
I've added a new input to store last result to hold numIni and previous operator. I've removed almost all variables from global scope to avoid unwanted changes.

Everytime that operator is clicked, check if there's previous result and operator, then get numSub from display input, do the math and save result, along with current operator if any.

I've tested it, but maybe there'll be some bugs.

let display = document.querySelector('#display');
let res = document.querySelector('#result');
clr();

//basic addition
function addition(numIni, numSub) {
  return parseFloat(numIni) + parseFloat(numSub);
}

//basic subtraction
function subtraction(numIni, numSub) {
  return parseFloat(numIni) - parseFloat(numSub);
}

//basic Multiplication
function multiply(numIni, numSub) {
  return parseFloat(numIni) * parseFloat(numSub);
}

//basic division
function divide(numIni, numSub) {
  return parseFloat(numIni) / parseFloat(numSub);
}

//operator function
function operate(op, numIni, numSub) {
  let result = 0;
  switch (op) {
    case "+":
      result = addition(numIni, numSub);
      break;
    case "-":
      result = subtraction(numIni, numSub);
      break;
    case "*":
      result = multiply(numIni, numSub);
      break;
    case "/":
      if (numSub == 0) {
        result = "Can't do that";
      } else {
        result = divide(numIni, numSub);
      }
      break;
    default:
      result = "Null";
  }
  return result;
}
//button display functions
function disNum(val) {
  parseFloat(display.value += val);
}

function disOp(val) {
  // Get last result
  let value = (res.value == '') ? '0' : res.value;
  // Search for valid operator stored previously
  let tmp = value.split('').pop();
  // Is it a valid previous operator?
  op = (['+', '-', '*', '/'].indexOf(tmp) == -1) ? '' : tmp;
  let numIni = parseFloat(value) || 0;
  let numSub = parseFloat(display.value) || 0;

  if(op == '') {
      // No previous operator
      if(res.value == "Can't do that" || res.value == 'Null') {
          res.value = '';
      } else if(display.value != '') {
          // Only if we have a value to show
          res.value = numSub;
      }
      // Don't add = as previous operator
      if(val != '=') {
          res.value += val;
      }
  } else if(display.value != '') {
      // Only do math if we have a value
      res.value = operate(op, numIni, numSub);
      // Don't add = as previous operator
      if(val != '=') {
          res.value += val;
      }
  }
  // Clear display, numIni will be taken from result
  display.value = '';
}

function clr() {
  res.value = '';
  display.value = '';
}

input[type=text] {
  text-align: right;
}

<head>Calc</head>
<div>
  <input type="text" id="result" disabled placeholder="Result"><br>
  <input type="text" id="display">
</div>

<input type="button" value="1" onClick="disNum('1')">
<input type="button" value="2" onClick="disNum('2')">
<input type="button" value="3" onClick="disNum('3')">
<input type="button" value="+" onClick="disOp('+')"><br>
<input type="button" value="4" onClick="disNum('4')">
<input type="button" value="5" onClick="disNum('5')">
<input type="button" value="6" onClick="disNum('6')">
<input type="button" value="-" onClick="disOp('-')"><br>
<input type="button" value="7" onClick="disNum('7')">
<input type="button" value="8" onClick="disNum('8')">
<input type="button" value="9" onClick="disNum('9')">
<input type="button" value="*" onClick="disOp('*')"><br>
<input type="button" value="     0     " onClick="disNum('0')">
<input type="button" value="/" onClick="disOp('/')">
<input type="button" value="=" onClick="disOp('=')"><br>
<input type="button" value="Clear" onClick="clr()">


问:
How can i display and bring column value out of foreach loop and out of table in MVC view?
I have the follwing code in MVC view :

```<code><div class="tab-pane container active" id="home">
            <h5 class="text-uppercase p-2 text-center">Parasitology Department</h5>
            <table class="table table-bordered" cellpadding="5" cellspacing="5" border="1">
                <thead>
                    <tr>
                        <th>@Html.DisplayNameFor(m => m.LabParaResult.FirstOrDefault().patient_no)</th>
                        <th>@Html.DisplayNameFor(m => m.LabParaResult.FirstOrDefault().SERIAL)</th>
                        <th>@Html.DisplayNameFor(m => m.LabParaResult.FirstOrDefault().TEXT)</th>
                        <th>@Html.DisplayNameFor(m => m.LabParaResult.FirstOrDefault().VALUE)</th>
                        <th>@Html.DisplayNameFor(m => m.LabParaResult.FirstOrDefault().unit)</th>
                        <th>@Html.DisplayNameFor(m => m.LabParaResult.FirstOrDefault().reference_range)</th>
                        <th>@Html.DisplayNameFor(m => m.LabParaResult.FirstOrDefault().APPROVED_DATE)</th>
                        <th>@Html.DisplayNameFor(m => m.patients.FirstOrDefault().Patient_Name)</th>
                        <th>@Html.DisplayNameFor(m => m.labtests.FirstOrDefault().TestName)</th>

                    </tr>
                </thead>
                @foreach (var employee in Model.LabParaResult.Where(x => para.Contains(x.LabTests.Dept_id.GetValueOrDefault())))
            {
                    <tr>
                        <td>@employee.patient_no</td>
                        <td>@employee.SERIAL</td>
                        <td>@employee.TEXT</td>
                        <td>@employee.VALUE</td>
                        <td>@employee.unit</td>
                        <td>@employee.reference_range</td>
                        <td>@employee.APPROVED_DATE</td>
                        <td>@employee.Patients.Patient_Name</td>
                        <td>@employee.LabTests.TestName</td>

                    </tr>
                }
            </table>
        </div>
</code>```

I need to bring and read the test name and patient name out of the foreach loop and out of table and show it next of Parasitology Department in the same row:

```<code><h5 class="text-uppercase p-2 text-center">Parasitology Department</h5>
<td>@employee.Patients.Patient_Name</td>
 <td>@employee.LabTests.TestName</td>
</code>```

答:
You can try the following code , if you dont have that columns in the table LabParaResult you can create SQL SERVER VIEW to read data you need from multiple tables and call it here  : </p>

```<code><dl>
 <dd >@Html.DisplayFor(model => model.LabParaResult.First().Test_Name)</dd>
 <dd >@Html.DisplayFor(model => model.LabParaResult.First().Patient_Name)</dd>
 </dl>
</code>```

Body:
I have the follwing code in MVC view :

Parasitology Department

                        @Html.DisplayNameFor(m => m.LabParaResult.FirstOrDefault().patient_no)
                        @Html.DisplayNameFor(m => m.LabParaResult.FirstOrDefault().SERIAL)
                        @Html.DisplayNameFor(m => m.LabParaResult.FirstOrDefault().TEXT)
                        @Html.DisplayNameFor(m => m.LabParaResult.FirstOrDefault().VALUE)
                        @Html.DisplayNameFor(m => m.LabParaResult.FirstOrDefault().unit)
                        @Html.DisplayNameFor(m => m.LabParaResult.FirstOrDefault().reference_range)
                        @Html.DisplayNameFor(m => m.LabParaResult.FirstOrDefault().APPROVED_DATE)
                        @Html.DisplayNameFor(m => m.patients.FirstOrDefault().Patient_Name)
                        @Html.DisplayNameFor(m => m.labtests.FirstOrDefault().TestName)

                @foreach (var employee in Model.LabParaResult.Where(x => para.Contains(x.LabTests.Dept_id.GetValueOrDefault())))
            {

                        @employee.patient_no
                        @employee.SERIAL
                        @employee.TEXT
                        @employee.VALUE
                        @employee.unit
                        @employee.reference_range
                        @employee.APPROVED_DATE
                        @employee.Patients.Patient_Name
                        @employee.LabTests.TestName

                }

I need to bring and read the test name and patient name out of the foreach loop and out of table and show it next of Parasitology Department in the same row:

Parasitology Department

@employee.Patients.Patient_Name
 @employee.LabTests.TestName

Body:
You can try the following code , if you dont have that columns in the table LabParaResult you can create SQL SERVER VIEW to read data you need from multiple tables and call it here  :

<dl>
 <dd >@Html.DisplayFor(model => model.LabParaResult.First().Test_Name)</dd>
 <dd >@Html.DisplayFor(model => model.LabParaResult.First().Patient_Name)</dd>
 </dl>


问:
Regex to match item in csv string
I have a string that's a csv of 5-6 digit numbers.
I.e.
'12345,67890,555555'. There can also be spaces in before/after a number. So ' 123456 , 12345,22222'.

I was initially doing my regex match of
`Trying to see in '12345' is in a csv

```<code> const csv = '12345,67890,555555';
   const regex = /12345/
   regex.test(csv);
</code>```

`

But I'm seeing this introduces false positive of if another character can exist before the test. I.e. It's also matching on '012345', etc.

What's the best way to search here? I'm doing my matches with regex matches with Mongo DB filters btw

答:
var csv = '12345,67890,555555';
var csv2 = '012345,67890,555555';
var regex = /\b12345\b/;
console.log(regex.test(csv)); //true
console.log(regex.test(csv2)); //false```

\b is the word boundary.

Title: Regex to match item in csv string

Body:
I have a string that's a csv of 5-6 digit numbers.
I.e.
'12345,67890,555555'. There can also be spaces in before/after a number. So ' 123456 , 12345,22222'.

I was initially doing my regex match of
`Trying to see in '12345' is in a csv

 const csv = '12345,67890,555555';
   const regex = /12345/
   regex.test(csv);

`

But I'm seeing this introduces false positive of if another character can exist before the test. I.e. It's also matching on '012345', etc.

What's the best way to search here? I'm doing my matches with regex matches with Mongo DB filters btw

Body:
var csv = '12345,67890,555555';
var csv2 = '012345,67890,555555';
var regex = /\b12345\b/;
console.log(regex.test(csv)); //true
console.log(regex.test(csv2)); //false

\b is the word boundary.


问:
React Native - Register Screen not working
I can't submit a form. My states:

```<code>function RegisterScreen({ navigation }) {
  const [formData, setFormData] = React.useState({
    name: "",
    surname: "",
    email: "",
    password: "",
    password2: "",
  });
</code>```

onSubmit:

```<code>const onSubmit = async (e) => {
    const { name, email, password, password2 } = formData;
    console.log(formData);
  };
</code>```

Return here: Inputs. I did onChangeText and value here.

```<code>return (
  <View>
      <TextInput
        placeholder={i18n.t("name")}
        value={formData.name}
        onChangeText={(name) => setFormData(name)}
        id="name"
        required
      />
    <TextInput
      placeholder={i18n.t("email")}
      value={formData.email}
      onChangeText={(email) => setFormData(email)}
      id="email"
      required
    />
    <TextInput
      secureTextEntry={true}
      placeholder={i18n.t("password")}
      value={formData.password}
      onChangeText={(password) => setFormData(password)}
      id="password"
    />

    <Button
      title={i18n.t("register")}
      onPress={() => onSubmit()}
    />
  </View>
);   }
</code>```

It just returns password. I am expecting all form data. I think the code has an error.

答:
it's because this is overwriting everything at the end:

onChangeText={(password) => setFormData(password)}

you need to do

```<code>onChangeText={(name) => setFormData({...formData, name})}
onChangeText={(email) => setFormData({...formData, email})}
onChangeText={(password) => setFormData({...formData, password})}
</code>```

Body:
I can't submit a form. My states:

function RegisterScreen({ navigation }) {
  const [formData, setFormData] = React.useState({
    name: "",
    surname: "",
    email: "",
    password: "",
    password2: "",
  });

onSubmit:

const onSubmit = async (e) => {
    const { name, email, password, password2 } = formData;
    console.log(formData);
  };

Return here: Inputs. I did onChangeText and value here.

return (
  <View>
      <TextInput
        placeholder={i18n.t("name")}
        value={formData.name}
        onChangeText={(name) => setFormData(name)}
        id="name"
        required
      />
    <TextInput
      placeholder={i18n.t("email")}
      value={formData.email}
      onChangeText={(email) => setFormData(email)}
      id="email"
      required
    />
    <TextInput
      secureTextEntry={true}
      placeholder={i18n.t("password")}
      value={formData.password}
      onChangeText={(password) => setFormData(password)}
      id="password"
    />

    <Button
      title={i18n.t("register")}
      onPress={() => onSubmit()}
    />
  </View>
);   }

It just returns password. I am expecting all form data. I think the code has an error.

Body:
it's because this is overwriting everything at the end:

onChangeText={(password) => setFormData(password)}

you need to do

onChangeText={(name) => setFormData({...formData, name})}
onChangeText={(email) => setFormData({...formData, email})}
onChangeText={(password) => setFormData({...formData, password})}


问:
aws graphql @connection not returning an array as expected?
I have a graphql model as follows (a user can have many posts 1:m)

```<code>type User @model {
  id: ID!
  fullName: String!
  emailAddress: String!
  posts: [Post] @connection(name: "UserPostConnection")
}

type Post @model {
  id: ID!
  text: String!
  user: User @connection(name: "UserPostConnection")
  createdAt: String
  updatedAt: String
}
</code>```

I am trying to return all the posts for a specific user, as so:

```<code>let queryInput = GetUserQuery(id: "879db4f2-1dad-47b9-b70d-8bca15bf2549")

appSyncClient?.fetch(query: queryInput, cachePolicy: .fetchIgnoringCacheData) { (result, error) in
            print(result?.data?.getUser?.posts)
        }
}
</code>```

However the result isn't returning an array, it is returning an optional:

```<code>Optional(AWSStackSocial.GetUserQuery.Data.GetUser.Post(snapshot: ["__typename": Optional("ModelPostConnection"), "nextToken": nil]))
</code>```

I have confirmed that a) the user exists, and b) the posts also exists.

On AWS:

```<code>query {
    getUser(id: "879db4f2-1dad-47b9-b70d-8bca15bf2549") {
      id
    posts {
      items {
        id
      }
    }
    }
}
</code>```

Output:

```<code>{
  "data": {
    "getUser": {
      "id": "879db4f2-1dad-47b9-b70d-8bca15bf2549",
      "posts": {
        "items": [
          {
            "id": "04c4b571-6e92-4745-9a40-1a67a9d49d77"
          },
          {
            "id": "0f44fe6e-4e15-4a8c-b591-555e8fa1f60e"
          },
          {
            "id": "60c18c40-fea3-4ff3-8b21-df6857703dd2"
          }
        ]
      }
    }
  }
}
</code>```

答:
I found the answer.  The default depth level for amplify GraphQL is 2, so this needed to be changed to 3.  This can be done by changing the maximum depth:</p>

```<code>amplify codegen configure
</code>```

Body:
I have a graphql model as follows (a user can have many posts 1:m)

type User @model {
  id: ID!
  fullName: String!
  emailAddress: String!
  posts: [Post] @connection(name: "UserPostConnection")
}

type Post @model {
  id: ID!
  text: String!
  user: User @connection(name: "UserPostConnection")
  createdAt: String
  updatedAt: String
}

I am trying to return all the posts for a specific user, as so:

let queryInput = GetUserQuery(id: "879db4f2-1dad-47b9-b70d-8bca15bf2549")

appSyncClient?.fetch(query: queryInput, cachePolicy: .fetchIgnoringCacheData) { (result, error) in
            print(result?.data?.getUser?.posts)
        }
}

However the result isn't returning an array, it is returning an optional:

Optional(AWSStackSocial.GetUserQuery.Data.GetUser.Post(snapshot: ["__typename": Optional("ModelPostConnection"), "nextToken": nil]))

I have confirmed that a) the user exists, and b) the posts also exists.

On AWS:

query {
    getUser(id: "879db4f2-1dad-47b9-b70d-8bca15bf2549") {
      id
    posts {
      items {
        id
      }
    }
    }
}

Output:

{
  "data": {
    "getUser": {
      "id": "879db4f2-1dad-47b9-b70d-8bca15bf2549",
      "posts": {
        "items": [
          {
            "id": "04c4b571-6e92-4745-9a40-1a67a9d49d77"
          },
          {
            "id": "0f44fe6e-4e15-4a8c-b591-555e8fa1f60e"
          },
          {
            "id": "60c18c40-fea3-4ff3-8b21-df6857703dd2"
          }
        ]
      }
    }
  }
}

Body:
I found the answer.  The default depth level for amplify GraphQL is 2, so this needed to be changed to 3.  This can be done by changing the maximum depth:

amplify codegen configure


问:
How to use custom icon fonts?
I'm creating a cross-platform application with Nativescript and Angular.
I had a custom font icon that I want to use. I had some svg files that I turned into a ttf file. When I use the chars with their unicode code it shows nothing.

What I've done is this:

Put the ttf file on /src/fonts/icomoon.ttf (the same level of app)

Insert this code on app.css file

.ico {
    font-family: icomoon, icomoon;
    font-weight: normal;
}
```

<p>In the home.component.html file I'm using it like this:</p>

```

```

<p>Where am I wrong? Did I miss something?</p>

<p>P.S.: the unicode codes go from e900 to e907</p>

<p>P.P.S: I've already used Fontawesome and it works with this code. Now I want to use my own font and this code doesn't work.</p>

<p><strong>EDIT</strong></p>

<p>I use this guide and I modified something.</p>

<p>In <code>home.component.html</code> file I have: </p>

```
```

<p>I addedd the file <code>app/assets/icomoon.css</code> in which I put this:</p>

<pre class="lang-css prettyprint-override"><code>  font-family: 'icomoon';
  src: url('../../fonts/icomoon');
  src: url('../../fonts/icomoon') format('embedded-opentype'), url('../../fonts/icomoon') format('woff2'), url('../../fonts/icomoon') format('woff'), url('../../fonts/icomoon') format('truetype'), url('../../fonts/icomoon') format('svg');
  font-weight: normal;
  font-style: normal;
}

.ico {
  display: inline-block;
  font: normal normal normal 14px/1 icomoon;
  font-size: inherit;
  text-rendering: auto;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
}

.ico-link:before {
  content: "\ue904";
}

</code>```

and in app.ts I added:

```<code>@NgModule({
    bootstrap: [
        AppComponent
    ],
    imports: [
       //...
       TNSFontIconModule.forRoot({
                'ico': './assets/icomoon.css'
            })
     ]
    //...
   });
</code>```

After all this it still doesn't work. The icon isn't show.

答:
I had the same issue, I notice that it is required to use the whole format , then I moved to that awesome icon plugin.

Try

```<code><Label row="0" col="1" text="" class="ico" style="color:white; margin-right:20;" (tap)="showAlert()" />
</code>```

Also, remember that Android and IOs handle naming different, please check with using the new docs.

Note: In iOS your font file should be named exactly as the font name. If you have any doubts about the original font name, use the Font Book app to get the original font name.

Icon Fonts Nativescript/Angular

Title: How to use custom icon fonts?

Body:
I'm creating a cross-platform application with Nativescript and Angular.
I had a custom font icon that I want to use. I had some svg files that I turned into a ttf file. When I use the chars with their unicode code it shows nothing.

What I've done is this:

Put the ttf file on /src/fonts/icomoon.ttf (the same level of app)

Insert this code on app.css file

.ico {
    font-family: icomoon, icomoon;
    font-weight: normal;
}

In the home.component.html file I'm using it like this:

Where am I wrong? Did I miss something?

P.S.: the unicode codes go from e900 to e907

P.P.S: I've already used Fontawesome and it works with this code. Now I want to use my own font and this code doesn't work.

EDIT

I use this guide and I modified something.

In home.component.html file I have:

I addedd the file app/assets/icomoon.css in which I put this:

  font-family: 'icomoon';
  src: url('../../fonts/icomoon');
  src: url('../../fonts/icomoon') format('embedded-opentype'), url('../../fonts/icomoon') format('woff2'), url('../../fonts/icomoon') format('woff'), url('../../fonts/icomoon') format('truetype'), url('../../fonts/icomoon') format('svg');
  font-weight: normal;
  font-style: normal;
}

.ico {
  display: inline-block;
  font: normal normal normal 14px/1 icomoon;
  font-size: inherit;
  text-rendering: auto;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
}

.ico-link:before {
  content: "\ue904";
}

and in app.ts I added:

@NgModule({
    bootstrap: [
        AppComponent
    ],
    imports: [
       //...
       TNSFontIconModule.forRoot({
                'ico': './assets/icomoon.css'
            })
     ]
    //...
   });

After all this it still doesn't work. The icon isn't show.

Body:
I had the same issue, I notice that it is required to use the whole format &#xe924;, then I moved to that awesome icon plugin.

Try

<Label row="0" col="1" text="&#xe924;" class="ico" style="color:white; margin-right:20;" (tap)="showAlert()" />

Also, remember that Android and IOs handle naming different, please check with using the new docs.

Note: In iOS your font file should be named exactly as the font name. If you have any doubts about the original font name, use the Font Book app to get the original font name.

Icon Fonts Nativescript/Angular


答:
I would just adjust your regex to use anchors.  Anchors restrict where your match can be, without matching any additional characters.  In this case, I believe you need to anchor to a word boundary on both sides, which will require that the character on either side of 12345 is not a "word character" (Any alphanumeric character or an underscore).  This means it could be next to a comma, space, beginning of line, or end of line in your case.  The token for a word boundary is \b.  This makes your regex: const regex = /\b12345\b/.

You can also avoid using regex by writing your own test() function.  Assuming you know that your CSV is comma-delimited, you can split the string by commas, store the result in an array, and then loop through that array, checking if each element is equal to the string you're looking for.  This could be implemented like so:

function test(needle, haystack) {
    let arr = haystack.split(",");

    for (let str of arr) {
        if (str === needle) {
            return true;
        }
    }

    return false;
}
```

Title: Regex to match item in csv string


问:
Playing local video files in macOS SwiftUI application using AVPlayer
I am trying to create a simple SwiftUI application using XCode 11.5 on macOS 10.15.4 using AVKit/AVFoundation to play videos stored on the local file system. I would like to be able to select the movie based on a file path determined by the user's actions (e.g. selecting from a series of menu options).

I am working from a code snippet found here: https://qiita.com/croquette0212/items/eb97e970d1dcfa2932fd

```<code>import SwiftUI
import AVKit
import AVFoundation

class VideoItem: ObservableObject {
    @Published var player: AVPlayer = AVPlayer()
    @Published var playerItem: AVPlayerItem?

    func open(_ url: URL) {
        let asset = AVAsset(url: url)
        let playerItem = AVPlayerItem(asset: asset)
        self.playerItem = playerItem
        player.replaceCurrentItem(with: playerItem)
    }
}

struct PlayerView: NSViewRepresentable {
    @Binding var player: AVPlayer

    func updateNSView(_ NSView: NSView, context: NSViewRepresentableContext<PlayerView>) {
        guard let view = NSView as? AVPlayerView else {
            debugPrint("unexpected view")
            return
        }

        view.player = player
    }

    func makeNSView(context: Context) -> NSView {
        return AVPlayerView(frame: .zero)
    }
}

struct ContentView: View {
    @ObservedObject var videoItem: VideoItem = VideoItem()

    var body: some View {
        VStack {
            if videoItem.playerItem != nil {
                PlayerView(player: $videoItem.player)
            }
            Button(action: {
                let panel = NSOpenPanel()
                panel.allowedFileTypes = [kUTTypeMovie as String]
                DispatchQueue.main.async {
                    if panel.runModal() == .OK {
                        guard let url = panel.url else {
                            return
                        }
                        self.videoItem.open(url)
                    }
                }
            }) {
                Text("Open")
            }
        }.frame(maxWidth: .infinity, maxHeight: .infinity)
    }
}
</code>```

This works perfectly well for selecting a file using the "panel" object, but I can't figure out the simple change of passing my own value of "url" to videoItem.open().

I have tried replacing the block:

```<code>let panel = NSOpenPanel()
panel.allowedFileTypes = [kUTTypeMovie as String]
DispatchQueue.main.async {
    if panel.runModal() == .OK {
        guard let url = panel.url else {
           return
        }
        self.videoItem.open(url)
    }
}
</code>```

, defining my value of "url" using URL(string:) or Bundle.main.url(forResource:, withExtension: ) or other options without any success. The application compiles and runs without error, but it does not display the video, only a placeholder image indicating that the file was not found.

I don't understand what the difference is between the value of "url" returned from panel.url and the values that I am manually assigning. I've checked the contents of panel.url using .absoluteString and this matches exactly the values which I am manually assigning.

I am surely missing something very obvious but I can't see what it is. Please, can anybody provide some help?

答:
Simple solution to this problem: make sure that the video file is being bundled with the target application.

I thought I was doing so, but apparently not, and a way to check (XCode 11) is:

click video file in the Project Navigator window and then,

tick the Target Membership box next to the target App in the File

Inspector window

That's it. Credit for this answer belongs to https://github.com/SergioEstevao/ who has a AVPlayer solution for SwiftUI applications: https://github.com/SergioEstevao/SVEVideoUI that does exactly what I was looking for.

Body:
I am trying to create a simple SwiftUI application using XCode 11.5 on macOS 10.15.4 using AVKit/AVFoundation to play videos stored on the local file system. I would like to be able to select the movie based on a file path determined by the user's actions (e.g. selecting from a series of menu options).

I am working from a code snippet found here: https://qiita.com/croquette0212/items/eb97e970d1dcfa2932fd

import SwiftUI
import AVKit
import AVFoundation

class VideoItem: ObservableObject {
    @Published var player: AVPlayer = AVPlayer()
    @Published var playerItem: AVPlayerItem?

    func open(_ url: URL) {
        let asset = AVAsset(url: url)
        let playerItem = AVPlayerItem(asset: asset)
        self.playerItem = playerItem
        player.replaceCurrentItem(with: playerItem)
    }
}

struct PlayerView: NSViewRepresentable {
    @Binding var player: AVPlayer

    func updateNSView(_ NSView: NSView, context: NSViewRepresentableContext<PlayerView>) {
        guard let view = NSView as? AVPlayerView else {
            debugPrint("unexpected view")
            return
        }

        view.player = player
    }

    func makeNSView(context: Context) -> NSView {
        return AVPlayerView(frame: .zero)
    }
}

struct ContentView: View {
    @ObservedObject var videoItem: VideoItem = VideoItem()

    var body: some View {
        VStack {
            if videoItem.playerItem != nil {
                PlayerView(player: $videoItem.player)
            }
            Button(action: {
                let panel = NSOpenPanel()
                panel.allowedFileTypes = [kUTTypeMovie as String]
                DispatchQueue.main.async {
                    if panel.runModal() == .OK {
                        guard let url = panel.url else {
                            return
                        }
                        self.videoItem.open(url)
                    }
                }
            }) {
                Text("Open")
            }
        }.frame(maxWidth: .infinity, maxHeight: .infinity)
    }
}

This works perfectly well for selecting a file using the "panel" object, but I can't figure out the simple change of passing my own value of "url" to videoItem.open().

I have tried replacing the block:

let panel = NSOpenPanel()
panel.allowedFileTypes = [kUTTypeMovie as String]
DispatchQueue.main.async {
    if panel.runModal() == .OK {
        guard let url = panel.url else {
           return
        }
        self.videoItem.open(url)
    }
}

, defining my value of "url" using URL(string:) or Bundle.main.url(forResource:, withExtension: ) or other options without any success. The application compiles and runs without error, but it does not display the video, only a placeholder image indicating that the file was not found.

I don't understand what the difference is between the value of "url" returned from panel.url and the values that I am manually assigning. I've checked the contents of panel.url using .absoluteString and this matches exactly the values which I am manually assigning.

I am surely missing something very obvious but I can't see what it is. Please, can anybody provide some help?


问:
Can i have the compiler ignore OS-Specific methods
I have a simple little console game which heavily relies on user input to move around a game board. Originally, we were implementing standard input and dealing with having to press enter for each move; However, we are now looking into platform specific user input methods so we can stick to moving on char press instead of waiting for an enter keypress.

To do this, we've set up our environment like so:

```<code>#if defined(_WIN32) || defined(_WIN64) || defined(_WINDOWS_)
    #define PLATFORM_NAME "windows" // Windows
    #include <conio.h>
#elif defined(__APPLE__) || defined(__linux__)
    #define PLATFORM_NAME "unix"
#endif
</code>```

we plan to use _getch() when a windows platform is detected, otherwise use getchar() for unix based.

currently we have our input calls set up like so:

```<code>void handleKeybinds() {
    char ascii = 0;
    if (PLATFORM_NAME == "windows") {
        ascii = tolower(_getch());
    } else {
        system("/bin/stty raw");
        ascii = tolower(getchar());
        system("/bin/stty cooked");
    }
    //move player
}
</code>```

this works completely fine when compiling on windows (seeing as how conio.h is compatible) however, results in an undefined _getch() since conio is not included as a header file on a linux server. How would we make the compiler completely ignore this line when on anything other than windows, similarly to how the header only includes conio.h when on a windows system.

Thank you!

答:
Thanks to BessieTheCow for the help! I got my user input working on both platforms! As mentioned above in their comment, I have moved the platform define checking to where the input is being recorded, which allows for the compiler to ignore the undeclared methods on the alternate platforms!

```<code>char GameBoard::getInputs() {
    char ascii = 0;
    #if defined(_WIN32) || defined(_WIN64) || defined(_WINDOWS_)
        ascii = tolower(_getch());
    #else
        system("/bin/stty raw");
        ascii = tolower(getchar());
        system("/bin/stty cooked");
    #endif

    return ascii;
}
</code>```

Thanks for the help!

Body:
I have a simple little console game which heavily relies on user input to move around a game board. Originally, we were implementing standard input and dealing with having to press enter for each move; However, we are now looking into platform specific user input methods so we can stick to moving on char press instead of waiting for an enter keypress.

To do this, we've set up our environment like so:

#if defined(_WIN32) || defined(_WIN64) || defined(_WINDOWS_)
    #define PLATFORM_NAME "windows" // Windows
    #include <conio.h>
#elif defined(__APPLE__) || defined(__linux__)
    #define PLATFORM_NAME "unix"
#endif

we plan to use _getch() when a windows platform is detected, otherwise use getchar() for unix based.

currently we have our input calls set up like so:

void handleKeybinds() {
    char ascii = 0;
    if (PLATFORM_NAME == "windows") {
        ascii = tolower(_getch());
    } else {
        system("/bin/stty raw");
        ascii = tolower(getchar());
        system("/bin/stty cooked");
    }
    //move player
}

this works completely fine when compiling on windows (seeing as how conio.h is compatible) however, results in an undefined _getch() since conio is not included as a header file on a linux server. How would we make the compiler completely ignore this line when on anything other than windows, similarly to how the header only includes conio.h when on a windows system.

Thank you!

Body:
Thanks to BessieTheCow for the help! I got my user input working on both platforms! As mentioned above in their comment, I have moved the platform define checking to where the input is being recorded, which allows for the compiler to ignore the undeclared methods on the alternate platforms!

char GameBoard::getInputs() {
    char ascii = 0;
    #if defined(_WIN32) || defined(_WIN64) || defined(_WINDOWS_)
        ascii = tolower(_getch());
    #else
        system("/bin/stty raw");
        ascii = tolower(getchar());
        system("/bin/stty cooked");
    #endif

    return ascii;
}

Thanks for the help!


问:
NodeJS via Serverless, path(s) for public assets?
Just converted my NodeJS webapp to serverless, but I'm confused how to describe the access for the public/ folder (images, javascripts, stylesheets).  I've seen syntax for {proxy+} and {id}, but the documentation I've read it's not clear if these apply to this situation.  How do I make sure all the assets in my public/{images, javascripts, stylesheets} are correctly pathed in my serverless.yml?

Note: I've tried stylesheets/* in the serverless.yml but I get a String/type error.

The below is valid, but does not work when I try to access aws-apigw-blahblah.com/dev/stylesheets/custom.css, getting a "Missing Authentication Token".

```<code>    events:
      - http:
          path: /
          method: GET
          cors: true
      - http:
          path: stylesheets
          method: GET
          cors: true
</code>```

答:
(self answer after more research)

Serverless needs to off a webapp strictly from the point of view of an API, that is each http verb of GET, POST, etc.  Any of the static content (images, custom JS) should be offered from another source such as S3.  The serverless syntax doesn't accommodate events down to individual static assets, rather just the APIable verbs.  See this AWS page, and the diagram with S3 flow at the top, and API-GW+Lambda at the bottom.

I extricated items from my public folder and put up on S3, and fit small bits of custom JS into the actual ejs file.  Otherwise it would be a more complex deploy pipeline to update the S3 assets upon serverless deploy.

Body:
Just converted my NodeJS webapp to serverless, but I'm confused how to describe the access for the public/ folder (images, javascripts, stylesheets).  I've seen syntax for {proxy+} and {id}, but the documentation I've read it's not clear if these apply to this situation.  How do I make sure all the assets in my public/{images, javascripts, stylesheets} are correctly pathed in my serverless.yml?

Note: I've tried stylesheets/* in the serverless.yml but I get a String/type error.

The below is valid, but does not work when I try to access aws-apigw-blahblah.com/dev/stylesheets/custom.css, getting a "Missing Authentication Token".

    events:
      - http:
          path: /
          method: GET
          cors: true
      - http:
          path: stylesheets
          method: GET
          cors: true


问:
Flutter widget not running initState and passing it into a Widget correctly
I have the below code, and the idea is that when the user logs in, they are pushed to this page ('dashboard'). I am trying to use initState to make the app run the function takenSurvey2(), which then creates a value for the bool takenSurvey. This comes from querying Cloud Firestore.

The value for the bool takenSurvey would then be used in the Stack's Positioned widget to determine which icon to show the user (if the user hasn't taken the survey (i.e. takenSurvey  = false) they would be shown a 'new' icon.

However what happens at the moment is that when the user logs in and the page loads, and the error icon shows, so the widget thinks that takenSurvey does not have a value of true or false. However, when I create an arbitrary button and use OnPressed to print the value of takenSurvey, it shows up as 'false' in the console. When I hot reload the dashboard page the error icon turns to the 'new' icon, as I expected - why doesn't it do this straight away?

I'm not sure what I'm doing wrong, and why the widget can't see the value of takenSurvey, even though takenSurvey2() has been run in initState, and I've wrapped it in a Builder widget?

```<code>      class Dashboard extends StatefulWidget {
      static const String id = 'dashboard';
      @override
      _DashboardState createState() => _DashboardState();
    }

    class _DashboardState extends State<Dashboard> {
      final _auth = FirebaseAuth.instance;
      var userid;
      String surveyName;
      bool takenSurvey;
      String title;

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

    getCurrentUser();
    getUserID();
    currentSurveyName();
    takenSurvey2();
  }

void takenSurvey2() async {
    final snapShot = await Firestore.instance
        .collection('$surveyName' + '_entrants')
        .document(userid)
        .get();
    if (snapShot.exists) {
      takenSurvey = true;
    } else {
      takenSurvey = false;
    }
  }

 @override   Widget build(BuildContext context) {
      body: SingleChildScrollView(
        child: Container(
          padding: EdgeInsets.symmetric(horizontal: 24.0),
          child: Column(
              mainAxisAlignment: MainAxisAlignment.start,
              children: <Widget>[
               Stack(
                  alignment: Alignment.center,
                  children: <Widget>[
                    Container(
                      width: MediaQuery.of(context).size.width * 0.9,
                      child: SquareButton(
                          buttonTitle: "",
                          fontSize: 36,
                          onPressed: () async {
                            final snapShot = await Firestore.instance
                                .collection('$surveyName' + '_entrants')
                                .document(userid)
                                .get();
                            if (snapShot.exists) {
                              _alreadyCompletedSurveyError();
                            } else if (surveyName.isEmpty)
                              _otherError();
                            else {
                              return Navigator.push(
                                  context,
                                  new MaterialPageRoute(
                                      builder: (BuildContext context) =>
                                          new TestSurvey(surveyName)));
                            }
                          }),
                    ),
                    Positioned(
                      right: 30,
                      top: 20,
                      child: Builder(builder: (context) {
                        if (takenSurvey == false) {
                          return Icon(
                            Foundation.burst_new,
                            size: 48,
                            color: Color(0xff303841),
                          );
                        } else if (takenSurvey == true) {
                          return Icon(
                            Foundation.check,
                            size: 48,
                            color: Color(0xff303841),
                          );
                        } else
                          return Icon(
                            MaterialIcons.error,
                            size: 48,
                            color: Color(0xff303841),
                          );
                      }),
                    ),
                    Container(
                      child: Text('Latest Survey',
                          style: TextStyle(
                              color: Colors.white,
                              fontSize: 36,
                              fontFamily: "Roboto")),
</code>```

答:
can you try adding a async func in initstate?

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

void test() async {
    await getCurrentUser();
    await getUserID();
    await currentSurveyName();
    await takenSurvey2();
}

```

Body:
I have the below code, and the idea is that when the user logs in, they are pushed to this page ('dashboard'). I am trying to use initState to make the app run the function takenSurvey2(), which then creates a value for the bool takenSurvey. This comes from querying Cloud Firestore.

The value for the bool takenSurvey would then be used in the Stack's Positioned widget to determine which icon to show the user (if the user hasn't taken the survey (i.e. takenSurvey  = false) they would be shown a 'new' icon.

However what happens at the moment is that when the user logs in and the page loads, and the error icon shows, so the widget thinks that takenSurvey does not have a value of true or false. However, when I create an arbitrary button and use OnPressed to print the value of takenSurvey, it shows up as 'false' in the console. When I hot reload the dashboard page the error icon turns to the 'new' icon, as I expected - why doesn't it do this straight away?

I'm not sure what I'm doing wrong, and why the widget can't see the value of takenSurvey, even though takenSurvey2() has been run in initState, and I've wrapped it in a Builder widget?

      class Dashboard extends StatefulWidget {
      static const String id = 'dashboard';
      @override
      _DashboardState createState() => _DashboardState();
    }

    class _DashboardState extends State<Dashboard> {
      final _auth = FirebaseAuth.instance;
      var userid;
      String surveyName;
      bool takenSurvey;
      String title;

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

    getCurrentUser();
    getUserID();
    currentSurveyName();
    takenSurvey2();
  }

void takenSurvey2() async {
    final snapShot = await Firestore.instance
        .collection('$surveyName' + '_entrants')
        .document(userid)
        .get();
    if (snapShot.exists) {
      takenSurvey = true;
    } else {
      takenSurvey = false;
    }
  }

 @override   Widget build(BuildContext context) {
      body: SingleChildScrollView(
        child: Container(
          padding: EdgeInsets.symmetric(horizontal: 24.0),
          child: Column(
              mainAxisAlignment: MainAxisAlignment.start,
              children: <Widget>[
               Stack(
                  alignment: Alignment.center,
                  children: <Widget>[
                    Container(
                      width: MediaQuery.of(context).size.width * 0.9,
                      child: SquareButton(
                          buttonTitle: "",
                          fontSize: 36,
                          onPressed: () async {
                            final snapShot = await Firestore.instance
                                .collection('$surveyName' + '_entrants')
                                .document(userid)
                                .get();
                            if (snapShot.exists) {
                              _alreadyCompletedSurveyError();
                            } else if (surveyName.isEmpty)
                              _otherError();
                            else {
                              return Navigator.push(
                                  context,
                                  new MaterialPageRoute(
                                      builder: (BuildContext context) =>
                                          new TestSurvey(surveyName)));
                            }
                          }),
                    ),
                    Positioned(
                      right: 30,
                      top: 20,
                      child: Builder(builder: (context) {
                        if (takenSurvey == false) {
                          return Icon(
                            Foundation.burst_new,
                            size: 48,
                            color: Color(0xff303841),
                          );
                        } else if (takenSurvey == true) {
                          return Icon(
                            Foundation.check,
                            size: 48,
                            color: Color(0xff303841),
                          );
                        } else
                          return Icon(
                            MaterialIcons.error,
                            size: 48,
                            color: Color(0xff303841),
                          );
                      }),
                    ),
                    Container(
                      child: Text('Latest Survey',
                          style: TextStyle(
                              color: Colors.white,
                              fontSize: 36,
                              fontFamily: "Roboto")),


问:
is it possible to explain why this returns 21
Hello this isn't an assignment or anything but can you explain why this returns 2 1.</p>
```<code>#include <string>
using namespace std;
void fun(int);
int main()
{
    int a = 0;
    fun(a);
    return 0;
}

void fun(int n)
{
    if (n < 2)
    {
        fun(++n);
        cout << n<<" ";
    }
}
</code>```

答:
Firstly function will not return anything until you add a return statement in the function, In your case you are not returning the value, you wrote a statement to print/display the current value of 'n' initially you set a=0 and calling a function "fun(a)" and passing the value of "a" So, in the "fun" function you added a condition which says the value of "n" should be smaller than "2", then you are using the recursive method(a function that calls itself) and pre incrementing "++n" the value of "n" and passing it in the fun function.

```<code>n = 0
fun(n)

fun(0){

if (n < 2) *first call true

    {
        fun(++n); *n = 1 before going to next condition it is calling itself*
        cout << 1<<" ";
    }

}
fun(1){

if (n < 2) *true*

    {
        fun(++n); *n = 2 again before going to next condition it is calling itself*
        cout << 2<<" ";
    }

}
fun(2){

if (n < 2) *flase*

    {
        fun(++n);
        cout << n<<" ";
    }

}
</code>```

So, it will print 2 and then 1.
flow of Recursive function

I hope you get your answer.

Body:
Hello this isn't an assignment or anything but can you explain why this returns 2 1.

#include <string>
using namespace std;
void fun(int);
int main()
{
    int a = 0;
    fun(a);
    return 0;
}

void fun(int n)
{
    if (n < 2)
    {
        fun(++n);
        cout << n<<" ";
    }
}

Body:
Firstly function will not return anything until you add a return statement in the function, In your case you are not returning the value, you wrote a statement to print/display the current value of 'n' initially you set a=0 and calling a function "fun(a)" and passing the value of "a" So, in the "fun" function you added a condition which says the value of "n" should be smaller than "2", then you are using the recursive method(a function that calls itself) and pre incrementing "++n" the value of "n" and passing it in the fun function.

n = 0
fun(n)

fun(0){

if (n < 2) *first call true

    {
        fun(++n); *n = 1 before going to next condition it is calling itself*
        cout << 1<<" ";
    }

}
fun(1){

if (n < 2) *true*

    {
        fun(++n); *n = 2 again before going to next condition it is calling itself*
        cout << 2<<" ";
    }

}
fun(2){

if (n < 2) *flase*

    {
        fun(++n);
        cout << n<<" ";
    }

}

So, it will print 2 and then 1.
flow of Recursive function

I hope you get your answer.


问:
How do i return column that contains images
I'm trying to build a widget that returns column of widgets, my code is like this

```<code>    import 'package:flutter/material.dart';

class ProductList extends StatelessWidget {

  String productImage;
  String productName;
  double productPrice;

  ProductList({this.productImage, this.productPrice, this.productName});

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Column(
        children: <Widget>[
          Image(image: Image.asset(productImage)),
          Text(productName),
          Text(productPrice.toString())

        ],
      ),
    );
  }
}
</code>```

Im getting error on line 16 which is  Image(image: Image.asset(productImage)),

the error message is The argument type 'Image' can't be assigned to the parameter type 'ImageProvider<dynamic>'.
How do i fix this

答: You shouldn't use the Image widget that way, to display an asset image just use Image.asset(productImage). Right now you're putting an image Image.asset(), inside the Image() widget, hence the error.

Body:
I'm trying to build a widget that returns column of widgets, my code is like this

    import 'package:flutter/material.dart';

class ProductList extends StatelessWidget {

  String productImage;
  String productName;
  double productPrice;

  ProductList({this.productImage, this.productPrice, this.productName});

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Column(
        children: <Widget>[
          Image(image: Image.asset(productImage)),
          Text(productName),
          Text(productPrice.toString())

        ],
      ),
    );
  }
}

Im getting error on line 16 which is  Image(image: Image.asset(productImage)),

the error message is The argument type 'Image' can't be assigned to the parameter type 'ImageProvider<dynamic>'.
How do i fix this


问:
Python not writing whole output into file
I am trying to join every_line in a txt file with a header text. But after successfully joining
up the lines. I cannot seem to write the file correctly as it will only write the last joined line into the internallinks.txt. How can I make it to write the whole output of combined into the file?

Any help would be appreciated, thank you very much!

Python code

```<code>with open(r"C:\Users\xingj\Desktop\writing.txt") as f:
    internallink = ("www.icom.org.cn")
    for every_line in f:
        combined = (internallink + every_line.strip())
        out_str = "".join(combined)

with open("C:\\Users\\xingj\\internallinks.txt",'w') as b:
    b.write(out_str)
</code>```

Content of writing.txt

```<code>/icom/faculty/viewer/?id=1122
/icom/faculty/viewer/?id=1125
/icom/faculty/viewer/?id=586&
/icom/faculty/viewer/?id=1126
/icom/faculty/viewer/?id=470&
</code>```

Output of internallinks.txt

```<code>www.icom.org.cn/icom/faculty/viewer/?id=470&
</code>```

Output of command print (combined) before with is closed

```<code>PS C:\Users\xingj> & python c:/Users/xingj/testingagain.py
www.icom.org.cn/icom/faculty/viewer/?id=1122
www.icom.org.cn/icom/faculty/viewer/?id=1125
www.icom.org.cn/icom/faculty/viewer/?id=586&
www.icom.org.cn/icom/faculty/viewer/?id=1126
www.icom.org.cn/icom/faculty/viewer/?id=470&
PS C:\Users\xingj>
</code>```

答:
Maybe you'd like a nested approach:</p>

```<code>with open(r"C:\Users\xingj\Desktop\writing.txt") as f, open("C:\\Users\\xingj\\internallinks.txt",'w') as b:
    for line in f:
        b.write('www.icom.org.cn'+line)
</code>```

Body:
I am trying to join every_line in a txt file with a header text. But after successfully joining
up the lines. I cannot seem to write the file correctly as it will only write the last joined line into the internallinks.txt. How can I make it to write the whole output of combined into the file?

Any help would be appreciated, thank you very much!

Python code

with open(r"C:\Users\xingj\Desktop\writing.txt") as f:
    internallink = ("www.icom.org.cn")
    for every_line in f:
        combined = (internallink + every_line.strip())
        out_str = "".join(combined)

with open("C:\\Users\\xingj\\internallinks.txt",'w') as b:
    b.write(out_str)

Content of writing.txt

/icom/faculty/viewer/?id=1122
/icom/faculty/viewer/?id=1125
/icom/faculty/viewer/?id=586&
/icom/faculty/viewer/?id=1126
/icom/faculty/viewer/?id=470&

Output of internallinks.txt

www.icom.org.cn/icom/faculty/viewer/?id=470&

Output of command print (combined) before with is closed

PS C:\Users\xingj> & python c:/Users/xingj/testingagain.py
www.icom.org.cn/icom/faculty/viewer/?id=1122
www.icom.org.cn/icom/faculty/viewer/?id=1125
www.icom.org.cn/icom/faculty/viewer/?id=586&
www.icom.org.cn/icom/faculty/viewer/?id=1126
www.icom.org.cn/icom/faculty/viewer/?id=470&
PS C:\Users\xingj>

Body:
Maybe you'd like a nested approach:

with open(r"C:\Users\xingj\Desktop\writing.txt") as f, open("C:\\Users\\xingj\\internallinks.txt",'w') as b:
    for line in f:
        b.write('www.icom.org.cn'+line)


问:
Is there anyway to disable the Grid caching in Dynamics AX?
Preferably something that will disable this useless, annoying feature globally.

Update 1

By default, Dynamics AX shows only the first 20 rows of a grid. This is an awful feature. I cannot see how much data is in the grid at a glance. I cannot quickly scroll to the data I want because once you get past 19 it only has "Go To Last Record" and then changes to only the last 20 records.

Or: How can I make grids just show all their data?

This feature is working as designed, it's just a crap feature.

Update 2

I've added an image to illustrate what I'm talking about. This lookup is only showing the first 10 rows. As soon as you move the scroll bar to the bottom, all you see is Go to the last record. I have no way of knowing if there are 20 choices or 2000! This behaviour is the same in normal grids as well, although I think they show 20 rows instead.

Update 3

I was informed by our companies AX guru that he did manage to disable this caching, although it required changes on the SQL Server end and introduced several stability issues. Since no-one was able to provide an answer, I'll leave this question open.

答:
AX (as most systems around) does not fetch all records from the table to the form because it uses a SQL cursor. It will typically limit the number of records fetched in the first round to between 20 and 50. This is usually optimal behaviour as the number of records is not known beforehand.

And no, it cannot be disabled.

Ressources: Top tips ...