问:
Triple-nested form with Rails form_with and strong parameters
I'm running Rails 6.0.0.rc1 and having trouble getting a triple nested form working. I have products that have options that have option_values. So a Product might have an option called "Color" and an Option Value named "Red." I'd like to create all of these in a classic nested form in the Product form.

The form works and I can save Product with an Option, but not the Option Value on submit. I'm not sure why it's not working when I try to embed fields_for Option Values inside the fields_for Options.

What am I doing wrong here? I feel like I'm missing something obvious, but can't figure it out. (Probably not relevant, but note that I need to scope each object to account_id and my User has_one :account that's the reason for the hidden field.)

Here is my product model:

```<code>class Product < ApplicationRecord
  belongs_to :account

  has_many :options, dependent: :destroy
  accepts_nested_attributes_for :options, allow_destroy: true

  validates :account_id,  presence: true
  validates :name,        presence: true
end
</code>```

Option model:

```<code>class Option < ApplicationRecord
  belongs_to :account
  belongs_to :product

  has_many :option_values, dependent: :destroy
  accepts_nested_attributes_for :option_values, allow_destroy: true

  validates :account_id,  presence: true
  validates :name,        presence: true
end
</code>```

OptionValue model:

```<code>class OptionValue < ApplicationRecord
  belongs_to :account
  belongs_to :option

  validates :account_id,  presence: true
  validates :name,        presence: true
end
</code>```

Here's the Product form:

```<code><%= form_with(model: product, local: true) do |f| %>
  <%= f.fields_for :options do |options_form| %>
    <fieldset class='form-group'>
      <%= options_form.hidden_field :account_id, value: current_user.account.id %>
      <%= options_form.label :name, 'Option' %>
      <%= options_form.text_field :name, class: 'form-control' %>
    </fieldset>

    <%= f.fields_for :option_values do |values_form| %>
      <fieldset class='form-group'>
        <%= values_form.label :name, 'Value' %>
        <%= values_form.text_field :name, class: 'form-control' %>
      </fieldset>
    <% end %>
  <% end %>
<% end %>
</code>```

ProductsController:

```<code>class ProductsController < ApplicationController
  def new
    @product = Product.new
    @product.options.build
  end

  def create
    @account = current_user.account
    @product = @account.products.build(product_params)

    respond_to do |format|
      if @product.save
        format.html { redirect_to @product, notice: 'Product was successfully created.' }
      else
        format.html { render :new }
      end
    end
  end

  private
    def product_params
      params.require(:product).permit(
        :account_id, :name,
        options_attributes: [
          :id, :account_id, :name, :_destroy,
          option_values_attributes:[:id, :account_id, :name, :_destroy ]
        ]
      )
    end
end
</code>```

答:
Update:

Because I was trying to follow along this Nested Form Railscast, the biggest problem was that I didn't realize that the version Ryan Bates has working is on "Edit", not "New", so I added the Products, Options, and Values via the console and got the form working with this code:

_form.html.erb

```<code>  <%= f.fields_for :options do |builder| %>
    <%= render 'option_fields', f: builder %>
  <% end %>
</code>```

_option_fields.html.erb

```<code><fieldset class='form-group'>
  <%= f.hidden_field :account_id, value: current_user.account.id %>

  <%= f.label :name, 'Option' %>
  <%= f.text_field :name, class: 'form-control' %>
  <br>
  <%= f.check_box :_destroy, class: 'form-check-input' %>
  <%= f.label :_destroy, 'Remove Option' %>

  <small id="optionHelp" class="form-text text-muted">
    (e.g. "Size" or "Color")
  </small>

  <%= f.fields_for :option_values do |builder| %>
    <%= render 'option_value_fields', f: builder %>
  <% end %>

</fieldset>
</code>```

_option_value_fields.html.erb

```<code><fieldset class='form-group'>
  <%= f.hidden_field :account_id, value: current_user.account.id %>
  <%= f.label :name, 'Value' %>
  <%= f.text_field :name, class: 'form-control' %>
  <br>
  <%= f.check_box :_destroy, class: 'form-check-input' %>
  <%= f.label :_destroy, 'Remove Value' %>

  <small id="optionValueHelp" class="form-text text-muted">
    (e.g. "Small, Medium, Large" or "Red, Green, Blue")
  </small>
</fieldset>
</code>```

Also, the only difference with the Railscast is using strong parameters in the controller, so you'll just need to nest them like this:

ProductsController

```<code>def product_params
      params.require(:product).permit(:account_id, :name, options_attributes [:id, :account_id, :name, :_destroy, option_values_attributes: [:id, :account_id, :name, :_destroy]])
end
</code>```

OptionsController

```<code>def option_params
     params.require(:option).permit(:account_id, :name, option_values_attributes [:id, :account_id, :name, :_destroy])
end
</code>```

OptionValuesController

```<code>def option_value_params
     params.require(:option_value).permit(:account_id, :option_id, :name)
end
</code>```

Rather than building the nested objects in the controller I'm going to do it with Javascript as in the Railscast episode or with the Cocoon gem as Vasilisa suggested in her answer.

Just wanted to share the code that actually ended up working in case someone else runs into similar problems. I think the Railscast, though old, is still a great introduction to nested forms in Rails, but you just have to be aware of the changes required to use form_with and strong parameters. Big thanks to Vasilisa for helping me figure this out.

The main "gotchas" that you need to look out for when following the Rails Nested Form Railscast are this:

form_with has some different syntax than the older rails form_tag

Make sure you don't have any typos or name problems when creating your form blocks because these are nested twice

Same with nesting parameters in your controllers, just be aware of your syntax and typos

Be aware that Ryan Bates is demoing with data that wasn't added through the form he's building so if you'd like to follow along you'll need to create some data in the console

With strong parameters you'll have to explicitly list :_destroy as a parameter in order for his "Remove" checkboxes to work

Body:
I'm running Rails 6.0.0.rc1 and having trouble getting a triple nested form working. I have products that have options that have option_values. So a Product might have an option called "Color" and an Option Value named "Red." I'd like to create all of these in a classic nested form in the Product form.

The form works and I can save Product with an Option, but not the Option Value on submit. I'm not sure why it's not working when I try to embed fields_for Option Values inside the fields_for Options.

What am I doing wrong here? I feel like I'm missing something obvious, but can't figure it out. (Probably not relevant, but note that I need to scope each object to account_id and my User has_one :account that's the reason for the hidden field.)

Here is my product model:

class Product < ApplicationRecord
  belongs_to :account

  has_many :options, dependent: :destroy
  accepts_nested_attributes_for :options, allow_destroy: true

  validates :account_id,  presence: true
  validates :name,        presence: true
end

Option model:

class Option < ApplicationRecord
  belongs_to :account
  belongs_to :product

  has_many :option_values, dependent: :destroy
  accepts_nested_attributes_for :option_values, allow_destroy: true

  validates :account_id,  presence: true
  validates :name,        presence: true
end

OptionValue model:

class OptionValue < ApplicationRecord
  belongs_to :account
  belongs_to :option

  validates :account_id,  presence: true
  validates :name,        presence: true
end

Here's the Product form:

<%= form_with(model: product, local: true) do |f| %>
  <%= f.fields_for :options do |options_form| %>
    <fieldset class='form-group'>
      <%= options_form.hidden_field :account_id, value: current_user.account.id %>
      <%= options_form.label :name, 'Option' %>
      <%= options_form.text_field :name, class: 'form-control' %>
    </fieldset>

    <%= f.fields_for :option_values do |values_form| %>
      <fieldset class='form-group'>
        <%= values_form.label :name, 'Value' %>
        <%= values_form.text_field :name, class: 'form-control' %>
      </fieldset>
    <% end %>
  <% end %>
<% end %>

ProductsController:

class ProductsController < ApplicationController
  def new
    @product = Product.new
    @product.options.build
  end

  def create
    @account = current_user.account
    @product = @account.products.build(product_params)

    respond_to do |format|
      if @product.save
        format.html { redirect_to @product, notice: 'Product was successfully created.' }
      else
        format.html { render :new }
      end
    end
  end

  private
    def product_params
      params.require(:product).permit(
        :account_id, :name,
        options_attributes: [
          :id, :account_id, :name, :_destroy,
          option_values_attributes:[:id, :account_id, :name, :_destroy ]
        ]
      )
    end
end

Body:
Update:

Because I was trying to follow along this Nested Form Railscast, the biggest problem was that I didn't realize that the version Ryan Bates has working is on "Edit", not "New", so I added the Products, Options, and Values via the console and got the form working with this code:

_form.html.erb

  <%= f.fields_for :options do |builder| %>
    <%= render 'option_fields', f: builder %>
  <% end %>

_option_fields.html.erb

<fieldset class='form-group'>
  <%= f.hidden_field :account_id, value: current_user.account.id %>

  <%= f.label :name, 'Option' %>
  <%= f.text_field :name, class: 'form-control' %>
  <br>
  <%= f.check_box :_destroy, class: 'form-check-input' %>
  <%= f.label :_destroy, 'Remove Option' %>

  <small id="optionHelp" class="form-text text-muted">
    (e.g. "Size" or "Color")
  </small>

  <%= f.fields_for :option_values do |builder| %>
    <%= render 'option_value_fields', f: builder %>
  <% end %>

</fieldset>

_option_value_fields.html.erb

<fieldset class='form-group'>
  <%= f.hidden_field :account_id, value: current_user.account.id %>
  <%= f.label :name, 'Value' %>
  <%= f.text_field :name, class: 'form-control' %>
  <br>
  <%= f.check_box :_destroy, class: 'form-check-input' %>
  <%= f.label :_destroy, 'Remove Value' %>

  <small id="optionValueHelp" class="form-text text-muted">
    (e.g. "Small, Medium, Large" or "Red, Green, Blue")
  </small>
</fieldset>

Also, the only difference with the Railscast is using strong parameters in the controller, so you'll just need to nest them like this:

ProductsController

def product_params
      params.require(:product).permit(:account_id, :name, options_attributes [:id, :account_id, :name, :_destroy, option_values_attributes: [:id, :account_id, :name, :_destroy]])
end

OptionsController

def option_params
     params.require(:option).permit(:account_id, :name, option_values_attributes [:id, :account_id, :name, :_destroy])
end

OptionValuesController

def option_value_params
     params.require(:option_value).permit(:account_id, :option_id, :name)
end

Rather than building the nested objects in the controller I'm going to do it with Javascript as in the Railscast episode or with the Cocoon gem as Vasilisa suggested in her answer.

Just wanted to share the code that actually ended up working in case someone else runs into similar problems. I think the Railscast, though old, is still a great introduction to nested forms in Rails, but you just have to be aware of the changes required to use form_with and strong parameters. Big thanks to Vasilisa for helping me figure this out.

The main "gotchas" that you need to look out for when following the Rails Nested Form Railscast are this:

form_with has some different syntax than the older rails form_tag

Make sure you don't have any typos or name problems when creating your form blocks because these are nested twice

Same with nesting parameters in your controllers, just be aware of your syntax and typos

Be aware that Ryan Bates is demoing with data that wasn't added through the form he's building so if you'd like to follow along you'll need to create some data in the console

With strong parameters you'll have to explicitly list :_destroy as a parameter in order for his "Remove" checkboxes to work


来源: stackexchange

问:
Flutter upgrade fail
When I attempt to update Flutter I get the following error.

error: Your local changes to the following files would be overwritten
  by merge:
    examples/flutter_gallery/ios/Runner.xcodeproj/project.pbxproj

Please
  commit your changes or stash them before you merge.

Aborting Updating
  f9bb4289e..5ab9e7072 Process finished with exit code 1

I suspect at some point I did something in the examples project and I don't care about loosing the changes.

What is the easiest thing to do?

答:
This happened to me too! What i did that worked was to rename flutter.gradle to anything e.g flutttttterrrr.gradle then run flutter upgrade command again.

The file is located at C:\your_flutter_location\flutter_main_folder\packages\flutter_tools\gradle

Hope this helps someone.

ContentLicense: CC BY-SA 4.0

Title: Flutter upgrade fail


问:
Necessity of const specifier in cast
Suppose I have some code like this:

```<code>void foo (void *ptr) {
    const struct some *azaza = (const struct some *)ptr;
    azaza->some_field = 123; // inadvertently assignment => error
    // ...
</code>```

Is the const specifier really needed in cast?

EDIT: foo is callback function with a particular prototype that I can't change (it's not in my code).

答:
If I understand your question, you want the instance to be protected by const, and you are asking is it sufficient to write:

```<code>  const struct some *azaza = (struct some *)ptr;
</code>```

Rather than

```<code>const struct some *azaza = (const struct some *)ptr;
</code>```

I would say that it is, as the const attribute can be automatically applied by the compiler, but it can't be taken away. If this were C++ this would be the minimum sufficient code, but as others have mentioned, in C it is sufficient to write:

```<code>const struct some *azaza = ptr;
</code>```

As C allows a void pointer to be cast to any other pointer type, and then the constness can be inferred. However, I think the C++ mandate makes for clearer readable code.

Note that if you already have a const pointer, you can't assign it to a non-const pointer without "casting away" the const. To match the C++ spec I would tend to put in 2 casts, though C would accept either one on its own:

```<code>void foo (const void *ptr) {
  struct some *azaza = (struct some *)(void*)ptr;
  azaza->some_field = 123; // intentional overwrite!
  // ...
</code>```

Title: Necessity of const specifier in cast

Body:
Suppose I have some code like this:

void foo (void *ptr) {
    const struct some *azaza = (const struct some *)ptr;
    azaza->some_field = 123; // inadvertently assignment => error
    // ...

Is the const specifier really needed in cast?

EDIT: foo is callback function with a particular prototype that I can't change (it's not in my code).

Body:
If I understand your question, you want the instance to be protected by const, and you are asking is it sufficient to write:

  const struct some *azaza = (struct some *)ptr;

Rather than

const struct some *azaza = (const struct some *)ptr;

I would say that it is, as the const attribute can be automatically applied by the compiler, but it can't be taken away. If this were C++ this would be the minimum sufficient code, but as others have mentioned, in C it is sufficient to write:

const struct some *azaza = ptr;

As C allows a void pointer to be cast to any other pointer type, and then the constness can be inferred. However, I think the C++ mandate makes for clearer readable code.

Note that if you already have a const pointer, you can't assign it to a non-const pointer without "casting away" the const. To match the C++ spec I would tend to put in 2 casts, though C would accept either one on its own:

void foo (const void *ptr) {
  struct some *azaza = (struct some *)(void*)ptr;
  azaza->some_field = 123; // intentional overwrite!
  // ...


问:
Firebase: get pathname after redirect
I want to create a website which will work on any pathname, like domain.com/abc, domain.com/xyz and so on.

But I want to serve from home page only. The content will be generated dynamically.

I think it is possible using firebase.json file, but how do I do that?

I have tried redirect, but that didn't work as pathname wasn't preserved.

答:
This should be configured by default, but here you go:

```<code>"hosting": {
  // ...

  // Add the "rewrites" attribute within "hosting"
  "rewrites": [ {
    // Serves index.html for requests to files or directories that do not exist
    "source": "**",
    "destination": "/index.html"
  } ]
}
</code>```

The appropriate section in the documentation can be found here.

This (rewrites) will serve content from the specified destination but not redirect to another URL.

Title: Firebase: get pathname after redirect

Body:
This should be configured by default, but here you go:

"hosting": {
  // ...

  // Add the "rewrites" attribute within "hosting"
  "rewrites": [ {
    // Serves index.html for requests to files or directories that do not exist
    "source": "**",
    "destination": "/index.html"
  } ]
}

The appropriate section in the documentation can be found here.

This (rewrites) will serve content from the specified destination but not redirect to another URL.


问:
How do I select specific lines from a file based on line number?
I have a class which takes in the name of the module to be tested. Then the class scans though a master text file and finds the files that need to be compiled based on the module selected.

This is what I have so far:

class Module():

    def __init__ (self,name):
        self.name = name
        module_start_line = []

        with open('master_module_list.txt', 'r') as master_list:
            for start_no, master_lines in enumerate(master_list):
                if re.search('module ' + self.name, master_lines):
                    module_start_line.append(start_no)
                    print(module_start_line)

```

```module eeprom_top
../../../project_ip/eeprom_ip/src/eeprom_pkg.vhd
../../../project_ip/eeprom_ip/src/eeprom_top.vhd
module fan_ip
../../../project_ip/fan_ip/src/fan_pkg.vhd
../../../project_ip/fan_ip/src/fan_pkg.vhd
module backplane
../../../project_ip/backplane_ip/src/backplane.vhd

```

So if the user types in "fan_ip" then I want to copy the two lines after module fan_ip from the text file.

I am fairly new to python so feel free to correct me on my previous code.
I am using python 3.4.

答: You could use the readline method to read one line at a time, and keep a count of what you've read to determine the line number of each.

Body:
I have a class which takes in the name of the module to be tested. Then the class scans though a master text file and finds the files that need to be compiled based on the module selected.

This is what I have so far:

class Module():

    def __init__ (self,name):
        self.name = name
        module_start_line = []

        with open('master_module_list.txt', 'r') as master_list:
            for start_no, master_lines in enumerate(master_list):
                if re.search('module ' + self.name, master_lines):
                    module_start_line.append(start_no)
                    print(module_start_line)

module eeprom_top
../../../project_ip/eeprom_ip/src/eeprom_pkg.vhd
../../../project_ip/eeprom_ip/src/eeprom_top.vhd
module fan_ip
../../../project_ip/fan_ip/src/fan_pkg.vhd
../../../project_ip/fan_ip/src/fan_pkg.vhd
module backplane
../../../project_ip/backplane_ip/src/backplane.vhd

So if the user types in "fan_ip" then I want to copy the two lines after module fan_ip from the text file.

I am fairly new to python so feel free to correct me on my previous code.
I am using python 3.4.


问:
Maximum amount of objects in NSArray
What is the largest amount of objects I can put in my NSArray? </p>

答:
NSNotFound is defined as NSIntegerMax (this value changes if you are on a 32bit or 64bit system)

NSNotFound is also the result you get when you do a

[nsarray indexOfObject:obj]

and no object is found.

If you do not run out of space/memory I would say that this would be your limit.

http://developer.apple.com/library/mac/#documentation/cocoa/reference/foundation/Miscellaneous/Foundation_Constants/Reference/reference.html

ContentLicense: CC BY-SA 2.5

Title: Maximum amount of objects in NSArray

ContentLicense: CC BY-SA 3.0


问:
How to insert a random string into the sed 's//' replace string for each line actioned?
This:

echo "    " | tr ' ' '\n' | sed "s|.*|$RANDOM|"

Or this:

echo "    " | tr ' ' '\n' | sed "s|.*|$(echo $RANDOM)|"

Will print a list of 5 numbers (space is replaced by newline, sed replaces each line with $RANDOM), and those 5 numbers will all be the same:

```<code>$ echo "    " | tr ' ' '\n' | sed "s|.*|$(echo $RANDOM)|"
21590
21590
21590
21590
21590
</code>```

This is because the replace of $RANDOM to a random value happens only once.

What is the easiest and shortest way, preferably by only using sed, to actually print a different random number for each line. i.e. to provide some "secondary input stream" which differs for each line that sed handles?

I could do it with xargs, but I wonder if there is a way to do it with sed only.

答:
This might work for you (GNU sed and Bash):

```<code>seq 5 | sed 's/.*/echo $RANDOM/e'
</code>```

This replaces the numbers 1 to 5 by echo $RANDOM and evaluates each line.

N.B. GNU sed uses /bin/sh which may be directed via a symbolic link to /bin/dash in which case the environmental variable $RANDOM will not be found. There are various solutions to get around this but probably the easiest (though possibly dangerous) is:

```<code>sudo ln -sf /bin/bash /bin/sh
# run sed
sudo ln -sf /bin/dash /bin/sh
</code>```

Another alternaive:

```<code>shuf -i 1-100000 -n 5
</code>```

Body:
This:

echo "    " | tr ' ' '\n' | sed "s|.*|$RANDOM|"

Or this:

echo "    " | tr ' ' '\n' | sed "s|.*|$(echo $RANDOM)|"

Will print a list of 5 numbers (space is replaced by newline, sed replaces each line with $RANDOM), and those 5 numbers will all be the same:

$ echo "    " | tr ' ' '\n' | sed "s|.*|$(echo $RANDOM)|"
21590
21590
21590
21590
21590

This is because the replace of $RANDOM to a random value happens only once.

What is the easiest and shortest way, preferably by only using sed, to actually print a different random number for each line. i.e. to provide some "secondary input stream" which differs for each line that sed handles?

I could do it with xargs, but I wonder if there is a way to do it with sed only.

Body:
This might work for you (GNU sed and Bash):

seq 5 | sed 's/.*/echo $RANDOM/e'

This replaces the numbers 1 to 5 by echo $RANDOM and evaluates each line.

N.B. GNU sed uses /bin/sh which may be directed via a symbolic link to /bin/dash in which case the environmental variable $RANDOM will not be found. There are various solutions to get around this but probably the easiest (though possibly dangerous) is:

sudo ln -sf /bin/bash /bin/sh
# run sed
sudo ln -sf /bin/dash /bin/sh

Another alternaive:

shuf -i 1-100000 -n 5


问:
Get class name using jQuery
I want to get the class name using jQuery

And if it has an id

```<code><div class="myclass"></div>
</code>```

答:
use like this:-

```<code>$(".myclass").css("color","red");
</code>```

if you've used this class more than once then use each operator

```<code>$(".myclass").each(function (index, value) {
//do you code
}
</code>```

Title: Get class name using jQuery

Body:
use like this:-

$(".myclass").css("color","red");

if you've used this class more than once then use each operator

$(".myclass").each(function (index, value) {
//do you code
}


问:
Regex with multiple email address seperated by a semi colon
I am trying to build a regex what would allow multiple emails separated with a semicolon for only one domain.

This is what I have now:

@"^(?>\b[\w+-.%]+@gmail\.com(?:[,;]\s*)?)+\b$"

This allow 1@gmail.com%2@gmail.com or 1@gmail.com&&2@gmail.com. I just want to have it to be allowed with semicolmn seperator as this. 1@gmail.com;2@gmail.com.

答:
You are really close, just remove the word boundaries, escape the hyphen in the character class and change the last part:

```<code>^(?>[\w+\-.%]+@gmail\.com(?:;\s*|$))+$
</code>```

Demo

Body:
You are really close, just remove the word boundaries, escape the hyphen in the character class and change the last part:

^(?>[\w+\-.%]+@gmail\.com(?:;\s*|$))+$

Demo


问:
How can I split this string as a UDF
I have this column (from an export from BigCommerce Database) that holds custom fields in a single column. Here's one example of the data:

```<code>[{"Name":"Unit Number","Value":"3698"},{"Name":"Region","Value":"Eastern Great Lakes (WNY, W PA)"}]
</code>```

I need a way to figure out how to extract the Field/Value pairs from this. In this sample, I'd like to get, as output:

```<code>Unit Number:3698
Region:Eastern Great Lakes (WNY, W PA)
</code>```

I'm hoping to have as a result a UDF that I can run as a part of a select query that gives me just the field name and the value output as a string (as exampled above). Every column of data in the source table has this format. Typically, the column data has two field/value pairs, but sometimes none, sometimes two, sometimes three. In other words, the column holds any number of variable field/value pairs.

Does anyone have any suggestions on how to build a UDF to help get those data elements out of this string?

I was tinkering around with things, but I'm stuck. I started with trying to remove the extraneous characters [,] which mean nothing, and {,} which delineate the field and the value. I was tinkering with string-split functions, but instead of splitting on a single character, I can't figure out how to split based upon pairs of open or closing brackets {,} to narrow it down.

```<code>Unit Number:3698 | Region:Eastern Great Lakes (WNY, W PA)
</code>```

答:
```<code>DECLARE @json NVARCHAR(MAX)
SET @json =  N'[{"Name":"Unit Number","Value":"3698"},{"Name":"Region","Value":"Eastern Great Lakes (WNY, W PA)"}]'

--read from json
SELECT [Name], [Value]
FROM OPENJSON(@json)
  WITH ([Name] NVARCHAR(100) '$.Name',
        [Value] NVARCHAR(50) '$.Value')

--if it has only these two fixed cols like Unit Number, Region starts here
SELECT [Region],[Unit Number] from
             (
                SELECT [Name], [Value]
                    FROM OPENJSON(@json)
                      WITH ([Name] NVARCHAR(100) '$.Name',
                            [Value] NVARCHAR(50) '$.Value')
            ) x
            pivot
            (
                MAX([Value])
                for [Name] in ([Region],[Unit Number])
            ) p
--if it has only these two fixed cols like Unit Number, Region ends here

--********if it has dynamic columns starts here********
DECLARE @cols AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX)

select @cols = STUFF((SELECT distinct ',' + QUOTENAME([Name])
            FROM OPENJSON(@json)
              WITH ([Name] NVARCHAR(100) '$.Name',
                    [Value] NVARCHAR(50) '$.Value')

            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)')
        ,1,1,'')

SET @query = 'SELECT ' + @cols + ' from
             (
                SELECT [Name], [Value]
                    FROM OPENJSON(@json)
                      WITH ([Name] NVARCHAR(100) ''$.Name'',
                            [Value] NVARCHAR(50) ''$.Value'')
            ) x
            pivot
            (
                MAX([Value])
                for [Name] in (' + @cols + ')
            ) p '

print @query
EXEC sp_executesql @query, N'@json NVARCHAR(MAX)', @json
--********if it has dynamic columns ends here********
</code>```

Note: this will only work from MSSQL 2016/17 or above, used v17.1

Title: How can I split this string as a UDF

Body:
I have this column (from an export from BigCommerce Database) that holds custom fields in a single column. Here's one example of the data:

[{"Name":"Unit Number","Value":"3698"},{"Name":"Region","Value":"Eastern Great Lakes (WNY, W PA)"}]

I need a way to figure out how to extract the Field/Value pairs from this. In this sample, I'd like to get, as output:

Unit Number:3698
Region:Eastern Great Lakes (WNY, W PA)

I'm hoping to have as a result a UDF that I can run as a part of a select query that gives me just the field name and the value output as a string (as exampled above). Every column of data in the source table has this format. Typically, the column data has two field/value pairs, but sometimes none, sometimes two, sometimes three. In other words, the column holds any number of variable field/value pairs.

Does anyone have any suggestions on how to build a UDF to help get those data elements out of this string?

I was tinkering around with things, but I'm stuck. I started with trying to remove the extraneous characters [,] which mean nothing, and {,} which delineate the field and the value. I was tinkering with string-split functions, but instead of splitting on a single character, I can't figure out how to split based upon pairs of open or closing brackets {,} to narrow it down.

Unit Number:3698 | Region:Eastern Great Lakes (WNY, W PA)

Body:
DECLARE @json NVARCHAR(MAX)
SET @json =  N'[{"Name":"Unit Number","Value":"3698"},{"Name":"Region","Value":"Eastern Great Lakes (WNY, W PA)"}]'

--read from json
SELECT [Name], [Value]
FROM OPENJSON(@json)
  WITH ([Name] NVARCHAR(100) '$.Name',
        [Value] NVARCHAR(50) '$.Value')

--if it has only these two fixed cols like Unit Number, Region starts here
SELECT [Region],[Unit Number] from
             (
                SELECT [Name], [Value]
                    FROM OPENJSON(@json)
                      WITH ([Name] NVARCHAR(100) '$.Name',
                            [Value] NVARCHAR(50) '$.Value')
            ) x
            pivot
            (
                MAX([Value])
                for [Name] in ([Region],[Unit Number])
            ) p
--if it has only these two fixed cols like Unit Number, Region ends here

--********if it has dynamic columns starts here********
DECLARE @cols AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX)

select @cols = STUFF((SELECT distinct ',' + QUOTENAME([Name])
            FROM OPENJSON(@json)
              WITH ([Name] NVARCHAR(100) '$.Name',
                    [Value] NVARCHAR(50) '$.Value')

            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)')
        ,1,1,'')

SET @query = 'SELECT ' + @cols + ' from
             (
                SELECT [Name], [Value]
                    FROM OPENJSON(@json)
                      WITH ([Name] NVARCHAR(100) ''$.Name'',
                            [Value] NVARCHAR(50) ''$.Value'')
            ) x
            pivot
            (
                MAX([Value])
                for [Name] in (' + @cols + ')
            ) p '

print @query
EXEC sp_executesql @query, N'@json NVARCHAR(MAX)', @json
--********if it has dynamic columns ends here********

Note: this will only work from MSSQL 2016/17 or above, used v17.1


问:
How to avoid "InternalError: too much recursion" in Angular observable?
I've got a simple Angular observable that should run continuously, checking a time difference on each loop, and looping once a second. I'm getting "InternalError: too much recursion" when I run it. According to this: http://bonsaiden.github.io/JavaScript-Garden/#dealing-with-possible-blocking-code
I'm using the correct method. How to fix?

The Angular observable:

```<code>export class MyService {
  private lastHeartBeatTime = null; // Time of the last heartbeat
  private heartBeatTimeoutId = null;

  private secondsToHeartbeatAlert = 5; // Number of seconds of no heartbeat

  constructor() {
    this.lastHeartBeatTime = performance.now(); // Initialise local heartbeat variable with current time
  }

  subscribeToHeartbeat(callbackfn): any {
    // Post a value via the observable to cause an alert to be raised:
    if((performance.now() - this.lastHeartBeatTime) / 1000 >= this.secondsToHeartbeatAlert) return(true);
    // Create a new timeout to call this function again after the specified num of milliseconds (e.g. after 1 second):

    // **** PROBLEM HERE: ***
    else this.heartBeatTimeoutId = setTimeout(this.subscribeToHeartbeat(callbackfn), 1000);
  }
}
</code>```

Subscription within another component:

```<code>// Subscribe to heartbeat over websockets:
MyService.subscribeToHeartbeat(this.handleHeartbeatFailure);

// Handler:
  handleHeartbeatFailure:any = (message) => {
   alert('Websocket is down!")
  }
</code>```

答:
You are calling the function and not assigning it in your timeout

```<code>setTimeout(this.subscribeToHeartbeat(callbackfn), 1000);
</code>```

needs to be

```<code>setTimeout(() => this.subscribeToHeartbeat(callbackfn), 1000);
</code>```

or you can use bind

```<code>setTimeout(this.subscribeToHeartbeat.bind(this, callbackfn), 1000);
</code>```

Body:
I've got a simple Angular observable that should run continuously, checking a time difference on each loop, and looping once a second. I'm getting "InternalError: too much recursion" when I run it. According to this: http://bonsaiden.github.io/JavaScript-Garden/#dealing-with-possible-blocking-code
I'm using the correct method. How to fix?

The Angular observable:

export class MyService {
  private lastHeartBeatTime = null; // Time of the last heartbeat
  private heartBeatTimeoutId = null;

  private secondsToHeartbeatAlert = 5; // Number of seconds of no heartbeat

  constructor() {
    this.lastHeartBeatTime = performance.now(); // Initialise local heartbeat variable with current time
  }

  subscribeToHeartbeat(callbackfn): any {
    // Post a value via the observable to cause an alert to be raised:
    if((performance.now() - this.lastHeartBeatTime) / 1000 >= this.secondsToHeartbeatAlert) return(true);
    // Create a new timeout to call this function again after the specified num of milliseconds (e.g. after 1 second):

    // **** PROBLEM HERE: ***
    else this.heartBeatTimeoutId = setTimeout(this.subscribeToHeartbeat(callbackfn), 1000);
  }
}

Subscription within another component:

// Subscribe to heartbeat over websockets:
MyService.subscribeToHeartbeat(this.handleHeartbeatFailure);

// Handler:
  handleHeartbeatFailure:any = (message) => {
   alert('Websocket is down!")
  }

Body:
You are calling the function and not assigning it in your timeout

setTimeout(this.subscribeToHeartbeat(callbackfn), 1000);

needs to be

setTimeout(() => this.subscribeToHeartbeat(callbackfn), 1000);

or you can use bind

setTimeout(this.subscribeToHeartbeat.bind(this, callbackfn), 1000);


问:
PayPal recurring payments
I am explaining by example:

A customer goes to the website and buys a service and opt for recurring payment. To complete the transaction, customer is redirected to the PayPal site. Customer does not have PayPal account and opt to pay via credit card. In such scenario is it possible for a customer to complete the transaction as a recurring transaction. If not then it is OK, but if it is so then later ON how customer can cancels this subscription as he has no account to log on to PayPal.

答:
PayPal now has an add-on for Website Payments Standard called "Enhanced Recurring Payments" that makes it possible now to have recurring payments without making your customers signup for PayPal. It costs $19.95/month extra to use this. The add-on also adds a few other features, like Installment payments, and Automatic Billing.

Here's a link to their overview page.

Title: PayPal recurring payments


问:
How to only get items that have not sold in the past 30 days?
I need to find items that have not sold in the past 30 days.

I can get items that have sold, but I don't know where to start when finding items that have not sold.

```<code>SELECT
    ITEMNMBR
FROM
    SOP10100

WHERE
    ORDRDATE>= DATEADD(DAY, -30, GETDATE())
</code>```

答:
You can use aggregation:</p>

```<code>SELECT ITEMNMBR
FROM SOP10100
GROUP BY ITEMNMBR
WHERE MAX(ORDRDATE) < DATEADD(DAY, -30, GETDATE())
</code>```

Body:
I need to find items that have not sold in the past 30 days.

I can get items that have sold, but I don't know where to start when finding items that have not sold.

SELECT
    ITEMNMBR
FROM
    SOP10100

WHERE
    ORDRDATE>= DATEADD(DAY, -30, GETDATE())

Body:
You can use aggregation:

SELECT ITEMNMBR
FROM SOP10100
GROUP BY ITEMNMBR
WHERE MAX(ORDRDATE) < DATEADD(DAY, -30, GETDATE())


问:
Is there any way to send an arraylist of int elements from javascritp to spring contoller without using Json?
I have a list  of int elements inside a javaScript code, so I want to send this list to a spring controller

答:
The API will generally simply return raw data back to the client – XML and JSON representations usually – and so the DispatcherServlet bypasses the view resolvers and returns the data right in the HTTP response body.

https://www.baeldung.com/spring-controllers

Basically, what this is saying is you can use XML (which is somewhat common), but I believe other datatypes are possible, as long as you account for them on both sides.

Just use:

```<code>myMethod(@RequestParam("value1") List<Integer> valueOne)
</code>```

in your Java and send it however you want in your JavaScript (as long is it's documented in Spring)

And you can cast that into whatever. But as far as I know you it's advised to pass it as either XML or JSON.

Body:
The API will generally simply return raw data back to the client – XML and JSON representations usually – and so the DispatcherServlet bypasses the view resolvers and returns the data right in the HTTP response body.

https://www.baeldung.com/spring-controllers

Basically, what this is saying is you can use XML (which is somewhat common), but I believe other datatypes are possible, as long as you account for them on both sides.

Just use:

myMethod(@RequestParam("value1") List<Integer> valueOne)

in your Java and send it however you want in your JavaScript (as long is it's documented in Spring)

And you can cast that into whatever. But as far as I know you it's advised to pass it as either XML or JSON.


问:
How can I extract a subtree from my SVN repository into a new one?
We have a Subversion repository with one directory that is:

Not really in need of revision control beyond the capabilities of RCS

Not versioned in conjunction with anything else in the repository

Modified about six times as often as the rest of the repository

Although I know that high revision numbers aren't a problem, nonetheless I'd like to pull this one single directory out of my main repository and into a second, ideally new one.

What is the best process for that? If it makes a difference, the SVN repository is hosted on a (... checks... ) FreeBSD machine.

It's worth noting that while I need to retain the version history in the new repository, there's no need to obliterate the content in the old; it can just sit there, for all I care.

答:
I would export (not checkout) the directory, import it into the new repository, then delete it from the original (with a log message indicating where it went, of course ;-).

That may or may not be the "best" way to do it...

OwnerDisplayName: Chris R

LastEditorDisplayName: Chris R

OwnerDisplayName: David


问:
why does tinyMce escape my PHP code that i want to display on my blog?
I'm trying to display PHP code in my blog, and I'm inserting it into tinymce textrea, but it escapes the php code? I tried doing it without tinymce and it worked, but with tinymce it doesn't? :)) thanks</p>

答: while inserting php code either insert it in designer mode or try encoding the code with htmlentities</p>


问:
How receive data with HAL_UART?
I'm learning about the STM32. I'm want receive data by UART byte-to-byte with interruption.

```<code>HAL_UART_Receive_IT(&huart1, buffer, length)
</code>```

Where &huart1 is my uart gate, buffer is the input storage and length is the amount of input bytes. I use the following function to read data

```<code>static requestRead(void *buffer, uint16_t length)
{
    uint8_t teste;
    while (HAL_UART_Receive_IT(&huart1, buffer, length) != HAL_OK) osDelay(1);
    //HAL_UART_RxCpltCallback
}
</code>```

I store my data in:

```<code>void StartDefaultTask(void const *argument)
{
    char sender[] = "Alaska Sending\n";
    uint8_t receive[10];
    uint8_t data[30];

    for (;;)
    {
        uint8_t i = 0;
        memset(data, 0, 30);

        requestRead(&receive, 1);
        data[i++] = receive;

        while (data != '\r')
        {
            requestRead(&receive, 1);
            data[i++] = receive;
        }

        //HAL_UART_Transmit(&huart1, data, i, HAL_MAX_DELAY);

    }
    /* USER CODE END StartDefaultTask */
}
</code>```

My problem is the value receive and store. When I send by serial a string of character as Welcome to Alaska\n, only W is read and stored, then I need send again the buffer and again just store only W. How solve this?

答:
Well, there are a few issues here.

Arrays and their contents

```<code>data[i++] = receive;
</code>```

stores the address of the receive buffer, a memory pointer value, into the data array. That's certainly not what you want. As this is a very basic C programming paradigm, I'd recommend reviewing the chapter on arrays and pointers in a good C textbook.

What you send and what you expect

```<code>while (data != '\r')
</code>```

Even if you'd get the array address and its value right (see above), you are sending a string terminated with '\n', and check for a '\r' character, so change one or the other to get a match.

Missing volatile

```<code>uint8_t receive[10];
</code>```

The receive buffer should be declared volatile, as it would be accessed by an interrupt handler. Otherwise the main program would miss writes to the buffer even if it had checked whether the receiving is complete (see below).

Working with hardware in realtime

```<code>while (HAL_UART_Receive_IT(&huart1, buffer, length) != HAL_OK) osDelay(1);
</code>```

This would enable the UART receive (and error handling) interrupt to receive one byte. That's fine so far, but the function returns before receiving the byte, and as it's called again immediately, it would return HAL_BUSY the second time, and wait a millisecond before attempting it again. In that millisecond, it would miss most of the rest of the transmission, as bytes are arriving faster than that, and your program does nothing about it.

Moreover, the main program does not check when the receive is complete, possibly accessing the buffer before the interrupt handler places a value in it.

If you receive data using interrupts, you'd have to do something about that data in the interrupt handler. (If you don't use interrupts, but polling for data, then be sure that you'd meet the deadline imposed by the speed of the interface).

HAL is not suited for this kind of tasks

HAL has no interface for receiving an unknown length of data terminated by a specific value. Of course the main program can poll the receiver one byte at a time, but then it must ensure that the polling occurs faster than the data comes in. In other words, the program can do very little else while expecting a transmission.

There are some workarounds, but I won't even hint at them now, because they would lead to deadlocks in an RTOS environment which tend to occur at the most inconvenient times, and are quite hard to investigate and to properly avoid.

Write your interrupt handler instead

(all of this is detailed in the Reference Manual for your controller)

set the UART interrupt priority NVIC_SetPriority()

enable the interrupt with NVIC_EnableIRQ()

set the USART_CR1_RXNEIE bit to 1

in the interrupt handler,

read the SR register

if the RXNE bit is set,

read the data from the data register

store it in the buffer

set a global flag if it matches the terminating character

switch to another buffer if more data is expected while the program processes the first line.

Don't forget declaring declaring all variables touched by the interrupt handler as volatile.

Title: How receive data with HAL_UART?

Body:
I'm learning about the STM32. I'm want receive data by UART byte-to-byte with interruption.

HAL_UART_Receive_IT(&huart1, buffer, length)

Where &huart1 is my uart gate, buffer is the input storage and length is the amount of input bytes. I use the following function to read data

static requestRead(void *buffer, uint16_t length)
{
    uint8_t teste;
    while (HAL_UART_Receive_IT(&huart1, buffer, length) != HAL_OK) osDelay(1);
    //HAL_UART_RxCpltCallback
}

I store my data in:

void StartDefaultTask(void const *argument)
{
    char sender[] = "Alaska Sending\n";
    uint8_t receive[10];
    uint8_t data[30];

    for (;;)
    {
        uint8_t i = 0;
        memset(data, 0, 30);

        requestRead(&receive, 1);
        data[i++] = receive;

        while (data != '\r')
        {
            requestRead(&receive, 1);
            data[i++] = receive;
        }

        //HAL_UART_Transmit(&huart1, data, i, HAL_MAX_DELAY);

    }
    /* USER CODE END StartDefaultTask */
}

My problem is the value receive and store. When I send by serial a string of character as Welcome to Alaska\n, only W is read and stored, then I need send again the buffer and again just store only W. How solve this?

Body:
Well, there are a few issues here.

Arrays and their contents

data[i++] = receive;

stores the address of the receive buffer, a memory pointer value, into the data array. That's certainly not what you want. As this is a very basic C programming paradigm, I'd recommend reviewing the chapter on arrays and pointers in a good C textbook.

What you send and what you expect

while (data != '\r')

Even if you'd get the array address and its value right (see above), you are sending a string terminated with '\n', and check for a '\r' character, so change one or the other to get a match.

Missing volatile

uint8_t receive[10];

The receive buffer should be declared volatile, as it would be accessed by an interrupt handler. Otherwise the main program would miss writes to the buffer even if it had checked whether the receiving is complete (see below).

Working with hardware in realtime

while (HAL_UART_Receive_IT(&huart1, buffer, length) != HAL_OK) osDelay(1);

This would enable the UART receive (and error handling) interrupt to receive one byte. That's fine so far, but the function returns before receiving the byte, and as it's called again immediately, it would return HAL_BUSY the second time, and wait a millisecond before attempting it again. In that millisecond, it would miss most of the rest of the transmission, as bytes are arriving faster than that, and your program does nothing about it.

Moreover, the main program does not check when the receive is complete, possibly accessing the buffer before the interrupt handler places a value in it.

If you receive data using interrupts, you'd have to do something about that data in the interrupt handler. (If you don't use interrupts, but polling for data, then be sure that you'd meet the deadline imposed by the speed of the interface).

HAL is not suited for this kind of tasks

HAL has no interface for receiving an unknown length of data terminated by a specific value. Of course the main program can poll the receiver one byte at a time, but then it must ensure that the polling occurs faster than the data comes in. In other words, the program can do very little else while expecting a transmission.

There are some workarounds, but I won't even hint at them now, because they would lead to deadlocks in an RTOS environment which tend to occur at the most inconvenient times, and are quite hard to investigate and to properly avoid.

Write your interrupt handler instead

(all of this is detailed in the Reference Manual for your controller)

set the UART interrupt priority NVIC_SetPriority()

enable the interrupt with NVIC_EnableIRQ()

set the USART_CR1_RXNEIE bit to 1

in the interrupt handler,

read the SR register

if the RXNE bit is set,

read the data from the data register

store it in the buffer

set a global flag if it matches the terminating character

switch to another buffer if more data is expected while the program processes the first line.

Don't forget declaring declaring all variables touched by the interrupt handler as volatile.


问:
StringLength Attribute Not validating why my implementation
I have used This to do my own implementation of data validation using attributes. However, when I run the unit test it fails

Unit test:

```<code>      [TestMethod]
      public void CheckAttributes_StringLengthAttribute_ShouldAddErrorIfToManyCharacters()
      {
           //Arrange
           _model.FirstName = "asdf";
           _model.LastName = "abcdefghijklmnopqrstuvwxyz";

           //Act
           _abstractModelValidation.CheckMyAttributes(_model);

           //Assert
           Assert.IsFalse(_abstractModelValidation.IsValid);
      }
</code>```

just FYI _abstractModelValidation.IsValid =  Errors.Any();

My implementation of the above link:

```<code>      protected void CheckAttributes(T model)
      {
           var context = new ValidationContext(model, null, null);
           var results = new List<ValidationResult>();

           var isValid = Validator.TryValidateObject(model, context, results);
           if (!isValid)
           {
                foreach (var validationResult in results)
                {
                     foreach (var memberName in validationResult.MemberNames)
                     {
                          AddError(memberName, validationResult.ErrorMessage);
                     }
                }
           }
      }
</code>```

The model class:

```<code> public class ValidatorModel
 {
      public int Id { get; set; }

      [StringLength(25), Required]
      public string FirstName { get; set; }

      [StringLength(9, MinimumLength = 9)]
      public string LastName { get; set; }

 }
</code>```

Just FYI the [Required] does add the error

Can someone please tell me what I and doing wrong?

Thanks!

答:
I have figured out my issue; I hope this helps someone else!

The issue is that there was another overload that is a boolean property validateAllProperties. Changing that to true, did it!

```<code>      protected void CheckAttributes(T model)
      {
           var context = new ValidationContext(model, null, null);
           var results = new List<ValidationResult>();

           var isValid = Validator.TryValidateObject(model, context, results, true);
           if (!isValid)
           {
                foreach (var validationResult in results)
                {
                     foreach (var memberName in validationResult.MemberNames)
                     {
                          AddError(memberName, validationResult.ErrorMessage);
                     }
                }
           }
      }
</code>```

Body:
I have used This to do my own implementation of data validation using attributes. However, when I run the unit test it fails

Unit test:

      [TestMethod]
      public void CheckAttributes_StringLengthAttribute_ShouldAddErrorIfToManyCharacters()
      {
           //Arrange
           _model.FirstName = "asdf";
           _model.LastName = "abcdefghijklmnopqrstuvwxyz";

           //Act
           _abstractModelValidation.CheckMyAttributes(_model);

           //Assert
           Assert.IsFalse(_abstractModelValidation.IsValid);
      }

just FYI _abstractModelValidation.IsValid =  Errors.Any();

My implementation of the above link:

      protected void CheckAttributes(T model)
      {
           var context = new ValidationContext(model, null, null);
           var results = new List<ValidationResult>();

           var isValid = Validator.TryValidateObject(model, context, results);
           if (!isValid)
           {
                foreach (var validationResult in results)
                {
                     foreach (var memberName in validationResult.MemberNames)
                     {
                          AddError(memberName, validationResult.ErrorMessage);
                     }
                }
           }
      }

The model class:

 public class ValidatorModel
 {
      public int Id { get; set; }

      [StringLength(25), Required]
      public string FirstName { get; set; }

      [StringLength(9, MinimumLength = 9)]
      public string LastName { get; set; }

 }

Just FYI the [Required] does add the error

Can someone please tell me what I and doing wrong?

Thanks!

Body:
I have figured out my issue; I hope this helps someone else!

The issue is that there was another overload that is a boolean property validateAllProperties. Changing that to true, did it!

      protected void CheckAttributes(T model)
      {
           var context = new ValidationContext(model, null, null);
           var results = new List<ValidationResult>();

           var isValid = Validator.TryValidateObject(model, context, results, true);
           if (!isValid)
           {
                foreach (var validationResult in results)
                {
                     foreach (var memberName in validationResult.MemberNames)
                     {
                          AddError(memberName, validationResult.ErrorMessage);
                     }
                }
           }
      }


问:
Array of tuples to JSON (TypeScript) not recognized by API entry point
I have an angular application that call my back-end written in Asp.net c#. The back-end works correctly (already used by a mobile application) but one entry point does not behave correctly while being hit by the angular Application.

I Serialize a tupple array of  and send it to the API, but when API entry point gets hit, it seems like the data of the tuple array is not being received.

I've already looked to my tuple array, the data is correctly serialized to json client-side but not received server-side.

Here is the entry point definition in my c# API :

```<code> public HttpResponseMessage Xamarin_UpdateStatut([FromRoute] int idEvent,          [System.Web.Http.FromBody] List<Tuple<int, bool>> listUsersStatut)
    {
    }
</code>```

And here is the tuple sended client-side (get via chrome console) :
       "[[2102,false],[1096,false],[73,false]]"

Here is the code used to serialized the tuple array to Json (client-side) :

```<code> var listUpdate = new Array<[number, boolean]>();
arr.forEach(re => {
  let el: [number, boolean] = [re.userId, re.wasThere];
  listUpdate.push(el);
});
let body = JSON.stringify(listUpdate);
</code>```

I debugged a few times server side, the list length is 0. I tried to change the type received from List to Tuple array (server side, in the method definition) but it didn't change anything.

It seems to me like the json output is correct so I don't understand why it does not work.

A little help would be very much appreciated :)

Have a nice day and thanks in advance,

Lio

答:
Binding happens by name. From Model Binding:
"MVC will try to bind request data to the action parameters by name. MVC will look for values for each parameter using the parameter name and the names of its public settable properties."

In order for binding to be successful, the names in your JSON must match the names of the C# parameters, including the names of the properties of each parameter.

Body:
I have an angular application that call my back-end written in Asp.net c#. The back-end works correctly (already used by a mobile application) but one entry point does not behave correctly while being hit by the angular Application.

I Serialize a tupple array of  and send it to the API, but when API entry point gets hit, it seems like the data of the tuple array is not being received.

I've already looked to my tuple array, the data is correctly serialized to json client-side but not received server-side.

Here is the entry point definition in my c# API :

 public HttpResponseMessage Xamarin_UpdateStatut([FromRoute] int idEvent,          [System.Web.Http.FromBody] List<Tuple<int, bool>> listUsersStatut)
    {
    }

And here is the tuple sended client-side (get via chrome console) :
       "[[2102,false],[1096,false],[73,false]]"

Here is the code used to serialized the tuple array to Json (client-side) :

 var listUpdate = new Array<[number, boolean]>();
arr.forEach(re => {
  let el: [number, boolean] = [re.userId, re.wasThere];
  listUpdate.push(el);
});
let body = JSON.stringify(listUpdate);

I debugged a few times server side, the list length is 0. I tried to change the type received from List to Tuple array (server side, in the method definition) but it didn't change anything.

It seems to me like the json output is correct so I don't understand why it does not work.

A little help would be very much appreciated :)

Have a nice day and thanks in advance,

Lio


问:
SignInManager.SignInAsync doesn't sign me in (Vue.js SPA)
I'm having some odd problems with authentication on an app which consists of a dotnet core 2.1 API back end and a Vue.js SPA front end.

I've got all of the key elements and layers in place for logging in and logging out on the back end using an Auth API controller and I've got a basic login page on the Vue app with which I can log in.

The front end app consists of 3 key pages at the moment 'Landing' (with a click here to log in line on it), 'Home' for logged in users and the Log In page itself.

If I log in then the log in API call returns my basic user data and roles, so I store that in Vuex state and use it to load the home page. However, if I try to go back to the landing page by refreshing the page back to the root URL then the Vue app should trigger a routine that will assess the user status and adapt accordingly (It does this first by checking Vuex state and, if empty, it then calls the auth controller to get the User and role data and repopulate itself) so, as I've logged in, I should be redirected back to the logged in 'Home' page. This doesn't happen - Instead, the 'Landing' (Not logged in) page is shown.

I've got some general logging that trickles through and I've added some more as I've gone and it's clear that when I make the second call I am, for some reason, no longer authorised although I cannot for the life of me figure out why.

I've used this set up before very successfully - the only difference is that the dev API backend is ASP.Net Core and not .net Framework.

I'm open to any ideas of where to start looking at this?

Here's my Startup config...

```<code>       public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory,
        ApplicationDbContext context, RoleManager<IdentityRole> roleManager, UserManager<ApplicationUser> userManager)
    {
        if (env.IsDevelopment())
        {
            app
                .UseDeveloperExceptionPage()
                .UseDatabaseErrorPage();
        }
        else
        {
            app
                .UseExceptionHandler("/Home/Error")
                .UseHsts();
        }

        app
            .UseAuthentication()
            .UseHttpsRedirection()
            .UseStaticFiles()
            .UseSpaStaticFiles();

        app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });

        app.UseSpa(spa =>
        {
            spa.Options.SourcePath = "VueApp";

            if (env.IsDevelopment())
            {
                spa.UseVueCliServer("serve");
            }
        });

        DbInitializer.Initialize(context, roleManager, userManager, env, loggerFactory);
    }
