问:
Code-behind for DataTemplate in a ResourceDictionary
I am attempting to use code-behind to support an event handler in a DataTemplate.  The below code works fine when it is the code-behind for a Window, but not for a ResourceDictionary.  The code will not even compile when put in the code-behind for the ResourceDictionary.

I know that Commands is the better option here, but this is largely a test to make sure I can handle events on resources in a ResourceDictionary, if needed.  My goal is to better organize my code, but this is not the straightforward "include" behavior that I thought a separate ResourceDictionary file would provide.

In MainWindow.xaml:

```<code>    <Window x:Class="Wizbang.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:my="clr-namespace:DevComponents.WpfEditors;assembly=DevComponents.WpfEditors"
        xmlns:diag="clr-namespace:System.Diagnostics;assembly=WindowsBase"
        xmlns:local ="clr-namespace:Wizbang"
        xmlns:m ="clr-namespace:Wizbang.Model"
        xmlns:vm="clr-namespace:Wizbang.ViewModel"
        xmlns:vw="clr-namespace:Wizbang.View"
        DataContext="{Binding Path=Main, Source={StaticResource Locator}}"
        Title="Wizbang" Height="760" Width="1335" WindowStartupLocation="CenterScreen">

        <Window.Resources>
            <ResourceDictionary>
                 <ResourceDictionary Source="Resources/MainWindowResources.xaml" />
            </ResourceDictionary>
        </Window.Resources>
</code>```

In code-behind MainWindow.xaml.cs and MainWindowResources.xaml.cs, the same code:

```<code>private void btnSave_Click(object sender, RoutedEventArgs e)
        {
            //switch item template
            Button btn = (Button)sender;
            //command contains the list item
            ContentControl itm = (ContentControl)btn.CommandParameter;

            itm.SetValue(ContentTemplateProperty, this.FindResource("DetailedTemplate") as DataTemplate);

            //this.UpdateLayout();

        }
</code>```

When I keep the ResourceDictionary inline in MainWindow.xaml, and put the code-behind in MainWindow.xaml.cs, everything works.  When I attempt to use a separate file for ResourceDictionary, the code does not compile. The compiler complains about the last line:

```<code>itm.SetValue(ContentTemplateProperty, this.FindResource("DetailedTemplate") as DataTemplate);
</code>```

The this.FindResource() is not a valid method, and "ContentTemplateProperty" is not found:

Error 4   The name
  'ContentTemplateProperty' does not
  exist in the current
  context   C:...\Visual Studio
  2010\Projects\Wizbang\Wizbang\Resources\MainWindowResources.xaml.cs   36  26  Wizbang

Error 5   'Wizbang.Resources.MainWindowResources'
  does not contain a definition for
  'FindResource' and no extension method
  'FindResource' accepting a first
  argument of type
  'Wizbang.Resources.MainWindowResources'
  could be found (are you missing a
  using directive or an assembly
  reference?)   C:...\Visual Studio
  2010\Projects\Wizbang\Wizbang\Resources\MainWindowResources.xaml.cs   36  56  Wizbang

If I remove that last line, the code compiles and runs, but the button has no functionality.  I think my issue is mapping that last line's references from the perspective of a ResourceDictionary, but I am not sure why it should be different.

Thanks for any thoughts.

Bill

答: I think that using Commands would be a much cleaner approach. </p>

Body:
I am attempting to use code-behind to support an event handler in a DataTemplate.  The below code works fine when it is the code-behind for a Window, but not for a ResourceDictionary.  The code will not even compile when put in the code-behind for the ResourceDictionary.

I know that Commands is the better option here, but this is largely a test to make sure I can handle events on resources in a ResourceDictionary, if needed.  My goal is to better organize my code, but this is not the straightforward "include" behavior that I thought a separate ResourceDictionary file would provide.

In MainWindow.xaml:

    <Window x:Class="Wizbang.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:my="clr-namespace:DevComponents.WpfEditors;assembly=DevComponents.WpfEditors"
        xmlns:diag="clr-namespace:System.Diagnostics;assembly=WindowsBase"
        xmlns:local ="clr-namespace:Wizbang"
        xmlns:m ="clr-namespace:Wizbang.Model"
        xmlns:vm="clr-namespace:Wizbang.ViewModel"
        xmlns:vw="clr-namespace:Wizbang.View"
        DataContext="{Binding Path=Main, Source={StaticResource Locator}}"
        Title="Wizbang" Height="760" Width="1335" WindowStartupLocation="CenterScreen">

        <Window.Resources>
            <ResourceDictionary>
                 <ResourceDictionary Source="Resources/MainWindowResources.xaml" />
            </ResourceDictionary>
        </Window.Resources>

In code-behind MainWindow.xaml.cs and MainWindowResources.xaml.cs, the same code:

private void btnSave_Click(object sender, RoutedEventArgs e)
        {
            //switch item template
            Button btn = (Button)sender;
            //command contains the list item
            ContentControl itm = (ContentControl)btn.CommandParameter;

            itm.SetValue(ContentTemplateProperty, this.FindResource("DetailedTemplate") as DataTemplate);

            //this.UpdateLayout();

        }

When I keep the ResourceDictionary inline in MainWindow.xaml, and put the code-behind in MainWindow.xaml.cs, everything works.  When I attempt to use a separate file for ResourceDictionary, the code does not compile. The compiler complains about the last line:

itm.SetValue(ContentTemplateProperty, this.FindResource("DetailedTemplate") as DataTemplate);

The this.FindResource() is not a valid method, and "ContentTemplateProperty" is not found:

Error 4   The name
  'ContentTemplateProperty' does not
  exist in the current
  context   C:...\Visual Studio
  2010\Projects\Wizbang\Wizbang\Resources\MainWindowResources.xaml.cs   36  26  Wizbang

Error 5   'Wizbang.Resources.MainWindowResources'
  does not contain a definition for
  'FindResource' and no extension method
  'FindResource' accepting a first
  argument of type
  'Wizbang.Resources.MainWindowResources'
  could be found (are you missing a
  using directive or an assembly
  reference?)   C:...\Visual Studio
  2010\Projects\Wizbang\Wizbang\Resources\MainWindowResources.xaml.cs   36  56  Wizbang

If I remove that last line, the code compiles and runs, but the button has no functionality.  I think my issue is mapping that last line's references from the perspective of a ResourceDictionary, but I am not sure why it should be different.

Thanks for any thoughts.

Bill


来源: stackexchange

问:
How do I ensure I am actually pulling a different release?
I am getting frustrated because I have a friend that is telling me the app of a certain branch off Bitbucket is working a certain way for him. I had a newer release.

So I decided to do:

git checkout -b release/3.5.1

and

git pull origin release/3.5.1

and I got this response:

```<code> * branch              release/3.5.1 -> FETCH_HEAD
Already up to date.
</code>```

I have never pulled this branch before, how can it be up to date?

答:
You shouldn't be creating a new branch (with the -b flag). Instead of doing so, just checkout the branch from origin:

```<code>git checkout origin/release/3.5.1
</code>```

If that results in a pathspec (branch not found) error, first do git fetch to retrieve the remote branch references.

Doing a pull as you did results in the remote branch being merged into the local branch only if there was a tracking arrangement created. In this case, there wasn't. You could set it up that way manually when you create the branch:

```<code>--track origin/release/3.5.1
</code>```

That's really more work than necessary, though.

ContentLicense: CC BY-SA 4.0

Body:
I am getting frustrated because I have a friend that is telling me the app of a certain branch off Bitbucket is working a certain way for him. I had a newer release.

So I decided to do:

git checkout -b release/3.5.1

and

git pull origin release/3.5.1

and I got this response:

 * branch              release/3.5.1 -> FETCH_HEAD
Already up to date.

I have never pulled this branch before, how can it be up to date?

Body:
You shouldn't be creating a new branch (with the -b flag). Instead of doing so, just checkout the branch from origin:

git checkout origin/release/3.5.1

If that results in a pathspec (branch not found) error, first do git fetch to retrieve the remote branch references.

Doing a pull as you did results in the remote branch being merged into the local branch only if there was a tracking arrangement created. In this case, there wasn't. You could set it up that way manually when you create the branch:

--track origin/release/3.5.1

That's really more work than necessary, though.


问:
Replace for loop with if statements by vectorised function in R
I'm having some trouble with a for loop that contains to many conditions and runs for ages (due to the size of the data frame). Hence, I would like to replace it with a vectorised function of the apply family. I have a variable of the format month/year and would like to define a year variable, depending on whether the month is smaller or equal to 10 (October), which would be defined as the very year, or larger than 10, which would be the year + 1 (e.g. 09/2001 = 2001, whereas 12/2001 = 2002). The date variable contains some NAs. Below I give a simplified version of my data frame, including the for-loop that I applied. Any hint for a vectorised function would be appreciated.

Example dataset:

```<code>d <- data.frame("10/2010")
names(d) <- "data"
d$data <- as.character(d$data)
d <- rbind(d, "11/2010","12/2009","08/2008", NA)
</code>```

For-loop:

```<code>d$ano <- NA
for(i in 1:length(d$data)){
  month <- as.numeric(substring(d$data[i],1,2))
  if(!is.na(d$data[i]) & month <=10){
    d$ano[i] <- substring(d$data[i],4,7)
  }
  if(!is.na(d$data[i]) & month >10){
      d$ano[i] <- as.numeric(substring(d$data[i],4,7))+1
  }
}
</code>```

Body:
I'm having some trouble with a for loop that contains to many conditions and runs for ages (due to the size of the data frame). Hence, I would like to replace it with a vectorised function of the apply family. I have a variable of the format month/year and would like to define a year variable, depending on whether the month is smaller or equal to 10 (October), which would be defined as the very year, or larger than 10, which would be the year + 1 (e.g. 09/2001 = 2001, whereas 12/2001 = 2002). The date variable contains some NAs. Below I give a simplified version of my data frame, including the for-loop that I applied. Any hint for a vectorised function would be appreciated.

Example dataset:

d <- data.frame("10/2010")
names(d) <- "data"
d$data <- as.character(d$data)
d <- rbind(d, "11/2010","12/2009","08/2008", NA)

For-loop:

d$ano <- NA
for(i in 1:length(d$data)){
  month <- as.numeric(substring(d$data[i],1,2))
  if(!is.na(d$data[i]) & month <=10){
    d$ano[i] <- substring(d$data[i],4,7)
  }
  if(!is.na(d$data[i]) & month >10){
      d$ano[i] <- as.numeric(substring(d$data[i],4,7))+1
  }
}

Body:
dplyr/tidyr solution:

library(tidyverse)

dat %>%
  separate(data, c('month', 'year'), '/', convert = T) %>%
  transmute(ano = year + (month > 10)) %>%
  bind_cols(dat, .)

