答:
I would propose to sort your list by tuple (first element, third element and date) and keep the smallest date first and then group the sorted list by first and third element and finally select first element from each subgroup:</p>

```<code>from itertools import groupby
from operator import itemgetter
from datetime import datetime

find_dup = {"one":[["1654","raj","425","16-02-2017"],["1654","mo","426","20-02-2017"],["1654","ss","425","20-02-2017"],["1654","vs","427","20-02-2017"],["1654","ss","425","14-02-2017"]]}

find_dup_sorted = sorted(find_dup["one"], key=lambda x: (x[0], x[2], datetime.strptime(x[3], "%d-%m-%Y")))

result = {"one": []}

for k, g in groupby(find_dup_sorted, key=itemgetter(0, 2)):
    result["one"].append(next(g))

print result
</code>```

Title: How to remove duplicate elements based date

Body:
I am having dictinoary which contains list of list

find_dup = {"one":[["1654","raj","425","16-02-2017"],["1654","mo","426","20-02-2017"],["1654","ss","425","20-02-2017"],["1654","vs","427","20-02-2017"],["1654","ss","425","14-02-2017"]]}

I want to find duplicated based in list of first and third element

eg

["1654","raj","425","16-02-2017"] -> 1654,425
["1654","mo","426","20-02-2017"] -> 1654,426
["1654","ss","425","20-02-2017"] -> 1654,425
["1654","vs","427","20-02-2017"] -> 1654,427
["1654","ss","425","14-02-2017"] -> 1654,425

From the above elements it shows 1654,425 are duplicates (since i want to find duplicates based on first and third elements)

So from the above list this list are duplicates

["1654","raj","425","16-02-2017"] -> 1654,425
["1654","ss","425","20-02-2017"] -> 1654,425
["1654","ss","425","14-02-2017"] -> 1654,425

now from this list we have to remove 2 elements which has older date (last element of list is date)

This 2 list has older date so this should be removed

["1654","raj","425","16-02-2017"] -> 1654,425
["1654","ss","425","14-02-2017"] -> 1654,425

Results should be this

find_dup = {"one":[["1654","mo","426","20-02-2017"],["1654","ss","425","20-02-2017"],["1654","vs","427","20-02-2017"]]}

I have python script which iterates through lists but i could not find logic on how to do pop an element if i find duplicate and replace the latest date

This is my script which failed

find_dup = {"one":[["1654","raj","425","16-02-2017"],["1654","mo","426","20-02-2017"],["1654","ss","425","20-02-2017"],["1654","vs","427","20-02-2017"],["1654","ss","425","14-02-2017"]]}

for d in find_dup:
    len_d = len(find_dup[d])
    store_array_dup = []
    store_array_ele = {}
    for i in find_dup[d]:

        val = i[0]+"-"+i[1]"-"+i[2]"-"+i[3]
        val_1 = i[0]+"-"+i[2]
        if val_1 in store_array_dup:
            store_array_ele.append(val_1)
        else:
            arrs = []
            arrs.append(val)
            store_array_ele[d] = arrs

How could i produce this results

find_dup = {"one":[["1654","mo","426","20-02-2017"],["1654","ss","425","20-02-2017"],["1654","vs","427","20-02-2017"]]}

Body:
I would propose to sort your list by tuple (first element, third element and date) and keep the smallest date first and then group the sorted list by first and third element and finally select first element from each subgroup:

from itertools import groupby
from operator import itemgetter
from datetime import datetime

find_dup = {"one":[["1654","raj","425","16-02-2017"],["1654","mo","426","20-02-2017"],["1654","ss","425","20-02-2017"],["1654","vs","427","20-02-2017"],["1654","ss","425","14-02-2017"]]}

find_dup_sorted = sorted(find_dup["one"], key=lambda x: (x[0], x[2], datetime.strptime(x[3], "%d-%m-%Y")))

result = {"one": []}

for k, g in groupby(find_dup_sorted, key=itemgetter(0, 2)):
    result["one"].append(next(g))

print result


来源: stackexchange

问:
Kentico 10 - Use a repeater to display multiple page types
We are currently use the oob page types for Blog, News and Event.  We have one page for each of these types that includes a repeater to show a list of the pages of that type.  We would also like to have a page that includes a repeater that shows all blog, news and event pages in one spot, sorted by their created date.

I have seen some old comments (here, here) on devnet saying that although a repeater can render multiple page types, the fields rendered must be identical across each of those page types.  The workarounds suggested are either to create the same fields in each page type, or to create a custom SQL query and use a query repeater to render the data.  I've done this and it works just fine, but it was pretty cumbersome to create and will be difficult to maintain.  (If we want to add other page types, for example.)  Can anyone suggest a more out-of-the-box method available in Kentico 10?

Update:

I'm trying to accomplish this as Brenden described, but am running into trouble.
My page structure is as follows:

```<code>Root
.RollupPage (CMS.MenuItem)
..BlogPosts (CMS.Blog)
...January 2017 (CMS.BlogMonth)
....blog post 1 (CMS.BlogPost)
...February 2017 (CMS.BlogMonth)
....blog post 2 (CMS.BlogPost)
..Events (CMS.MenuItem)
...Event1 (CMS.BookingEvent)
...Event2 (CMS.BookingEvent)
</code>```

I've attempted to use a universal viewer, but failed to get it to return any data.

I configured it with:

```<code>Path: /RollupPage/%
Page types: CMS.BlogPost;CMS.BookingEvent
Hierarchical Transformation: CMS.MenuItem.HierTrans1
</code>```

HierTrans1 has the following transformations:

```<code>CMS.BlogPost.Default (Item transformation for type CMS.BlogPost)
CMS.BookingEvent.EventCalendarItem (Item transformation for type CMS.BookingEvent)
</code>```

These aren't customized at all; they are standard OOB transformations just so I can see it work.

When I view the RollupPage, the universal viewer displays nothing.

I attempted to use a Hierarchical Viewer with the same settings as I did with the Universal Viewer.  It kind-of worked.  It displayed my booking events but did not display any blog posts.  Yet using the same blog post transformation (CMS.BlogPost.default) with hierarchical viewer whose Path was set to /RollupPage/BlogPosts/% displayed my blog posts correctly but, obviously, did not display my booking events.

The results I've gotten so far makes me think a) something about the way I've created my pages is stopping the universal viewer from traversing the whole tree and/or b) the hierarchical viewer either only goes a couple of levels deep, or maybe it is being blocked from traversing the tree too...  No events are recorded when I edit or view these web parts.

Any idea what I may be doing wrong?

答:
You can use the Hierarchical viewer or the Universal viewer, as Brenden Kehren mentioned, to achieve the goal you are describing.

When configuring the web part you must select all the Page types that are included in the hierarchy, in your case: CMS.MenuItem, CMS.Blog, CMS.BlogMonth, CMS.BlogPost and CMSBookingEvent.

Create a Hierarchical transformation to be used with your viewer and add an Item transformation for each of the items you wish to display. Also make sure the Level setting for each transformation is configured properly (-1 applies the transformation to all levels).

For Universal viewer it is necessary to check the property Load hierarchical data in the section Extended settings of the configuration.

As an additional note, you can leave the path property empty in case you are viewing the child documents of the current page.

For reference there is also an example on the Corporate Site example site in the content tree path Examples > Web Parts > Listings and viewers > Pages > Hierarchical viewer (or Universal viewer).

Hope this helps!

ContentLicense: CC BY-SA 3.0

Body:
We are currently use the oob page types for Blog, News and Event.  We have one page for each of these types that includes a repeater to show a list of the pages of that type.  We would also like to have a page that includes a repeater that shows all blog, news and event pages in one spot, sorted by their created date.

I have seen some old comments (here, here) on devnet saying that although a repeater can render multiple page types, the fields rendered must be identical across each of those page types.  The workarounds suggested are either to create the same fields in each page type, or to create a custom SQL query and use a query repeater to render the data.  I've done this and it works just fine, but it was pretty cumbersome to create and will be difficult to maintain.  (If we want to add other page types, for example.)  Can anyone suggest a more out-of-the-box method available in Kentico 10?

Update:

I'm trying to accomplish this as Brenden described, but am running into trouble.
My page structure is as follows:

Root
.RollupPage (CMS.MenuItem)
..BlogPosts (CMS.Blog)
...January 2017 (CMS.BlogMonth)
....blog post 1 (CMS.BlogPost)
...February 2017 (CMS.BlogMonth)
....blog post 2 (CMS.BlogPost)
..Events (CMS.MenuItem)
...Event1 (CMS.BookingEvent)
...Event2 (CMS.BookingEvent)

I've attempted to use a universal viewer, but failed to get it to return any data.

I configured it with:

Path: /RollupPage/%
Page types: CMS.BlogPost;CMS.BookingEvent
Hierarchical Transformation: CMS.MenuItem.HierTrans1

HierTrans1 has the following transformations:

CMS.BlogPost.Default (Item transformation for type CMS.BlogPost)
CMS.BookingEvent.EventCalendarItem (Item transformation for type CMS.BookingEvent)

These aren't customized at all; they are standard OOB transformations just so I can see it work.

When I view the RollupPage, the universal viewer displays nothing.

