问:
How to get information using css selector and store it variable
I want to verify the values from a register by using a css selector

```<code>[FindsBy(How = How.CssSelector, Using = "#grid_cases > table > tbody")]
private IWebElement CaseListGrid;
</code>```

I have to return the WebElements value and store it to string

```<code>public List<CaseListEntry> GetCaseListEntries()
{
    CaseListGrid.
    return null;
}
</code>```

答:
You can get the text from your CaseListGrid element by using the following:

```<code>CaseListGrid.Text;
</code>```

But you are retrieving a tbody, which probably doesn't have any text in it.

After you retrieved the CaseListGrid element, you could do something like this to retrieve all td tags inside the tbody.

```<code>CaseListGrid.FindElements(By.TagName("td"));
</code>```

After that, loop over the elements and retrieve the text:

```<code>public List<CaseListEntry> GetCaseListEntries()
{
    var elements = CaseListGrid.FindElements(By.TagName("td"));
    var listEntries = new List<CaseListEntry>();

    foreach (var element in elements)
    {
        var text = element.Text;

        if (!string.IsNullOrWhiteSpace(text))
            listEntries.Add(new CaseListEntry(text)); // I don't know what kind of class CaseListEntry is, so this is pseudo code
    }

    return listEntries;
}
</code>```

Body:
I want to verify the values from a register by using a css selector

[FindsBy(How = How.CssSelector, Using = "#grid_cases > table > tbody")]
private IWebElement CaseListGrid;

I have to return the WebElements value and store it to string

public List<CaseListEntry> GetCaseListEntries()
{
    CaseListGrid.
    return null;
}

Body:
You can get the text from your CaseListGrid element by using the following:

CaseListGrid.Text;

But you are retrieving a tbody, which probably doesn't have any text in it.

After you retrieved the CaseListGrid element, you could do something like this to retrieve all td tags inside the tbody.

CaseListGrid.FindElements(By.TagName("td"));

After that, loop over the elements and retrieve the text:

public List<CaseListEntry> GetCaseListEntries()
{
    var elements = CaseListGrid.FindElements(By.TagName("td"));
    var listEntries = new List<CaseListEntry>();

    foreach (var element in elements)
    {
        var text = element.Text;

        if (!string.IsNullOrWhiteSpace(text))
            listEntries.Add(new CaseListEntry(text)); // I don't know what kind of class CaseListEntry is, so this is pseudo code
    }

    return listEntries;
}


来源: stackexchange

问:
Is there any event to notify when Environment.CurrentDirectory got changed?
In my code I am trying to read a file using File.Open() with relative path. But some times the current directory is getting changed and directory not found exception is coming.

I am trying to figure out where is Environment.CurrentDirectory is getting changed. I checked the Directory.SetCurrentDirectory method but its calling to native method.

Is there any event which will notify me when Environment.CurrentDirectory has changed? How do I find out where exactly is directory changed?

I have tried putting break point in all occurrence of Environment.CurrentDirectory and Directory.SetCurrentDirectory().

答:
It's necessary more details, I've never seen this attribute changing during runtime.

If you are running the executable from Start Menu ou another shortcuts, the current directory will change, check the property "Starts In".

If you are deploying a Click Once application, every version was installed at different folder, and you won't find files saved at same executable folder.

I found some references that OpenFileDialogs (and opendirectorydialog) changes the Environment.CurrentDirectory.

Source: OpenFileDialog and Environment.CurrentDirectory

ContentLicense: CC BY-SA 3.0


问:
How to call external javascript function in angular 5?
I have downloaded a theme from this link. I have to define script and CSS in index.html file.

index.html (body section)

```<code><body>
  <app-root></app-root>
  <script type="text/javascript" src="./assets/js/main.85741bff.js"></script>
  <script type="text/javascript" src="./assets/js/common.js"></script>
</body>
</code>```

I have defind my function in common.js and call it from main.85741bff.js file.

common.js (function)

```<code>document.addEventListener("DOMContentLoaded", function (event) {
     masonryBuild();
     navbarToggleSidebar();
     navActivePage();
});
</code>```

The issue is that I am able to call the function while page reloads but can't call the function while content load.

Can anyone help me to resolve this issue? Any help would be appreciated.

答:
You can call these methods by window object-</p>

```<code>document.addEventListener("DOMContentLoaded", function (event) {
      window['navbarToggleSidebar']();
      window['navActivePage']();
 });
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have downloaded a theme from this link. I have to define script and CSS in index.html file.

index.html (body section)

  <app-root></app-root>

I have defind my function in common.js and call it from main.85741bff.js file.

common.js (function)

document.addEventListener("DOMContentLoaded", function (event) {
     masonryBuild();
     navbarToggleSidebar();
     navActivePage();
});

The issue is that I am able to call the function while page reloads but can't call the function while content load.

Can anyone help me to resolve this issue? Any help would be appreciated.

Body:
You can call these methods by window object-

document.addEventListener("DOMContentLoaded", function (event) {
      window['navbarToggleSidebar']();
      window['navActivePage']();
 });


问:
Running Azcopy in parallel - bottleneck?
I want to download/upload files to Azure in parallel.
AzCopy, by default does not allow multiple runs on the same copy because of the locks on journal files. I am running multiple Azcopy instances on the same machine by pointing each of these instances to different journal files (using /Z )

But what is the bottle-neck in doing this? Bandwidth is obvious, but what is the bottleneck from Azure's side.

答:
There is no real bottleneck from Azure's sides. Keep in mind though that the transfers are done with spare bandwidth and that there is no SLA as to whether it'll be fast or slow. That's all.

The other bottleneck you may need to check is your local CPU, when running over 4 AzCopy instances in parallel with 4 parallel uploads each my i7 starts to sweat a bit.


问:
how to create a variable that can store object of unrelated classes
I'm using reflection to call methods of different classes which are unrelated in terms of functionality but related in terms of operation. Hence I have to pass the object of those classes to invoke method, but how do I store the object in the same variable?

```<code>Method target;
if (handlerType.equals("database")){
    target = DatabaseRequestHandler.class.getMethod(method, Args.class);
} else if (handlerType.equals("document")){
    target = DocumentRequestHandler.class.getMethod(method, Args.class);
} else if (handlerType.equals("dictionary")){
    target = DictionaryRequestHandler.class.getMethod(method, Args.class);
} else {
    throw new IllegalArgumentException("Handler not implemented for this call");
}
//Method target = RequestHandler.class.getMethod(method, Args.class);
if (target.getReturnType().equals(Void.TYPE)) {
    target.invoke(requestHandler, args);
} else {
    Object result = target.invoke(requestHandler, args);
    body = ValueSerializer.serialize(result, memory);
}
</code>```

How should I declare requestHandler variable so that I can store the object of DatabaseHandler, DocumentHandler and DictionaryHandler? All these classes are not related to each other, so there is not point of using the inheritance with them. I'm from a Python background so really not sure how to achieve this.

答:
Method.invoke accept an Object for the instance to use. So you can simply declare an Object or (better) a common class/interface if available.

```<code>MyHandler requestHandler ...
</code>```

or

```<code>Object requestHandler ....
</code>```

FYI :

You should rethink that logic, I believe you should be able to remove the reflection using a Consumer or a Function to execute a method reference.

Body:
I'm using reflection to call methods of different classes which are unrelated in terms of functionality but related in terms of operation. Hence I have to pass the object of those classes to invoke method, but how do I store the object in the same variable?

Method target;
if (handlerType.equals("database")){
    target = DatabaseRequestHandler.class.getMethod(method, Args.class);
} else if (handlerType.equals("document")){
    target = DocumentRequestHandler.class.getMethod(method, Args.class);
} else if (handlerType.equals("dictionary")){
    target = DictionaryRequestHandler.class.getMethod(method, Args.class);
} else {
    throw new IllegalArgumentException("Handler not implemented for this call");
}
//Method target = RequestHandler.class.getMethod(method, Args.class);
if (target.getReturnType().equals(Void.TYPE)) {
    target.invoke(requestHandler, args);
} else {
    Object result = target.invoke(requestHandler, args);
    body = ValueSerializer.serialize(result, memory);
}

How should I declare requestHandler variable so that I can store the object of DatabaseHandler, DocumentHandler and DictionaryHandler? All these classes are not related to each other, so there is not point of using the inheritance with them. I'm from a Python background so really not sure how to achieve this.

Body:
Method.invoke accept an Object for the instance to use. So you can simply declare an Object or (better) a common class/interface if available.

MyHandler requestHandler ...

or

Object requestHandler ....

FYI :

You should rethink that logic, I believe you should be able to remove the reflection using a Consumer or a Function to execute a method reference.


问:
Zend Framework Routing: .html extension
I know I've seen this done before but I can't find the information anywhere. I need to be able to route with .html extensions in the Zend Framework.

I.E. /controller/action.html should route to the appropriate controller / action.

We have an idea to throw away the .html extension with our .htaccess file but I think changing the route config would be the better solution.

Any advice is welcome.

答:
A quick search on google yielded the following tutorials:

Extending Zend Framework Route and Router for custom routing

Routing and complex URLs in Zend Framework

ContentLicense: CC BY-SA 2.5

Title: Zend Framework Routing: .html extension

LastEditorDisplayName: Fabian Steeg


问:
How do you become an expert in a programming language?
Assuming you have basic to intermediate knowledge of a particular language, how can you become an expert in that language in a short amount of time?</p>

答:
Pull all your information sources together - such as:

The official language documentation,
Best practice books,
Google around for tutorial sites,

Get used to searching and finding what you need quickly


问:
Xamarin : Change label text inside listview
I am new with xamarin, I am facing an issue in my xamarin forms project.
I have a Label and 2 images inside listview-viewcell. I want to change the label text onclick of images. Increase the label text value by 1 if click like and decrease by 1 if click unlike. I use the label x:name, but it is not accessible in class. How can i fix this?

```<code>    <StackLayout>
        <ListView>
            <ListView.ItemTemplate>
                <DataTemplate>
                    <ViewCell>
                    <StackLayout>
                        <Label
                            Text="{Binding likeCount}"
                            x:Name="likecount"/>
                         <Image Source="like.png">
                               <Image.GestureRecognizers>
                                    <TapGestureRecognizer
                                        Tapped="LikeOrUnlikeTweet"
                                        CommandParameter="{Binding .}"
                                        NumberOfTapsRequired="1" />
                                </Image.GestureRecognizers>
                            </Image
                            <Image Source="unlike.png">
                               <Image.GestureRecognizers>
                                    <TapGestureRecognizer
                                        Tapped="LikeOrUnlikeTweet"
                                        CommandParameter="{Binding .}"
                                        NumberOfTapsRequired="1" />
                                </Image.GestureRecognizers>
                            </Image
                        </StackLayout>
                    </ViewCell>
                </DataTemplate>
            </ListView.ItemTemplate>
          </ListView>
    </StackLayout>
</code>```

Anybody please suggest a solution with working code.
Thanks in advance

答:
First of you need to create command in your VM and need to change as follow:

```<code> <TapGestureRecognizer
      Tapped="{Binding Source={x:Reference YourListName}, Path=BindingContext.LikeOrUnlikeTweetCommand}"
      CommandParameter="{Binding .}"
      NumberOfTapsRequired="1" />
