问:
Error package grid does not have a namespace
I'm using R.3.3.1 in RStudio 0.99.903 on a work PC.

I'm having the same error message when trying to use both ggplot2 and tidytext:  although I managed to install both packages, when i launch them i get this error message:

```<code>Error : package ‘grid’ does not have a namespace
</code>```

At first i thought this meant grid was missing but i read that it's now part of base so i don't understand why it doesn't load when i run library(grid)...  Adding to my confusion is the fact that i can only see gridBase and gridExtra in my list of packages, not grid.  And when i try library(gridBase) i also get the same "Error : package ‘grid’ does not have a namespace" message.

Here's my session info:

sessionInfo()
      R version 3.3.1 (2016-06-21)
      Platform: x86_64-w64-mingw32/x64 (64-bit)
      Running under: Windows 7 x64 (build 7601) Service Pack 1

```<code>locale:
[1] LC_COLLATE=English_United Kingdom.1252  LC_CTYPE=English_United     Kingdom.1252    LC_MONETARY=English_United Kingdom.1252
[4] LC_NUMERIC=C                            LC_TIME=English_United Kingdom.1252

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

other attached packages:
[1] stringr_1.0.0   tidyr_0.5.1     scales_0.4.0    lubridate_1.5.6 purrr_0.2.2     dplyr_0.5.0

loaded via a namespace (and not attached):
 [1] Rcpp_0.12.6      assertthat_0.1   R6_2.1.2         plyr_1.8.4       DBI_0.4-1        magrittr_1.5     stringi_1.1.1
 [8] lazyeval_0.2.0   tools_3.3.1      munsell_0.4.3    colorspace_1.2-6 tibble_1.1
</code>```

i've looked everywhere online and tried various approaches (using an older version of R, changing the default CRAN in my RStudio global options, unticking "use internet explorer library proxy", remove and re-install the packages from R not RStudio, both GUI and Shell...) but nothing works...

答:
This happened to me after unloading packages that I thought I was not using. "Grid" was a package listed in the Packages window in Rstudio and I deleted it along with about 20 others.  Not having "grid" prevented loading "ggplot2" which in turn prevented loading "rstan".

I recovered by reinstalling R, presuming that such a fundamental package must be part of the base install since it was not on CRAN. After reinstall, the error related to "grid" disappeared, but the package "scales" was now identified as missing. "Scales" was on CRAN and easily loaded. library(ggplot2) appear to be working again.

Body:
I'm using R.3.3.1 in RStudio 0.99.903 on a work PC.

I'm having the same error message when trying to use both ggplot2 and tidytext:  although I managed to install both packages, when i launch them i get this error message:

Error : package ‘grid’ does not have a namespace

At first i thought this meant grid was missing but i read that it's now part of base so i don't understand why it doesn't load when i run library(grid)...  Adding to my confusion is the fact that i can only see gridBase and gridExtra in my list of packages, not grid.  And when i try library(gridBase) i also get the same "Error : package ‘grid’ does not have a namespace" message.

Here's my session info:

sessionInfo()
      R version 3.3.1 (2016-06-21)
      Platform: x86_64-w64-mingw32/x64 (64-bit)
      Running under: Windows 7 x64 (build 7601) Service Pack 1

locale:
[1] LC_COLLATE=English_United Kingdom.1252  LC_CTYPE=English_United     Kingdom.1252    LC_MONETARY=English_United Kingdom.1252
[4] LC_NUMERIC=C                            LC_TIME=English_United Kingdom.1252

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

other attached packages:
[1] stringr_1.0.0   tidyr_0.5.1     scales_0.4.0    lubridate_1.5.6 purrr_0.2.2     dplyr_0.5.0

loaded via a namespace (and not attached):
 [1] Rcpp_0.12.6      assertthat_0.1   R6_2.1.2         plyr_1.8.4       DBI_0.4-1        magrittr_1.5     stringi_1.1.1
 [8] lazyeval_0.2.0   tools_3.3.1      munsell_0.4.3    colorspace_1.2-6 tibble_1.1

i've looked everywhere online and tried various approaches (using an older version of R, changing the default CRAN in my RStudio global options, unticking "use internet explorer library proxy", remove and re-install the packages from R not RStudio, both GUI and Shell...) but nothing works...


来源: stackexchange

问:
C programming - segmentation fault (core dump)
I am continuously getting a seg fault (core dump) each time that I run it, no matter what I change or the fact that is compiling fine! Not sure where I am making the mistake? Any suggestions?</p>

```<code>int main (int argc, char** argv)
{
    FILE *output;
    if ((output = fopen("output", "w")) == NULL)
    {
            printf ("cannot open the file input\n");
            exit (EXIT_FAILURE);
    }

    int data = 1;
    while (scanf("%d", data) > 0)
    {
            print(output, data);
    }

    fclose(output);
    return (0);
}
void print(FILE* output, int data)
{
    fprintf(output, "%d\n", data);
    return;
}
</code>```

答:
First of all, as someone said here before, you need to pass an adress of a variable to scanf function, so it looks like this:

```<code>    scanf("%d", &data)
</code>```

But using it in a while loop like you do won't work correctly, since scanf does not return a value you assign to a variable.
You have to use it like this:

```<code>   while(data > 0)
   {
       scanf("%d", &data);
       print(output, data);
   }
</code>```

And in this case, I believe a do-while loop is more suitable, rather than while loop:

```<code>   do
   {
       scanf("%d", &data);
       print(output, data);
   } while (data > 0);
</code>```

This way it will work the way You expect it to work.

You also forgot to specify a filetype of Your output file:

```<code>    if ((output = fopen("output", "w")) == NULL)
</code>```

should probably be

```<code>    if ((output = fopen("output.txt", "w")) == NULL)
</code>```

I posted a complete solution for You here: https://pastebin.com/vpK9i6Wk

ContentLicense: CC BY-SA 3.0

Body:
I am continuously getting a seg fault (core dump) each time that I run it, no matter what I change or the fact that is compiling fine! Not sure where I am making the mistake? Any suggestions?

int main (int argc, char** argv)
{
    FILE *output;
    if ((output = fopen("output", "w")) == NULL)
    {
            printf ("cannot open the file input\n");
            exit (EXIT_FAILURE);
    }

    int data = 1;
    while (scanf("%d", data) > 0)
    {
            print(output, data);
    }

    fclose(output);
    return (0);
}
void print(FILE* output, int data)
{
    fprintf(output, "%d\n", data);
    return;
}

Body:
First of all, as someone said here before, you need to pass an adress of a variable to scanf function, so it looks like this:

    scanf("%d", &data)

But using it in a while loop like you do won't work correctly, since scanf does not return a value you assign to a variable.
You have to use it like this:

   while(data > 0)
   {
       scanf("%d", &data);
       print(output, data);
   }

And in this case, I believe a do-while loop is more suitable, rather than while loop:

   do
   {
       scanf("%d", &data);
       print(output, data);
   } while (data > 0);

This way it will work the way You expect it to work.

You also forgot to specify a filetype of Your output file:

    if ((output = fopen("output", "w")) == NULL)

should probably be

    if ((output = fopen("output.txt", "w")) == NULL)

I posted a complete solution for You here: https://pastebin.com/vpK9i6Wk


问:
Handle HTTP error with NSURLSession?
I'm trying to send a HTTP request with NSURLSession. It works fine, but when the server doesn't respond I can't find where the HTTP error code is stored. The third parameter of completionHandler is just a very general NSError. I read the reference of NSURLResponse but found nothing.

```<code>NSURLSessionDataTask *dataTask =
    [session dataTaskWithRequest:[self postRequestWithURLString:apiEntry parameters:parameters]
         completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
             if(!error) NSLog([[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
         }
    ];
[dataTask resume];
</code>```

答:
you could try something like this. I've created a simple method that will be able to post a data into server and get the server response. You can get the server status code via NSHTTPURLResponse class.
Hope will help :)</p>

```<code>-(void) POST:(NSURL *) url URLparameters:(NSString *) parameters success:(void (^)(NSURLSessionDataTask *  task, id   responseObject)) successHandler errorHandler:(void (^)(NSURLSessionDataTask *  task, NSError *  error)) errorHandler{
     requestBody = [[NSMutableURLRequest alloc]
                   initWithURL:url
                   cachePolicy: NSURLRequestUseProtocolCachePolicy
                   timeoutInterval:60.0];
    [requestBody setHTTPMethod:@"POST"];
    [requestBody setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    [requestBody setHTTPBody:[NSData dataWithBytes:
                              [parameters UTF8String]length:strlen([parameters UTF8String])]];
    NSURLSession *session = [NSURLSession sessionWithConfiguration: sessionConfiguration delegate: self delegateQueue: [NSOperationQueue mainQueue]];

    NSURLSessionDataTask *task = [session dataTaskWithRequest:requestBody completionHandler:
                                  ^(NSData *data, NSURLResponse *response, NSError *error) {
                                      NSHTTPURLResponse* respHttp = (NSHTTPURLResponse*) response;

                                      if (respHttp.statusCode == SUCCESS) {
                                          NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
                                          successHandler(task, dictionary);
                                          NSLog(@"HTTP_STATUS: success %@", response);
                                      }else if (respHttp.statusCode == UNAUTHORIZE) {
                                          NSLog(@"HTTP_STATUS: anauthorize");
                                      }else if (respHttp.statusCode== BAD_REQUEST) {
                                          NSLog(@"HTTP_STATUS: badrequest");
                                      }else if (respHttp.statusCode == INTERNAL_SERVER_ERROR) {
                                          NSLog(@"HTTP_STATUS: internalerror");
                                      }else if (respHttp.statusCode== NOT_FOUND) {
                                          NSLog(@"HTTP_STATUS: internalerror");
                                      }
                                      errorHandler(task, error);
                                      return;
                                  }];
    [task resume];
}
</code>```

Title: Handle HTTP error with NSURLSession?

Body:
I'm trying to send a HTTP request with NSURLSession. It works fine, but when the server doesn't respond I can't find where the HTTP error code is stored. The third parameter of completionHandler is just a very general NSError. I read the reference of NSURLResponse but found nothing.