I attempted to use a Hierarchical Viewer with the same settings as I did with the Universal Viewer.  It kind-of worked.  It displayed my booking events but did not display any blog posts.  Yet using the same blog post transformation (CMS.BlogPost.default) with hierarchical viewer whose Path was set to /RollupPage/BlogPosts/% displayed my blog posts correctly but, obviously, did not display my booking events.

The results I've gotten so far makes me think a) something about the way I've created my pages is stopping the universal viewer from traversing the whole tree and/or b) the hierarchical viewer either only goes a couple of levels deep, or maybe it is being blocked from traversing the tree too...  No events are recorded when I edit or view these web parts.

Any idea what I may be doing wrong?


问:
Typescript, JSON: Mapping nested array always returns empty
I am new to typescript and trying to parse a JSON from a GET request which looks like this (removed some data):

```<code>{
   "currency_rate":1,
   "data":[
     {
        "mapIdfrom":"oslo_no",
        "refr":false,
        "duration":{
        "total":75300,
        "return":0,
        "departure":75300
     },
     "flyTo":"STR"
    }
   ]
}
</code>```

I am getting the "currency_rate" for example, but the "data"-array is empty.

The GET request looks like this (only relevant parts) :

```<code>[...]
api_url = 'https://api.skypicker.com/flights';
[...]
let body =  {
              flyFrom: 'OSL',
              to: 'STR',
              dateFrom: '01%252F04%252F2017',
              dateTo: '20%2F04%2F2017',
              daysInDestinationFrom: 15,
              daysInDestinationTo: 20,
              returnFrom: '01%2F04%2F2017',
              returnTo: '20%2F04%2F2017',
              typeFlight: 'oneway',
              oneforcity: 0,
              one_per_date: 0,
              passengers: 1,
              adults: 1,
              children: 0,
              infants: 0,
              flyDays: '%5B0%2C1%2C2%2C3%2C4%2C5%2C6%5D',
              onlyWorkingDays: 0,
              directFlights: 0,
              partner: 'picky',
              partner_market: 'en',
              v: 2,
              xml: 0,
              curr: 'EUR',
              locale: 'en',
              price_from: 1,
              price_to: 10000,
              dtimefrom: '00%3A00',
              dtimeto: '00%3A00',
              atimefrom: '00%3A00',
              atimeto: '00%3A00',
              returndtimefrom: '00%3A00',
              returndtimeto: '00%3A00',
              returnatimefrom: '00%3A00',
              returnatimeto: '00%3A00',
              stopoverfrom: '00%3A00',
              stopoverto: '00%3A00',
              booking_token: 'hashed%20data',
              offset: 0,
              limit: 30,
              sort: 'price',
              asc: 1
            }

let bodyString = JSON.stringify(body)

return this.http.get(`${this.api_url}?${bodyString}`)
  .map(res => <SkyPickerFlight>res.json());
</code>```

The model "SkyPickerFlight" is defined like this:

```<code>import { SkyPickerFlightData } from '../models/skyPickerFlightData';
import { Observable } from 'rxjs/Rx';

export interface SkyPickerFlightI {
  currency: string;
  data: Observable<any[]>;
}
</code>```

I have also tried replacing data: Observable<any[]> with data: Observable<SkyPickerFlightData[]>, the actual object, but also doesn't work.

Here you can get the full GET request:

```<code>https://api.skypicker.com/flights?flyFrom=OSL&to=STR&dateFrom=01%2F04%2F2017&dateTo=20%2F04%2F2017&daysInDestinationFrom=15&daysInDestinationTo=20&returnFrom=01%2F04%2F2017&returnTo=20%2F04%2F2017&typeFlight=oneway&oneforcity=0&one_per_date=0&passengers=1&adults=1&children=0&infants=0&flyDays=%5B0%2C1%2C2%2C3%2C4%2C5%2C6%5D&onlyWorkingDays=0&onlyWeekends=0&directFlights=0&partner=picky&partner_market=en&v=2&xml=0&curr=EUR&locale=en&price_from=1&price_to=10000&dtimefrom=00%3A00&dtimeto=00%3A00&atimefrom=00%3A00&atimeto=00%3A00&returndtimefrom=00%3A00&returndtimeto=00%3A00&returnatimefrom=00%3A00&returnatimeto=00%3A00&stopoverfrom=00%3A00&stopoverto=00%3A00&booking_token=hashed%20data&offset=0&limit=30&sort=price&asc=1
</code>```

I am still looking into it but it looks like the GET request is a bit funky using this.http.get(${this.api_url}?${bodyString}) actually returns:

```<code>{"connections":[],"currency":"EUR","del":0,"time":1,"search_params":{"to_type":"anywhere","flyFrom_type":"anywhere","seats":{"infants":0,"passengers":1,"adults":1,"children":0}},"ref_tasks":{},"currency_rate":1.0,"data":[],"refresh":[]}
</code>```

A different result than the GET request above. Not sure if I was clear. But trying the GET request like this (I will spare you with the long definition of the URLSearchParams) ends in a Bad Gateway error:

```<code>return this.http.get(this.api_url, {search: params})
  .map(res => res)
</code>```

---- EDIT -----
It worked after I copy-pasted the entire URL in:

```<code>return this.http.get(<URL PASTED HERE>)
  .map(res => res)
</code>```

Would still like to know how to pass the parameters in a clean way rather than pasting the entire URL in there.

答:
The problem was the GET request. Using URLSearchParams/RequestOptions didnt work for some reason. Kept getting a 'BAD GATEWAY' error. So I passed the url directly in the http request like so:

```<code>this.http.get('https://api.skypicker.com/flights?' + bodyStringSerialized)
</code>```

Using the below serialize function (another version of this function I found messed with the values of the param-values, so I removed the encoding). I used it likt this 'serialized(json, '')':

```<code>serialize(obj, prefix) {
var str = [], p;
for(p in obj) {
  if (obj.hasOwnProperty(p)) {
    var k = prefix ? prefix + "[" + p + "]" : p, v = obj[p];
    str.push((v !== null && typeof v === "object") ?
      this.serialize(v, k) :
      k + "=" + v);
  }
}
return str.join("&");
}
</code>```

Thanks for the help!

ContentLicense: CC BY-SA 4.0

Body:
I am new to typescript and trying to parse a JSON from a GET request which looks like this (removed some data):

{
   "currency_rate":1,
   "data":[
     {
        "mapIdfrom":"oslo_no",
        "refr":false,
        "duration":{
        "total":75300,
        "return":0,
        "departure":75300
     },
     "flyTo":"STR"
    }
   ]
}

I am getting the "currency_rate" for example, but the "data"-array is empty.

The GET request looks like this (only relevant parts) :

[...]
api_url = 'https://api.skypicker.com/flights';
[...]
let body =  {
              flyFrom: 'OSL',
              to: 'STR',
              dateFrom: '01%252F04%252F2017',
              dateTo: '20%2F04%2F2017',
              daysInDestinationFrom: 15,
              daysInDestinationTo: 20,
              returnFrom: '01%2F04%2F2017',
              returnTo: '20%2F04%2F2017',
              typeFlight: 'oneway',
              oneforcity: 0,
              one_per_date: 0,
              passengers: 1,
              adults: 1,
              children: 0,
              infants: 0,
              flyDays: '%5B0%2C1%2C2%2C3%2C4%2C5%2C6%5D',
              onlyWorkingDays: 0,
              directFlights: 0,
              partner: 'picky',
              partner_market: 'en',
              v: 2,
              xml: 0,
              curr: 'EUR',
              locale: 'en',
              price_from: 1,
              price_to: 10000,
              dtimefrom: '00%3A00',
              dtimeto: '00%3A00',
              atimefrom: '00%3A00',
              atimeto: '00%3A00',
              returndtimefrom: '00%3A00',
              returndtimeto: '00%3A00',
              returnatimefrom: '00%3A00',
              returnatimeto: '00%3A00',
              stopoverfrom: '00%3A00',
              stopoverto: '00%3A00',
              booking_token: 'hashed%20data',
              offset: 0,
              limit: 30,
              sort: 'price',
              asc: 1
            }

let bodyString = JSON.stringify(body)

return this.http.get(`${this.api_url}?${bodyString}`)
  .map(res => <SkyPickerFlight>res.json());

The model "SkyPickerFlight" is defined like this:

import { SkyPickerFlightData } from '../models/skyPickerFlightData';
import { Observable } from 'rxjs/Rx';

export interface SkyPickerFlightI {
  currency: string;
  data: Observable<any[]>;
}

I have also tried replacing data: Observable<any[]> with data: Observable<SkyPickerFlightData[]>, the actual object, but also doesn't work.

Here you can get the full GET request:

https://api.skypicker.com/flights?flyFrom=OSL&to=STR&dateFrom=01%2F04%2F2017&dateTo=20%2F04%2F2017&daysInDestinationFrom=15&daysInDestinationTo=20&returnFrom=01%2F04%2F2017&returnTo=20%2F04%2F2017&typeFlight=oneway&oneforcity=0&one_per_date=0&passengers=1&adults=1&children=0&infants=0&flyDays=%5B0%2C1%2C2%2C3%2C4%2C5%2C6%5D&onlyWorkingDays=0&onlyWeekends=0&directFlights=0&partner=picky&partner_market=en&v=2&xml=0&curr=EUR&locale=en&price_from=1&price_to=10000&dtimefrom=00%3A00&dtimeto=00%3A00&atimefrom=00%3A00&atimeto=00%3A00&returndtimefrom=00%3A00&returndtimeto=00%3A00&returnatimefrom=00%3A00&returnatimeto=00%3A00&stopoverfrom=00%3A00&stopoverto=00%3A00&booking_token=hashed%20data&offset=0&limit=30&sort=price&asc=1