</code>```

ViewModel Code

```<code>public ICommand LikeOrUnlikeTweetCommand { get; }
</code>```

Initialise in constructor

```<code>LikeOrUnlikeTweetCommand = new Command<YourModelDto>(LikeOrUnlikeTweet);
</code>```

Function code in this you change your count value and update list.

```<code>void LikeOrUnlikeTweet(YourModelDto yourModelDto)
{
        ....
}
</code>```

Body:
I am new with xamarin, I am facing an issue in my xamarin forms project.
I have a Label and 2 images inside listview-viewcell. I want to change the label text onclick of images. Increase the label text value by 1 if click like and decrease by 1 if click unlike. I use the label x:name, but it is not accessible in class. How can i fix this?

    <StackLayout>
        <ListView>
            <ListView.ItemTemplate>
                <DataTemplate>
                    <ViewCell>
                    <StackLayout>

                         <Image Source="like.png">
                               <Image.GestureRecognizers>
                                    <TapGestureRecognizer
                                        Tapped="LikeOrUnlikeTweet"
                                        CommandParameter="{Binding .}"
                                        NumberOfTapsRequired="1" />
                                </Image.GestureRecognizers>
                            </Image
                            <Image Source="unlike.png">
                               <Image.GestureRecognizers>
                                    <TapGestureRecognizer
                                        Tapped="LikeOrUnlikeTweet"
                                        CommandParameter="{Binding .}"
                                        NumberOfTapsRequired="1" />
                                </Image.GestureRecognizers>
                            </Image
                        </StackLayout>
                    </ViewCell>
                </DataTemplate>
            </ListView.ItemTemplate>
          </ListView>
    </StackLayout>

Anybody please suggest a solution with working code.
Thanks in advance

Body:
First of you need to create command in your VM and need to change as follow:

 <TapGestureRecognizer
      Tapped="{Binding Source={x:Reference YourListName}, Path=BindingContext.LikeOrUnlikeTweetCommand}"
      CommandParameter="{Binding .}"
      NumberOfTapsRequired="1" />

ViewModel Code

public ICommand LikeOrUnlikeTweetCommand { get; }

Initialise in constructor

LikeOrUnlikeTweetCommand = new Command<YourModelDto>(LikeOrUnlikeTweet);

Function code in this you change your count value and update list.

void LikeOrUnlikeTweet(YourModelDto yourModelDto)
{
        ....
}


问:
Database Design: How to store column properties?
I have an web application which has many forms with many fields. Some of these fields are required and some are not, but I would like to be able to save the form values in a database table so that users can save their progress. How do I store this meta-information about columns? To be concrete, say I have a table:

```<code>create table form1 (
    field1 text,
    field2 text,
    -- ...
    fieldn text
)
</code>```

I would like to store the business logic about which fields are required somewhere, so that I can query the DB to get something like:

```<code>('field1_val', true, null, false, ..., 'fieldn_val', true)
</code>```

where every odd column is are the values store in the table, and even column are whether the fields are required or not. I thought about having a separate table storing the requirement data as so:

```<code>create table form1_requirements (
    table_name text,
    field_name text,
    required boolean
);
insert into form1_requirements values ('foo', 'field1', true);
insert into form1_requirements values ('foo', 'field2', false);
insert into form1_requirements values ('foo', 'fieldn', true);
</code>```

However, I'm not sure if it's possible to do a join like that, and if it's advisable.

What is the best solution for this? I'm primarily interested in postgresql, but also mysql and sqlite3.

答:
Why not just define the columns you need as NOT NULL?

```<code>create table form1 (
    field1 text not null,
    field2 text,
    -- ...
    fieldn text not null
);
</code>```

The ones declared not null are then required.

Body:
I have an web application which has many forms with many fields. Some of these fields are required and some are not, but I would like to be able to save the form values in a database table so that users can save their progress. How do I store this meta-information about columns? To be concrete, say I have a table:

create table form1 (
    field1 text,
    field2 text,
    -- ...
    fieldn text
)

I would like to store the business logic about which fields are required somewhere, so that I can query the DB to get something like:

('field1_val', true, null, false, ..., 'fieldn_val', true)

where every odd column is are the values store in the table, and even column are whether the fields are required or not. I thought about having a separate table storing the requirement data as so:

create table form1_requirements (
    table_name text,
    field_name text,
    required boolean
);
insert into form1_requirements values ('foo', 'field1', true);
insert into form1_requirements values ('foo', 'field2', false);
insert into form1_requirements values ('foo', 'fieldn', true);

However, I'm not sure if it's possible to do a join like that, and if it's advisable.

What is the best solution for this? I'm primarily interested in postgresql, but also mysql and sqlite3.

Body:
Why not just define the columns you need as NOT NULL?

create table form1 (
    field1 text not null,
    field2 text,
    -- ...
    fieldn text not null
);

The ones declared not null are then required.


问:
JavaScript closure that returns a function
```<code>function funcA(){
  var name = "jack";
  console.log(name);
  return function(){
    name = name + " plus";
    console.log(name);
  };
}
var funB = funcA();
funB()

// expected result: "jack" and "jack plus"
</code>```

I am confused why runnnig var funB = funcA(); only outputs "jack"?

Why doesn't the second sentence output? Why must it be run a second time to output as intended?

答: When you call funcA() "var funB = funcA()". It logs "jack" then it returns a function. If you return a function, it does not automatically run it first. You only run it when you call it "funB();".</p>

Body:
function funcA(){
  var name = "jack";
  console.log(name);
  return function(){
    name = name + " plus";
    console.log(name);
  };
}
var funB = funcA();
funB()

// expected result: "jack" and "jack plus"

I am confused why runnnig var funB = funcA(); only outputs "jack"?

Why doesn't the second sentence output? Why must it be run a second time to output as intended?


问:
Thinking Sphinx Facets on associated model
Is there anyway of defining facet on an associated model's column which is of type int?Does sphinx convert all fields defined as facets to strings if they are of an associated models columns?

I am trying to define a column of my child table as an facet.After
rebuilding when I do Model1.facets i get this error.

```<code>class Model1 < ActiveRecord::Base
  ....

  has_many :communities, :through => :model2

  ...

  define indexes

     ...

     indexes model2.community_id, :as => :community_id, :facet => :true

     ...

  end

end
</code>```

model 1 - Current model
model 2 - join model using :through

```<code>Model1.facets

NoMethodError: undefined method `to_crc32' for 9:Fixnum
        from D:/Current/TechAssistTest/vendor/plugins/thinking-sphinx/
lib/thinking_sphinx/facet.rb:99:in `translate'
        from (irb):3:in `detect'
        from D:/Current/TechAssistTest/vendor/plugins/thinking-sphinx/
lib/thinking_sphinx/facet.rb:98:in `each'
        from D:/Current/TechAssistTest/vendor/plugins/thinking-sphinx/
lib/thinking_sphinx/facet.rb:98:in `detect'
        from D:/Current/TechAssistTest/vendor/plugins/thinking-sphinx/
lib/thinking_sphinx/facet.rb:98:in `translate'
        from D:/Current/TechAssistTest/vendor/plugins/thinking-sphinx/
lib/thinking_sphinx/facet.rb:75:in `value'
        from D:/Current/TechAssistTest/vendor/plugins/thinking-sphinx/
lib/thinking_sphinx/facet_search.rb:114:in `add_from_results'
        from D:/Current/TechAssistTest/vendor/plugins/thinking-sphinx/
lib/thinking_sphinx/search.rb:219:in `each_with_groupby_and_count'
        from (irb):3:in `each_with_index'
        from D:/Current/TechAssistTest/vendor/plugins/thinking-sphinx/
lib/thinking_sphinx/search.rb:218:in `each'
        from D:/Current/TechAssistTest/vendor/plugins/thinking-sphinx/
lib/thinking_sphinx/search.rb:218:in `each_with_index'
        from D:/Current/TechAssistTest/vendor/plugins/thinking-sphinx/
lib/thinking_sphinx/search.rb:218:in `each_with_groupby_and_count'
        from D:/Current/TechAssistTest/vendor/plugins/thinking-sphinx/
lib/thinking_sphinx/facet_search.rb:113:in `add_from_results'
        from D:/Current/TechAssistTest/vendor/plugins/thinking-sphinx/
lib/thinking_sphinx/facet_search.rb:49:in `populate'
        from D:/Current/TechAssistTest/vendor/plugins/thinking-sphinx/
lib/thinking_sphinx/facet_search.rb:47:in `each'
        from D:/Current/TechAssistTest/vendor/plugins/thinking-sphinx/
lib/thinking_sphinx/facet_search.rb:47:in `populate'
        from D:/Current/TechAssistTest/vendor/plugins/thinking-sphinx/
lib/thinking_sphinx/facet_search.rb:13:in `initialize'
        from D:/Current/TechAssistTest/vendor/plugins/thinking-sphinx/
lib/thinking_sphinx/search_methods.rb:422:in `new'
        from D:/Current/TechAssistTest/vendor/plugins/thinking-sphinx/
lib/thinking_sphinx/search_methods.rb:422:in `facets'
        from (irb):3>>
</code>```

答:
If you're using integers for facets, then they should be defined as attributes:

```<code>has model2.community_id, :as => :community_id, :facet => :true
</code>```

The indexes method is for fields - which are the textual data you want people to be able to search for. I'm guessing the people who use your site won't be entering in the community id into the search field. Leave a comment if that's not the case, and I'll expand on how you can have the community_id as both a field and an attribute.

Body:
Is there anyway of defining facet on an associated model's column which is of type int?Does sphinx convert all fields defined as facets to strings if they are of an associated models columns?

I am trying to define a column of my child table as an facet.After
rebuilding when I do Model1.facets i get this error.

class Model1 < ActiveRecord::Base
  ....

  has_many :communities, :through => :model2

  ...

  define indexes

     ...

     indexes model2.community_id, :as => :community_id, :facet => :true

     ...

  end

end

model 1 - Current model
model 2 - join model using :through

Model1.facets

NoMethodError: undefined method `to_crc32' for 9:Fixnum
        from D:/Current/TechAssistTest/vendor/plugins/thinking-sphinx/
lib/thinking_sphinx/facet.rb:99:in `translate'
        from (irb):3:in `detect'
        from D:/Current/TechAssistTest/vendor/plugins/thinking-sphinx/
lib/thinking_sphinx/facet.rb:98:in `each'
        from D:/Current/TechAssistTest/vendor/plugins/thinking-sphinx/
lib/thinking_sphinx/facet.rb:98:in `detect'
        from D:/Current/TechAssistTest/vendor/plugins/thinking-sphinx/
lib/thinking_sphinx/facet.rb:98:in `translate'
        from D:/Current/TechAssistTest/vendor/plugins/thinking-sphinx/
lib/thinking_sphinx/facet.rb:75:in `value'
        from D:/Current/TechAssistTest/vendor/plugins/thinking-sphinx/
lib/thinking_sphinx/facet_search.rb:114:in `add_from_results'
        from D:/Current/TechAssistTest/vendor/plugins/thinking-sphinx/
lib/thinking_sphinx/search.rb:219:in `each_with_groupby_and_count'
        from (irb):3:in `each_with_index'
        from D:/Current/TechAssistTest/vendor/plugins/thinking-sphinx/
lib/thinking_sphinx/search.rb:218:in `each'
        from D:/Current/TechAssistTest/vendor/plugins/thinking-sphinx/
lib/thinking_sphinx/search.rb:218:in `each_with_index'
        from D:/Current/TechAssistTest/vendor/plugins/thinking-sphinx/
lib/thinking_sphinx/search.rb:218:in `each_with_groupby_and_count'
        from D:/Current/TechAssistTest/vendor/plugins/thinking-sphinx/