</code>```

and the services...

```<code>public void ConfigureServices(IServiceCollection services)
    {
        services
            .AddLogging(builder => builder
                .AddConsole()
                .AddDebug());

        services
            .AddMvc()
                .SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
                .AddJsonOptions(options => options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver());

        // In production, the Vue files will be served from this directory
        services
            .AddSpaStaticFiles(configuration =>
            {
                configuration.RootPath = "wwwroot";
            });

        services
            .AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("MyConnection")))
            .AddIdentity<ApplicationUser, IdentityRole>(options =>
                {
                    // Password settings
                    options.Password.RequireDigit = true;
                    options.Password.RequiredLength = 8;
                    options.Password.RequireNonAlphanumeric = true;

                    // Lockout settings
                    options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(30);
                    options.Lockout.MaxFailedAccessAttempts = 10;

                    // User settings
                    options.User.RequireUniqueEmail = true;
                })
            .AddRoleManager<RoleManager<IdentityRole>>()
            .AddSignInManager<SignInManager<ApplicationUser>>() // Not sure I need this - added to see if it made things better but it didn't
            .AddEntityFrameworkStores<ApplicationDbContext>()
            .AddDefaultTokenProviders();

        services
            .ConfigureEntityServices()
            .ConfigureIdentityDependencies()
            .ConfigureDomainServices();

        services.AddAuthentication(options =>
        {
            options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
        }).AddCookie(options =>
        {
            options.SlidingExpiration = true;
            options.Events.OnRedirectToLogin = cxt =>
            {
                cxt.Response.StatusCode = 401;
                return Task.CompletedTask;
            };
            options.Events.OnRedirectToAccessDenied = cxt =>
            {
                cxt.Response.StatusCode = 403;
                return Task.CompletedTask;
            };
            options.Events.OnRedirectToLogout = cxt => Task.CompletedTask;
        });
    }