#      data  ano
# 1 10/2010 2010
# 2 11/2010 2011
# 3 12/2009 2010
# 4 08/2008 2008
# 5    <NA>   NA

Data:

dat <- structure(
  list(data = c("10/2010", "11/2010", "12/2009", "08/2008", NA)),
  row.names = c(NA,-5L),
  class = "data.frame"
  )


问:
Why i can't configure my mobile app service in azure portal for xamarin.forms?
I'm developing a mobile app for iOS and Android with Xamarin.Forms through Visual Studio IDE. In order to connect my application with my Azure SQL database, I wanted to configure in the quickstart screen my mobile service for Xamarin.Forms. Unfortunately, the quickstart screen suddenly changed and I can't anymore configure the service for Xamarin.forms. Instead, I have to face out with this screen:

Can I have some assistance about it?

答: Mobile apps Quickstart experience from Azure portal is changed and we are making changes to the documentation to reflect the new instructions. The updated docs will be live in a few days. Sorry for the inconvenience that it might have caused.</p>


问:
Undefined variable: all_data (View: /var/www/html/resources/views/welcome.blade.php)
I'm trying to post data from controller to view, basically when page loads user sees the form and when it get submits, it returns the data. I'm not sure what I'm doing wrong. I have tried the following to returns the data

Return methods tried:

```<code>return view('welcome',['all_data'=>$all_data]);
return view('welcome')->with('all_data', $all_data);
return view('welcome')->with('data', json_decode($data, true));
return View::make('welcome', array('all_data'=>$all_data));
</code>```

Controller:

```<code>public function getStatus(Request $request){

//SQLQuery which returns $all_data

$all_data = json_encode($data);
return view('welcome', compact('all_data'));
}
</code>```

Route:

```<code>Route::get('/', function () {
    return view('welcome');
});

Route::post('/getstatus', 'GetApplicationStatusController@getStatus');
</code>```

View:

```<code>@foreach ($all_data as $data)
<td id="appid">{{$data->appid}}</td>
<td id="firstname">{{$data->firstname}}</td>
<td id="middlename">{{$data->middlename}}</td>
<td id="lastname">{{$data->lastname}}</td>
<td id="action">{{$data->action}}</td>
@endforeach
</code>```

答:
try this:
return view('welcome')->with(compact('all_data'));

or this:
return view('welcome')->with(['all_data'=>$all_data])

Body:
I'm trying to post data from controller to view, basically when page loads user sees the form and when it get submits, it returns the data. I'm not sure what I'm doing wrong. I have tried the following to returns the data

Return methods tried:

return view('welcome',['all_data'=>$all_data]);
return view('welcome')->with('all_data', $all_data);
return view('welcome')->with('data', json_decode($data, true));
return View::make('welcome', array('all_data'=>$all_data));

Controller:

public function getStatus(Request $request){

//SQLQuery which returns $all_data

$all_data = json_encode($data);
return view('welcome', compact('all_data'));
}

Route:

Route::get('/', function () {
    return view('welcome');
});

Route::post('/getstatus', 'GetApplicationStatusController@getStatus');

View:

@foreach ($all_data as $data)
{{$data->appid}}
{{$data->firstname}}
{{$data->middlename}}
{{$data->lastname}}
{{$data->action}}
@endforeach


问:
Grails json views : opaque view selection - picks out default template in another directory
I am using Grails 3.3.9 and json views 1.2.10.

In another test I have a url mapping like this

```<code>    "/api/test"(resources:'test')
</code>```

And I have an empty views/test folder, and I don't have a Test domain object.

But I do have a Device domain entity, and have a views/device/_device.gson template in that directory to help render a device object.

The TestController's show action looks like this

```<code>def show (Device device) {
    if(device == null) {
        render status:404
    } else {
        respond device}
}
</code>```

This looks for a Device in domain model and populates into Shows parameter list, and I respond with the device.