lib/thinking_sphinx/facet_search.rb:113:in `add_from_results'
        from D:/Current/TechAssistTest/vendor/plugins/thinking-sphinx/
lib/thinking_sphinx/facet_search.rb:49:in `populate'
        from D:/Current/TechAssistTest/vendor/plugins/thinking-sphinx/
lib/thinking_sphinx/facet_search.rb:47:in `each'
        from D:/Current/TechAssistTest/vendor/plugins/thinking-sphinx/
lib/thinking_sphinx/facet_search.rb:47:in `populate'
        from D:/Current/TechAssistTest/vendor/plugins/thinking-sphinx/
lib/thinking_sphinx/facet_search.rb:13:in `initialize'
        from D:/Current/TechAssistTest/vendor/plugins/thinking-sphinx/
lib/thinking_sphinx/search_methods.rb:422:in `new'
        from D:/Current/TechAssistTest/vendor/plugins/thinking-sphinx/
lib/thinking_sphinx/search_methods.rb:422:in `facets'
        from (irb):3>>

Body:
If you're using integers for facets, then they should be defined as attributes:

has model2.community_id, :as => :community_id, :facet => :true

The indexes method is for fields - which are the textual data you want people to be able to search for. I'm guessing the people who use your site won't be entering in the community id into the search field. Leave a comment if that's not the case, and I'll expand on how you can have the community_id as both a field and an attribute.


答:
I would not store those fields like that. The fields should be in a separate table with a one-to-many relation to a forms table:

```<code>create table form
(
   id integer primary key,
   name text not null unique,
   ... other columns for the form ...
);