</code>```

I've also tried adding a Development only CORS policy to the Startup to allow anything in development mode to rule that out - It made no difference.

My log in method looks like this...

```<code>        public async Task<ActionResult<CurrentUserJsonModel>> LogIn(LoginJsonModel model)
    {
        if (model == null) return BadRequest();
        if (!ModelState.IsValid) return BadRequest(ModelState);

        var result = await authService.LogInAsync(model.UserName, model.Password);

        if (!result.Succeeded)
            return BadRequest(result.Errors.Select(e => new ErrorJsonModel(e)).ToArray());

        var principal = User;

        return new CurrentUserJsonModel
        {
            UserName = result.UserName,
            Roles = await authService.GetRolesAsync(model.UserName, model.Password)
        };
    }
</code>```

TANGENT: (The var principal line was to test the current state while stepping through - While not null, User has not UserName or Claims in the Identity object when I step through after LogInAsync has been called (which I would think it should do at that point...).

Which calls an authService.LogInAsync method that looks like this...

```<code>        public async Task<AuthResult> LogInAsync(ApplicationUser user)
    {
        if (user != null)
        {
            await identityService.SignOutAsync();
            await identityService.SignInAsync(user);
        }

        return user != null
            ? new AuthResult(user)
            : new AuthResult("Password or Email address incorrect.");
    }