There is however no show.gson in the views/test directory (it's empty).

However when you hit the url in the browser "http://localhost:8080/api/test/1", grails renders a response using the "views/device/_device.gson" template.

This is very confusing as it's very hard to figure exactly view view respond is actually using (unless you force it using a view:'xxx' map variable.

How/why is the TestController/show action response return,  picking up "views/device/_device.gson" template ?

答:
(Posted answer on behalf of the question author).

Step 1) if you create a new controller (I used grails create-controller <controller>, and then edit the generated controller to extend from RestfulController<domain type> (but don't override any methods).  Then Setup the URL mapping for your controller, in my example this was

```<code>"/api/org"(resources:'OrgRoleInstance')
</code>```

for which I have the corresponding domain class 'OrgRoleInstance' in my model.

The create-controller action also generates an empty view package 'views/orgRoleInstance' (no gson files are generated)

a) if you do the run app now and open the url

```<code>http://localhost:8080/api/org
</code>```

then your still get a rendered response (like this) !

```<code>[{"id":1,"sites":[],"domains":[],"role":{"enumType":"com.softwood.domain.OrgRoleInstance$OrgRoleType","name":"Service_Provider"},"name":"Vodafone","mags":[{"id":2}]},{"id":2,"sites":[],"domains":[],"role":{"enumType":"com.softwood.domain.OrgRoleInstance$OrgRoleType","name":"Maintainer"},"name":"Cisco","mags":[{"id":1}]},{"id":3,"sites":[],"domains":[],"role":{"enumType":"com.softwood.domain.OrgRoleInstance$OrgRoleType","name":"Supplier"},"name":"Cisco","mags":[]},{"id":4,"sites":[{"id":1},{"id":2}],"domains":[{"id":1}],"role":{"enumType":"com.softwood.domain.OrgRoleInstance$OrgRoleType","name":"Customer"},"name":"Acme","mags":[]}]
</code>```

Ipso facto there is some 'default framework logic' that tries to render the default implementation of the 'index' (and 'show' etc) action inherited from RestfulController'.  This is done even with with no pre-existing gson - no warnings are provided.

Step 2: next stop the app (it's still caching the previous 'default' behaviour).

Now go to the empty view directory and create an 'index.gson' like this with no model

```<code>json ([1,2,3])
</code>```

Then restart the app in your IDE.  Now when it starts, it detects that an index.gson exists, and when you call the url 'http://localhost:8080/api/org' what you get is the rendered json for the static list [1,2,3]

step 3:  gson views are using static compilation under the covers and very fiddly to get exactly right.  However in the case of default RestfulController index action , a list of OrgRoleInstances is selected from the domain model and passed as a lit to the view.  if you want the databinding to the view to work, then if your domain object is type T, the you get a List<T> returned.

The internal default in the code base, is if you get List<T> returned to respond then, the data model in the view is assumed to be List<T> <T>List i.e. in my example this would be

List<OrgRoleInstance> orgRoleInstanceList in the gson view model.  Now with a revised index.gson (you can edit this without stop/start of server in dev mode)

```<code>import com.softwood.domain.OrgRoleInstance

model {
    List<OrgRoleInstance> orgRoleInstanceList
}

json {

    recordCount orgRoleInstanceList.size()
}
</code>```

Now when you Get the URL you get a json response with the size of the list:

```<code>{"recordCount":4}
</code>```

Note that if you add an extra variable to your model like this:

```<code>import com.softwood.domain.OrgRoleInstance

model {
    List<OrgRoleInstance> orgRoleInstanceList
    Integer orgRoleInstanceCount
}

json {

    recordCount orgRoleInstanceList.size()
    size orgRoleInstanceCount
}
</code>```

and modify the index.gson to print the new Integer variable - then it is not data bound from the default respond action.

Browser response looks like this:

```<code>{"recordCount":4,"size":null}
</code>```

Option 4: - look at invoking a 'template' class. Having set up a model that's expecting a List<T>, the runTime type built via data binding is an instance of "grails.orm.PagedResultList".  This is an Iterable type.

This is very confusing to read in the documentation - it's really not clear however if you create a file called _<file>.gson. Then this is treated is a template gson file.

This can have its own model/json, but because all this is statically compiled you have to get the types exactly matching and where necessary declare the 'name' of the model variable when calling the template (either via g.render or implicit tmpl.<file>.

When you call the template from the parent view you can pass either an the List<T> iterable model type or iterate in the parent view and pass each <T> to the template.  You have to ensure that the model type you pass to the tmpl is declared as the same type in the tmpl model.

e.g. assuming a List<T> in the parent view but a <T> in the template, you need to invoke the tmpl for each item in the list.  e.g.
if you have a tmpl like this "_orgRoleInstance.gson".

If you have the parent view like this (note single <T> declared and model variable named 'org'

```<code>import com.softwood.domain.OrgRoleInstance

model {
    OrgRoleInstance org
}
json {
    id org.id
    name org.name
}
</code>```

Then the parent view "index.gson" you need something like this that invokes the tmpl as many times as you have entries in the list, but I've had to tell the framework that the tmpl model variable name is 'org' by passing a map.  This will render as you expect.

```<code>import com.softwood.domain.OrgRoleInstance

model {
    List<OrgRoleInstance> orgRoleInstanceList
    Integer orgRoleInstanceCount
}

orgRoleInstanceList.each { OrgRoleInstance org ->
    json tmpl.orgRoleInstance(org:org)
}
</code>```

If you declare the tmpl variable to be "def org", it still works but as this is statically typed, the variable is passed as static instance of Object (run time type is correct, but you cant just access the properties as the static type is Object), and it gets hard sorting out the casts required to access the properties.

If you want the parent view to pass the model List<T> variable to the tmpl, you can = but you have to ensure that the model variable in the tmpl is List<T> else the data binding doesn't work.

Now in the template you can invoke the json and iterate over the List

e.g. with a modified tmpl like this

```<code>http://localhost:8080/api/org
</code>```0

and a revised parent view like this to invoke the tmpl:

```<code>http://localhost:8080/api/org
</code>```1

What get rendered is this:

```<code>http://localhost:8080/api/org
</code>```2

You will note that there is a single json clause so it iterates all the ids first and the all the names second.

If this is not what you want you have to iterate over the list to do each in turn

i.e. a modified tmpl like this will iterate over each entry in turn

```<code>import com.softwood.domain.OrgRoleInstance

model {
    //OrgRoleInstance org
    List<OrgRoleInstance> orgs
}
json (orgs) {OrgRoleInstance org ->
        id org.id
        name org.name
}
</code>```

and produce this in the browser

```<code>[{"id":1,"name":"Vodafone"},{"id":2,"name":"Cisco"},{"id":3,"name":"Cisco"},{"id":4,"name":"Acme"}]
</code>```

For anyone else who is confused by Grails Views, I hope this shows how this works between url mappings (you can use the Gradle "urlMappingsReport" to see these) and shows what urls are mapped to what actions.  You then need gson views created with the same name as these actions, and configure your gson views and any tmpl you create to be aware of the implicit behaviour that the JsonViews applies when processing your code.

Body:
I am using Grails 3.3.9 and json views 1.2.10.

In another test I have a url mapping like this

    "/api/test"(resources:'test')

And I have an empty views/test folder, and I don't have a Test domain object.

But I do have a Device domain entity, and have a views/device/_device.gson template in that directory to help render a device object.

The TestController's show action looks like this

def show (Device device) {
    if(device == null) {
        render status:404
    } else {
        respond device}
}

This looks for a Device in domain model and populates into Shows parameter list, and I respond with the device.

There is however no show.gson in the views/test directory (it's empty).

However when you hit the url in the browser "http://localhost:8080/api/test/1", grails renders a response using the "views/device/_device.gson" template.

This is very confusing as it's very hard to figure exactly view view respond is actually using (unless you force it using a view:'xxx' map variable.

How/why is the TestController/show action response return,  picking up "views/device/_device.gson" template ?

Body:
(Posted answer on behalf of the question author).

Step 1) if you create a new controller (I used grails create-controller <controller>, and then edit the generated controller to extend from RestfulController<domain type> (but don't override any methods).  Then Setup the URL mapping for your controller, in my example this was

"/api/org"(resources:'OrgRoleInstance')

for which I have the corresponding domain class 'OrgRoleInstance' in my model.

The create-controller action also generates an empty view package 'views/orgRoleInstance' (no gson files are generated)

a) if you do the run app now and open the url

http://localhost:8080/api/org

then your still get a rendered response (like this) !

[{"id":1,"sites":[],"domains":[],"role":{"enumType":"com.softwood.domain.OrgRoleInstance$OrgRoleType","name":"Service_Provider"},"name":"Vodafone","mags":[{"id":2}]},{"id":2,"sites":[],"domains":[],"role":{"enumType":"com.softwood.domain.OrgRoleInstance$OrgRoleType","name":"Maintainer"},"name":"Cisco","mags":[{"id":1}]},{"id":3,"sites":[],"domains":[],"role":{"enumType":"com.softwood.domain.OrgRoleInstance$OrgRoleType","name":"Supplier"},"name":"Cisco","mags":[]},{"id":4,"sites":[{"id":1},{"id":2}],"domains":[{"id":1}],"role":{"enumType":"com.softwood.domain.OrgRoleInstance$OrgRoleType","name":"Customer"},"name":"Acme","mags":[]}]

Ipso facto there is some 'default framework logic' that tries to render the default implementation of the 'index' (and 'show' etc) action inherited from RestfulController'.  This is done even with with no pre-existing gson - no warnings are provided.

Step 2: next stop the app (it's still caching the previous 'default' behaviour).

Now go to the empty view directory and create an 'index.gson' like this with no model

json ([1,2,3])

Then restart the app in your IDE.  Now when it starts, it detects that an index.gson exists, and when you call the url 'http://localhost:8080/api/org' what you get is the rendered json for the static list [1,2,3]

step 3:  gson views are using static compilation under the covers and very fiddly to get exactly right.  However in the case of default RestfulController index action , a list of OrgRoleInstances is selected from the domain model and passed as a lit to the view.  if you want the databinding to the view to work, then if your domain object is type T, the you get a List<T> returned.

The internal default in the code base, is if you get List<T> returned to respond then, the data model in the view is assumed to be List<T> <T>List i.e. in my example this would be

List<OrgRoleInstance> orgRoleInstanceList in the gson view model.  Now with a revised index.gson (you can edit this without stop/start of server in dev mode)

import com.softwood.domain.OrgRoleInstance

model {
    List<OrgRoleInstance> orgRoleInstanceList
}

json {

    recordCount orgRoleInstanceList.size()
}

Now when you Get the URL you get a json response with the size of the list:

{"recordCount":4}

Note that if you add an extra variable to your model like this:

import com.softwood.domain.OrgRoleInstance

model {
    List<OrgRoleInstance> orgRoleInstanceList
    Integer orgRoleInstanceCount
}

json {

    recordCount orgRoleInstanceList.size()
    size orgRoleInstanceCount
}

and modify the index.gson to print the new Integer variable - then it is not data bound from the default respond action.

Browser response looks like this:

{"recordCount":4,"size":null}

Option 4: - look at invoking a 'template' class. Having set up a model that's expecting a List<T>, the runTime type built via data binding is an instance of "grails.orm.PagedResultList".  This is an Iterable type.

This is very confusing to read in the documentation - it's really not clear however if you create a file called _<file>.gson. Then this is treated is a template gson file.

This can have its own model/json, but because all this is statically compiled you have to get the types exactly matching and where necessary declare the 'name' of the model variable when calling the template (either via g.render or implicit tmpl.<file>.

When you call the template from the parent view you can pass either an the List<T> iterable model type or iterate in the parent view and pass each <T> to the template.  You have to ensure that the model type you pass to the tmpl is declared as the same type in the tmpl model.

e.g. assuming a List<T> in the parent view but a <T> in the template, you need to invoke the tmpl for each item in the list.  e.g.
if you have a tmpl like this "_orgRoleInstance.gson".

If you have the parent view like this (note single <T> declared and model variable named 'org'

import com.softwood.domain.OrgRoleInstance

model {
    OrgRoleInstance org
}
json {
    id org.id
    name org.name
}

Then the parent view "index.gson" you need something like this that invokes the tmpl as many times as you have entries in the list, but I've had to tell the framework that the tmpl model variable name is 'org' by passing a map.  This will render as you expect.

import com.softwood.domain.OrgRoleInstance

model {
    List<OrgRoleInstance> orgRoleInstanceList
    Integer orgRoleInstanceCount
}

orgRoleInstanceList.each { OrgRoleInstance org ->
    json tmpl.orgRoleInstance(org:org)
}

If you declare the tmpl variable to be "def org", it still works but as this is statically typed, the variable is passed as static instance of Object (run time type is correct, but you cant just access the properties as the static type is Object), and it gets hard sorting out the casts required to access the properties.

If you want the parent view to pass the model List<T> variable to the tmpl, you can = but you have to ensure that the model variable in the tmpl is List<T> else the data binding doesn't work.

Now in the template you can invoke the json and iterate over the List

e.g. with a modified tmpl like this

import com.softwood.domain.OrgRoleInstance

model {
    //OrgRoleInstance org
    List<OrgRoleInstance> orgs
}
json {
    id orgs.id
    name orgs.name
}

and a revised parent view like this to invoke the tmpl:

import com.softwood.domain.OrgRoleInstance

model {
    List<OrgRoleInstance> orgRoleInstanceList
    Integer orgRoleInstanceCount
}

/*
orgRoleInstanceList.each { OrgRoleInstance org ->
    json tmpl.orgRoleInstance(orgs:org)
}*/

//alternate approach
json tmpl.orgRoleInstance (orgs:orgRoleInstanceList)

What get rendered is this:

{"id":[1,2,3,4],"name":["Vodafone","Cisco","Cisco","Acme"]}

You will note that there is a single json clause so it iterates all the ids first and the all the names second.

If this is not what you want you have to iterate over the list to do each in turn

i.e. a modified tmpl like this will iterate over each entry in turn

import com.softwood.domain.OrgRoleInstance

model {
    //OrgRoleInstance org
    List<OrgRoleInstance> orgs
}
json (orgs) {OrgRoleInstance org ->
        id org.id
        name org.name
}

and produce this in the browser

[{"id":1,"name":"Vodafone"},{"id":2,"name":"Cisco"},{"id":3,"name":"Cisco"},{"id":4,"name":"Acme"}]

For anyone else who is confused by Grails Views, I hope this shows how this works between url mappings (you can use the Gradle "urlMappingsReport" to see these) and shows what urls are mapped to what actions.  You then need gson views created with the same name as these actions, and configure your gson views and any tmpl you create to be aware of the implicit behaviour that the JsonViews applies when processing your code.


问:
Asynchronous write (append) to a file by multiple parallel threads NIO
Can I leverage NIO Async APIs to write (append) in a single file by multiple parallel threads? What I am trying to do is break the queries into different categories and assign a thread to each category to get the records from DB and write to a file (say user-records.json).

Thread A
Users of some category A

Query by user ids - write the resultset to user-records.json

Thread B
Users of some category B

Query by user ids - append the resultset to user-records.json

Thread C
Users of some category C

Query by user ids - append the resultset to user-records.json

and so on ....

Here are the classes which are not the actual implementation but just a sample to enable Async file write/append -

```<code>public class AsyncAppender {

    private final AsynchronousFileChannel channel;
    /** Where new append operations are told to start writing. */
    private final AtomicLong              projectedSize;

    AsyncAppender( AsynchronousFileChannel channel) throws IOException {
        this.channel = channel;
        this.projectedSize = new AtomicLong(channel.size());
    }

    public void append( ByteBuffer buf) throws IOException {
        final int buflen = buf.remaining();
        long size;
        do {
            size = projectedSize.get();
        } while (!projectedSize.compareAndSet(size, size + buflen));

        channel.write(buf, channel.size(), channel, new WriteOp(buf, size));
    }
}

public class WriteOp implements CompletionHandler<Integer, AsynchronousFileChannel> {

    private final ByteBuffer buf;
    private long             position;

    WriteOp( ByteBuffer buf, long position) {
        this.buf = buf;
        this.position = position;
    }

    @Override
    public void completed( Integer result, AsynchronousFileChannel channel) {
        if (buf.hasRemaining()) { // incomplete write
            position += result;
            channel.write(buf, position, channel, this);
        }
    }

    @Override
    public void failed( Throwable ex, AsynchronousFileChannel channel) {
        // ?
    }
}
</code>```

The main class -

```<code>public class AsyncWriteMain {

    public static void main( String[] args) {
        AsyncWriteMain m = new AsyncWriteMain();
        m.asyncWrite();
    }

    public void asyncWrite() {
        try {
            String filePath = "D:\\temp\\user-records.txt";
            Path file = Paths.get(filePath);
            AsynchronousFileChannel asyncFile = AsynchronousFileChannel.open(file, StandardOpenOption.WRITE, StandardOpenOption.CREATE);

            AsyncAppender aa = new AsyncAppender(asyncFile);

            for ( int i = 0; i < 10; i++) {
                aa.append(ByteBuffer.wrap((i + " Some text to be written").getBytes()));
            }
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
    }
}
</code>```

答:
I think you can. Bascically, you need file lock

Future<FileLock> featureLock = asynchFileChannel.lock();
        log.info("Waiting for the file to be locked ...");
        FileLock lock = featureLock.get();
        if (lock.isValid()) {...}
```

coming from here

Body:
Can I leverage NIO Async APIs to write (append) in a single file by multiple parallel threads? What I am trying to do is break the queries into different categories and assign a thread to each category to get the records from DB and write to a file (say user-records.json).

Thread A
Users of some category A

Query by user ids - write the resultset to user-records.json

Thread B
Users of some category B

Query by user ids - append the resultset to user-records.json

Thread C
Users of some category C

Query by user ids - append the resultset to user-records.json

and so on ....

Here are the classes which are not the actual implementation but just a sample to enable Async file write/append -

public class AsyncAppender {

    private final AsynchronousFileChannel channel;
    /** Where new append operations are told to start writing. */
    private final AtomicLong              projectedSize;

    AsyncAppender( AsynchronousFileChannel channel) throws IOException {
        this.channel = channel;
        this.projectedSize = new AtomicLong(channel.size());
    }

    public void append( ByteBuffer buf) throws IOException {
        final int buflen = buf.remaining();
        long size;
        do {
            size = projectedSize.get();
        } while (!projectedSize.compareAndSet(size, size + buflen));

        channel.write(buf, channel.size(), channel, new WriteOp(buf, size));
    }
}

public class WriteOp implements CompletionHandler<Integer, AsynchronousFileChannel> {

    private final ByteBuffer buf;
    private long             position;

    WriteOp( ByteBuffer buf, long position) {
        this.buf = buf;
        this.position = position;
    }

    @Override
    public void completed( Integer result, AsynchronousFileChannel channel) {
        if (buf.hasRemaining()) { // incomplete write
            position += result;
            channel.write(buf, position, channel, this);
        }
    }

    @Override
    public void failed( Throwable ex, AsynchronousFileChannel channel) {
        // ?
    }
}

The main class -

public class AsyncWriteMain {

    public static void main( String[] args) {
        AsyncWriteMain m = new AsyncWriteMain();
        m.asyncWrite();
    }

    public void asyncWrite() {
        try {
            String filePath = "D:\\temp\\user-records.txt";
            Path file = Paths.get(filePath);
            AsynchronousFileChannel asyncFile = AsynchronousFileChannel.open(file, StandardOpenOption.WRITE, StandardOpenOption.CREATE);

            AsyncAppender aa = new AsyncAppender(asyncFile);

            for ( int i = 0; i < 10; i++) {
                aa.append(ByteBuffer.wrap((i + " Some text to be written").getBytes()));
            }
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
    }
}

Body:
I think you can. Bascically, you need file lock

Future<FileLock> featureLock = asynchFileChannel.lock();
        log.info("Waiting for the file to be locked ...");
        FileLock lock = featureLock.get();
        if (lock.isValid()) {...}

coming from here


问:
How to get Memory (Private working set) per users in powershell
I'm trying to get the memory usage of process per user (like task manager), that info comes to Memory (Private working set) if we convert that values into MB we should get the memory usage, like in the users view in task manager...

Maybe i missing something, if someone know about this pls tell me.

And this is my script

```<code>Get-WmiObject Win32_Process | Sort-Object -Property privatememorysize -Descending |
Select processname, @{Name="Mem Usage(MB)";Expression={[math]::round($_.privatememorysize/ 1mb,2)}},@{Name="UserID";Expression={$_.getowner().Domain+"\"+$_.getowner().user}} | fl *
</code>```

答:
Try using WorkingSetSize instead of PrivateMemorySize.

```<code>Get-WmiObject Win32_Process | Sort-Object -Property WorkingSetSize -Descending |
Select processname, @{Name="Mem Usage(MB)";Expression={[math]::round($_.WorkingSetSize / 1mb,2)}},@{Name="UserID";Expression={$_.getowner().Domain+"\"+$_.getowner().user}} | FL
</code>```

Body:
I'm trying to get the memory usage of process per user (like task manager), that info comes to Memory (Private working set) if we convert that values into MB we should get the memory usage, like in the users view in task manager...

Maybe i missing something, if someone know about this pls tell me.

And this is my script

Get-WmiObject Win32_Process | Sort-Object -Property privatememorysize -Descending |
Select processname, @{Name="Mem Usage(MB)";Expression={[math]::round($_.privatememorysize/ 1mb,2)}},@{Name="UserID";Expression={$_.getowner().Domain+"\"+$_.getowner().user}} | fl *

Body:
Try using WorkingSetSize instead of PrivateMemorySize.

Get-WmiObject Win32_Process | Sort-Object -Property WorkingSetSize -Descending |
Select processname, @{Name="Mem Usage(MB)";Expression={[math]::round($_.WorkingSetSize / 1mb,2)}},@{Name="UserID";Expression={$_.getowner().Domain+"\"+$_.getowner().user}} | FL


问:
Which Lisp should I learn?

Which Lisp (dialect) should I learn, and why?

The fragmentation between CL and Scheme slows uptake (at least for me!).

So, give me the "true answer", please!

I have tried to read feature comparisons, and they seem to get bogged down in esoterica (that I don't fully understand) like whether the dialect is fully tail-recursive, and the like.  I'm hoping you all (collectively) can make the opaque differences clear.

Things I like

Good library support, good environments, and Unicode support.

Things I dislike

Flamewars. Features that are useful at the beginning, but interfere with long-term learning.

Updates

I've been mostly using MzScheme, which I'm enjoying just fine, once I got readline support going.  I don't run a GUI on Unix, so it seemed to be a fine environment option for me.

I'm also very happy that Clojure has an easy to install .deb package on debian, so it's much easier to play with.  This is a big win.  Despite the hostility of some rather easy-to-anger below, low barrier to entry is a win.  I like being spoonfed.

After reading a lot more of SICP, I do understand the issues around tail recursion much better.

答: Take a look at IronScheme.</p>

OwnerDisplayName: Gregg Lind

ContentLicense: CC BY-SA 3.0

Title: Which Lisp should I learn?

LastEditorDisplayName: Gregg Lind

Body: Take a look at IronScheme.

OwnerDisplayName: Nemanja Trifunovic

ContentLicense: CC BY-SA 2.5


问:
Why I cannot create a class object inside a function?
I have my main code that contains several functions and I tested it and it works perfectly fine. I then create a class for tkinter window, and test it separately and it also works fine. When I incorporate the both of them together, by creating a class object inside a function, I get this error message:

"TclError: can't invoke "frame" command: application has been destroyed"

```<code>import tkinter

class InputFromForm():
    def __init__(self, root, values):
        self.field = []
        self.fieldStrings = values
        self.temp = self.makeform(self.fieldStrings)

    def makeform(self, fields):
        entries = []
        for i in fields:
            row = tkinter.Frame(root)
            lab = tkinter.Label(row, width=15, text=i, anchor='w')
            ent = tkinter.Entry(row)
            ent.insert(tkinter.END, fields[i])
            ent.bind("<FocusIn>", lambda event, e=ent: e.selection_range(0, tkinter.END))
            row.pack(side=tkinter.TOP, fill=tkinter.X, padx=5, pady=10)
            lab.pack(side=tkinter.LEFT)
            ent.pack(side=tkinter.RIGHT, expand=tkinter.YES, fill=tkinter.X)
            entries.append((i, ent))

        return entries

    def fetch(self, entries):
        for entry in entries:
            string = entry[0]
            text  = entry[1].get()
            self.field.append(text)
        return self.field

    def close(self, root):
        root.destroy()

def extractData(dOfValues):
    root = tkinter.Tk()
    root.title('Test')
    userInput = InputFromForm(root, dOfValues)
    root.bind('<Return>', (lambda event, e=userInput.temp: userInput.fetch(e)))
    b1 = tkinter.Button(root, text='OK',command=(lambda e=userInput.temp: [userInput.fetch(e), userInput.close(root)]))
    b1.config(width=25)
    b1.pack(anchor=tkinter.CENTER, padx=5, pady=20)

    root.mainloop()

if __name__ == '__main__':

    dOfValues = {'Customer No.': '',
            'PO #':'020202',
            'Order Date': '2/3/2012',
            'Zip to code':'92182'}

    #root = tkinter.Tk()
    #root.title('Test')

    #userInput = InputFromForm(root, dOfValues)

    #root.bind('<Return>', (lambda event, e=userInput.temp: userInput.fetch(e)))
    #b1 = tkinter.Button(root, text='OK',command=(lambda e=userInput.temp: [userInput.fetch(e), userInput.close(root)]))
    #b1.config(width=25)
    #b1.pack(anchor=tkinter.CENTER, padx=5, pady=20)

    #root.mainloop()
    extractData(dOfValues)  # Adding this, creates the error. If I put the code
                            # from this function into main, it works.
</code>```

Can someone explain what is going on?

答:
@paul "Printing and returning are completely unrelated"

are you sure? try this code.I think you can change it to retrieve what

you want, the values on your fields, if I've understand what you want.

```<code>import tkinter as tk
from tkinter import messagebox

class InputFromForm(tk.Tk):
    def __init__(self, root, values):
        self.field = []
        self.entries = []
        self.fieldStrings = values
        self.temp = self.makeform(self.fieldStrings)

    def makeform(self, fields):

        entries = []

        for i in fields:
            row = tk.Frame()
            lab = tk.Label(row, width=15, text=i, anchor='w')
            ent = tk.Entry(row)
            ent.insert(tk.END, fields[i])
            ent.bind("<FocusIn>", lambda event, e=ent: e.selection_range(0, tk.END))
            row.pack(side=tk.TOP, fill=tk.X, padx=5, pady=10)
            lab.pack(side=tk.LEFT)
            ent.pack(side=tk.RIGHT, expand=tk.YES, fill=tk.X)
            entries.append((i, ent))

        return entries

    def fetch(self, entries):
        for entry in entries:
            string = entry[0]
            text  = entry[1].get()
            self.field.append(text)
        return self.field

    def close(self, root):

        msg = "Do you want to quit?\nI've this data for you\n {0}".format(self.field)

        if messagebox.askokcancel("Simple App", msg):
            root.destroy()

def extractData(dOfValues):
    root = tk.Tk()
    root.title('Test')
    userInput = InputFromForm(root, dOfValues)
    root.bind('<Return>', (lambda event, e=userInput.temp: userInput.fetch(e)))
    b1 = tk.Button(root, text='OK',command=(lambda e=userInput.temp: [userInput.fetch(e), userInput.close(root)]))
    b1.config(width=25)
    b1.pack(anchor=tk.CENTER, padx=5, pady=20)

    root.mainloop()

if __name__ == '__main__':

    dOfValues = {'Customer No.': '',
            'PO #':'020202',
            'Order Date': '2/3/2012',
            'Zip to code':'92182'}

    #root = tk.Tk()
    #root.title('Test')

    #userInput = InputFromForm(root, dOfValues)

    #root.bind('<Return>', (lambda event, e=userInput.temp: userInput.fetch(e)))
    #b1 = tk.Button(root, text='OK',command=(lambda e=userInput.temp: [userInput.fetch(e), userInput.close(root)]))
    #b1.config(width=25)
    #b1.pack(anchor=tk.CENTER, padx=5, pady=20)

    #root.mainloop()
    extractData(dOfValues)  # Adding this, creates the error. If I put the code
                            # from this function into main, it works.
</code>```

Body:
I have my main code that contains several functions and I tested it and it works perfectly fine. I then create a class for tkinter window, and test it separately and it also works fine. When I incorporate the both of them together, by creating a class object inside a function, I get this error message:

"TclError: can't invoke "frame" command: application has been destroyed"

import tkinter

class InputFromForm():
    def __init__(self, root, values):
        self.field = []
        self.fieldStrings = values
        self.temp = self.makeform(self.fieldStrings)

    def makeform(self, fields):
        entries = []
        for i in fields:
            row = tkinter.Frame(root)
            lab = tkinter.Label(row, width=15, text=i, anchor='w')
            ent = tkinter.Entry(row)
            ent.insert(tkinter.END, fields[i])
            ent.bind("<FocusIn>", lambda event, e=ent: e.selection_range(0, tkinter.END))
            row.pack(side=tkinter.TOP, fill=tkinter.X, padx=5, pady=10)
            lab.pack(side=tkinter.LEFT)
            ent.pack(side=tkinter.RIGHT, expand=tkinter.YES, fill=tkinter.X)
            entries.append((i, ent))

        return entries

    def fetch(self, entries):
        for entry in entries:
            string = entry[0]
            text  = entry[1].get()
            self.field.append(text)
        return self.field

    def close(self, root):
        root.destroy()

def extractData(dOfValues):
    root = tkinter.Tk()
    root.title('Test')
    userInput = InputFromForm(root, dOfValues)
    root.bind('<Return>', (lambda event, e=userInput.temp: userInput.fetch(e)))
    b1 = tkinter.Button(root, text='OK',command=(lambda e=userInput.temp: [userInput.fetch(e), userInput.close(root)]))
    b1.config(width=25)
    b1.pack(anchor=tkinter.CENTER, padx=5, pady=20)

    root.mainloop()

if __name__ == '__main__':

    dOfValues = {'Customer No.': '',
            'PO #':'020202',
            'Order Date': '2/3/2012',
            'Zip to code':'92182'}

    #root = tkinter.Tk()
    #root.title('Test')

    #userInput = InputFromForm(root, dOfValues)

    #root.bind('<Return>', (lambda event, e=userInput.temp: userInput.fetch(e)))
    #b1 = tkinter.Button(root, text='OK',command=(lambda e=userInput.temp: [userInput.fetch(e), userInput.close(root)]))
    #b1.config(width=25)
    #b1.pack(anchor=tkinter.CENTER, padx=5, pady=20)

    #root.mainloop()
    extractData(dOfValues)  # Adding this, creates the error. If I put the code
                            # from this function into main, it works.

Can someone explain what is going on?

Body:
@paul "Printing and returning are completely unrelated"

are you sure? try this code.I think you can change it to retrieve what

you want, the values on your fields, if I've understand what you want.

import tkinter as tk
from tkinter import messagebox

class InputFromForm(tk.Tk):
    def __init__(self, root, values):
        self.field = []
        self.entries = []
        self.fieldStrings = values
        self.temp = self.makeform(self.fieldStrings)

    def makeform(self, fields):

        entries = []

        for i in fields:
            row = tk.Frame()
            lab = tk.Label(row, width=15, text=i, anchor='w')
            ent = tk.Entry(row)
            ent.insert(tk.END, fields[i])
            ent.bind("<FocusIn>", lambda event, e=ent: e.selection_range(0, tk.END))
            row.pack(side=tk.TOP, fill=tk.X, padx=5, pady=10)
            lab.pack(side=tk.LEFT)
            ent.pack(side=tk.RIGHT, expand=tk.YES, fill=tk.X)
            entries.append((i, ent))

        return entries

    def fetch(self, entries):
        for entry in entries:
            string = entry[0]
            text  = entry[1].get()
            self.field.append(text)
        return self.field

    def close(self, root):

        msg = "Do you want to quit?\nI've this data for you\n {0}".format(self.field)

        if messagebox.askokcancel("Simple App", msg):
            root.destroy()

def extractData(dOfValues):
    root = tk.Tk()
    root.title('Test')
    userInput = InputFromForm(root, dOfValues)
    root.bind('<Return>', (lambda event, e=userInput.temp: userInput.fetch(e)))
    b1 = tk.Button(root, text='OK',command=(lambda e=userInput.temp: [userInput.fetch(e), userInput.close(root)]))
    b1.config(width=25)
    b1.pack(anchor=tk.CENTER, padx=5, pady=20)

    root.mainloop()

if __name__ == '__main__':

    dOfValues = {'Customer No.': '',
            'PO #':'020202',
            'Order Date': '2/3/2012',
            'Zip to code':'92182'}

    #root = tk.Tk()
    #root.title('Test')

    #userInput = InputFromForm(root, dOfValues)

    #root.bind('<Return>', (lambda event, e=userInput.temp: userInput.fetch(e)))
    #b1 = tk.Button(root, text='OK',command=(lambda e=userInput.temp: [userInput.fetch(e), userInput.close(root)]))
    #b1.config(width=25)
    #b1.pack(anchor=tk.CENTER, padx=5, pady=20)

    #root.mainloop()
    extractData(dOfValues)  # Adding this, creates the error. If I put the code
                            # from this function into main, it works.


问:
pass un-escaped HTML into vue slot string
I'm trying to replace an existing element with a component, but using the existing element data in the new component.

How would you pass the existing element into the new components slot, maintaining the original elements un-escaped HTML markup?

document.addEventListener("DOMContentLoaded", function() {
  let ExampleComponent = {
    data: function() {
      return {};
    },
    props: ["type"],
    template: `

              Decoration
              <slot name="myslot">default content</slot>

            `
  };

  new Vue({
    el: "#app",
    components: {
      example: ExampleComponent
    },
    data() {
      return {};
    },
    methods: {
      addExampleComponent: function() {
        let target = this.$el.querySelector(".example-target");

        let ComponentClass = Vue.extend(ExampleComponent);
        let instance = new ComponentClass({
          propsData: { type: "primary" }
        });
        instance.$slots.myslot = target.outerHTML;
        instance.$mount();

        target.replaceWith(instance.$el);
      }
    }
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdn.jsdelivr.net/npm/vue@2.6.10/dist/vue.js"></script>

  <div id="app">
    <div class="example-target">replace me!</div>
    <div>
      <button v-on:click="addExampleComponent">Replace</button>
    </div>
  </div></code>```

Currently replace me! in the "example-target" element literally displays  Decoration
replace me!
 after pressing the "Replace" button. I'm looking to keep the HTML intact, without being escaped.

答:
Try using the v:html directive.

    document.addEventListener('DOMContentLoaded', function () {
        let ExampleComponent = {
            data: function () { return {} },
            props: ['type'],
            template: `

            Decoration
            <slot name="myslot">default content</slot>

        `
        }

        new Vue({
            el: '#app',
            components: {
                'example': ExampleComponent
            },
            data() { return {} },
            computed: {
                addExampleComponent: function () {
                    let target = this.$el.querySelector('.example-target')

                    let ComponentClass = Vue.extend(ExampleComponent)
                    let instance = new ComponentClass({
                        propsData: { type: 'primary' }
                    })
                    instance.$slots.myslot = target.outerHTML
                    instance.$mount()

                    return instance.$options.template
                }
            }
        })
    })```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.10/vue.js"></script>
<body>
    <div id="app">
        <div class="example-target">replace me!</div>
        <div>
            <div v-html="addExampleComponent"></div>
        </div>
    </div>
</body></code>```

Body:
I'm trying to replace an existing element with a component, but using the existing element data in the new component.

How would you pass the existing element into the new components slot, maintaining the original elements un-escaped HTML markup?

document.addEventListener("DOMContentLoaded", function() {
  let ExampleComponent = {
    data: function() {
      return {};
    },
    props: ["type"],
    template: `

              Decoration
              <slot name="myslot">default content</slot>

            `
  };

  new Vue({
    el: "#app",
    components: {
      example: ExampleComponent
    },
    data() {
      return {};
    },
    methods: {
      addExampleComponent: function() {
        let target = this.$el.querySelector(".example-target");

        let ComponentClass = Vue.extend(ExampleComponent);
        let instance = new ComponentClass({
          propsData: { type: "primary" }
        });
        instance.$slots.myslot = target.outerHTML;
        instance.$mount();

        target.replaceWith(instance.$el);
      }
    }
  });
});

replace me!

      <button v-on:click="addExampleComponent">Replace</button>

Currently replace me! in the "example-target" element literally displays  Decoration
replace me!
 after pressing the "Replace" button. I'm looking to keep the HTML intact, without being escaped.

Body:
Try using the v:html directive.

    document.addEventListener('DOMContentLoaded', function () {
        let ExampleComponent = {
            data: function () { return {} },
            props: ['type'],
            template: `
          <div>
            <span :class="type">Decoration</span>
            <slot name="myslot">default content</slot>
          </div>
        `
        }

        new Vue({
            el: '#app',
            components: {
                'example': ExampleComponent
            },
            data() { return {} },
            computed: {
                addExampleComponent: function () {
                    let target = this.$el.querySelector('.example-target')

                    let ComponentClass = Vue.extend(ExampleComponent)
                    let instance = new ComponentClass({
                        propsData: { type: 'primary' }
                    })
                    instance.$slots.myslot = target.outerHTML
                    instance.$mount()

                    return instance.$options.template
                }
            }
        })
    })

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.10/vue.js"></script>
<body>
    <div id="app">
        <div class="example-target">replace me!</div>
        <div>
            <div v-html="addExampleComponent"></div>
        </div>
    </div>
</body>


答:
One way to do this is to transform each cell into a list by doing a Text.Split on the line feed / carriage return symbol.

```<code>TextSplit = Table.TransformColumns(Source,
                {
                    {"Name",     each Text.Split(_,"#(lf)"), type text},
                    {"Initial",  each Text.Split(_,"#(lf)"), type text},
                    {"Age",      each Text.Split(_,"#(lf)"), type text}
                }
            )
</code>```

Now each column is a list of lists which you can combine into one long list using List.Combine and you can glue these columns together to make table with Table.FromColumns.

```<code>= Table.FromColumns(
      {
          List.Combine(TextSplit[Name]),
          List.Combine(TextSplit[Initial]),
          List.Combine(TextSplit[Age])
      },
      {"Name", "Initial", "Age"}
  )
</code>```

Putting this together, the whole query looks like this:

```<code>let
    Source = <Your data source>
    TextSplit = Table.TransformColumns(Source,{{"Name",  each Text.Split(_,"#(lf)"), type text},{"Initial",  each Text.Split(_,"#(lf)"), type text},{"Age",  each Text.Split(_,"#(lf)"), type text}}),
    FromColumns = Table.FromColumns({List.Combine(TextSplit[Name]),List.Combine(TextSplit[Initial]),List.Combine(TextSplit[Age])},{"Name","Initial","Age"})
in
    FromColumns
</code>```

Title: How to split a row where there's 2 data in each cells separated by a carriage return?

Body:
Someone gives me a file with, sometimes, inadequate data.

Data should be like this :

+---------+-----------+--------+
| Name    | Initial   | Age    |
+---------+-----------+--------+
| Jack    | J         | 43     |
+---------+-----------+--------+
| Nicole  | N         | 12     |
+---------+-----------+--------+
| Mark    | M         | 22     |
+---------+-----------+--------+
| Karine  | K         | 25     |
+---------+-----------+--------+

Sometimes it comes like this tho :

+---------+-----------+--------+
| Name    | Initial   | Age    |
+---------+-----------+--------+
| Jack    | J         | 43     |
+---------+-----------+--------+
| Nicole  | N         | 12     |
| Mark    | M         | 22     |
+---------+-----------+--------+
| Karine  | K         | 25     |
+---------+-----------+--------+

As you can see, Nicole and Mark are put in the same row, but the data are separated by a carriage return.

I can do split by row, but it demultiply the data :

+---------+-----------+--------+
| Nicole  | N         | 12     |
|         | M         | 22     |
+---------+-----------+--------+
| Mark    | N         | 12     |
|         | M         | 22     |
+---------+-----------+--------+

Which make me lose that Mark is associated with the "2nd row" of data.

(The data here is purely an example)

Body:
One way to do this is to transform each cell into a list by doing a Text.Split on the line feed / carriage return symbol.

TextSplit = Table.TransformColumns(Source,
                {
                    {"Name",     each Text.Split(_,"#(lf)"), type text},
                    {"Initial",  each Text.Split(_,"#(lf)"), type text},
                    {"Age",      each Text.Split(_,"#(lf)"), type text}
                }
            )

Now each column is a list of lists which you can combine into one long list using List.Combine and you can glue these columns together to make table with Table.FromColumns.

= Table.FromColumns(
      {
          List.Combine(TextSplit[Name]),
          List.Combine(TextSplit[Initial]),
          List.Combine(TextSplit[Age])
      },
      {"Name", "Initial", "Age"}
  )

Putting this together, the whole query looks like this:

let
    Source = <Your data source>
    TextSplit = Table.TransformColumns(Source,{{"Name",  each Text.Split(_,"#(lf)"), type text},{"Initial",  each Text.Split(_,"#(lf)"), type text},{"Age",  each Text.Split(_,"#(lf)"), type text}}),
    FromColumns = Table.FromColumns({List.Combine(TextSplit[Name]),List.Combine(TextSplit[Initial]),List.Combine(TextSplit[Age])},{"Name","Initial","Age"})
in
    FromColumns


问:
How do I get my Google Map to display in .NetCore web application?
I'm follow the tutorial from https://developers.google.com/maps/documentation/javascript/importing_data. when I run my app I can see in my development tool that I get a 200 response from the server but my map does not display. I have no console errors.

I've got my API key from google cloud. I'm using the Maps JavaScript API. My billing is enabled. This is a clean .Net core web application.

index.html

```<code><div id="map"></div>
    <script>
        var map;
        function initMap() {
            map = new google.maps.Map(document.getElementById('map'), {
                zoom: 2,
                center: new google.maps.LatLng(2.8,-187.3),
                mapTypeId: 'terrain'
            });

            // Create a <script> tag and set the USGS URL as the source.
            var script = document.createElement('script');
            // This example uses a local copy of the GeoJSON stored at
            // http://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/2.5_week.geojsonp
            script.src = 'https://developers.google.com/maps/documentation/javascript/examples/json/earthquake_GeoJSONP.js';
            document.getElementsByTagName('head')[0].appendChild(script);
        }

// Loop through the results array and place a marker for each
// set of coordinates.
        window.eqfeed_callback = function(results) {
            for (var i = 0; i < results.features.length; i++) {
                var coords = results.features[i].geometry.coordinates;
                var latLng = new google.maps.LatLng(coords[1],coords[0]);
                var marker = new google.maps.Marker({
                    position: latLng,
                    map: map
                });
            }
        }
    </script>
<script async defer
        src="https://maps.googleapis.com/maps/api/js?key=MY_API_KEY&callback=initMap">
</script>
</code>```

site.css

```<code>/* Always set the map height explicitly to define the size of the div
       * element that contains the map. */
#map {
    height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html, body {
    height: 100%;
    margin: 0;
    padding: 0;
}
</code>```

When I run the app on localhost or Azure my browser does not display a map. Why is my map not displaying?

答: I resolved this issue my creating a new controller action, and view. I then add the JavaScript and the HTML code to the newly created view and navigate to that controller action from the browser and google map displayed as expected.</p>

Body:
I'm follow the tutorial from https://developers.google.com/maps/documentation/javascript/importing_data. when I run my app I can see in my development tool that I get a 200 response from the server but my map does not display. I have no console errors.

I've got my API key from google cloud. I'm using the Maps JavaScript API. My billing is enabled. This is a clean .Net core web application.

index.html

site.css

/* Always set the map height explicitly to define the size of the div
       * element that contains the map. */
#map {
    height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html, body {
    height: 100%;
    margin: 0;
    padding: 0;
}

When I run the app on localhost or Azure my browser does not display a map. Why is my map not displaying?


问:
gin-contrib/cors returns 404
I've got a golang REST API, which implements gin-contrib/cors. But when I call a POST request the preflight request (OPTIONS) returns a 404 result.

Here's a snippet of the implementation:

```<code>engine := gin.New()
group := engine.Group("/api/v1")

// Recovery middleware recovers from any panics and writes a 500 if there was one.
group.Use(gin.Recovery())

// Set cors and db middleware
engine.Use(cors.New(cors.Config{
    AllowOrigins:     []string{"*"},
    AllowMethods:     []string{"*"},
    AllowHeaders:     []string{"*"},
    AllowCredentials: true,
    MaxAge: 12 * time.Hour,
}))

// Register routes
group.POST("/customers", ctrl.SendRequest)
</code>```

答:
```<code>engine := gin.New()

engine.Use(func(c *gin.Context) {
    c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
    c.Writer.Header().Set("Access-Control-Allow-Credentials", "true")
    c.Writer.Header().Set("Access-Control-Allow-Headers", "Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, accept, origin, Cache-Control, X-Requested-With")
    c.Writer.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS, GET, PUT, DELETE")

    if c.Request.Method == "OPTIONS" {
        c.AbortWithStatus(204)
        return
    }

    c.Next()
})

</code>```

make sure you add CORS middleware before you adding group

Title: gin-contrib/cors returns 404

Body:
I've got a golang REST API, which implements gin-contrib/cors. But when I call a POST request the preflight request (OPTIONS) returns a 404 result.

Here's a snippet of the implementation:

engine := gin.New()
group := engine.Group("/api/v1")

// Recovery middleware recovers from any panics and writes a 500 if there was one.
group.Use(gin.Recovery())

// Set cors and db middleware
engine.Use(cors.New(cors.Config{
    AllowOrigins:     []string{"*"},
    AllowMethods:     []string{"*"},
    AllowHeaders:     []string{"*"},
    AllowCredentials: true,
    MaxAge: 12 * time.Hour,
}))

// Register routes
group.POST("/customers", ctrl.SendRequest)

Body:
engine := gin.New()

engine.Use(func(c *gin.Context) {
    c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
    c.Writer.Header().Set("Access-Control-Allow-Credentials", "true")
    c.Writer.Header().Set("Access-Control-Allow-Headers", "Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, accept, origin, Cache-Control, X-Requested-With")
    c.Writer.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS, GET, PUT, DELETE")

    if c.Request.Method == "OPTIONS" {
        c.AbortWithStatus(204)
        return
    }

    c.Next()
})

make sure you add CORS middleware before you adding group


问:
iOS crash : Unable to open a realm at Path
I am seeing a number of crashes on Crashlytics but unable to reproduce the the crash which is happening on app launch. Does anyone know how to reproduce the below crash. I have tried all the answers on Github and stackoverflow and no one has mentioned about reproducing this specific crash.
So if i do have a fix there is no way to test it except putting the fix in production and then assuming Crashlytics wont show crashes.

Please help.

Error:

Fatal error: 'try!' expression unexpectedly raised an error: Error Domain=io.realm Code=2 "Unable to open a realm at path '/var/mobile/Containers/Data/Application/03BA7C37-9852-4A01-8EF6-949E308EADCD/Documents/default.realm.lock': open() failed: Operation not permitted." UserInfo={Error Code=2, NSFilePath=/var/mobile/Containers/Data/Application/03BA7C37-9852-4A01-8EF6-949E308EADCD/Documents/default.realm.lock,

calling code

```<code>//passing the fileProtectionType as .none
RealmHelper.configureRealmFiles(with: .none)
</code>```

Sample code

```<code>   static func configureRealmFiles(with fileProtectionType: FileProtectionType) {
            guard let folderPath = realm.configuration.fileURL?.deletingLastPathComponent().path else {
                return
            }

            do {
                try FileManager.default.setAttributes([FileAttributeKey.protectionKey: fileProtectionType],
                                                      ofItemAtPath: folderPath)
            } catch {
                logI("Realm: Couldn't change Realm file protection type")
            }
        }
</code>```

答: Realm documentation has some information on how to handle this this error. Check if their instructions to downgrade file access attribute is suitable for your case.</p>

Body:
I am seeing a number of crashes on Crashlytics but unable to reproduce the the crash which is happening on app launch. Does anyone know how to reproduce the below crash. I have tried all the answers on Github and stackoverflow and no one has mentioned about reproducing this specific crash.
So if i do have a fix there is no way to test it except putting the fix in production and then assuming Crashlytics wont show crashes.

Please help.

Error:

Fatal error: 'try!' expression unexpectedly raised an error: Error Domain=io.realm Code=2 "Unable to open a realm at path '/var/mobile/Containers/Data/Application/03BA7C37-9852-4A01-8EF6-949E308EADCD/Documents/default.realm.lock': open() failed: Operation not permitted." UserInfo={Error Code=2, NSFilePath=/var/mobile/Containers/Data/Application/03BA7C37-9852-4A01-8EF6-949E308EADCD/Documents/default.realm.lock,

calling code

//passing the fileProtectionType as .none
RealmHelper.configureRealmFiles(with: .none)

Sample code

   static func configureRealmFiles(with fileProtectionType: FileProtectionType) {
            guard let folderPath = realm.configuration.fileURL?.deletingLastPathComponent().path else {
                return
            }

            do {
                try FileManager.default.setAttributes([FileAttributeKey.protectionKey: fileProtectionType],
                                                      ofItemAtPath: folderPath)
            } catch {
                logI("Realm: Couldn't change Realm file protection type")
            }
        }


问:
Unique Index Fail
I created a unique index for employee IDs to an existing table.  I did a test and entered an employee ID already saved in the database, and the database still saved it.  When I do a search on that ID it lists both records.

Test the index by inserting a record with a duplicate employee ID

```<code>CREATE INDEX empid_index ON staff (empId)
</code>```

Expected an error message of a duplicated ID, but no error came up, the record was still saved.

答:
Don't create unique indexes: add unique constraints to the table instead. For example:

```<code>create table staff (
  ...
  constraint unique_empid unique (empid),
  ...
);
</code>```

Even though unique indexes will prevent you from inserting duplicate rows with that value, you will be missing other features of the constraint, such as exporting foreign keys, that you may need later on.

Title: Unique Index Fail

Body:
I created a unique index for employee IDs to an existing table.  I did a test and entered an employee ID already saved in the database, and the database still saved it.  When I do a search on that ID it lists both records.

Test the index by inserting a record with a duplicate employee ID

CREATE INDEX empid_index ON staff (empId)

Expected an error message of a duplicated ID, but no error came up, the record was still saved.

Body:
Don't create unique indexes: add unique constraints to the table instead. For example:

create table staff (
  ...
  constraint unique_empid unique (empid),
  ...
);

Even though unique indexes will prevent you from inserting duplicate rows with that value, you will be missing other features of the constraint, such as exporting foreign keys, that you may need later on.


问:
WiFi packet sniffing
I am trying to find out specifics of the communication between a DJI Osmo Action camera and the Android vendor app (https://play.google.com/store/apps/details?id=dji.mimo). The camera communicates over WiFi (Bluetooth is disabled on the Android phone) with the app but all packet scanners catch zero packets (for instance this one: https://play.google.com/store/apps/details?id=app.greyshirts.sslcapture). I can capture packets with the same sniffer apps between other devices and apps.

Why are no packets captured for this specific camera and app? Even if the data is encrypted and cannot be decoded using the VPN/certificate trick: is there a way to get the encrypted packets at least?

Regards,

答: You can use Charles Proxy in your android device. I don't know if there is a version for android, I use it in iOS. All traffic between your android and camera will be through the proxy and the application will allow you to see all sent packets in a human readable form. If there is not an app for android, you can install it in your windows machine and configure your android emulator for using it. There are plenty of tutorials on how to configure your emulator to work with Charles Proxy.</p>

Title: WiFi packet sniffing


问:
androidTest not compiling, showing cannot resolve symbol
I'm trying to add instrumented test using Espresso in my android project.

I've added all necessary libs, besides adding AndroidJUnitRunner as the testInstrumentationRunner:

 build.gradle">

But for some reason, the imports are not working in instrumented test file:

But the local test file is getting the imports properly:

I've also added junit as androidTestImplementation, but makes no difference:

```<code>androidTestImplementation 'junit:junit:4.12'
</code>```

This is why I cannot run the test file.

If I run the file anyway, I get this error:

```<code>Process finished with exit code 1
Class not found: "com.mcp.shippax.MainActivityEspressoTest"Empty test suite.
</code>```

I cannot understand why this is happening (numerous grade syncs/invalidate caches/restarts), when the setup is so straight and simple.

I don't remember making any project changes other than converting most of my source files to Kotlin, including the test files. But later I reverted the test files back to java again.

答:
I had the same issue. I've had various build types for dev and prod environments and what helped me, was to specify testBuildType like in this answer https://stackoverflow.com/a/34778780/9736105.

So something like this:

```<code>android {

    ...

    testBuildType "<my-build-type>"

    buildTypes {
        <my-build-type> {
            ...
        }
        ....
    }
}
</code>```

After I did that and set my build variant to that build type, I was able to resolve all dependecies.

Body:
I'm trying to add instrumented test using Espresso in my android project.

I've added all necessary libs, besides adding AndroidJUnitRunner as the testInstrumentationRunner:

 build.gradle">

But for some reason, the imports are not working in instrumented test file:

But the local test file is getting the imports properly:

I've also added junit as androidTestImplementation, but makes no difference:

androidTestImplementation 'junit:junit:4.12'

This is why I cannot run the test file.

If I run the file anyway, I get this error:

Process finished with exit code 1
Class not found: "com.mcp.shippax.MainActivityEspressoTest"Empty test suite.

I cannot understand why this is happening (numerous grade syncs/invalidate caches/restarts), when the setup is so straight and simple.

I don't remember making any project changes other than converting most of my source files to Kotlin, including the test files. But later I reverted the test files back to java again.

Body:
I had the same issue. I've had various build types for dev and prod environments and what helped me, was to specify testBuildType like in this answer https://stackoverflow.com/a/34778780/9736105.

So something like this:

android {

    ...

    testBuildType "<my-build-type>"

    buildTypes {
        <my-build-type> {
            ...
        }
        ....
    }
}

After I did that and set my build variant to that build type, I was able to resolve all dependecies.


问:
I am trying to download an image from a link and display it in an image view, but the line imgView.setImageBitmap(myImg); is throwing some error
I am trying to get an image from the internet through a link and display it on an imageView with the press of a button but the image won't display. After some debugging I found out that the line
    imgView.setImageBitmap(myImg);
is throwing an exception.

```<code>public class MainActivity extends AppCompatActivity {
    ImageView imgView;

public void imageFromWeb(View view){

    imageDownloader task = new imageDownloader();
    Bitmap myImg;
    try{
        myImg = task.execute("https://upload.wikimedia.org/wikipedia/commons/4/40/R_federer.jpg").get();
        imgView.setImageBitmap(myImg);
    }catch(Exception e){
        Log.i("check","error");
        e.printStackTrace();
    }

}

public class imageDownloader extends AsyncTask<String, Void, Bitmap>{

    @Override
    protected Bitmap doInBackground(String... urls) {
        URL url;
        HttpURLConnection urlConnection;
        try {
            url = new URL(urls[0]);
            urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.connect();
            InputStream inputStream = urlConnection.getInputStream();
            Bitmap img = BitmapFactory.decodeStream(inputStream);
            return img;

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    imgView = findViewById(R.id.imageView);
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}
</code>```

}

When I run the app and click the button I see that the "check error" line is printed which I log.i in the catch block of imageFromWeb function, along with

```<code>2019-05-28 10:29:13.515 4764-4764/com.ashwin.imagefromweb I/Choreographer: Skipped 53 frames!  The application may be doing too much work on its main thread.
</code>```

What is going wrong here? Thanks a lot!

答:
Try using Glide for accessing images from url</p>

```<code>Glide.with(this)
        .load("url here") // image url
        .placeholder(R.drawable.placeholder) // any placeholder to load at start
        .error(R.drawable.imagenotfound)  // any image in case of error
        .override(200, 200); // resizing
        .centerCrop();
        .into(imageView);  // imageview object
</code>```

Body:
I am trying to get an image from the internet through a link and display it on an imageView with the press of a button but the image won't display. After some debugging I found out that the line
    imgView.setImageBitmap(myImg);
is throwing an exception.

public class MainActivity extends AppCompatActivity {
    ImageView imgView;

public void imageFromWeb(View view){

    imageDownloader task = new imageDownloader();
    Bitmap myImg;
    try{
        myImg = task.execute("https://upload.wikimedia.org/wikipedia/commons/4/40/R_federer.jpg").get();
        imgView.setImageBitmap(myImg);
    }catch(Exception e){
        Log.i("check","error");
        e.printStackTrace();
    }

}

public class imageDownloader extends AsyncTask<String, Void, Bitmap>{

    @Override
    protected Bitmap doInBackground(String... urls) {
        URL url;
        HttpURLConnection urlConnection;
        try {
            url = new URL(urls[0]);
            urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.connect();
            InputStream inputStream = urlConnection.getInputStream();
            Bitmap img = BitmapFactory.decodeStream(inputStream);
            return img;

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    imgView = findViewById(R.id.imageView);
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}

}

When I run the app and click the button I see that the "check error" line is printed which I log.i in the catch block of imageFromWeb function, along with

2019-05-28 10:29:13.515 4764-4764/com.ashwin.imagefromweb I/Choreographer: Skipped 53 frames!  The application may be doing too much work on its main thread.

What is going wrong here? Thanks a lot!

Body:
Try using Glide for accessing images from url

Glide.with(this)
        .load("url here") // image url
        .placeholder(R.drawable.placeholder) // any placeholder to load at start
        .error(R.drawable.imagenotfound)  // any image in case of error
        .override(200, 200); // resizing
        .centerCrop();
        .into(imageView);  // imageview object


问:
How to detect the browser's format for input[type=date]
Using Javascript, how would it be possible to detect the format of dates in date input fields (input[type=date])?

Tools like Modernizr only detect the capability of using an HTML5 datepicker (desirable especially for mobile devices, and their UI for selecting dates). However, I haven't been able to find any solution on detecting the format used by the browser.

I have an input field like this:

```<code><input type="date" class="border-radius" min="2013-12-21" max="2015-12-20" data-persist-local="FromDate">
</code>```

The value is entered with a jQuery call .val() if it's found in localStorage. I thought that since valid date formats for min and max attributes are in valid ISO format, getting the value of the field would return the same format. It turns out, it doesn't.

Testing on a Chrome browser (31.0.1650.63 m) with Swedish as primary language gives the ISO format, but using the same browser with Danish as primary language reverses the date format to dd-mm-yyyy instead of yyyy-mm-dd. I suspect it's the same for other locales.

I'm not looking to change the input format - and ideally there would be a function to get the date by a consistent "wire format" but I haven't found a way to get anything but the display format.

How do I detect the format of the input field, and consistently convert to a valid Date in JS, and back again?

答:
I think I got an easier solution. Not sure if it will work at any browser, but assuming that javascript date function uses same local format, this would work:

```<code> $(".date").on("change", function () {
      var selectedDate = new Date(jQuery(this).val());

      var selectedDateFormat = selectedDate.toLocaleDateString()
          .replace(selectedDate.getDate(), "DD")
          .replace(selectedDate.getMonth()+1, "MM")
          .replace(selectedDate.getFullYear(), "YYYY");

           console.log(selectedDateFormat);
 });
</code>```

But anyway, reaching at this point we might not need this, as the point is to use any browser date format, and send it on the format we desire if Im not wrong. In this case I would do it in another way wich is the following:

```<code>$(".date").on("change", function () {
   var selectedDate = new Date(jQuery(this).val());
   this.setAttribute('value',
   (selectedDate.getMonth() + 1) +
   '/' + selectedDate.getDate() +
   '/' + selectedDate.getFullYear());
});
</code>```

Body:
Using Javascript, how would it be possible to detect the format of dates in date input fields (input[type=date])?

Tools like Modernizr only detect the capability of using an HTML5 datepicker (desirable especially for mobile devices, and their UI for selecting dates). However, I haven't been able to find any solution on detecting the format used by the browser.

I have an input field like this:

<input type="date" class="border-radius" min="2013-12-21" max="2015-12-20" data-persist-local="FromDate">

The value is entered with a jQuery call .val() if it's found in localStorage. I thought that since valid date formats for min and max attributes are in valid ISO format, getting the value of the field would return the same format. It turns out, it doesn't.

Testing on a Chrome browser (31.0.1650.63 m) with Swedish as primary language gives the ISO format, but using the same browser with Danish as primary language reverses the date format to dd-mm-yyyy instead of yyyy-mm-dd. I suspect it's the same for other locales.

I'm not looking to change the input format - and ideally there would be a function to get the date by a consistent "wire format" but I haven't found a way to get anything but the display format.

How do I detect the format of the input field, and consistently convert to a valid Date in JS, and back again?

Body:
I think I got an easier solution. Not sure if it will work at any browser, but assuming that javascript date function uses same local format, this would work:

 $(".date").on("change", function () {
      var selectedDate = new Date(jQuery(this).val());

      var selectedDateFormat = selectedDate.toLocaleDateString()
          .replace(selectedDate.getDate(), "DD")
          .replace(selectedDate.getMonth()+1, "MM")
          .replace(selectedDate.getFullYear(), "YYYY");

           console.log(selectedDateFormat);
 });

But anyway, reaching at this point we might not need this, as the point is to use any browser date format, and send it on the format we desire if Im not wrong. In this case I would do it in another way wich is the following:

$(".date").on("change", function () {
   var selectedDate = new Date(jQuery(this).val());
   this.setAttribute('value',
   (selectedDate.getMonth() + 1) +
   '/' + selectedDate.getDate() +
   '/' + selectedDate.getFullYear());
});


问:
Different behavior on read() depending on file descriptor representing a file, anonymous pipe or socket when writing to non writable memory
I have the following code:

```<code>#include <sys/mman.h>
#include <unistd.h>
#include <cstdio>

int main() {
        char *p = (char *)mmap(0, 0x3000, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
        munmap(p + 0x2000, 0x1000);
        p += 0x800;
        printf("%zd\n", read(0, p, 0x3000));
        return 0;
}
</code>```

When compiling it and running it with input that will write past writable memory, I get different behaviors based on the way this input is fed:

```<code>$ python3 -c 'print("A"*0x3000)' | ./test
4096
$ python3 -c 'print("A"*0x3000)' > input.bin; ./test < input.bin
6144
$ nc.traditional -l -p 1337 -e ./test &
[1] 25855
$ python3 -c 'print("A"*0x3000)' | nc localhost 1337
-1
[1]+  Done                    nc.traditional -l -p 1337 -e ./test
</code>```

I would have expected the read() call to return the same result in all cases, but this is not the case. Why do I get different behaviors?

答:
The strace output from this command shows that the full 12288 (0x3000) bytes are written in one go:

```<code>$ strace python3 -c 'print("A"*0x3000)' | ./test
...
write(1, "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"..., 12288) = 12288
...
</code>```

Using strace on the ./test command at the other end of the pipe shows that only 4096 (0x1000) bytes are read:

```<code>$ python3 -c 'print("A"*0x3000)' | strace ./test
...
read(0, "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"..., 12288) = 4096
...
</code>```

If the standard input for ./test comes from input.bin (which contains 12288 'A's followed by a newline), strace shows that 6144 (0x1800) bytes are read:

```<code>$ strace ./test < input.bin
...
read(0, "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"..., 12288) = 6144
...
</code>```

I think the explanation can only be found by delving into the kernel's code for reading from a pipe in the pipe_read function in "fs/pipe.c". Internally, the pipe contains a cyclic array of struct pipe_buffer, each of which contains a pointer to a page of data. The pipe_read function loops through these buffers copying the contents to the user until all requested data has been read, there is nothing left in the pipe (after waiting for more data from the writer when in blocking mode), or a fault occurs when copying data to the user. The reason why only 4096 bytes are returned instead of 6144 when the fault occurs seems to be due to this bit of code:

```<code>        written = copy_page_to_iter(buf->page, buf->offset, chars, to);
        if (unlikely(written < chars)) {
            if (!ret)
                ret = -EFAULT;
            break;
        }
        ret += chars;
        buf->offset += chars;
        buf->len -= chars;
</code>```

(The above section is from Linux kernel version 4.19.)

Here, chars is the amount to be copied from the current pipe buffer, written is the amount that was actually copied, and ret is the return value of the function, which is normally the number of bytes read. The initial value of ret is 0. written normally gets set to chars unless an address fault occurs, in which case it will be less than chars.

The fault occurs when copying the second page from the pipe. The first page was copied successfully so ret will be 4096. When copying the second page, an address fault occurs in the user buffer after 6144 - 4096 = 2048 (0x800) bytes, so the break; statement is reached to break out of the loop before the ret += chars; statement is reached. ret is not set to -EFAULT because it is non-zero. However, the partial copy of 2048 bytes from the second page of the pipe to the user buffer have been disregarded as far as the returned value of the pipe_buf function indicates. (The disregarded data is not discarded from the pipe. The position in the pipe is only moved on after a successful copy, so a subsequent call to pipe_read will continue from the same point.)

Note that although read only returned 4096, it seems likely that it actually copied 6144 bytes to the user buffer. This could be confirmed by examining the buffer contents from p + 4096 onwards after returning from the read call.

I'm sure the relevant part of the pipe_read function could be rewritten to properly account for the partially copied portion, but I don't know if the core kernel developers would consider it a bug worth fixing.  For example, a fix might replace the above code with something like the following (untested) code:

```<code>        written = copy_page_to_iter(buf->page, buf->offset, chars, to);
        ret += written;
        buf->offset += written;
        buf->len -= written;
        if (unlikely(written < chars)) {
            if (!ret)
                ret = -EFAULT;
            break;
        }
</code>```

I am pretty sure that your ./test program would manage to read 6144 bytes from the pipe with this change to the kernel code.

Body:
I have the following code:

#include <sys/mman.h>
#include <unistd.h>
#include <cstdio>

int main() {
        char *p = (char *)mmap(0, 0x3000, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
        munmap(p + 0x2000, 0x1000);
        p += 0x800;
        printf("%zd\n", read(0, p, 0x3000));
        return 0;
}

When compiling it and running it with input that will write past writable memory, I get different behaviors based on the way this input is fed:

$ python3 -c 'print("A"*0x3000)' | ./test
4096
$ python3 -c 'print("A"*0x3000)' > input.bin; ./test < input.bin
6144
$ nc.traditional -l -p 1337 -e ./test &
[1] 25855
$ python3 -c 'print("A"*0x3000)' | nc localhost 1337
-1
[1]+  Done                    nc.traditional -l -p 1337 -e ./test

I would have expected the read() call to return the same result in all cases, but this is not the case. Why do I get different behaviors?

Body:
The strace output from this command shows that the full 12288 (0x3000) bytes are written in one go:

$ strace python3 -c 'print("A"*0x3000)' | ./test
...
write(1, "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"..., 12288) = 12288
...

Using strace on the ./test command at the other end of the pipe shows that only 4096 (0x1000) bytes are read:

$ python3 -c 'print("A"*0x3000)' | strace ./test
...
read(0, "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"..., 12288) = 4096
...

If the standard input for ./test comes from input.bin (which contains 12288 'A's followed by a newline), strace shows that 6144 (0x1800) bytes are read:

$ strace ./test < input.bin
...
read(0, "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"..., 12288) = 6144
...

I think the explanation can only be found by delving into the kernel's code for reading from a pipe in the pipe_read function in "fs/pipe.c". Internally, the pipe contains a cyclic array of struct pipe_buffer, each of which contains a pointer to a page of data. The pipe_read function loops through these buffers copying the contents to the user until all requested data has been read, there is nothing left in the pipe (after waiting for more data from the writer when in blocking mode), or a fault occurs when copying data to the user. The reason why only 4096 bytes are returned instead of 6144 when the fault occurs seems to be due to this bit of code:

        written = copy_page_to_iter(buf->page, buf->offset, chars, to);
        if (unlikely(written < chars)) {
            if (!ret)
                ret = -EFAULT;
            break;
        }
        ret += chars;
        buf->offset += chars;
        buf->len -= chars;

(The above section is from Linux kernel version 4.19.)

Here, chars is the amount to be copied from the current pipe buffer, written is the amount that was actually copied, and ret is the return value of the function, which is normally the number of bytes read. The initial value of ret is 0. written normally gets set to chars unless an address fault occurs, in which case it will be less than chars.

The fault occurs when copying the second page from the pipe. The first page was copied successfully so ret will be 4096. When copying the second page, an address fault occurs in the user buffer after 6144 - 4096 = 2048 (0x800) bytes, so the break; statement is reached to break out of the loop before the ret += chars; statement is reached. ret is not set to -EFAULT because it is non-zero. However, the partial copy of 2048 bytes from the second page of the pipe to the user buffer have been disregarded as far as the returned value of the pipe_buf function indicates. (The disregarded data is not discarded from the pipe. The position in the pipe is only moved on after a successful copy, so a subsequent call to pipe_read will continue from the same point.)

Note that although read only returned 4096, it seems likely that it actually copied 6144 bytes to the user buffer. This could be confirmed by examining the buffer contents from p + 4096 onwards after returning from the read call.

I'm sure the relevant part of the pipe_read function could be rewritten to properly account for the partially copied portion, but I don't know if the core kernel developers would consider it a bug worth fixing.  For example, a fix might replace the above code with something like the following (untested) code:

        written = copy_page_to_iter(buf->page, buf->offset, chars, to);
        ret += written;
        buf->offset += written;
        buf->len -= written;
        if (unlikely(written < chars)) {
            if (!ret)
                ret = -EFAULT;
            break;
        }

I am pretty sure that your ./test program would manage to read 6144 bytes from the pipe with this change to the kernel code.