I am still looking into it but it looks like the GET request is a bit funky using this.http.get(${this.api_url}?${bodyString}) actually returns:

{"connections":[],"currency":"EUR","del":0,"time":1,"search_params":{"to_type":"anywhere","flyFrom_type":"anywhere","seats":{"infants":0,"passengers":1,"adults":1,"children":0}},"ref_tasks":{},"currency_rate":1.0,"data":[],"refresh":[]}

A different result than the GET request above. Not sure if I was clear. But trying the GET request like this (I will spare you with the long definition of the URLSearchParams) ends in a Bad Gateway error:

return this.http.get(this.api_url, {search: params})
  .map(res => res)

---- EDIT -----
It worked after I copy-pasted the entire URL in:

return this.http.get(<URL PASTED HERE>)
  .map(res => res)

Would still like to know how to pass the parameters in a clean way rather than pasting the entire URL in there.

Body:
The problem was the GET request. Using URLSearchParams/RequestOptions didnt work for some reason. Kept getting a 'BAD GATEWAY' error. So I passed the url directly in the http request like so:

this.http.get('https://api.skypicker.com/flights?' + bodyStringSerialized)

Using the below serialize function (another version of this function I found messed with the values of the param-values, so I removed the encoding). I used it likt this 'serialized(json, '')':

serialize(obj, prefix) {
var str = [], p;
for(p in obj) {
  if (obj.hasOwnProperty(p)) {
    var k = prefix ? prefix + "[" + p + "]" : p, v = obj[p];
    str.push((v !== null && typeof v === "object") ?
      this.serialize(v, k) :
      k + "=" + v);
  }
}
return str.join("&");
}

Thanks for the help!


问:
Print out only headers in Rails request
I know how to access a header in Rails

```<code>request.headers["HEADER_NAME"]
</code>```

However, I want to get all headers passed by a browser. I see that I can enumerate it

```<code>request.headers.each { |header| ... }
</code>```

However, this will spit out both headers and other environment variables. Is there a way to get only headers?

Update 1

My problem isn't interation. My problem is distinguising between environment variables and headers. Both of them will be reported while interation using each or keys.

答:
You can try this to get only headers list from request

```<code>request.headers.first(50).to_h.keys
</code>```

It will convert request.headers object into array and then to hash to get list of all keys in request to be used as

```<code>request.headers["keyname"]
</code>```

It might be not much efficient but I think it can do the job.

Hope this helps.

Title: Print out only headers in Rails request

Body:
I know how to access a header in Rails

request.headers["HEADER_NAME"]

However, I want to get all headers passed by a browser. I see that I can enumerate it

request.headers.each { |header| ... }

However, this will spit out both headers and other environment variables. Is there a way to get only headers?

Update 1

My problem isn't interation. My problem is distinguising between environment variables and headers. Both of them will be reported while interation using each or keys.

Body:
You can try this to get only headers list from request

request.headers.first(50).to_h.keys

It will convert request.headers object into array and then to hash to get list of all keys in request to be used as

request.headers["keyname"]

It might be not much efficient but I think it can do the job.

Hope this helps.


问:
How do we index a tensor in python?
I'm trying to understand the following code.

```<code>content_array[:, :, :, 0] -= 103.939
content_array[:, :, :, 1] -= 116.779
content_array[:, :, :, 2] -= 123.68
content_array = content_array[:, :, :, ::-1]

style_array[:, :, :, 0] -= 103.939
style_array[:, :, :, 1] -= 116.779
style_array[:, :, :, 2] -= 123.68
style_array = style_array[:, :, :, ::-1]
</code>```

content_array and style_array are arrays with dimensions of
(1, 512, 512, 3) respectively.

What i don't really understand is the indexing([:, :, :, 0], [:, :, :, 1], [:, :, :, 2]). Does this means we are indexing each dimension? and why do we use ':'?

答:
One of numpy's most interesting indexing features, is the ability to index slices. Slices are subarrays in a given dimensions, they are written in the form of i:j:k where i is the starting index, j the ending (not included), and k the step. Specifying all 3 parameters would be tedious most of the time, that's why they all have default values. i=0, j=n where n is the length of the array, k=1. Therefore selecting all the elements along a dimension would come down to writting array[::] for which a syntactic sugar is array[:].

Therefore content_array[:, :, :, 0] is an array of dimension (1, 512, 512). And writing content_array[:, :, :, 0] -= 103.939 means set all the values of the array taken by selecting all the elements such that they have index 0 on last dimension, and decrement all these elements by 103.939.

I would recommend that you read https://docs.scipy.org/doc/numpy/reference/arrays.indexing.html.

Title: How do we index a tensor in python?

Body:
I'm trying to understand the following code.

content_array[:, :, :, 0] -= 103.939
content_array[:, :, :, 1] -= 116.779
content_array[:, :, :, 2] -= 123.68
content_array = content_array[:, :, :, ::-1]

style_array[:, :, :, 0] -= 103.939
style_array[:, :, :, 1] -= 116.779
style_array[:, :, :, 2] -= 123.68
style_array = style_array[:, :, :, ::-1]

content_array and style_array are arrays with dimensions of
(1, 512, 512, 3) respectively.

What i don't really understand is the indexing([:, :, :, 0], [:, :, :, 1], [:, :, :, 2]). Does this means we are indexing each dimension? and why do we use ':'?


问:
Unable to resume alarm after reboot android
I need to resume an alarm after reboot. I am saving alarm time in SharedPreferences before reboot and after reboot i am setting an alarm with that time but it doesn't fire at all.
Here is my code for the alarm in my Helpers class:

```<code>public static void scheduleNotification(Notification notification, long delay) {

    Intent notificationIntent = new Intent(AppGlobals.getContext(), AlarmReceiver.class);
    notificationIntent.putExtra(AlarmReceiver.NOTIFICATION_ID, 1);
    notificationIntent.putExtra(AlarmReceiver.NOTIFICATION, notification);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(AppGlobals.getContext(), 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);

    long futureInMillis = SystemClock.elapsedRealtime() + delay;
    AlarmManager alarmManager = (AlarmManager)AppGlobals.getContext().getSystemService(Context.ALARM_SERVICE);
    alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, futureInMillis, pendingIntent);
    AppGlobals.putAlarmTime(futureInMillis);
    System.out.println("Alarm time before: " + futureInMillis);
}
</code>```

I am using the above code for scheduling an alarm before reboot in another class and it works fine until a reboot.

Here is my AlarmReceiver class code:

```<code>public class AlarmReceiver extends BroadcastReceiver {

public static String NOTIFICATION_ID = "notification-id";
public static String NOTIFICATION = "notification";

@Override
public void onReceive(Context context, Intent intent) {
    NotificationManager notificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
    Notification notification = intent.getParcelableExtra(NOTIFICATION);
    int id = intent.getIntExtra(NOTIFICATION_ID, 0);
    notificationManager.notify(id, notification);
    Toast.makeText(context, "Alarm!!!", Toast.LENGTH_LONG).show();
}
</code>```

Code for BootStateListener class:

```<code>public class BootStateListenerService extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {
    if (intent.getAction().equals("android.intent.action.BOOT_COMPLETED")) {
        PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
        AlarmManager alarmManager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
        alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, AppGlobals.getAlarmTime(), pendingIntent);
        System.out.println("Alarm time after reboot: " + AppGlobals.getAlarmTime());
    }
}
</code>```

AndroidManifest Code:

```<code><uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<uses-permission android:name="android.permission.WAKE_LOCK"/>

<application
    android:name=".utils.AppGlobals"
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".MainActivity"
        android:screenOrientation="portrait"
        android:windowSoftInputMode="adjustPan">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <service android:name=".services.LocationService" />
    <receiver android:name=".services.BootStateListenerService"
        android:enabled="true">
        <intent-filter>
            <action android:name="android.intent.action.BOOT_COMPLETED"></action>
        </intent-filter>
    </receiver>

    <receiver android:name=".receivers.AlarmReceiver" />
</application>
</code>```

I am getting the same time after reboot in Logs which means my bootstatelistener class code is also working but it doesn't fire alarm at all.

答:
Add this in your activity from u call alaram

```<code>    ComponentName receiver = new ComponentName(Activity.this, BootStateListenerService .class);
    PackageManager pm = Activity.this.getPackageManager();

    pm.setComponentEnabledSetting(receiver, PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
            PackageManager.DONT_KILL_APP);
</code>```

Body:
I need to resume an alarm after reboot. I am saving alarm time in SharedPreferences before reboot and after reboot i am setting an alarm with that time but it doesn't fire at all.
Here is my code for the alarm in my Helpers class:

public static void scheduleNotification(Notification notification, long delay) {

    Intent notificationIntent = new Intent(AppGlobals.getContext(), AlarmReceiver.class);
    notificationIntent.putExtra(AlarmReceiver.NOTIFICATION_ID, 1);
    notificationIntent.putExtra(AlarmReceiver.NOTIFICATION, notification);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(AppGlobals.getContext(), 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);

    long futureInMillis = SystemClock.elapsedRealtime() + delay;
    AlarmManager alarmManager = (AlarmManager)AppGlobals.getContext().getSystemService(Context.ALARM_SERVICE);
    alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, futureInMillis, pendingIntent);
    AppGlobals.putAlarmTime(futureInMillis);
    System.out.println("Alarm time before: " + futureInMillis);
}

I am using the above code for scheduling an alarm before reboot in another class and it works fine until a reboot.

Here is my AlarmReceiver class code:

public class AlarmReceiver extends BroadcastReceiver {

public static String NOTIFICATION_ID = "notification-id";
public static String NOTIFICATION = "notification";

@Override
public void onReceive(Context context, Intent intent) {
    NotificationManager notificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
    Notification notification = intent.getParcelableExtra(NOTIFICATION);
    int id = intent.getIntExtra(NOTIFICATION_ID, 0);
    notificationManager.notify(id, notification);
    Toast.makeText(context, "Alarm!!!", Toast.LENGTH_LONG).show();
}

Code for BootStateListener class:

public class BootStateListenerService extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {
    if (intent.getAction().equals("android.intent.action.BOOT_COMPLETED")) {
        PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
        AlarmManager alarmManager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
        alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, AppGlobals.getAlarmTime(), pendingIntent);
        System.out.println("Alarm time after reboot: " + AppGlobals.getAlarmTime());
    }
}

AndroidManifest Code:

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<uses-permission android:name="android.permission.WAKE_LOCK"/>

<application
    android:name=".utils.AppGlobals"
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".MainActivity"
        android:screenOrientation="portrait"
        android:windowSoftInputMode="adjustPan">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <service android:name=".services.LocationService" />
    <receiver android:name=".services.BootStateListenerService"
        android:enabled="true">
        <intent-filter>
            <action android:name="android.intent.action.BOOT_COMPLETED"></action>
        </intent-filter>
    </receiver>

    <receiver android:name=".receivers.AlarmReceiver" />
</application>

I am getting the same time after reboot in Logs which means my bootstatelistener class code is also working but it doesn't fire alarm at all.

Body:
Add this in your activity from u call alaram

    ComponentName receiver = new ComponentName(Activity.this, BootStateListenerService .class);
    PackageManager pm = Activity.this.getPackageManager();

    pm.setComponentEnabledSetting(receiver, PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
            PackageManager.DONT_KILL_APP);


问:
Amazon EC2, elastic beanstalk, need static outbound IP's
I need to integrate with a service, that needs to know my IP's in advance to whitelist them, my app is hosted on EBS amazon with autoscaling.

Is this possible?

Here is what my current config file looks like.

```<code>Resources:
  # LB SG
  AWSEBLoadBalancerSecurityGroup:
    Type: "AWS::EC2::SecurityGroup"
    Properties:
      GroupDescription: "Generated by app"
      SecurityGroupIngress:
        - {CidrIp: "0.0.0.0/0", IpProtocol: "tcp", FromPort: "80", ToPort: "80"}
        - {CidrIp: "0.0.0.0/0", IpProtocol: "tcp", FromPort: "443", ToPort: "443"}

  # CONFIGURE LB Health Check different port

  # EB SG
  AWSEBSecurityGroup:
    Type: "AWS::EC2::SecurityGroup"
    Properties:
      GroupDescription: "Generated by app"
      SecurityGroupIngress:
        - {SourceSecurityGroupId: {Ref: "AWSEBLoadBalancerSecurityGroup"}, IpProtocol: "tcp", FromPort: "80", ToPort: "80"}
        - {SourceSecurityGroupId: {Ref: "AWSEBLoadBalancerSecurityGroup"}, IpProtocol: "tcp", FromPort: "443", ToPort: "443"}
        - {CidrIp: "0.0.0.0/0", IpProtocol: "tcp", FromPort: "22", ToPort: "22"}

option_settings:
  aws:elb:listener:80:
    ListenerProtocol: HTTP
    InstancePort: 80
    InstanceProtocol: HTTP
  aws:elb:listener:443:
    ListenerProtocol: TCP
    InstancePort: 443
    InstanceProtocol: TCP
</code>```

To make this easy, can i somehow reserve a range of IP's and make EBS prefer them when launching a new instance ?

答:
If I understood your question right, I think you are looking for elastic IP.
http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/elastic-ip-addresses-eip.html </p>

Body:
I need to integrate with a service, that needs to know my IP's in advance to whitelist them, my app is hosted on EBS amazon with autoscaling.

Is this possible?

Here is what my current config file looks like.

Resources:
  # LB SG
  AWSEBLoadBalancerSecurityGroup:
    Type: "AWS::EC2::SecurityGroup"
    Properties:
      GroupDescription: "Generated by app"
      SecurityGroupIngress:
        - {CidrIp: "0.0.0.0/0", IpProtocol: "tcp", FromPort: "80", ToPort: "80"}
        - {CidrIp: "0.0.0.0/0", IpProtocol: "tcp", FromPort: "443", ToPort: "443"}

  # CONFIGURE LB Health Check different port

  # EB SG
  AWSEBSecurityGroup:
    Type: "AWS::EC2::SecurityGroup"
    Properties:
      GroupDescription: "Generated by app"
      SecurityGroupIngress:
        - {SourceSecurityGroupId: {Ref: "AWSEBLoadBalancerSecurityGroup"}, IpProtocol: "tcp", FromPort: "80", ToPort: "80"}
        - {SourceSecurityGroupId: {Ref: "AWSEBLoadBalancerSecurityGroup"}, IpProtocol: "tcp", FromPort: "443", ToPort: "443"}
        - {CidrIp: "0.0.0.0/0", IpProtocol: "tcp", FromPort: "22", ToPort: "22"}

option_settings:
  aws:elb:listener:80:
    ListenerProtocol: HTTP
    InstancePort: 80
    InstanceProtocol: HTTP
  aws:elb:listener:443:
    ListenerProtocol: TCP
    InstancePort: 443
    InstanceProtocol: TCP

To make this easy, can i somehow reserve a range of IP's and make EBS prefer them when launching a new instance ?


问:
Position div to bottom of a different div, without using Absolute
I have one div in another div. The inner div has margins of 0, auto to centralize it. However, I can't get it to float to the bottom without making it absolute. Is there anyway of making a relative div float to the bottom of a normal div? </p>

答:
Add this styling to the inner div.</p>

```<code>position: relative;
top: 100%;
transform: translateY(-100%);
</code>```

Body:
Add this styling to the inner div.

position: relative;
top: 100%;
transform: translateY(-100%);


问:
Grails, executing a javascript by clicking on a column in a table row
I have a view consisting of two lists: products and offers. You can select several rows by checking checkboxes on them and then by clicking on a link, offer lines will be created for each selected product.
Every offer line has the id of the product which I will use to list all offers created for that product in a list below the list of products.

I tried to solve that by using a javascript which should be activated when you click on a link or field in the product list.
The script sends a message to the controller that creates the list of offers for this product and then render a template in this view.

I can just use a link and call the controller and the template will be rendered but of course not the rest of the view.

So I need to have line:

```<code><td><g:link action="listOffers" id="${pb.id}">${pb.volumeOffered}</g:link></td>
</code>```

replaced with something better that can call my javascript-function.
I read somewhere you could put an -onclick="javascript-function" in the g:link tag but it doesn't work.

Below is the most important part of controller and gsp in this case.

In the List.gsp:

```<code>    <script type="text/javascript">
        function listOffers(id){
        $.ajax({
                url:'${g.createLink( controller:'ordersAndStore', action:'listOffers' )}',
        data: [id],
        type: 'get'
        }).success( function ( data ) { $( '#offerList' ).html( data ); });
        }
    </script>
.....
.....
    <g:render template="ListOffers" model="[offerDetails:offerDetails]"/>
</code>```

In the template _AvailableProductData.gsp:

```<code>    <g:each in="${prodBuffer}" status="i" var="pb">
  <tr class="${ (i % 2) == 0 ? 'even': 'odd'}">
                <td><a onclick="listOffers(${pb.id})">${pb.volumeOffered}</a></td>
</code>```

In the template _ListOffers.gsp:

```<code><div id="offerList">
    <g:set var="entityName" value='Offers' />
    <div id="list-offers" class="content scaffold-list" role="main">
        <h1><g:message code="default.list.label" args="[entityName]" /></h1>
        <table style="width:100%">
            <thead>
                <tr>
                    <g:sortableColumn property="product" title='Product' />
                    <g:sortableColumn property="volumeOffered" title='Volume' />
                </tr>
            </thead>
            <tbody>
                <g:each in="${offerDetails}" status="i" var="od">
                    <tr class="${ (i % 2) == 0 ? 'even': 'odd'}">
                        <td><g:link class="edit" action="edit" resource="offerDetail" id="${od?.id}"> ${od.product?.encodeAsHTML()}</g:link></td>
                        <td>${od?.volumeOffered}</td>
                    </tr>
                </g:each>
            </tbody>
        </table>
        <div class="pagination">
            <g:paginate total="${offersCount ?: 0}" />
        </div>
    </div>
</div>
</code>```