</code>```

which uses identityService to wrap access to UserManager, SignInManager and RoleManager functions...

```<code>        public async Task SignInAsync(ApplicationUser user, bool isPersistent = true, string authenticationMethod = null)
        => await signInManager.SignInAsync(user, isPersistent, authenticationMethod);
</code>```

When I load the app after having logged into the back end but having cleared the Vuex state (by refreshing the page) the app tries to call this method...

```<code>    [Authorize]
    [HttpGet]
    [ProducesResponseType(StatusCodes.Status401Unauthorized)]
    [ProducesResponseType(StatusCodes.Status403Forbidden)]
    public async Task<ActionResult<CurrentUserJsonModel>> Get()
    {
        if (HttpContextAccessor.HttpContext.User != null)
        {
            if (HttpContextAccessor.HttpContext.User.Identity.IsAuthenticated)
                return new CurrentUserJsonModel
                {
                    UserName = HttpContextAccessor.HttpContext.User.Identity.Name,
                    Roles = await authService.GetRolesAsync(HttpContextAccessor.HttpContext.User)
                };

            return Forbid();
        }

        return Unauthorized();
    }
</code>```

When debugging the method isn't even stepped into - I'm getting a 401 thrown back at me on my browser console (which would make sense if Authorize was failing).

And for completeness, here's my vue.config.js

```<code>const baseUrl = ''