create table field
(
  id integer primary key,
  form_id integer not null reference form
  name text not null,
  required boolean,
  ... other columns describing a single field, e.g. the data type ...
);
</code>```

And the individual values should be stored in a separate table:

```<code>create table form_values
(
  form_id integer not null references form,
  field_id integer not null references field,
  value text,
  primary key (form_id, field_id)
);
</code>```

The above is also know as the "Entity-Attribute-Value" design pattern.

Another option is to store that information in json columns:

```<code>create table form
(
   id integer primary key,
   name text not null unique,
   field_definitions jsonb
);
</code>```

In the column field_definitions you would store something like:

```<code>{
  "field_1": {"name": "Lastname", "required": true }},
  "field_2": {"name": "Firstname", "required": false }}
}
</code>```

You should still use a second table to store the actual field values. You could also store all values for a single form in one JSON column.

Title: Database Design: How to store column properties?

Body:
I would not store those fields like that. The fields should be in a separate table with a one-to-many relation to a forms table:

create table form
(
   id integer primary key,
   name text not null unique,
   ... other columns for the form ...
);

create table field
(
  id integer primary key,
  form_id integer not null reference form
  name text not null,
  required boolean,
  ... other columns describing a single field, e.g. the data type ...
);

And the individual values should be stored in a separate table:

create table form_values
(
  form_id integer not null references form,
  field_id integer not null references field,
  value text,
  primary key (form_id, field_id)
);

The above is also know as the "Entity-Attribute-Value" design pattern.

Another option is to store that information in json columns:

create table form
(
   id integer primary key,
   name text not null unique,
   field_definitions jsonb
);

In the column field_definitions you would store something like:

{
  "field_1": {"name": "Lastname", "required": true }},
  "field_2": {"name": "Firstname", "required": false }}
}

You should still use a second table to store the actual field values. You could also store all values for a single form in one JSON column.


问:
return Json as string from spring controller and get in Ajax to populate in datatable
am trying to convert my list of data as string using Json and return it to Ajax to populate in datatable. The spring controller able to convert it to Json data but am confusing how to return it from spring and get it in Ajax success, can anyone help me on this. Below is my code details,

Controller Class

```<code>    @Controller
    @RequestMapping(value = "/json")
    public class JsonController {
        @RequestMapping(value = "/postEmployee", method = RequestMethod.POST, produces = "application/json")
        public @ResponseBody
        String postEmployeeData() throws JsonGenerationException,
                JsonMappingException, IOException {
            List<Users> users = new ArrayList<Users>();
            for (int i = 0; i < 5; i++) {
                Users user = new Users();
                user.setName("Akram");
                user.setPrincipal("DEC");
                users.add(user);
            }
            ObjectMapper mapper = new ObjectMapper();
            String data = mapper.writeValueAsString(users);
            return data;
        }
</code>```

Jquery

```<code>    <script type="text/javascript">
            $("#submit").click(function() {
                $.ajax({
                    type : "post",
                    url : "/myApp/json/postEmployee.do",
                    cache : false,
                    success : function(response) {
                        display(response);
                        alert('Inside success');
                        var obj = JSON.parse(response);
                        alert(obj);
                    },
                    error : function() {
                        alert('Error while request..');
                    }
                });
            });
        </script>
</code>```

In POM.xml

```<code><dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.6.3</version>
</dependency>
</code>```

Here am getting no response. So please help me to achieve this.

答:
You can return a list directly if you have a properly configured Spring application it should return a json value. </p>

```<code>    (...)
    public @ResponseBody List<Users> postEmployeeData() {
        (...)
        return users;
    }
</code>```

Body:
am trying to convert my list of data as string using Json and return it to Ajax to populate in datatable. The spring controller able to convert it to Json data but am confusing how to return it from spring and get it in Ajax success, can anyone help me on this. Below is my code details,

Controller Class

    @Controller
    @RequestMapping(value = "/json")
    public class JsonController {
        @RequestMapping(value = "/postEmployee", method = RequestMethod.POST, produces = "application/json")
        public @ResponseBody
        String postEmployeeData() throws JsonGenerationException,
                JsonMappingException, IOException {
            List<Users> users = new ArrayList<Users>();
            for (int i = 0; i < 5; i++) {
                Users user = new Users();
                user.setName("Akram");
                user.setPrincipal("DEC");
                users.add(user);
            }
            ObjectMapper mapper = new ObjectMapper();
            String data = mapper.writeValueAsString(users);
            return data;
        }

Jquery

In POM.xml

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.6.3</version>
</dependency>

Here am getting no response. So please help me to achieve this.

Body:
You can return a list directly if you have a properly configured Spring application it should return a json value.

    (...)
    public @ResponseBody List<Users> postEmployeeData() {
        (...)
        return users;
    }


问:
cake build angular application to deploy to azure
I have created a angular application using command ng new APPNAME. I want to use cake build to deploy this application. Is it possible to use cake build? If so how? My end target is to deploy it to azure, but i need to do it with Cake build. I have uploaded all the source code to git repository.

答:
So building a plain vanilla app with the Angular CLI would look something like this

```<code>string          target      = Argument("target", "Build");
FilePath        ngPath      = Context.Tools.Resolve("ng.cmd");
FilePath        npmPath     = Context.Tools.Resolve("npm.cmd");
DirectoryPath   outputPath  = MakeAbsolute(Directory("./output"));

Action<FilePath, ProcessArgumentBuilder> Cmd => (path, args) => {
    var result = StartProcess(
        path,
        new ProcessSettings {
            Arguments = args
        });

    if(0 != result)
    {
        throw new Exception($"Failed to execute tool {path.GetFilename()} ({result})");
    }
};

Task("Install-AngularCLI")
    .Does(() => {
    if (ngPath != null && FileExists(ngPath))
    {
        Information("Found Angular CLI at {0}.", ngPath);
        return;
    }

    DirectoryPath ngDirectoryPath = MakeAbsolute(Directory("./Tools/ng"));

    EnsureDirectoryExists(ngDirectoryPath);

    Cmd(npmPath,
        new ProcessArgumentBuilder()
                .Append("install")
                .Append("--prefix")
                .AppendQuoted(ngDirectoryPath.FullPath)
                .Append("@angular/cli")
    );
    ngPath = Context.Tools.Resolve("ng.cmd");
});

Task("Clean")
    .Does( ()=> {
        CleanDirectory(outputPath);
});

Task("Install")
    .IsDependentOn("Clean")
    .Does( ()=> {
    Cmd(npmPath,
        new ProcessArgumentBuilder()
            .Append("install")
    );
});

Task("Build")
    .IsDependentOn("Install-AngularCLI")
    .IsDependentOn("Install")
    .Does( ()=> {
    Cmd(ngPath,
        new ProcessArgumentBuilder()
            .Append("build")
            .Append("--output-path")
            .AppendQuoted(outputPath.FullPath)
    );
});

RunTarget(target);
</code>```

Which basically does

Install Angular CLI If not found

Install node modules

Build Angular app

If you want to run the build and publish on kudu you can use the Cake.Kudu addin and KuduSync tool, dependencies are declared by adding tool and addin pre-processor directives like this:

```<code>#tool nuget:?package=KuduSync.NET&version=1.3.1
#addin nuget:?package=Cake.Kudu&version=0.6.0
</code>```

And the publish task would look something like this

```<code>Task("Publish")
    .IsDependentOn("Build")
    .Does( ()=> {
      Kudu.Sync(outputPath);
});
</code>```

For kudu to know it should use a custom deployment script you need to add a .deployment file telling it do so, which could look something like this:

```<code>[config]
command = deploy.cmd
</code>```

And a custom boostrapper to install Cake i the kudu environment which could look something like this:

```<code>@ECHO OFF
REM SET Cake
SET CAKE_VERSION=0.23.0
SET CAKE_FOLDER=Cake.%CAKE_VERSION%
SET PATH=%~dp0\Tools;%PATH%

REM Cleanup any old Cake versions
FOR /f "delims=" %%c IN ('dir /AD /B "Tools\Cake*"') DO (
        IF NOT "%%c" == "%CAKE_FOLDER%" (RD /S /Q "Tools\%%c")
)

REM Install Dependencies
IF NOT EXIST "Tools" (md "Tools")
IF NOT EXIST "Tools\Addins" (md "Tools\Addins")
IF NOT EXIST "Tools\%CAKE_FOLDER%\Cake.exe" (
    echo Downloading Cake %CAKE_VERSION%
    nuget install Cake -Version %CAKE_VERSION% -OutputDirectory "Tools" -Source https://api.nuget.org/v3/index.json
    )

REM Execute deploy
Tools\%CAKE_FOLDER%\Cake.exe -version
Tools\%CAKE_FOLDER%\Cake.exe build.cake --Target="Publish"
</code>```

Which basically just cleans up any old Cake versions and fetches 0.23.0 if not already installed.

The complete Cake script would look something like below

```<code>#tool nuget:?package=KuduSync.NET&version=1.3.1
#addin nuget:?package=Cake.Kudu&version=0.6.0
    string          target      = Argument("target", "Build");
    FilePath        ngPath      = Context.Tools.Resolve("ng.cmd");
    FilePath        npmPath     = Context.Tools.Resolve("npm.cmd");
    DirectoryPath   outputPath  = MakeAbsolute(Directory("./output"));

    Action<FilePath, ProcessArgumentBuilder> Cmd => (path, args) => {
        var result = StartProcess(
            path,
            new ProcessSettings {
                Arguments = args
            });

        if(0 != result)
        {
            throw new Exception($"Failed to execute tool {path.GetFilename()} ({result})");
        }
    };

    Task("Install-AngularCLI")
        .Does(() => {
        if (ngPath != null && FileExists(ngPath))
        {
            Information("Found Angular CLI at {0}.", ngPath);
            return;
        }

        DirectoryPath ngDirectoryPath = MakeAbsolute(Directory("./Tools/ng"));

        EnsureDirectoryExists(ngDirectoryPath);

        Cmd(npmPath,
            new ProcessArgumentBuilder()
                    .Append("install")
                    .Append("--prefix")
                    .AppendQuoted(ngDirectoryPath.FullPath)
                    .Append("@angular/cli")
        );
        ngPath = Context.Tools.Resolve("ng.cmd");
    });

    Task("Clean")
        .Does( ()=> {
            CleanDirectory(outputPath);
    });

    Task("Install")
        .IsDependentOn("Clean")
        .Does( ()=> {
        Cmd(npmPath,
            new ProcessArgumentBuilder()
                .Append("install")
        );
    });

    Task("Build")
        .IsDependentOn("Install-AngularCLI")
        .IsDependentOn("Install")
        .Does( ()=> {
        Cmd(ngPath,
            new ProcessArgumentBuilder()
                .Append("build")
                .Append("--output-path")
                .AppendQuoted(outputPath.FullPath)
        );
    });

Task("Publish")
    .IsDependentOn("Build")
    .Does( ()=> {
    Kudu.Sync(outputPath);
});

RunTarget(target);
</code>```

And output on the Kudu build running on your Azure web site would look something like this

```<code>             +##   #;;'
             #;;#  .+;;;;+,
             '+;;#;,+';;;;;'#.
             ++'''';;;;;;;;;;# ;#;
            ##';;;;++'+#;;;;;'.   `#:
         ;#   '+'';;;;;;;;;'#`       #.
      `#,        .'++;;;;;':..........#
    '+      `.........';;;;':.........#
   #..................+;;;;;':........#
   #..................#';;;;;'+''''''.#
   #.......,:;''''''''##';;;;;'+'''''#,
   #''''''''''''''''''###';;;;;;+''''#
   #''''''''''''''''''####';;;;;;#'''#
   #''''''''''''''''''#####';;;;;;#''#
   #''''''''''''''''''######';;;;;;#'#
   #''''''''''''''''''#######';;;;;;##
   #''''''''''''''''''########';;;;;;#
   #''''''''''''++####+;#######';;;;;;#
   #+####':,`             ,#####';;;;;;'
                              +##'''''+.
   ___      _          ___       _ _     _
  / __\__ _| | _____  / __\_   _(_) | __| |
 / /  / _` | |/ / _ \/__\// | | | | |/ _` |
/ /___ (_| |   <  __/ \/  \ |_| | | | (_| |
\____/\__,_|_|\_\___\_____/\__,_|_|_|\__,_|

                             Version 0.23.0+Branch.main.Sha.67afe72f1c21a8a3cfd96d3969fb2591d62f37ff

========================================
Install-AngularCLI
========================================
Found Angular CLI at D:/home/site/repository/tools/ng/ng.cmd.

========================================
Clean
========================================

========================================
Install
========================================
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@^1.0.0 (node_modules\chokidar\node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.1.3: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"ia32"})
npm WARN codelyzer@3.2.2 requires a peer of @angular/compiler@^2.3.1 || >=4.0.0-beta <5.0.0 but none was installed.
npm WARN codelyzer@3.2.2 requires a peer of @angular/core@^2.3.1 || >=4.0.0-beta <5.0.0 but none was installed.

========================================
Build
========================================
Date: 2017-11-17T10:36:45.847Z
Hash: 3b11c732f8aa65f3a08c
Time: 8815ms
chunk {inline} inline.bundle.js, inline.bundle.js.map (inline) 5.83 kB [entry] [rendered]
chunk {main} main.bundle.js, main.bundle.js.map (main) 7.79 kB [initial] [rendered]
chunk {polyfills} polyfills.bundle.js, polyfills.bundle.js.map (polyfills) 200 kB [initial] [rendered]
chunk {styles} styles.bundle.js, styles.bundle.js.map (styles) 11.3 kB [initial] [rendered]
chunk {vendor} vendor.bundle.js, vendor.bundle.js.map (vendor) 2.29 MB [initial] [rendered]

========================================
Publish
========================================
KuduSync.NET from: 'D:\home\site\repository\output' to: 'D:\home\site\wwwroot'
Copying file: 'favicon.ico'
Copying file: 'index.html'
Copying file: 'inline.bundle.js'
Copying file: 'inline.bundle.js.map'
Copying file: 'main.bundle.js'
Copying file: 'main.bundle.js.map'
Copying file: 'polyfills.bundle.js'
Copying file: 'polyfills.bundle.js.map'
Copying file: 'styles.bundle.js'
Copying file: 'styles.bundle.js.map'
Copying file: 'vendor.bundle.js'
Copying file: 'vendor.bundle.js.map'
Time 444

Task                          Duration
--------------------------------------------------
Install-AngularCLI            00:00:00.0491433
Clean                         00:00:00.0782836
Install                       00:00:35.4828120
Build                         00:01:12.5709830
Publish                       00:00:00.8032134
--------------------------------------------------
Total:                        00:01:48.9844353
</code>```

In the last comment you write that you want to deploy using Octopus deploy, that would basically mean adding 2 new tasks to just like the kudu publish execute post build.

Package up the artifact

Push to Octopus server

For this Cake has the OctoPack and OctoPush aliases.

These aliases require the octo.exe tool, which can be fetch using the tool directive like this

```<code>#tool nuget:?package=OctopusTools&version=4.25.0
</code>```

A pack task could look something like this

```<code>    DirectoryPath   nugetPath= MakeAbsolute(Directory("./nuget"));
Task("Pack")
    .IsDependentOn("Build")
    .Does( ()=> {
    OctoPack(
        "PoCApp",
        new OctopusPackSettings {
            BasePath = outputPath,
            OutFolder = nugetPath,
            Format = OctopusPackFormat.Zip
        }
    );
});
</code>```

Once you packaged your app and pushed package to our octopus server, then you can use their built-in  deploy to Azure web app functionality, there's a good guide for that at
https://octopus.com/docs/deploying-applications/deploying-to-azure/deploying-a-package-to-an-azure-web-app

Some of the above code is available in the below repo
https://github.com/azurevoodoo/NGAppDeployedWithKuduPoC

Body:
So building a plain vanilla app with the Angular CLI would look something like this

string          target      = Argument("target", "Build");
FilePath        ngPath      = Context.Tools.Resolve("ng.cmd");
FilePath        npmPath     = Context.Tools.Resolve("npm.cmd");
DirectoryPath   outputPath  = MakeAbsolute(Directory("./output"));

Action<FilePath, ProcessArgumentBuilder> Cmd => (path, args) => {
    var result = StartProcess(
        path,
        new ProcessSettings {
            Arguments = args
        });

    if(0 != result)
    {
        throw new Exception($"Failed to execute tool {path.GetFilename()} ({result})");
    }
};

Task("Install-AngularCLI")
    .Does(() => {
    if (ngPath != null && FileExists(ngPath))
    {
        Information("Found Angular CLI at {0}.", ngPath);
        return;
    }

    DirectoryPath ngDirectoryPath = MakeAbsolute(Directory("./Tools/ng"));

    EnsureDirectoryExists(ngDirectoryPath);

    Cmd(npmPath,
        new ProcessArgumentBuilder()
                .Append("install")
                .Append("--prefix")
                .AppendQuoted(ngDirectoryPath.FullPath)
                .Append("@angular/cli")
    );
    ngPath = Context.Tools.Resolve("ng.cmd");
});

Task("Clean")
    .Does( ()=> {
        CleanDirectory(outputPath);
});

Task("Install")
    .IsDependentOn("Clean")
    .Does( ()=> {
    Cmd(npmPath,
        new ProcessArgumentBuilder()
            .Append("install")
    );
});

Task("Build")
    .IsDependentOn("Install-AngularCLI")
    .IsDependentOn("Install")
    .Does( ()=> {
    Cmd(ngPath,
        new ProcessArgumentBuilder()
            .Append("build")
            .Append("--output-path")
            .AppendQuoted(outputPath.FullPath)
    );
});

RunTarget(target);

Which basically does

Install Angular CLI If not found

Install node modules

Build Angular app

If you want to run the build and publish on kudu you can use the Cake.Kudu addin and KuduSync tool, dependencies are declared by adding tool and addin pre-processor directives like this:

#tool nuget:?package=KuduSync.NET&version=1.3.1
#addin nuget:?package=Cake.Kudu&version=0.6.0

And the publish task would look something like this

Task("Publish")
    .IsDependentOn("Build")
    .Does( ()=> {
      Kudu.Sync(outputPath);
});

For kudu to know it should use a custom deployment script you need to add a .deployment file telling it do so, which could look something like this:

[config]
command = deploy.cmd

And a custom boostrapper to install Cake i the kudu environment which could look something like this:

@ECHO OFF
REM SET Cake
SET CAKE_VERSION=0.23.0
SET CAKE_FOLDER=Cake.%CAKE_VERSION%
SET PATH=%~dp0\Tools;%PATH%

REM Cleanup any old Cake versions
FOR /f "delims=" %%c IN ('dir /AD /B "Tools\Cake*"') DO (
        IF NOT "%%c" == "%CAKE_FOLDER%" (RD /S /Q "Tools\%%c")
)

REM Install Dependencies
IF NOT EXIST "Tools" (md "Tools")
IF NOT EXIST "Tools\Addins" (md "Tools\Addins")
IF NOT EXIST "Tools\%CAKE_FOLDER%\Cake.exe" (
    echo Downloading Cake %CAKE_VERSION%
    nuget install Cake -Version %CAKE_VERSION% -OutputDirectory "Tools" -Source https://api.nuget.org/v3/index.json
    )

REM Execute deploy
Tools\%CAKE_FOLDER%\Cake.exe -version
Tools\%CAKE_FOLDER%\Cake.exe build.cake --Target="Publish"

Which basically just cleans up any old Cake versions and fetches 0.23.0 if not already installed.

The complete Cake script would look something like below

#tool nuget:?package=KuduSync.NET&version=1.3.1
#addin nuget:?package=Cake.Kudu&version=0.6.0
    string          target      = Argument("target", "Build");
    FilePath        ngPath      = Context.Tools.Resolve("ng.cmd");
    FilePath        npmPath     = Context.Tools.Resolve("npm.cmd");
    DirectoryPath   outputPath  = MakeAbsolute(Directory("./output"));

    Action<FilePath, ProcessArgumentBuilder> Cmd => (path, args) => {
        var result = StartProcess(
            path,
            new ProcessSettings {
                Arguments = args
            });

        if(0 != result)
        {
            throw new Exception($"Failed to execute tool {path.GetFilename()} ({result})");
        }
    };

    Task("Install-AngularCLI")
        .Does(() => {
        if (ngPath != null && FileExists(ngPath))
        {
            Information("Found Angular CLI at {0}.", ngPath);
            return;
        }

        DirectoryPath ngDirectoryPath = MakeAbsolute(Directory("./Tools/ng"));

        EnsureDirectoryExists(ngDirectoryPath);

        Cmd(npmPath,
            new ProcessArgumentBuilder()
                    .Append("install")
                    .Append("--prefix")
                    .AppendQuoted(ngDirectoryPath.FullPath)
                    .Append("@angular/cli")
        );
        ngPath = Context.Tools.Resolve("ng.cmd");
    });

    Task("Clean")
        .Does( ()=> {
            CleanDirectory(outputPath);
    });

    Task("Install")
        .IsDependentOn("Clean")
        .Does( ()=> {
        Cmd(npmPath,
            new ProcessArgumentBuilder()
                .Append("install")
        );
    });

    Task("Build")
        .IsDependentOn("Install-AngularCLI")
        .IsDependentOn("Install")
        .Does( ()=> {
        Cmd(ngPath,
            new ProcessArgumentBuilder()
                .Append("build")
                .Append("--output-path")
                .AppendQuoted(outputPath.FullPath)
        );
    });

Task("Publish")
    .IsDependentOn("Build")
    .Does( ()=> {
    Kudu.Sync(outputPath);
});

RunTarget(target);

And output on the Kudu build running on your Azure web site would look something like this

             +##   #;;'
             #;;#  .+;;;;+,
             '+;;#;,+';;;;;'#.
             ++'''';;;;;;;;;;# ;#;
            ##';;;;++'+#;;;;;'.   `#:
         ;#   '+'';;;;;;;;;'#`       #.
      `#,        .'++;;;;;':..........#
    '+      `.........';;;;':.........#
   #..................+;;;;;':........#
   #..................#';;;;;'+''''''.#
   #.......,:;''''''''##';;;;;'+'''''#,
   #''''''''''''''''''###';;;;;;+''''#
   #''''''''''''''''''####';;;;;;#'''#
   #''''''''''''''''''#####';;;;;;#''#
   #''''''''''''''''''######';;;;;;#'#
   #''''''''''''''''''#######';;;;;;##
   #''''''''''''''''''########';;;;;;#
   #''''''''''''++####+;#######';;;;;;#
   #+####':,`             ,#####';;;;;;'
                              +##'''''+.
   ___      _          ___       _ _     _
  / __\__ _| | _____  / __\_   _(_) | __| |
 / /  / _` | |/ / _ \/__\// | | | | |/ _` |
/ /___ (_| |   <  __/ \/  \ |_| | | | (_| |
\____/\__,_|_|\_\___\_____/\__,_|_|_|\__,_|

                             Version 0.23.0+Branch.main.Sha.67afe72f1c21a8a3cfd96d3969fb2591d62f37ff

========================================
Install-AngularCLI
========================================
Found Angular CLI at D:/home/site/repository/tools/ng/ng.cmd.

========================================
Clean
========================================

========================================
Install
========================================
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@^1.0.0 (node_modules\chokidar\node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.1.3: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"ia32"})
npm WARN codelyzer@3.2.2 requires a peer of @angular/compiler@^2.3.1 || >=4.0.0-beta <5.0.0 but none was installed.
npm WARN codelyzer@3.2.2 requires a peer of @angular/core@^2.3.1 || >=4.0.0-beta <5.0.0 but none was installed.

========================================
Build
========================================
Date: 2017-11-17T10:36:45.847Z
Hash: 3b11c732f8aa65f3a08c
Time: 8815ms
chunk {inline} inline.bundle.js, inline.bundle.js.map (inline) 5.83 kB [entry] [rendered]
chunk {main} main.bundle.js, main.bundle.js.map (main) 7.79 kB [initial] [rendered]
chunk {polyfills} polyfills.bundle.js, polyfills.bundle.js.map (polyfills) 200 kB [initial] [rendered]
chunk {styles} styles.bundle.js, styles.bundle.js.map (styles) 11.3 kB [initial] [rendered]
chunk {vendor} vendor.bundle.js, vendor.bundle.js.map (vendor) 2.29 MB [initial] [rendered]

========================================
Publish
========================================
KuduSync.NET from: 'D:\home\site\repository\output' to: 'D:\home\site\wwwroot'
Copying file: 'favicon.ico'
Copying file: 'index.html'
Copying file: 'inline.bundle.js'
Copying file: 'inline.bundle.js.map'
Copying file: 'main.bundle.js'
Copying file: 'main.bundle.js.map'
Copying file: 'polyfills.bundle.js'
Copying file: 'polyfills.bundle.js.map'
Copying file: 'styles.bundle.js'
Copying file: 'styles.bundle.js.map'
Copying file: 'vendor.bundle.js'
Copying file: 'vendor.bundle.js.map'
Time 444

Task                          Duration
--------------------------------------------------
Install-AngularCLI            00:00:00.0491433
Clean                         00:00:00.0782836
Install                       00:00:35.4828120
Build                         00:01:12.5709830
Publish                       00:00:00.8032134
--------------------------------------------------
Total:                        00:01:48.9844353

In the last comment you write that you want to deploy using Octopus deploy, that would basically mean adding 2 new tasks to just like the kudu publish execute post build.

Package up the artifact

Push to Octopus server

For this Cake has the OctoPack and OctoPush aliases.

These aliases require the octo.exe tool, which can be fetch using the tool directive like this

#tool nuget:?package=OctopusTools&version=4.25.0

A pack task could look something like this

    DirectoryPath   nugetPath= MakeAbsolute(Directory("./nuget"));
Task("Pack")
    .IsDependentOn("Build")
    .Does( ()=> {
    OctoPack(
        "PoCApp",
        new OctopusPackSettings {
            BasePath = outputPath,
            OutFolder = nugetPath,
            Format = OctopusPackFormat.Zip
        }
    );
});

Once you packaged your app and pushed package to our octopus server, then you can use their built-in  deploy to Azure web app functionality, there's a good guide for that at
https://octopus.com/docs/deploying-applications/deploying-to-azure/deploying-a-package-to-an-azure-web-app

Some of the above code is available in the below repo
https://github.com/azurevoodoo/NGAppDeployedWithKuduPoC


问:
Why is [0] === [0] false
If debugging shows that a variable is 0, then I think that I should be able to catch it with either ==='0' or ===0 but that didn't work. I had to use only == instead, then it worked:

```<code>var offset = 0;
alert("## DEBUG non_sortable_columns " + non_sortable_columns)
if (non_sortable_columns == '0' || non_sortable_columns == 0) {
    offset = 1;
}
</code>```

I first tried this but it didn't work:

```<code>var offset = 0;
alert("## DEBUG non_sortable_columns " + non_sortable_columns)
if (non_sortable_columns === '0' || non_sortable_columns === 0) {
    offset = 1;
}
</code>```

The value was [0] and [0] === [0] is false. How can it be false?

答:
The value of non_sortable_columns might be false.
The basic difference between the === and == is that the 3 equals to comparison operator also checks the type of the variable, that means: '0' which is a string would not be equal to: 0 which is a number.

In your case the variable non_sortable_columns value might be false which means 0in JavaScript therefore the value of the == finds it same as it doesn't check the type but === fails as it checks the type of it.

For better understanding refer to: Which equals operator (== vs ===) should be used in JavaScript comparisons?

Title: Why is [0] === [0] false

Body:
If debugging shows that a variable is 0, then I think that I should be able to catch it with either ==='0' or ===0 but that didn't work. I had to use only == instead, then it worked:

var offset = 0;
alert("## DEBUG non_sortable_columns " + non_sortable_columns)
if (non_sortable_columns == '0' || non_sortable_columns == 0) {
    offset = 1;
}

I first tried this but it didn't work:

var offset = 0;
alert("## DEBUG non_sortable_columns " + non_sortable_columns)
if (non_sortable_columns === '0' || non_sortable_columns === 0) {
    offset = 1;
}

The value was [0] and [0] === [0] is false. How can it be false?


问:
snakemake: handle rule connect on wrong mode on another rule
I need to run two rules (gatk_Mutect2 and gatk_IndelRealigner) in the same snakefile.

If put these rules in different snakefiles, I can run them without error.

I use two input functions (get_files_somatic and get_files). Both use the case name as dictionary key. (Each case have a normal).
When I put these rules in the same snakefile, snakemake tries to find the id of the normal on the input of gatk_IndelRealigner.

My question is: How can  manage the ambiguity of two rules? I mean I want snakemake not try to connect these two rules.

def get_files_somatic(wildcards):
    case = wildcards.case
    control = aCondition[case][0]
    return ["{}.sorted.dup.reca.cleaned.bam".format(case),"{}.sorted.dup.reca.cleaned.bam".format(control)]

rule all:
    input: expand("{sample}.sorted.dup.reca.cleaned.bam",sample=create_tumor()),
           expand("Results/vcf/{case}.vcf",case=create_tumor()),

include_prefix="rules"

include:
    include_prefix + "/gatk2.rules"
include:
    include_prefix + "/mutec2.rules"

rule gatk_Mutect2:
    input: get_files_somatic,
    output: "Results/vcf/{case}.vcf",
    params:
    log: "logs/{case}.mutect2.log"
    threads: 8
    shell:

rule gatk_IndelRealigner:
    input:
        get_files,
    output:
       "{case}.sorted.dup.reca.cleaned.bam",
       "{case}.sorted.dup.reca.cleaned.bai",
    params:
    log:
        "mapped_reads/merged_samples/logs/{case}_indel_realign_2.log"
    threads: 8
    shell:

def get_files(wildcards):
    case = wildcards.case
    control = aCondition[case][0]
    wildcards.control = control
    return ["mapped_reads/merged_samples/{}.sorted.dup.reca.bam".format(case), "mapped_reads/merged_samples/{}.sorted.dup.reca.bam".format(control),"mapped_reads/merged_samples/operation/{}_{}.realign.intervals".format(case,control)]
```

答:
I'm not sure I really understood your problem. For instance, I don't get what you mean by "Each case have a normal".

But I can see that the output of gatk_IndelRealigner ("{case}.sorted.dup.reca.cleaned.bam") happens to be the same file name as one of the results of get_files_somatic ("{}.sorted.dup.reca.cleaned.bam".format(case), where case is wildcards.case).

That is the reason why gatk_Mutect2 gets "connected" to gatk_IndelRealigner.

It is the essence of snakemake to connect rules based on matching file names between their input and output.

If you do not want to have these two rules linked, you need to have different file names.


问:
how to track from where visitor come to my site php
I want to track the site URL from where user reached my site.

From where he came i.el, Google, GMail, Facebook, etc.

I tried $_SERVER['HTTP_REFERER'] but it does not contain anything when user click on my site link from any external site but resides the value when I visit among my site pages and this is also not trusted.

So, What I can do from here?

Is there any other way to track the external URL through PHP?

Any idea?

EDIT: Now HTTP_REFERER is able to get the url from most of sites but not able to get the url if user came through Gmail and AOL. What could be the causes?

答:
HTTP_REFERER is the only way to get any information about previous site.

And that is also up to the broser if it supplies that information, most do as default.

Its a header that is set by the browser in the request to your server, if it is not present, then you will never know where the user came from.

If the browser is sending and you still to not get anything on the server check if you have any code that interferes with the $_SERVER variable.

Try this URL, its a google search result that goes to a page that just dumps the HTTP_REFERER.

As the pages indicates, if the box lists (none), then your browser is not sending HTTP_REFERER but if you get a result then the problem is in sour server.

http://www.google.com/url?sa=t&source=web&cd=1&sqi=2&ved=0CBIQFjAA&url=http%3A%2F%2Fkarmak.org%2F2004%2Freftest%2Ftest&rct=j&q=http_referer%20test&ei=cNQ2TdGYGsmUOp_ExPoD&usg=AFQjCNFVSmYmQBUcL2l3_ZpmZzVWZztjWg&cad=rja

You can compare it to when you load the page withour google to redirect you:

http://karmak.org/2004/reftest/test

Here is their own start page with link:

http://karmak.org/2004/reftest/


问:
How can I automatically register all my fluent validators with Unity?
Right now I've got my validators hooked up and building in my app, but every time we add a new validator we need to manually go into our Unity configuration and register the type. I'd like to do this automatically, much like this blog post describes doing with StructureMap, only for Unity instead.

Right now I've got something like this:

```<code>    // in global.asax.cs
    protected void Application_Start(Object sender, EventArgs e)
    {
        // some irrelevant registrations (area registrations, route config, etc)

        var container = new UnityContainer();
        UnityConfig.RegisterComponents(container);
        FluentValidationModelValidatorProvider.Configure(c => c.ValidatorFactory = new UnityValidatorFactory(container));
    }

public class UnityValidatorFactory : ValidatorFactoryBase
{
    private readonly IUnityContainer container;

    public UnityValidatorFactory(IUnityContainer container)
    {
        this.container = container;
    }

    public override IValidator CreateInstance(Type validatorType)
    {
        if (container.IsRegistered(validatorType))
        {
            return container.Resolve(validatorType) as IValidator;
        }

        return null;
    }
}

public static class UnityConfig
{
    public static void RegisterComponents(IUnityContainer container)
    {
        container.RegisterTypes(
            AllClasses.FromAssemblies(
                Assembly.GetAssembly(typeof (UnityConfig)),
            WithMappings.FromMatchingInterface, WithName.Default);

        RegisterValidators(container);

        DependencyResolver.SetResolver(new UnityDependencyResolver(container));
    }

    private static void RegisterValidators(IUnityContainer container)
    {
        container.RegisterType<IValidator<MyFirstViewModel>, MyFirstViewModelValidator>();
        container.RegisterType<IValidator<MySecondViewModel>, MySecondViewModelValidator>();
    }
 }
</code>```

What I have is working, but I have to keep adding registrations to RegisterValidators() every time a new validator is created. Is there a way I can set this up to automatically detect and register all validators?

答:
You can let FV setup do the job for you, please refer to 1st comment here for more details from the contributers</p>

```<code>public IServiceProvider ConfigureServices( IServiceCollection services )
        {
            services.AddAuthorization(options =>...);
            services.AddMvc()
                    .AddFluentValidation( o =>
                    {
                        o.RegisterValidatorsFromAssemblyContaining<Startup>();
                    } );
</code>```

Body:
Right now I've got my validators hooked up and building in my app, but every time we add a new validator we need to manually go into our Unity configuration and register the type. I'd like to do this automatically, much like this blog post describes doing with StructureMap, only for Unity instead.

Right now I've got something like this:

    // in global.asax.cs
    protected void Application_Start(Object sender, EventArgs e)
    {
        // some irrelevant registrations (area registrations, route config, etc)

        var container = new UnityContainer();
        UnityConfig.RegisterComponents(container);
        FluentValidationModelValidatorProvider.Configure(c => c.ValidatorFactory = new UnityValidatorFactory(container));
    }

public class UnityValidatorFactory : ValidatorFactoryBase
{
    private readonly IUnityContainer container;

    public UnityValidatorFactory(IUnityContainer container)
    {
        this.container = container;
    }

    public override IValidator CreateInstance(Type validatorType)
    {
        if (container.IsRegistered(validatorType))
        {
            return container.Resolve(validatorType) as IValidator;
        }

        return null;
    }
}

public static class UnityConfig
{
    public static void RegisterComponents(IUnityContainer container)
    {
        container.RegisterTypes(
            AllClasses.FromAssemblies(
                Assembly.GetAssembly(typeof (UnityConfig)),
            WithMappings.FromMatchingInterface, WithName.Default);

        RegisterValidators(container);

        DependencyResolver.SetResolver(new UnityDependencyResolver(container));
    }

    private static void RegisterValidators(IUnityContainer container)
    {
        container.RegisterType<IValidator<MyFirstViewModel>, MyFirstViewModelValidator>();
        container.RegisterType<IValidator<MySecondViewModel>, MySecondViewModelValidator>();
    }
 }

What I have is working, but I have to keep adding registrations to RegisterValidators() every time a new validator is created. Is there a way I can set this up to automatically detect and register all validators?

Body:
You can let FV setup do the job for you, please refer to 1st comment here for more details from the contributers

public IServiceProvider ConfigureServices( IServiceCollection services )
        {
            services.AddAuthorization(options =>...);
            services.AddMvc()
                    .AddFluentValidation( o =>
                    {
                        o.RegisterValidatorsFromAssemblyContaining<Startup>();
                    } );


问:
Java code to ruby
I want to convert this to ruby syntax but i can not understand the method being used to encode in the following code.

```<code>String orderAmount = "250.00";
String mobile = " 7687675645";
String email = "a@abc.com"  ;
String data=mobile+email+orderAmount+"INR";
javax.crypto.Mac mac = javax.crypto.Mac.getInstance("HmacSHA1");
mac.init(new javax.crypto.spec.SecretKeySpec(secret_key.getBytes(), "HmacSHA1"));
byte[] hexBytes = new org.apache.commons.codec.binary.Hex().encode(mac.doFinal(data.getBytes()));
String signature = new String(hexBytes, "UTF-8");
</code>```

Help will be really appreciated.

答:
Try this:</p>

```<code>require 'openssl'

secret_key = 'place_your_secret_key_here'
orderAmount = '250.00'
mobile = ' 7687675645'
email = 'a@abc.com'
data = mobile + email + orderAmount + 'INR'

signature = OpenSSL::HMAC.hexdigest('SHA1', secret_key, data)
</code>```

Title: Java code to ruby

Body:
I want to convert this to ruby syntax but i can not understand the method being used to encode in the following code.

String orderAmount = "250.00";
String mobile = " 7687675645";
String email = "a@abc.com"  ;
String data=mobile+email+orderAmount+"INR";
javax.crypto.Mac mac = javax.crypto.Mac.getInstance("HmacSHA1");
mac.init(new javax.crypto.spec.SecretKeySpec(secret_key.getBytes(), "HmacSHA1"));
byte[] hexBytes = new org.apache.commons.codec.binary.Hex().encode(mac.doFinal(data.getBytes()));
String signature = new String(hexBytes, "UTF-8");

Help will be really appreciated.

Body:
Try this:

require 'openssl'

secret_key = 'place_your_secret_key_here'
orderAmount = '250.00'
mobile = ' 7687675645'
email = 'a@abc.com'
data = mobile + email + orderAmount + 'INR'

signature = OpenSSL::HMAC.hexdigest('SHA1', secret_key, data)


问:
Install numpy latest package using apt-get
I used below query to install numpy package. But it installed 1.11.0 version. How to install the most recent version.</p>

```<code> sudo apt-get install python-numpy
</code>```

答:
```<code>sudo easy_install --upgrade numpy
</code>```

<p>Will simply do it fo you </p>

Body:
I used below query to install numpy package. But it installed 1.11.0 version. How to install the most recent version.

 sudo apt-get install python-numpy

Body:
sudo easy_install --upgrade numpy

Will simply do it fo you


问:
Can _lodash test an array to check if an array element has a field with a certain value?
I have a variable selectedSubTopicId and I have an array of subTopic objects: objectiveDetail.subTopics[].  Each subTopic object has a field subTopicId

I would like to use this to enable or disable and Add topic button. Can I use lodash in the ng-disabled to test this array and report true if any subTopic object element of the array has a subTopicId that is equal to the selectedSubTopicId.

Here's a sample of the data that's in objectiveDetail. In this case there's just one element in the subTopics array.

```<code>{"objectiveDetailId":285,
 "objectiveId":29,
 "number":1,
 "text":"x",
 "subTopics":[{"subTopicId":1,
               "number":1}]
}
</code>```

Here is the code in my Angular Controller suggested by thefourtheye:

```<code>    $scope.checkDuplicateSubTopicId = function (objectiveDetail, sSubTopic) {
        if (_.some(objectiveDetail.subTopics, function(currentTopic) {
            return _.contains(currentTopic, selectedSubTopicId);
        })) {
            return true;
        } else {
            return false;
        }
    }
</code>```

My button with the click function not shown looks like this:

```<code>   <button data-ng-disabled="checkDuplicateSubTopicId(objectiveDetail, subTopicId)">
       Add Topic
   </button>
</code>```

The problem is that it's not quite working and the button does not show disabled.

答:
This one worked for me very well: It helps where you have many columns of data to check against, say title, category and description.

To check if stringTosearch is found in any of those columns of data, you can do:

```<code>let searchResults = _.filter(yourArrayHere, (item) => {
            return item.title.indexOf(stringTosearch) > -1
                    || item.category.indexOf(stringTosearch) > -1
                    || item.description.indexOf(stringTosearch) > -1;
        });
</code>```

It will return any object of your array that has stringTosearch in any of the columns you specified.

Body:
I have a variable selectedSubTopicId and I have an array of subTopic objects: objectiveDetail.subTopics[].  Each subTopic object has a field subTopicId

I would like to use this to enable or disable and Add topic button. Can I use lodash in the ng-disabled to test this array and report true if any subTopic object element of the array has a subTopicId that is equal to the selectedSubTopicId.

Here's a sample of the data that's in objectiveDetail. In this case there's just one element in the subTopics array.

{"objectiveDetailId":285,
 "objectiveId":29,
 "number":1,
 "text":"x",
 "subTopics":[{"subTopicId":1,
               "number":1}]
}

Here is the code in my Angular Controller suggested by thefourtheye:

    $scope.checkDuplicateSubTopicId = function (objectiveDetail, sSubTopic) {
        if (_.some(objectiveDetail.subTopics, function(currentTopic) {
            return _.contains(currentTopic, selectedSubTopicId);
        })) {
            return true;
        } else {
            return false;
        }
    }

My button with the click function not shown looks like this:

   <button data-ng-disabled="checkDuplicateSubTopicId(objectiveDetail, subTopicId)">
       Add Topic
   </button>

The problem is that it's not quite working and the button does not show disabled.

Body:
This one worked for me very well: It helps where you have many columns of data to check against, say title, category and description.

To check if stringTosearch is found in any of those columns of data, you can do:

let searchResults = _.filter(yourArrayHere, (item) => {
            return item.title.indexOf(stringTosearch) > -1
                    || item.category.indexOf(stringTosearch) > -1
                    || item.description.indexOf(stringTosearch) > -1;
        });

It will return any object of your array that has stringTosearch in any of the columns you specified.


问:
LOOPBACK Modify another model inside a hook
I want to insert new data in Event model when the property "code" in Transaction model is equal to 3</p>

```<code> module.exports = function(Transaction) {
    Transaction.observe('before save', function(ctx, next) {
        if(ctx.data.code == 3){
          //How to access and insert data in Event model ?
        }
    });
};
</code>```

答:
this works for me. it's just like what @Sunil Lama said but I use loopback.getModel additionally

server.js

```<code>const loopback = require('loopback');
const ModelInst = require('./model-instnace');
boot(app, __dirname, function (err) {
   if (err) throw err;
   ModelInst.event = (loopback.getModel('event'));
};
</code>```

model-instance.js

```<code>const ModelInst = {
    ...
    event:null
    ...
}
</code>```

model.js

```<code>const models = require('model-instnace Path');
module.exports = function(Transaction) {
    Transaction.observe('before save', function(ctx, next) {
        if(ctx.data.code == 3){
            models.event.insertNewDate('blah');
        }
    });
};
</code>```

Body:
I want to insert new data in Event model when the property "code" in Transaction model is equal to 3

 module.exports = function(Transaction) {
    Transaction.observe('before save', function(ctx, next) {
        if(ctx.data.code == 3){
          //How to access and insert data in Event model ?
        }
    });
};

Body:
this works for me. it's just like what @Sunil Lama said but I use loopback.getModel additionally

server.js

const loopback = require('loopback');
const ModelInst = require('./model-instnace');
boot(app, __dirname, function (err) {
   if (err) throw err;
   ModelInst.event = (loopback.getModel('event'));
};

model-instance.js

const ModelInst = {
    ...
    event:null
    ...
}

model.js

const models = require('model-instnace Path');
module.exports = function(Transaction) {
    Transaction.observe('before save', function(ctx, next) {
        if(ctx.data.code == 3){
            models.event.insertNewDate('blah');
        }
    });
};


问:
Change to AMP page based on screen size
I'm looking for a super easy way to make my normal html page, change to my AMP page based on a smaller screen size. Can this be done via the header?</p>

答:
I use following and it works perfectly. Doesn't change to AMP on tablets which is fine as my site is responsive.</p>

```<code><script type="text/javascript">
<!--
if (screen.width <= 699) {
document.location = "https://example.com/amp";
}
//-->
</script>
</code>```

Title: Change to AMP page based on screen size

Body:
I use following and it works perfectly. Doesn't change to AMP on tablets which is fine as my site is responsive.

<script type="text/javascript">
<!--
if (screen.width <= 699) {
document.location = "https://example.com/amp";
}
//-->
</script>


问:
CSS safe area attributes doesn't work on iPhone X
In my case I'm running a web app on iPhone X, I'm trying to add a padding on top to push my body to the safe area using the safe area css attributes of Webkit padding-top: constant(safe-area-inset-top); and padding-top: env(safe-area-inset-top);. However the web view doesn't evaluate correctly these attributes and it's always set to 0.
What should I dod to make it work !
code :

```<code>body {
padding-top: 44px;
    padding-top: constant(safe-area-inset-top);
    padding-top: env(safe-area-inset-top);
}
</code>```

答:
without the line
padding-top: env(safe-area-inset-top);
it should work</p>

Body:
In my case I'm running a web app on iPhone X, I'm trying to add a padding on top to push my body to the safe area using the safe area css attributes of Webkit padding-top: constant(safe-area-inset-top); and padding-top: env(safe-area-inset-top);. However the web view doesn't evaluate correctly these attributes and it's always set to 0.
What should I dod to make it work !
code :

body {
padding-top: 44px;
    padding-top: constant(safe-area-inset-top);
    padding-top: env(safe-area-inset-top);
}


问:
Conditionally create an object in c++
I am writing a program that has the option to visualize the output of an algorithm I am working on - this is done by changing a const bool VISUALIZE_OUTPUT variable defined in a header file. In the main file, I want to have this kind of pattern:

```<code>if(VISUALIZE_OUTPUT) {
    VisualizerObject vis_object;
}
...
if(VISUALIZE_OUTPUT) {
    vis_object.initscene(objects_here);
}
...
if(VISUALIZE_OUTPUT) {
    vis_object.drawScene(objects_here);
}
</code>```

However, this clearly won't compile since vis_object goes out of scope. I don't want to declare the object before the condition since it is a big object and it needs to available for multiple points in the code (I can't just have one conditional statement where everything is done).

What is the preferred way of doing this?

Declare the object on the heap and refer to it by using a pointer (or
unique_ptr)?

Declare the object on the heap and make a reference to it
since it won't ever change?

Some other alternative?

答:
A reference will not be useable here, because at declaration it should refere to an already existing object, and live in a scope englobing all your  if(VISUALIZE_OUTPUT). Long story short, the object will have to be created unconditionally.

So IMHO a simple way would be to create it on the heap and use it through a pointer - do not forget do delete it when done. The good point is that the pointer could be initialized to nullptr, and so it could be unconditionnaly deleted.

But I think that the best way would be to encapsulate everything in an object created in highest scope. This object would then contain methods to create, use internally and finally destroy the actual vis_object. That way, if you do not need it, nothing will be actually instanciated, but the main procedure will not be cluttered with raw pointer processing.

Title: Conditionally create an object in c++

Body:
I am writing a program that has the option to visualize the output of an algorithm I am working on - this is done by changing a const bool VISUALIZE_OUTPUT variable defined in a header file. In the main file, I want to have this kind of pattern:

if(VISUALIZE_OUTPUT) {
    VisualizerObject vis_object;
}
...
if(VISUALIZE_OUTPUT) {
    vis_object.initscene(objects_here);
}
...
if(VISUALIZE_OUTPUT) {
    vis_object.drawScene(objects_here);
}

However, this clearly won't compile since vis_object goes out of scope. I don't want to declare the object before the condition since it is a big object and it needs to available for multiple points in the code (I can't just have one conditional statement where everything is done).

What is the preferred way of doing this?

Declare the object on the heap and refer to it by using a pointer (or
unique_ptr)?

Declare the object on the heap and make a reference to it
since it won't ever change?

Some other alternative?


问:
Why does the 404 page not work in certain cases? (IIS, Classic ASP)
Explanation

In production and locally, the 404 page for my site works fine for the most part. A URL such as http://localhost:43424/gibberish_r3hjjnwef will return the well designed 404 HTML page that is in the website folder, and pointed to by IIS.

However when I change the this URL to http://localhost:43424/gibberish_r3hjjnwef... it gives the following "hard" error, whilst still claiming to be a 404.

```<code>Server Error in '/' Application.

The resource cannot be found.

Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable.  Please review the following URL and make sure that it is spelled correctly.

Requested URL: /gibberish_r3hjjnwef...

Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.7.2110.0
</code>```

I'd rather it still gave the 404 HTML page.

I thought maybe it was an outright invalid URL, but both http://www.bbc.co.uk/news/fdisdhfdu and http://www.bbc.co.uk/news/fdisdhfdu... give the BBC's nice 404 page.

Question

Is there anything I can do to improve this?

Relevant Information (happy to provide more if necessary)

Microsoft .NET Framework Version: 4.0.30319

ASP.NET Version: 4.7.2110.0

Language/Framework:C#/Classic .ASP

答:
I'm not sure whether this is what you are referring to, but maybe try this out:

Go to IIS Manager -> Site -> IIS Error pages. On the right hand panel, there's a setting "Edit Feature Settings...".

The options there mean:

Custom error pages: Use the 'IIS error pages' as fallback for all failed requests (e.g. your 404 page set up the list behind)

Detailed error pages: In case of an Asp.Net error, shows the 'Asp.Net error page' ("Server Error in '/' Application." etc.)

Detailed errors for local requests etc.: Show the 'IIS error page' for remote requests, for local requests show the 'Asp.net error page' ("Server error in '/' etc.)

This is in place to effectively hide the detailed Asp.net error page (with the stack trace etc.) from external callers as you may not want to give them the details of your application. This is the default setting, where you should only see the 'Asp.net error page' when you call the invalid URL on 'localhost', but the 'IIS error page' (404) when you call the page from a different computer.

So, what you may want to try is to select the "Custom error pages" option ('IIS error pages' for all failed requests).

Body:
Explanation

In production and locally, the 404 page for my site works fine for the most part. A URL such as http://localhost:43424/gibberish_r3hjjnwef will return the well designed 404 HTML page that is in the website folder, and pointed to by IIS.

However when I change the this URL to http://localhost:43424/gibberish_r3hjjnwef... it gives the following "hard" error, whilst still claiming to be a 404.

Server Error in '/' Application.

The resource cannot be found.

Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable.  Please review the following URL and make sure that it is spelled correctly.

Requested URL: /gibberish_r3hjjnwef...

Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.7.2110.0

I'd rather it still gave the 404 HTML page.

I thought maybe it was an outright invalid URL, but both http://www.bbc.co.uk/news/fdisdhfdu and http://www.bbc.co.uk/news/fdisdhfdu... give the BBC's nice 404 page.

Question

Is there anything I can do to improve this?

Relevant Information (happy to provide more if necessary)

Microsoft .NET Framework Version: 4.0.30319

ASP.NET Version: 4.7.2110.0

Language/Framework:C#/Classic .ASP


问:
How to increase font size in javascript?
I'm trying to increase the font size for the title of a GUI that was made using javascript. I'm a java script noob but i just wanted to make a few adjustments to the pre-made GUI in a short amount of time. Any help would be appreciated.

```<code>templateObj.$.ti_widget_plot1.layout.title = 'X-Y Scatter Plot';
</code>```

The code above is what allows me access the title and change the name.

Thanks

答:
Since you are a starter, I am spelling it out for you. Hope this helps;

Note: For styling issues (like yours), please glance through css first before taking up any html related assignment;

#div1 {
  font-size:100%
}
#div2 {
  font-size:200%
}
#div3 {
  font-size:300%
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="div1">this is normal text</div>
<div id="div2">this is BIGG</div>
<div id="div3">this is even more BIGGGGGG</div></code>```

Body:
I'm trying to increase the font size for the title of a GUI that was made using javascript. I'm a java script noob but i just wanted to make a few adjustments to the pre-made GUI in a short amount of time. Any help would be appreciated.

templateObj.$.ti_widget_plot1.layout.title = 'X-Y Scatter Plot';

The code above is what allows me access the title and change the name.

Thanks

Body:
Since you are a starter, I am spelling it out for you. Hope this helps;

Note: For styling issues (like yours), please glance through css first before taking up any html related assignment;

#div1 {
  font-size:100%
}
#div2 {
  font-size:200%
}
#div3 {
  font-size:300%
}

<div id="div1">this is normal text</div>
<div id="div2">this is BIGG</div>
<div id="div3">this is even more BIGGGGGG</div>


问:
A-FRAME + mobile phone) how touch move up or down by finger gesture
my product is below (Please see by mobile phone)

https://pano-mixer360.com/viewer/sphere/11/43

in the case of move to left or right,
touch moving by finger gesture is working well.

but,
in the case of move to up or down,
touch moving by finger gesture is not working! It's problem.

what should I do?

using

```
A-Frame0.5.0
Safari iOS 10
```

my code

```<code><a-scene>
  <a-entity position="0 0 0">
    <a-entity>
      <a-entity camera="userHeight: 1.6" look-controls>
      <a-entity id="myCursor" cursor="fuse:true maxDistance:30; timeout:500;" scale="0.05 0.05 0.05" position="0 0 -1" geometry="primitive: ring" material="color: #00ff00; shader: flat; opacity:0.5">
        <a-animation begin="cursor-fusing" easing="ease-in" attribute="scale" fill="none" from="0.3 0.3 0.3" to="0.01 0.01 0.01"></a-animation>
      </a-entity>
    </a-entity>
  </a-entity>
  <a-sky src="test.jpeg" rotation="0 0 0"></a-sky>
</a-scene>
</code>```

by the way,
I tried clone look-controls.js

https://github.com/aframevr/aframe/blob/master/src/components/look-controls.js

and line #L173 replace to

```<code>x: radToDeg(hmdEuler.x) + radToDeg(yawObject.rotation.x),
</code>```

as using yawObject.

but It's now working.
because touch moving listener(#L301-L313) is no set rotaion.x!

perhaps,
I should calculation the rotation.x

```<code>yawObject.rotation.x = ????
</code>```

but I don't understand how to calculation.

Please help me

答:
The problem is about pitchObject not yawObject,place the code into onTouchMove function in your clone of look-controls.js

```<code>var deltaX = 2 * Math.PI * (evt.touches[0].pageY - this.touchStart.y) / canvas.clientHeight;
this.pitchObject.rotation.x -= deltaX * 0.5;
</code>```

Body:
my product is below (Please see by mobile phone)

https://pano-mixer360.com/viewer/sphere/11/43

in the case of move to left or right,
touch moving by finger gesture is working well.

but,
in the case of move to up or down,
touch moving by finger gesture is not working! It's problem.

what should I do?

using

A-Frame0.5.0
Safari iOS 10

my code

by the way,
I tried clone look-controls.js

https://github.com/aframevr/aframe/blob/master/src/components/look-controls.js

and line #L173 replace to

x: radToDeg(hmdEuler.x) + radToDeg(yawObject.rotation.x),

as using yawObject.

but It's now working.
because touch moving listener(#L301-L313) is no set rotaion.x!

perhaps,
I should calculation the rotation.x

yawObject.rotation.x = ????

but I don't understand how to calculation.

Please help me

Body:
The problem is about pitchObject not yawObject,place the code into onTouchMove function in your clone of look-controls.js

var deltaX = 2 * Math.PI * (evt.touches[0].pageY - this.touchStart.y) / canvas.clientHeight;
this.pitchObject.rotation.x -= deltaX * 0.5;


问:
Get specific CSS Hover properties
How can I see the differences in the style of an element with and without the hover property.

I want a full list of CSS styles that only happen when the specific element is hovered (or that has the :hover state).

答: Is there a reason you can't just look in the CSS file and find the selector:hover declaration?

Title: Get specific CSS Hover properties


问:
Using destruct on pattern match expression with 'convoy pattern'
For the purpose of this question, suppose I have:

```<code>Parameter eq_bool : forall (A:Type), A -> A -> bool.

Arguments eq_bool {A} _ _.

Axiom eq_bool_correct : forall (A:Type) (x y:A),
    eq_bool x y = true -> x = y.

Axiom eq_bool_correct' : forall (A:Type) (x y:A),
     x = y -> eq_bool x y = true.
</code>```

I have a function which given two valuesx y:A returns Some proof of x = y whenever x = y and None otherwise. This function is implemented with a pattern match on eq_bool x y to test for equality, and uses the convoy pattern as a trick to get access within your code to a proof of the equality corresponding to the branch of your match:

```<code>Definition test (A:Type) (x y:A) : option (x = y) :=
    match eq_bool x y as b return eq_bool x y = b -> option (x = y) with
    | true  => fun p => Some (eq_bool_correct A x y p)
    | false => fun _ => None
    end (eq_refl (eq_bool x y)).
</code>```

I am now attempting to prove a simple result about this function:

```<code>Theorem basic: forall (A:Type) (x y:A),
    x = y -> test A x y <> None.
Proof.
    intros A x y H. rewrite H. unfold test.

A : Type
x, y : A
H : x = y
============================
(if eq_bool y y as b return (eq_bool y y = b -> option (y = y))
 then fun p : eq_bool y y = true => Some (eq_bool_correct A y y p)
 else fun _ : eq_bool y y = false => None) eq_refl <> None
</code>```

At this point it feels I have to use destruct on eq_bool y y (possibly keeping equation):

```<code>destruct (eq_bool y y).

Error: Abstracting over the term "b" leads to a term
fun b0 : bool =>
(if b0 as b1 return (b0 = b1 -> option (y = y))
 then fun p : b0 = true => Some (eq_bool_correct A y y p)
 else fun _ : b0 = false => None) eq_refl <> None
which is ill-typed.
Reason is: Illegal application:
The term "eq_bool_correct" of type
 "forall (A : Type) (x y : A), eq_bool x y = true -> x = y"
cannot be applied to the terms
 "A" : "Type"
 "y" : "A"
 "y" : "A"
 "p" : "b0 = true"
The 4th term has type "b0 = true" which should be coercible to
 "eq_bool y y = true".
</code>```

I know I have to read CPDT (especially on convoy pattern) but I have a better learning experience with the Software Foundation book (which is suited for beginners): at my current level of skills, I cannot think of anything but destruct and was hoping someone could suggest a way to finish this proof.

答:
This is the typical case where careless abstraction makes terms ill-typed. In general, you want to use slightly different principles as to avoid these problems, matching on sumbool or reflect may provide you with better results.

In this particular case, in order for things to go through you first need to generalize the goal a bit (so it doesn't depend on eq_refl, which is a problem when matching as its typing rule is too strict) and then select the proper subterms. I use the ssreflect pattern language as it is far more convenient:

```<code>(* Do From Coq Require Import ssreflect. *)
Theorem basic (A : Type) (x y : A) (p : x = y) : test x y <> None.
Proof.
rewrite p /test; move: eq_refl; case: {2 3}(eq_dec y y) => //.
by rewrite eq_dec_correct'.
Qed.
</code>```

Indeed, we need to select for matching the occurrences of eq_dec in the match and in the right side of the equality proof. You can step the above proof, or you could see the above as building and proving a more general lemma:

```<code>Theorem basic0 (A : Type) (x : A) b (p : eq_dec x x = b) :
  match b as b1 return eq_dec x x = b1 -> option (x = x) with
  | true  => fun p => Some (eq_dec_correct p)
  | false => fun _ => None
  end p <> None.
Proof. by case: b p; rewrite ?eq_dec_correct'. Qed.

Theorem basic1 (A : Type) (x y : A) (p : x = y) : test x y <> None.
Proof. by rewrite p; apply: basic0. Qed.
</code>```

Note how here, by carefully choosing our parameters, we avoid having to perform tricks with pattern-selection. The key step is to "unlink" the boolean in the match from the eq_dec witness present in the "convoy" argument, so we can still correctly type the call to eq_dec_correct. The last interesting bit is that we also have to turn eq_dec x x = eq_dec x x into eq_dec x x = b, thus we need to abstract over the equality proof.

But as I said before, you'll likely want to define even a more general lemma. [Why not use some of the lemmas already present in eqtype?]

Body:
For the purpose of this question, suppose I have:

Parameter eq_bool : forall (A:Type), A -> A -> bool.

Arguments eq_bool {A} _ _.

Axiom eq_bool_correct : forall (A:Type) (x y:A),
    eq_bool x y = true -> x = y.

Axiom eq_bool_correct' : forall (A:Type) (x y:A),
     x = y -> eq_bool x y = true.

I have a function which given two valuesx y:A returns Some proof of x = y whenever x = y and None otherwise. This function is implemented with a pattern match on eq_bool x y to test for equality, and uses the convoy pattern as a trick to get access within your code to a proof of the equality corresponding to the branch of your match:

Definition test (A:Type) (x y:A) : option (x = y) :=
    match eq_bool x y as b return eq_bool x y = b -> option (x = y) with
    | true  => fun p => Some (eq_bool_correct A x y p)
    | false => fun _ => None
    end (eq_refl (eq_bool x y)).

I am now attempting to prove a simple result about this function:

Theorem basic: forall (A:Type) (x y:A),
    x = y -> test A x y <> None.
Proof.
    intros A x y H. rewrite H. unfold test.

A : Type
x, y : A
H : x = y
============================
(if eq_bool y y as b return (eq_bool y y = b -> option (y = y))
 then fun p : eq_bool y y = true => Some (eq_bool_correct A y y p)
 else fun _ : eq_bool y y = false => None) eq_refl <> None

At this point it feels I have to use destruct on eq_bool y y (possibly keeping equation):

destruct (eq_bool y y).

Error: Abstracting over the term "b" leads to a term
fun b0 : bool =>
(if b0 as b1 return (b0 = b1 -> option (y = y))
 then fun p : b0 = true => Some (eq_bool_correct A y y p)
 else fun _ : b0 = false => None) eq_refl <> None
which is ill-typed.
Reason is: Illegal application:
The term "eq_bool_correct" of type
 "forall (A : Type) (x y : A), eq_bool x y = true -> x = y"
cannot be applied to the terms
 "A" : "Type"
 "y" : "A"
 "y" : "A"
 "p" : "b0 = true"
The 4th term has type "b0 = true" which should be coercible to
 "eq_bool y y = true".

I know I have to read CPDT (especially on convoy pattern) but I have a better learning experience with the Software Foundation book (which is suited for beginners): at my current level of skills, I cannot think of anything but destruct and was hoping someone could suggest a way to finish this proof.

Body:
This is the typical case where careless abstraction makes terms ill-typed. In general, you want to use slightly different principles as to avoid these problems, matching on sumbool or reflect may provide you with better results.

In this particular case, in order for things to go through you first need to generalize the goal a bit (so it doesn't depend on eq_refl, which is a problem when matching as its typing rule is too strict) and then select the proper subterms. I use the ssreflect pattern language as it is far more convenient:

(* Do From Coq Require Import ssreflect. *)
Theorem basic (A : Type) (x y : A) (p : x = y) : test x y <> None.
Proof.
rewrite p /test; move: eq_refl; case: {2 3}(eq_dec y y) => //.
by rewrite eq_dec_correct'.
Qed.

Indeed, we need to select for matching the occurrences of eq_dec in the match and in the right side of the equality proof. You can step the above proof, or you could see the above as building and proving a more general lemma:

Theorem basic0 (A : Type) (x : A) b (p : eq_dec x x = b) :
  match b as b1 return eq_dec x x = b1 -> option (x = x) with
  | true  => fun p => Some (eq_dec_correct p)
  | false => fun _ => None
  end p <> None.
Proof. by case: b p; rewrite ?eq_dec_correct'. Qed.

Theorem basic1 (A : Type) (x y : A) (p : x = y) : test x y <> None.
Proof. by rewrite p; apply: basic0. Qed.

Note how here, by carefully choosing our parameters, we avoid having to perform tricks with pattern-selection. The key step is to "unlink" the boolean in the match from the eq_dec witness present in the "convoy" argument, so we can still correctly type the call to eq_dec_correct. The last interesting bit is that we also have to turn eq_dec x x = eq_dec x x into eq_dec x x = b, thus we need to abstract over the equality proof.

But as I said before, you'll likely want to define even a more general lemma. [Why not use some of the lemmas already present in eqtype?]


问:
C++ with STM32CubeMX and Eclipse System Workbench for STM32 AC6 tools
I generated a FreeRTOS project with STM32CubeMX for a Nucleo F429ZI demo board, built with success on Eclipse System Workbench for STM32 AC6 tools and run on the demo board.
I would like to use C++, stl libraries.<
Simply renaming main.c to main.cpp does not work...
 I see someone was able to use C++ with FreeRTOS but I cannot find any help if with this STM32Toolchain it is possible.

答:
Yes, it is posssible. And it's not so difficult (I assume you are using a standard ARM noneabi gcc). But you have to remember any futher modyfication in CubeMX will revert your project to C.

Rename your main.c to main.cpp (now, during compilation you should get an error undefined reference to 'main'.

Right Click on your STM project and select "Convert to C++". Now compilation is successful!

That's all. Remeber that you cannot invoke directly C++ functions form .c files. Also invoking interrupts by MCU will be also impossible when function is in .cpp file and doesn't have extern "C" attribute.
There is no matter if you include into project FreeRTOS, or any other stuff prepared by STM. C++ compiler works only with .cpp files and doesn't affect to .c files. So they works as earlier.


问:
What would be a good project to learn node.js
Everyone is talking about NodeJS so I though I'll look into it by creating a usefull project but I cant really think of something usefull to build on NodeJS tha fully demonstrates it's capabilities.

does any of you have a good idea ?

答:
If it's web-based apps you're interested in creating, and if you don't mind following a tutorial, then I'll recommend DailyJS's tutorial series on building a web-based, Notepad-like application from start to finish on Node: http://dailyjs.com/tags.html#lmawa.

It covers all the basics, including databases, middleware, templates and testing.