In the controller:

```<code>def listOffers(){
    def List<OfferDetail> offerDetails = getOfferList()
    render(template:"ListOffers", model:[offerDetails: offerDetails])
}
</code>```

Added a printout to see what params contains:

```<code>def listOffers(){
    System.out.println("#--#"+params)
    def List<OfferDetail> offerDetails = getOfferList()
    render(template:"ListOffers", model:[offerDetails: offerDetails])
}
</code>```

The printout is:

```<code>#--#[undefined:, controller:ordersAndStore, format:null, action:listOffers]
</code>```

Following is the complete javascript section, the first one is working good but then comes the onclick version that responds and calls the controller but can not send the id. Then comes your version and another one simple but no one is working.

```<code>    <script type="text/javascript">
        function availableProducts(){
            $.ajax({
                url:'${g.createLink( controller:'ordersAndStore', action:'availableProducts' )}',
                    data: [sawMill],
                    type: 'get'
            }).success( function ( data ) { $( '#divToUpdate' ).html( data ); });
        }

        function listOffers(){
            $.ajax({
                url:'${g.createLink( controller:'ordersAndStore', action:'listOffers' )}',
                data: [],
                type: 'get'
            }).success( function ( data ) { $( '#offerList' ).html( data ); });
        }

        $( document ).ready( function() {
            $( '.offers' ).click( function ( event ){
                alert('HEJ')
                $.ajax({
                    url:'${g.createLink( controller:'ordersAndStore', action:'listOffers' )}',
                    data: [this.id],
                    type: 'get'
                }).success( function ( data ) { $( '#offerList' ).html( data ); });
            });
        });
        $( document ).ready( function() {
            $('.test1').bind('click', function (){
            alert('KLICKED');
            });
        });

    </script>
</code>```

And the gsp-part in the template:

```<code>        <g:each in="${prodBuffer}" status="i" var="pb">
            <tr id="{$pb.id}" class="offers" class=" ${ (i % 2) == 0 ? 'even': 'odd'}">
                <td><g:checkBox name="toOffer" value="${pb.id}" checked="false"  /></td>
                <td><g:link action="edit_prodbuffer" id="${pb.id}">${pb.id}</g:link></td>
                <td>${pb.sawMill}</td>
                <td>${pb.product}</td>
                <td>${pb.length}</td>
                <td>${pb.volumeAvailable}</td>
                <td><a  onclick='listOffers()' > ${pb.volumeOffered}</a></td>
</code>```

==================================================

I have taken an old test project which I cleaned and modified to this simple example that still don't work:

```<code><!DOCTYPE html>
<html>
    <head>
        <meta name="layout" content="main" />
        <g:set var="entityName" value="${message(code: 'author.label', default: 'Author')}" />
        <title><g:message code="default.list.label" args="[entityName]" /></title>
        <script type="text/javascript">
            $( document ).ready( function() {
                $( '.off1' ).click( function ( event ){
                    alert('HEJ');
                });
            });
        </script>
    </head>
    <body>
        <a href="#list-author" class="skip" tabindex="-1"><g:message code="default.link.skip.label" default="Skip to content…"/></a>
        <div class="nav" role="navigation">
            <ul>
                <li><a class="home" href="${createLink(uri: '/')}"><g:message code="default.home.label"/></a></li>
                <li><g:link class="create" action="create"><g:message code="default.new.label" args="[entityName]" /></g:link></li>
            </ul>
        </div>
        <div id="list-author" class="content scaffold-list" role="main">
            <h1><g:message code="default.list.label" args="[entityName]" /></h1>
            <g:if test="${flash.message}">
                <div class="message" role="status">${flash.message}</div>
            </g:if>
            <table>
                <th></th>
                <tbody
                    <g:each in="${authorList}" status='i' var='a'>
                        <tr id="${a.id}" class="off1">
                            <td><g:field  type="text" name="author" value="${a?.name}"/> </td>
                        </tr>
                    </g:each>
            <div class="pagination">
                <g:paginate total="${authorCount ?: 0}" />
            </div>
        </div>
    </body>
</html>
</code>```

I begin to be desperate, can't make this work but I must :(
I'll list the code again with some different settings and the output.
Sure something must be wrong with my code as others can make it work but what is wrong?

Part of the GSP-file where things start, there is two alternative lines one is commented here.

```<code>    <script type="text/javascript">
        function listOffers(id){
        $.ajax({
                url:'${g.createLink( controller:'ordersAndStore', action:'listOffers' )}',
        data: [id],
        type: 'get'
        }).success( function ( data ) { $( '#offerList' ).html( data ); });
        }
    </script>
.....
.....
    <g:render template="ListOffers" model="[offerDetails:offerDetails]"/>
</code>```0

-- Controller:

```<code>    <script type="text/javascript">
        function listOffers(id){
        $.ajax({
                url:'${g.createLink( controller:'ordersAndStore', action:'listOffers' )}',
        data: [id],
        type: 'get'
        }).success( function ( data ) { $( '#offerList' ).html( data ); });
        }
    </script>
.....
.....
    <g:render template="ListOffers" model="[offerDetails:offerDetails]"/>
</code>```1

-- Script A:

```<code>    <script type="text/javascript">
        function listOffers(id){
        $.ajax({
                url:'${g.createLink( controller:'ordersAndStore', action:'listOffers' )}',
        data: [id],
        type: 'get'
        }).success( function ( data ) { $( '#offerList' ).html( data ); });
        }
    </script>
.....
.....
    <g:render template="ListOffers" model="[offerDetails:offerDetails]"/>
</code>```2

-- Script B:

```<code>        $( document ).ready( function() {
            $(".off1").click( function(event){
                alert('HEJ');
            });
        });
</code>```

Script B: never respond - WHY?

Output from controller using script A:

```<code>### --- HEJ --- ### [undefined:, controller:author, format:null, action:listOffers, id:null]
</code>```

Modified script A -- data is empty:

```<code>        function listOffers(id){
            alert('HEJ<<<<<<<<<<<<<<'+ id);
            $.ajax({
                url:'${g.createLink( controller:'author', action:'listOffers', id:"${id}" )}',
                data: [],
                type: 'get'
            }).success( function ( data ) { $( '#offerList' ).html( data ); });
        }
</code>```

Output from controller using modified version of script A:

```<code>### --- HEJ --- ### [controller:author, format:null, action:listOffers, id:null]
</code>```

The alert call works ok and I get the correct value of id there.
As yo can see from the controller printout id is null and if data contains id I also get 'undefined:' as a parameter.
If I remove id from data, now data[], this 'undefined:' disappear

答:
You could give each table row the ID then respond to events when the row is clicked:

Breaking this down to a simple example with JUST the parts to show how it works.

OrdersAndStoreController

```<code>class OrdersAndStoreController {

    def index() {
        [prodBuffer: [new ProdBuffer(id: 1, volumeOffered: 100), new ProdBuffer(id: 2, volumeOffered: 200)]]
    }

    def listOffers() {
        render(template:"ListOffers", model:[offerDetails: [offer1: 'offer1', offer2: 'offer2']])
    }
}

class ProdBuffer{
    Integer id
    Integer volumeOffered
}
</code>```

index.gsp

```<code><!DOCTYPE html>
<html>
<head>
<meta name="layout" content="main" />

<script type="text/javascript">
    $( document ).ready( function() {
        $( '.offers' ).click( function ( event ){
            $.ajax({
                url:'${g.createLink( controller:'ordersAndStore', action:'listOffers' )}',
                data: [this.id],
                type: 'get'
            }).success( function ( data ) { $( '#offerList' ).html( data );     });
        });
    });
</script>
</head>
<body>

<table>
    <thead>
    <th>Volume offered</th>
    </thead>
    <g:each in="${prodBuffer}" status="i" var="pb">
        <tr id="${pb.id}" class="offers">
            <td>${pb.volumeOffered}</td>
        </tr>
    </g:each>
</table>

<div id="offerList"></div>

</body>
</html>
</code>```

_ListOffers.gsp

```<code>${offerDetails}
</code>```

Body:
I have a view consisting of two lists: products and offers. You can select several rows by checking checkboxes on them and then by clicking on a link, offer lines will be created for each selected product.
Every offer line has the id of the product which I will use to list all offers created for that product in a list below the list of products.

I tried to solve that by using a javascript which should be activated when you click on a link or field in the product list.
The script sends a message to the controller that creates the list of offers for this product and then render a template in this view.

I can just use a link and call the controller and the template will be rendered but of course not the rest of the view.

So I need to have line:

<g:link action="listOffers" id="${pb.id}">${pb.volumeOffered}</g:link>

replaced with something better that can call my javascript-function.
I read somewhere you could put an -onclick="javascript-function" in the g:link tag but it doesn't work.

Below is the most important part of controller and gsp in this case.

In the List.gsp:

.....
.....
    <g:render template="ListOffers" model="[offerDetails:offerDetails]"/>

In the template _AvailableProductData.gsp:

    <g:each in="${prodBuffer}" status="i" var="pb">

                ${pb.volumeOffered}

In the template _ListOffers.gsp:

    <g:set var="entityName" value='Offers' />