module.exports = {
    publicPath: baseUrl + '/',

    // place our built files into the parent project where they will be copied
    // into the distribution for deployment
    outputDir: '../wwwroot',

    filenameHashing: true, //process.env.NODE_ENV === 'production',
    lintOnSave: 'error',

    css: {
        modules: false,
        sourceMap: process.env.NODE_ENV !== 'production',
        loaderOptions: {
            sass: {
                data: `
                    $fa-font-path: ${process.env.NODE_ENV !== 'production' ? '"~/fonts"' : '"' + baseUrl + '/fonts"'};
                    @import "@/scss/base/index.scss";
                    @import "@/scss/helpers/index.scss";
                `
            }
        }
    },

    devServer: {
        host: 'localhost',
        port: 8080,
        hot: true,
        open: true,
        openPage: '',
        overlay: true,
        disableHostCheck: true,
        proxy: {
            // Proxy services to a backend API
            '/api': {
                target: process.env.PROXY || 'https://localhost:44368',
                secure: false,
                changeOrigin: true
            }
        }
    },

    // these node_modules use es6 so need transpiling for IE
    transpileDependencies: [
    ]
}
</code>```

My console output in Visual Studio looks like this...

```<code>Microsoft.AspNetCore.Hosting.Internal.WebHost:Information: Request starting HTTP/1.1 GET http://localhost:44368/api/auth
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker:Information: Route matched with {action = "Get", controller = "Auth"}. Executing action Ddm.Lcp.Iptn.Dashboard.Web.Api.AuthController.Get (Ddm.Lcp.Iptn.Dashboard.Web)
Microsoft.AspNetCore.Authorization.DefaultAuthorizationService:Information: Authorization failed.
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker:Information: Authorization failed for the request at filter 'Microsoft.AspNetCore.Mvc.Authorization.AuthorizeFilter'.
Microsoft.AspNetCore.Mvc.ChallengeResult:Information: Executing ChallengeResult with authentication schemes ().
Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationHandler:Information: AuthenticationScheme: Cookies was challenged.
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker:Information: Executed action Ddm.Lcp.Iptn.Dashboard.Web.Api.AuthController.Get (Ddm.Lcp.Iptn.Dashboard.Web) in 10.8469ms
Microsoft.AspNetCore.Hosting.Internal.WebHost:Information: Request finished in 18.1495ms 401
</code>```

This suggests that cookies are being challenged, as they should be given my set up - It does feel as if the actual sign in creation is not actually working.

The question is ... why is it failing?

UPDATE: According to @Kirk it may be related to a scheme mismatch between Cookies and Identity.Application. I have tested by commenting out the cookie elements in Startup and in this case I find myself in a recursive loop - I added the cookie elements to Startup.cs to enable me to get sensible responses from Authorization results.

I need to be able to do this but not get redirected to login pages which (In my app) do not exist and won't exist because it's an SPA.

答:
signInManager.SignInAsync(...) uses the Identity.Application scheme, rather than the Cookies scheme that you've both registered and configured as the default. To use Identity and customise the cookie that it uses, use ConfigureApplicationCookie.

Replace the following:

```<code>services.AddAuthentication(options =>
{
    options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
}).AddCookie(options =>
{
    options.SlidingExpiration = true;
    options.Events.OnRedirectToLogin = cxt =>
    {
        cxt.Response.StatusCode = 401;
        return Task.CompletedTask;
    };
    options.Events.OnRedirectToAccessDenied = cxt =>
    {
        cxt.Response.StatusCode = 403;
        return Task.CompletedTask;
    };
    options.Events.OnRedirectToLogout = cxt => Task.CompletedTask;
});
</code>```

-with-:

```<code>services.ConfigureApplicationCookie(options =>
{
    options.SlidingExpiration = true;
    options.Events.OnRedirectToLogin = cxt =>
    {
        cxt.Response.StatusCode = 401;
        return Task.CompletedTask;
    };
    options.Events.OnRedirectToAccessDenied = cxt =>
    {
        cxt.Response.StatusCode = 403;
        return Task.CompletedTask;
    };
    options.Events.OnRedirectToLogout = cxt => Task.CompletedTask;
});
</code>```

Body:
I'm having some odd problems with authentication on an app which consists of a dotnet core 2.1 API back end and a Vue.js SPA front end.

I've got all of the key elements and layers in place for logging in and logging out on the back end using an Auth API controller and I've got a basic login page on the Vue app with which I can log in.

The front end app consists of 3 key pages at the moment 'Landing' (with a click here to log in line on it), 'Home' for logged in users and the Log In page itself.

If I log in then the log in API call returns my basic user data and roles, so I store that in Vuex state and use it to load the home page. However, if I try to go back to the landing page by refreshing the page back to the root URL then the Vue app should trigger a routine that will assess the user status and adapt accordingly (It does this first by checking Vuex state and, if empty, it then calls the auth controller to get the User and role data and repopulate itself) so, as I've logged in, I should be redirected back to the logged in 'Home' page. This doesn't happen - Instead, the 'Landing' (Not logged in) page is shown.

I've got some general logging that trickles through and I've added some more as I've gone and it's clear that when I make the second call I am, for some reason, no longer authorised although I cannot for the life of me figure out why.

I've used this set up before very successfully - the only difference is that the dev API backend is ASP.Net Core and not .net Framework.

I'm open to any ideas of where to start looking at this?

Here's my Startup config...

       public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory,
        ApplicationDbContext context, RoleManager<IdentityRole> roleManager, UserManager<ApplicationUser> userManager)
    {
        if (env.IsDevelopment())
        {
            app
                .UseDeveloperExceptionPage()
                .UseDatabaseErrorPage();
        }
        else
        {
            app
                .UseExceptionHandler("/Home/Error")
                .UseHsts();
        }

        app
            .UseAuthentication()
            .UseHttpsRedirection()
            .UseStaticFiles()
            .UseSpaStaticFiles();

        app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });

        app.UseSpa(spa =>
        {
            spa.Options.SourcePath = "VueApp";

            if (env.IsDevelopment())
            {
                spa.UseVueCliServer("serve");
            }
        });

        DbInitializer.Initialize(context, roleManager, userManager, env, loggerFactory);
    }

and the services...

public void ConfigureServices(IServiceCollection services)
    {
        services
            .AddLogging(builder => builder
                .AddConsole()
                .AddDebug());

        services
            .AddMvc()
                .SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
                .AddJsonOptions(options => options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver());

        // In production, the Vue files will be served from this directory
        services
            .AddSpaStaticFiles(configuration =>
            {
                configuration.RootPath = "wwwroot";
            });

        services
            .AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("MyConnection")))
            .AddIdentity<ApplicationUser, IdentityRole>(options =>
                {
                    // Password settings
                    options.Password.RequireDigit = true;
                    options.Password.RequiredLength = 8;
                    options.Password.RequireNonAlphanumeric = true;

                    // Lockout settings
                    options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(30);
                    options.Lockout.MaxFailedAccessAttempts = 10;

                    // User settings
                    options.User.RequireUniqueEmail = true;
                })
            .AddRoleManager<RoleManager<IdentityRole>>()
            .AddSignInManager<SignInManager<ApplicationUser>>() // Not sure I need this - added to see if it made things better but it didn't
            .AddEntityFrameworkStores<ApplicationDbContext>()
            .AddDefaultTokenProviders();

        services
            .ConfigureEntityServices()
            .ConfigureIdentityDependencies()
            .ConfigureDomainServices();

        services.AddAuthentication(options =>
        {
            options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
        }).AddCookie(options =>
        {
            options.SlidingExpiration = true;
            options.Events.OnRedirectToLogin = cxt =>
            {
                cxt.Response.StatusCode = 401;
                return Task.CompletedTask;
            };
            options.Events.OnRedirectToAccessDenied = cxt =>
            {
                cxt.Response.StatusCode = 403;
                return Task.CompletedTask;
            };
            options.Events.OnRedirectToLogout = cxt => Task.CompletedTask;
        });
    }

I've also tried adding a Development only CORS policy to the Startup to allow anything in development mode to rule that out - It made no difference.

My log in method looks like this...

        public async Task<ActionResult<CurrentUserJsonModel>> LogIn(LoginJsonModel model)
    {
        if (model == null) return BadRequest();
        if (!ModelState.IsValid) return BadRequest(ModelState);

        var result = await authService.LogInAsync(model.UserName, model.Password);

        if (!result.Succeeded)
            return BadRequest(result.Errors.Select(e => new ErrorJsonModel(e)).ToArray());

        var principal = User;

        return new CurrentUserJsonModel
        {
            UserName = result.UserName,
            Roles = await authService.GetRolesAsync(model.UserName, model.Password)
        };
    }

TANGENT: (The var principal line was to test the current state while stepping through - While not null, User has not UserName or Claims in the Identity object when I step through after LogInAsync has been called (which I would think it should do at that point...).

Which calls an authService.LogInAsync method that looks like this...

        public async Task<AuthResult> LogInAsync(ApplicationUser user)
    {
        if (user != null)
        {
            await identityService.SignOutAsync();
            await identityService.SignInAsync(user);
        }

        return user != null
            ? new AuthResult(user)
            : new AuthResult("Password or Email address incorrect.");
    }

which uses identityService to wrap access to UserManager, SignInManager and RoleManager functions...

        public async Task SignInAsync(ApplicationUser user, bool isPersistent = true, string authenticationMethod = null)
        => await signInManager.SignInAsync(user, isPersistent, authenticationMethod);

When I load the app after having logged into the back end but having cleared the Vuex state (by refreshing the page) the app tries to call this method...

    [Authorize]
    [HttpGet]
    [ProducesResponseType(StatusCodes.Status401Unauthorized)]
    [ProducesResponseType(StatusCodes.Status403Forbidden)]
    public async Task<ActionResult<CurrentUserJsonModel>> Get()
    {
        if (HttpContextAccessor.HttpContext.User != null)
        {
            if (HttpContextAccessor.HttpContext.User.Identity.IsAuthenticated)
                return new CurrentUserJsonModel
                {
                    UserName = HttpContextAccessor.HttpContext.User.Identity.Name,
                    Roles = await authService.GetRolesAsync(HttpContextAccessor.HttpContext.User)
                };

            return Forbid();
        }

        return Unauthorized();
    }

When debugging the method isn't even stepped into - I'm getting a 401 thrown back at me on my browser console (which would make sense if Authorize was failing).

And for completeness, here's my vue.config.js

const baseUrl = ''

module.exports = {
    publicPath: baseUrl + '/',

    // place our built files into the parent project where they will be copied
    // into the distribution for deployment
    outputDir: '../wwwroot',

    filenameHashing: true, //process.env.NODE_ENV === 'production',
    lintOnSave: 'error',

    css: {
        modules: false,
        sourceMap: process.env.NODE_ENV !== 'production',
        loaderOptions: {
            sass: {
                data: `
                    $fa-font-path: ${process.env.NODE_ENV !== 'production' ? '"~/fonts"' : '"' + baseUrl + '/fonts"'};
                    @import "@/scss/base/index.scss";
                    @import "@/scss/helpers/index.scss";
                `
            }
        }
    },

    devServer: {
        host: 'localhost',
        port: 8080,
        hot: true,
        open: true,
        openPage: '',
        overlay: true,
        disableHostCheck: true,
        proxy: {
            // Proxy services to a backend API
            '/api': {
                target: process.env.PROXY || 'https://localhost:44368',
                secure: false,
                changeOrigin: true
            }
        }
    },

    // these node_modules use es6 so need transpiling for IE
    transpileDependencies: [
    ]
}

My console output in Visual Studio looks like this...

Microsoft.AspNetCore.Hosting.Internal.WebHost:Information: Request starting HTTP/1.1 GET http://localhost:44368/api/auth
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker:Information: Route matched with {action = "Get", controller = "Auth"}. Executing action Ddm.Lcp.Iptn.Dashboard.Web.Api.AuthController.Get (Ddm.Lcp.Iptn.Dashboard.Web)
Microsoft.AspNetCore.Authorization.DefaultAuthorizationService:Information: Authorization failed.
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker:Information: Authorization failed for the request at filter 'Microsoft.AspNetCore.Mvc.Authorization.AuthorizeFilter'.
Microsoft.AspNetCore.Mvc.ChallengeResult:Information: Executing ChallengeResult with authentication schemes ().
Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationHandler:Information: AuthenticationScheme: Cookies was challenged.
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker:Information: Executed action Ddm.Lcp.Iptn.Dashboard.Web.Api.AuthController.Get (Ddm.Lcp.Iptn.Dashboard.Web) in 10.8469ms
Microsoft.AspNetCore.Hosting.Internal.WebHost:Information: Request finished in 18.1495ms 401

This suggests that cookies are being challenged, as they should be given my set up - It does feel as if the actual sign in creation is not actually working.

The question is ... why is it failing?

UPDATE: According to @Kirk it may be related to a scheme mismatch between Cookies and Identity.Application. I have tested by commenting out the cookie elements in Startup and in this case I find myself in a recursive loop - I added the cookie elements to Startup.cs to enable me to get sensible responses from Authorization results.

I need to be able to do this but not get redirected to login pages which (In my app) do not exist and won't exist because it's an SPA.

Body:
signInManager.SignInAsync(...) uses the Identity.Application scheme, rather than the Cookies scheme that you've both registered and configured as the default. To use Identity and customise the cookie that it uses, use ConfigureApplicationCookie.

Replace the following:

services.AddAuthentication(options =>
{
    options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
}).AddCookie(options =>
{
    options.SlidingExpiration = true;
    options.Events.OnRedirectToLogin = cxt =>
    {
        cxt.Response.StatusCode = 401;
        return Task.CompletedTask;
    };
    options.Events.OnRedirectToAccessDenied = cxt =>
    {
        cxt.Response.StatusCode = 403;
        return Task.CompletedTask;
    };
    options.Events.OnRedirectToLogout = cxt => Task.CompletedTask;
});

-with-:

services.ConfigureApplicationCookie(options =>
{
    options.SlidingExpiration = true;
    options.Events.OnRedirectToLogin = cxt =>
    {
        cxt.Response.StatusCode = 401;
        return Task.CompletedTask;
    };
    options.Events.OnRedirectToAccessDenied = cxt =>
    {
        cxt.Response.StatusCode = 403;
        return Task.CompletedTask;
    };
    options.Events.OnRedirectToLogout = cxt => Task.CompletedTask;
});


问:
how can i add a css file to body of a page?
I am working on a page which has a print view so when the user clicks on "Print" a new window pops up and I want to add a .css file just for that window. </p>

<p>Thanks </p>

答:
EDIT: Removed due to clarification.  New answer:

Open the URL in a new window as such: blah.aspx?print=true

Then on your backend:

```<code>//Assuming you use .NET...
if(Request.Querystring("print").toLower() == "true" ) { //Convert to bool type if you are so inclined
   printCSS.Visible = True;
}
</code>```

HTML:

```<code><head>
    <link rel="stylesheet" type="text/css" href="..." visible="false" runat="server" id="printCSS" />
