问:
nextElementSibling not working, unexpected behavior with objects or class javascript
I'm having an unexpected behavior using nextElementSibling property. the unexpected behavior only happens when I use the object document and his methods in another object attributes.

I'm doing a slider the goal is passing slides removing some class name from the current element add to the next element the same class name removed before, the problem is that I can remove from the first element and add to the second element but than stops doing it to the next elements, allways stop at the second element, and it only happens when I'm adding the document object to an attribute of an object.

My code

const Slider = {
    slides: document.querySelectorAll('.slide'),
    currentSlide: document.querySelector('.current-slide'),
    next: document.getElementById("next"),
    nextSlide: function () {
        this.currentSlide.classList.remove("current-slide");
        if (this.currentSlide.nextElementSibling) {
            this.currentSlide.nextElementSibling.classList.add('current-slide');
        } else {
            this.slides[0].classList.add('current-slide');
        }
    },
    onClick: function () {
        console.log()
        this.next.addEventListener('click', event => {
            console.log('CLICK');
            this.nextSlide();
        });

    }
}

Slider.onClick();```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.slider {
  position: relative;
  overflow: hidden;
  height: 100vh;
  width: 100vw;
  background-color: aqua;
}

/* SLIDE AND ALL CONTENT */

.slide {
  background-color: blueviolet;
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  opacity: 0;
  transition: opacity 0.4 ease-in-out;
}

.slide.current-slide {
  opacity: 1;
}

.slide .slide-content {
  position: absolute;
  left: -2500px;
  opacity: 0;
  width: 100vw;
  height: 100vh;
  background-color: rgba(136, 18, 18, 0.8);
  color: #fff;
  padding: 35px;
}

.slide.current-slide .slide-content {
  opacity: 1;
  transform: translateX(2500px);
  transition: all 0.1s ease-in-out 0.2s;
}

.slide-content h1 {
  margin: 0;
}</code>```

<!DOCTYPE html>

  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width,initial-scale=1.0">
  <link href="https://fonts.googleapis.com/css?family=Orbitron:400,500,600,700&display=swap" rel="stylesheet" />

  <title>test</title>

Slide1

Slide2

Slide3

Slide4

    <button id="next">
     click
    </button>

```

答:
As pointed out in the comments, the properties of Slider (slides and currentSlide) are not updated automatically when you have modified the DOM elements. They have the state when querySelectorAll was executed, so you have to update them manually or query them again.

To give you an idea:

```<code>getCurrentSlide: function() {
  this.currentSlide = document.querySelector(".current-slide");
},
nextSlide: function() {
  this.currentSlide.classList.remove("current-slide");
  if (this.currentSlide.nextElementSibling) {
    this.currentSlide.nextElementSibling.classList.add("current-slide");
  } else {
    this.slides[0].classList.add("current-slide");
  }
  this.getCurrentSlide(); // update currentSlide in Slider
},
</code>```

The slides object still represents the initial content though.

Body:
I'm having an unexpected behavior using nextElementSibling property. the unexpected behavior only happens when I use the object document and his methods in another object attributes.

I'm doing a slider the goal is passing slides removing some class name from the current element add to the next element the same class name removed before, the problem is that I can remove from the first element and add to the second element but than stops doing it to the next elements, allways stop at the second element, and it only happens when I'm adding the document object to an attribute of an object.

My code

const Slider = {
    slides: document.querySelectorAll('.slide'),
    currentSlide: document.querySelector('.current-slide'),
    next: document.getElementById("next"),
    nextSlide: function () {
        this.currentSlide.classList.remove("current-slide");
        if (this.currentSlide.nextElementSibling) {
            this.currentSlide.nextElementSibling.classList.add('current-slide');
        } else {
            this.slides[0].classList.add('current-slide');
        }
    },
    onClick: function () {
        console.log()
        this.next.addEventListener('click', event => {
            console.log('CLICK');
            this.nextSlide();
        });

    }
}

Slider.onClick();

.slider {
  position: relative;
  overflow: hidden;
  height: 100vh;
  width: 100vw;
  background-color: aqua;
}

/* SLIDE AND ALL CONTENT */

.slide {
  background-color: blueviolet;
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  opacity: 0;
  transition: opacity 0.4 ease-in-out;
}

.slide.current-slide {
  opacity: 1;
}

.slide .slide-content {
  position: absolute;
  left: -2500px;
  opacity: 0;
  width: 100vw;
  height: 100vh;
  background-color: rgba(136, 18, 18, 0.8);
  color: #fff;
  padding: 35px;
}

.slide.current-slide .slide-content {
  opacity: 1;
  transform: translateX(2500px);
  transition: all 0.1s ease-in-out 0.2s;
}

.slide-content h1 {
  margin: 0;
}

<!DOCTYPE html>

  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width,initial-scale=1.0">
  <link href="https://fonts.googleapis.com/css?family=Orbitron:400,500,600,700&display=swap" rel="stylesheet" />

  <title>test</title>

Slide1

Slide2

Slide3

Slide4

    <button id="next">
     click
    </button>

Body:
As pointed out in the comments, the properties of Slider (slides and currentSlide) are not updated automatically when you have modified the DOM elements. They have the state when querySelectorAll was executed, so you have to update them manually or query them again.

To give you an idea:

getCurrentSlide: function() {
  this.currentSlide = document.querySelector(".current-slide");
},
nextSlide: function() {
  this.currentSlide.classList.remove("current-slide");
  if (this.currentSlide.nextElementSibling) {
    this.currentSlide.nextElementSibling.classList.add("current-slide");
  } else {
    this.slides[0].classList.add("current-slide");
  }
  this.getCurrentSlide(); // update currentSlide in Slider
},

The slides object still represents the initial content though.


来源: stackexchange

问:
Interactive PDF Creation Alternatives to Acrobat?
Are there any good alternatives to Adobe Acrobat for creating interactive PDFs? The terminology is a little fuzzy here - by interactive, I mean "able to be filled in", and not necessarily "scriptable". So this form would be for data collection, rather than report generation which seems to be the common scenario for pdf-related questions on SO.

The trick is that they need to be fillable using Adobe Reader. For those who have not experienced the many frustrations of Acrobat - by default, Reader cannot fill in a form unless it was created using Acrobat Pro >8.0 and has specifically enabled usage rights. That's fine and it basically works (except then Pro users can't save their data - WTF?).

Because I am getting frustrated, I would ideally like to avoid Adobe products altogether (that is on the design side, for the users Reader is still a necessity or I would just do it as a db-backed web form). I'm wondering if anyone has has good experiences with alternatives? Either software libraries or products?

Thanks!

EDIT - Thanks, matt b - I'd seen iText before but didn't know it could create forms. Unfortunately, it looks like Reader cannot save filled-in data to the forms generated by iText (or generated by OO Writer). I've got the nasty feeling that what I want is fundamentally impossible except using Adobe's own rights management tools. If there are other ideas. I'd love to hear them.

答: iText is pretty much the standard in the java-world for generating PDF files programmatically. Perhaps it can also be used to create PDFs with forms in them as you would like?</p>

OwnerDisplayName: allclaws

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: allclaws

OwnerDisplayName: matt b


问:
Send Object as string, not JSON, via Node Express
Ok, I want the response to be a plain string, not JSON.

Ex. this object

let obj = {
  foo: 'bar',
  baz: 1
}
```

<p>Should be returned as </p>

```"{foo: 'bar', baz: 1}"
```

<p>Instead of</p>

```{"foo": "bar", "baz": 1}
```

<p>Why? I need to use the string as a link in quickchart</p>