<g:message code="default.list.label" args="[entityName]" />

                    <g:sortableColumn property="product" title='Product' />
                    <g:sortableColumn property="volumeOffered" title='Volume' />

                <g:each in="${offerDetails}" status="i" var="od">

                        <g:link class="edit" action="edit" resource="offerDetail" id="${od?.id}"> ${od.product?.encodeAsHTML()}</g:link>
                        ${od?.volumeOffered}

                </g:each>

            <g:paginate total="${offersCount ?: 0}" />

In the controller:

def listOffers(){
    def List<OfferDetail> offerDetails = getOfferList()
    render(template:"ListOffers", model:[offerDetails: offerDetails])
}

Added a printout to see what params contains:

def listOffers(){
    System.out.println("#--#"+params)
    def List<OfferDetail> offerDetails = getOfferList()
    render(template:"ListOffers", model:[offerDetails: offerDetails])
}

The printout is:

#--#[undefined:, controller:ordersAndStore, format:null, action:listOffers]

Following is the complete javascript section, the first one is working good but then comes the onclick version that responds and calls the controller but can not send the id. Then comes your version and another one simple but no one is working.

And the gsp-part in the template:

        <g:each in="${prodBuffer}" status="i" var="pb">

                <g:checkBox name="toOffer" value="${pb.id}" checked="false"  />
                <g:link action="edit_prodbuffer" id="${pb.id}">${pb.id}</g:link>
                ${pb.sawMill}
                ${pb.product}
                ${pb.length}
                ${pb.volumeAvailable}
                 ${pb.volumeOffered}

==================================================

I have taken an old test project which I cleaned and modified to this simple example that still don't work:

<!DOCTYPE html>

        <meta name="layout" content="main" />
        <g:set var="entityName" value="${message(code: 'author.label', default: 'Author')}" />
        <title><g:message code="default.list.label" args="[entityName]" /></title>

        <g:message code="default.link.skip.label" default="Skip to content…"/>

<g:message code="default.home.label"/>

<g:link class="create" action="create"><g:message code="default.new.label" args="[entityName]" /></g:link>

<g:message code="default.list.label" args="[entityName]" />

            <g:if test="${flash.message}">

${flash.message}

            </g:if>

                <tbody
                    <g:each in="${authorList}" status='i' var='a'>

                            <g:field  type="text" name="author" value="${a?.name}"/>

                    </g:each>

                <g:paginate total="${authorCount ?: 0}" />

I begin to be desperate, can't make this work but I must :(
I'll list the code again with some different settings and the output.
Sure something must be wrong with my code as others can make it work but what is wrong?

Part of the GSP-file where things start, there is two alternative lines one is commented here.

                <g:each in="${authorList}" status='i' var='a'>

                        <g:field  type="text" name="author" value="${a?.name}"/>

                </g:each>

-- Controller:

def listOffers() {
    System.out.println("### --- HEJ --- ### "+params)
}

-- Script A:

    function listOffers(id){
            alert('HEJ<<<<<<<<<<<<<<'+ id);
            $.ajax({
                url:'${g.createLink( controller:'author', action:'listOffers', id:"${id}" )}',
                data: [id],
                type: 'get'
            }).success( function ( data ) { $( '#offerList' ).html( data ); });
        }

-- Script B:

        $( document ).ready( function() {
            $(".off1").click( function(event){
                alert('HEJ');
            });
        });

Script B: never respond - WHY?

Output from controller using script A:

### --- HEJ --- ### [undefined:, controller:author, format:null, action:listOffers, id:null]

Modified script A -- data is empty:

        function listOffers(id){
            alert('HEJ<<<<<<<<<<<<<<'+ id);
            $.ajax({
                url:'${g.createLink( controller:'author', action:'listOffers', id:"${id}" )}',
                data: [],
                type: 'get'
            }).success( function ( data ) { $( '#offerList' ).html( data ); });
        }

Output from controller using modified version of script A:

### --- HEJ --- ### [controller:author, format:null, action:listOffers, id:null]

The alert call works ok and I get the correct value of id there.
As yo can see from the controller printout id is null and if data contains id I also get 'undefined:' as a parameter.
If I remove id from data, now data[], this 'undefined:' disappear

Body:
You could give each table row the ID then respond to events when the row is clicked:

Breaking this down to a simple example with JUST the parts to show how it works.

OrdersAndStoreController

class OrdersAndStoreController {

    def index() {
        [prodBuffer: [new ProdBuffer(id: 1, volumeOffered: 100), new ProdBuffer(id: 2, volumeOffered: 200)]]
    }

    def listOffers() {
        render(template:"ListOffers", model:[offerDetails: [offer1: 'offer1', offer2: 'offer2']])
    }
}

class ProdBuffer{
    Integer id
    Integer volumeOffered
}

index.gsp

<!DOCTYPE html>
<html>
<head>
<meta name="layout" content="main" />

<script type="text/javascript">
    $( document ).ready( function() {
        $( '.offers' ).click( function ( event ){
            $.ajax({
                url:'${g.createLink( controller:'ordersAndStore', action:'listOffers' )}',
                data: [this.id],
                type: 'get'
            }).success( function ( data ) { $( '#offerList' ).html( data );     });
        });
    });
</script>
</head>
<body>

<table>
    <thead>
    <th>Volume offered</th>
    </thead>
    <g:each in="${prodBuffer}" status="i" var="pb">
        <tr id="${pb.id}" class="offers">
            <td>${pb.volumeOffered}</td>
        </tr>
    </g:each>
</table>

<div id="offerList"></div>

</body>
</html>

_ListOffers.gsp

${offerDetails}


问:
Uploading excel file from IIS hosted asp application not uploading complete rows
I have developed C# web application to upload excel file to SQL server. The targeted excel file has almost 265000 + Rows.
 When I upload it from localhost, all rows gets uploaded. I hosted the application in another computer using IIS ,and tried uploading only 19238 rows are getting uploaded.

The file size is 16Mb.

Here I copied sample code block, it is of no use though.

```<code> private void bulkUpload()
    {
        btnUpload.Enabled = false;
        string excelPath = Server.MapPath("~/Files/") + Path.GetFileName(ExcelFileUpload.PostedFile.FileName);
        ExcelFileUpload.SaveAs(excelPath);

        string conString = string.Empty;
        string extension = Path.GetExtension(ExcelFileUpload.PostedFile.FileName);
        switch (extension)
        {
            case ".xls": //Excel 97-03
                conString = ConfigurationManager.ConnectionStrings["Excel03ConString"].ConnectionString;
                break;
            case ".xlsx": //Excel 07 or higher
                conString = ConfigurationManager.ConnectionStrings["Excel07ConString"].ConnectionString;
                break;

        }

        conString = string.Format(conString, excelPath);
        using (OleDbConnection excel_con = new OleDbConnection(conString))
        {
            excel_con.Open();
            string Sheet1 = excel_con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null).Rows[0]["TABLE_NAME"].ToString();
            DataTable dtExcelData = new DataTable();

            using (OleDbDataAdapter oda = new OleDbDataAdapter("SELECT * FROM [" + Sheet1 + "]", excel_con))
            {
                oda.Fill(dtExcelData);
            }
            excel_con.Close();

            using (SqlConnection con = new SqlConnection(constr))
            {
                using (SqlBulkCopy sqlBulkCopy = new SqlBulkCopy(con))
                {
                    //Set the database table name
                    sqlBulkCopy.DestinationTableName = "dbo.MBQ_All_1";

                    sqlBulkCopy.ColumnMappings.Add("Uniq", "Uniq");
                    sqlBulkCopy.ColumnMappings.Add("StoreClass", "StoreClass");
                    sqlBulkCopy.ColumnMappings.Add("Store", "Store");
                    sqlBulkCopy.ColumnMappings.Add("code", "code");
                    sqlBulkCopy.ColumnMappings.Add("ExtendedDescription", "ExtendedDescription");
                    sqlBulkCopy.ColumnMappings.Add("ITEM_CLASS", "ITEM_CLASS");
                    sqlBulkCopy.ColumnMappings.Add("SUPPLIER", "SUPPLIER");
                    sqlBulkCopy.ColumnMappings.Add("Brands", "Brands");
                    sqlBulkCopy.ColumnMappings.Add("Min", "Min");
                    sqlBulkCopy.ColumnMappings.Add("Max", "Max");

                    con.Open();
                    sqlBulkCopy.WriteToServer(dtExcelData);
                    con.Close();
                    Page.ClientScript.RegisterStartupScript(GetType(), "msgbox", "alert('Your list uploaded successfully');", true);
                    lblExcelMsg.Text = "Your list uploaded successfully";
                }
            }
        }
    }
</code>```

答: Added IMEX=1 with the Excel connection string and is uploading all rows now. </p>

Body:
I have developed C# web application to upload excel file to SQL server. The targeted excel file has almost 265000 + Rows.
 When I upload it from localhost, all rows gets uploaded. I hosted the application in another computer using IIS ,and tried uploading only 19238 rows are getting uploaded.

The file size is 16Mb.