</head>
</code>```

You could also use one of the jQuery methods shown to load it in using jQuery too.

Body:
I am working on a page which has a print view so when the user clicks on "Print" a new window pops up and I want to add a .css file just for that window.

Thanks

Body:
EDIT: Removed due to clarification.  New answer:

Open the URL in a new window as such: blah.aspx?print=true

Then on your backend:

//Assuming you use .NET...
if(Request.Querystring("print").toLower() == "true" ) { //Convert to bool type if you are so inclined
   printCSS.Visible = True;
}

HTML:

<head>
    <link rel="stylesheet" type="text/css" href="..." visible="false" runat="server" id="printCSS" />
</head>

You could also use one of the jQuery methods shown to load it in using jQuery too.


问:
How to read json payload of a large response?
I am developing some code that will read a large json payload returned by the Export API of Mailchimp.

```<code>        var response = caller.PostAsync(endpoint, data).Result;

        var exportedData = response.Content.ReadAsStringAsync().Result;
</code>```

I am currently using the Visual Studio 2017 debugger to try and view the response but I keep getting an error that says:

Cannot obtain value of the local variable or argument because there is not enough memory available.

I ultimately want to extract information from each 'row' of this json data and do operations on them.  What do I need to do so that I can view this data without running out of memory?

答:
A general approach to operating over large JSON files:

I'd start by avoiding any attempt to decode to string. Instead, grab the content stream of your response, following what is described in my answer here to avoid downloading the entire stream into memory before you get your hands on it.

Now you can:

```<code>var stream = await response.Content.ReadAsStreamAsync();
</code>```

to grab a Stream instead of a string.

Now you can feed the stream directly into a deserializer, according to the information here:

```<code>using (StreamReader sr = new StreamReader(stream))
using (JsonReader reader = new JsonTextReader(sr))
{
    JsonSerializer serializer = new JsonSerializer();
    var o = serializer.Deserialize<SomeClassMatchingTheJsonSchema>(reader);
}
</code>```

If you're still choking on memory, you might need to consider operating at a lower-level using JsonTextReader

Body:
I am developing some code that will read a large json payload returned by the Export API of Mailchimp.

        var response = caller.PostAsync(endpoint, data).Result;

        var exportedData = response.Content.ReadAsStringAsync().Result;

I am currently using the Visual Studio 2017 debugger to try and view the response but I keep getting an error that says:

Cannot obtain value of the local variable or argument because there is not enough memory available.

I ultimately want to extract information from each 'row' of this json data and do operations on them.  What do I need to do so that I can view this data without running out of memory?

Body:
A general approach to operating over large JSON files:

I'd start by avoiding any attempt to decode to string. Instead, grab the content stream of your response, following what is described in my answer here to avoid downloading the entire stream into memory before you get your hands on it.

Now you can:

var stream = await response.Content.ReadAsStreamAsync();

to grab a Stream instead of a string.

Now you can feed the stream directly into a deserializer, according to the information here:

using (StreamReader sr = new StreamReader(stream))
using (JsonReader reader = new JsonTextReader(sr))
{
    JsonSerializer serializer = new JsonSerializer();
    var o = serializer.Deserialize<SomeClassMatchingTheJsonSchema>(reader);
}

If you're still choking on memory, you might need to consider operating at a lower-level using JsonTextReader


问:
Travis build is hanging waiting for user input (To install angular)
When building the app with Travis, the build hangs after it tries to install angular. It does this by waiting for input.

I have gone through the docs which show that this is indeed the case when "Waiting for keyboard input or other kind of human interaction". But I get no option of doing this anywhere. My  .travis.yml is up to date and does what is expected.

My .yml code

```<code>language: node_js
node_js:
  - "11.0"
