问:
Vue.js global event not working
I've got

```<code><component-one></component-one>

<component-two></component-two>
      <component-three></component-three>
</code>```

Component two contains component three.

Currently I emit an event in <component-one> that has to be caught in <component-three>.

In <component-one> I fire the event like this:

```<code>this.$bus.$emit('setSecondBanner', finalBanner);
</code>```

Then in <component-three> I catch it like this:

```<code>mounted() {
    this.$bus.$on('setSecondBanner', (banner) => {
        alert('Caught');
        this.banner = banner;
    });
},
</code>```

But the event is never caught!

I define the bus like this (in my core.js):

```<code>let eventBus = new Vue();

Object.defineProperties(Vue.prototype, {
    $bus: {
        get: () => { return eventBus; }
    }
});
</code>```

What could be wrong here? When I check vue-dev-tools I can see that the event has fired!

答:
This is the working example for vue1.

Object.defineProperty(Vue.prototype, '$bus', {
 get() {
  return this.$root.bus;
 }
});

Vue.component('third', {
 template: `<div> Third : {{ data }} </div>`,
  props:['data']
});

Vue.component('second', {
 template: `<div>Second component <third :data="data"></third></div>`,
 ready() {
  this.$bus.$on('setSecondBanner', (event) => {
   this.data = event.data;
  });
 },
 data() {
  return {
     data: 'Defautl value in second'
    }
 }
});

Vue.component('first', {
 template: `<div>{{ data }}</div>`,
 ready() {
  setInterval(() => {
   this.$bus.$emit('setSecondBanner', {
    data: 'Bus sending some data : '+new Date(),
   });
  }, 1000);
 },

 data() {
  return {
     data: 'Defautl value in first'
    }
 }
});