Here I copied sample code block, it is of no use though.

 private void bulkUpload()
    {
        btnUpload.Enabled = false;
        string excelPath = Server.MapPath("~/Files/") + Path.GetFileName(ExcelFileUpload.PostedFile.FileName);
        ExcelFileUpload.SaveAs(excelPath);

        string conString = string.Empty;
        string extension = Path.GetExtension(ExcelFileUpload.PostedFile.FileName);
        switch (extension)
        {
            case ".xls": //Excel 97-03
                conString = ConfigurationManager.ConnectionStrings["Excel03ConString"].ConnectionString;
                break;
            case ".xlsx": //Excel 07 or higher
                conString = ConfigurationManager.ConnectionStrings["Excel07ConString"].ConnectionString;
                break;

        }

        conString = string.Format(conString, excelPath);
        using (OleDbConnection excel_con = new OleDbConnection(conString))
        {
            excel_con.Open();
            string Sheet1 = excel_con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null).Rows[0]["TABLE_NAME"].ToString();
            DataTable dtExcelData = new DataTable();

            using (OleDbDataAdapter oda = new OleDbDataAdapter("SELECT * FROM [" + Sheet1 + "]", excel_con))
            {
                oda.Fill(dtExcelData);
            }
            excel_con.Close();

            using (SqlConnection con = new SqlConnection(constr))
            {
                using (SqlBulkCopy sqlBulkCopy = new SqlBulkCopy(con))
                {
                    //Set the database table name
                    sqlBulkCopy.DestinationTableName = "dbo.MBQ_All_1";

                    sqlBulkCopy.ColumnMappings.Add("Uniq", "Uniq");
                    sqlBulkCopy.ColumnMappings.Add("StoreClass", "StoreClass");
                    sqlBulkCopy.ColumnMappings.Add("Store", "Store");
                    sqlBulkCopy.ColumnMappings.Add("code", "code");
                    sqlBulkCopy.ColumnMappings.Add("ExtendedDescription", "ExtendedDescription");
                    sqlBulkCopy.ColumnMappings.Add("ITEM_CLASS", "ITEM_CLASS");
                    sqlBulkCopy.ColumnMappings.Add("SUPPLIER", "SUPPLIER");
                    sqlBulkCopy.ColumnMappings.Add("Brands", "Brands");
                    sqlBulkCopy.ColumnMappings.Add("Min", "Min");
                    sqlBulkCopy.ColumnMappings.Add("Max", "Max");

                    con.Open();
                    sqlBulkCopy.WriteToServer(dtExcelData);
                    con.Close();
                    Page.ClientScript.RegisterStartupScript(GetType(), "msgbox", "alert('Your list uploaded successfully');", true);
                    lblExcelMsg.Text = "Your list uploaded successfully";
                }
            }
        }
    }


问:
How to separate letters and digits from a string in php
I have a string which is combination of letters and digits. For my application i have to separate a string with letters and digits:  ex:If my string is "12jan" i hav to get "12" "jan" separately..</p>

答:
```<code>$string = "12312313sdfsdf24234";
preg_match_all('/([0-9]+|[a-zA-Z]+)/',$string,$matches);
print_r($matches);
</code>```

this might work alot better

ContentLicense: CC BY-SA 2.5

Body:
$string = "12312313sdfsdf24234";
preg_match_all('/([0-9]+|[a-zA-Z]+)/',$string,$matches);
print_r($matches);

this might work alot better


问:
"package java.net.http does not exist" error on JDK9
I have a problem compiling simple blocking GET example from the HttpRequest JavaDoc:

```<code>package org.example;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

import static java.net.http.HttpRequest.noBody;
import static java.net.http.HttpResponse.asString;

public class Http2 {
    public static void main(String[] args) throws URISyntaxException, IOException, InterruptedException {
        HttpResponse response = HttpRequest
                .create(new URI("http://www.infoq.com"))
                .body(noBody())
                .GET().response();
        int responseCode = response.statusCode();
        String responseBody = response.body(asString());

        System.out.println(responseBody);
    }
}
</code>```

I'm getting package java.net.http does not exist error when compiling using JDK 9:

```
{ jdk9 }  » /cygdrive/c/Program\ Files/Java/jdk-9/bin/javac -d out/production -modulesourcepath org.example.module1/src/ -m org.example.module1

org.example.module1\src\org.example.module1\org\example\Http2.java:6: error: package java.net.http does not exist
import java.net.http.HttpRequest;
                    ^
org.example.module1\src\org.example.module1\org\example\Http2.java:7: error: package java.net.http does not exist
import java.net.http.HttpResponse;
                    ^
org.example.module1\src\org.example.module1\org\example\Http2.java:9: error: package java.net.http does not exist
import static java.net.http.HttpRequest.noBody;
                           ^
org.example.module1\src\org.example.module1\org\example\Http2.java:9: error: static import only from classes and interfaces
import static java.net.http.HttpRequest.noBody;
^
org.example.module1\src\org.example.module1\org\example\Http2.java:10: error: package java.net.http does not exist
import static java.net.http.HttpResponse.asString;
                           ^
org.example.module1\src\org.example.module1\org\example\Http2.java:10: error: static import only from classes and interfaces
import static java.net.http.HttpResponse.asString;
^
org.example.module1\src\org.example.module1\org\example\Http2.java:14: error: cannot find symbol
        HttpResponse response = HttpRequest
        ^
  symbol:   class HttpResponse
  location: class Http2
org.example.module1\src\org.example.module1\org\example\Http2.java:14: error: cannot find symbol
        HttpResponse response = HttpRequest
                                ^
  symbol:   variable HttpRequest
  location: class Http2
org.example.module1\src\org.example.module1\org\example\Http2.java:16: error: cannot find symbol
                .body(noBody())
                      ^
  symbol:   method noBody()
  location: class Http2
org.example.module1\src\org.example.module1\org\example\Http2.java:19: error: cannot find symbol
        String responseBody = response.body(asString());
                                            ^
  symbol:   method asString()
  location: class Http2
10 errors
```

Same error occurs using command line and IntelliJ.

It is not a problem with my module because classes without java.net.http compiles and run without any problem.

Any idea what is going on?

答:
Meanwhile, since build 149 of the jdk9, the classes

HttpClient

HttpRequest

HttpResponse

WebSocket

have been moved to the package jdk.incubator.http. They are part of the jigsaw module jdk.incubator.httpclient. See ticket JDK-8170648 for more details.

So you have to change your imports to jdk.incubator.http.*. Furthermore, you must include the module jdk.incubator.httpclient in your module-info.java.  When compiling and running your code, add the argument  --add-modules=jdk.incubator.httpclient to your invocation of the java and javac executables.

All classes related to the http client have been removed from jdk9. They are included as incubator features and are no longer part of the API. Hopefully, the new client will be part of jdk10.

Body:
I have a problem compiling simple blocking GET example from the HttpRequest JavaDoc:

package org.example;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

import static java.net.http.HttpRequest.noBody;
import static java.net.http.HttpResponse.asString;

public class Http2 {
    public static void main(String[] args) throws URISyntaxException, IOException, InterruptedException {
        HttpResponse response = HttpRequest
                .create(new URI("http://www.infoq.com"))
                .body(noBody())
                .GET().response();
        int responseCode = response.statusCode();
        String responseBody = response.body(asString());

        System.out.println(responseBody);
    }
}

I'm getting package java.net.http does not exist error when compiling using JDK 9:

{ jdk9 }  » /cygdrive/c/Program\ Files/Java/jdk-9/bin/javac -d out/production -modulesourcepath org.example.module1/src/ -m org.example.module1

org.example.module1\src\org.example.module1\org\example\Http2.java:6: error: package java.net.http does not exist
import java.net.http.HttpRequest;
                    ^
org.example.module1\src\org.example.module1\org\example\Http2.java:7: error: package java.net.http does not exist
import java.net.http.HttpResponse;
                    ^
org.example.module1\src\org.example.module1\org\example\Http2.java:9: error: package java.net.http does not exist
import static java.net.http.HttpRequest.noBody;
                           ^
org.example.module1\src\org.example.module1\org\example\Http2.java:9: error: static import only from classes and interfaces
import static java.net.http.HttpRequest.noBody;
^
org.example.module1\src\org.example.module1\org\example\Http2.java:10: error: package java.net.http does not exist
import static java.net.http.HttpResponse.asString;
                           ^
org.example.module1\src\org.example.module1\org\example\Http2.java:10: error: static import only from classes and interfaces
import static java.net.http.HttpResponse.asString;
^
org.example.module1\src\org.example.module1\org\example\Http2.java:14: error: cannot find symbol
        HttpResponse response = HttpRequest
        ^
  symbol:   class HttpResponse
  location: class Http2
org.example.module1\src\org.example.module1\org\example\Http2.java:14: error: cannot find symbol
        HttpResponse response = HttpRequest
                                ^
  symbol:   variable HttpRequest
  location: class Http2
org.example.module1\src\org.example.module1\org\example\Http2.java:16: error: cannot find symbol
                .body(noBody())
                      ^
  symbol:   method noBody()
  location: class Http2
org.example.module1\src\org.example.module1\org\example\Http2.java:19: error: cannot find symbol
        String responseBody = response.body(asString());
                                            ^
  symbol:   method asString()
  location: class Http2
10 errors

Same error occurs using command line and IntelliJ.

It is not a problem with my module because classes without java.net.http compiles and run without any problem.

Any idea what is going on?


问:
Angular2 Pass data between two components via service
Hi I'm trying to pass selected value(from options) from first component to second component but I am having trouble getting the values in second component.

I am currently using services to do so and am console.logging everythign to see if I'm passing the value.