sudo: required
branches:
  only:
    - master
before_script:
  - npm install -g --silent firebase-tools
  - npm install -g @angular/cli
script:
  - npm install
  - ng build --prod
deploy:
  skip_cleanup: true
  provider: firebase
  token:
    secure: "1/St7DD3G1QTmK-hdghJoK4cS348_bxklRqbuM3t7KGuE"

after_success:
  - firebase deploy --token "1/St7DD3G1QTmK-hdghJoK4cS348_bxklRqbuM3t7KGuE" --non-interactive

</code>```

Would you like to share anonymous usage data with the Angular Team at
  Google under Google’s Privacy Policy at
  https://policies.google.com/privacy? For more details  and how to
  change this setting, see http://angular.io/analytics. (y/N)  No output
  has been received in the last 10m0s, this potentially indicates a
  stalled build or something wrong with the build itself. Check the
  details on how to adjust your build configuration on:
  https://docs.travis-ci.com/user/common-build-problems/#Build-times-out-because-no-output-was-received
  The build has been terminated

答:
Change in your Travis file

from: npm install -g @angular/cli
to: es | npm install -g @angular/cli

This sends one "yes" to the NPM install command.

Body:
When building the app with Travis, the build hangs after it tries to install angular. It does this by waiting for input.

I have gone through the docs which show that this is indeed the case when "Waiting for keyboard input or other kind of human interaction". But I get no option of doing this anywhere. My  .travis.yml is up to date and does what is expected.

My .yml code

language: node_js
node_js:
  - "11.0"
sudo: required
branches:
  only:
    - master
before_script:
  - npm install -g --silent firebase-tools
  - npm install -g @angular/cli
script:
  - npm install
  - ng build --prod
deploy:
  skip_cleanup: true
  provider: firebase
  token:
    secure: "1/St7DD3G1QTmK-hdghJoK4cS348_bxklRqbuM3t7KGuE"

after_success:
  - firebase deploy --token "1/St7DD3G1QTmK-hdghJoK4cS348_bxklRqbuM3t7KGuE" --non-interactive

Would you like to share anonymous usage data with the Angular Team at
  Google under Google’s Privacy Policy at
  https://policies.google.com/privacy? For more details  and how to
  change this setting, see http://angular.io/analytics. (y/N)  No output
  has been received in the last 10m0s, this potentially indicates a
  stalled build or something wrong with the build itself. Check the
  details on how to adjust your build configuration on:
  https://docs.travis-ci.com/user/common-build-problems/#Build-times-out-because-no-output-was-received
  The build has been terminated


问:
Use Package variable instead of creating local variable
Consider following code snippet:

```<code>var name string