<pre class="lang-html prettyprint-override"><code><img src="https://quickchart.io/chart?c={type:'line',data:{labels:['January','February', 'March','April', 'May'], datasets:[{label:'Dogs', data: [50,60,70,180,190], fill:false,borderColor:'blue'},{label:'Cats', data:[100,200,300,400,500], fill:false,borderColor:'green'}]}}">
</code>```

The double quotes in JSON break the image link.

Or, maybe suggest a better way.

答:
You might leverage a dedicated API for that like Image-Charts that handles such encoding issue nicely:

```<code>https://image-charts.com/chart?cht=lc
&chd=a:50,60,70,180,190|100,200,300,400,500
&chs=900x400
&chdl=Dogs|Cats&chdlp=t&chdls=444444,15
&chxt=x,y
&chxl=0:|January|February|March|April|May
&chg=1,1
&chco=0018F5,377E22
</code>```

Disclaimer: I'm Image-Charts founder.

ContentLicense: CC BY-SA 4.0

Body:
Ok, I want the response to be a plain string, not JSON.

Ex. this object

let obj = {
  foo: 'bar',
  baz: 1
}

Should be returned as

"{foo: 'bar', baz: 1}"

Instead of

{"foo": "bar", "baz": 1}

Why? I need to use the string as a link in quickchart

The double quotes in JSON break the image link.

Or, maybe suggest a better way.

Body:
You might leverage a dedicated API for that like Image-Charts that handles such encoding issue nicely:

https://image-charts.com/chart?cht=lc
&chd=a:50,60,70,180,190|100,200,300,400,500
&chs=900x400
&chdl=Dogs|Cats&chdlp=t&chdls=444444,15
&chxt=x,y
&chxl=0:|January|February|March|April|May
&chg=1,1
&chco=0018F5,377E22

Disclaimer: I'm Image-Charts founder.


问:
How to toggle sidebar container for mac application development using Swift?
I am learning Mac application development. I am using Xcode 10.3 & Swift 5. I have used 2 vertical split view controller in my application. But I would like to add the functionality of hiding the middle container or view using the button in the header.

I have started from scratch to create a new project and I have only touched my Storyboard where I have used Vertical split view controller and added few constraints.

I would like to use that toggle button to collapse and expand the middle split view (highlighted in yellow).

Also, Is there any icon provided by Apple for showing toggling functionality or do I need to upload one into the application?

I would appreciate the help. Thank you.

答: Yes, Apple provide NSToolbarToggleSidebarItemIdentifier which sends toggleSidebar: to the first responder (but target can be changed if necessary during toolbarWillAddItem:) and it looks like this:


问:
Angular Nested subscribe call
I have an Ionic app and trying to implement Login module for this using PHP REST and JWT.

1) User types credentials and api returns with token

2) Storing token in capacitor storage and intercept next http request and add token in header

3) Make call back to api and get logged in user info

4) Store info in capacitor storage and proceed further.

Following is the code.

```<code>loginAction() {
    if (this.validateInputs()) {
        console.log(this.postData);
        this.authService.login(this.postData).subscribe(
            (res: any) => {
                console.log(res);
                if (res.token) {
                    this.storageService.store('accessToken', res.token);
                    this.authService.getUserProfile().subscribe((profile: any) => {
                        console.log(profile);
                        this.storageService
                            .store(AuthConstants.AUTH, profile)
                            .then(res => {
                                this.router.navigate(['home']);
                            });
                    });
                }
            },
            (error: any) => {
                this.toastService.presentToast('Network Issue.');
            }
        );
    } else {
        this.toastService.presentToast(
            'Please enter email/username or password.'
        );
    }
}
</code>```

The only problem I am having is with the capacitor and nested subscribe call.

Sometimes execution to get the profile is quick and intercept returns with null value for accessToken.

How can I make sure that second http call is only executed after the accessToken is stored properly?

```<code>export class StorageService {
  constructor() {}

  // Store the value
  async store(storageKey: string, value: any) {
    const encryptedValue = btoa(escape(JSON.stringify(value)));
    await Storage.set({
      key: storageKey,
      value: encryptedValue
    });
  }
}
</code>```

Thank you

答:
Edit the storageService.store() function to return the Storage.set. As per the docs, it returns a Promise. You could then apply .then to your call and handle your operations in the callbacks.

```<code>export class StorageService {
  constructor() { }

  // Store the value
  public store(storageKey: string, value: any): any {
    const encryptedValue = btoa(escape(JSON.stringify(value)));
    return Storage.set({ key: storageKey, value: encryptedValue });
  }
}
</code>```

And within you loginAction() function:

```<code>if (res.token) {
  this.storageService.store('accessToken', res.token).then(
    data => {
      this.authService.getUserProfile().subscribe((profile: any) => {
          console.log(profile);
          this.storageService
            .store(AuthConstants.AUTH, profile)
            .then(res => { this.router.navigate(['home']); });
      });
    },
    error => { // handle error }
  );
}
</code>```

Title: Angular Nested subscribe call

Body:
I have an Ionic app and trying to implement Login module for this using PHP REST and JWT.

1) User types credentials and api returns with token

2) Storing token in capacitor storage and intercept next http request and add token in header

3) Make call back to api and get logged in user info

4) Store info in capacitor storage and proceed further.

Following is the code.

loginAction() {
    if (this.validateInputs()) {
        console.log(this.postData);
        this.authService.login(this.postData).subscribe(
            (res: any) => {
                console.log(res);
                if (res.token) {
                    this.storageService.store('accessToken', res.token);
                    this.authService.getUserProfile().subscribe((profile: any) => {
                        console.log(profile);
                        this.storageService
                            .store(AuthConstants.AUTH, profile)
                            .then(res => {
                                this.router.navigate(['home']);
                            });
                    });
                }
            },
            (error: any) => {
                this.toastService.presentToast('Network Issue.');
            }
        );
    } else {
        this.toastService.presentToast(
            'Please enter email/username or password.'
        );
    }
}

The only problem I am having is with the capacitor and nested subscribe call.

Sometimes execution to get the profile is quick and intercept returns with null value for accessToken.

How can I make sure that second http call is only executed after the accessToken is stored properly?

export class StorageService {
  constructor() {}

  // Store the value
  async store(storageKey: string, value: any) {
    const encryptedValue = btoa(escape(JSON.stringify(value)));
    await Storage.set({
      key: storageKey,
      value: encryptedValue
    });
  }
}

Thank you

Body:
Edit the storageService.store() function to return the Storage.set. As per the docs, it returns a Promise. You could then apply .then to your call and handle your operations in the callbacks.

export class StorageService {
  constructor() { }

  // Store the value
  public store(storageKey: string, value: any): any {
    const encryptedValue = btoa(escape(JSON.stringify(value)));
    return Storage.set({ key: storageKey, value: encryptedValue });
  }
}

And within you loginAction() function:

if (res.token) {
  this.storageService.store('accessToken', res.token).then(
    data => {
      this.authService.getUserProfile().subscribe((profile: any) => {
          console.log(profile);
          this.storageService
            .store(AuthConstants.AUTH, profile)
            .then(res => { this.router.navigate(['home']); });
      });
    },
    error => { // handle error }
  );
}


问:
Angular2 -- ngAfterViewChecked is called many times..How to call a method just once after DOM is completely loaded?
I need to apply jquery plugin to radio buttons in Angular2 using Typescript.

If I assign in ngAfterViewChecked, it is called many times and the control is refreshed multiple times.

What is the alternate solution for calling the javascript method after DOM is ready?

答:
I don't exactly know what you need to do and or achieve but I will show you my solution for a similar use case.

My Problem was that I needed to scroll down a div on load. AfterViewChecked got executed multiple times but I needed to scroll down in this lifecycle. Thats what I did, maybe it helps you:

```<code>    public scrollSuccessfull = false; // global variable

    public ngAfterViewChecked(): void {
        if (!this.scrollSuccessful) {
          // gets executed as long as the scroll wasnt successfull, so the (successful) scroll only gets executed once
          this.scrollSuccessful = this.scrollToBottom(this.internal ? this.internalChatDiv : this.externalChatDiv);
        }
      }

    private scrollToBottom(element: ElementRef): boolean {
        if (element) {
          element.nativeElement.scrollTop = element.nativeElement.scrollHeight;
          return element.nativeElement.scrollTop !== 0;
        }

        return false;
      }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I don't exactly know what you need to do and or achieve but I will show you my solution for a similar use case.

My Problem was that I needed to scroll down a div on load. AfterViewChecked got executed multiple times but I needed to scroll down in this lifecycle. Thats what I did, maybe it helps you:

    public scrollSuccessfull = false; // global variable

    public ngAfterViewChecked(): void {
        if (!this.scrollSuccessful) {
          // gets executed as long as the scroll wasnt successfull, so the (successful) scroll only gets executed once
          this.scrollSuccessful = this.scrollToBottom(this.internal ? this.internalChatDiv : this.externalChatDiv);
        }
      }

    private scrollToBottom(element: ElementRef): boolean {
        if (element) {
          element.nativeElement.scrollTop = element.nativeElement.scrollHeight;
          return element.nativeElement.scrollTop !== 0;
        }

        return false;
      }


问:
Passing variable from a function to a function within a function
I'm trying to create a chrome extension that takes a selected text via context menu, appends it to a url and update an existing tab (from the same domain) with the new URL.
This is my code:

```<code>function soso(search_target){
    alert(search_target);
    //search_target gets here successfully

    chrome.tabs.query({
        url: "https://lightning.force.com/lightning/*"},
        function(tabs, search_target){

        if (tabs[0]){

            chrome.tabs.update(tabs[0].id, {
                url: "http://www.facebook.com"+search_target, //search_target doesnt get here
                active: true
            });
        }
        else{
            alert("no window");
        }
        });
}

function selectionHandler (info, tab)
{
        soso( info.selectionText);
}

function resetContextMenus ()
{
    chrome.contextMenus.removeAll(
    function()
    {
            var id = chrome.contextMenus.create( {
                title: "Open in Salesforce",
                contexts: [ "selection" ],
            onclick: selectionHandler
        } );
    }
    );
}
resetContextMenus();
</code>```

The problem is that I cannot pass search_target to chrome.tabs.update, I get an undefined after the URL.

Any ideas on how to pass this variable?

答:
Let's move backwards with our analysis:

you try to call chrome.tabs.update, passing search_target

inside a callback function which has a search_target parameter

the function is called by chrome.tabs.query

and not by your outer function

but you have a valid search_target in the outer context

which is unreachable from the block of the callback function because a parameter with similar name which is undefined shadows it

Solution: Remove the parameter to allow the variable of the outer context be known inside the callback function:

```<code>function soso(search_target){
    alert(search_target);
    //search_target gets here successfully

    chrome.tabs.query({
        url: "https://lightning.force.com/lightning/*"},
        function(tabs){

        if (tabs[0]){

            chrome.tabs.update(tabs[0].id, {
                url: "http://www.facebook.com"+search_target, //search_target doesnt get here
                active: true
            });
        }
        else{
            alert("no window");
        }
        });
}

function selectionHandler (info, tab)
{
        soso( info.selectionText);
}

function resetContextMenus ()
{
    chrome.contextMenus.removeAll(
    function()
    {
            var id = chrome.contextMenus.create( {
                title: "Open in Salesforce",
                contexts: [ "selection" ],
            onclick: selectionHandler
        } );
    }
    );
}
resetContextMenus();
</code>```

Body:
I'm trying to create a chrome extension that takes a selected text via context menu, appends it to a url and update an existing tab (from the same domain) with the new URL.
This is my code:

function soso(search_target){
    alert(search_target);
    //search_target gets here successfully

    chrome.tabs.query({
        url: "https://lightning.force.com/lightning/*"},
        function(tabs, search_target){

        if (tabs[0]){

            chrome.tabs.update(tabs[0].id, {
                url: "http://www.facebook.com"+search_target, //search_target doesnt get here
                active: true
            });
        }
        else{
            alert("no window");
        }
        });
}

function selectionHandler (info, tab)
{
        soso( info.selectionText);
}

function resetContextMenus ()
{
    chrome.contextMenus.removeAll(
    function()
    {
            var id = chrome.contextMenus.create( {
                title: "Open in Salesforce",
                contexts: [ "selection" ],
            onclick: selectionHandler
        } );
    }
    );
}
resetContextMenus();

The problem is that I cannot pass search_target to chrome.tabs.update, I get an undefined after the URL.

Any ideas on how to pass this variable?

Body:
Let's move backwards with our analysis:

you try to call chrome.tabs.update, passing search_target

inside a callback function which has a search_target parameter

the function is called by chrome.tabs.query

and not by your outer function

but you have a valid search_target in the outer context

which is unreachable from the block of the callback function because a parameter with similar name which is undefined shadows it

Solution: Remove the parameter to allow the variable of the outer context be known inside the callback function:

function soso(search_target){
    alert(search_target);
    //search_target gets here successfully

    chrome.tabs.query({
        url: "https://lightning.force.com/lightning/*"},
        function(tabs){

        if (tabs[0]){

            chrome.tabs.update(tabs[0].id, {
                url: "http://www.facebook.com"+search_target, //search_target doesnt get here
                active: true
            });
        }
        else{
            alert("no window");
        }
        });
}

function selectionHandler (info, tab)
{
        soso( info.selectionText);
}

function resetContextMenus ()
{
    chrome.contextMenus.removeAll(
    function()
    {
            var id = chrome.contextMenus.create( {
                title: "Open in Salesforce",
                contexts: [ "selection" ],
            onclick: selectionHandler
        } );
    }
    );
}
resetContextMenus();


问:
Django admin change view exclude field if value is None
Currently i need to remove some fields from change view if it values is None

So i have an admin of Withdrawals model like so:

```<code>class WithdrawalsAdminForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(WithdrawalsAdminForm, self).__init__(*args, **kwargs)
        none_fields = []
        for single_field in self.fields:
            self.fields[single_field].disabled = True
            if self.initial[single_field] == None:
                none_fields.append(single_field)
        if none_fields:
            for single_none_field in none_fields:
                self.fields.pop(single_none_field)

class WithdrawalsAdmin(admin.ModelAdmin):
    list_display = ('get_email', 'get_phone_number', 'currency', 'method', 'amount', 'status', 'created')
    list_display_links = ('get_email', 'get_phone_number', 'currency', 'method', 'amount', 'status', 'created')
    list_filter = [WithdrawalsStatusFilter] #just a custom list filter
    change_form_template = 'admin/backend/withdrawals_change_form.html'
    form = WithdrawalsAdminForm
    fields = (
        'id',
        'get_email',
        'get_phone_number',
        'get_full_name',
        'currency',
        'method',
        'to_bank',
        'to_address',
        'to_card',
        'amount',
        'status',
        'transaction_id',
        'created',
        'submitted',
        'confirmed',
        )
    readonly_fields = (
        'id',
        'get_email',
        'get_phone_number',
        'get_full_name',
        'created',
    )

    def has_add_permission(self, request, obj=None):
        return False

    def get_queryset(self, request):
        qs = super(WithdrawalsAdmin, self).get_queryset(request)
        return qs.filter(Q(method=1) | Q(method=4))

    def get_email(self, obj):
        return obj.user.email
    get_email.short_description = 'User email'
    get_email.admin_order_field = 'EMAIL'

    def get_phone_number(self, obj):
        return obj.user.phone_number
    get_phone_number.short_description = 'User phone number'
    get_phone_number.admin_order_field = 'PHONE NUMBER'

    def get_full_name(self, obj):
        try:
            user_kyc = UserKyc.objects.get(user=obj.user)
            return decrypt_string(user_kyc.full_name)
        except:
            return None
    get_full_name.short_description = 'User full name'
    get_full_name.admin_order_field = 'FULL NAME'

admin.site.register(Withdrawals, WithdrawalsAdmin)
</code>```

But it returned to me the following error:

"Key 'to_address' not found in 'WithdrawalsForm'. Choices are: amount,
  currency, method, status, to_bank."

amount,currency, method, status, to_bank all have value not None in the object

to_address value is None, i had also tried to print out any field that is none in if self.initial[single_field] == None: and got the correct fields name(included to_address in it) that has None value.

How do i exclude field that have None value from change view ?

答:
The hard part is still about check None value on custom field.

Currently i only use the following get_fields to check , not much logical but still can remove field from the form:

```<code>def get_fields(self, request, obj=None):
    fields = super(WithdrawalsAdmin, self).get_fields(request, obj)
    fields_list = list(fields)
    if obj:
        if obj.to_address is None:
            fields_list.remove('to_address')
        .... #and other fields
    fields_tuple = tuple(fields_list)
    return fields_tuple
</code>```

Body:
Currently i need to remove some fields from change view if it values is None

So i have an admin of Withdrawals model like so:

class WithdrawalsAdminForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(WithdrawalsAdminForm, self).__init__(*args, **kwargs)
        none_fields = []
        for single_field in self.fields:
            self.fields[single_field].disabled = True
            if self.initial[single_field] == None:
                none_fields.append(single_field)
        if none_fields:
            for single_none_field in none_fields:
                self.fields.pop(single_none_field)

class WithdrawalsAdmin(admin.ModelAdmin):
    list_display = ('get_email', 'get_phone_number', 'currency', 'method', 'amount', 'status', 'created')
    list_display_links = ('get_email', 'get_phone_number', 'currency', 'method', 'amount', 'status', 'created')
    list_filter = [WithdrawalsStatusFilter] #just a custom list filter
    change_form_template = 'admin/backend/withdrawals_change_form.html'
    form = WithdrawalsAdminForm
    fields = (
        'id',
        'get_email',
        'get_phone_number',
        'get_full_name',
        'currency',
        'method',
        'to_bank',
        'to_address',
        'to_card',
        'amount',
        'status',
        'transaction_id',
        'created',
        'submitted',
        'confirmed',
        )
    readonly_fields = (
        'id',
        'get_email',
        'get_phone_number',
        'get_full_name',
        'created',
    )

    def has_add_permission(self, request, obj=None):
        return False

    def get_queryset(self, request):
        qs = super(WithdrawalsAdmin, self).get_queryset(request)
        return qs.filter(Q(method=1) | Q(method=4))

    def get_email(self, obj):
        return obj.user.email
    get_email.short_description = 'User email'
    get_email.admin_order_field = 'EMAIL'

    def get_phone_number(self, obj):
        return obj.user.phone_number
    get_phone_number.short_description = 'User phone number'
    get_phone_number.admin_order_field = 'PHONE NUMBER'

    def get_full_name(self, obj):
        try:
            user_kyc = UserKyc.objects.get(user=obj.user)
            return decrypt_string(user_kyc.full_name)
        except:
            return None
    get_full_name.short_description = 'User full name'
    get_full_name.admin_order_field = 'FULL NAME'

admin.site.register(Withdrawals, WithdrawalsAdmin)

But it returned to me the following error:

"Key 'to_address' not found in 'WithdrawalsForm'. Choices are: amount,
  currency, method, status, to_bank."

amount,currency, method, status, to_bank all have value not None in the object

to_address value is None, i had also tried to print out any field that is none in if self.initial[single_field] == None: and got the correct fields name(included to_address in it) that has None value.

How do i exclude field that have None value from change view ?

Body:
The hard part is still about check None value on custom field.

Currently i only use the following get_fields to check , not much logical but still can remove field from the form:

def get_fields(self, request, obj=None):
    fields = super(WithdrawalsAdmin, self).get_fields(request, obj)
    fields_list = list(fields)
    if obj:
        if obj.to_address is None:
            fields_list.remove('to_address')
        .... #and other fields
    fields_tuple = tuple(fields_list)
    return fields_tuple


问:
How to write diffrent code for ios and android in xamarin.forms?
I created a xamarin.forms project. Suppose I have a button, and I want this button to call different platforms' APIs (third-party ios / android skd) on different platforms.

How to import jar for xamarin.android/ios sdk for xamarin.ios?

Assuming this button is in a page of xamarin.forms, how do I bind different events for different platforms so that it can call different APIs on different platforms?

Project structure:

答:
In this case you must implement dependency service

Pseudo code example

In shared code create public interface

```<code>public interface IService
{
    void DoSomething();
}
</code>```

In specific platform code create dependency service

```<code>[assembly: Xamarin.Forms.Dependency(typeof(MyServiceIOS))]

namespace MyNamespace.iOS
{
    public class MyServiceIOS : IService
    {
        public void DoSomething()
        {
            //your code here
        }
    }
}
</code>```

Body:
In this case you must implement dependency service

Pseudo code example

In shared code create public interface

public interface IService
{
    void DoSomething();
}

In specific platform code create dependency service

[assembly: Xamarin.Forms.Dependency(typeof(MyServiceIOS))]

namespace MyNamespace.iOS
{
    public class MyServiceIOS : IService
    {
        public void DoSomething()
        {
            //your code here
        }
    }
}


问:
How can i format the date into specified format which comes from db in <g:select>
I need to have a dropdown which holds dates.

when i write

```<code><g:select id="dob" name="dob" from="${Person.list().dateOfBirth}"  value="${personInstance?.dateOfBirth}" />
</code>```

this displays the date in the format 2011-05-17 00:00:00.0 But i need to have the format mm/dd/yyyy.

How can i do that?

答:
Grails has a formatDate Tag which you can use as a method call in this situation. Example:

value="${formatDate(format:'mm/dd/yyyy', date: yourDate)}" />

Body:
I need to have a dropdown which holds dates.

when i write

<g:select id="dob" name="dob" from="${Person.list().dateOfBirth}"  value="${personInstance?.dateOfBirth}" />

this displays the date in the format 2011-05-17 00:00:00.0 But i need to have the format mm/dd/yyyy.

How can i do that?


问:
Removing a line break after using list in paragraph
I am working on website where i have to put information so I am using a list inside a paragraph but after the list name the text moves to another line. I want to start a paragraph after the list.I have attached the output and my target.The output Output The target Target</p>

```<code>    <div class="history">
        <h1 class="h-history">History</h1>
        <p class="p">It was established in 1879....</p>
        <h1 class="h-history">Areas and attractions</h1>
        <p class="p"><li>Elephant House</li>is the first....</p>

    </div>
</code>```

答:
You can achieve by :before content: '\2022'; property like below snippet.

.bullet {
  position: relative;
  padding-left: 10px;
}
.bullet:before {
  content: '\2022';
  color: blue;
  position: absolute;
  left: 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="history">
  <h1 class="h-history">History</h1>
  <p class="p">It was established in 1879.</p>
  <h1 class="h-history">Areas and attractions</h1>
  <p class="p bullet"><strong>Elephant House</strong>is the most famous exhibit in the zoo. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>
</div></code>```

Body:
I am working on website where i have to put information so I am using a list inside a paragraph but after the list name the text moves to another line. I want to start a paragraph after the list.I have attached the output and my target.The output Output The target Target

History

It was established in 1879....

Areas and attractions

Elephant House
is the first....

Body:
You can achieve by :before content: '\2022'; property like below snippet.

.bullet {
  position: relative;
  padding-left: 10px;
}
.bullet:before {
  content: '\2022';
  color: blue;
  position: absolute;
  left: 0;
}

<div class="history">
  <h1 class="h-history">History</h1>
  <p class="p">It was established in 1879.</p>
  <h1 class="h-history">Areas and attractions</h1>
  <p class="p bullet"><strong>Elephant House</strong>is the most famous exhibit in the zoo. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>
</div>


问:
Distinct values in python list
I need to extract unique values in python list by omitting the repeated values altogether:

Input:

```<code>lis = ['a','l','f','a']
</code>```

Desired Output:

```<code>lis2 = ['l','f']
</code>```

So I need to remove all duplicate iteams.
Sets won't do cause I don't want 'a' in it

答:
You basically want items which count in the list is only 1. Count of items in the list - use Counter class

```<code>from collections import Counter
lis = ['a','l','f','a']
counter = Counter(lis)
lis2 = [elem for elem in lis if counter[elem] == 1]
print(lis2)
</code>```

You could also use list.count, but that would go through the list each time, giving you O(n^2) complexity, while creating the Counter is O(n) and then checking count is O(1) (n times), resulting in O(n).

Title: Distinct values in python list

Body:
I need to extract unique values in python list by omitting the repeated values altogether:

Input:

lis = ['a','l','f','a']

Desired Output:

lis2 = ['l','f']

So I need to remove all duplicate iteams.
Sets won't do cause I don't want 'a' in it

Body:
You basically want items which count in the list is only 1. Count of items in the list - use Counter class

from collections import Counter
lis = ['a','l','f','a']
counter = Counter(lis)
lis2 = [elem for elem in lis if counter[elem] == 1]
print(lis2)

You could also use list.count, but that would go through the list each time, giving you O(n^2) complexity, while creating the Counter is O(n) and then checking count is O(1) (n times), resulting in O(n).


问:
IBM Domino Java - optimize searching on $(Rooms) view for specific internet address
I'm fairly new to IBM Domino. I have an XPages Java application that works as an extended API for the standard Rooms & Resoruce management database (allows me to manipulate appointments easily and offers more functionality than the standard API, such as modifying appointments of other people).

When I want to get a list of all appointments for a specific room, I pass the internet (mail) address of the room to my API, and in the Java app I iterate over the $(Rooms) view in names.nsf looking for documents until I find one with the InternetAddress item I'm looking for. I then get some other interesting information from the document such as the auto processing settings.

It works, but I'm pretty sure it's not efficient at all and I'm querying over 50 rooms, getting appointments for all of them takes about 18 seconds, and I'm not really satisfied with this result.
How could I optimize this? I'm pretty sure I can do some simple search on the view that will do everything under the hood in a more optimized way, but I haven't got enough experience to make it work.
My current code:

        Session session = ExtLibUtil.getCurrentSession();
        Database names = session.getDatabase(session.getServerName(), "names.nsf");
        View vw = names.getView("($Rooms)");
        lotus.domino.ViewNavigator nav = vw.createViewNav();

        ViewEntry nextEntry = nav.getFirst();
        Document docRoom = null;
        while (nextEntry != null) {
            ViewEntry processEntry = nextEntry;
            nextEntry = nav.getNext();

            if (processEntry.isDocument() && processEntry.isValid()) {
                docRoom = processEntry.getDocument();
                // found
                if(docRoom.getItemValueString("InternetAddress").equals(mail)) {
                    processEntry.recycle();
                    break;
                } else { // not found
                    processEntry.recycle();
                    docRoom.recycle();
                    docRoom = null;
                }
            } else processEntry.recycle();
        }
        if(docRoom == null)
            return null;
        nav.recycle();

        String fileName = docRoom.getItemValueString("MailFile");
        String fileServer = docRoom.getItemValueString("MailServer");
        String fullName = docRoom.getItemValueString("FullName");
```

答:
You're running 50 times over all available view entries. Because of that it takes too much time. Time complexity of your approach is O(N*M).

There's more efficient way to get a document from view by key.

```<code>Document doc = view.getDocumentByKey(yourKeyValue);
</code>```

It runs way more faster (O(LogN) time complexity), but it requires that the view should contain the first sorted column with the yourKeyValue values. In our case, we should have a view that has InternetAddress as the first sorted column.

Unfortunately ($Rooms) view does not apply to this rule. The first column of this view contains different data, than we need.

I would create a new view in the names.nsf for the task.

Let's name it (RoomsByInternetAddress) and put the following formula as selection formula for the created view:

```<code>SELECT ((Type = "Database") &(ResourceFlag="1") & (ResourceType="1") & (AutoProcessType != "D")) & (Form="Resource":"Database") & @IsUnavailable($Conflict)
</code>```

It is the actual formula for ($Rooms) view.

Make the first column of the view sorted and set the first column value to the InternetAddress field.

Then save it and close it. As it is closed, in the view properties (in the designer view list), enable "Prohibit design refresh or modify". It will protect the new created view from removing upon refreshing from the original server names.nsf template.

After that in your code you do not need to walk over all entries.

```<code>View vw = names.getView("(RoomsByInternetAddress)");

String InternetAddressIWantToFind = "someroom@company.com";
Document foundDoc = vw.getDocumentByKey(InternetAddressIWantToFind, true);
if (foundDoc != null) {
   // you've found the document by InternetAddress
}
</code>```

Update

For cases when you are not authorized to change server's names.nsf there is another option.

IBM Domino Java API Database class supports search() method.

Here's info about search formula syntax: https://stackoverflow.com/a/9770367/12576990

Body:
You're running 50 times over all available view entries. Because of that it takes too much time. Time complexity of your approach is O(N*M).

There's more efficient way to get a document from view by key.

Document doc = view.getDocumentByKey(yourKeyValue);

It runs way more faster (O(LogN) time complexity), but it requires that the view should contain the first sorted column with the yourKeyValue values. In our case, we should have a view that has InternetAddress as the first sorted column.

Unfortunately ($Rooms) view does not apply to this rule. The first column of this view contains different data, than we need.

I would create a new view in the names.nsf for the task.

Let's name it (RoomsByInternetAddress) and put the following formula as selection formula for the created view:

SELECT ((Type = "Database") &(ResourceFlag="1") & (ResourceType="1") & (AutoProcessType != "D")) & (Form="Resource":"Database") & @IsUnavailable($Conflict)

It is the actual formula for ($Rooms) view.

Make the first column of the view sorted and set the first column value to the InternetAddress field.

Then save it and close it. As it is closed, in the view properties (in the designer view list), enable "Prohibit design refresh or modify". It will protect the new created view from removing upon refreshing from the original server names.nsf template.

After that in your code you do not need to walk over all entries.

View vw = names.getView("(RoomsByInternetAddress)");

String InternetAddressIWantToFind = "someroom@company.com";
Document foundDoc = vw.getDocumentByKey(InternetAddressIWantToFind, true);
if (foundDoc != null) {
   // you've found the document by InternetAddress
}

Update

For cases when you are not authorized to change server's names.nsf there is another option.

IBM Domino Java API Database class supports search() method.

Here's info about search formula syntax: https://stackoverflow.com/a/9770367/12576990


问:
The formula "lookup" cannot find the value searched
In the table below, I am registering new products on the page named data. If the serial number in the page named "matbaaya_giden" has the largest 4 values, it is transferred to the page named "data" as 5. What I want is;

He needs to add -1 to the number 5 on the "data" page and bring the price for the product name and serial number match.
I use the formula below for this.

```<code>"=LOOKUP(2;1/((matbaaya_giden!$B$2:$B$2000=$B2)*(matbaaya_giden!$G$2:$G$2000=G2-1));matbaaya_giden!I$2:I$2000)"
</code>```

This formula works in Excel. But I can't find the 2 value in "LOOKUP (2" in google tables and it gives an error. How can I make the formula work?

SHEET:
https://docs.google.com/spreadsheets/d/1G2I52a7o15IRMzNHxRmkmZ2IuWpph0e4k7URWm3E6Gs/edit?usp=sharing

答:
You need to  explicitly state that it's a arrayformula</p>

```<code>=ARRAYFORMULA(LOOKUP(2;1/((matbaaya_giden!$B$2:$B$2000=$B2)*(matbaaya_giden!$G$2:$G$2000=G2-1));matbaaya_giden!I$2:I$2000))
</code>```

Body:
In the table below, I am registering new products on the page named data. If the serial number in the page named "matbaaya_giden" has the largest 4 values, it is transferred to the page named "data" as 5. What I want is;

He needs to add -1 to the number 5 on the "data" page and bring the price for the product name and serial number match.
I use the formula below for this.

"=LOOKUP(2;1/((matbaaya_giden!$B$2:$B$2000=$B2)*(matbaaya_giden!$G$2:$G$2000=G2-1));matbaaya_giden!I$2:I$2000)"

This formula works in Excel. But I can't find the 2 value in "LOOKUP (2" in google tables and it gives an error. How can I make the formula work?

SHEET:
https://docs.google.com/spreadsheets/d/1G2I52a7o15IRMzNHxRmkmZ2IuWpph0e4k7URWm3E6Gs/edit?usp=sharing

Body:
You need to  explicitly state that it's a arrayformula

=ARRAYFORMULA(LOOKUP(2;1/((matbaaya_giden!$B$2:$B$2000=$B2)*(matbaaya_giden!$G$2:$G$2000=G2-1));matbaaya_giden!I$2:I$2000))


问:
How to reverse multiple lines of input? (C)
I've been stuck on this for a while and any help would be greatly appreciated.

I'm trying to reverse input one line at a time but display it all together at the end.

```<code>Eg Input = abc 123
           lorem ipsum
           dolor sit amet

Output = 321 cba
         muspi merol
         tema tis rolod
</code>```

This is what I have so far, but it only reverses the last line of input.
My thoughts are that I am possibly not reading in all the input, but am unusure how to remedy this?

```<code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void reverse(char *input, int length){
    for(int i = length-1; i >= 0; i--){
        printf("%c", input[i]);

    }

}

int main(void){
    char input[100];

    while(!feof(stdin)){

        fgets(input, 100, stdin);

    }

    reverse(input, strlen(input));

    return 0;
}
</code>```

答:
As noted in the comments,

Anything you put inside your while loop will be executed for each line. Anything you put outside your while loop will only be executed once.

So put your reversing code in the loop, together with fgets.

Body:
I've been stuck on this for a while and any help would be greatly appreciated.

I'm trying to reverse input one line at a time but display it all together at the end.

Eg Input = abc 123
           lorem ipsum
           dolor sit amet

Output = 321 cba
         muspi merol
         tema tis rolod

This is what I have so far, but it only reverses the last line of input.
My thoughts are that I am possibly not reading in all the input, but am unusure how to remedy this?

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void reverse(char *input, int length){
    for(int i = length-1; i >= 0; i--){
        printf("%c", input[i]);

    }

}

int main(void){
    char input[100];

    while(!feof(stdin)){

        fgets(input, 100, stdin);

    }

    reverse(input, strlen(input));

    return 0;
}


问:
How to improve or debug Typescript ts-node compile time?
I switched my codebase to typescript. It's around 100k lines of codes in hundreds of files.

Before my launch time was 2 seconds with ESLint --fix --cache. Now with Typescript (ts-node) it is 25 seconds (20 seconds is typescript only).

The project is backend only.

25 seconds is kind of unacceptable speed. Is this normal? I tried to remove every dynamic require I could find but still didn't help. Could it be some large file that is taking too long? How can I know what's taking so long?

答:
You do not have to run production build with ts-node, it just transpiles your code on a fly. You can simply check it, run ts-node and paste some code, then try to see sources of runtime code. Also compilation level and other configurations matter at your tsconfig file.

```<code>> const a = (a: string) => a + 'hello';
undefined
> a.toString()
"function (a) { return a + 'hello'; }"
</code>```

So when you run your project it:

Typechecks your every file

Transpiles your every file

Interprets such file

Then only runs your code

As it is an interpreted process so your time goes to (require -> typecheck -> transpile -> run -> repeat) till all your code is executed. As your codebase is cascade you my run into performance issues on typechecking

Body:
You do not have to run production build with ts-node, it just transpiles your code on a fly. You can simply check it, run ts-node and paste some code, then try to see sources of runtime code. Also compilation level and other configurations matter at your tsconfig file.

> const a = (a: string) => a + 'hello';
undefined
> a.toString()
"function (a) { return a + 'hello'; }"

So when you run your project it:

Typechecks your every file

Transpiles your every file

Interprets such file

Then only runs your code

As it is an interpreted process so your time goes to (require -> typecheck -> transpile -> run -> repeat) till all your code is executed. As your codebase is cascade you my run into performance issues on typechecking


问:
ActionNotSupported error when a WCF Service is created at runtime
I am trying to create a WCF service at runtime. My service interface is:

```<code>[ServiceContract]
public interface IInformationService : IService
{
    [OperationContract]
    [WebInvoke(Method = "Get", ResponseFormat = WebMessageFormat.Json,
     UriTemplate = "Test",     RequestFormat  = WebMessageFormat.Json)]
    string Test();
}
</code>```

I am serving my service as follows:

```<code>var httpEnumerator = ImplementedContracts.Values.GetEnumerator();
httpEnumerator.MoveNext();

var httpContractType = httpEnumerator.Current.ContractType;
var webBinding = new WebHttpBinding()
                 {
                   Security =
                   {
                     Mode = WebHttpSecurityMode.None
                   }
                 };

var httpEndpoint = AddServiceEndpoint(
  httpContractType,
  webBinding, baseAddress+/Get"
);

httpEndpoint.Behaviors.Add(new CustomEndpointBehavior());
</code>```

The ServiceHost is created by this method:

```<code>protected override ServiceHost CreateServiceHost(Type serviceType, Uri[] baseAddresses)
{
  var host = new WcfServiceHost(serviceType, baseAddresses);

  if (host.Description.Behaviors.Contains(typeof(ServiceDebugBehavior)))
  {
    (host.Description.Behaviors[typeof(ServiceDebugBehavior)] as
    ServiceDebugBehavior).IncludeExceptionDetailInFaults = true;
  }
  else
  {
    var debug = new ServiceDebugBehavior
                {
                  IncludeExceptionDetailInFaults = true
                };

    host.Description.Behaviors.Add(debug);
  }

  if (host.Description.Behaviors.Contains(typeof(ServiceMetadataBehavior)))
  {
    (host.Description.Behaviors[typeof(ServiceMetadataBehavior)] as ServiceMetadataBehavior).HttpGetEnabled = true;
    (host.Description.Behaviors[typeof(ServiceMetadataBehavior)] as ServiceMetadataBehavior).HttpsGetEnabled = true;
  }
  else
  {
    var smb = new ServiceMetadataBehavior
              {
                HttpGetEnabled = true,
                HttpsGetEnabled = true
              };

    host.Description.Behaviors.Add(smb);
  }

  host.AddServiceEndpoint(
    ServiceMetadataBehavior.MexContractName,
    MetadataExchangeBindings.CreateMexHttpsBinding(),
    "mex"
  );

  host.AddServiceEndpoint(
    ServiceMetadataBehavior.MexContractName,
    MetadataExchangeBindings.CreateMexHttpBinding(),
    "mex"
  );

  return host;
}
</code>```

Service route creation:

```<code>var serviceRoute = new ServiceRoute(
  "wcf.service/" + service.Value.Name,
  new WcfServiceHostFactory(),
  service.Value
);

if (!RouteTable.Routes.Contains(serviceRoute))
{
    RouteTable.Routes.Add(serviceRoute);
}
</code>```

When I try to access my service from a web browser using the address

http://localhost/Werp.View/wcf.service/InformationService/Get/Test

I obtain the following error:

```<code><Fault xmlns="http://schemas.microsoft.com/ws/2005/05/envelope/none">
  <Code>
    <Value>Sender</Value>
    <Subcode>
      <Value xmlns:a="http://schemas.microsoft.com/ws/2005/05/addressing/none">
         a:ActionNotSupported
      </Value>
    </Subcode>
  </Code>

<Reason>
  <Text xml:lang="en-US">
    The message with Action '' cannot be processed at the receiver, due to a
    ContractFilter mismatch at the EndpointDispatcher. This may be because of
    either a contract mismatch (mismatched Actions between sender and receiver)
    or a binding/security mismatch between the  sender and the receiver. Check
    that sender and receiver have the same contract and the same  binding
    (including security requirements, e.g. Message, Transport, None).
  </Text>
</Reason>
</code>```

Can anyone help me?

答: In my case, I needed to add a HTTP header to the request called SOAPAction, where the value was set to the xmlns path to the service I was requesting.

Body:
I am trying to create a WCF service at runtime. My service interface is:

[ServiceContract]
public interface IInformationService : IService
{
    [OperationContract]
    [WebInvoke(Method = "Get", ResponseFormat = WebMessageFormat.Json,
     UriTemplate = "Test",     RequestFormat  = WebMessageFormat.Json)]
    string Test();
}

I am serving my service as follows:

var httpEnumerator = ImplementedContracts.Values.GetEnumerator();
httpEnumerator.MoveNext();

var httpContractType = httpEnumerator.Current.ContractType;
var webBinding = new WebHttpBinding()
                 {
                   Security =
                   {
                     Mode = WebHttpSecurityMode.None
                   }
                 };

var httpEndpoint = AddServiceEndpoint(
  httpContractType,
  webBinding, baseAddress+/Get"
);

httpEndpoint.Behaviors.Add(new CustomEndpointBehavior());

The ServiceHost is created by this method:

protected override ServiceHost CreateServiceHost(Type serviceType, Uri[] baseAddresses)
{
  var host = new WcfServiceHost(serviceType, baseAddresses);

  if (host.Description.Behaviors.Contains(typeof(ServiceDebugBehavior)))
  {
    (host.Description.Behaviors[typeof(ServiceDebugBehavior)] as
    ServiceDebugBehavior).IncludeExceptionDetailInFaults = true;
  }
  else
  {
    var debug = new ServiceDebugBehavior
                {
                  IncludeExceptionDetailInFaults = true
                };

    host.Description.Behaviors.Add(debug);
  }

  if (host.Description.Behaviors.Contains(typeof(ServiceMetadataBehavior)))
  {
    (host.Description.Behaviors[typeof(ServiceMetadataBehavior)] as ServiceMetadataBehavior).HttpGetEnabled = true;
    (host.Description.Behaviors[typeof(ServiceMetadataBehavior)] as ServiceMetadataBehavior).HttpsGetEnabled = true;
  }
  else
  {
    var smb = new ServiceMetadataBehavior
              {
                HttpGetEnabled = true,
                HttpsGetEnabled = true
              };

    host.Description.Behaviors.Add(smb);
  }

  host.AddServiceEndpoint(
    ServiceMetadataBehavior.MexContractName,
    MetadataExchangeBindings.CreateMexHttpsBinding(),
    "mex"
  );

  host.AddServiceEndpoint(
    ServiceMetadataBehavior.MexContractName,
    MetadataExchangeBindings.CreateMexHttpBinding(),
    "mex"
  );

  return host;
}

Service route creation:

var serviceRoute = new ServiceRoute(
  "wcf.service/" + service.Value.Name,
  new WcfServiceHostFactory(),
  service.Value
);

if (!RouteTable.Routes.Contains(serviceRoute))
{
    RouteTable.Routes.Add(serviceRoute);
}

When I try to access my service from a web browser using the address

http://localhost/Werp.View/wcf.service/InformationService/Get/Test

I obtain the following error:

<Fault xmlns="http://schemas.microsoft.com/ws/2005/05/envelope/none">

    <Value>Sender</Value>
    <Subcode>
      <Value xmlns:a="http://schemas.microsoft.com/ws/2005/05/addressing/none">
         a:ActionNotSupported
      </Value>
    </Subcode>

<Reason>
  <Text xml:lang="en-US">
    The message with Action '' cannot be processed at the receiver, due to a
    ContractFilter mismatch at the EndpointDispatcher. This may be because of
    either a contract mismatch (mismatched Actions between sender and receiver)
    or a binding/security mismatch between the  sender and the receiver. Check
    that sender and receiver have the same contract and the same  binding
    (including security requirements, e.g. Message, Transport, None).
  </Text>
</Reason>

Can anyone help me?


问:
Git Diff - How do I revert selected lines or chunks
In Git GUI I can select parts of a diff and stage just those lines or chunks. How would I do the opposite, as in roll back changed lines in a file. Usually these are accidental white space changes I just want to revert out but still stage/commit other parts of the same file.</p>

答:
Since Git 2.24, Git GUI features the "Revert Hunk" and "Revert Line" options in the context menu, similar to staging. You can even "Undo Last Revert" which is a great addition.

Here's the commit that added this functionality:
https://github.com/git/git/commit/62bd99934bb2b1a07f786fdf9b94d7b692768e30


问:
JQuery or Javascript function for MOD 10 algorithm
What will be the Javascript or JQuery code for following scenario ?

"A ABA  TextBox=Mandatory field".

Must be numeric and 9 digits. Perform MOD 10 algorithm

Multiply each digit of the first 8 digits of the ABA/Routing number with the following numbers respectively.
a. 3,7,1,3,7,1,3,7

Add the results of the 8 multiplications.

Subtract the sum from the next highest multiple of 10.

The result of the above step 3 must be equal to the 9th digit of the ABA/Routing number. If not display error in Message section

I have 9 different textboxes for each digit of ABA number . First I have to check if the entered number is numeric or not then I have to add this valid number in a String Array onwhich finally i will be adding my ABA Number validation .

I am absolutely stuck . Dont know how to solve this thing . I have found few codes but which doesnt qualify my need

EDIT :This is my HTML Code  OnKeyUp Event I am adding value of perticular textbox in a string Array and OnKeyPress I am checking if the entered number is numeric or not

```<code>    <div style="padding-bottom: 5px; padding-left: 200px;padding-right: 20px;padding-top: 0;vertical-align: middle; width: 500px;">
  <input type="text" maxlength="1" size="10px" style="width:15px" id="ab1" onkeypress ="return onlyNumbers();" onkeyup ="return addABNumbers();"  />
  <input type="text" maxlength="1" size="10px" style="width:15px" id="ab2" onkeypress ="return onlyNumbers();" onkeyup ="return addABNumbers();" />
  <input type="text" maxlength="1" size="10px" style="width:15px" id="ab3" onkeypress ="return onlyNumbers();" onkeyup ="return addABNumbers();" />
  <input type="text" maxlength="1" size="10px" style="width:15px" id="ab4" onkeypress ="return onlyNumbers();" onkeyup ="return addABNumbers();" />
  <input type="text" maxlength="1" size="10px" style="width:15px" id="ab5" onkeypress ="return onlyNumbers();" onkeyup ="return addABNumbers();"  />
  <input type="text" maxlength="1" size="10px" style="width:15px" id="ab6" onkeypress ="return onlyNumbers();" onkeyup ="return addABNumbers();" />
  <input type="text" maxlength="1"  size="10px" style="width:15px" id="ab7" onkeypress ="return onlyNumbers();" onkeyup ="return addABNumbers();" />
  <input type="text" maxlength="1" size="10px" style="width:15px" id="ab8" onkeypress ="return onlyNumbers();" onkeyup ="return addABNumbers();" />
  <input type="text" maxlength="1" size="10px" style="width:15px" id="ab9" onkeypress ="return onlyNumbers();" onkeyup ="return addABNumbers();" />
  <input type="hidden" id="finalABNumber" value=""  onkeyup="return onlyNumbers();" />
  </div>

  <script language="javascript" type="text/javascript">
    function addABNumbers() {
        var finalabNumber = document.getElementById("ab1").value + document.getElementById("ab2").value +
                                                     document.getElementById("ab3").value +
                                                     document.getElementById("ab4").value +
                                                     document.getElementById("ab5").value +
                                                    document.getElementById("ab6").value +
                                                    document.getElementById("ab7").value +
                                                    document.getElementById("ab8").value +
                                                    document.getElementById("ab9").value;

        alert(finalabNumber);
        document.getElementById('finalABNumber').value = finalabNumber;
    } function onlyNumbers() {
      //  debugger;
        var chek=true;
        //var finalNumber = document.getElementById('finalAcntNumber').value;
        //document.getElementById("finalAcntNumber").value =
        var finalNumber =
                                                     document.getElementById("ac1").value +
                                                     document.getElementById("ac2").value +
                                                     document.getElementById("ac3").value +
                                                     document.getElementById("ac4").value +
                                                     document.getElementById("ac5").value +
                                                    document.getElementById("ac6").value +
                                                    document.getElementById("ac7").value +
                                                    document.getElementById("ac8").value +
                                                    document.getElementById("ac9").value +
                                                    document.getElementById("ac10").value +
                                                    document.getElementById("ac11").value +
                                                    document.getElementById("ac12").value +
                                                    document.getElementById("ac13").value +
                                                    document.getElementById("ac14").value +
                                                    document.getElementById("ac15").value+
                                                    document.getElementById("ac16").value;
       // debugger;
        var test = document.getElementById("ac1").value;

       // chek = IsNumeric(document.getElementById("ac1").value);
       //            alert(chek);
       //            if (finalNumber.length < 15 )
       //            if(chek=false)
       //                alert('not a valid');
       //            alert(finalNumber);
        var e = event || evt; // for trans-browser compatibility
        var charCode = e.which || e.keyCode;

        if (charCode > 31 && (charCode < 48 || charCode > 57)) {
            return false;
        }
        else if (isNaN(document.getElementById('finalAcntNumber').value)) {
            alert('not a valid');
        }
        else {
           // debugger;
        //                if (test != "") {
        //                    alert(finalNumber);
                document.getElementById("Text1").value = finalNumber;
          //  }
            return true;
        }
       //   if (!isNaN(document.getElementById("finalAcntNumber").value))

      }
    </script>
</code>```

答:
I figured out the answer on my own and  the correct answer as per my requirement  is  as follows </p>

```<code><script>
function validation {
    var input = $("#someTextBox").val();

    if (!isNaN(input)) {
        var values = {
            input.charAt(0) * 3,
            input.charAt(1) * 7,
            input.charAt(2) * 1,
            input.charAt(3) * 3,
            input.charAt(4) * 7,
            input.charAt(5) * 1,
            input.charAt(6) * 3,
            input.charAt(7) * 7,
        }

        var sum = 0;

        for (int i = 0; i < values.length; i ++) {
            sum += values[i];
        }

       var modTen = parseInt(sum / 10);
                    var result = (modTen + 1) * 10;

                    var finalResult = result - sum;
                    if (finalResult == (input.charAt(8)))
                        alert("Valid ABA Number.");
                    else
                        alert("Error");

}
</script>
</code>```

Body:
What will be the Javascript or JQuery code for following scenario ?

"A ABA  TextBox=Mandatory field".

Must be numeric and 9 digits. Perform MOD 10 algorithm

Multiply each digit of the first 8 digits of the ABA/Routing number with the following numbers respectively.
a. 3,7,1,3,7,1,3,7

Add the results of the 8 multiplications.

Subtract the sum from the next highest multiple of 10.

The result of the above step 3 must be equal to the 9th digit of the ABA/Routing number. If not display error in Message section

I have 9 different textboxes for each digit of ABA number . First I have to check if the entered number is numeric or not then I have to add this valid number in a String Array onwhich finally i will be adding my ABA Number validation .

I am absolutely stuck . Dont know how to solve this thing . I have found few codes but which doesnt qualify my need

EDIT :This is my HTML Code  OnKeyUp Event I am adding value of perticular textbox in a string Array and OnKeyPress I am checking if the entered number is numeric or not

  <input type="text" maxlength="1" size="10px" style="width:15px" id="ab1" onkeypress ="return onlyNumbers();" onkeyup ="return addABNumbers();"  />
  <input type="text" maxlength="1" size="10px" style="width:15px" id="ab2" onkeypress ="return onlyNumbers();" onkeyup ="return addABNumbers();" />
  <input type="text" maxlength="1" size="10px" style="width:15px" id="ab3" onkeypress ="return onlyNumbers();" onkeyup ="return addABNumbers();" />
  <input type="text" maxlength="1" size="10px" style="width:15px" id="ab4" onkeypress ="return onlyNumbers();" onkeyup ="return addABNumbers();" />
  <input type="text" maxlength="1" size="10px" style="width:15px" id="ab5" onkeypress ="return onlyNumbers();" onkeyup ="return addABNumbers();"  />
  <input type="text" maxlength="1" size="10px" style="width:15px" id="ab6" onkeypress ="return onlyNumbers();" onkeyup ="return addABNumbers();" />
  <input type="text" maxlength="1"  size="10px" style="width:15px" id="ab7" onkeypress ="return onlyNumbers();" onkeyup ="return addABNumbers();" />
  <input type="text" maxlength="1" size="10px" style="width:15px" id="ab8" onkeypress ="return onlyNumbers();" onkeyup ="return addABNumbers();" />
  <input type="text" maxlength="1" size="10px" style="width:15px" id="ab9" onkeypress ="return onlyNumbers();" onkeyup ="return addABNumbers();" />
  <input type="hidden" id="finalABNumber" value=""  onkeyup="return onlyNumbers();" />

Body:
I figured out the answer on my own and  the correct answer as per my requirement  is  as follows

<script>
function validation {
    var input = $("#someTextBox").val();

    if (!isNaN(input)) {
        var values = {
            input.charAt(0) * 3,
            input.charAt(1) * 7,
            input.charAt(2) * 1,
            input.charAt(3) * 3,
            input.charAt(4) * 7,
            input.charAt(5) * 1,
            input.charAt(6) * 3,
            input.charAt(7) * 7,
        }

        var sum = 0;

        for (int i = 0; i < values.length; i ++) {
            sum += values[i];
        }

       var modTen = parseInt(sum / 10);
                    var result = (modTen + 1) * 10;

                    var finalResult = result - sum;
                    if (finalResult == (input.charAt(8)))
                        alert("Valid ABA Number.");
                    else
                        alert("Error");

}
</script>


问:
How to re-transform XSTL to XSLT with additional tags added
I am new to the XSLT 1.0, where i have the below XML which we are passing into XSLT to generate the PDF.

XML:

```<code><Family>
     <Description>General psychiatry</Description>
</Family>

<Family>
    <Description>Liaison Psychiatry</Description>
    <Parent>General psychiatry</Parent>
</Family>

 <Family>
    <Description>Old age psychiatry</Description>
</Family>

<Family>
    <Description>General psychiatry</Description>
</Family>

<Family>
     <Description>Liaison</Description>
     <Parent>General psychiatry</Parent>
</Family>
</code>```

Case 1:
The first-Family-tag holds the parent name(Description) and in the second-Family-tag will hold the child name(Decription) and the parent name(Parent).

Case 2:
Will have only first-Family-tag holds the parent name(Description) but there will no second-Family-tag.

Now i need to group the above based on the Parent- Child/Children's, i thought of using THE MUENCHIAN METHOD but this need all the Family-tag should have the same sub-tags under it and i can't change the XML format as well.

Any suggestion to overcome the above 2 cased and group based on the Family-tag is most appreciated.
Thanks

答:
In XSLT 2.0 you can use for-each-group

```<code><xsl:template match="root">
        <xsl:copy>
            <xsl:for-each-group select="//Family[count(*) = 1][Description]" group-by=".">
                <xsl:copy>
                    <xsl:copy-of select="Description"/>
                    <xsl:if test="//Family[Parent = current-group()[1]/Description]">
                        <SubFamily>
                            <xsl:for-each select="//Family[Parent = current-group()[1]/Description]">
                                <xsl:copy-of select="Description"/>
                            </xsl:for-each>
                        </SubFamily>
                    </xsl:if>
                </xsl:copy>
            </xsl:for-each-group>
        </xsl:copy>
    </xsl:template>
</code>```

See Transformation at https://xsltfiddle.liberty-development.net/3NSTbfe

In XSLT 1.0 using MUENCHIAN METHOD

```<code><xsl:key name="parent" match="Family" use="Description"/>

        <xsl:key name="child" match="Family" use="Parent"/>

        <xsl:template match="root">
            <xsl:copy>
                <xsl:for-each select="Family[not(Parent)][generate-id() = generate-id(key('parent', Description)[1])]">
                    <xsl:copy>
                        <xsl:copy-of select="Description"/>
                        <xsl:if test="//Family[Parent = current()/Description]">
                            <SubFamily>
                                <xsl:for-each select="//Family[Parent = current()/Description]">
                                    <xsl:copy-of select="Description"/>
                                </xsl:for-each>
                            </SubFamily>
                        </xsl:if>
                    </xsl:copy>
                </xsl:for-each>
            </xsl:copy>
        </xsl:template>
</code>```

See Transformation at https://xsltfiddle.liberty-development.net/3NSTbfe/1

Body:
I am new to the XSLT 1.0, where i have the below XML which we are passing into XSLT to generate the PDF.

XML:

<Family>
     <Description>General psychiatry</Description>
</Family>

<Family>
    <Description>Liaison Psychiatry</Description>
    <Parent>General psychiatry</Parent>
</Family>

 <Family>
    <Description>Old age psychiatry</Description>
</Family>

<Family>
    <Description>General psychiatry</Description>
</Family>

<Family>
     <Description>Liaison</Description>
     <Parent>General psychiatry</Parent>
</Family>

Case 1:
The first-Family-tag holds the parent name(Description) and in the second-Family-tag will hold the child name(Decription) and the parent name(Parent).

Case 2:
Will have only first-Family-tag holds the parent name(Description) but there will no second-Family-tag.

Now i need to group the above based on the Parent- Child/Children's, i thought of using THE MUENCHIAN METHOD but this need all the Family-tag should have the same sub-tags under it and i can't change the XML format as well.

Any suggestion to overcome the above 2 cased and group based on the Family-tag is most appreciated.
Thanks

Body:
In XSLT 2.0 you can use for-each-group

<xsl:template match="root">
        <xsl:copy>
            <xsl:for-each-group select="//Family[count(*) = 1][Description]" group-by=".">
                <xsl:copy>
                    <xsl:copy-of select="Description"/>
                    <xsl:if test="//Family[Parent = current-group()[1]/Description]">
                        <SubFamily>
                            <xsl:for-each select="//Family[Parent = current-group()[1]/Description]">
                                <xsl:copy-of select="Description"/>
                            </xsl:for-each>
                        </SubFamily>
                    </xsl:if>
                </xsl:copy>
            </xsl:for-each-group>
        </xsl:copy>
    </xsl:template>

See Transformation at https://xsltfiddle.liberty-development.net/3NSTbfe

In XSLT 1.0 using MUENCHIAN METHOD

<xsl:key name="parent" match="Family" use="Description"/>

        <xsl:key name="child" match="Family" use="Parent"/>

        <xsl:template match="root">
            <xsl:copy>
                <xsl:for-each select="Family[not(Parent)][generate-id() = generate-id(key('parent', Description)[1])]">
                    <xsl:copy>
                        <xsl:copy-of select="Description"/>
                        <xsl:if test="//Family[Parent = current()/Description]">
                            <SubFamily>
                                <xsl:for-each select="//Family[Parent = current()/Description]">
                                    <xsl:copy-of select="Description"/>
                                </xsl:for-each>
                            </SubFamily>
                        </xsl:if>
                    </xsl:copy>
                </xsl:for-each>
            </xsl:copy>
        </xsl:template>

See Transformation at https://xsltfiddle.liberty-development.net/3NSTbfe/1


问:
Draw circle of certain radius on map view in Android
I want to draw a circle on map view. I want the user to input the radius and for that radius I have to show circle on map. After that I have to display markers on some locations on that circle.

I know how to display markers on on  map view.

How can I draw circle on map view  and to show markers on that circle boundary.

答:
In the implementation of the ItemizedOverlay, do something like the method drawCircle from the onDraw method

```<code>protected void drawCircle(Canvas canvas, Point curScreenCoords) {
    curScreenCoords = toScreenPoint(curScreenCoords);
    int CIRCLE_RADIUS = 50;
    // Draw inner info window
    canvas.drawCircle((float) curScreenCoords.x, (float) curScreenCoords.y, CIRCLE_RADIUS, getInnerPaint());
    // if needed, draw a border for info window
    canvas.drawCircle(curScreenCoords.x, curScreenCoordsy, CIRCLE_RADIUS, getBorderPaint());
}

private Paint innerPaint, borderPaint;

public Paint getInnerPaint() {
    if (innerPaint == null) {
        innerPaint = new Paint();
        innerPaint.setARGB(225, 68, 89, 82); // gray
        innerPaint.setAntiAlias(true);
    }
    return innerPaint;
}

public Paint getBorderPaint() {
    if (borderPaint == null) {
        borderPaint = new Paint();
        borderPaint.setARGB(255, 68, 89, 82);
        borderPaint.setAntiAlias(true);
        borderPaint.setStyle(Style.STROKE);
        borderPaint.setStrokeWidth(2);
    }
    return borderPaint;
}

@Override
protected void onDraw(Canvas canvas) {
    Point p = new Point();
    for(OverlayItem item : items) {
        drawCircle(canvas, getProjection().toPixels(item.getPoint(), p));
    }
}
</code>```

Body:
In the implementation of the ItemizedOverlay, do something like the method drawCircle from the onDraw method

protected void drawCircle(Canvas canvas, Point curScreenCoords) {
    curScreenCoords = toScreenPoint(curScreenCoords);
    int CIRCLE_RADIUS = 50;
    // Draw inner info window
    canvas.drawCircle((float) curScreenCoords.x, (float) curScreenCoords.y, CIRCLE_RADIUS, getInnerPaint());
    // if needed, draw a border for info window
    canvas.drawCircle(curScreenCoords.x, curScreenCoordsy, CIRCLE_RADIUS, getBorderPaint());
}

private Paint innerPaint, borderPaint;

public Paint getInnerPaint() {
    if (innerPaint == null) {
        innerPaint = new Paint();
        innerPaint.setARGB(225, 68, 89, 82); // gray
        innerPaint.setAntiAlias(true);
    }
    return innerPaint;
}

public Paint getBorderPaint() {
    if (borderPaint == null) {
        borderPaint = new Paint();
        borderPaint.setARGB(255, 68, 89, 82);
        borderPaint.setAntiAlias(true);
        borderPaint.setStyle(Style.STROKE);
        borderPaint.setStrokeWidth(2);
    }
    return borderPaint;
}

@Override
protected void onDraw(Canvas canvas) {
    Point p = new Point();
    for(OverlayItem item : items) {
        drawCircle(canvas, getProjection().toPixels(item.getPoint(), p));
    }
}


问:
How to suppress matplotlib inline for a single cell in Jupyter Notebooks/Lab?
I was looking at matplotlib python inline on/off and this kind of solves the problem but when I do plt.ion() all of the Figures pop up (100s of figures).  I want to keep them suppressed in a single cell.  Is there a with loop I can use to turn off %matplotlib inline or is this impossible?

答: Figures closed before the end of the cell will not be shown. Calling plt.close("all") at the end of the cell will close all figures and none will be displayed in the cell's output.


Title: From two dates and frequency get daterange list

Body:
I have two dates:

'1990-01-01'

'2020-02-18'

I would want to convert them in a date range list of as maximum, 25 years:

[ ['1990-01-01', '2015-01-01'], ['2015-01-01', '2020-02-18'] ]

Or as maximun, 5 years:

[ ['1990-01-01', 1995-01-01'], [1995-01-01', '2000-01-01'], ['2000-01-01', '2005-01-01'], ['2005-01-01', '2010-01-01'], ['2010-01-01', '2015-01-01'], ['2015-01-01', '2020-01-01'], ['2020-01-01', '2020-02-18'] ]

I tried with pandas.interval_range with no success.

Body:
You can use pd.date_range. Since the spacing between the generated dates must be of 5 years, you'll have to add the end date yourself, then create the intervals from the generated dates:

start = '1990-01-01'
end = '2020-02-18'

s = pd.date_range(start, end, freq='5YS').append(pd.DatetimeIndex([end]))

print(s)
DatetimeIndex(['1990-01-01', '1995-01-01', '2000-01-01', '2005-01-01',
               '2010-01-01', '2015-01-01', '2020-01-01', '2020-02-18'],
          dtype='datetime64[ns]', freq=None)

Then use zip to create the interval:

list(zip(s[:-1], s[1:]))

[(Timestamp('1990-01-01 00:00:00'), Timestamp('1995-01-01 00:00:00')),
 (Timestamp('1995-01-01 00:00:00'), Timestamp('2000-01-01 00:00:00')),
 (Timestamp('2000-01-01 00:00:00'), Timestamp('2005-01-01 00:00:00')),
 (Timestamp('2005-01-01 00:00:00'), Timestamp('2010-01-01 00:00:00')),
 (Timestamp('2010-01-01 00:00:00'), Timestamp('2015-01-01 00:00:00')),
 (Timestamp('2015-01-01 00:00:00'), Timestamp('2020-01-01 00:00:00')),
 (Timestamp('2020-01-01 00:00:00'), Timestamp('2020-02-18 00:00:00'))]


问:
Generate 8 digit OTP in java
Generate 8 digit OTP in java with first digit as zero.
I have tried with Math() function in Java but it gives random numbers first digit without zero.
Suggest me an easiest way to achieve the same

答:
```<code>static final LENGHT = 8;

Random randomizer = new Random();
StringBuilder builder = new StringBuilder();
for(i = 0; i <= LENGHT; i++) {
   builder.append(randomizer.nextInt(10));
}

String otp = builder.toString();
</code>```

EDIT

As Smile mentioned, using SecureRandom would be better choice.

```<code>static final LENGHT = 8;

SecureRandom randomizer = new SecureRandom();
StringBuilder builder = new StringBuilder();
for(i = 0; i <= LENGHT; i++) {
   builder.append(randomizer.nextInt(10));
}

String otp = builder.toString();
</code>```

If you want first digit as zero always;

```<code>static final LENGHT = 7;

SecureRandom randomizer = new SecureRandom();
StringBuilder builder = new StringBuilder("0");
for(i = 0; i <= LENGHT; i++) {
   builder.append(randomizer.nextInt(10));
}

String otp = builder.toString();
</code>```

Title: Generate 8 digit OTP in java

Body:
static final LENGHT = 8;

Random randomizer = new Random();
StringBuilder builder = new StringBuilder();
for(i = 0; i <= LENGHT; i++) {
   builder.append(randomizer.nextInt(10));
}

String otp = builder.toString();

EDIT

As Smile mentioned, using SecureRandom would be better choice.

static final LENGHT = 8;

SecureRandom randomizer = new SecureRandom();
StringBuilder builder = new StringBuilder();
for(i = 0; i <= LENGHT; i++) {
   builder.append(randomizer.nextInt(10));
}

String otp = builder.toString();

If you want first digit as zero always;

static final LENGHT = 7;

SecureRandom randomizer = new SecureRandom();
StringBuilder builder = new StringBuilder("0");
for(i = 0; i <= LENGHT; i++) {
   builder.append(randomizer.nextInt(10));
}

String otp = builder.toString();


问:
MySQL Group by aggregate functions
Sorry if i sound total newbie but i know im one step away from solving this problem.
Is there any way that i can GROUP BY the number_of_trans? i would like to know how many users have the same number of transaction, grouped by the number of transaction. my query is like this:

```<code>SELECT
  cust_id, COUNT(*) AS number_of_trans
FROM
  table
GROUP BY
  cust_id
HAVING COUNT(*) > 1
ORDER BY
  number_of_trans
</code>```

the result im getting is like this

```<code>+------------------+--------------+
| cust_id          | numb_of_trans|
+------------------+--------------+
| 01               |  2           |
| 02               |  3           |
| 03               |  3           |
| 04               |  4           |
| 05               |  4           |
+------------------+--------------+
</code>```

while im expecting a result like this:

```<code>+------------------+--------------+
| numb_of_trans    | count        |
+------------------+--------------+
| 1                |  null        |
| 2                |  1           |
| 3                |  2           |
| 4                |  2           |
| 5                |  null        |
+------------------+--------------+
</code>```

答:
You could left join your current aggregate query with a list of numbers, and aggregate once more:

```<code>select
    n.number_of_trans,
    count(*) cnt
from (
    select 1 number_of_trans
    union all select 2
    union all select 3
    union all select 4
    union all select 5
) n
left join (
    select count(*) as number_of_trans
    from mytable
    group by cust_id
    -- having count(*) > 1
) t on t.number_of_trans = n.number_of_trans
group by n.number_of_trans
order by n.number_of_trans
</code>```

You can expand the union all subquery with more numbers if needed.

I am unsure that you do want a having clause in the aggregate query that filters out cust_ids that have just one entry, so I commented it - feel free to uncomment it as needed.

Also please note that this will yield 0 instead of null for number_of_trans that do not exist in the aggregate subquery. If you really want null, then you can do:

```<code>nullif(count(*), 0) cnt
</code>```

Title: MySQL Group by aggregate functions

Body:
Sorry if i sound total newbie but i know im one step away from solving this problem.
Is there any way that i can GROUP BY the number_of_trans? i would like to know how many users have the same number of transaction, grouped by the number of transaction. my query is like this:

SELECT
  cust_id, COUNT(*) AS number_of_trans
FROM
  table
GROUP BY
  cust_id
HAVING COUNT(*) > 1
ORDER BY
  number_of_trans

the result im getting is like this

+------------------+--------------+
| cust_id          | numb_of_trans|
+------------------+--------------+
| 01               |  2           |
| 02               |  3           |
| 03               |  3           |
| 04               |  4           |
| 05               |  4           |
+------------------+--------------+

while im expecting a result like this:

+------------------+--------------+
| numb_of_trans    | count        |
+------------------+--------------+
| 1                |  null        |
| 2                |  1           |
| 3                |  2           |
| 4                |  2           |
| 5                |  null        |
+------------------+--------------+

Body:
You could left join your current aggregate query with a list of numbers, and aggregate once more:

select
    n.number_of_trans,
    count(*) cnt
from (
    select 1 number_of_trans
    union all select 2
    union all select 3
    union all select 4
    union all select 5
) n
left join (
    select count(*) as number_of_trans
    from mytable
    group by cust_id
    -- having count(*) > 1
) t on t.number_of_trans = n.number_of_trans
group by n.number_of_trans
order by n.number_of_trans

You can expand the union all subquery with more numbers if needed.

I am unsure that you do want a having clause in the aggregate query that filters out cust_ids that have just one entry, so I commented it - feel free to uncomment it as needed.

Also please note that this will yield 0 instead of null for number_of_trans that do not exist in the aggregate subquery. If you really want null, then you can do:

nullif(count(*), 0) cnt


问:
Google Mock and override keyword
Is there a macro in Google Mock to ensure compile time check of the signature of f() by appending the override keyword to the macro substitution:

```<code>struct I
{
    virtual void f() = 0;
};

struct MockI
{
    MOCK_METHOD0(f, void()); // this will define another function if f signature changes
                             // leading to weird runtime test failures
};
</code>```

答:
You need to upgrade your GoogleMock to 1.10.x version to do that (unless you want to modify the library yourself).

1.10 version has new macro MOCK_METHOD which can use any function specifier (const, noexcept, override, final, ...)

MOCK_METHOD macro usage:

```<code>struct MockI: public I
{
    MOCK_METHOD(void, f, (), (override));
};
</code>```

Old macros MOCK_METHODx can still be used, but one should prefer to write new mocks using new method when using 1.10.x

Title: Google Mock and override keyword

Body:
Is there a macro in Google Mock to ensure compile time check of the signature of f() by appending the override keyword to the macro substitution:

struct I
{
    virtual void f() = 0;
};

struct MockI
{
    MOCK_METHOD0(f, void()); // this will define another function if f signature changes
                             // leading to weird runtime test failures
};

Body:
You need to upgrade your GoogleMock to 1.10.x version to do that (unless you want to modify the library yourself).

1.10 version has new macro MOCK_METHOD which can use any function specifier (const, noexcept, override, final, ...)

MOCK_METHOD macro usage:

struct MockI: public I
{
    MOCK_METHOD(void, f, (), (override));
};

Old macros MOCK_METHODx can still be used, but one should prefer to write new mocks using new method when using 1.10.x


问:
Laravel attribute accessor capital letter is ignored
I am using Lumen framework. I have one problem, I need to set custom accessor for attribute, but the problem is that column in database starts with capital letter.

For example Logo.And in case of first capital letter, accessor is not called while retrieving object, I have tried with several columns, columns with name starts from small letter works perfectly.

```<code> public function getLogoAttribute($value)
</code>```

This accessor doesn't work ,because name of column is Logo

I cannot change the name of columns in the database, but need to use accessors in my application.

I understand that I can change sources of Eloquent framework, but maybe there any other way to get it working.

Thanks.

答:
I did like this</p>

```<code>protected $appends = ['image'];
public function getImageAttribute(){
      $img = null;
      $value = $this->attributes['Image'];
      if ($value) {
          if (strpos($value, 'baseurl') !== false) {
              $img = $value;
          } else {
              $img = 'prefixurl' . $value;
          }
      }
      return $img;
   }
</code>```

Body:
I am using Lumen framework. I have one problem, I need to set custom accessor for attribute, but the problem is that column in database starts with capital letter.

For example Logo.And in case of first capital letter, accessor is not called while retrieving object, I have tried with several columns, columns with name starts from small letter works perfectly.

 public function getLogoAttribute($value)

This accessor doesn't work ,because name of column is Logo

I cannot change the name of columns in the database, but need to use accessors in my application.

I understand that I can change sources of Eloquent framework, but maybe there any other way to get it working.

Thanks.

Body:
I did like this

protected $appends = ['image'];
public function getImageAttribute(){
      $img = null;
      $value = $this->attributes['Image'];
      if ($value) {
          if (strpos($value, 'baseurl') !== false) {
              $img = $value;
          } else {
              $img = 'prefixurl' . $value;
          }
      }
      return $img;
   }


问:
Adjust div height to div parent's
I'm designing a nav panel and I need to adjust the different option's styles to the parent div. For example, I need to adjust the background color of the options to the parent div (Paint the color in the full height of the parent div).

This is the code:

```<code><div class="text-center text-muted"> <div class="container">
 <div class="card">
  <div class="card-header" style="background-color: #e9ecef;">
   <div class="row mt8" id="nav_panel">
    <div class="col-md-2" id="nav_panel_monday" style="background-color: rgb(0, 160, 157);">
    <a id="nav_href_monday" href="#" style="color: white;">Monday</a>
   </div>
   <div class="col-md-2" id="nav_panel_tuesday">
    <a id="nav_href_tuesday" href="#">Tuesday</a>
   </div>
   <div class="col-md-2" id="nav_panel_wednesday">
    <a id="nav_href_wednesday" href="#">Wednesday</a>
   </div>
   <div class="col-md-2" id="nav_panel_thursday">
    <a id="nav_href_thursday" href="#">Thursday</a>
   </div>
   <div class="col-md-2" id="nav_panel_friday">
    <a id="nav_href_friday" href="#">Friday</a>
   </div>
  </div>
 </div>
 <div class="card-body">
  <div id="div_hidden_monday"></div>
  <div id="div_hidden_tuesday" style="display: none;"></div>
  <div id="div_hidden_wednesday" style="display: none;"></div>
  <div id="div_hidden_thursday" style="display: none;"></div>
  <div id="div_hidden_friday" style="display: none;"></div>
 </div>
 </div>
</div>
</div>
</code>```

```<code>.container {
    width: 100%;
    padding-right: 0;
    padding-left: 0;
    margin-right: auto;
    margin-left: auto;
}
.card {
    position: relative;
    display: flex;
    -webkit-box-orient: vertical;
    -webkit-box-direction: normal;
    flex-direction: column;
    min-width: 0;
    word-wrap: break-word;
    background-color: #FFFFFF;
    background-clip: border-box;
    border: 1px solid rgba(0, 0, 0, 0.125);
    border-radius: 0.25rem;
}
.card-header {
    padding: 0.75rem 1.25rem;
    margin-bottom: 0;
    border-bottom: 1px solid rgba(0, 0, 0, 0.125);
}
#nav_panel {
    background-color: #e9ecef;
    padding-right: 0;
    padding-left: 0;
    border-radius: 5px;
}
.col-md-2 {
    position: relative;
    width: 100%;
    min-height: 1px;
    padding-right: 15px;
    padding-left: 15px;
}
</code>```

Any suggestion? Thanks for reading!

答:
For the time being using padding and margin issue is fixed but You
  need to re-right the nav HTML structure using nav and ul li
  like here

.container {
  width: 100%;
  padding-right: 0;
  padding-left: 0;
  margin-right: auto;
  margin-left: auto;
}

.card {
  position: relative;
  display: flex;
  -webkit-box-orient: vertical;
  -webkit-box-direction: normal;
  flex-direction: column;
  min-width: 0;
  word-wrap: break-word;
  background-color: #FFFFFF;
  background-clip: border-box;
  border: 1px solid rgba(0, 0, 0, 0.125);
  border-radius: 0.25rem;
}

.card-header {
  padding: 0 15px !important;
  margin-bottom: 0;
  background-color: rgba(0, 0, 0, .03);
  border-bottom: 1px solid rgba(0, 0, 0, .125);
}

.card-header a {
  display: block;
  padding: 10px 0;
}

#nav_panel {
  background-color: #e9ecef;
  padding-right: 0;
  padding-left: 0;
  border-radius: 5px;
}

.col-md-2 {
  position: relative;
  width: 100%;
  min-height: 1px;
  padding-right: 15px;
  padding-left: 15px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script>
<div class="text-center text-muted">
  <div class="container">
    <div class="card">
      <div class="card-header" style="background-color: #e9ecef;">
        <div class="row mt8" id="nav_panel">
          <div class="col-md-2" id="nav_panel_monday" style="background-color: rgb(0, 160, 157);">
            Monday
          </div>
          <div class="col-md-2" id="nav_panel_tuesday">
            Tuesday
          </div>
          <div class="col-md-2" id="nav_panel_wednesday">
            Wednesday
          </div>
          <div class="col-md-2" id="nav_panel_thursday">
            Thursday
          </div>
          <div class="col-md-2" id="nav_panel_friday">
            Friday
          </div>
        </div>
      </div>
      <div class="card-body">
        <div id="div_hidden_monday"></div>
        <div id="div_hidden_tuesday" style="display: none;"></div>
        <div id="div_hidden_wednesday" style="display: none;"></div>
        <div id="div_hidden_thursday" style="display: none;"></div>
        <div id="div_hidden_friday" style="display: none;"></div>
      </div>
    </div>
  </div>
</div></code>```

Title: Adjust div height to div parent's

Body:
I'm designing a nav panel and I need to adjust the different option's styles to the parent div. For example, I need to adjust the background color of the options to the parent div (Paint the color in the full height of the parent div).

This is the code:

    Monday

    Tuesday

    Wednesday

    Thursday

    Friday

.container {
    width: 100%;
    padding-right: 0;
    padding-left: 0;
    margin-right: auto;
    margin-left: auto;
}
.card {
    position: relative;
    display: flex;
    -webkit-box-orient: vertical;
    -webkit-box-direction: normal;
    flex-direction: column;
    min-width: 0;
    word-wrap: break-word;
    background-color: #FFFFFF;
    background-clip: border-box;
    border: 1px solid rgba(0, 0, 0, 0.125);
    border-radius: 0.25rem;
}
.card-header {
    padding: 0.75rem 1.25rem;
    margin-bottom: 0;
    border-bottom: 1px solid rgba(0, 0, 0, 0.125);
}
#nav_panel {
    background-color: #e9ecef;
    padding-right: 0;
    padding-left: 0;
    border-radius: 5px;
}
.col-md-2 {
    position: relative;
    width: 100%;
    min-height: 1px;
    padding-right: 15px;
    padding-left: 15px;
}

Any suggestion? Thanks for reading!

Body:
For the time being using padding and margin issue is fixed but You
  need to re-right the nav HTML structure using nav and ul li
  like here

.container {
  width: 100%;
  padding-right: 0;
  padding-left: 0;
  margin-right: auto;
  margin-left: auto;
}

.card {
  position: relative;
  display: flex;
  -webkit-box-orient: vertical;
  -webkit-box-direction: normal;
  flex-direction: column;
  min-width: 0;
  word-wrap: break-word;
  background-color: #FFFFFF;
  background-clip: border-box;
  border: 1px solid rgba(0, 0, 0, 0.125);
  border-radius: 0.25rem;
}

.card-header {
  padding: 0 15px !important;
  margin-bottom: 0;
  background-color: rgba(0, 0, 0, .03);
  border-bottom: 1px solid rgba(0, 0, 0, .125);
}

.card-header a {
  display: block;
  padding: 10px 0;
}

#nav_panel {
  background-color: #e9ecef;
  padding-right: 0;
  padding-left: 0;
  border-radius: 5px;
}

.col-md-2 {
  position: relative;
  width: 100%;
  min-height: 1px;
  padding-right: 15px;
  padding-left: 15px;
}

<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script>
<div class="text-center text-muted">
  <div class="container">
    <div class="card">
      <div class="card-header" style="background-color: #e9ecef;">
        <div class="row mt8" id="nav_panel">
          <div class="col-md-2" id="nav_panel_monday" style="background-color: rgb(0, 160, 157);">
            <a id="nav_href_monday" href="#" style="color: white;">Monday</a>
          </div>
          <div class="col-md-2" id="nav_panel_tuesday">
            <a id="nav_href_tuesday" href="#">Tuesday</a>
          </div>
          <div class="col-md-2" id="nav_panel_wednesday">
            <a id="nav_href_wednesday" href="#">Wednesday</a>
          </div>
          <div class="col-md-2" id="nav_panel_thursday">
            <a id="nav_href_thursday" href="#">Thursday</a>
          </div>
          <div class="col-md-2" id="nav_panel_friday">
            <a id="nav_href_friday" href="#">Friday</a>
          </div>
        </div>
      </div>
      <div class="card-body">
        <div id="div_hidden_monday"></div>
        <div id="div_hidden_tuesday" style="display: none;"></div>
        <div id="div_hidden_wednesday" style="display: none;"></div>
        <div id="div_hidden_thursday" style="display: none;"></div>
        <div id="div_hidden_friday" style="display: none;"></div>
      </div>
    </div>
  </div>
</div>