Everything loads as I intend until second component.

Below is my code

First Component HTML

```<code> <p class="fonts-title"> Select Region</p>
 <div class="selectcontainer">
    <select (change)="passValue1()" formControlName="region" class="form- control"  class="selectionbox" [(ngModel)]="selected_region" required>
  <option *ngFor="let region of regions | filterregion" [ngValue]="region">
{{region.areaName}}
</option>
</select>
</code>```

First Component

```<code>export class SearchSelectComponent implements OnInit {

  constructor(
    private passData: TeacherPassDataService) { }

  selected_region: string;

  passValue1(val1) {
    this.passData.setValue1(val1=this.selected_region['areaCode'])
  }
</code>```

Service

```<code>@Injectable()
export class TeacherPassDataService {

    value1: string;

    constructor() {
        this.value1="",
    }

    setValue1(val1: string) {
        this.value1 = val1
        console.log(this.getValue1()) //this prints selected_region value from the first component as I intented
    }

    getValue1() {
        return this.value1;
    }

}
</code>```

However, in second component,

```<code>constructor(
        private getVal: TeacherPassDataService) {
    }

   getVal1() {
       return this.getVal.getValue1(),
       this.firstVal=this.getVal1(),
       console.log(this.getVal.getValue1()) //this prints 'undefined'
    }
</code>```

Why I am getting undefined in the second component when I am setting the value correctly using service?

Please Help!

Thank you in advance

答:
Please see the attached working plunkr. I have tried to mimic your use case. It uses routing to load the second component. I believe it should answer your question. Please have a look -
https://plnkr.co/edit/w7A8RJeFPYq5rstTfXYF?p=preview

I have used following in the TeacherPassDataService-

```<code>this.router.navigate(["/secondComponent"]);
</code>```

Body:
Hi I'm trying to pass selected value(from options) from first component to second component but I am having trouble getting the values in second component.

I am currently using services to do so and am console.logging everythign to see if I'm passing the value.

Everything loads as I intend until second component.

Below is my code

First Component HTML

 Select Region

    <select (change)="passValue1()" formControlName="region" class="form- control"  class="selectionbox" [(ngModel)]="selected_region" required>
  <option *ngFor="let region of regions | filterregion" [ngValue]="region">
{{region.areaName}}
</option>
</select>

First Component

export class SearchSelectComponent implements OnInit {

  constructor(
    private passData: TeacherPassDataService) { }

  selected_region: string;

  passValue1(val1) {
    this.passData.setValue1(val1=this.selected_region['areaCode'])
  }

Service

@Injectable()
export class TeacherPassDataService {

    value1: string;

    constructor() {
        this.value1="",
    }

    setValue1(val1: string) {
        this.value1 = val1
        console.log(this.getValue1()) //this prints selected_region value from the first component as I intented
    }

    getValue1() {
        return this.value1;
    }

}

However, in second component,

constructor(
        private getVal: TeacherPassDataService) {
    }

   getVal1() {
       return this.getVal.getValue1(),
       this.firstVal=this.getVal1(),
       console.log(this.getVal.getValue1()) //this prints 'undefined'
    }

Why I am getting undefined in the second component when I am setting the value correctly using service?

Please Help!

Thank you in advance

Body:
Please see the attached working plunkr. I have tried to mimic your use case. It uses routing to load the second component. I believe it should answer your question. Please have a look -
https://plnkr.co/edit/w7A8RJeFPYq5rstTfXYF?p=preview

I have used following in the TeacherPassDataService-

this.router.navigate(["/secondComponent"]);


问:
Unable to launch App on iOs 9.1 Adobe Air (not all devices)
we have inhouse iOS app (created with adobe air). On some iPads we can't launch the app after installing.
(iPad Air 2, iOS 9.1)

We get the following messages in console.

```<code><Warning>: Binary is improperly signed.
<Warning>: Unable to register for exec notifications: No such process
<Warning>: Unable to obtain a task name port right for pid 1278: (os/kern) failure (5)
<Warning>: Unable to obtain a task name port right for <FBApplicationProcess: 0x1643e6f40; pid: 1278>
<Warning>: exited due to an invalid code signature.
<Warning>: Application '(null)' exited for an unknown reason.
</code>```

It looks like a certificate problem but on other devices we can install and run the application without any problems. We have created the cerficate on october 2015.

I would have been pleased if someone has any idea, what's going wrong.

Kind Regards

答: You need to add UDID of all devices in provision profile. Than build your app again with this provision and test.</p>

Body:
we have inhouse iOS app (created with adobe air). On some iPads we can't launch the app after installing.
(iPad Air 2, iOS 9.1)

We get the following messages in console.

<Warning>: Binary is improperly signed.
<Warning>: Unable to register for exec notifications: No such process
<Warning>: Unable to obtain a task name port right for pid 1278: (os/kern) failure (5)
<Warning>: Unable to obtain a task name port right for <FBApplicationProcess: 0x1643e6f40; pid: 1278>
<Warning>: exited due to an invalid code signature.
<Warning>: Application '(null)' exited for an unknown reason.

It looks like a certificate problem but on other devices we can install and run the application without any problems. We have created the cerficate on october 2015.

I would have been pleased if someone has any idea, what's going wrong.

Kind Regards


问:
Ionic Angular js IDE
Is there an IDE like Xcode to develop cross platform apps using ionic? I played with creator.ionic.io but they charge 40$ per month for the complete app development. Can you suggest some open source IDEs? Basically I wanted something similar to ionic where I can drag and drop objects to build the UI</p>

答:
I had come across the same problem when i started at first and found some suggestions from ionic official website.

I copied contents here for convenience.

Visual Studio Code

VS Code is a new editor that comes with support for ES6 syntax, as well as TypeScript support. It will also prompt users to include TypeScript definition files and download them from Definitely Typed. Visual Studio Code is free and works on OS X, Windows, and Linux.

Atom

Atom is cross platform editor built on web technologies. Atom has many plugins to make ES6/TypeScript development very easy. If there isn't something provided by Atom or a plugin, you can even make a plugin yourself, using JavaScript. Atom works on OS X, Windows, and Linux.

WebStorm

WebStorm is a paid IDE that provides many features, such as advanced refactoring support, automatic compilation of code, and gulp/grunt/webpack support. Out of the box, WebStorm comes with support for ES6 and TypeScript, as well as Angular and Ionic syntax support.

ALM

ALM is a free open source IDE built for typescript development, it can be run on any computer running chrome and can be hosted on a server and used on any computer with internet access.

Angular IDE by Webclipse

Angular IDE is a freemium IDE built for Angular 2 and TypeScript development providing integrated terminal support helping with node and npm management. Out of the box, Angular IDE includes code completion and validation for ES6, TypeScript, and Angular 2 HTML templates.

Personally i am using "Brackets" its open source as well and really good.

Title: Ionic Angular js IDE


问:
Saving variables in applescript using plist's within application xcode
How do I make my script write to a Property List file without having to create a ".plist" file on the user's computer, but rather directly in the current application?</p>

答:
The plist files are created from the user defaults. So you need to save your values there.

Make a property to shorten writings at top

```<code>property NSUserDefaults : class "NSUserDefaults" of current application
</code>```

to write

```<code>NSUserDefaults's standardUserDefaults()'s setObject_forKey_(yourValue, yourKey)
</code>```

to read

```<code>NSUserDefaults's standardUserDefaults()'s object_forKey(yourKey)
</code>```

Example

```<code>property NSUserDefaults : class "NSUserDefaults" of current application

set mytext to "Hello"

-- write
NSUserDefaults's standardUserDefaults()'s setObject_forKey_(mytext, "MyKey")

-- read it with
log NSUserDefaults's standardUserDefaults()'s object_forKey_("MyKey")
-- Hello
</code>```

It's untested cause i don't have a mac here at the moment. But it should work.

Edit

To set standard values do the following in your application's appDelegate method applicationWillFinishLaunching:aNotification (don't forget to declare the property mentioned above):

```<code>on applicationWillFinishLaunching:aNotification
    set prefs to {MyKey:"Hello", SomeOtherKey:true}
    NSUserDefaults's standardUserDefaults()'s registerDefaults_(prefs)
end
</code>```

Body:
The plist files are created from the user defaults. So you need to save your values there.

Make a property to shorten writings at top

property NSUserDefaults : class "NSUserDefaults" of current application

to write

NSUserDefaults's standardUserDefaults()'s setObject_forKey_(yourValue, yourKey)

to read

NSUserDefaults's standardUserDefaults()'s object_forKey(yourKey)

Example

property NSUserDefaults : class "NSUserDefaults" of current application

set mytext to "Hello"

-- write
NSUserDefaults's standardUserDefaults()'s setObject_forKey_(mytext, "MyKey")

-- read it with
log NSUserDefaults's standardUserDefaults()'s object_forKey_("MyKey")
-- Hello

It's untested cause i don't have a mac here at the moment. But it should work.

Edit

To set standard values do the following in your application's appDelegate method applicationWillFinishLaunching:aNotification (don't forget to declare the property mentioned above):

on applicationWillFinishLaunching:aNotification
    set prefs to {MyKey:"Hello", SomeOtherKey:true}
    NSUserDefaults's standardUserDefaults()'s registerDefaults_(prefs)
end