func init() {
   name = "ginny"
}

func test() {
   name, err := ...<some method>..
}
</code>```

In the method test, name is created as new local variable.

How do I make the test method to use the package variable name instead of creating new local variable?

答:
The := operator always creates new variables. You can it like this:

```<code>var name string

func init() {
   name = "ginny"
}

func test() {
   var err error
   name, err = ...<some method>..
}
</code>```

Body:
Consider following code snippet:

var name string

func init() {
   name = "ginny"
}

func test() {
   name, err := ...<some method>..
}

In the method test, name is created as new local variable.

How do I make the test method to use the package variable name instead of creating new local variable?

Body:
The := operator always creates new variables. You can it like this:

var name string

func init() {
   name = "ginny"
}

func test() {
   var err error
   name, err = ...<some method>..
}


问:
How to retrieve the password from a java.sql.Connection object
I'm looking for a way to get the password from a java.sql.Connection object.  I know there's a getUserName() method in the DatabaseMetaData object, but unfortunately no corresponding getPassword() method.  Using the debugger in Netbeans I can see a field for the password, so there must be a way to get this information using reflection, but thus far I've been unable to figure out how.</p>

答:
As I commented, the only way must be looking into the code. For instance, for MySQL using the latest driver (5.1.15). You can get the password like this:

```<code>public static void main(String[] args) throws Exception{
  ConnectionImpl con = (ConnectionImpl) DriverManager.getConnection("jdbc:mysql://localhost:3908/mydb?user=edalorzo&password=mandrake");

   System.out.println(con.getProperties().get("password"));

   con.close();
}
</code>```

But for this, you would need to know the class hierarchy and its implementation details.

Other databases most probably will be different. If your database is open source, like MySQL you can know the details of the inner construction and find ways to retrieve the password.

Body:
As I commented, the only way must be looking into the code. For instance, for MySQL using the latest driver (5.1.15). You can get the password like this:

public static void main(String[] args) throws Exception{
  ConnectionImpl con = (ConnectionImpl) DriverManager.getConnection("jdbc:mysql://localhost:3908/mydb?user=edalorzo&password=mandrake");

   System.out.println(con.getProperties().get("password"));

   con.close();
}

But for this, you would need to know the class hierarchy and its implementation details.

Other databases most probably will be different. If your database is open source, like MySQL you can know the details of the inner construction and find ways to retrieve the password.


问:
Inserting empty values as string to sql table
I have a project which has a Class which has some members as string which equal "". My teacher had shown examples with Class members declared as String = "NULL". I try to insert to SQL and I get this message:

Error insertion... Error converting data type varchar to numeric.

I know many will suggest to use parameterized values for inserting but I like to finish the way I started this.

I have tried to cast query string Object values with CDec, CInt, Cbit and still no clue how to do it right because I got Exceptions for trying to cast an "".

Also, I have changed to default values of members like this;

Dim NumberOfPackage As String = ""
```

<p>instead of;</p>

<pre class="lang-vb prettyprint-override"><code>Dim NumberOfPackage As String = "NULL"
</code>```

Some Columns in SQL table had ALLOW NULL checkBox set to NOT allowed, I changed the design of the Table to make it easier for insertion.

答:
To insert a NULL value, it must be without the apostrophes like @RichBenner and @the_lotus state:

Dim myCommand As String
myCommand = "INSERT INTO dbo.Foo (Foo_Text) VALUES (NULL);"
'The query for an empty string would look like this
myCommand = "INSERT INTO dbo.Foo (Foo_Text) VALUES ('');"
```

Body:
I have a project which has a Class which has some members as string which equal "". My teacher had shown examples with Class members declared as String = "NULL". I try to insert to SQL and I get this message:

Error insertion... Error converting data type varchar to numeric.

I know many will suggest to use parameterized values for inserting but I like to finish the way I started this.

I have tried to cast query string Object values with CDec, CInt, Cbit and still no clue how to do it right because I got Exceptions for trying to cast an "".

Also, I have changed to default values of members like this;

Dim NumberOfPackage As String = ""

instead of;

Dim NumberOfPackage As String = "NULL"

Some Columns in SQL table had ALLOW NULL checkBox set to NOT allowed, I changed the design of the Table to make it easier for insertion.