NSURLSessionDataTask *dataTask =
    [session dataTaskWithRequest:[self postRequestWithURLString:apiEntry parameters:parameters]
         completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
             if(!error) NSLog([[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
         }
    ];
[dataTask resume];

Body:
you could try something like this. I've created a simple method that will be able to post a data into server and get the server response. You can get the server status code via NSHTTPURLResponse class.
Hope will help :)

-(void) POST:(NSURL *) url URLparameters:(NSString *) parameters success:(void (^)(NSURLSessionDataTask *  task, id   responseObject)) successHandler errorHandler:(void (^)(NSURLSessionDataTask *  task, NSError *  error)) errorHandler{
     requestBody = [[NSMutableURLRequest alloc]
                   initWithURL:url
                   cachePolicy: NSURLRequestUseProtocolCachePolicy
                   timeoutInterval:60.0];
    [requestBody setHTTPMethod:@"POST"];
    [requestBody setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    [requestBody setHTTPBody:[NSData dataWithBytes:
                              [parameters UTF8String]length:strlen([parameters UTF8String])]];
    NSURLSession *session = [NSURLSession sessionWithConfiguration: sessionConfiguration delegate: self delegateQueue: [NSOperationQueue mainQueue]];

    NSURLSessionDataTask *task = [session dataTaskWithRequest:requestBody completionHandler:
                                  ^(NSData *data, NSURLResponse *response, NSError *error) {
                                      NSHTTPURLResponse* respHttp = (NSHTTPURLResponse*) response;

                                      if (respHttp.statusCode == SUCCESS) {
                                          NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
                                          successHandler(task, dictionary);
                                          NSLog(@"HTTP_STATUS: success %@", response);
                                      }else if (respHttp.statusCode == UNAUTHORIZE) {
                                          NSLog(@"HTTP_STATUS: anauthorize");
                                      }else if (respHttp.statusCode== BAD_REQUEST) {
                                          NSLog(@"HTTP_STATUS: badrequest");
                                      }else if (respHttp.statusCode == INTERNAL_SERVER_ERROR) {
                                          NSLog(@"HTTP_STATUS: internalerror");
                                      }else if (respHttp.statusCode== NOT_FOUND) {
                                          NSLog(@"HTTP_STATUS: internalerror");
                                      }
                                      errorHandler(task, error);
                                      return;
                                  }];
    [task resume];
}


问:
Could I use a pre-built CMS or should I build one from the ground-up?
I am working on a project for a client that started out as a simple CMS with pages, posts, and a directory. The client is constantly expanding the scope of this project with requirements for customization of just about everything. As a single developer, I am having trouble keeping up with the clients time-table. I have googled for software packages that might already exist that proved the features my client needs but I have not found anything. Does anyone know of any pre-built software that allows for the following customization or at least better words to describe this type of package?

Here are some examples of the customization that is requested:

A page or directory listing needs to be formatted from an admin-defined template. Within this template there needs to be admin-defined sections that contain admin-defined data types. (This is so the look and feel of the site can be maintained while users can easily build content, add listings, and etc.)

Advertising-tiles need to be able to be defined and populated globally and at page level.

All user generated content, pages, posts, and directory listings need to be associated with user and have flexibility to show all other user generated content for inter-linking between same users content.

Site would need billing/e-commerce system for premium listings, premium posts, advertising tiles, and etc.

Approval system for all user added or edited content (pages, posts, directory listings, etc.)

(asp.net and mvc are definitely preferable)

答: I've not had a change to use it, and I'm not sure if it will provide for you all of your demands or not, but I've heard a lot of great things about the project. Have you tried the open source project Drupal?</p>

ContentLicense: CC BY-SA 2.5


问:
Cloud SDK command gsutil config -a
I'm trying to include the credentials for my Google storage in my Dockerfile so that I don't have to do it every time I create a new Pod or another dies in Kubernetes.
So is there a way to put this command like this

```<code> gsutil config -a (Access Key) (Secret)
</code>```

rather than running the command

```<code> gsutil config -a
</code>```

and then inserting the  (Access Key) and (Secret) manually.

Thanks

答:
You can pass the input using echo and pipe it to gsutil.

Do keep in mind why the gsutil command does not accept command line args - commands are stored in history files in your shell and can easily leak your secrets if they contained these secrets as command line arguments.

So the following command will get stored in shell history (unless you prevent it in some other way) and could contain your secret.

```<code>$ echo -e "$ACCESS_KEY_ID\n$ACCESS_KEY_SECRET\n" | gsutil config -a

This command will configure HMAC credentials, but gsutil will use
OAuth2 credentials from the Cloud SDK by default. To make sure the
HMAC credentials are used, run: "gcloud config set
pass_credentials_to_gsutil false".

This command will create a boto config file at /Users/tuxdude/.boto
containing your credentials, based on your responses to the following
questions.

Boto config file "/Users/tuxdude/.boto" created. If you need to use a
proxy to access the Internet please see the instructions in that file.
What is your google access key ID? What is your google secret access key?
</code>```

Title: Cloud SDK command gsutil config -a

Body:
I'm trying to include the credentials for my Google storage in my Dockerfile so that I don't have to do it every time I create a new Pod or another dies in Kubernetes.
So is there a way to put this command like this

 gsutil config -a (Access Key) (Secret)

rather than running the command

 gsutil config -a

and then inserting the  (Access Key) and (Secret) manually.

Thanks

Body:
You can pass the input using echo and pipe it to gsutil.

Do keep in mind why the gsutil command does not accept command line args - commands are stored in history files in your shell and can easily leak your secrets if they contained these secrets as command line arguments.

So the following command will get stored in shell history (unless you prevent it in some other way) and could contain your secret.

$ echo -e "$ACCESS_KEY_ID\n$ACCESS_KEY_SECRET\n" | gsutil config -a

This command will configure HMAC credentials, but gsutil will use
OAuth2 credentials from the Cloud SDK by default. To make sure the
HMAC credentials are used, run: "gcloud config set
pass_credentials_to_gsutil false".

This command will create a boto config file at /Users/tuxdude/.boto
containing your credentials, based on your responses to the following
questions.

Boto config file "/Users/tuxdude/.boto" created. If you need to use a
proxy to access the Internet please see the instructions in that file.
What is your google access key ID? What is your google secret access key?


问:
jquery sorting function and prepend/insertAfter?
I have a function to sort list items based on the date and class of the list item. It's late and I am tired and frustrated, so not sure what I am missing here.

The function should first determine if the class is .pinned and sort them by date and insert them to the top of the list.

Then it should look at the date of the item (found in data-date) and if it is earlier than today, add the class .past sort them by date, and then insert them after the pinned items.

Lastly, it should sort the remaining items and insert them after the last item with the class of .past

here is the code:

```<code>//sort todo list-items by type and then date
function sortTodo() {
  var itemDate = "";
  var date = new Date();
  $(".todo-list-item").each(function() {
    var itemDate = new Date($(this).data("date"));
    if($(this).hasClass('pinned')) {
      $(".todo-list-item.pinned").sort(function(a,b) {
        return date > itemDate;
      }).each(function() {
          $(".todo-list").prepend(this);
      })
    } else if(date > itemDate) {
      $(this).addClass("past");
      $(".todo-list-item.past").sort(function(a,b) {
          return date > itemDate;
      }).each(function() {
          $(".todo-list").prepend(this);
      })
    } else {
      $(".todo-list-item").not(".pinned, .past").sort(function(a,b) {
        return date > itemDate;
      }).each(function() {
          $(".todo-list").append(this);
      })
    }
  });
}

$(document).ready(function() {
    sortTodo();
});
</code>```

CODE PEN DEMO

as of now, the script not placing pinned items to the top as desired, unless I add a new pinned item, and is not sorting by date after an items class changes or is removed.

答:
The reason that the pinned item is not at the top of your list of todos on first page load is because it is the first item in your list to get prepended to the todo list.

When the page loads, the first item is pinned so it gets prepended to the list. Then it keeps looping through the list until it finds the items whose date > itemDate and puts it before the pinned item.

To see what I mean: try changing your html by putting the pinned item as the last item in your unordered list.

*Sorry - I don't have enough rep to leave a comment...

Body:
I have a function to sort list items based on the date and class of the list item. It's late and I am tired and frustrated, so not sure what I am missing here.

The function should first determine if the class is .pinned and sort them by date and insert them to the top of the list.

Then it should look at the date of the item (found in data-date) and if it is earlier than today, add the class .past sort them by date, and then insert them after the pinned items.

Lastly, it should sort the remaining items and insert them after the last item with the class of .past

here is the code:

//sort todo list-items by type and then date
function sortTodo() {
  var itemDate = "";
  var date = new Date();
  $(".todo-list-item").each(function() {
    var itemDate = new Date($(this).data("date"));
    if($(this).hasClass('pinned')) {
      $(".todo-list-item.pinned").sort(function(a,b) {
        return date > itemDate;
      }).each(function() {
          $(".todo-list").prepend(this);
      })
    } else if(date > itemDate) {
      $(this).addClass("past");
      $(".todo-list-item.past").sort(function(a,b) {
          return date > itemDate;
      }).each(function() {
          $(".todo-list").prepend(this);
      })
    } else {
      $(".todo-list-item").not(".pinned, .past").sort(function(a,b) {
        return date > itemDate;
      }).each(function() {
          $(".todo-list").append(this);
      })
    }
  });
}

$(document).ready(function() {
    sortTodo();
});

CODE PEN DEMO

as of now, the script not placing pinned items to the top as desired, unless I add a new pinned item, and is not sorting by date after an items class changes or is removed.


问:
TemplateDoesNotExist at /admin/ admin/index.html
I am unable to access the admin interface in django 1.1.1 using localloop:8000/admin. It was working fine on Ubuntu 8.4 then I upgraded to Ubuntu 10.10 and the problem occurred.

In settings.py I have:

```<code>import os.path
PROJECT_DIR=os.path.dirname(__file__)

TEMPLATE_DIRS =(os.path.join(PROJECT_DIR,'templates'))
</code>```

This  was working fine on Ubuntu 8.04 but not in Ubuntu 10.10.

Any ideas on what goes wrong? Here is the traceback:

```<code>Environment:

Request Method: GET
Request URL: http://localhost:8000/admin/
Django Version: 1.1.1
Python Version: 2.6.6
Installed Applications:
['django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.sites',
 'django.contrib.admin',
 'hotweb.accounts',
 'django.contrib.flatpages',
 'messages',
 'hotweb.jchat']
Installed Middleware:
('django.middleware.common.CommonMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.flatpages.middleware.FlatpageFallbackMiddleware',
 'django.middleware.http.SetRemoteAddrFromForwardedFor')

Template Loader Error:
Django tried loading these templates, in this order:
Using loader django.template.loaders.filesystem.load_template_source:
/home/scorpion/Desktop/hotweb/templates/admin/index.html (File does not exist)
Using loader django.template.loaders.app_directories.load_template_source:
/usr/local/lib/python2.6/dist-packages/django/contrib/admin/templates/admin/index.html (File exists)

Traceback:
File "/usr/local/lib/python2.6/dist-packages/django/core/handlers/base.py" in get_response
  92.                 response = callback(request, *callback_args, **callback_kwargs)
File "/usr/local/lib/python2.6/dist-packages/django/contrib/admin/sites.py" in wrapper
  196.                 return self.admin_view(view, cacheable)(*args, **kwargs)
File "/usr/local/lib/python2.6/dist-packages/django/views/decorators/cache.py" in _wrapped_view_func
  44.         response = view_func(request, *args, **kwargs)
File "/usr/local/lib/python2.6/dist-packages/django/contrib/admin/sites.py" in inner
  186.             return view(request, *args, **kwargs)
File "/usr/local/lib/python2.6/dist-packages/django/views/decorators/cache.py" in _wrapped_view_func
  44.         response = view_func(request, *args, **kwargs)
File "/usr/local/lib/python2.6/dist-packages/django/contrib/admin/sites.py" in index
  374.             context_instance=context_instance
File "/usr/local/lib/python2.6/dist-packages/django/shortcuts/__init__.py" in render_to_response
  20.     return HttpResponse(loader.render_to_string(*args, **kwargs), **httpresponse_kwargs)
File "/usr/local/lib/python2.6/dist-packages/django/template/loader.py" in render_to_string
  103.         t = get_template(template_name)
File "/usr/local/lib/python2.6/dist-packages/django/template/loader.py" in get_template
  81.     source, origin = find_template_source(template_name)
File "/usr/local/lib/python2.6/dist-packages/django/template/loader.py" in find_template_source
  74.     raise TemplateDoesNotExist, name

Exception Type: TemplateDoesNotExist at /admin/
Exception Value: admin/index.html
</code>```

here is the trace back

```<code>Environment:

Request Method: GET
Request URL: http://localhost:8000/admin/
Django Version: 1.1.1
Python Version: 2.6.6
Installed Applications:
['django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.sites',
 'django.contrib.admin',
 'hotweb.accounts',
 'django.contrib.flatpages',
 'messages',
 'hotweb.jchat']
Installed Middleware:
('django.middleware.common.CommonMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.flatpages.middleware.FlatpageFallbackMiddleware',
 'django.middleware.http.SetRemoteAddrFromForwardedFor')

Template Loader Error:
Django tried loading these templates, in this order:
Using loader django.template.loaders.filesystem.load_template_source:
/home/scorpion/Desktop/hotweb/templates/admin/index.html (File does not exist)
Using loader django.template.loaders.app_directories.load_template_source:
/usr/local/lib/python2.6/dist-packages/django/contrib/admin/templates/admin/index.html (File exists)

Traceback:
File "/usr/local/lib/python2.6/dist-packages/django/core/handlers/base.py" in get_response
  92.                 response = callback(request, *callback_args, **callback_kwargs)
File "/usr/local/lib/python2.6/dist-packages/django/contrib/admin/sites.py" in wrapper
  196.                 return self.admin_view(view, cacheable)(*args, **kwargs)
File "/usr/local/lib/python2.6/dist-packages/django/views/decorators/cache.py" in _wrapped_view_func
  44.         response = view_func(request, *args, **kwargs)
File "/usr/local/lib/python2.6/dist-packages/django/contrib/admin/sites.py" in inner
  186.             return view(request, *args, **kwargs)
File "/usr/local/lib/python2.6/dist-packages/django/views/decorators/cache.py" in _wrapped_view_func
  44.         response = view_func(request, *args, **kwargs)
File "/usr/local/lib/python2.6/dist-packages/django/contrib/admin/sites.py" in index
  374.             context_instance=context_instance
File "/usr/local/lib/python2.6/dist-packages/django/shortcuts/__init__.py" in render_to_response
  20.     return HttpResponse(loader.render_to_string(*args, **kwargs), **httpresponse_kwargs)
File "/usr/local/lib/python2.6/dist-packages/django/template/loader.py" in render_to_string
  103.         t = get_template(template_name)
File "/usr/local/lib/python2.6/dist-packages/django/template/loader.py" in get_template
  81.     source, origin = find_template_source(template_name)
File "/usr/local/lib/python2.6/dist-packages/django/template/loader.py" in find_template_source
  74.     raise TemplateDoesNotExist, name

Exception Type: TemplateDoesNotExist at /admin/
Exception Value: admin/index.html
</code>```

答:
Hmm, that's odd since TEMPLATE_DIRS setting doesn't have anything to do with the admin app.

If you're sure it's those 3 lines, the only possible thing I see wrong is TEMPLATE_DIRS is supposed to be a tuple (yours is a string), but on 1.2.3 it doesn't cause any problems.

You say "the problem occurred in settings.py"... but
I don't see where a TemplateDoesNotExist error would appear from the lines you pasted -- can you post the full traceback? Which line of code triggered TemplateDoesNotExist? How do you know it was settings.py?

I think the problem lies outside of your 3 lines.

PS: I can't comment since I have <50 rep.

Body:
I am unable to access the admin interface in django 1.1.1 using localloop:8000/admin. It was working fine on Ubuntu 8.4 then I upgraded to Ubuntu 10.10 and the problem occurred.

In settings.py I have:

import os.path
PROJECT_DIR=os.path.dirname(__file__)

TEMPLATE_DIRS =(os.path.join(PROJECT_DIR,'templates'))

This  was working fine on Ubuntu 8.04 but not in Ubuntu 10.10.

Any ideas on what goes wrong? Here is the traceback:

Environment:

Request Method: GET
Request URL: http://localhost:8000/admin/
Django Version: 1.1.1
Python Version: 2.6.6
Installed Applications:
['django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.sites',
 'django.contrib.admin',
 'hotweb.accounts',
 'django.contrib.flatpages',
 'messages',
 'hotweb.jchat']
Installed Middleware:
('django.middleware.common.CommonMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.flatpages.middleware.FlatpageFallbackMiddleware',
 'django.middleware.http.SetRemoteAddrFromForwardedFor')

Template Loader Error:
Django tried loading these templates, in this order:
Using loader django.template.loaders.filesystem.load_template_source:
/home/scorpion/Desktop/hotweb/templates/admin/index.html (File does not exist)
Using loader django.template.loaders.app_directories.load_template_source:
/usr/local/lib/python2.6/dist-packages/django/contrib/admin/templates/admin/index.html (File exists)

Traceback:
File "/usr/local/lib/python2.6/dist-packages/django/core/handlers/base.py" in get_response
  92.                 response = callback(request, *callback_args, **callback_kwargs)
File "/usr/local/lib/python2.6/dist-packages/django/contrib/admin/sites.py" in wrapper
  196.                 return self.admin_view(view, cacheable)(*args, **kwargs)
File "/usr/local/lib/python2.6/dist-packages/django/views/decorators/cache.py" in _wrapped_view_func
  44.         response = view_func(request, *args, **kwargs)
File "/usr/local/lib/python2.6/dist-packages/django/contrib/admin/sites.py" in inner
  186.             return view(request, *args, **kwargs)
File "/usr/local/lib/python2.6/dist-packages/django/views/decorators/cache.py" in _wrapped_view_func
  44.         response = view_func(request, *args, **kwargs)
File "/usr/local/lib/python2.6/dist-packages/django/contrib/admin/sites.py" in index
  374.             context_instance=context_instance
File "/usr/local/lib/python2.6/dist-packages/django/shortcuts/__init__.py" in render_to_response
  20.     return HttpResponse(loader.render_to_string(*args, **kwargs), **httpresponse_kwargs)
File "/usr/local/lib/python2.6/dist-packages/django/template/loader.py" in render_to_string
  103.         t = get_template(template_name)
File "/usr/local/lib/python2.6/dist-packages/django/template/loader.py" in get_template
  81.     source, origin = find_template_source(template_name)
File "/usr/local/lib/python2.6/dist-packages/django/template/loader.py" in find_template_source
  74.     raise TemplateDoesNotExist, name

Exception Type: TemplateDoesNotExist at /admin/
Exception Value: admin/index.html

here is the trace back

Environment:

Request Method: GET
Request URL: http://localhost:8000/admin/
Django Version: 1.1.1
Python Version: 2.6.6
Installed Applications:
['django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.sites',
 'django.contrib.admin',
 'hotweb.accounts',
 'django.contrib.flatpages',
 'messages',
 'hotweb.jchat']
Installed Middleware:
('django.middleware.common.CommonMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.flatpages.middleware.FlatpageFallbackMiddleware',
 'django.middleware.http.SetRemoteAddrFromForwardedFor')

Template Loader Error:
Django tried loading these templates, in this order:
Using loader django.template.loaders.filesystem.load_template_source:
/home/scorpion/Desktop/hotweb/templates/admin/index.html (File does not exist)
Using loader django.template.loaders.app_directories.load_template_source:
/usr/local/lib/python2.6/dist-packages/django/contrib/admin/templates/admin/index.html (File exists)

Traceback:
File "/usr/local/lib/python2.6/dist-packages/django/core/handlers/base.py" in get_response
  92.                 response = callback(request, *callback_args, **callback_kwargs)
File "/usr/local/lib/python2.6/dist-packages/django/contrib/admin/sites.py" in wrapper
  196.                 return self.admin_view(view, cacheable)(*args, **kwargs)
File "/usr/local/lib/python2.6/dist-packages/django/views/decorators/cache.py" in _wrapped_view_func
  44.         response = view_func(request, *args, **kwargs)
File "/usr/local/lib/python2.6/dist-packages/django/contrib/admin/sites.py" in inner
  186.             return view(request, *args, **kwargs)
File "/usr/local/lib/python2.6/dist-packages/django/views/decorators/cache.py" in _wrapped_view_func
  44.         response = view_func(request, *args, **kwargs)
File "/usr/local/lib/python2.6/dist-packages/django/contrib/admin/sites.py" in index
  374.             context_instance=context_instance
File "/usr/local/lib/python2.6/dist-packages/django/shortcuts/__init__.py" in render_to_response
  20.     return HttpResponse(loader.render_to_string(*args, **kwargs), **httpresponse_kwargs)
File "/usr/local/lib/python2.6/dist-packages/django/template/loader.py" in render_to_string
  103.         t = get_template(template_name)
File "/usr/local/lib/python2.6/dist-packages/django/template/loader.py" in get_template
  81.     source, origin = find_template_source(template_name)
File "/usr/local/lib/python2.6/dist-packages/django/template/loader.py" in find_template_source
  74.     raise TemplateDoesNotExist, name

Exception Type: TemplateDoesNotExist at /admin/
Exception Value: admin/index.html


问:
How To setfocus on spinner?
I have spinner and edittext, and i want if spinner is selected can setfocus in edittext. I am already try, but not going to work, how to fix this?

This is my code :

```<code>edkontak1.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if(actionId== EditorInfo.IME_ACTION_NEXT) {
                    sembunyikanKeyboard();
                    v.clearFocus();
                    spinnerkontak1.requestFocus();
                    spinnerkontak1.performClick();
                }
                return true;
            }
        });

 spinnerkontak1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                String jeniskontak1 = spinnerkontak1.getSelectedItem().toString();
                if(jeniskontak1.equals("--")){
                    edkontak1.setText("");
                    edkontak1.setEnabled(false);
                    tkontak2.setVisibility(View.GONE);
                    tkontak3.setVisibility(View.GONE);
                    tkontak4.setVisibility(View.GONE);
                    tkontak5.setVisibility(View.GONE);
                }
                else{
                    edkontak1.setEnabled(true);
                    tkontak2.setVisibility(View.VISIBLE);
                    spinnerkontak1.setFocusable(true);
                    spinnerkontak1.setFocusableInTouchMode(true);
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

private void sembunyikanKeyboard() {
        InputMethodManager inputmanaget = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
        inputmanaget.hideSoftInputFromInputMethod(this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
    }
</code>```

Thanks in advance.

答: I think you should implement request focus method edkontak1.requestFocus();

Title: How To setfocus on spinner?

Body:
I have spinner and edittext, and i want if spinner is selected can setfocus in edittext. I am already try, but not going to work, how to fix this?

This is my code :

edkontak1.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if(actionId== EditorInfo.IME_ACTION_NEXT) {
                    sembunyikanKeyboard();
                    v.clearFocus();
                    spinnerkontak1.requestFocus();
                    spinnerkontak1.performClick();
                }
                return true;
            }
        });

 spinnerkontak1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                String jeniskontak1 = spinnerkontak1.getSelectedItem().toString();
                if(jeniskontak1.equals("--")){
                    edkontak1.setText("");
                    edkontak1.setEnabled(false);
                    tkontak2.setVisibility(View.GONE);
                    tkontak3.setVisibility(View.GONE);
                    tkontak4.setVisibility(View.GONE);
                    tkontak5.setVisibility(View.GONE);
                }
                else{
                    edkontak1.setEnabled(true);
                    tkontak2.setVisibility(View.VISIBLE);
                    spinnerkontak1.setFocusable(true);
                    spinnerkontak1.setFocusableInTouchMode(true);
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

private void sembunyikanKeyboard() {
        InputMethodManager inputmanaget = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
        inputmanaget.hideSoftInputFromInputMethod(this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
    }

Thanks in advance.


问:
How to parse JSON response from Alamofire API in Swift?
Following code I have written and I am getting response in JSON also but the type of JSON is "AnyObject" and I am not able to convert that into Array so that I can use that.</p>

```<code>Alamofire.request(.POST, "MY URL", parameters:parameters, encoding: .JSON) .responseJSON
{
    (request, response, JSON, error) in

    println(JSON?)
}
</code>```

答:
Swift 3, Alamofire 4.4, and SwiftyJSON:

```<code>Alamofire.request(url, method: .get)
  .responseJSON { response in
      if response.data != nil {
        let json = JSON(data: response.data!)
        let name = json["people"][0]["name"].string
        if name != nil {
          print(name!)
        }
      }
  }
</code>```

That will parse this JSON input:

```<code>{
  people: [
    { name: 'John' },
    { name: 'Dave' }
  ]
}
</code>```

Body:
Following code I have written and I am getting response in JSON also but the type of JSON is "AnyObject" and I am not able to convert that into Array so that I can use that.

Alamofire.request(.POST, "MY URL", parameters:parameters, encoding: .JSON) .responseJSON
{
    (request, response, JSON, error) in

    println(JSON?)
}

Body:
Swift 3, Alamofire 4.4, and SwiftyJSON:

Alamofire.request(url, method: .get)
  .responseJSON { response in
      if response.data != nil {
        let json = JSON(data: response.data!)
        let name = json["people"][0]["name"].string
        if name != nil {
          print(name!)
        }
      }
  }

That will parse this JSON input:

{
  people: [
    { name: 'John' },
    { name: 'Dave' }
  ]
}


问:
VueJS - Axios array not updated
I'm trying to update from an API my array declared in data. When I init the array with an object, this object appears well in the HTML code. It seems that the array is not "saved" after the scope of the axios call. Anyone can help me please ? I don't have any error code/message.

```<code>var vm = new Vue({
el: '#recettes',
data: {
  results: []
},
created() {
  axios.get('url')
  .then((response) => {
    this.results = response.data
    console.log("Size before end of scope = " + this.results.length)  // = 4
  });
  console.log("Size after = " + this.results.length) // = 0
}
});
</code>```

The response API is:

```<code>[
  {
    "id": 1,
    "titre": "Cassoulet",
    "contenu": "Couper. Faire cuire...",
    "id_util": 1
  },
  {
    "id": 2,
    "titre": "Gateau",
    "contenu": "chocolat",
    "id_util": 4
  },
  {
    "id": 3,
    "titre": "Gateau",
    "contenu": "fraise",
    "id_util": 5
  },
  {
    "id": 4,
    "titre": "Gateau",
    "contenu": "Mélanger, cuire, four 220°...",
    "id_util": 5
  }
]
</code>```

Template:

```<code>    <div id="recettes">
    <div v-for="result in results">
      <div class="card">
        <div class="card-divider">
          {{ result.titre }}
        </div>
        <div class="card-section">
          {{ result.contenu }}
        </div>
      </div>
    </div>
    </div>
</code>```

UPDATE

```<code>var vm = new Vue({
  el: '#recettes',
  data: {
    results: []
},
created() {
  axios.get('URL')
  .then(response => {
    this.results = response.data
    console.log("size: " + this.results.length)
    console.log('results[0]: ' + this.results[0].titre)
  })
}
});
</code>```

With this code, results[0].titre contains the right string. But in the HTML code, no cards are displayed.
And with this code:

```<code>var vm = new Vue({
  el: '#recettes',
  data: {
    results: [
      {"id" = 1, "id":1,"titre":"Cassoulet","contenu":"Couper. Faire cuire...","id_util":1}
    ]
},
created() {
  axios.get('URL')
  .then(response => {
    this.results = response.data
    console.log("size: " + this.results.length)
    console.log('results[0]: ' + this.results[0].titre)
  })
}
});
</code>```

One card is displayed in the HTML with titre = "Cassoulet" and contenu = "Couper. Faire cuire..."

It's why I said that it seems that the array is not updated...

答:
Vue is reactive.

The request is async so the code where you're checking the size runs before the then() part. If you put {{ results.length }} in your template it'll be 0 then 4 very quickly, you'll likely never even see it at 0.

Just because the length is 0 when you log doesn't mean it's not "saved".

If you want the length in a variable you can use a computed property and do:

```<code>computed: {
  resultsLength () {
    return this.results.length
  },
}
</code>```

Title: VueJS - Axios array not updated

Body:
I'm trying to update from an API my array declared in data. When I init the array with an object, this object appears well in the HTML code. It seems that the array is not "saved" after the scope of the axios call. Anyone can help me please ? I don't have any error code/message.

var vm = new Vue({
el: '#recettes',
data: {
  results: []
},
created() {
  axios.get('url')
  .then((response) => {
    this.results = response.data
    console.log("Size before end of scope = " + this.results.length)  // = 4
  });
  console.log("Size after = " + this.results.length) // = 0
}
});

The response API is:

[
  {
    "id": 1,
    "titre": "Cassoulet",
    "contenu": "Couper. Faire cuire...",
    "id_util": 1
  },
  {
    "id": 2,
    "titre": "Gateau",
    "contenu": "chocolat",
    "id_util": 4
  },
  {
    "id": 3,
    "titre": "Gateau",
    "contenu": "fraise",
    "id_util": 5
  },
  {
    "id": 4,
    "titre": "Gateau",
    "contenu": "Mélanger, cuire, four 220°...",
    "id_util": 5
  }
]

Template:

          {{ result.titre }}

          {{ result.contenu }}

UPDATE

var vm = new Vue({
  el: '#recettes',
  data: {
    results: []
},
created() {
  axios.get('URL')
  .then(response => {
    this.results = response.data
    console.log("size: " + this.results.length)
    console.log('results[0]: ' + this.results[0].titre)
  })
}
});

With this code, results[0].titre contains the right string. But in the HTML code, no cards are displayed.
And with this code:

var vm = new Vue({
  el: '#recettes',
  data: {
    results: [
      {"id" = 1, "id":1,"titre":"Cassoulet","contenu":"Couper. Faire cuire...","id_util":1}
    ]
},
created() {
  axios.get('URL')
  .then(response => {
    this.results = response.data
    console.log("size: " + this.results.length)
    console.log('results[0]: ' + this.results[0].titre)
  })
}
});

One card is displayed in the HTML with titre = "Cassoulet" and contenu = "Couper. Faire cuire..."

It's why I said that it seems that the array is not updated...

Body:
Vue is reactive.

The request is async so the code where you're checking the size runs before the then() part. If you put {{ results.length }} in your template it'll be 0 then 4 very quickly, you'll likely never even see it at 0.

Just because the length is 0 when you log doesn't mean it's not "saved".

If you want the length in a variable you can use a computed property and do:

computed: {
  resultsLength () {
    return this.results.length
  },
}


问:
Is guava ImmutableSet.copyOf() thread safe?
I would like to know if this call is thread safe. For example, if I have a set s:

```<code>Set<String> s = new HashSet<>();
</code>```

and two threads A and B, thread A modifying the set:

```<code>for (int i = 0; i < 1234; i++) {
    // add, remove from s
}
</code>```

while thread B creating ImmutableSets from s:

```<code>for (int i = 0; i < 5678; i++) {
    Set<String> newS =  ImmutableSet.copyOf(s);
}
</code>```

Is it safe to assume that each time ImmutableSet.copyOf() is called I get an immutable set for a valid state of s in time? Will there be any kind of exception (like ConcurrentModificationException) that can occur?

If it is thread safe, how was it achieved without locking the set?

答: The relevant question isn't whether copyOf is safe -- it's whether the collection it's copying from is safe, and in particular, whether the Iterators that it creates via its iterator() method are thread-safe. For HashMap, that answer is no.

Body:
I would like to know if this call is thread safe. For example, if I have a set s:

Set<String> s = new HashSet<>();

and two threads A and B, thread A modifying the set:

for (int i = 0; i < 1234; i++) {
    // add, remove from s
}

while thread B creating ImmutableSets from s:

for (int i = 0; i < 5678; i++) {
    Set<String> newS =  ImmutableSet.copyOf(s);
}

Is it safe to assume that each time ImmutableSet.copyOf() is called I get an immutable set for a valid state of s in time? Will there be any kind of exception (like ConcurrentModificationException) that can occur?

If it is thread safe, how was it achieved without locking the set?


问:
Encoding Issues �
Getting the symbol from the above and I'm at a loss what I'm missing.
What I've done so far.

Set on header

```<code><meta charset="UTF-8" />
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</code>```

Database output charset: UTF8

```<code>$char = mysqli_character_set_name($conn);
echo "The current character set is: $char\n";
</code>```

Set on file.

```<code>mysqli_set_charset($conn, "utf8");
</code>```

File is: UTF 8
Database Table is: utf8_general_ci

EDIT: SHOW TABLE

```<code>CREATE TABLE `testimonials` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`showflag` varchar(10) NOT NULL DEFAULT '10',
`heading` varchar(155) DEFAULT NULL,
`testimonial` longtext NOT NULL,
`name` varchar(50) NOT NULL,
`domain` varchar(50) DEFAULT NULL,
`date` date NOT NULL,
`image` varchar(255) DEFAULT NULL,
`rating` int(1) DEFAULT '5',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=47 DEFAULT CHARSET=utf8
</code>```

EDIT: Database storage is fine, the issue occurs on output only.

答:
You seem to have a contradiction with the two meta clauses -- use the same charset.

Look for "black diamond" in http://stackoverflow.com/questions/38363566/trouble-with-utf8-characters-what-i-see-is-not-what-i-stored

Let's see SHOW CREATE TABLE; the column is the important part.

Title: Encoding Issues �

Body:
Getting the symbol from the above and I'm at a loss what I'm missing.
What I've done so far.

Set on header

<meta charset="UTF-8" />
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">

Database output charset: UTF8

$char = mysqli_character_set_name($conn);
echo "The current character set is: $char\n";

Set on file.

mysqli_set_charset($conn, "utf8");

File is: UTF 8
Database Table is: utf8_general_ci

EDIT: SHOW TABLE

CREATE TABLE `testimonials` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`showflag` varchar(10) NOT NULL DEFAULT '10',
`heading` varchar(155) DEFAULT NULL,
`testimonial` longtext NOT NULL,
`name` varchar(50) NOT NULL,
`domain` varchar(50) DEFAULT NULL,
`date` date NOT NULL,
`image` varchar(255) DEFAULT NULL,
`rating` int(1) DEFAULT '5',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=47 DEFAULT CHARSET=utf8

EDIT: Database storage is fine, the issue occurs on output only.


问:
Limit display rows in Admin Panel Django
I have Admin.py as follows .

```<code>from django.contrib import admin
from do.models import *

class NewsAdmin(admin.ModelAdmin):
    list_display=['time','message']

 admin.site.register(do_model,NewsAdmin)
</code>```

I while i go to the admin panel and go to the do_models , it is showing me huge lots of data . I dont want to see all data from the beginning date , is it possible that i can limit data till 20  or 30 lines of data and rest of data should not be shown like paginating  so that it load easily . Kindly suggest .

答:
```<code> class NewsAdmin(admin.ModelAdmin):
    list_display=['time','message']
    list_per_page = 400

 admin.site.register(do_model,NewsAdmin)
</code>```

you can use list_per_page to limit the number of rows shown in a single page

Body:
I have Admin.py as follows .

from django.contrib import admin
from do.models import *

class NewsAdmin(admin.ModelAdmin):
    list_display=['time','message']

 admin.site.register(do_model,NewsAdmin)

I while i go to the admin panel and go to the do_models , it is showing me huge lots of data . I dont want to see all data from the beginning date , is it possible that i can limit data till 20  or 30 lines of data and rest of data should not be shown like paginating  so that it load easily . Kindly suggest .

Body:
 class NewsAdmin(admin.ModelAdmin):
    list_display=['time','message']
    list_per_page = 400

 admin.site.register(do_model,NewsAdmin)

you can use list_per_page to limit the number of rows shown in a single page

ContentLicense: CC BY-SA 4.0


问:
C# : Currency Rendering Solution
i have to find a solution for this task :

"Supermarkets are increasingly equipped with automatic cash registers. Most of these funds only accept payment by credit card, although a significant proportion of consumers still pay cash (with banknotes and coins).

One of the problems encountered with the cash payment is the rendering of money: how to make a given sum optimally, ie with the minimum number of coins and notes? This is a problem for every one of us every day, let alone the automatic cash registers.

In this exercise, i m asked to try to find an optimal solution to make change in a specific case: when an automatic cash register contains only 2 € coins, 5 € and 10 € banknotes.

To simplify the problem, we will consider that all these coins and bills are available in unlimited quantities.

Here are some examples of currency:

The return of money is expressed by a Currency object. This item has 3 properties: piece2, billet5 and billet10 which respectively store the number of coins of 2 €, 5 € tickets and 10 € tickets.

For example, if we take example 2 of the table (6 €), we should get a Money object with:

Piece2 worth 3 (3 pieces of 2 €)

Ticket5 is worth 0 (no ticket of 5 €)

Ticket10 is worth 0 (no ticket of 10 €)

Task : Implement the MonnaieOptimale(int s) method that returns a Currency object containing the coins and notes whose sum is s. If it is impossible to return the currency (as in example 1), return null.

To get it best the solution will always have to make change when possible and with the minimum number of coins and tickets."

Data: s is always a strictly positive integer (long) less than or equal to 9223372036854775807

the general structure of the solution is the following:

Suggestions ??

答:
Firstly, simple greedy approach (always get the largest i.e.10) is not working here, as the system is not canonical, consider s = 11, you will get "Impossible" if you use coin 10, but it is possible with { 5, 2, 2, 2 }.

I have a slightly different idea here, using the parity of odd /even numbers:

If s is even, do the greedy approach but never uses coin 5

If s is odd, keep using coin 5 until s becomes even, then do step 1.

For eg: s = 18, solution = { 10, 2, 2, 2, 2 }. s = 23, solution = { 5, 10, 2, 2, 2, 2 }

Why it works, is because one can notice, for coin system { 2, 10 }, you can make any even s using greedy approach (it is canonical to even domain).

Plus the fact that for any odd number minus another odd number will make a even number, so for odd s we can use one coin 5 to make s even to reduce the problem.

From this logic, I think at most one 5 coin would be used for any s, and only when s = 1 or 3 the answer is "Impossible"

Title: C# : Currency Rendering Solution


问:
Subsetting by variables within grouped observations R
so if you do this you'll get a data frame similar to what I am working with

```<code>test <- Indometh[Indometh$time %in% c(1.00,3.00,6.00),]
dil <- c(50,500,5000)
test$dilution <- dil
test <- test[-c(3,7,11,17),]
test[14,4] <- 50
test$time <- gsub(1, "run_1", test$time)
test$time <- gsub(3, "run_3", test$time)
test$time <- gsub(6, "run_6", test$time)

   Subject  time conc dilution
        1 run_1 0.48       50
        1 run_3 0.12      500
        2 run_1 0.70       50
        2 run_3 0.32      500
        2 run_6 0.12     5000
        3 run_3 0.22      500
        3 run_6 0.08     5000
        4 run_1 0.89       50
        4 run_6 0.07     5000
        5 run_1 0.39       50
        5 run_3 0.13      500
        5 run_6 0.10     5000
        6 run_1 0.84       50
        6 run_6 0.10       50
</code>```

What I need to do is apply the following logic.

For each subject, if the dilution is 50 and there is any other dilution, keep the other dilutions.

If the dilution is 50 and there is only other dilution 50 available then keep all the dilution 50's for that subject.

so my resulting data frame should look like:

```<code>testres <- test[-c(1,3,8,10),]

 Subject  time conc dilution
       1 run_3 0.12      500
       2 run_3 0.32      500
       2 run_6 0.12     5000
       3 run_3 0.22      500
       3 run_6 0.08     5000
       4 run_6 0.07     5000
       5 run_3 0.13      500
       5 run_6 0.10     5000
       6 run_1 0.84       50
       6 run_6 0.10       50
</code>```

Thanks

PS: It was hard wording this question, any recommendations for how I could of titled this question better?

Body:
so if you do this you'll get a data frame similar to what I am working with

test <- Indometh[Indometh$time %in% c(1.00,3.00,6.00),]
dil <- c(50,500,5000)
test$dilution <- dil
test <- test[-c(3,7,11,17),]
test[14,4] <- 50
test$time <- gsub(1, "run_1", test$time)
test$time <- gsub(3, "run_3", test$time)
test$time <- gsub(6, "run_6", test$time)

   Subject  time conc dilution
        1 run_1 0.48       50
        1 run_3 0.12      500
        2 run_1 0.70       50
        2 run_3 0.32      500
        2 run_6 0.12     5000
        3 run_3 0.22      500
        3 run_6 0.08     5000
        4 run_1 0.89       50
        4 run_6 0.07     5000
        5 run_1 0.39       50
        5 run_3 0.13      500
        5 run_6 0.10     5000
        6 run_1 0.84       50
        6 run_6 0.10       50

What I need to do is apply the following logic.

For each subject, if the dilution is 50 and there is any other dilution, keep the other dilutions.

If the dilution is 50 and there is only other dilution 50 available then keep all the dilution 50's for that subject.

so my resulting data frame should look like:

testres <- test[-c(1,3,8,10),]

 Subject  time conc dilution
       1 run_3 0.12      500
       2 run_3 0.32      500
       2 run_6 0.12     5000
       3 run_3 0.22      500
       3 run_6 0.08     5000
       4 run_6 0.07     5000
       5 run_3 0.13      500
       5 run_6 0.10     5000
       6 run_1 0.84       50
       6 run_6 0.10       50

Thanks

PS: It was hard wording this question, any recommendations for how I could of titled this question better?

Body:
Here is an option using data.table

library(data.table)
setDT(test)[, .SD[(all(dilution == 50) & dilution == 50)|
         (!all(dilution == 50) & dilution !=50)], Subject]
#    Subject  time conc dilution
# 1:       1 run_3 0.12      500
# 2:       2 run_3 0.32      500
# 3:       2 run_6 0.12     5000
# 4:       3 run_3 0.22      500
# 5:       3 run_6 0.08     5000
# 6:       4 run_6 0.07     5000
# 7:       5 run_3 0.13      500
# 8:       5 run_6 0.10     5000
# 9:       6 run_1 0.84       50
#10:       6 run_6 0.10       50


问:
delete rows that do not have min(rid)
```<code>select min(q.rid)
    from qvalues q
        inner join batchinfo b
            on q.rowid = b.rowid
                and b.instrument = 'tf1'
    group by q.rowid, q.name, q.compound
    having count(*) > 1
</code>```

instead of selecting the min(rid) how do i delete everything except for min(rid)?

how do i delete everything except for max(rid)?

please note that i want to delete only values that have the same rowid, name, and compound

答:
```<code>begin transaction

delete from [table]
where rid !=
(select min(q.rid)
from qvalues q
    inner join batchinfo b
        on q.rowid = b.rowid
            and b.instrument = 'tf1'
group by q.rowid, q.name, q.compound
having count(*) > 1)
and rowid !=
(select q.rowid
from qvalues q
    inner join batchinfo b
        on q.rowid = b.rowid
            and b.instrument = 'tf1'
group by q.rowid, q.name, q.compound
having count(*) > 1)
and name !=
(select q.name
from qvalues q
    inner join batchinfo b
        on q.rowid = b.rowid
            and b.instrument = 'tf1'
group by q.rowid, q.name, q.compound
having count(*) > 1)
and compound !=
(select q.compound
from qvalues q
    inner join batchinfo b
        on q.rowid = b.rowid
            and b.instrument = 'tf1'
group by q.rowid, q.name, q.compound
having count(*) > 1)
</code>```

to delete all but max, you do the same with the max syntax

Title: delete rows that do not have min(rid)

Body:
select min(q.rid)
    from qvalues q
        inner join batchinfo b
            on q.rowid = b.rowid
                and b.instrument = 'tf1'
    group by q.rowid, q.name, q.compound
    having count(*) > 1

instead of selecting the min(rid) how do i delete everything except for min(rid)?

how do i delete everything except for max(rid)?

please note that i want to delete only values that have the same rowid, name, and compound

Body:
begin transaction

delete from [table]
where rid !=
(select min(q.rid)
from qvalues q
    inner join batchinfo b
        on q.rowid = b.rowid
            and b.instrument = 'tf1'
group by q.rowid, q.name, q.compound
having count(*) > 1)
and rowid !=
(select q.rowid
from qvalues q
    inner join batchinfo b
        on q.rowid = b.rowid
            and b.instrument = 'tf1'
group by q.rowid, q.name, q.compound
having count(*) > 1)
and name !=
(select q.name
from qvalues q
    inner join batchinfo b
        on q.rowid = b.rowid
            and b.instrument = 'tf1'
group by q.rowid, q.name, q.compound
having count(*) > 1)
and compound !=
(select q.compound
from qvalues q
    inner join batchinfo b
        on q.rowid = b.rowid
            and b.instrument = 'tf1'
group by q.rowid, q.name, q.compound
having count(*) > 1)

to delete all but max, you do the same with the max syntax


答: HashSet isn't thread safe. ImmutableSet.copyOf needs to iterate over your HashSet, which isn't safe if another thread is concurrently modifying it. What's more, your having two threads modifying the HashSet is already unsafe.

Title: Is guava ImmutableSet.copyOf() thread safe?


答:
```<code><meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</code>```

You are setting charset to iso-8859-1..Try changing it to utf-8

Your second meta tag is only useful only for HTML4 though. For modern browsers that work well with HTML5, having only <meta charset="UTF-8" /> is good enough.

Title: Encoding Issues �

Body:
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">

You are setting charset to iso-8859-1..Try changing it to utf-8

Your second meta tag is only useful only for HTML4 though. For modern browsers that work well with HTML5, having only <meta charset="UTF-8" /> is good enough.


问:
ERROR: pipeline could not be constructed: no element "audiotestsrc"
I'm trying to write a simple audio streaming application with C using Gstreamer library (gstreamer1.0-libav) on ubuntu 16.04. I was testing the gstreamer1.0-tools with a simple "gst-launch audiotestsrc ! alsasink" command, but each time I run this I get the following error: pipeline could not be constructed: no element "audiotestsrc". I've tried running the command on different path locations such as usr/bin/, usr/local/lib/, etc., but I cannot seem to figure out where Ubuntu installed the Gstreamer binaries that let me run these commands. Also, I'm assuming, with my lack of experience with linux, that the problem is that I'm not running this command on the right directory. I'm following this guide: https://gstreamer.freedesktop.org/documentation/tutorials/basic/gstreamer-tools.html#. Could someone shed some light on this matter? Any help is appreciated. Thanks.</p>

答: Found a workaround, although I'm still unsure whether this is a fix. Doing more research I found this great resource http://labs.isee.biz/index.php/Example_GStreamer_Pipelines. I replaced "gst-launch audiotestsrc ! alsasink" with "gst-launch-0.10 audiotestsrc ! alsasink" and that did the trick. The problem was with the version on the gst-launch command. Hope this can help anyone. Any other comments for clarity purposes are more than welcomed.</p>


问:
Positioning within a HTML form
I realize this is a very basic issue.

I am currently trying to create a website http://theviewbeyond.co.uk/.

I am currently adding a contact form to which I have created a picture to use as the background of the form, the issue is I cannot move the objects within the form such as text boxes to within the picture.

I have tried absolute positioning which doesn't seem to work either.

How can I do this ?

```<code>form {
margin: 0 auto;
width: 60%;
background-image: url("../IMG/contactpage1[2742].jpg");
background-size: cover;
</code>```

答:
I was reviewing your site and see your problem, I was trying some styles and I realice that background-image doesn't fit correctly if your container has a different size of your image so you need to play with the height and width of your form.

```<code>margin: 0 auto;
background-image: url(../IMG/contactpage1[2742].jpg);
background-position: center center;
background-size: cover;
height: 350px;
width: 370px;
</code>```

In different screen sizes you'll need to use media queries to make it work well.

Title: Positioning within a HTML form

Body:
I realize this is a very basic issue.

I am currently trying to create a website http://theviewbeyond.co.uk/.

I am currently adding a contact form to which I have created a picture to use as the background of the form, the issue is I cannot move the objects within the form such as text boxes to within the picture.

I have tried absolute positioning which doesn't seem to work either.

How can I do this ?

form {
margin: 0 auto;
width: 60%;
background-image: url("../IMG/contactpage1[2742].jpg");
background-size: cover;

Body:
I was reviewing your site and see your problem, I was trying some styles and I realice that background-image doesn't fit correctly if your container has a different size of your image so you need to play with the height and width of your form.

margin: 0 auto;
background-image: url(../IMG/contactpage1[2742].jpg);
background-position: center center;
background-size: cover;
height: 350px;
width: 370px;

In different screen sizes you'll need to use media queries to make it work well.


问:
How to get the XML node name?
I am doing a challenge thing but I am struggling to get the name of the XML node, "folder". I am trying to return all folders that begin with 'u'.

I want to output to be "Uninstall Information" and "Users" but I still have all the XML structure.

Any help would be great.

```<code> class Program
    {
        public static IEnumerable<string> FolderNames(string xml, char startingLetter)
        {
            List<string> elem = new List<string>();
            List<int> list = new List<int>();

            XmlDocument xmldoc = new XmlDocument();
            xmldoc.LoadXml(xml);

            XmlNodeList temp = xmldoc.SelectNodes("folder");

             elem.Add(temp[0].InnerXml);
             Console.WriteLine(elem[0]);

            return elem;
        }

        public static void Main(string[] args)
        {
            string xml =
                "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
                "<folder name=\"c\">" +
                "<folder name=\"program files\">" +
                "<folder name=\"uninstall information\" />" +
                "</folder>" +
                "<folder name=\"users\" />" +
                "</folder>";

            Program.FolderNames(xml, 'u');

            //foreach (string name in Program.FolderNames(xml, 'u'))
                //Console.WriteLine(name);
        }
    }
}
</code>```

答:
Following code shows how to use XPath expression to select folder names starting with particular letter from your XML. This XPath consists of following parts:

//folder selects all "folder" XML elements (including subfolders)

/@name selects attribute "name" of those elements

[starts-with(., 'u')] is condition that selects only attributes starting with specified letter

```<code>public static IEnumerable<string> FolderNames(string xml, char startingLetter)
{
    List<string> elem = new List<string>();

    XmlDocument xmldoc = new XmlDocument();
    xmldoc.LoadXml(xml);

    foreach (XmlAttribute folderName in xmldoc.SelectNodes("//folder/@name[starts-with(., '"+ startingLetter +"')]"))
    {
        elem.Add(folderName.Value);
        Console.WriteLine(folderName.Value);
    }

    return elem;
}
</code>```

Title: How to get the XML node name?

Body:
I am doing a challenge thing but I am struggling to get the name of the XML node, "folder". I am trying to return all folders that begin with 'u'.

I want to output to be "Uninstall Information" and "Users" but I still have all the XML structure.

Any help would be great.

 class Program
    {
        public static IEnumerable<string> FolderNames(string xml, char startingLetter)
        {
            List<string> elem = new List<string>();
            List<int> list = new List<int>();

            XmlDocument xmldoc = new XmlDocument();
            xmldoc.LoadXml(xml);

            XmlNodeList temp = xmldoc.SelectNodes("folder");

             elem.Add(temp[0].InnerXml);
             Console.WriteLine(elem[0]);

            return elem;
        }

        public static void Main(string[] args)
        {
            string xml =
                "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
                "<folder name=\"c\">" +
                "<folder name=\"program files\">" +
                "<folder name=\"uninstall information\" />" +
                "</folder>" +
                "<folder name=\"users\" />" +
                "</folder>";

            Program.FolderNames(xml, 'u');

            //foreach (string name in Program.FolderNames(xml, 'u'))
                //Console.WriteLine(name);
        }
    }
}

Body:
Following code shows how to use XPath expression to select folder names starting with particular letter from your XML. This XPath consists of following parts:

//folder selects all "folder" XML elements (including subfolders)

/@name selects attribute "name" of those elements

[starts-with(., 'u')] is condition that selects only attributes starting with specified letter

public static IEnumerable<string> FolderNames(string xml, char startingLetter)
{
    List<string> elem = new List<string>();

    XmlDocument xmldoc = new XmlDocument();
    xmldoc.LoadXml(xml);

    foreach (XmlAttribute folderName in xmldoc.SelectNodes("//folder/@name[starts-with(., '"+ startingLetter +"')]"))
    {
        elem.Add(folderName.Value);
        Console.WriteLine(folderName.Value);
    }

    return elem;
}


问:
How do you make a LinearLayout scrollable?
I have lot of items on the screen and I need to use the scrollbar so the user can scroll down. However, the scroll is either not visible or it's not working. How is it possible to add a scrollbar to a LinearLayout?

答:
This can be done using the tag <ScrollView>. For ScrollView, one thing you have to remind that, ScrollView must have a single child.

If you want your full layout to be scrollable then add <ScrollView> at the top. Check the example given below.

```<code><ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/scroll"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:id="@+id/container"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">
            <!-- Content here -->
    </LinearLayout>

</ScrollView>
</code>```

But if you want some part of your layout to be scrollable then add <ScrollView> within that part. Check the example given below.

```<code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="400dp">

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="vertical">
                <!-- Content here -->
        </LinearLayout>

    </ScrollView>

</LinearLayout>
</code>```

Body:
This can be done using the tag <ScrollView>. For ScrollView, one thing you have to remind that, ScrollView must have a single child.

If you want your full layout to be scrollable then add <ScrollView> at the top. Check the example given below.

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/scroll"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:id="@+id/container"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">
            <!-- Content here -->
    </LinearLayout>

</ScrollView>

But if you want some part of your layout to be scrollable then add <ScrollView> within that part. Check the example given below.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="400dp">

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="vertical">
                <!-- Content here -->
        </LinearLayout>

    </ScrollView>

</LinearLayout>


问:
Xts Error when calculating return
I am getting the following error from Xts package when I call periodReturns function. I have upgraded the Quantmod and Xts packages from github but still the error persists.
Can anyone suggest how to fix this ?

Thanks,

```<code>getSymbols('AAPL', src = 'yahoo', from = '2016-01-01', auto.assign = T)

> periodReturn(AAPL,by=years,from='2003-01-01')
Error in lag.xts(x1, K.) :
INTEGER() can only be applied to a 'integer', not a 'double'

> sessionInfo()
R version 3.4.0 (2017-04-21)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 8.1 x64 (build 9600)

Matrix products: default

locale:
[1] LC_COLLATE=English_Australia.1252  LC_CTYPE=English_Australia.1252    LC_MONETARY=English_Australia.1252
[4] LC_NUMERIC=C                       LC_TIME=English_Australia.1252

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

other attached packages:
[1] PerformanceAnalytics_1.5.1 quantmod_0.4-9             TTR_0.23-1                 xts_0.10-0
[5] zoo_1.8-0

loaded via a namespace (and not attached):
 [1] Rcpp_0.12.10              lattice_0.20-35           codetools_0.2-15          IKTrading_1.0
 [5] foreach_1.4.4             grid_3.4.0                curl_2.6                  boot_1.3-19
 [9] blotter_0.11.3            iterators_1.0.8           FinancialInstrument_1.2.0 compiler_3.4.0
[13] quantstrat_0.10.0
</code>```

Title: Xts Error when calculating return

Body:
I am getting the following error from Xts package when I call periodReturns function. I have upgraded the Quantmod and Xts packages from github but still the error persists.
Can anyone suggest how to fix this ?

Thanks,

getSymbols('AAPL', src = 'yahoo', from = '2016-01-01', auto.assign = T)

> periodReturn(AAPL,by=years,from='2003-01-01')
Error in lag.xts(x1, K.) :
INTEGER() can only be applied to a 'integer', not a 'double'

> sessionInfo()
R version 3.4.0 (2017-04-21)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 8.1 x64 (build 9600)

Matrix products: default

locale:
[1] LC_COLLATE=English_Australia.1252  LC_CTYPE=English_Australia.1252    LC_MONETARY=English_Australia.1252
[4] LC_NUMERIC=C                       LC_TIME=English_Australia.1252

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

other attached packages:
[1] PerformanceAnalytics_1.5.1 quantmod_0.4-9             TTR_0.23-1                 xts_0.10-0
[5] zoo_1.8-0

loaded via a namespace (and not attached):
 [1] Rcpp_0.12.10              lattice_0.20-35           codetools_0.2-15          IKTrading_1.0
 [5] foreach_1.4.4             grid_3.4.0                curl_2.6                  boot_1.3-19
 [9] blotter_0.11.3            iterators_1.0.8           FinancialInstrument_1.2.0 compiler_3.4.0
[13] quantstrat_0.10.0

Body:
I couldn't reproduce your error. Although you are downloading data from = '2016-01-01' and calculating returns from='2003-01-01' your code still worked for me. Maybe you can try to fix that and see?

> getSymbols('AAPL', src = 'yahoo', from = '2016-01-01', auto.assign = T)
[1] "AAPL"
> class(AAPL)
[1] "xts" "zoo"
> periodReturn(AAPL, by = years, from = '2003-01-01')
           monthly.returns
2016-01-29   -5.135956e-02
2016-02-29   -6.677563e-03
2016-03-31    1.272106e-01
2016-04-29   -1.399211e-01
2016-05-31    6.528700e-02
2016-06-30   -4.265975e-02
2016-07-29    9.006277e-02
2016-08-31    1.813645e-02
2016-09-30    6.550429e-02
2016-10-31    4.334348e-03
2016-11-30   -2.659859e-02
2016-12-30    4.795515e-02
2017-01-31    4.774649e-02
2017-02-28    1.288835e-01
2017-03-31    4.868968e-02
2017-04-28   -6.967841e-05
2017-05-31    6.341804e-02
2017-06-08    1.459813e-02


问:
small image link as a button at the bottom right of the image it is selling
Im trying to put a link button to amazon on a picture but not only is it not working its making my website all wonky

.review-page-lander > img {
  width: 100%;
  max-width: 1169px;
  margin: 0 auto;
}
img.buy-from-button{
  height: 35px;
  width: 150px;
  top: 35px;
  float:left;
  position: relative;
  z-index: 1;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="lander-image">

    <img class="buy-from-button" src="http://oathtohealth.com/wp-content/uploads/2016/05/Amazon.png" alt="buy at amazon">

  <img src="amazon-item.jpg">
</div>   </code>```

答:
As i mentioned in my comment, difficult to answer without more info

First off, using .review-page-lander > img wont work as the > means immediate child, http://www.w3schools.com/cssref/css_selectors.asp

To find what else not working, use F12+inspect in chrome (or similar in other browsers) to find what css being applied

https://developers.google.com/web/tools/chrome-devtools/

https://developers.google.com/web/tools/chrome-devtools/inspect-styles/


问:
Grails - Removing an item from a hasMany association List on data bind?
Grails offers the ability to automatically create and bind domain objects to a hasMany List, as described in the grails user guide.

So, for example, if my domain object "Author" has a List of many "Book" objects, I could create and bind these using the following markup (from the user guide):

```<code><g:textField name="books[0].title" value="the Stand" />
<g:textField name="books[1].title" value="the Shining" />
<g:textField name="books[2].title" value="Red Madder" />
</code>```

In this case, if any of the books specified don't already exist, Grails will create them and set their titles appropriately. If there are already books in the specified indices, their titles will be updated and they will be saved. My question is: is there some easy way to tell Grails to remove one of those books from the 'books' association on data bind?

The most obvious way to do this would be to omit the form element that corresponds to the domain instance you want to delete; unfortunately, this does not work, as per the user guide:

Then Grails will automatically create
  a new instance for you at the defined
  position. If you "skipped" a few
  elements in the middle ... Then Grails
  will automatically create instances in
  between.

I realize that a specific solution could be engineered as part of a command object, or as part of a particular controller- however, the need for this functionality appears repeatedly throughout my application, across multiple domain objects and for associations of many different types of objects. A general solution, therefore, would be ideal. Does anyone know if there is something like this included in Grails?

答:
Just ran into this issue myself. It's easy to solve. Grails uses java.util.Set to represent lists. You can just use the clear() method to wipe the data, and then add in the ones you want.

```<code>//clear all documents
bidRequest.documents.clear()

//add the selected ones back
params.documentId.each() {
    def Document document = Document.get(it)
    bidRequest.documents.add(document)
    log.debug("in associateDocuments: added " + document)
};

//try to save the changes
if (!bidRequest.save(flush: true)) {
    return error()
} else {
    flash.message = "Successfully associated documents"
}
</code>```

I bet you can do the same thing by using the "remove()" method in the case that you don't want to "clear()" all the data.

Body:
Grails offers the ability to automatically create and bind domain objects to a hasMany List, as described in the grails user guide.

So, for example, if my domain object "Author" has a List of many "Book" objects, I could create and bind these using the following markup (from the user guide):

<g:textField name="books[0].title" value="the Stand" />
<g:textField name="books[1].title" value="the Shining" />
<g:textField name="books[2].title" value="Red Madder" />

In this case, if any of the books specified don't already exist, Grails will create them and set their titles appropriately. If there are already books in the specified indices, their titles will be updated and they will be saved. My question is: is there some easy way to tell Grails to remove one of those books from the 'books' association on data bind?

The most obvious way to do this would be to omit the form element that corresponds to the domain instance you want to delete; unfortunately, this does not work, as per the user guide:

Then Grails will automatically create
  a new instance for you at the defined
  position. If you "skipped" a few
  elements in the middle ... Then Grails
  will automatically create instances in
  between.

I realize that a specific solution could be engineered as part of a command object, or as part of a particular controller- however, the need for this functionality appears repeatedly throughout my application, across multiple domain objects and for associations of many different types of objects. A general solution, therefore, would be ideal. Does anyone know if there is something like this included in Grails?

Body:
Just ran into this issue myself. It's easy to solve. Grails uses java.util.Set to represent lists. You can just use the clear() method to wipe the data, and then add in the ones you want.

//clear all documents
bidRequest.documents.clear()

//add the selected ones back
params.documentId.each() {
    def Document document = Document.get(it)
    bidRequest.documents.add(document)
    log.debug("in associateDocuments: added " + document)
};

//try to save the changes
if (!bidRequest.save(flush: true)) {
    return error()
} else {
    flash.message = "Successfully associated documents"
}

I bet you can do the same thing by using the "remove()" method in the case that you don't want to "clear()" all the data.


问:
Visual Studio PreBuildEvent powershell The string is missing the terminator: "
Had the strangest error earlier that I was genuinely confused about, so I thought I would write up a self-answer to help people out. My googlefu turned up nothing neatly, so here we are.

This was my original line

```<code><PreBuildEvent>powershell.exe -noninteractive -command "$(solutiondir)\..\PreBuild.ps1" "$(TargetFileName)" "$(ProjectDir)" "$(SolutionDir)"</PreBuildEvent>
</code>```

and here's my PreBuild.ps1 file:

```<code>Param(
    [Parameter(Mandatory=$false)][string]$targetFileName,
    [Parameter(Mandatory=$false)][string]$projectDir,
    [Parameter(Mandatory=$false)][string]$solutionDir
)
process {
    Write-Host "`$targetFileName $targetFileName";
    Write-Host "`$projectDir $projectDir";
    Write-Host "`$solutionDir $solutionDir";
}
</code>```

For some reason the variable $projectDir in my script contains both the projectdir and the solutiondir. Like so:

```<code>2>  Processing files with gulp script.
2>  $targetFileName project.dll
2>  $projectDir c:\src\sln\project c:\src\sln
</code>```

So I changed it to this

```<code><PreBuildEvent>powershell.exe -noninteractive -command "$(solutiondir)\..\PreBuild.ps1" "$(TargetFileName)" "$(ProjectDir)"</PreBuildEvent>
</code>```

and I get this error in VS Output:  The string is missing the terminator: ".

答:
Here's where I messed up. $(ProjectDir) ends with a trailing slash. So effectively my command is:

```<code>powershell.exe -noninteractive -command "c:\src\sln\project\..\PreBuild.ps1" "project.dll" "c:\src\sln\project\"
</code>```

Do you see it? It's subtle, took me a few minutes. It's the \" at the end. That escapes the quote, making the string unbounded. Hence the missing closing quote.

So now if I put simply this line:

```<code><PreBuildEvent>powershell.exe -noninteractive -command "$(solutiondir)\..\PreBuild.ps1" $(TargetFileName) $(ProjectDir)</PreBuildEvent>
</code>```

It all works as expected. The quotes were really because I was afraid of spaces. If someone ends up with some in their paths, I'll go back and punt.

Body:
Had the strangest error earlier that I was genuinely confused about, so I thought I would write up a self-answer to help people out. My googlefu turned up nothing neatly, so here we are.

This was my original line

<PreBuildEvent>powershell.exe -noninteractive -command "$(solutiondir)\..\PreBuild.ps1" "$(TargetFileName)" "$(ProjectDir)" "$(SolutionDir)"</PreBuildEvent>

and here's my PreBuild.ps1 file:

Param(
    [Parameter(Mandatory=$false)][string]$targetFileName,
    [Parameter(Mandatory=$false)][string]$projectDir,
    [Parameter(Mandatory=$false)][string]$solutionDir
)
process {
    Write-Host "`$targetFileName $targetFileName";
    Write-Host "`$projectDir $projectDir";
    Write-Host "`$solutionDir $solutionDir";
}

For some reason the variable $projectDir in my script contains both the projectdir and the solutiondir. Like so:

2>  Processing files with gulp script.
2>  $targetFileName project.dll
2>  $projectDir c:\src\sln\project c:\src\sln

So I changed it to this

<PreBuildEvent>powershell.exe -noninteractive -command "$(solutiondir)\..\PreBuild.ps1" "$(TargetFileName)" "$(ProjectDir)"</PreBuildEvent>

and I get this error in VS Output:  The string is missing the terminator: ".

Body:
Here's where I messed up. $(ProjectDir) ends with a trailing slash. So effectively my command is:

powershell.exe -noninteractive -command "c:\src\sln\project\..\PreBuild.ps1" "project.dll" "c:\src\sln\project\"

Do you see it? It's subtle, took me a few minutes. It's the \" at the end. That escapes the quote, making the string unbounded. Hence the missing closing quote.

So now if I put simply this line:

<PreBuildEvent>powershell.exe -noninteractive -command "$(solutiondir)\..\PreBuild.ps1" $(TargetFileName) $(ProjectDir)</PreBuildEvent>

It all works as expected. The quotes were really because I was afraid of spaces. If someone ends up with some in their paths, I'll go back and punt.


问:
jquery sorting function and prepend/insertAfter?
I have a function to sort list items based on the date and class of the list item. It's late and I am tired and frustrated, so not sure what I am missing here.

The function should first determine if the class is .pinned and sort them by date and insert them to the top of the list.

Then it should look at the date of the item (found in data-date) and if it is earlier than today, add the class .past sort them by date, and then insert them after the pinned items.

Lastly, it should sort the remaining items and insert them after the last item with the class of .past

here is the code:

```<code>//sort todo list-items by type and then date
function sortTodo() {
  var itemDate = "";
  var date = new Date();
  $(".todo-list-item").each(function() {
    var itemDate = new Date($(this).data("date"));
    if($(this).hasClass('pinned')) {
      $(".todo-list-item.pinned").sort(function(a,b) {
        return date > itemDate;
      }).each(function() {
          $(".todo-list").prepend(this);
      })
    } else if(date > itemDate) {
      $(this).addClass("past");
      $(".todo-list-item.past").sort(function(a,b) {
          return date > itemDate;
      }).each(function() {
          $(".todo-list").prepend(this);
      })
    } else {
      $(".todo-list-item").not(".pinned, .past").sort(function(a,b) {
        return date > itemDate;
      }).each(function() {
          $(".todo-list").append(this);
      })
    }
  });
}

$(document).ready(function() {
    sortTodo();
});
</code>```

CODE PEN DEMO

as of now, the script not placing pinned items to the top as desired, unless I add a new pinned item, and is not sorting by date after an items class changes or is removed.

答:
Your code is sorting and moving elements in three separate steps once per item (!). This messes up the order of the overall result.

Just sort once and append different sections of the sorted list one after another (jQuery .filter() is useful for this). When you're through, all items will have been re-ordered.

Note about Array#sort: It does not work when you return true or false. It expects you return numbers less than, equal to or greater than 0. Luckily, subtracting dates from one another gives you exactly these kinds of numbers.

The following sorts all items across all lists on the page.

// helper
function appendToParent() { this.parentNode.appendChild(this); }

$(function() {
  var $items = $(".todo-list-item").sort(function(a, b) {
    return new Date($(a).data("date")) - new Date($(b).data("date"));
  });

  // append items by priority
  $items.filter(".pinned").each(appendToParent);
  $items.filter(".pinned.past").each(appendToParent);
  $items.filter(":not(.pinned)").each(appendToParent);
  $items.filter(":not(.pinned).past").each(appendToParent);
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.past { font-style: italic; }
.pinned { color: red; }</code>```

List 1

Past Item 5

Item 4

Item 1 (pinned)

Item 3

Past Item 2 (Pinned)

List 2

Past Item 5

Item 4

Item 1 (pinned)

Item 3

Past Item 2 (Pinned)

```
</div>
</div>
</p>

<p>Toggling the <code>.past</code> class is easy, too, but I've left it out of the sample code above because at some point in the future all items here would end up being "past", which would defy the purpose of the sample code.</p>

```$items.each(function () {
  $(this).toggleClass("past", new Date( $(this).data("date") ) < Date.now());
});
```

Body:
I have a function to sort list items based on the date and class of the list item. It's late and I am tired and frustrated, so not sure what I am missing here.

The function should first determine if the class is .pinned and sort them by date and insert them to the top of the list.

Then it should look at the date of the item (found in data-date) and if it is earlier than today, add the class .past sort them by date, and then insert them after the pinned items.

Lastly, it should sort the remaining items and insert them after the last item with the class of .past

here is the code:

//sort todo list-items by type and then date
function sortTodo() {
  var itemDate = "";
  var date = new Date();
  $(".todo-list-item").each(function() {
    var itemDate = new Date($(this).data("date"));
    if($(this).hasClass('pinned')) {
      $(".todo-list-item.pinned").sort(function(a,b) {
        return date > itemDate;
      }).each(function() {
          $(".todo-list").prepend(this);
      })
    } else if(date > itemDate) {
      $(this).addClass("past");
      $(".todo-list-item.past").sort(function(a,b) {
          return date > itemDate;
      }).each(function() {
          $(".todo-list").prepend(this);
      })
    } else {
      $(".todo-list-item").not(".pinned, .past").sort(function(a,b) {
        return date > itemDate;
      }).each(function() {
          $(".todo-list").append(this);
      })
    }
  });
}

$(document).ready(function() {
    sortTodo();
});

CODE PEN DEMO

as of now, the script not placing pinned items to the top as desired, unless I add a new pinned item, and is not sorting by date after an items class changes or is removed.

Body:
Your code is sorting and moving elements in three separate steps once per item (!). This messes up the order of the overall result.

Just sort once and append different sections of the sorted list one after another (jQuery .filter() is useful for this). When you're through, all items will have been re-ordered.

Note about Array#sort: It does not work when you return true or false. It expects you return numbers less than, equal to or greater than 0. Luckily, subtracting dates from one another gives you exactly these kinds of numbers.

The following sorts all items across all lists on the page.

// helper
function appendToParent() { this.parentNode.appendChild(this); }

$(function() {
  var $items = $(".todo-list-item").sort(function(a, b) {
    return new Date($(a).data("date")) - new Date($(b).data("date"));
  });

  // append items by priority
  $items.filter(".pinned").each(appendToParent);
  $items.filter(".pinned.past").each(appendToParent);
  $items.filter(":not(.pinned)").each(appendToParent);
  $items.filter(":not(.pinned).past").each(appendToParent);
});

.past { font-style: italic; }
.pinned { color: red; }

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

List 1
<ul class="todo-list">
  <li class="todo-list-item past" data-date="2017-05-03">Past Item 5</li>
  <li class="todo-list-item" data-date="2017-06-04">Item 4</li>
  <li class="todo-list-item pinned" data-date="2017-06-02">Item 1 (pinned)</li>
  <li class="todo-list-item" data-date="2017-06-03">Item 3</li>
  <li class="todo-list-item pinned past" data-date="2017-05-03">Past Item 2 (Pinned)</li>
</ul>

List 2
<ul class="todo-list">
  <li class="todo-list-item past" data-date="2017-05-03">Past Item 5</li>
  <li class="todo-list-item" data-date="2017-06-04">Item 4</li>
  <li class="todo-list-item pinned" data-date="2017-06-02">Item 1 (pinned)</li>
  <li class="todo-list-item" data-date="2017-06-03">Item 3</li>
  <li class="todo-list-item pinned past" data-date="2017-05-03">Past Item 2 (Pinned)</li>
</ul>

Toggling the .past class is easy, too, but I've left it out of the sample code above because at some point in the future all items here would end up being "past", which would defy the purpose of the sample code.

$items.each(function () {
  $(this).toggleClass("past", new Date( $(this).data("date") ) < Date.now());
});


问:
How to calculate the difference in days for two Date in Swift as days start at 6 a.m. instead of 0
I'm trying to get the difference in two Date objects.
I know how to do it basically, which is like this:

```<code>        let date = Date()
        let dateFormatter = DateFormatter()
        dateFormatter.locale = Locale.current

        print(count)
        // print(history[count - 1].value(forKey: "multipleURLs") as! [String])
        let latestDate = history[count - 1].value(forKey: "date") as! Date
        let calendar = Calendar.current

        let components = calendar.dateComponents([.year, .month, .day, .hour], from: date)

        let nowDate = calendar.startOfDay(for: date)
        let lastDate = calendar.startOfDay(for: latestDate)

        let diffDateComponent = (calendar as NSCalendar).components([NSCalendar.Unit.year, NSCalendar.Unit.month, NSCalendar.Unit.day], from: lastDate, to: nowDate, options: NSCalendar.Options.init(rawValue: 0))

        print("Status Checked" + String(describing: diffDateComponent.day))
</code>```

But I'm trying to get the result as a day start from 6 a.m. in the morning instead of 0.

So I did something like this:

```<code>        let nowDate = calendar.startOfDay(for: date.addingTimeInterval(-3600))
        let lastDate = calendar.startOfDay(for: latestDate.addingTimeInterval(-3600))
</code>```

But it doesn't seem to be working, can anyone help me with this?

答:
Thanks guy, I finally figured it out. In case anyone need it, this is how it's done:</p>

```<code>        let date = Date()
        let dateFormatter = DateFormatter()
        dateFormatter.locale = Locale.current

        let latestDate = history[count - 1].value(forKey: "date") as! Date
        let calendar = Calendar.current

        let nowDate = calendar.date(byAdding: .hour, value: -6, to: date)
        let lastDate = calendar.date(byAdding: .hour, value: -6, to: latestDate)

        let finalNowDate = calendar.startOfDay(for: nowDate!)
        let finalLastDate = calendar.startOfDay(for: lastDate!)

        let diffDateComponent = calendar.dateComponents([.day], from: finalLastDate, to: finalNowDate)
        print("dif\(diffDateComponent.day)")
</code>```

Body:
I'm trying to get the difference in two Date objects.
I know how to do it basically, which is like this:

        let date = Date()
        let dateFormatter = DateFormatter()
        dateFormatter.locale = Locale.current

        print(count)
        // print(history[count - 1].value(forKey: "multipleURLs") as! [String])
        let latestDate = history[count - 1].value(forKey: "date") as! Date
        let calendar = Calendar.current

        let components = calendar.dateComponents([.year, .month, .day, .hour], from: date)

        let nowDate = calendar.startOfDay(for: date)
        let lastDate = calendar.startOfDay(for: latestDate)

        let diffDateComponent = (calendar as NSCalendar).components([NSCalendar.Unit.year, NSCalendar.Unit.month, NSCalendar.Unit.day], from: lastDate, to: nowDate, options: NSCalendar.Options.init(rawValue: 0))

        print("Status Checked" + String(describing: diffDateComponent.day))

But I'm trying to get the result as a day start from 6 a.m. in the morning instead of 0.

So I did something like this:

        let nowDate = calendar.startOfDay(for: date.addingTimeInterval(-3600))
        let lastDate = calendar.startOfDay(for: latestDate.addingTimeInterval(-3600))

But it doesn't seem to be working, can anyone help me with this?

Body:
Thanks guy, I finally figured it out. In case anyone need it, this is how it's done:

        let date = Date()
        let dateFormatter = DateFormatter()
        dateFormatter.locale = Locale.current

        let latestDate = history[count - 1].value(forKey: "date") as! Date
        let calendar = Calendar.current

        let nowDate = calendar.date(byAdding: .hour, value: -6, to: date)
        let lastDate = calendar.date(byAdding: .hour, value: -6, to: latestDate)

        let finalNowDate = calendar.startOfDay(for: nowDate!)
        let finalLastDate = calendar.startOfDay(for: lastDate!)

        let diffDateComponent = calendar.dateComponents([.day], from: finalLastDate, to: finalNowDate)
        print("dif\(diffDateComponent.day)")