var bus = new Vue({});
new Vue({
 el: '#app',
 data: {
  bus: bus
 }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/vue/1.0.28/vue.js"></script>
<div id="app">
  <second></second>
  <first></first>
</div></code>```

Title: Vue.js global event not working

Body:
I've got

<component-one></component-one>

<component-two></component-two>
      <component-three></component-three>

Component two contains component three.

Currently I emit an event in <component-one> that has to be caught in <component-three>.

In <component-one> I fire the event like this:

this.$bus.$emit('setSecondBanner', finalBanner);

Then in <component-three> I catch it like this:

mounted() {
    this.$bus.$on('setSecondBanner', (banner) => {
        alert('Caught');
        this.banner = banner;
    });
},

But the event is never caught!

I define the bus like this (in my core.js):

let eventBus = new Vue();

Object.defineProperties(Vue.prototype, {
    $bus: {
        get: () => { return eventBus; }
    }
});

What could be wrong here? When I check vue-dev-tools I can see that the event has fired!

Body:
This is the working example for vue1.

Object.defineProperty(Vue.prototype, '$bus', {
 get() {
  return this.$root.bus;
 }
});

Vue.component('third', {
 template: `<div> Third : {{ data }} </div>`,
  props:['data']
});

Vue.component('second', {
 template: `<div>Second component <third :data="data"></third></div>`,
 ready() {
  this.$bus.$on('setSecondBanner', (event) => {
   this.data = event.data;
  });
 },
 data() {
  return {
     data: 'Defautl value in second'
    }
 }
});

Vue.component('first', {
 template: `<div>{{ data }}</div>`,
 ready() {
  setInterval(() => {
   this.$bus.$emit('setSecondBanner', {
    data: 'Bus sending some data : '+new Date(),
   });
  }, 1000);
 },

 data() {
  return {
     data: 'Defautl value in first'
    }
 }
});

var bus = new Vue({});
new Vue({
 el: '#app',
 data: {
  bus: bus
 }
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/1.0.28/vue.js"></script>
<div id="app">
  <second></second>
  <first></first>
</div>


来源: stackexchange

问:
Convert a custom helper without LinqExpression to one using LinqExpression
I have a custom helper that works.

Custom helper without LinqExpression (this is working)

```<code>public static MvcHtmlString Image(this HtmlHelper html, byte[] image)
 {
   var img = String.Format("data:image/jpg;base64,{0}", Convert.ToBase64String(image));
   return new MvcHtmlString("<img src='" + img + "'  />");
 }
</code>```

Using above custom helper (this works)

```<code>@Html.Image(item.Picture)
</code>```

I am trying to re-write the same custom helper using LinqExpression.

I have come up with the following code, but TModel and TValue are not being recognized in Visual Studio and also I am not sure how to get the byte[] value passed to this custom helper i.e. set the value of variable databaseImge.

I am getting following compile time errors when using the LinqExpression version of the custom helper.

The type or namespace name 'TModel' could not be found...
  The type or namespace name 'TValue' could not be found...

Question : What am I missing in my method and how would I get the value of item.Picture passed to this helper?

Custom Helper with LinqExpression (this is giving compile-time error)

```<code>public static MvcHtmlString DatabaseImage(this HtmlHelper htmlHelper, Expression<Func<TModel, TValue>> expression)
{

  //TModel model = (TModel)helper.ViewContext.ViewData.ModelMetadata.Model;
  //var metadata = ModelMetadata.FromLambdaExpression(expression,htmlHelper.ViewData);
  var dastabaseImg = expression.Compile().Invoke(htmlHelper.ViewData.Model);
  var img = String.Format("data:image/jpg;base64,{0}", Convert.ToBase64String(dastabaseImg));
  return new MvcHtmlString("<img src='" + img + "'  />");
}
</code>```

I would like to use the above LinqExpression helper, by using the below code, where item.Picture returns a byte[].

```<code> @Html.DatabaseImage(modeItem => item.Picture)
</code>```

答:
There is no need to use Expression here, because all you do with it is compile and invoke.Instead, pass Func<TModel, byte[]:

```<code>public static MvcHtmlString DatabaseImage<TModel>(this HtmlHelper htmlHelper, Func<TModel, byte[]> func) {
    var dastabaseImg = func((TModel) htmlHelper.ViewData.Model);
    var img = String.Format("data:image/jpg;base64,{0}", Convert.ToBase64String(dastabaseImg));
    return new MvcHtmlString("<img src='" + img + "'  />");
}
</code>```

You will have to call it like this:

```<code>@Html.DatabaseImage<YourModelType>(modeItem => modeItem.Picture)
</code>```

or

```<code>@Html.DatabaseImage((YourModelType modeItem) => modeItem.Picture)
</code>```

It's better to extend generic HtmlHelper<TModel> by the way, like this:

```<code>public static MvcHtmlString DatabaseImage<TModel>(this HtmlHelper<TModel> htmlHelper, Func<TModel, byte[]> func) {
    var dastabaseImg = func(htmlHelper.ViewData.Model);
    var img = String.Format("data:image/jpg;base64,{0}", Convert.ToBase64String(dastabaseImg));
    return new MvcHtmlString("<img src='" + img + "'  />");
}
</code>```

Then you can call it easier:

```<code>@Html.DatabaseImage(modeItem => modeItem.Picture)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a custom helper that works.

Custom helper without LinqExpression (this is working)

public static MvcHtmlString Image(this HtmlHelper html, byte[] image)
 {
   var img = String.Format("data:image/jpg;base64,{0}", Convert.ToBase64String(image));
   return new MvcHtmlString("");
 }

Using above custom helper (this works)

@Html.Image(item.Picture)

I am trying to re-write the same custom helper using LinqExpression.

I have come up with the following code, but TModel and TValue are not being recognized in Visual Studio and also I am not sure how to get the byte[] value passed to this custom helper i.e. set the value of variable databaseImge.

I am getting following compile time errors when using the LinqExpression version of the custom helper.

The type or namespace name 'TModel' could not be found...
  The type or namespace name 'TValue' could not be found...

Question : What am I missing in my method and how would I get the value of item.Picture passed to this helper?

Custom Helper with LinqExpression (this is giving compile-time error)

public static MvcHtmlString DatabaseImage(this HtmlHelper htmlHelper, Expression<Func<TModel, TValue>> expression)
{

  //TModel model = (TModel)helper.ViewContext.ViewData.ModelMetadata.Model;
  //var metadata = ModelMetadata.FromLambdaExpression(expression,htmlHelper.ViewData);
  var dastabaseImg = expression.Compile().Invoke(htmlHelper.ViewData.Model);
  var img = String.Format("data:image/jpg;base64,{0}", Convert.ToBase64String(dastabaseImg));
  return new MvcHtmlString("");
}

I would like to use the above LinqExpression helper, by using the below code, where item.Picture returns a byte[].

 @Html.DatabaseImage(modeItem => item.Picture)

Body:
There is no need to use Expression here, because all you do with it is compile and invoke.Instead, pass Func<TModel, byte[]:

public static MvcHtmlString DatabaseImage<TModel>(this HtmlHelper htmlHelper, Func<TModel, byte[]> func) {
    var dastabaseImg = func((TModel) htmlHelper.ViewData.Model);
    var img = String.Format("data:image/jpg;base64,{0}", Convert.ToBase64String(dastabaseImg));
    return new MvcHtmlString("<img src='" + img + "'  />");
}

You will have to call it like this:

@Html.DatabaseImage<YourModelType>(modeItem => modeItem.Picture)

or

@Html.DatabaseImage((YourModelType modeItem) => modeItem.Picture)

It's better to extend generic HtmlHelper<TModel> by the way, like this:

public static MvcHtmlString DatabaseImage<TModel>(this HtmlHelper<TModel> htmlHelper, Func<TModel, byte[]> func) {
    var dastabaseImg = func(htmlHelper.ViewData.Model);
    var img = String.Format("data:image/jpg;base64,{0}", Convert.ToBase64String(dastabaseImg));
    return new MvcHtmlString("<img src='" + img + "'  />");
}

Then you can call it easier:

@Html.DatabaseImage(modeItem => modeItem.Picture)


问:
CodeDeploy on programmatically created EC2 Instance
I have a auto-scaling-group setup. When there are no running instances per that group and my application deploys, the auto-scaling-group will spin up an instance and deploy. Fantastic. ... well sorta...

If there are more than one instances in that auto-scaling-group, then my scripts might point to one instance or another.

How do I deploy to a specific instance without having to setup all the CodeDeploy application, deployment-group, send a new revision, yada, yada, yada...

Or, do you have to take all of those steps each time? How then do you track your deployments? Surely there's a better way to this?

Ideally, I would like to create an Instance based on an AMI, associate that instance with my auto-scaling-group, then deploy specifically to that instance. But I can't create-deployment to an instance, only to a deployment-group.

This is maddening.

答:
The problem you describe can easily be solved with HashiCorp Packer.
With a packerfile you can describe the way your application is supposed to be deployed to an instance. This instance is then snapshotted and turned into an available AMI.
After which you can update your target group for your autoscaling group with a new AMI.

Documentation for Packer can be found here:


问:
Css. Doesn't work text-overflow: ellipsis
I have something like this:

```<code><div>
  <span>
    text text text text text text
  </span>
</div>

div{
  width:100px;
  border: 1px solid black;
  line-height: 12px;
  height: 16px;
  position: relative;
  overflow:hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

span{
  position: absolute;
  overflow: hidden;
  text-overflow: ellipsis;
}
</code>```

And ellipsis doesn't work.
I do not necessarily need to use position: absolute, but as result I should have text, that doesn't expand div and truncated width ellipsis.

P.S. Width for div is included for sample, in reality div width is unknown.

答:
text-overflow: ellipsis; affects when it does not have enough space for the text.

div {
 width: 100px;
 border: 1px solid black;
 line-height: 12px;
 height: 16px;
}
span {
 overflow: hidden;
 text-overflow: ellipsis;
 display: block;
 white-space: nowrap;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
  <span>
    text text text text text text
  </span>
</div></code>```

Body:
I have something like this:

    text text text text text text

div{
  width:100px;
  border: 1px solid black;
  line-height: 12px;
  height: 16px;
  position: relative;
  overflow:hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

span{
  position: absolute;
  overflow: hidden;
  text-overflow: ellipsis;
}

And ellipsis doesn't work.
I do not necessarily need to use position: absolute, but as result I should have text, that doesn't expand div and truncated width ellipsis.

P.S. Width for div is included for sample, in reality div width is unknown.

Body:
text-overflow: ellipsis; affects when it does not have enough space for the text.

div {
 width: 100px;
 border: 1px solid black;
 line-height: 12px;
 height: 16px;
}
span {
 overflow: hidden;
 text-overflow: ellipsis;
 display: block;
 white-space: nowrap;
}

<div>
  <span>
    text text text text text text
  </span>
</div>


问:
Get field of optional object or return null
I have optional object:

```<code>Optional<Detail> newestDetail;
</code>```

I would like to return newestDetail.getId() or if newestDetail is null return null.

Do we have more sophisticated approach of doing this, than following?

```<code>return newestDetail.isPresent()?newestDetail.get().getId():null;
</code>```

答:
Map the value to an Optional with the id field and turn that one into a null value if it is empty:

```<code>return newestDetail.map(Detail::getId).orElse(null);
</code>```

Body:
I have optional object:

Optional<Detail> newestDetail;

I would like to return newestDetail.getId() or if newestDetail is null return null.

Do we have more sophisticated approach of doing this, than following?

return newestDetail.isPresent()?newestDetail.get().getId():null;

Body:
Map the value to an Optional with the id field and turn that one into a null value if it is empty:

return newestDetail.map(Detail::getId).orElse(null);


问:
How to update report in access with bound dataset automatically?
I have a single entry output from a paradox table which is imported into Access.  Now I have created a report and done the databinding within the report to the dataset from Paradox.  When work is done in Paradox the single entry output changes...
How do I open up access and have the values from the report update automatically without having to reimport the table manually?

The objective is that when access is opened the report comes up immediately for inspection before printing.

答:
From the design view of the report, go to the property sheet and the Event tab. Find the On Load event and click the elipsis button. Select Code Builder if presented with the Choose Builder dialog. This will drop you into the VBA editor in the Report_Load event. Edit to look something like this:

Private Sub Report_Load()

```<code>DoCmd.TransferDatabase acImport, "Paradox 7.x", "c:\yourdata\yourfile.tbl", acTable, "SourceTable", "YourAccessTable"
</code>```

End Sub

I'm not sure on the specifics for the Paradox version, the file naming convention, etc. (I only dabbled with Paradox briefly and don't remember it's specifics). Watch the intellisense or put the cursor on TransferData and press F1 to get the Help for the TransferDatabase method for reference.

Ahead of the TrasferDatabase statement you might want to run something like:

CurrentDb.Execute "DELETE FROM TableName"

That will blow out the destination table on the Access side ahead of the load from the Paradox side.

OwnerDisplayName: CGF

ContentLicense: CC BY-SA 2.5

Body:
From the design view of the report, go to the property sheet and the Event tab. Find the On Load event and click the elipsis button. Select Code Builder if presented with the Choose Builder dialog. This will drop you into the VBA editor in the Report_Load event. Edit to look something like this:

Private Sub Report_Load()

DoCmd.TransferDatabase acImport, "Paradox 7.x", "c:\yourdata\yourfile.tbl", acTable, "SourceTable", "YourAccessTable"

End Sub

I'm not sure on the specifics for the Paradox version, the file naming convention, etc. (I only dabbled with Paradox briefly and don't remember it's specifics). Watch the intellisense or put the cursor on TransferData and press F1 to get the Help for the TransferDatabase method for reference.

Ahead of the TrasferDatabase statement you might want to run something like:

CurrentDb.Execute "DELETE FROM TableName"

That will blow out the destination table on the Access side ahead of the load from the Paradox side.

OwnerDisplayName: John Mo


问:
Singleton class working on 4.0 iOS and earlier version but not on 4.1 and 4.2 SDK
I am using Singleton Class to share huge data I am getting from webservice to handle, which I have done in my previous apps also. But with new ios 4.2 its not working, I can't understand the reason of it not working as it has nothing to do with new api/frameworks.

Here is the code of my singleton:

```<code> @interface SingleTon : NSObject {

  NSMutableArray *hname;

}
+ (SingleTon *) sharedInstanceHname;

//hname
-(NSMutableArray *) getHname:(NSMutableArray  *)x;
-(void) setHname:(NSMutableArray  *)x;
</code>```

.m class:

@implementation SingleTon
     static SingleTon  *_sharedInstanceHname;

```<code> - (id) init
 {
if (self = [super init])
{
    // custom initialization
    //memset(board, 0, sizeof(board));
    hname = [[NSMutableArray alloc] initWithObjects:@"NO RESULT",nil];

    index =1;
}
return self;
</code>```

}

```<code>  + (SingleTon *) sharedInstanceHname
  {
if (!_sharedInstanceHname)
{
    _sharedInstanceHname = [[SingleTon alloc] init];
}

return _sharedInstanceHname;
</code>```

}

```<code>- (NSMutableArray *) getHname:(NSMutableArray *)x
 {
return hname;
  }

- (void) setHname:(NSMutableArray *)x
{
hname = x;
 }
</code>```

Here how i am using Singleton to store value in my first view:

```<code>    SingleTon *sname = [SingleTon sharedInstanceHname];
 [sname setHname:hname];
</code>```

And here is how i am accessing this set value in second view viewDidLoad method:

```<code>    SingleTon *places = [SingleTon sharedInstanceHname];
NSLog(@"%@", [places getHname:getname]);
</code>```

I tried all possible retain release but of no use...and yea error also varies..some time it is “EXC_BAD_ACCESS”  and some time other

答:
Calling initWithObjects:, you should terminate list of values with nil. Except this is a typo you made while preparing the example.

Also, there could be a problem with your setHname: method neither retaining nor copying the value being assigned.

Body:
I am using Singleton Class to share huge data I am getting from webservice to handle, which I have done in my previous apps also. But with new ios 4.2 its not working, I can't understand the reason of it not working as it has nothing to do with new api/frameworks.

Here is the code of my singleton:

 @interface SingleTon : NSObject {

  NSMutableArray *hname;

}
+ (SingleTon *) sharedInstanceHname;

//hname
-(NSMutableArray *) getHname:(NSMutableArray  *)x;
-(void) setHname:(NSMutableArray  *)x;

.m class:

@implementation SingleTon
     static SingleTon  *_sharedInstanceHname;

 - (id) init
 {
if (self = [super init])
{
    // custom initialization
    //memset(board, 0, sizeof(board));
    hname = [[NSMutableArray alloc] initWithObjects:@"NO RESULT",nil];

    index =1;
}
return self;

}

  + (SingleTon *) sharedInstanceHname
  {
if (!_sharedInstanceHname)
{
    _sharedInstanceHname = [[SingleTon alloc] init];
}

return _sharedInstanceHname;

}

- (NSMutableArray *) getHname:(NSMutableArray *)x
 {
return hname;
  }

- (void) setHname:(NSMutableArray *)x
{
hname = x;
 }

Here how i am using Singleton to store value in my first view:

    SingleTon *sname = [SingleTon sharedInstanceHname];
 [sname setHname:hname];

And here is how i am accessing this set value in second view viewDidLoad method:

    SingleTon *places = [SingleTon sharedInstanceHname];
NSLog(@"%@", [places getHname:getname]);

I tried all possible retain release but of no use...and yea error also varies..some time it is “EXC_BAD_ACCESS”  and some time other


问:
Rxjava split getting contacts
I need to split getting contacts from phone's contact list database. If user has a lot of contacts loading stucks for few seconds to load what is not very good. I want to divide it with Rx to load 20 contacts a time, but with loading all contacts on start, not with lazy loading. At this moment i tried it with pull of observables with concat, but it collects all the results and return after finishing all of them instead of returning every 20 contacts after getting them and just after returning continue with next pack of contacts. What is wrong with this implementation?</p>

```<code> @Override public Observable<List<Contact>> getPhoneContacts() {
    return Observable.fromCallable(this::getCursor)
        .concatMap(cursor -> {
          List<Observable<List<Contact>>> list = new ArrayList<>();
          int pagesCount = cursor.getCount()/20 + 1;
          for(int i = 0; i < pagesCount; i++){
            list.add(Observable.just(getContactList(cursor)));
          }
          return Observable.concat(list).compose(upstream -> {
            cursor.close();
            return upstream;
          });
        });
  }

  private List<Contact> getContactList(Cursor cursor) {
    List<Contact> contacts = new ArrayList<>();
    if (cursor != null && !cursor.isClosed() && areContactsPresent(cursor)) {
      while (contacts.size() < 20){
        if (cursor.moveToNext()) {
            String id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
            Contact contact = getContact(cursor, id);
            if (contact != null) {
              contacts.add(contact);
            }

        }
        //else {
        //  cursor.close();
        //  break;
        //}
      }
    }
    return contacts;
  }

  private Cursor getCursor(){
    return contentResolver.query(ContactsContract.Contacts.CONTENT_URI,
        null, ContactsContract.Data.HAS_PHONE_NUMBER+">0", null, ContactsContract.Contacts.DISPLAY_NAME + " ASC");
  }

  private Contact getContact(Cursor cursor, String id) {
    Contact contact = null;
    Cursor phonesCursor = contentResolver.query(
        ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
        null,
        ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?",
        new String[]{id}, null);
    if (phonesCursor != null) {
      while (phonesCursor.moveToNext()) {
        String name = cursor.getString(cursor.getColumnIndex(
            ContactsContract.Contacts.DISPLAY_NAME));
        String phoneNo = phonesCursor.getString(
            phonesCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
        if (!phoneNo.isEmpty()) {
          contact = Contact.create(name, phoneNo);
        }
      }
      phonesCursor.close();
    }
    return contact;
  }
</code>```

答:
You source observable needs to look something like that

```<code>Observable.create((ObservableOnSubscribe<List<Contact>>) emitter -> {
    int pagesCount = cursor.getCount()/20 + 1;
    for(int i = 0; i < pagesCount; i++){
        emitter.onNext(getContactList(cursor)); // Passes list with 20 items to onNext()
    }
    emitter.onComplete();
});
</code>```

Your data source now returns List<Contact> instead of a single Contact, which means each emission will provide you with a list of contacts, each list has 20 items as per your implementation.

Then you can update UI with each emission, instead of waiting for all of the contacts to load.

Title: Rxjava split getting contacts

Body:
I need to split getting contacts from phone's contact list database. If user has a lot of contacts loading stucks for few seconds to load what is not very good. I want to divide it with Rx to load 20 contacts a time, but with loading all contacts on start, not with lazy loading. At this moment i tried it with pull of observables with concat, but it collects all the results and return after finishing all of them instead of returning every 20 contacts after getting them and just after returning continue with next pack of contacts. What is wrong with this implementation?

 @Override public Observable<List<Contact>> getPhoneContacts() {
    return Observable.fromCallable(this::getCursor)
        .concatMap(cursor -> {
          List<Observable<List<Contact>>> list = new ArrayList<>();
          int pagesCount = cursor.getCount()/20 + 1;
          for(int i = 0; i < pagesCount; i++){
            list.add(Observable.just(getContactList(cursor)));
          }
          return Observable.concat(list).compose(upstream -> {
            cursor.close();
            return upstream;
          });
        });
  }

  private List<Contact> getContactList(Cursor cursor) {
    List<Contact> contacts = new ArrayList<>();
    if (cursor != null && !cursor.isClosed() && areContactsPresent(cursor)) {
      while (contacts.size() < 20){
        if (cursor.moveToNext()) {
            String id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
            Contact contact = getContact(cursor, id);
            if (contact != null) {
              contacts.add(contact);
            }

        }
        //else {
        //  cursor.close();
        //  break;
        //}
      }
    }
    return contacts;
  }

  private Cursor getCursor(){
    return contentResolver.query(ContactsContract.Contacts.CONTENT_URI,
        null, ContactsContract.Data.HAS_PHONE_NUMBER+">0", null, ContactsContract.Contacts.DISPLAY_NAME + " ASC");
  }

  private Contact getContact(Cursor cursor, String id) {
    Contact contact = null;
    Cursor phonesCursor = contentResolver.query(
        ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
        null,
        ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?",
        new String[]{id}, null);
    if (phonesCursor != null) {
      while (phonesCursor.moveToNext()) {
        String name = cursor.getString(cursor.getColumnIndex(
            ContactsContract.Contacts.DISPLAY_NAME));
        String phoneNo = phonesCursor.getString(
            phonesCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
        if (!phoneNo.isEmpty()) {
          contact = Contact.create(name, phoneNo);
        }
      }
      phonesCursor.close();
    }
    return contact;
  }

Body:
You source observable needs to look something like that

Observable.create((ObservableOnSubscribe<List<Contact>>) emitter -> {
    int pagesCount = cursor.getCount()/20 + 1;
    for(int i = 0; i < pagesCount; i++){
        emitter.onNext(getContactList(cursor)); // Passes list with 20 items to onNext()
    }
    emitter.onComplete();
});

Your data source now returns List<Contact> instead of a single Contact, which means each emission will provide you with a list of contacts, each list has 20 items as per your implementation.

Then you can update UI with each emission, instead of waiting for all of the contacts to load.


问:
No such module 'RestKit' with cocoapods and swift
I am having this problem with a brand new project.  This problem happens with both RestKit and Facebook SDK. Strangely SwiftyJSON works just fine. I create a brand new swift project and a Podfile with:

```<code>source 'https://github.com/CocoaPods/Specs.git'

use_frameworks!

target 'test-fb-swift4' do
    pod "FBSDKCoreKit"
    pod 'SwiftyJSON', '~> 2.1'
    pod 'RestKit', :inhibit_warnings => true
end

target 'test-fb-swift4Tests' do

end
</code>```

After creating that file I run pod install and reopen xcode with the test-fb-swift4.xcworkspace file.

Now inside my controller I put a import RestKit and I get the error No such module 'RestKit'.  I have tried many different ways to format the Podfile even down to very simple versions like:

```<code>source 'https://github.com/CocoaPods/Specs.git'

pod 'RestKit'
</code>```

I have tried adding and removing the use_frameworks, with and without the target.  With and without the :inhibit_warnings.

I am running CocoaPods 0.36.4 and tried the latest rc build, same deal.  The Objective-C version from another project runs fine.  This is my first project using Swift and I am stuck on this issue.

答:
In my case, at first I had only one target in xcode. I executed pod install.
A few months later, I had to make another target so I had multi targets.

In this situation, if I do pod install and build xcode, I get a "no such module" error.

So I removed pod files and then pod init.

Podfile format has been changed for multiple targets

It works!!

Check this out!

Body:
I am having this problem with a brand new project.  This problem happens with both RestKit and Facebook SDK. Strangely SwiftyJSON works just fine. I create a brand new swift project and a Podfile with:

source 'https://github.com/CocoaPods/Specs.git'

use_frameworks!

target 'test-fb-swift4' do
    pod "FBSDKCoreKit"
    pod 'SwiftyJSON', '~> 2.1'
    pod 'RestKit', :inhibit_warnings => true
end

target 'test-fb-swift4Tests' do

end

After creating that file I run pod install and reopen xcode with the test-fb-swift4.xcworkspace file.

Now inside my controller I put a import RestKit and I get the error No such module 'RestKit'.  I have tried many different ways to format the Podfile even down to very simple versions like:

source 'https://github.com/CocoaPods/Specs.git'

pod 'RestKit'

I have tried adding and removing the use_frameworks, with and without the target.  With and without the :inhibit_warnings.

I am running CocoaPods 0.36.4 and tried the latest rc build, same deal.  The Objective-C version from another project runs fine.  This is my first project using Swift and I am stuck on this issue.


问:
how can i set custom color of data in amCharts
I have a stanadart data form form my graphics.

```<code>var data = [
  {"product": "Laptop",   "sellOfMonth": 250},
  {"product": "Phone",    "sellOfMonth": 1250},
  {"product": "Comupter", "sellOfMonth": 20}
];
</code>```

Fro thi data my data values are sellOfMonth property. And I have a new array for style of this data like this:

```<code>var styles = [{"name":"sellOfMonth", "color": "#123"}];
</code>```

This style will be color of column chart.

If my data is stacked:

```<code>var data = [
  {"product": "Laptop",   "sellOfMonth": 250, "sellOfYear": 2500},
  {"product": "Phone",    "sellOfMonth": 1250, "sellOfYear": 1500},
  {"product": "Comupter", "sellOfMonth": 20,, "sellOfYear": 200}
];
</code>```

and style array is:

```<code>var styles = [
       {"name":"sellOfMonth", "color": "#123"},
       {"name":"sellOfYear", "color": "#dfc"}
];
</code>```

So I can create an amchart and set dataProvider as my data array.

But I could not set the colors.

答:
Looking at how your styles are set up, you can easily use that to create your graphs array and set each graph's fillColors property to the desired color.

```<code>var graphs = styles.map(function(style) {
  return {
    "type": "column",
    "valueField": style.name,
    "fillColors": style.color,
    "lineColor": style.color,
    "fillAlphas": .8
  };
});
</code>```

From there you can assign your graphs array to makeChart or the object's graphs array if you're using the library's class-based methods.

Demo below:

var styles = [
       {"name":"sellOfMonth", "color": "#123"},
       {"name":"sellOfYear", "color": "#dfc"}
];
var graphs = styles.map(function(style) {
  return {
    "type": "column",
    "valueField": style.name,
    "fillColors": style.color,
    "lineColor": style.color,
    "fillAlphas": .8
  };
});
var data = [
  {"product": "Laptop",   "sellOfMonth": 250, "sellOfYear": 2500},
  {"product": "Phone",    "sellOfMonth": 1250, "sellOfYear": 1500},
  {"product": "Comupter", "sellOfMonth": 20, "sellOfYear": 200}
];

var chart = AmCharts.makeChart("chartdiv", {
  "type": "serial",
  "theme": "light",
  "valueAxes": [{
    "stackType": "regular"
  }],
  "dataProvider": data,
  "graphs": graphs,
  "categoryField": "product"
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>html, body {
  width: 100%;
  height: 100%;
  margin: 0px;
}

#chartdiv {
 width: 100%;
 height: 100%;
}</code>```

```

Body:
I have a stanadart data form form my graphics.

var data = [
  {"product": "Laptop",   "sellOfMonth": 250},
  {"product": "Phone",    "sellOfMonth": 1250},
  {"product": "Comupter", "sellOfMonth": 20}
];

Fro thi data my data values are sellOfMonth property. And I have a new array for style of this data like this:

var styles = [{"name":"sellOfMonth", "color": "#123"}];

This style will be color of column chart.

If my data is stacked:

var data = [
  {"product": "Laptop",   "sellOfMonth": 250, "sellOfYear": 2500},
  {"product": "Phone",    "sellOfMonth": 1250, "sellOfYear": 1500},
  {"product": "Comupter", "sellOfMonth": 20,, "sellOfYear": 200}
];

and style array is:

var styles = [
       {"name":"sellOfMonth", "color": "#123"},
       {"name":"sellOfYear", "color": "#dfc"}
];

So I can create an amchart and set dataProvider as my data array.

But I could not set the colors.

Body:
Looking at how your styles are set up, you can easily use that to create your graphs array and set each graph's fillColors property to the desired color.

var graphs = styles.map(function(style) {
  return {
    "type": "column",
    "valueField": style.name,
    "fillColors": style.color,
    "lineColor": style.color,
    "fillAlphas": .8
  };
});

From there you can assign your graphs array to makeChart or the object's graphs array if you're using the library's class-based methods.

Demo below:

var styles = [
       {"name":"sellOfMonth", "color": "#123"},
       {"name":"sellOfYear", "color": "#dfc"}
];
var graphs = styles.map(function(style) {
  return {
    "type": "column",
    "valueField": style.name,
    "fillColors": style.color,
    "lineColor": style.color,
    "fillAlphas": .8
  };
});
var data = [
  {"product": "Laptop",   "sellOfMonth": 250, "sellOfYear": 2500},
  {"product": "Phone",    "sellOfMonth": 1250, "sellOfYear": 1500},
  {"product": "Comupter", "sellOfMonth": 20, "sellOfYear": 200}
];

var chart = AmCharts.makeChart("chartdiv", {
  "type": "serial",
  "theme": "light",
  "valueAxes": [{
    "stackType": "regular"
  }],
  "dataProvider": data,
  "graphs": graphs,
  "categoryField": "product"
});

html, body {
  width: 100%;
  height: 100%;
  margin: 0px;
}

#chartdiv {
 width: 100%;
 height: 100%;
}

<script src="//www.amcharts.com/lib/3/amcharts.js"></script>
<script src="//www.amcharts.com/lib/3/serial.js"></script>
<script src="//www.amcharts.com/lib/3/themes/light.js"></script>

<div id="chartdiv"></div>


问:
What is the SVN term for deleting changes?
I made changes to a few files in SVN and I want to reverse the changes I made, i.e., have my version be the one in HEAD. What is the SVN term for that (so I can find it in tortoisesvn - I'm not sure if I should revert/clean up, etc.)?

答:
What you want is to svn revert.

To revert all files in your working copy from the command line use the recursive parameter:  svn revert -R $WC_ROOT.  I'm not positive if the revert command in Tortoise is recursive by default but it should have an option for it.

Note that revert will not remove any files that aren't part of the revision you have checked out.  For instance, if you used svn add to add a file that hasn't been committed or have a file in the path of your working copy that hasn't been added yet, they will still exist with a "?" status even after you issue your revert command.

Here is some documentation on all commands available in subversion: http://svnbook.red-bean.com/en/1.5/svn-book.html#svn.ref


问:
Catel freezing on usercontrol focus
I got a simple application with nested usercontrol.

MainWindow.xaml:

```<code><Grid x:Name="LayoutRoot">
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto" />
        <RowDefinition Height="Auto" />
    </Grid.RowDefinitions>

    <TextBox Grid.Row="0">Test TextBox</TextBox>

    <userControls:SuggestUserControl Grid.Row="1" Grid.Column="0"
        DataContext="{Binding CitizenshipViewModel}" />
</Grid>
</code>```

Violation of the naming convention is reason for subsequent re-use of this usercontrol. In that case I'm registering custom view model in App.xaml.cs:

```<code>var viewLocator = ServiceLocator.Default.ResolveType<IViewModelLocator>();
viewLocator.Register(typeof(SuggestUserControl), typeof(CitizenshipSuggestViewModel));
</code>```

CitizenshipSuggestViewModel is a simple class with empty constructor, some additional logic (which I commented in test reason) and derived from base class SuggestModule:

```<code>    public class SuggestModule<TEntity> : ViewModelBase
        where TEntity : class, ISuggestable, new()
    {
        #region Private fields

        private readonly IDataBaseService _dataBaseService;

        #endregion

        #region Default constructor

        public SuggestModule(IDataBaseService dataBaseService)
        {
            Argument.IsNotNull(() => dataBaseService);
            _dataBaseService = dataBaseService;

            //Loading data from context
            var collection = _dataBaseService.LoadObservableCollectionOf<TEntity>();
            ItemsCollection = new ObservableCollection<TEntity>(collection);
            ItemsCollection.Sort();
        }

        #endregion

        ...Some logic here...
   }
</code>```

MainWindowViewModel:

```<code>    public class MainWindowViewModel : ViewModelBase
        {
            public MainWindowViewModel(Person person)
            {
                Argument.IsNotNull(()=>person);

                Person = person;
            }

            [Model]
            public Person Person
            {
                get => GetValue<Person>(PersonProperty);
                set => SetValue(PersonProperty, value);
            }

            public static readonly PropertyData PersonProperty =
                RegisterProperty<MainWindowViewModel, Person>(model => model.Person);

            [ViewModelToModel("Person")]
            public Citizenship Citizenship
            {
                get => GetValue<Citizenship>(CitizenshipProperty);
                set => SetValue(CitizenshipProperty, value);
            }

            public static readonly PropertyData CitizenshipProperty =
                RegisterProperty<MainWindowViewModel, Citizenship>(model => model.Citizenship);

            public Citizenship Citizenship
            {
                get => GetValue<Citizenship>(CitizenshipProperty);
                set => SetValue(CitizenshipProperty, value);
            }

            public static readonly PropertyData CitizenshipProperty =
                RegisterProperty<MainWindowViewModel, Citizenship>(model => model.Citizenship);

            public IViewModel CitizenshipViewModel
            {
                get => GetValue<IViewModel>(CitizenshipViewModelProperty);
                set => SetValue(CitizenshipViewModelProperty, value);
            }

            public static readonly PropertyData CitizenshipViewModelProperty =
                RegisterProperty<MainWindowViewModel, IViewModel>(model => model.CitizenshipViewModel);

            protected override async Task InitializeAsync()
            {
                await base.InitializeAsync();

                CitizenshipViewModel = this.GetTypeFactory().CreateInstance<CitizenshipSuggestViewModel>();
            }
        }
    }
</code>```

So, when application fully loaded, particularly ItemsCollection on SuggestModule is already filled with data from context, in Log got this information:

```<code>12:19:34:844 => [DEBUG] [Catel.MVVM.Views.ViewToViewModelMappingHelper] [1] Initializing view model container to manage ViewToViewModel mappings
12:19:34:864 => [DEBUG] [Catel.MVVM.Views.ViewToViewModelMappingHelper] [1] Initializing view model 'CitizenshipSuggestViewModel'
12:19:34:874 => [DEBUG] [Catel.MVVM.Views.ViewToViewModelMappingHelper] [1] Initialized view model 'CitizenshipSuggestViewModel'
12:19:34:895 => [DEBUG] [Catel.MVVM.Views.ViewToViewModelMappingHelper] [1] Initialized view model container to manage ViewToViewModel mappings
</code>```

But now, if I getting focus on second TextBox, which is part of nested usercontrol I have about 5...6 seconds freeze. Logging information in this time:

```<code>12:23:21:212 => [DEBUG] [Catel.IoC.TypeFactory] [1] Cleared type constructor cache
12:23:21:387 => [DEBUG] [Catel.IoC.TypeFactory] [1] Cleared type constructor cache
12:23:21:809 => [DEBUG] [Catel.IoC.TypeFactory] [1] Cleared type constructor cache
12:23:21:901 => [DEBUG] [Catel.IoC.TypeFactory] [1] Cleared type constructor cache
12:23:22:016 => [DEBUG] [Catel.IoC.TypeFactory] [1] Cleared type constructor cache
12:23:22:063 => [DEBUG] [Catel.IoC.TypeFactory] [1] Cleared type constructor cache
12:23:22:221 => [DEBUG] [Catel.IoC.TypeFactory] [1] Cleared type constructor cache
12:23:22:235 => [DEBUG] [Catel.IoC.TypeFactory] [1] Cleared type constructor cache
12:23:22:585 => [DEBUG] [Catel.IoC.TypeFactory] [1] Cleared type constructor cache
12:23:22:654 => [DEBUG] [Catel.IoC.TypeFactory] [1] Cleared type constructor cache
12:23:22:703 => [DEBUG] [Catel.IoC.TypeFactory] [1] Cleared type constructor cache
12:23:23:019 => [DEBUG] [Catel.IoC.TypeFactory] [1] Cleared type constructor cache
12:23:23:319 => [DEBUG] [Catel.IoC.TypeFactory] [1] Cleared type constructor cache
12:23:23:431 => [DEBUG] [Catel.IoC.TypeFactory] [1] Cleared type constructor cache
12:23:24:105 => [DEBUG] [Catel.IoC.TypeFactory] [1] Cleared type constructor cache
12:23:24:566 => [DEBUG] [Catel.IoC.TypeFactory] [1] Cleared type constructor cache
12:23:24:644 => [DEBUG] [Catel.IoC.TypeFactory] [1] Cleared type constructor cache
12:23:25:803 => [DEBUG] [Catel.IoC.TypeFactory] [1] Cleared type constructor cache
12:23:26:115 => [DEBUG] [Catel.IoC.TypeFactory] [1] Cleared type constructor cache
</code>```

How can I avoid this behavior?
Thank you in advance!

答:
We recommend to use InitializeAsync instead of the constructor for data retrieval

Are you using Catel 5.2 in combination with VS 2017? Does the issue still occur when you run without a debugger attached?

ContentLicense: CC BY-SA 4.0

Title: Catel freezing on usercontrol focus

Body:
I got a simple application with nested usercontrol.

MainWindow.xaml:

<Grid x:Name="LayoutRoot">
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto" />
        <RowDefinition Height="Auto" />
    </Grid.RowDefinitions>

    <TextBox Grid.Row="0">Test TextBox</TextBox>

    <userControls:SuggestUserControl Grid.Row="1" Grid.Column="0"
        DataContext="{Binding CitizenshipViewModel}" />
</Grid>

Violation of the naming convention is reason for subsequent re-use of this usercontrol. In that case I'm registering custom view model in App.xaml.cs:

var viewLocator = ServiceLocator.Default.ResolveType<IViewModelLocator>();
viewLocator.Register(typeof(SuggestUserControl), typeof(CitizenshipSuggestViewModel));

CitizenshipSuggestViewModel is a simple class with empty constructor, some additional logic (which I commented in test reason) and derived from base class SuggestModule:

    public class SuggestModule<TEntity> : ViewModelBase
        where TEntity : class, ISuggestable, new()
    {
        #region Private fields

        private readonly IDataBaseService _dataBaseService;

        #endregion

        #region Default constructor

        public SuggestModule(IDataBaseService dataBaseService)
        {
            Argument.IsNotNull(() => dataBaseService);
            _dataBaseService = dataBaseService;

            //Loading data from context
            var collection = _dataBaseService.LoadObservableCollectionOf<TEntity>();
            ItemsCollection = new ObservableCollection<TEntity>(collection);
            ItemsCollection.Sort();
        }

        #endregion

        ...Some logic here...
   }

MainWindowViewModel:

    public class MainWindowViewModel : ViewModelBase
        {
            public MainWindowViewModel(Person person)
            {
                Argument.IsNotNull(()=>person);

                Person = person;
            }

            [Model]
            public Person Person
            {
                get => GetValue<Person>(PersonProperty);
                set => SetValue(PersonProperty, value);
            }

            public static readonly PropertyData PersonProperty =
                RegisterProperty<MainWindowViewModel, Person>(model => model.Person);

            [ViewModelToModel("Person")]
            public Citizenship Citizenship
            {
                get => GetValue<Citizenship>(CitizenshipProperty);
                set => SetValue(CitizenshipProperty, value);
            }

            public static readonly PropertyData CitizenshipProperty =
                RegisterProperty<MainWindowViewModel, Citizenship>(model => model.Citizenship);

            public Citizenship Citizenship
            {
                get => GetValue<Citizenship>(CitizenshipProperty);
                set => SetValue(CitizenshipProperty, value);
            }

            public static readonly PropertyData CitizenshipProperty =
                RegisterProperty<MainWindowViewModel, Citizenship>(model => model.Citizenship);

            public IViewModel CitizenshipViewModel
            {
                get => GetValue<IViewModel>(CitizenshipViewModelProperty);
                set => SetValue(CitizenshipViewModelProperty, value);
            }

            public static readonly PropertyData CitizenshipViewModelProperty =
                RegisterProperty<MainWindowViewModel, IViewModel>(model => model.CitizenshipViewModel);

            protected override async Task InitializeAsync()
            {
                await base.InitializeAsync();

                CitizenshipViewModel = this.GetTypeFactory().CreateInstance<CitizenshipSuggestViewModel>();
            }
        }
    }

So, when application fully loaded, particularly ItemsCollection on SuggestModule is already filled with data from context, in Log got this information:

12:19:34:844 => [DEBUG] [Catel.MVVM.Views.ViewToViewModelMappingHelper] [1] Initializing view model container to manage ViewToViewModel mappings
12:19:34:864 => [DEBUG] [Catel.MVVM.Views.ViewToViewModelMappingHelper] [1] Initializing view model 'CitizenshipSuggestViewModel'
12:19:34:874 => [DEBUG] [Catel.MVVM.Views.ViewToViewModelMappingHelper] [1] Initialized view model 'CitizenshipSuggestViewModel'
12:19:34:895 => [DEBUG] [Catel.MVVM.Views.ViewToViewModelMappingHelper] [1] Initialized view model container to manage ViewToViewModel mappings

But now, if I getting focus on second TextBox, which is part of nested usercontrol I have about 5...6 seconds freeze. Logging information in this time:

12:23:21:212 => [DEBUG] [Catel.IoC.TypeFactory] [1] Cleared type constructor cache
12:23:21:387 => [DEBUG] [Catel.IoC.TypeFactory] [1] Cleared type constructor cache
12:23:21:809 => [DEBUG] [Catel.IoC.TypeFactory] [1] Cleared type constructor cache
12:23:21:901 => [DEBUG] [Catel.IoC.TypeFactory] [1] Cleared type constructor cache
12:23:22:016 => [DEBUG] [Catel.IoC.TypeFactory] [1] Cleared type constructor cache
12:23:22:063 => [DEBUG] [Catel.IoC.TypeFactory] [1] Cleared type constructor cache
12:23:22:221 => [DEBUG] [Catel.IoC.TypeFactory] [1] Cleared type constructor cache
12:23:22:235 => [DEBUG] [Catel.IoC.TypeFactory] [1] Cleared type constructor cache
12:23:22:585 => [DEBUG] [Catel.IoC.TypeFactory] [1] Cleared type constructor cache
12:23:22:654 => [DEBUG] [Catel.IoC.TypeFactory] [1] Cleared type constructor cache
12:23:22:703 => [DEBUG] [Catel.IoC.TypeFactory] [1] Cleared type constructor cache
12:23:23:019 => [DEBUG] [Catel.IoC.TypeFactory] [1] Cleared type constructor cache
12:23:23:319 => [DEBUG] [Catel.IoC.TypeFactory] [1] Cleared type constructor cache
12:23:23:431 => [DEBUG] [Catel.IoC.TypeFactory] [1] Cleared type constructor cache
12:23:24:105 => [DEBUG] [Catel.IoC.TypeFactory] [1] Cleared type constructor cache
12:23:24:566 => [DEBUG] [Catel.IoC.TypeFactory] [1] Cleared type constructor cache
12:23:24:644 => [DEBUG] [Catel.IoC.TypeFactory] [1] Cleared type constructor cache
12:23:25:803 => [DEBUG] [Catel.IoC.TypeFactory] [1] Cleared type constructor cache
12:23:26:115 => [DEBUG] [Catel.IoC.TypeFactory] [1] Cleared type constructor cache

How can I avoid this behavior?
Thank you in advance!


问:
Make Java GC logs show MB or GB instead of KB
By default Java GC log output shows the memory details in KB (kilo bytes). I know it might sound silly, but given most of the Jvms I deal with have heap sizes close to 20 to 40GB, I find it quite inconvenient to read the numbers in KB quickly, especially when quickly scanning logs in putty etc.

Is it possible to make Java print these number in fractions of MB or GB instead?

I didn't find any option in JDK documentation.

If it is not possible, are there any ideas around how one can go about adding this feature to GC logging? (not from outside but from with in JVM)

Thank you in advance for your help.

答:
lets say your GC log file is in : (./my-app-gc.log,)

then use this online plugin to invoke the API :

```<code>curl -X POST --data-binary @./my-app-gc.log http://api.gceasy.io/analyzeGC?apiKey= --header "Content-Type:text"
</code>```

Or use the 3rd software [ PostMan ]

This software Support :

......................................................

| • - Download for Computer : here |

| • - Download for Browsers   : here |

......................................................

Example of PostMan plugin output :

```<code>{
 {
 "isProblem": true,
 "problem": [
 "122 times threads were stopped for more than 5 seconds"
],
"jvmHeapSize": {
"youngGen": {
  "allocatedSize": "7.5 gb",
  "peakSize": "6 gb"
},
"oldGen": {
  "allocatedSize": "22.5 gb",
  "peakSize": "22.5 gb"
},
"metaSpace": {
  "allocatedSize": "1.04 gb",
  "peakSize": "48.52 mb"
},
"total": {
  "allocatedSize": "30 gb",
  "peakSize": "28.5 gb"
}
},
"gcStatistics": {
"totalCreatedBytes": "249.49 gb",
</code>```

this output for you a useful Json Format of Data can be used later.

Body:
lets say your GC log file is in : (./my-app-gc.log,)

then use this online plugin to invoke the API :

curl -X POST --data-binary @./my-app-gc.log http://api.gceasy.io/analyzeGC?apiKey= --header "Content-Type:text"

Or use the 3rd software [ PostMan ]

This software Support :

......................................................

| • - Download for Computer : here |

| • - Download for Browsers   : here |

......................................................

Example of PostMan plugin output :

{
 {
 "isProblem": true,
 "problem": [
 "122 times threads were stopped for more than 5 seconds"
],
"jvmHeapSize": {
"youngGen": {
  "allocatedSize": "7.5 gb",
  "peakSize": "6 gb"
},
"oldGen": {
  "allocatedSize": "22.5 gb",
  "peakSize": "22.5 gb"
},
"metaSpace": {
  "allocatedSize": "1.04 gb",
  "peakSize": "48.52 mb"
},
"total": {
  "allocatedSize": "30 gb",
  "peakSize": "28.5 gb"
}
},
"gcStatistics": {
"totalCreatedBytes": "249.49 gb",

this output for you a useful Json Format of Data can be used later.


问:
How to combine sync object iteration and async code in python?
I have a list of objects, and for each object, I need to do some async work on it. I am not sure if I construct it right:

```<code>def run(tasks):
    async def async_wrapper():
        async def update_task():
            updated_task = await task_manager.async_get_task_status(session, task)
            # do some works with updated_task

        workers = []
        resolver = aiohttp.AsyncResolver()
        connector = aiohttp.TCPConnector(resolver=resolver, family=socket.AF_INET)
        async with aiohttp.ClientSession(connector=connector) as session:
            for local_task in tasks: # tasks is a list of object
                await update_ocr_task()

    loop = asyncio.get_event_loop()
    loop.run_until_complete(aysnc_wrapper())
</code>```

I think the for loop is sync and will totally block the progress, am I right? If I am, how to construct it?

答:
```<code>def run(tasks):
    # ...

    loop = asyncio.get_event_loop()
    loop.run_until_complete(aysnc_wrapper())
</code>```

Usually it's not how people write async programs: event loop should be global and be started as main entry point of whole script. Doing like you do (running event loop inside single function run) makes unable for upper code to run other coroutines in same event loop.

If you understand this and all you want is blocking run function that can't be used alongside with other async stuff, read further.

Problem with your async_wrapper is that it awaits next update_ocr_task() coroutine only after previous one been done. For loop is not what we call "blocking", but it's just not concurrent - it doesn't use benefits provided by asynchronous paradigm.

To achieve benefits of using asyncio you should run multiple coroutines concurrently. Common way to do it is to use asyncio.gather():

```<code>async def async_wrapper():

    async def process_single_task(task):
        resolver = aiohttp.AsyncResolver()
        connector = aiohttp.TCPConnector(resolver=resolver, family=socket.AF_INET)
        async with aiohttp.ClientSession(connector=connector) as session:
            await session.get(...) # do all job for *single* local task here.

    # Run multiple task processing coroutines concurrently:
    await asyncio.gather(
        *[process_single_task(t) for t in tasks]
    )
</code>```

If you want you can also read this little answer about asyncio in general.

Body:
I have a list of objects, and for each object, I need to do some async work on it. I am not sure if I construct it right:

def run(tasks):
    async def async_wrapper():
        async def update_task():
            updated_task = await task_manager.async_get_task_status(session, task)
            # do some works with updated_task

        workers = []
        resolver = aiohttp.AsyncResolver()
        connector = aiohttp.TCPConnector(resolver=resolver, family=socket.AF_INET)
        async with aiohttp.ClientSession(connector=connector) as session:
            for local_task in tasks: # tasks is a list of object
                await update_ocr_task()

    loop = asyncio.get_event_loop()
    loop.run_until_complete(aysnc_wrapper())

I think the for loop is sync and will totally block the progress, am I right? If I am, how to construct it?

Body:
def run(tasks):
    # ...

    loop = asyncio.get_event_loop()
    loop.run_until_complete(aysnc_wrapper())

Usually it's not how people write async programs: event loop should be global and be started as main entry point of whole script. Doing like you do (running event loop inside single function run) makes unable for upper code to run other coroutines in same event loop.

If you understand this and all you want is blocking run function that can't be used alongside with other async stuff, read further.

Problem with your async_wrapper is that it awaits next update_ocr_task() coroutine only after previous one been done. For loop is not what we call "blocking", but it's just not concurrent - it doesn't use benefits provided by asynchronous paradigm.

To achieve benefits of using asyncio you should run multiple coroutines concurrently. Common way to do it is to use asyncio.gather():

async def async_wrapper():

    async def process_single_task(task):
        resolver = aiohttp.AsyncResolver()
        connector = aiohttp.TCPConnector(resolver=resolver, family=socket.AF_INET)
        async with aiohttp.ClientSession(connector=connector) as session:
            await session.get(...) # do all job for *single* local task here.

    # Run multiple task processing coroutines concurrently:
    await asyncio.gather(
        *[process_single_task(t) for t in tasks]
    )

If you want you can also read this little answer about asyncio in general.


问:
Fast stable sorting algorithm implementation in javascript
I'm looking to sort an array of about 200-300 objects, sorting on a specific key and a given order (asc/desc). The order of results must be consistent and stable.

What would be the best algorithm to use, and could you provide an example of it's implementation in javascript?

Thanks!

答:
The following sorts the supplied array, by applying the supplied compare function, returning the original index comparison when the compare function returns 0:

```<code>function stableSort(arr, compare) {
    var original = arr.slice(0);

    arr.sort(function(a, b){
        var result = compare(a, b);
        return result === 0 ? original.indexOf(a) - original.indexOf(b) : result;
    });

    return arr;
}
</code>```

The example below sorts an array of names by surname, retaining the order of equal surnames:

var names = [
 { surname: "Williams", firstname: "Mary" },
 { surname: "Doe", firstname: "Mary" },
 { surname: "Johnson", firstname: "Alan" },
 { surname: "Doe", firstname: "John" },
 { surname: "White", firstname: "John" },
 { surname: "Doe", firstname: "Sam" }
]

function stableSort(arr, compare) {
    var original = arr.slice(0);

    arr.sort(function(a, b){
        var result = compare(a, b);
        return result === 0 ? original.indexOf(a) - original.indexOf(b) : result;
    });

    return arr;
}

stableSort(names, function(a, b) {
 return a.surname > b.surname ? 1 : a.surname < b.surname ? -1 : 0;
})

names.forEach(function(name) {
 console.log(name.surname + ', ' + name.firstname);
});```

Body:
The following sorts the supplied array, by applying the supplied compare function, returning the original index comparison when the compare function returns 0:

function stableSort(arr, compare) {
    var original = arr.slice(0);

    arr.sort(function(a, b){
        var result = compare(a, b);
        return result === 0 ? original.indexOf(a) - original.indexOf(b) : result;
    });

    return arr;
}

The example below sorts an array of names by surname, retaining the order of equal surnames:

var names = [
 { surname: "Williams", firstname: "Mary" },
 { surname: "Doe", firstname: "Mary" },
 { surname: "Johnson", firstname: "Alan" },
 { surname: "Doe", firstname: "John" },
 { surname: "White", firstname: "John" },
 { surname: "Doe", firstname: "Sam" }
]

function stableSort(arr, compare) {
    var original = arr.slice(0);

    arr.sort(function(a, b){
        var result = compare(a, b);
        return result === 0 ? original.indexOf(a) - original.indexOf(b) : result;
    });

    return arr;
}

stableSort(names, function(a, b) {
 return a.surname > b.surname ? 1 : a.surname < b.surname ? -1 : 0;
})

names.forEach(function(name) {
 console.log(name.surname + ', ' + name.firstname);
});


问:
Jenkins with Mesos for Non container Tasks
My usecase would be running jenkins jobs on windows slaves where I have mesos agents running.
The jenkins-mesos plugin that is available spins up jenkins slave as containers. Is there any jenkins plugin out there which will connect jenkins master to mesos master & run the jobs on agents without any containers ?</p>

答:
By default, the Jenkins slaves are run in the default Mesos container. To run the Jenkins slave inside a Docker container, there are two options.

The MesosContainerizer currently does not provide any actual resource isolation (similar to running the Mesos agent on POSIX).

default Mesos container is working on Windows so there shoul not be any problem to run Jenkins on Windows with Mesos. You need to install Java on agents.


问:
Splinter fill function is very slow, with IE Webdriver
So, I've followed this tutorial to use the Splinter framework with Internet Explorer (https://stirunagari.wordpress.com/2017/08/20/using-internet-explorer-web-driver-with-splinter-framework/), and It's working....well kind of working.

```<code>from splinter import Browser
browser = Browser('iexplorer')
browser.visit('http://google.com')
browser.fill('q', 'Text to fill in the search bar')
</code>```

The search field is being filled but at a very slow rate, like 1 keystroke in 1-2 seconds. While using Chrome or Firefox as the browser the browser.fill is working well.
I know that this issue is most probably because IE is not directly supported by Splinter, but maybe someone knows a workaround or something?

Edit: I don't know what IEDriver I was using before, but I replaced it with IEDriverServer_Win32 from Here,and it's working fine now. I can't answer my question because someone deleted my answer...

答:
I wasn't using the latest Internet Explorer WebDriver; Updated it from here and it's working fine now:
http://selenium-release.storage.googleapis.com/index.html?path=3.8/</p>

Body:
So, I've followed this tutorial to use the Splinter framework with Internet Explorer (https://stirunagari.wordpress.com/2017/08/20/using-internet-explorer-web-driver-with-splinter-framework/), and It's working....well kind of working.

from splinter import Browser
browser = Browser('iexplorer')
browser.visit('http://google.com')
browser.fill('q', 'Text to fill in the search bar')

The search field is being filled but at a very slow rate, like 1 keystroke in 1-2 seconds. While using Chrome or Firefox as the browser the browser.fill is working well.
I know that this issue is most probably because IE is not directly supported by Splinter, but maybe someone knows a workaround or something?

Edit: I don't know what IEDriver I was using before, but I replaced it with IEDriverServer_Win32 from Here,and it's working fine now. I can't answer my question because someone deleted my answer...


问:
-su: /dev/tty: No such device or address
could please someone explain to me why this happens?

```<code># su - someone -s /bin/bash -c "ls -la /dev/tty"
crw-rw-rw- 1 nobody nogroup 5, 0 Dec  7 20:53 /dev/tty
# BUT:
# su - someone -s /bin/bash -c "echo hello > /dev/tty"
-su: /dev/tty: No such device or address
</code>```

I'm trieng to build a docker Container which has two services inside. Those services a startet by a Shell-Script:

```<code>CMD ["./starter.sh"]
</code>```

Withing the Dockerfile I have redirected the Logs to /dev/stderr or /dev/tty

```<code># None of the following works:
RUN ln -sf /dev/tty /var/log/thelog.log
RUN ln -sf /dev/stdout /var/log/thelog.log
RUN ln -sf /dev/stderr /var/log/thelog.log
</code>```

The problem is that I'm trying to run one of the services as not root (su -
 someone -c "service"), which give's the following error:

```<code>unable to open log file [/var/log/thelog.log]: [6] No such device or address
</code>```

How could I solve this problem? I want the logs to be linked to /dev/* AND want to run the User as non-root. Also I tried to add the User to the group tty, which did not work out.

Thanks.

答:
The manpage for su states that the executed command will have no controlling terminal.  Any writes to /dev/tty will return the ENXIO error:

```<code>$ errno ENXIO
ENXIO 6 No such device or address
</code>```

sudo does allocate a controlling terminal:

```<code>sudo -u someone /bin/bash -c "echo hello > /dev/tty"
</code>```

There's no need for you to make a symbolic link to /dev/tty (/dev/stdout and /dev/stderr is enough) or use sudo if you use the USER directive in the Dockerfile or supervisor.

Body:
could please someone explain to me why this happens?

# su - someone -s /bin/bash -c "ls -la /dev/tty"
crw-rw-rw- 1 nobody nogroup 5, 0 Dec  7 20:53 /dev/tty
# BUT:
# su - someone -s /bin/bash -c "echo hello > /dev/tty"
-su: /dev/tty: No such device or address

I'm trieng to build a docker Container which has two services inside. Those services a startet by a Shell-Script:

CMD ["./starter.sh"]

Withing the Dockerfile I have redirected the Logs to /dev/stderr or /dev/tty

# None of the following works:
RUN ln -sf /dev/tty /var/log/thelog.log
RUN ln -sf /dev/stdout /var/log/thelog.log
RUN ln -sf /dev/stderr /var/log/thelog.log

The problem is that I'm trying to run one of the services as not root (su -
 someone -c "service"), which give's the following error:

unable to open log file [/var/log/thelog.log]: [6] No such device or address

How could I solve this problem? I want the logs to be linked to /dev/* AND want to run the User as non-root. Also I tried to add the User to the group tty, which did not work out.

Thanks.

Body:
The manpage for su states that the executed command will have no controlling terminal.  Any writes to /dev/tty will return the ENXIO error:

$ errno ENXIO
ENXIO 6 No such device or address

sudo does allocate a controlling terminal:

sudo -u someone /bin/bash -c "echo hello > /dev/tty"

There's no need for you to make a symbolic link to /dev/tty (/dev/stdout and /dev/stderr is enough) or use sudo if you use the USER directive in the Dockerfile or supervisor.


问:
Google App Engine (Java) TaskQueue API: how to query number of running/pending tasks?
Is it possible to programmatically query the Task Queue API to see how many tasks are currently executing/pending?

I don't see any way to do this in the API, and so I resorted to creating objects in the Datastore to represent queued tasks. When run, the tasks then remove their corresponding entry from the Datastore.

As you can imagine, it's easy for this to get out of sync. I'd actually be pretty happy just to be able to get a simple count of tasks in the queue for a given queue name.

答: Unfortunately, there is no API you can use to get information about the task queues.  However, this is something I believe the team has in mind for the future (a programmatic interface to get stats that we currently see on the dashboard, like task count).</p>


问:
Javascript: Splice Multidimensional Object
I'm having this Object/Array Structure :

```<code>Obj = {
    "User": {
        "user1": [{
            "desc": "NG60",
            "Id": 3473631702,
            "Status": "offline"
        }],

        "user2": [{
            "desc": "somevalue",
            "Id": 963346121,
            "Status": "offline"
        },
        {
            "desc": "othervalue",  // SPLICE THIS OUT
            "Id": 963346122,      // SPLICE THIS OUT
            "Status": "offline"  // SPLICE THIS OUT
        }],

        "user3": [{
            "desc": "whatever",
            "Id": 972878784
        }]
    }
}
</code>```

I want to filter out different values, dynamically (fixed in this example)
and if there are no Ids left, I want to delete the whole user Array.

For example, if I want to filter out the 2nd Array Element of user2:

```<code> for(var users in Obj) {
     for(var Ids in Obj[users]) {
         if(Obj[users][Ids].Id == 963346122){
             Obj[users][Ids].splice(0, 1); // ERROR HERE
         }
     }
     if(Obj[users][Ids] == undefined) {
         delete Obj[users];
     }
 }
</code>```

I get this Error:

User[users][Ids].splice(0, 1) is not a function

How to splice only the Array Element that I'm addressing, not the complete user2 Array?

答:
You have to use another for loop to wrap the actual operation because the length is not the same for all iterating objects. That's why you have to slice the object from the proper position.

Try the following:

let Obj = {
  "User": {
      "user1": [
        {
          "desc": "NG60",
          "Id": 3473631702,
          "Status": "offline"
        }
      ],
      "user2": [
        {
          "desc": "somevalue",
          "Id": 963346121,
          "Status": "offline"
        },
        {
          "desc": "othervalue",  // SPLICE THIS OUT
          "Id": 963346122,      // SPLICE THIS OUT
          "Status": "offline"  // SPLICE THIS OUT
        }
      ],
      "user3": [
        {
          "desc": "whatever",
          "Id": 972878784
        }
      ]
    }
  }

for(var users in Obj) {
  for(var Ids in Obj[users]) {
    for(var i=0; i<Obj[users][Ids].length;i++){
      if(Obj[users][Ids][i].Id == 963346122){
          Obj[users][Ids].splice(i, 1); // ERROR HERE
      }
    }
  }
  if(Obj[users][Ids] == undefined) {
    delete Obj[users];
  }
}

console.log(Obj);```

Body:
I'm having this Object/Array Structure :

Obj = {
    "User": {
        "user1": [{
            "desc": "NG60",
            "Id": 3473631702,
            "Status": "offline"
        }],

        "user2": [{
            "desc": "somevalue",
            "Id": 963346121,
            "Status": "offline"
        },
        {
            "desc": "othervalue",  // SPLICE THIS OUT
            "Id": 963346122,      // SPLICE THIS OUT
            "Status": "offline"  // SPLICE THIS OUT
        }],

        "user3": [{
            "desc": "whatever",
            "Id": 972878784
        }]
    }
}

I want to filter out different values, dynamically (fixed in this example)
and if there are no Ids left, I want to delete the whole user Array.

For example, if I want to filter out the 2nd Array Element of user2:

 for(var users in Obj) {
     for(var Ids in Obj[users]) {
         if(Obj[users][Ids].Id == 963346122){
             Obj[users][Ids].splice(0, 1); // ERROR HERE
         }
     }
     if(Obj[users][Ids] == undefined) {
         delete Obj[users];
     }
 }

I get this Error:

User[users][Ids].splice(0, 1) is not a function

How to splice only the Array Element that I'm addressing, not the complete user2 Array?


问:
Python error: global variable in class undefined
I have a class with two variables set to some default value. I have defined a function where I declare these variables as global inside my function.  I get this error which says the variable is not defined. One variable is counter, which will increment on each function call and other variable has to append message on each call. After appending multiple messages and counter value reaches some threshold I want to insert all these messages into MySQL database.
But the variable is not appending the values. It shows the variable is undefined.</p>

```<code>class Message():
     insertStatement= ''
     insertCounter = 0

    def Save(self, msg)
        global insertCounter
        global insertStatement

        if  msg.topic.startswith("topic1/"):
            insertStatement += "INSERT INTO mydatabase.table VALUES (" + msg.payload.decode("utf-8") + "," + datetime + ");"
       elif msg.topic.startswith("topic2/"):
            insertStatement += "INSERT INTO mydatabase.table1 VALUES (" + msg.payload.decode("utf-8") + "," + datetime + ");"
       elif msg.topic.startswith("topic3/")
            insertStatement += "INSERT INTO mydatabase.table2 VALUES (" +msg.payload.decode("utf-8") + "," + datetime + ");"
       elif msg.topic.startswith("messages"):
            insertStatement += "INSERT INTO mydatabase.table3 VALUES ('" + msg.topic + "',"  + msg.payload.decode("utf-8") + "," + datetime + ");"
       else:
            return
       insertcounter +=1
       if(insertCounter > 1000):
         for result in cursor.execute(insertStatement, multi=True):
             print result.row_count  # i changed it to result
</code>```

答:
The variables insertStatement and insertCounter  are class variables. You dont have to reference them as global inside Save(). To access these class variables use Message.insertStatement  and Message.insertCounter

```<code> class Message():
         insertStatement= ''
         insertCounter = 0

        def Save(self, msg):

            if  msg.topic.startswith("topic1/"):
                Message.insertStatement += "INSERT INTO mydatabase.table VALUES (" + msg.payload.decode("utf-8") + "," + datetime + ");"
           elif msg.topic.startswith("topic2/"):
                Message.insertStatement += "INSERT INTO mydatabase.table1 VALUES (" + msg.payload.decode("utf-8") + "," + datetime + ");"
           elif msg.topic.startswith("topic3/")
                Message.insertStatement += "INSERT INTO mydatabase.table2 VALUES (" +msg.payload.decode("utf-8") + "," + datetime + ");"
           elif msg.topic.startswith("messages"):
                Message.insertStatement += "INSERT INTO mydatabase.table3 VALUES ('" + msg.topic + "',"  + msg.payload.decode("utf-8") + "," + datetime + ");"
           else:
                return
           Message.insertcounter +=1
           if(Message.insertCounter > 1000):
             for result in cursor.execute(Message.insertStatement, multi=True):
                 print result.row_count  # i changed it to result
</code>```

Body:
I have a class with two variables set to some default value. I have defined a function where I declare these variables as global inside my function.  I get this error which says the variable is not defined. One variable is counter, which will increment on each function call and other variable has to append message on each call. After appending multiple messages and counter value reaches some threshold I want to insert all these messages into MySQL database.
But the variable is not appending the values. It shows the variable is undefined.

class Message():
     insertStatement= ''
     insertCounter = 0

    def Save(self, msg)
        global insertCounter
        global insertStatement

        if  msg.topic.startswith("topic1/"):
            insertStatement += "INSERT INTO mydatabase.table VALUES (" + msg.payload.decode("utf-8") + "," + datetime + ");"
       elif msg.topic.startswith("topic2/"):
            insertStatement += "INSERT INTO mydatabase.table1 VALUES (" + msg.payload.decode("utf-8") + "," + datetime + ");"
       elif msg.topic.startswith("topic3/")
            insertStatement += "INSERT INTO mydatabase.table2 VALUES (" +msg.payload.decode("utf-8") + "," + datetime + ");"
       elif msg.topic.startswith("messages"):
            insertStatement += "INSERT INTO mydatabase.table3 VALUES ('" + msg.topic + "',"  + msg.payload.decode("utf-8") + "," + datetime + ");"
       else:
            return
       insertcounter +=1
       if(insertCounter > 1000):
         for result in cursor.execute(insertStatement, multi=True):
             print result.row_count  # i changed it to result

Body:
The variables insertStatement and insertCounter  are class variables. You dont have to reference them as global inside Save(). To access these class variables use Message.insertStatement  and Message.insertCounter

 class Message():
         insertStatement= ''
         insertCounter = 0

        def Save(self, msg):

            if  msg.topic.startswith("topic1/"):
                Message.insertStatement += "INSERT INTO mydatabase.table VALUES (" + msg.payload.decode("utf-8") + "," + datetime + ");"
           elif msg.topic.startswith("topic2/"):
                Message.insertStatement += "INSERT INTO mydatabase.table1 VALUES (" + msg.payload.decode("utf-8") + "," + datetime + ");"
           elif msg.topic.startswith("topic3/")
                Message.insertStatement += "INSERT INTO mydatabase.table2 VALUES (" +msg.payload.decode("utf-8") + "," + datetime + ");"
           elif msg.topic.startswith("messages"):
                Message.insertStatement += "INSERT INTO mydatabase.table3 VALUES ('" + msg.topic + "',"  + msg.payload.decode("utf-8") + "," + datetime + ");"
           else:
                return
           Message.insertcounter +=1
           if(Message.insertCounter > 1000):
             for result in cursor.execute(Message.insertStatement, multi=True):
                 print result.row_count  # i changed it to result


问:
sublime text : open containing folder
I'm working on some file in my sublime text 2 editor, and I want to open a folder in which that file resides.

I know there is a 2 step procedure to do this already

```<code>step 1: right click and reveal in sidebar (ctrl+shift+r)
step 2: right click on the same file in sidebar and click open containing folder.
</code>```

I would like to know if there is only one shortcut key to do the same. This is something that I use quite often.

答:
By default the editor has this item in context menu. If you need this feature on tabs you have to create a file with name "Tab Context.sublime-menu" in "\Data\Packages\User\" (if does not exist yet) and add this code:

```<code>[
    {
        "caption": "-"
    },
    {
        "command": "open_dir",
        "args": {"dir": "$file_path", "file": "$file_name"},
        "caption": "Open Containing Folder…"
    }
]
</code>```

Do not forget formatting lines as a JSON file! If you do not need a separator before this menu item you need to delete first block with caption "-"! You can add any other menu in this file. For example:

```<code>{
    "command": "copy_path",
    "caption": "Copy File Path"
},
</code>```

Title: sublime text : open containing folder

Body:
I'm working on some file in my sublime text 2 editor, and I want to open a folder in which that file resides.

I know there is a 2 step procedure to do this already

step 1: right click and reveal in sidebar (ctrl+shift+r)
step 2: right click on the same file in sidebar and click open containing folder.

I would like to know if there is only one shortcut key to do the same. This is something that I use quite often.

Body:
By default the editor has this item in context menu. If you need this feature on tabs you have to create a file with name "Tab Context.sublime-menu" in "\Data\Packages\User\" (if does not exist yet) and add this code:

[
    {
        "caption": "-"
    },
    {
        "command": "open_dir",
        "args": {"dir": "$file_path", "file": "$file_name"},
        "caption": "Open Containing Folder…"
    }
]

Do not forget formatting lines as a JSON file! If you do not need a separator before this menu item you need to delete first block with caption "-"! You can add any other menu in this file. For example:

{
    "command": "copy_path",
    "caption": "Copy File Path"
},


问:
count and groupby together in one query
The following query is fetching some product info on a page which is fine, but I also want to show the number of the product that it occurs as a text, however, I used groupby but I also want to use count on pro_id.

```<code> "SELECT * FROM cart  WHERE session_id='" . $_SESSION['session'] . "' GROUP BY
    pro_id  "
</code>```

答:
Your query won't work. Try like this;</p>

```<code> "SELECT pro_id,count(*) FROM cart  WHERE session_id='" . $_SESSION['session'] . "' GROUP BY
  pro_id  "
</code>```

Title: count and groupby together in one query

Body:
The following query is fetching some product info on a page which is fine, but I also want to show the number of the product that it occurs as a text, however, I used groupby but I also want to use count on pro_id.

 "SELECT * FROM cart  WHERE session_id='" . $_SESSION['session'] . "' GROUP BY
    pro_id  "

Body:
Your query won't work. Try like this;

 "SELECT pro_id,count(*) FROM cart  WHERE session_id='" . $_SESSION['session'] . "' GROUP BY
  pro_id  "


问:
Lightweight tool for generating random coordinates for specific region / country?
For now, I'm generating geo positions with only random module:

```<code>from random import uniform
geo_position =  (uniform(-90, 90), uniform(-180, 180))
</code>```

Obviously, this method can produce a dot somewhere in the ocean or about it. So I want to be able to specify some region (e.g. Asia) or even country and get the dot from that area.

Are there any tools/snippets for this?

答:
I'm answering my own question, and the answer is pretty simple, so I think it will work in the most of the cases. All you need to do is to:

Download the databases of the cities (link, maxmind.com). It weights 33mb in .gz format and includes 3.173.959 cities with there names and coordinates.

Extract the .txt file and shuffle the lines. It can be done with a simple command sort -R worldcitiespop.txt -o shuffled_cities.txt

Select the random line and it's done! Here's a visualization for 100 randomly selected cities:

Body:
For now, I'm generating geo positions with only random module:

from random import uniform
geo_position =  (uniform(-90, 90), uniform(-180, 180))

Obviously, this method can produce a dot somewhere in the ocean or about it. So I want to be able to specify some region (e.g. Asia) or even country and get the dot from that area.

Are there any tools/snippets for this?


问:
How do we get maximum value from table without using Max,Min or Order by Clause in SQL Server 2005?
I have one table has Salary has 3 columns and I want to get maximum value from this table without using Max, Min or order by clause.

Data

Salary has three fields - ID,Name,Amount
value of Amount - 100,70,80,400,300

I need to get value of 400 from this data.

I know Select max(Amount) from Salary, But i need without max,min or Order by clause.

Thanks in advance.

答:
Given this is a theoretical question only and NOT AT ALL practical... here's my answer.

ALL is a cool solution for SQL Server (see notes below). For the rest, and any ANSI compliant RDBMS

```<code>SELECT *
FROM salary s1
WHERE not exists (SELECT *
                  FROM salary s2
                  WHERE s2.id <> s1.id AND s2.Amount > s1.Amount);
</code>```

It is a bit better than the ALL answer though, since it will show all the TIES if there are multiple with the Max(salary) whereas Martin's will not return any results if there are TIES at the MAX.

It may also run faster due to not exists quitting per s1 row for any matches found in the correlated subquery.

Body:
Given this is a theoretical question only and NOT AT ALL practical... here's my answer.

ALL is a cool solution for SQL Server (see notes below). For the rest, and any ANSI compliant RDBMS

SELECT *
FROM salary s1
WHERE not exists (SELECT *
                  FROM salary s2
                  WHERE s2.id <> s1.id AND s2.Amount > s1.Amount);

It is a bit better than the ALL answer though, since it will show all the TIES if there are multiple with the Max(salary) whereas Martin's will not return any results if there are TIES at the MAX.

It may also run faster due to not exists quitting per s1 row for any matches found in the correlated subquery.


问:
Saving Value into Relation Column
Im new to Caché and got a problem: I want to save a value into the Relation Column in Class B via Class A and thats not working ...

Currently I am doing it like this

In Class A:

```<code>set Obj1 = ##class(This.Is.Class.B).%New()
set Obj1.PID = ..id
set Obj1.PName = ..name
set status = Obj1.%Save(0)
</code>```

Its saving the PName into Class B but not the PID which I defined as Relationship [One to Many] in Class B

答:
Connection objects in a relationship are bidirectional. But in any case, you can't just set id to such property. You should set object or insert object depending on which side you want to do it. In your case you do it like

```<code>do obj1.PIDSetObjectId(..id)
</code>```

To get more information read the documentation.

Title: Saving Value into Relation Column

Body:
Im new to Caché and got a problem: I want to save a value into the Relation Column in Class B via Class A and thats not working ...

Currently I am doing it like this

In Class A:

set Obj1 = ##class(This.Is.Class.B).%New()
set Obj1.PID = ..id
set Obj1.PName = ..name
set status = Obj1.%Save(0)

Its saving the PName into Class B but not the PID which I defined as Relationship [One to Many] in Class B

Body:
Connection objects in a relationship are bidirectional. But in any case, you can't just set id to such property. You should set object or insert object depending on which side you want to do it. In your case you do it like

do obj1.PIDSetObjectId(..id)

To get more information read the documentation.


问:
Increasing image margin based on a label value html
I have an image that is at the bottom of the screen and I would like to increase its margins (move it towards the top) based on the value of a label.

```<code><img src="flag.png"
style=" margin-left:50%;
        position:absolute;
        margin-top:50%;
        bottom:0px;
        ">
<label id="countdown" > countdown: </label>
</code>```

Label id="countdown" is updated frequently.

Essentially, is it possible to move the image up (increase the value of "bottom:0;") based on the value of the id="countdown"?

答:
I'm not sure how the value of the label is changed.
It might be easier to update the flag styling at the same time you update the label content.

Here's an example to get you started:
https://jsfiddle.net/fztkjb89/

```<code>$(function() {
  var initialCountDown = 100;
  var countDown = initialCountDown;

  setInterval(function(){
    // update label
    $('#counter').text(countDown);

    // update image style
    $('img').css('bottom', initialCountDown-countDown);

    // progress countdown
    countDown--;

    // reset counter
    if (countDown == 0){
      countDown = initialCountDown;
    }
  }, 100);
});
</code>```

If this is not an option, check out my other answer.

Body:
I have an image that is at the bottom of the screen and I would like to increase its margins (move it towards the top) based on the value of a label.

 countdown:

Label id="countdown" is updated frequently.

Essentially, is it possible to move the image up (increase the value of "bottom:0;") based on the value of the id="countdown"?

Body:
I'm not sure how the value of the label is changed.
It might be easier to update the flag styling at the same time you update the label content.

Here's an example to get you started:
https://jsfiddle.net/fztkjb89/

$(function() {
  var initialCountDown = 100;
  var countDown = initialCountDown;

  setInterval(function(){
    // update label
    $('#counter').text(countDown);

    // update image style
    $('img').css('bottom', initialCountDown-countDown);

    // progress countdown
    countDown--;

    // reset counter
    if (countDown == 0){
      countDown = initialCountDown;
    }
  }, 100);
});

If this is not an option, check out my other answer.