问:
How to get average of last N numbers in a stream with static memory
I have a stream of numbers and in every cycle I need to count the average of last N of them. This can be, of course, solved using an array where I store the last N numbers and in every cycle I shift it, add the new one and count the average.

```<code>N = 3

+---+-----+
| a | avg |
+---+-----+
| 1 |     |
| 2 |     |
| 3 | 2.0 |
| 4 | 3.0 |
| 3 | 3.3 |
| 3 | 3.3 |
| 5 | 3.7 |
| 4 | 4.0 |
| 5 | 4.7 |
+---+-----+
</code>```

First N numbers (where there "isn't enough data for counting the average") doesn't interest me much, so the results there may be anything/undefined.

My question is, can this be done without using an array, that is, with static amount of memory? If so, then how?

I'll do the coding myself - I just need to know the theory.

Thanks

答:
Think of this as a black box containing some state. If you control the input stream, you can draw conclusions on the state. In your sliding window array-based approach, it is kind of obvious that if you feed a bunch of zeros into the algorithm after the original input, you get a bunch of averages with a decreasing number of non-zero values taken into account. The last one has just one original non-zero value, so if you multiply that my N you get the last input back. Using that and the second-to-last output which accounts for two non-zero inputs, you can reconstruct the second-to-last input, and so on.

So essentially your algorithm needs to maintain sufficient state to reconstruct the last N elements of input, at least if you formulate it as an on-line algorithm. I don't think an off-line algorithm can do any better, except if you consider it reading the input multiple times, but I don't have as strong an agument for that.

Of course, in some theoretical models you can avoid the array and e.g. encode all the state into a single arbitrary length integer, but that's just cheating the theory, and doesn't make any difference in practice.

Body:
I have a stream of numbers and in every cycle I need to count the average of last N of them. This can be, of course, solved using an array where I store the last N numbers and in every cycle I shift it, add the new one and count the average.

N = 3

+---+-----+
| a | avg |
+---+-----+
| 1 |     |
| 2 |     |
| 3 | 2.0 |
| 4 | 3.0 |
| 3 | 3.3 |
| 3 | 3.3 |
| 5 | 3.7 |
| 4 | 4.0 |
| 5 | 4.7 |
+---+-----+

First N numbers (where there "isn't enough data for counting the average") doesn't interest me much, so the results there may be anything/undefined.

My question is, can this be done without using an array, that is, with static amount of memory? If so, then how?

I'll do the coding myself - I just need to know the theory.

Thanks


来源: stackexchange

问:
matplotlib legend performance issue
I am using Jupyter-notebook with python 3.6.2 and matplotlib to plot some data.

When I plot my data, I want to add a legend to the plot (basically to know which line is which)

However calling plt.legend takes a lot of time (almost as much as the plot itself, which to my understanding should just be instant).

Minimal toy problem that reproduces the issue:

```<code>import numpy as np
import matplotlib.pyplot as plt

# Toy useless data (one milion x 4)
my_data = np.random.rand(1000000,4)

plt.plot(my_data)
#plt.legend(['A','C','G','T'])
plt.show()
</code>```

The data here is just random and useless, but it reproduces my problem:
If I uncomment the plt.legend line, the run takes almost double the time

Why? Shouldn't the legend just look at the plot, see that 4 plots have been made, and draw a box assigning each color to the corresponding string?

Why is a simple legend taking so much time?

Am I missing something?

答:
Replicating the answer by @bnaecker, such that this question is answered:

By default, the legend will be placed in the "best" location, which requires computing how many points from each line are inside a potential legend box. If there are many points, this can take a while. Drawing is much faster when specifying a location other than "best", e.g. plt.legend(loc=3).

ContentLicense: CC BY-SA 3.0

Title: matplotlib legend performance issue

Body:
I am using Jupyter-notebook with python 3.6.2 and matplotlib to plot some data.

When I plot my data, I want to add a legend to the plot (basically to know which line is which)

However calling plt.legend takes a lot of time (almost as much as the plot itself, which to my understanding should just be instant).

Minimal toy problem that reproduces the issue:

import numpy as np
import matplotlib.pyplot as plt

# Toy useless data (one milion x 4)
my_data = np.random.rand(1000000,4)

plt.plot(my_data)
#plt.legend(['A','C','G','T'])
plt.show()

The data here is just random and useless, but it reproduces my problem:
If I uncomment the plt.legend line, the run takes almost double the time

Why? Shouldn't the legend just look at the plot, see that 4 plots have been made, and draw a box assigning each color to the corresponding string?

Why is a simple legend taking so much time?

Am I missing something?


问:
Toggle routeLink in angular 4
I'm creating a web app that will have a side menu loaded from another page in angular 4.
My menu-button with routerLink is defined in here. </p>

```<code><a class="menu-button"routerLink="/menu">
  <div class="menu" >
    <div class="bar" id="bar-1"></div>
    <div class="bar" id="bar-2"></div>
    <div class="bar" id="bar-3"></div>
  </div>
</a>
</code>```

<p>The navbar will be visible even when the menu is open, and I was wondering if there's a way in angular 4 to toggle the routerLink from "/menu" to "/home" when the menu is open. </p>

答:
I just had the need to toggle between routes and the app root route. I added that capability with the following directive:

import { Directive, HostListener, Input, Self } from '@angular/core';
import { RouterLink, Router } from '@angular/router';

/**
 * This directive adds the ability to toggle a route with Angular's
 * {@link RouterLink} directive.
 *
 * ### Example:
 * ```html
 * <button routerLink="/my-path" routerLinkToggle></button>
 * ```
 * The example above creates a toggle button that navigates between
 * `http://localhost/my-path` and `http://localhost`.
 */
@Directive({
    selector: '[routerLinkToggle]'
})
export class RouterLinkToggleDirective {

    /**
     * The {@link RouterLink.onClick} method.
     */
    private readonly _onClick: () => boolean;

    /**
     * Navigation commands.
     */
    private commands: any[] = [];

    constructor(@Self() private routerLink: RouterLink,
        private router: Router) {

        // Keep a reference to the original `routerLink.onClick` method.
        this._onClick = this.routerLink.onClick;

        // Replace the `routerLink.onClick` method with a dummy method.
        // This is needed because the order in which directives on the
        // same host element are executed is undefined. By overwriting
        // routerLink's onClick method but keeping a reference to it, we
        // now have control over when it will be called.
        this.routerLink.onClick = () => true;
    }

    /**
     * Set the path of the route that you want to toggle to. If no path
     * is provided, the directive navigates to the root of the app.
     */
    @Input()
    set routerLinkToggle(commands: any[] | string) {
        if (commands != null) {
            this.commands = Array.isArray(commands) ? commands : [commands];
        } else {
            this.commands = [];
        }
    }

    @HostListener('click')
    onClick() {
        if (this.router.isActive(this.routerLink.urlTree, true)) {
            this.router.navigate(this.commands);

        } else {
            // Call the `_onClick` method within its original `routerLink` conext.
            this._onClick.call(this.routerLink);
        }
    }
}
```

Title: Toggle routeLink in angular 4

Body:
I'm creating a web app that will have a side menu loaded from another page in angular 4.
My menu-button with routerLink is defined in here.

The navbar will be visible even when the menu is open, and I was wondering if there's a way in angular 4 to toggle the routerLink from "/menu" to "/home" when the menu is open.


问:
FacebookCore framework AppEventBuiltin (ambiguous use init)
I have updated my pods and framework but after that when I try to compile, xcode shows this errors in AppEventBuiltin swift (Ambiguous use init)

```<code>maxRatingValue.onSome({ parameters[.maxRatingValue] = NSNumber(value: UInt64($0)) })

itemCount.onSome({ parameters[.itemCount] = NSNumber(value: UInt64($0)) })
</code>```

It's for this:
https://developer.apple.com/documentation/swift/uint64

How can I modify these lines for eliminate the errors?

答:
The error happened becouse of Swift 4 updation. If you are using swift 3, replace with the following code:

```<code>maxRatingValue.onSome({ parameters[.maxRatingValue] = NSNumber(value: $0.toUIntMax()) })

itemCount.onSome({ parameters[.itemCount] = NSNumber(value: $0.toUIntMax()) })
</code>```

Hope this will help you. :)

Body:
I have updated my pods and framework but after that when I try to compile, xcode shows this errors in AppEventBuiltin swift (Ambiguous use init)

maxRatingValue.onSome({ parameters[.maxRatingValue] = NSNumber(value: UInt64($0)) })

itemCount.onSome({ parameters[.itemCount] = NSNumber(value: UInt64($0)) })

It's for this:
https://developer.apple.com/documentation/swift/uint64

How can I modify these lines for eliminate the errors?

Body:
The error happened becouse of Swift 4 updation. If you are using swift 3, replace with the following code:

maxRatingValue.onSome({ parameters[.maxRatingValue] = NSNumber(value: $0.toUIntMax()) })

itemCount.onSome({ parameters[.itemCount] = NSNumber(value: $0.toUIntMax()) })

Hope this will help you. :)


问:
Can't Display HTML context into the Text Area
Hi everyone I have been trying to display HTML context into the TinyMCE text area. When I choose the line for editing first time it displays the data but,  after I choose different row it can't get the context. Any Help would be appreciated. Here are my component and HTML that I have created. I am trying to display context when clicking the edit button.

import { Component, AfterViewInit, OnDestroy, Input, Output, EventEmitter, ElementRef, provide } from 'angular2/core';
import { RdComponent, RdLib } from '../../../../../node_modules/mulberry/core';

declare let tinymce: any;

@Component({
  selector: 'aril-mail-template',
  template: `<textarea contentEditable="true" style="height:30em"><p>{{model}}</p></textarea>`
})

export class MailTemplatesComponent extends RdComponent {

  @Input("rd-model") model;
  @Input("rd-default") default;
  @Input("rd-required") required;
  @Output("mail-template-save") mailTemplateSave: EventEmitter<any> = new EventEmitter<any>();

  editor;
  elementRef: ElementRef;

  constructor(elementRef: ElementRef) {
    super()
    this.elementRef = elementRef;
  }

  ngOnChanges() {
    tinymce.init({
      selector: 'textarea',
      height: "30em",
      menubar: true,
      plugins: [
        'advlist autolink lists link image charmap print preview anchor',
        'searchreplace visualblocks code fullscreen hr',
        'insertdatetime media table contextmenu paste',
        'wordcount'
      ],
      toolbar: 'bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image code',
      table_toolbar: "tableprops cellprops tabledelete | tableinsertrowbefore tableinsertrowafter tabledeleterow | tableinsertcolbefore tableinsertcolafter tabledeletecol",
      powerpaste_allow_local_images: true,
      powerpaste_word_import: 'prompt',
      powerpaste_html_import: 'prompt',
      content_css: [
        '//fonts.googleapis.com/css?family=Lato:300,300i,400,400i',
        '//www.tinymce.com/css/codepen.min.css'],

      setup: editor => {
        this.editor = editor;
        editor.on('init', () => {
          this.model && this.editor.setContent(this.model, { format: 'raw' });
        });
        editor.on('change', () => {
          const content = editor.getContent();
          this.mailTemplateSave.emit(content);
        });
      }
    });
  }

  ngOnDestroy() {
    tinymce.remove(this.editor);
  }

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><rd-service-provider #mailTemplateProvider rd-client-side-paging [rd-service-proxy]="clientSideProxy" [rd-page-size]="25"
  (rd-init)="mailTemplateProvider.call(getMailTemplates())">
</rd-service-provider>
<rd-service-provider #deleteMailTemplateProvider [rd-service-proxy]="serviceProxy" (rd-success)="toastr.info(translate('İşlem Başarıyla Sonlandırıldı')); mailTemplateProvider.call(getMailTemplates())"></rd-service-provider>
<rd-service-provider #saveMailTemplateProvider [rd-service-proxy]="serviceProxy" (rd-success)="toastr.info(translate('Mail Şablonu Başarıyla Oluşturuldu.')); mailTemplateProvider.call(getMailTemplates())"></rd-service-provider>

<div class="row">
  <div class="col-md-4">
    <rd-portlet [rd-text]="translate('Mail Şablonları')" rd-color="green" rd-icon="fa fa-envelope">
      <rd-tools>
        <rd-tool rd-icon="icon-plus" rd-color="white" [rd-tooltip]="translate('Yeni Şablon Ekle')" rd-animate="flash infinite" (rd-click)="data;showMailTemplate=true;console.log(data)"></rd-tool>
        <rd-tool rd-type="refresh" *ngIf="mailTemplateProvider.content.state.serviceCalled"></rd-tool>
        <rd-tool rd-type="collapse" [rd-default-collapse]="false"></rd-tool>
      </rd-tools>

      <rd-body>
        <rd-grid #grid [rd-provider]="mailTemplateProvider" rd-enableSorting="true" [rd-block]="mailTemplateProvider.content.state.waitigForResponse">
          <rd-grid-column [rd-text]="translate('Mail Türü')" rd-key="EmailType">
            <template #item>
              <rd-value rd-type="text" [rd-model]="item.EmailType"></rd-value>
            </template>
          </rd-grid-column>
          <rd-grid-column [rd-text]="translate('Mail Konusu')" rd-key="MailSubject">
            <template #item>
              <rd-value rd-type="text" [rd-model]="item.MailSubject"></rd-value>
            </template>
          </rd-grid-column>
          <rd-grid-column rd-type="operations">
            <template #item>
              <rd-button rd-icon="fa fa-pencil" rd-icon-color="yellow" rd-size="small" [rd-tooltip]="translate('Düzenle')" (rd-click)="data = item;showMailTemplate=true;console.log(data)"></rd-button>
              <rd-button rd-icon="fa fa-trash-o" rd-icon-color="red" rd-size="small" [rd-tooltip]="translate('Sil')" (rd-confirm-popover)="$event ? deleteMailTemplateProvider.call(deleteMailTemplates(item.Serno)) : null"></rd-button>
            </template>
          </rd-grid-column>
        </rd-grid>
      </rd-body>
    </rd-portlet>
  </div>

  <div class="col-md-8" *ngIf="showMailTemplate">
    <rd-portlet [rd-text]="translate('Mail Şablonu Tanımlama')" rd-color="green" rd-icon="fa fa-envelope">
      <rd-body>
        <rd-form>
          <rd-body>
            <div class="row">
              <div class="col-md-12">
                <div class="col-md-12">
                  <div class="col-md-6" style="padding:0%">
                    <rd-field [rd-text]="translate('Mail Türü')"></rd-field>
                    <rd-input-select [(rd-model)]="data.EmailType" rd-form-data="EmailType" rd-display="Value" rd-value="Key" [rd-items]="mailTemplatesList">
                    </rd-input-select>
                  </div>
                  <div class="col-md-6">
                    <rd-field [rd-text]="translate('Mail Konusu')"></rd-field>
                    <rd-input-text [(rd-model)]="data.MailSubject" rd-form-data="MailSubject" [rd-required]="true"></rd-input-text>
                  </div>
                </div>
                <div class="col-md-12">
                  <rd-field [rd-text]="translate('Mail İçeriği')"></rd-field>
                  <aril-mail-template [(rd-model)]="data.MailContent" (mail-template-save)="mailContent = $event" [rd-required]="true"></aril-mail-template>
                </div>
              </div>
            </div>
          </rd-body>
          <rd-footer>
            <rd-submit [rd-text]="translate('Kaydet')" rd-size="medium" (rd-click)="saveMailTemplateProvider.call(saveMailTemplates($event, mailContent))"></rd-submit>
            <rd-clean [rd-text]="translate('Temizle')" rd-size="medium"></rd-clean>
          </rd-footer>
        </rd-form>
      </rd-body>
    </rd-portlet>
  </div>
</div></code>```

答:
Now the problem that I see is that you're trying to init a new tinymce editor when your data changes, but the editor already exists and therefore the editor.on('init'...) is not called again. The problem only occurs when you switch to another Email template after tinymce was initialized already, but works fine when the first row is selected.

So basically calling tinymce.init the first time works fine, calling it again later does not. The MailTemplatesComponent stays the same when switching to another row, it's not changing, only the data in it, so its reference to editor will also be kept and not destroyed, which is why calling init again is probably not working. tinymce probably thinks, hey I already have initialized that, I don't have to do it again.

Here are two possible solutions I see. First one is to remove the editor on every ngOnChanges and reinit again.

```<code>ngOnChanges() {
    if(this.editor){
        tinymce.remove(this.editor);
    }
    tinymce.init({
        ....
    });
}
</code>```

But that seems to be a little overkill. Second thing is what I also would recommend. Check if the editor of the component is already existing. If so, don't try to init again, but just set the content.

```<code>ngOnChanges() {
    if(this.editor){
        this.editor.setContent(this.model);
    } else {
        tinymce.init({
            ....
        });
    }
}
</code>```

edit

Now when you want to create a new MailTemplate you have to override the current values so that the ngOnChanges function is triggered. Currently you're not changing the data object that is bound.

```<code><rd-tool ... (rd-click)="data;showMailTemplate=true;console.log(data)"></rd-tool>
</code>```

You can see you're not setting data to anything. To clean this up a bit, I would take the code inside your (rd-click) event and put it into a function in your component. In that function I would then update the data by giving it empty values. This way the ngOnChanges function is triggered and your new MailContent value (which we just set to an empty string) will be set to the tinymce editor.

```<code>createNewTemplate(){
    this.data = {
        EmailType: "",
        MailSubject: "",
        MailContent: ""
    };
    this.showMailTemplate=true;
    console.log(this.data);
}
</code>```

Then call this function in your html (rd-click) binding.

```<code><rd-tool ... (rd-click)="createNewTemplate()"></rd-tool>
</code>```

Body:
Hi everyone I have been trying to display HTML context into the TinyMCE text area. When I choose the line for editing first time it displays the data but,  after I choose different row it can't get the context. Any Help would be appreciated. Here are my component and HTML that I have created. I am trying to display context when clicking the edit button.

import { Component, AfterViewInit, OnDestroy, Input, Output, EventEmitter, ElementRef, provide } from 'angular2/core';
import { RdComponent, RdLib } from '../../../../../node_modules/mulberry/core';

declare let tinymce: any;

@Component({
  selector: 'aril-mail-template',
  template: `<textarea contentEditable="true" style="height:30em"><p>{{model}}</p></textarea>`
})

export class MailTemplatesComponent extends RdComponent {

  @Input("rd-model") model;
  @Input("rd-default") default;
  @Input("rd-required") required;
  @Output("mail-template-save") mailTemplateSave: EventEmitter<any> = new EventEmitter<any>();

  editor;
  elementRef: ElementRef;

  constructor(elementRef: ElementRef) {
    super()
    this.elementRef = elementRef;
  }

  ngOnChanges() {
    tinymce.init({
      selector: 'textarea',
      height: "30em",
      menubar: true,
      plugins: [
        'advlist autolink lists link image charmap print preview anchor',
        'searchreplace visualblocks code fullscreen hr',
        'insertdatetime media table contextmenu paste',
        'wordcount'
      ],
      toolbar: 'bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image code',
      table_toolbar: "tableprops cellprops tabledelete | tableinsertrowbefore tableinsertrowafter tabledeleterow | tableinsertcolbefore tableinsertcolafter tabledeletecol",
      powerpaste_allow_local_images: true,
      powerpaste_word_import: 'prompt',
      powerpaste_html_import: 'prompt',
      content_css: [
        '//fonts.googleapis.com/css?family=Lato:300,300i,400,400i',
        '//www.tinymce.com/css/codepen.min.css'],

      setup: editor => {
        this.editor = editor;
        editor.on('init', () => {
          this.model && this.editor.setContent(this.model, { format: 'raw' });
        });
        editor.on('change', () => {
          const content = editor.getContent();
          this.mailTemplateSave.emit(content);
        });
      }
    });
  }

  ngOnDestroy() {
    tinymce.remove(this.editor);
  }

}

<rd-service-provider #mailTemplateProvider rd-client-side-paging [rd-service-proxy]="clientSideProxy" [rd-page-size]="25"
  (rd-init)="mailTemplateProvider.call(getMailTemplates())">
</rd-service-provider>
<rd-service-provider #deleteMailTemplateProvider [rd-service-proxy]="serviceProxy" (rd-success)="toastr.info(translate('İşlem Başarıyla Sonlandırıldı')); mailTemplateProvider.call(getMailTemplates())"></rd-service-provider>
<rd-service-provider #saveMailTemplateProvider [rd-service-proxy]="serviceProxy" (rd-success)="toastr.info(translate('Mail Şablonu Başarıyla Oluşturuldu.')); mailTemplateProvider.call(getMailTemplates())"></rd-service-provider>

    <rd-portlet [rd-text]="translate('Mail Şablonları')" rd-color="green" rd-icon="fa fa-envelope">
      <rd-tools>
        <rd-tool rd-icon="icon-plus" rd-color="white" [rd-tooltip]="translate('Yeni Şablon Ekle')" rd-animate="flash infinite" (rd-click)="data;showMailTemplate=true;console.log(data)"></rd-tool>
        <rd-tool rd-type="refresh" *ngIf="mailTemplateProvider.content.state.serviceCalled"></rd-tool>
        <rd-tool rd-type="collapse" [rd-default-collapse]="false"></rd-tool>
      </rd-tools>

      <rd-body>
        <rd-grid #grid [rd-provider]="mailTemplateProvider" rd-enableSorting="true" [rd-block]="mailTemplateProvider.content.state.waitigForResponse">
          <rd-grid-column [rd-text]="translate('Mail Türü')" rd-key="EmailType">
            <template #item>
              <rd-value rd-type="text" [rd-model]="item.EmailType"></rd-value>
            </template>
          </rd-grid-column>
          <rd-grid-column [rd-text]="translate('Mail Konusu')" rd-key="MailSubject">
            <template #item>
              <rd-value rd-type="text" [rd-model]="item.MailSubject"></rd-value>
            </template>
          </rd-grid-column>
          <rd-grid-column rd-type="operations">
            <template #item>
              <rd-button rd-icon="fa fa-pencil" rd-icon-color="yellow" rd-size="small" [rd-tooltip]="translate('Düzenle')" (rd-click)="data = item;showMailTemplate=true;console.log(data)"></rd-button>
              <rd-button rd-icon="fa fa-trash-o" rd-icon-color="red" rd-size="small" [rd-tooltip]="translate('Sil')" (rd-confirm-popover)="$event ? deleteMailTemplateProvider.call(deleteMailTemplates(item.Serno)) : null"></rd-button>
            </template>
          </rd-grid-column>
        </rd-grid>
      </rd-body>
    </rd-portlet>

    <rd-portlet [rd-text]="translate('Mail Şablonu Tanımlama')" rd-color="green" rd-icon="fa fa-envelope">
      <rd-body>
        <rd-form>
          <rd-body>

                    <rd-field [rd-text]="translate('Mail Türü')"></rd-field>
                    <rd-input-select [(rd-model)]="data.EmailType" rd-form-data="EmailType" rd-display="Value" rd-value="Key" [rd-items]="mailTemplatesList">
                    </rd-input-select>

                    <rd-field [rd-text]="translate('Mail Konusu')"></rd-field>
                    <rd-input-text [(rd-model)]="data.MailSubject" rd-form-data="MailSubject" [rd-required]="true"></rd-input-text>

                  <rd-field [rd-text]="translate('Mail İçeriği')"></rd-field>
                  <aril-mail-template [(rd-model)]="data.MailContent" (mail-template-save)="mailContent = $event" [rd-required]="true"></aril-mail-template>

          </rd-body>
          <rd-footer>
            <rd-submit [rd-text]="translate('Kaydet')" rd-size="medium" (rd-click)="saveMailTemplateProvider.call(saveMailTemplates($event, mailContent))"></rd-submit>
            <rd-clean [rd-text]="translate('Temizle')" rd-size="medium"></rd-clean>
          </rd-footer>
        </rd-form>
      </rd-body>
    </rd-portlet>

Body:
Now the problem that I see is that you're trying to init a new tinymce editor when your data changes, but the editor already exists and therefore the editor.on('init'...) is not called again. The problem only occurs when you switch to another Email template after tinymce was initialized already, but works fine when the first row is selected.

So basically calling tinymce.init the first time works fine, calling it again later does not. The MailTemplatesComponent stays the same when switching to another row, it's not changing, only the data in it, so its reference to editor will also be kept and not destroyed, which is why calling init again is probably not working. tinymce probably thinks, hey I already have initialized that, I don't have to do it again.

Here are two possible solutions I see. First one is to remove the editor on every ngOnChanges and reinit again.

ngOnChanges() {
    if(this.editor){
        tinymce.remove(this.editor);
    }
    tinymce.init({
        ....
    });
}

But that seems to be a little overkill. Second thing is what I also would recommend. Check if the editor of the component is already existing. If so, don't try to init again, but just set the content.

ngOnChanges() {
    if(this.editor){
        this.editor.setContent(this.model);
    } else {
        tinymce.init({
            ....
        });
    }
}

edit

Now when you want to create a new MailTemplate you have to override the current values so that the ngOnChanges function is triggered. Currently you're not changing the data object that is bound.

<rd-tool ... (rd-click)="data;showMailTemplate=true;console.log(data)"></rd-tool>

You can see you're not setting data to anything. To clean this up a bit, I would take the code inside your (rd-click) event and put it into a function in your component. In that function I would then update the data by giving it empty values. This way the ngOnChanges function is triggered and your new MailContent value (which we just set to an empty string) will be set to the tinymce editor.

createNewTemplate(){
    this.data = {
        EmailType: "",
        MailSubject: "",
        MailContent: ""
    };
    this.showMailTemplate=true;
    console.log(this.data);
}

Then call this function in your html (rd-click) binding.

<rd-tool ... (rd-click)="createNewTemplate()"></rd-tool>


问:
How to lock the horizontal scrolling of a scrollView in iOS
i have a scrollView. i want it to scroll only in one direction(VERTICAL). Is there a way in which i can lock the horizontal scrolling...?? ...</p>

答:
Swift

Make contentOffset.x = 0 for disable horizontal scroll

```<code>   extension ViewController: UIScrollViewDelegate {
          func scrollViewDidScroll(_ scrollView: UIScrollView) {
            scrollView.contentOffset.x = 0//to lock horizontal scrolling
            //scrollView.contentOffset.y = 0//to lock vertical scrolling
        }
    }
</code>```

Additionally you can disable scroll indicator as

```<code>  scrollView.showsHorizontalScrollIndicator = false//to disable HorizontalScrollIndicator
    scrollView.showsVerticalScrollIndicator = false//to disable VerticalScrollIndicator
</code>```

Body:
Swift

Make contentOffset.x = 0 for disable horizontal scroll

   extension ViewController: UIScrollViewDelegate {
          func scrollViewDidScroll(_ scrollView: UIScrollView) {
            scrollView.contentOffset.x = 0//to lock horizontal scrolling
            //scrollView.contentOffset.y = 0//to lock vertical scrolling
        }
    }

Additionally you can disable scroll indicator as

  scrollView.showsHorizontalScrollIndicator = false//to disable HorizontalScrollIndicator
    scrollView.showsVerticalScrollIndicator = false//to disable VerticalScrollIndicator


问:
Realm - results.remove() is deprecated in realm
Now that results.remove(0) is deprecated in realm, what is the best way to remove the realm element in an android application?

I have tried to delete particular element and I have used following code :

using result.deleteAllFromRealm(); it's delete all element but need to delete particular position.

```<code>RealmResults<PersonDetailsModel> results = myRealm.where(PersonDetailsModel.class).equalTo("id", personId).findAll();
        myRealm.beginTransaction();
        results.remove(0);     // App crash
        myRealm.commitTransaction();
</code>```

But it's app crash on that line and I am getting this error :

```<code>java.lang.UnsupportedOperationException: This method is not supported by 'RealmResults' or 'OrderedRealmCollectionSnapshot'.
</code>```

Suggest some way to solved this issue.

答:
```<code>realm.executeTransaction((r) -> {
    r.where(PersonDetailsModel.class).equalTo("id", personId).findAll().deleteAllFromRealm();
});
</code>```

Or

```<code>realm.executeTransaction((r) -> {
    PersonDetailsModel person = r.where(PersonDetailsModel.class).equalTo("id", personId).findFirst();
    if(person != null) {
        person.deleteFromRealm();
    }
});
</code>```

Body:
Now that results.remove(0) is deprecated in realm, what is the best way to remove the realm element in an android application?

I have tried to delete particular element and I have used following code :

using result.deleteAllFromRealm(); it's delete all element but need to delete particular position.

RealmResults<PersonDetailsModel> results = myRealm.where(PersonDetailsModel.class).equalTo("id", personId).findAll();
        myRealm.beginTransaction();
        results.remove(0);     // App crash
        myRealm.commitTransaction();

But it's app crash on that line and I am getting this error :

java.lang.UnsupportedOperationException: This method is not supported by 'RealmResults' or 'OrderedRealmCollectionSnapshot'.

Suggest some way to solved this issue.

Body:
realm.executeTransaction((r) -> {
    r.where(PersonDetailsModel.class).equalTo("id", personId).findAll().deleteAllFromRealm();
});

Or

realm.executeTransaction((r) -> {
    PersonDetailsModel person = r.where(PersonDetailsModel.class).equalTo("id", personId).findFirst();
    if(person != null) {
        person.deleteFromRealm();
    }
});


问:
Trouble with String + RandBetween() VBA
```<code>For i = i To nr_commercial
    Cells(i, 1) = commercial & RandBetween(1, 6)
Next i
</code>```

Hi All - I have the above but I am not able to solve it. It returns a compiler error every time. I'm having issues putting a string plus a formula together.

commercial is defined as a string

I have even tried

```<code>Cells(i, 1) = commercial & = Randbetween(1,6)
</code>```

and it returns error saying expecting expression. Is there something not right with the randbetween functionality?

I need to have output in cells such like:

```<code>commercial-1
commercial-5
commercial-3
</code>```

答:
Try this

```<code>For i = i To nr_commercial
  Cells(i, 1) = "commercial-" & Application.WorksheetFunction.RANDBETWEEN(1,6)
Next i
</code>```

Edited : Application.WorksheetFunction.RANDBETWEEN(1,6) is the correct formula to be used

Also it is not advisable to use Cells try to use Sheet or Worksheet in your code.

Title: Trouble with String + RandBetween() VBA

Body:
For i = i To nr_commercial
    Cells(i, 1) = commercial & RandBetween(1, 6)
Next i

Hi All - I have the above but I am not able to solve it. It returns a compiler error every time. I'm having issues putting a string plus a formula together.

commercial is defined as a string

I have even tried

Cells(i, 1) = commercial & = Randbetween(1,6)

and it returns error saying expecting expression. Is there something not right with the randbetween functionality?

I need to have output in cells such like:

commercial-1
commercial-5
commercial-3

Body:
Try this

For i = i To nr_commercial
  Cells(i, 1) = "commercial-" & Application.WorksheetFunction.RANDBETWEEN(1,6)
Next i

Edited : Application.WorksheetFunction.RANDBETWEEN(1,6) is the correct formula to be used

Also it is not advisable to use Cells try to use Sheet or Worksheet in your code.


问:
how can I create executable file for the program written on Java?
everyone, how can I create executable file for the program written on Java in Eclipse Helios? I mean to create small icon to be able start program only by double-clicking on its icon, thanks in advance
edited
I mean executable for Windows

答:
Here is a tutorial that shows you how to make a jar file from eclipse.

If Java is installed on the computer, you can execute your application by doubleclicking the jar file:

http://ecs.victoria.ac.nz/Courses/COMP205_2009T1/TutorialEclipseExportToJar

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: anon


问:
How to covert a 9 digit number into 128bit, 192bit, 256bit key
I am trying to generate encryption key of 128,192,256 bits.

I have a number, suppose that is 965276154.

I want to convert this number into a large string into 128,192,256 bit keys

答:
Use a KDF (Key Derivation Function) such as PBKDF2 to create an encryption key.

Each side will have to agree on a salt value and roud count but these do not need to be secret.

But this seems suspect, it is better and more secure to use well vetted standard methods such as TLS/HTTPS.

Obligatory: "Schneier's Law": "Anyone, from the most clueless amateur to the best cryptographer, can create an algorithm that he himself can't break."


问:
FFmpeg - combine 2 commands
I have 2 commands as listed below.

Add intro image to a video

```<code>ffmpeg -y -loop 1 -framerate 10 -t 3 -i intro.png -i video.mp4 -filter_complex "[0:0] [1:0] concat=n=2:v=1:a=0" -c:v libx264 -crf 23 videoWithIntro.mp4
</code>```

Add watermark to video

```<code>ffmpeg -y -i video.mp4 -i watermark_color.png -filter_complex "overlay=x=(main_w-overlay_w)/2:y=(main_h-overlay_h)/2"  videoWithWatermark.mp4
</code>```

I was wondering is it possible to combine these into the 1 command?

答:
Use

```<code>ffmpeg -y -loop 1 -framerate 10 -t 3 -i intro.png -i video.mp4 -i watermark_color.png -filter_complex "[0][1]concat=n=2:v=1:a=0[v];[v][2]overlay=x=(main_w-overlay_w)/2:y=(main_h-overlay_h)/2"  videoWithWatermark.mp4
</code>```

I assume your videos don't have audio, else use

```<code>ffmpeg -y -loop 1 -framerate 10 -t 3 -i intro.png -i video.mp4 -i watermark_color.png -f lavfi -t 3 -i anullsrc -filter_complex "[0][1]concat=n=2:v=1:a=0[v];[v][2]overlay=x=(main_w-overlay_w)/2:y=(main_h-overlay_h)/2;[3][1]concat=n=2:v=0:a=1"  videoWithWatermark.mp4
</code>```

Title: FFmpeg - combine 2 commands

Body:
I have 2 commands as listed below.

Add intro image to a video

ffmpeg -y -loop 1 -framerate 10 -t 3 -i intro.png -i video.mp4 -filter_complex "[0:0] [1:0] concat=n=2:v=1:a=0" -c:v libx264 -crf 23 videoWithIntro.mp4

Add watermark to video

ffmpeg -y -i video.mp4 -i watermark_color.png -filter_complex "overlay=x=(main_w-overlay_w)/2:y=(main_h-overlay_h)/2"  videoWithWatermark.mp4

I was wondering is it possible to combine these into the 1 command?

Body:
Use

ffmpeg -y -loop 1 -framerate 10 -t 3 -i intro.png -i video.mp4 -i watermark_color.png -filter_complex "[0][1]concat=n=2:v=1:a=0[v];[v][2]overlay=x=(main_w-overlay_w)/2:y=(main_h-overlay_h)/2"  videoWithWatermark.mp4

I assume your videos don't have audio, else use

ffmpeg -y -loop 1 -framerate 10 -t 3 -i intro.png -i video.mp4 -i watermark_color.png -f lavfi -t 3 -i anullsrc -filter_complex "[0][1]concat=n=2:v=1:a=0[v];[v][2]overlay=x=(main_w-overlay_w)/2:y=(main_h-overlay_h)/2;[3][1]concat=n=2:v=0:a=1"  videoWithWatermark.mp4


问:
libgdx firing event from actor to call another actor
I'm using Scene2D and have 2 actors. When MyActor1 is touched, it should fire an event which should be handled by MyActor2. I've tried several different variants on how to fire and even from MyActor1, but it is still not being handled by MyActor2. The full code is below.

Game class which just forwards to a Screen

```<code>public class MyGdxGame extends Game {
   @Override
   public void create() {
       setScreen(new MyGdxScreen());
   }
}
</code>```

Screen class (empty methods ommited)

```<code>public class MyGdxScreen implements Screen {

   private Stage stage;

   @Override
   public void show() {
       stage = new Stage(new ScreenViewport());
       stage.addActor(new MyActor1());
       stage.addActor(new MyActor2());
       Gdx.input.setInputProcessor(stage);
   }

   @Override
   public void render(float delta) {
       Gdx.gl.glClearColor(1, 1, 1, 1);
       Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

       stage.act(delta);
       stage.draw();
   }

   @Override
   public void dispose() {
       stage.dispose();
   }
}
</code>```

First Actor (fires custom event when touched)

```<code>public class MyActor1 extends Actor {

   private Texture image;

   public MyActor1() {
       this.image = new Texture("badlogic.jpg");

       setPosition(0, 0);
       setBounds(0, 0, image.getWidth(), image.getHeight());
       setTouchable(Touchable.enabled);

       addListener(new InputListener() {
           @Override
           public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) {
               Gdx.app.log("touched", "First actor touched!");
               MyActor1.this.fire(new ActorTouchedListener.ActorTouchedEvent());
               MyActor1.this.getParent().fire(new ActorTouchedListener.ActorTouchedEvent());
               return true;
           }
       });
   }

   @Override
   public void draw(Batch batch, float parentAlpha) {
       batch.draw(image, 0, 0, image.getWidth(), image.getHeight());
   }
}
</code>```

Second Actor (should handle an Event fired by Actor1)

```<code>public class MyActor2 extends Actor {

   public MyActor2() {
       addListener(new ActorTouchedListener());
   }
}
</code>```

Event listener

```<code>public class ActorTouchedListener implements EventListener {
   @Override
   public boolean handle(Event event) {
       if (event instanceof ActorTouchedEvent) {
           Gdx.app.log("fired", "Second actor got event!");
           return true;
       }
       return false;
   }

public static class ActorTouchedEvent extends Event {
     public ActorTouchedEvent() {
     }
   }
}
</code>```

答:
Intercomponent events

LibGDX does not provide embeded intercomponent event system, but you can use additional frameworks. For example LibGDX Autumn. You can use two type events:

text event - to notify components about changing of some state

object event - this mechanism deliver your event object to observers

This framework have documentaion and examples, it will help to do what you want

Delayed actor update

For actor's update purposes LibGDX have actions mechanism. In your case I suggest to attach DelayAction to MyActor2 with wrapped MyRedrawAction

```<code>DelayAction delayAction = new DelayAction();

// set wrapped action dellay (in sec.)
delayAction.setDuration(1F);
// set wrapped action. It will be invoked after 1 sec. of stage drawing
delayAction.setAction(new MyRedrawAction());

actor2.addAction(delayAction);
</code>```

You can do this in touchDown() method as @icarumbas suggest

Body:
I'm using Scene2D and have 2 actors. When MyActor1 is touched, it should fire an event which should be handled by MyActor2. I've tried several different variants on how to fire and even from MyActor1, but it is still not being handled by MyActor2. The full code is below.

Game class which just forwards to a Screen

public class MyGdxGame extends Game {
   @Override
   public void create() {
       setScreen(new MyGdxScreen());
   }
}

Screen class (empty methods ommited)

public class MyGdxScreen implements Screen {

   private Stage stage;

   @Override
   public void show() {
       stage = new Stage(new ScreenViewport());
       stage.addActor(new MyActor1());
       stage.addActor(new MyActor2());
       Gdx.input.setInputProcessor(stage);
   }

   @Override
   public void render(float delta) {
       Gdx.gl.glClearColor(1, 1, 1, 1);
       Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

       stage.act(delta);
       stage.draw();
   }

   @Override
   public void dispose() {
       stage.dispose();
   }
}

First Actor (fires custom event when touched)

public class MyActor1 extends Actor {

   private Texture image;

   public MyActor1() {
       this.image = new Texture("badlogic.jpg");

       setPosition(0, 0);
       setBounds(0, 0, image.getWidth(), image.getHeight());
       setTouchable(Touchable.enabled);

       addListener(new InputListener() {
           @Override
           public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) {
               Gdx.app.log("touched", "First actor touched!");
               MyActor1.this.fire(new ActorTouchedListener.ActorTouchedEvent());
               MyActor1.this.getParent().fire(new ActorTouchedListener.ActorTouchedEvent());
               return true;
           }
       });
   }

   @Override
   public void draw(Batch batch, float parentAlpha) {
       batch.draw(image, 0, 0, image.getWidth(), image.getHeight());
   }
}

Second Actor (should handle an Event fired by Actor1)

public class MyActor2 extends Actor {

   public MyActor2() {
       addListener(new ActorTouchedListener());
   }
}

Event listener

public class ActorTouchedListener implements EventListener {
   @Override
   public boolean handle(Event event) {
       if (event instanceof ActorTouchedEvent) {
           Gdx.app.log("fired", "Second actor got event!");
           return true;
       }
       return false;
   }

public static class ActorTouchedEvent extends Event {
     public ActorTouchedEvent() {
     }
   }
}

Body:
Intercomponent events

LibGDX does not provide embeded intercomponent event system, but you can use additional frameworks. For example LibGDX Autumn. You can use two type events:

text event - to notify components about changing of some state

object event - this mechanism deliver your event object to observers

This framework have documentaion and examples, it will help to do what you want

Delayed actor update

For actor's update purposes LibGDX have actions mechanism. In your case I suggest to attach DelayAction to MyActor2 with wrapped MyRedrawAction

DelayAction delayAction = new DelayAction();

// set wrapped action dellay (in sec.)
delayAction.setDuration(1F);
// set wrapped action. It will be invoked after 1 sec. of stage drawing
delayAction.setAction(new MyRedrawAction());

actor2.addAction(delayAction);

You can do this in touchDown() method as @icarumbas suggest


问:
How to scroll up and down and swipe using real android devices? Appium version 1.7.1
I'm a newbie in automation and I dont know scripting either, but I'm trying to learn automation and we are using java script. I'm trying to scroll the page up and down for the EULA terms, could someone help me? I'm using appium version 1.7.1.
Could also someone recommend a tutorial using android studio and not eclipse.

Thanks,
me.

答:
You can perform scroll / swipe up action with below code:

```<code>Dimension size = this.driver.manage ()
    .window ()
    .getSize ();
int startX = size.getWidth () / 2;
int startY = size.getHeight () / 2;
int endX = 0;
int endY = (int) (startY * -1 * 0.5);
TouchAction action = new TouchAction (this.driver);
action.press (startX, startY)
    .moveTo (endX, endY)
    .release ()
    .perform ();
</code>```

You can tweak the code to perform left, down and right swipe.

As for the tutorial you are looking for, it's not easy to find a good resource. But to help you with Mobile Automation, I've created an open source framework, coteafs-appium which you can easily use to Automate the tests. It uses Appium internally. To understand how to use it, see it's wiki on it's GitHub page.

Body:
You can perform scroll / swipe up action with below code:

Dimension size = this.driver.manage ()
    .window ()
    .getSize ();
int startX = size.getWidth () / 2;
int startY = size.getHeight () / 2;
int endX = 0;
int endY = (int) (startY * -1 * 0.5);
TouchAction action = new TouchAction (this.driver);
action.press (startX, startY)
    .moveTo (endX, endY)
    .release ()
    .perform ();

You can tweak the code to perform left, down and right swipe.

As for the tutorial you are looking for, it's not easy to find a good resource. But to help you with Mobile Automation, I've created an open source framework, coteafs-appium which you can easily use to Automate the tests. It uses Appium internally. To understand how to use it, see it's wiki on it's GitHub page.


问:
Js barcode reader
I have barcode image:

And I need to read this barcode.
I tried use getBarcodeFromImage() function from this example.

```<code><img src="photo.jpg" id="barcode" >
<button onclick="alert(getBarcodeFromImage('barcode'))">Scan</button>
</code>```

But I get this code: 18XXXXX21XXX

I think it is wrong.

How can I solve this problem and read barcode?

Thanks.

答: The barcode you are trying to scan is of type Code 128C. Tobias' program only works on UPC symbols.</p>

Title: Js barcode reader

Body:
I have barcode image:

And I need to read this barcode.
I tried use getBarcodeFromImage() function from this example.

<button onclick="alert(getBarcodeFromImage('barcode'))">Scan</button>

But I get this code: 18XXXXX21XXX

I think it is wrong.

How can I solve this problem and read barcode?

Thanks.


问:
Get last modified file without enumerating all files
In c#, given a folder path, is there a way to get the last modified file without getting all files?
I need to quickly find folders that have been updated after a certain time and if the file that was last modified is before the time, i want to skip the folder entirely.
I noticed that folder's last modified time does not get updated when one of its file get updated so this approach does't work.</p>

答:
No, this is why windows comes with indexing to speed up searching. The NTFS file system wasn't designed with fast searching in mind.

In any case you can monitor file changes which is not difficult to do. If it is possible to allow your program to run in the background and monitor changes then this would work. If you needed past history you could do an initial scan only once and then build up your hierarchy from their. As long as your program is always being ran then it should have a current snapshot and not have to do the slow scan.

You can also use the Window Search itself to find the files. If indexing is available then it's probably as fast as you'll get.


问:
i want to UPDATE Fax table and FaxData table that link between Fax&employees tables
i made viewmodel view to allow me to use the 2 model (Fax&Faxdata) in my view
but i have NULL value of SelectedEmployees in listboxfor
what is the problem in my viewmodel ??

```<code> namespace FaxProject.ViewModel
{
public class SendFaxVm
{

    public List<SelectListItem> Employees { set; get; }

    public int[] SelectedEmployees { set; get; }
    public Fax fax { set; get; }

  }
}
</code>```

this is the view (Edite view)

```<code>@model FaxProject.ViewModel.SendFaxVm

    @using (Html.BeginForm("Edit","Fax"))
      {
      @Html.AntiForgeryToken()

<div class="form-horizontal">
    <h4>Fax</h4>
    <hr />
    @Html.ValidationSummary(true, "", new { @class = "text-danger" })
    @Html.HiddenFor(model => model.fax.Id)

    <div class="form-group">
        @Html.LabelFor(model => model.fax.Courier_Num, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.fax.Courier_Num, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.fax.Courier_Num, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.fax.NumberOfPages, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.fax.NumberOfPages, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.fax.NumberOfPages, "",
    <div class="form-group">
        @Html.LabelFor(model => model.Employees, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">

            @Html.ListBoxFor(a => a.SelectedEmployees, Model.Employees)
            @Html.ValidationMessageFor(a => a.SelectedEmployees)

        </div>
    </div>

    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input type="submit" value="Back" class="btn btn-default" />
        </div>
    </div>
</div>
</code>```

}

i got null exception in the listbox so how can i get the list of employees of edit it ??

```<code> public ActionResult Edit (int id,SendFaxVm vm,Fax fax)
    {
        var faxindb = Db.Faxes.Single(f=>f.Id==id);
        faxindb.Courier_Num = fax.Courier_Num;
        faxindb.NumberOfPages = fax.NumberOfPages;
        faxindb.CompanyName = fax.CompanyName;
        faxindb.ReceivingDate = fax.ReceivingDate;
        faxindb.Attachment = fax.Attachment;
        faxindb.Subject = fax.Subject;
        Db.SaveChanges();

        foreach (var userId in vm.SelectedEmployees)
        {
            var faxdataindb = Db.FaxDatas.Single(f => f.FaxId == fax.Id);
            faxdataindb.EmpId = userId;
            //to do  : Save fd

            Db.SaveChanges();
        }

        return RedirectToAction("FaxForm","Fax");
    }
</code>```

this is the action in Fax controller ...

答:
Hey You can improve couple of things.

```<code>public class SendFaxVm
{
    public List<SelectListItem> Employees { set; get; }
    public List<int> SelectedEmployees { set; get; }
    public Fax fax { set; get; }

  }
</code>```

Change array to a List in your Model, You can also use IEnumerable here too. If you , Also follow this example to populate Listbox https://www.codeproject.com/Articles/771999/ASP-Net-MVC-How-to-create-a-ListBox

Body:
i made viewmodel view to allow me to use the 2 model (Fax&Faxdata) in my view
but i have NULL value of SelectedEmployees in listboxfor
what is the problem in my viewmodel ??

 namespace FaxProject.ViewModel
{
public class SendFaxVm
{

    public List<SelectListItem> Employees { set; get; }

    public int[] SelectedEmployees { set; get; }
    public Fax fax { set; get; }

  }
}

this is the view (Edite view)

@model FaxProject.ViewModel.SendFaxVm

    @using (Html.BeginForm("Edit","Fax"))
      {
      @Html.AntiForgeryToken()

Fax

    @Html.ValidationSummary(true, "", new { @class = "text-danger" })
    @Html.HiddenFor(model => model.fax.Id)

        @Html.LabelFor(model => model.fax.Courier_Num, htmlAttributes: new { @class = "control-label col-md-2" })

            @Html.EditorFor(model => model.fax.Courier_Num, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.fax.Courier_Num, "", new { @class = "text-danger" })

        @Html.LabelFor(model => model.fax.NumberOfPages, htmlAttributes: new { @class = "control-label col-md-2" })

            @Html.EditorFor(model => model.fax.NumberOfPages, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.fax.NumberOfPages, "",

        @Html.LabelFor(model => model.Employees, htmlAttributes: new { @class = "control-label col-md-2" })

            @Html.ListBoxFor(a => a.SelectedEmployees, Model.Employees)
            @Html.ValidationMessageFor(a => a.SelectedEmployees)

            <input type="submit" value="Back" class="btn btn-default" />

}

i got null exception in the listbox so how can i get the list of employees of edit it ??

 public ActionResult Edit (int id,SendFaxVm vm,Fax fax)
    {
        var faxindb = Db.Faxes.Single(f=>f.Id==id);
        faxindb.Courier_Num = fax.Courier_Num;
        faxindb.NumberOfPages = fax.NumberOfPages;
        faxindb.CompanyName = fax.CompanyName;
        faxindb.ReceivingDate = fax.ReceivingDate;
        faxindb.Attachment = fax.Attachment;
        faxindb.Subject = fax.Subject;
        Db.SaveChanges();

        foreach (var userId in vm.SelectedEmployees)
        {
            var faxdataindb = Db.FaxDatas.Single(f => f.FaxId == fax.Id);
            faxdataindb.EmpId = userId;
            //to do  : Save fd

            Db.SaveChanges();
        }

        return RedirectToAction("FaxForm","Fax");
    }

this is the action in Fax controller ...

Body:
Hey You can improve couple of things.

public class SendFaxVm
{
    public List<SelectListItem> Employees { set; get; }
    public List<int> SelectedEmployees { set; get; }
    public Fax fax { set; get; }

  }

Change array to a List in your Model, You can also use IEnumerable here too. If you , Also follow this example to populate Listbox https://www.codeproject.com/Articles/771999/ASP-Net-MVC-How-to-create-a-ListBox


问:
Smooch.io .createConversation() is not a method
I have a chatbot based on Smooch.io and I am trying to show a menu on chat initialization so user can start from here instead of typing anything.

As far as I understand from the docs, to do that I need to create conversation Smooch.startConversation(); and then send stuff from my backend app. However it gives me "Smooch.startConversation();" error.

So my question is 1) What I am doing wrong here?; 2) Is there any other way to show initial menu instead of starting conversation without user yet messaging anything?

答:
Assuming you're using the latest version of the SDK, you're probably calling startConversation before the SDK has finished initializing.

You should wait for the promise returned by init to resolve before calling startConversation. Like this:

```<code>Smooch.init({appId: '<app-id>'})
  .then(() => {
    Smooch.startConversation();
  })
</code>```

Body:
Assuming you're using the latest version of the SDK, you're probably calling startConversation before the SDK has finished initializing.

You should wait for the promise returned by init to resolve before calling startConversation. Like this:

Smooch.init({appId: '<app-id>'})
  .then(() => {
    Smooch.startConversation();
  })


问:
MPMoviePlayerViewController video not played using URL in ios
i am trying to play video using URL but it's not playing.
Here is my code :-

```<code>var moviePlayer = MPMoviePlayerViewController(contentURL: mediaItem.fileURL)
self.presentMoviePlayerViewControllerAnimated(moviePlayer)
moviePlayer?.moviePlayer.play()
</code>```

Not getting any kind of error and also not played .

I also checked URL value.Value pass properly but again not play video.

so any one have solution then please help me.

Thanks in advance.

答:
As MPMoviePlayerViewController is deprecated from iOS 9 use AVPlayerViewController instead.

Make sure your video URL is correct because i am able to play video from URL with below code:

```<code>import AVKit

let avPlayerController = AVPlayerViewController()
avPlayerController.player = AVPlayer.init(url: URL.init(string: "http://techslides.com/demos/sample-videos/small.mp4")!)
avPlayerController.player?.play()
present(avPlayerController, animated: true, completion: nil)
</code>```

if your URL is not https then please add below code in plist:

```<code><key>NSAppTransportSecurity</key>
    <dict>
        <key>NSAllowsArbitraryLoads</key>
        <true/>
    </dict>
</code>```

Body:
i am trying to play video using URL but it's not playing.
Here is my code :-

var moviePlayer = MPMoviePlayerViewController(contentURL: mediaItem.fileURL)
self.presentMoviePlayerViewControllerAnimated(moviePlayer)
moviePlayer?.moviePlayer.play()

Not getting any kind of error and also not played .

I also checked URL value.Value pass properly but again not play video.

so any one have solution then please help me.

Thanks in advance.

Body:
As MPMoviePlayerViewController is deprecated from iOS 9 use AVPlayerViewController instead.

Make sure your video URL is correct because i am able to play video from URL with below code:

import AVKit

let avPlayerController = AVPlayerViewController()
avPlayerController.player = AVPlayer.init(url: URL.init(string: "http://techslides.com/demos/sample-videos/small.mp4")!)
avPlayerController.player?.play()
present(avPlayerController, animated: true, completion: nil)

if your URL is not https then please add below code in plist:

<key>NSAppTransportSecurity</key>
    <dict>
        <key>NSAllowsArbitraryLoads</key>
        <true/>
    </dict>


问:
How to set an environment variable in Vagrant that PHP can access
I want my local development environment to have an environment variable set so that my PHP app can read it.

In my Vagrantfile I have:

```<code>config.vm.provision "shell", inline: <<-SHELL

    ## Set environment variables...
    echo "export APP_ENV=development" > /home/vagrant/.profile
    echo "export APP_ENV=development" > /home/vagrant/.bashrc
    ...
</code>```

In my PHP code I added:

```<code>var_dump(shell_exec( 'whoami' ));
var_dump(shell_exec( 'echo $APP_ENV' ));
</code>```

The output is:

```<code>string(8) "vagrant "
string(1) " "
</code>```

I remembered to re-provision my box (many times). I'm mostly confused why the second var_dump isn't returning "development" but I'm especially confused why it would return a single space rather than an empty string or NULL if it's not set at all. What am I missing?

Vagrant 1.8.5

Virtualbox 5.1.30r118389

UPDATE:

When I SSH into the box as vagrant user, and run $ echo $APP_ENV, it returns "development".

I added source /home/vagrant/.profile to the provisioning script and PHP still can't see the var I'm setting.

UPDATE2:

I think Apache might be running as www-data. Here's some screenshots from my phpinfo().

答:
You run the provisioning as root user which your bash is for vagrant user so make sure to run the provisioning as vagrant by adding privileged: false so the files will be owned by vagrant and they will be run

```<code>config.vm.provision "shell", privileged: false, inline: <<-SHELL

    ## Set environment variables...
    echo "export APP_ENV=development" >> /home/vagrant/.profile
    echo "export APP_ENV=development" >> /home/vagrant/.bashrc
    ...
</code>```

Body:
I want my local development environment to have an environment variable set so that my PHP app can read it.

In my Vagrantfile I have:

config.vm.provision "shell", inline: <<-SHELL

    ## Set environment variables...
    echo "export APP_ENV=development" > /home/vagrant/.profile
    echo "export APP_ENV=development" > /home/vagrant/.bashrc
    ...

In my PHP code I added:

var_dump(shell_exec( 'whoami' ));
var_dump(shell_exec( 'echo $APP_ENV' ));

The output is:

string(8) "vagrant "
string(1) " "

I remembered to re-provision my box (many times). I'm mostly confused why the second var_dump isn't returning "development" but I'm especially confused why it would return a single space rather than an empty string or NULL if it's not set at all. What am I missing?

Vagrant 1.8.5

Virtualbox 5.1.30r118389

UPDATE:

When I SSH into the box as vagrant user, and run $ echo $APP_ENV, it returns "development".

I added source /home/vagrant/.profile to the provisioning script and PHP still can't see the var I'm setting.

UPDATE2:

I think Apache might be running as www-data. Here's some screenshots from my phpinfo().

Body:
You run the provisioning as root user which your bash is for vagrant user so make sure to run the provisioning as vagrant by adding privileged: false so the files will be owned by vagrant and they will be run

config.vm.provision "shell", privileged: false, inline: <<-SHELL

    ## Set environment variables...
    echo "export APP_ENV=development" >> /home/vagrant/.profile
    echo "export APP_ENV=development" >> /home/vagrant/.bashrc
    ...


问:
.NET open PDF in winform without external dependencies
Is there a FREE library which will allow me to open a pdf and show it on a winform project. I know I could open it in adobe reader or something but it always seems so bloated to me and I would be relying on it being installed. Is there a nice lightweight alternative where I could just include a dll in my project or similar avoiding external dependencies.

I don't need much functionality just view, change page zoom..

I have seen a few libraries but they seem to be about creating PDF's not viewing.

答: You can use Spire.PDFViewer from Nuget. See here</p>


问:
Trying to create reflection effect using visual brush bound to a listbox as the fill (dynamicresource) of a rectangle,
I have a resource keyed as 'listBoxVisualBrush'

and a list box named 'listBox' which has it's ItemsSource property bound to a datamodel's observable collection

I would like to create a reflection effect using a rectangle(for example) by setting the fill to be the 'listBoxVisualBrush' brush.

It doesn't work (It seems it takes a snapshot of the empty list, so nothing is being reflected. But when I use some data in design time, everything shows up well and the list is being reflected in the rectangle.

Does anybody have an idea?

Thanks, Mike

答:
Hard to say without seeing code, but it sounds like the Visual property on your VisualBrush is being set to a different ListBox than the one being reflected. You want to use the same ListBox, not a distinct one. Something like:

```<code><ListBox x:Name="listBox" ItemsSource="{Binding Items}"/>
<Rectangle>
    <Rectangle.Fill>
        <VisualBrush Visual="{Binding ElementName=listBox}"/>
    </Rectangle.Fill>
</Rectangle>
</code>```

Body:
Hard to say without seeing code, but it sounds like the Visual property on your VisualBrush is being set to a different ListBox than the one being reflected. You want to use the same ListBox, not a distinct one. Something like:

<ListBox x:Name="listBox" ItemsSource="{Binding Items}"/>
<Rectangle>
    <Rectangle.Fill>
        <VisualBrush Visual="{Binding ElementName=listBox}"/>
    </Rectangle.Fill>
</Rectangle>


问:
Access VBA write multiple values to single text field on form
I'm attempting to concatenate multiple values into a single text field on a form and needs help on assigning those values to the text field.

Setup:  I have an access form that a user can select a drop down and choose an ID number.  Selecting the ID and then clicking a button will run a query that can return one or multiple rows of results.   The rows returned in the results will have duplicate data except for one field (e.g. description).  I'm attempting to loop over the results and add the description to a text field on the form so that shows all the field values from each row, thus listing all the descriptions.

Example of data returned:
Columns:

```<code>ID | Issue Date | Description | CBD | ECD
</code>```

Results return could be 1 or more rows: example below

```<code>17-0001 | 11/30/2017 | ABC | 12/5/2017 | 12/10/2017
17-0001 | 11/30/2017 | XYZ | 12/5/2017 | 12/10/2017
17-0001 | 11/30/2017 | LMN | 12/5/2017 | 12/10/2017
17-0001 | 11/30/2017 | QAZ | 12/5/2017 | 12/10/2017
</code>```

In the text box I'm trying to add the values to I want it add the description to a single text box in order.

Text box contains:
Subject:
ID

Body Text:
ABC
XYZ
LMN
QAZ

Here is Code I have so far:  It works but I just not sure how to get the description to concatenate together.

```<code>Private Sub createAnnouncement_Click()
Dim qdf As DAO.QueryDef
Dim rst As DAO.Recordset
Dim db As Database
Dim issID As String

Set db = CurrentDb
Set qdf = db.QueryDefs("nso_announce_qry")
qdf.Parameters(0) = Forms![NSO Announcements]!annID

Set rst = qdf.OpenRecordset

annSubject = rst.Fields("Issuance Title")

Do While (Not rst.EOF)
   MsgBox (rst.Fields("Issuance Detail Description").Value)
   rst.MoveNext
Loop
End Sub
</code>```

should there be a annBody variable outside the Do while that you add in each value as it loops through?

答:
You can "acumulate" the contents of the Description field for each record:</p>

```<code>Dim concatenated as String

Do While (Not rst.EOF)
   concatenated = concatenated + rst.Fields("Issuance Detail Description") + " "
   rst.MoveNext
Loop
concatenated = Left(concatenated, Len(concatenated) - 1)
</code>```

Body:
I'm attempting to concatenate multiple values into a single text field on a form and needs help on assigning those values to the text field.

Setup:  I have an access form that a user can select a drop down and choose an ID number.  Selecting the ID and then clicking a button will run a query that can return one or multiple rows of results.   The rows returned in the results will have duplicate data except for one field (e.g. description).  I'm attempting to loop over the results and add the description to a text field on the form so that shows all the field values from each row, thus listing all the descriptions.

Example of data returned:
Columns:

ID | Issue Date | Description | CBD | ECD

Results return could be 1 or more rows: example below

17-0001 | 11/30/2017 | ABC | 12/5/2017 | 12/10/2017
17-0001 | 11/30/2017 | XYZ | 12/5/2017 | 12/10/2017
17-0001 | 11/30/2017 | LMN | 12/5/2017 | 12/10/2017
17-0001 | 11/30/2017 | QAZ | 12/5/2017 | 12/10/2017

In the text box I'm trying to add the values to I want it add the description to a single text box in order.

Text box contains:
Subject:
ID

Body Text:
ABC
XYZ
LMN
QAZ

Here is Code I have so far:  It works but I just not sure how to get the description to concatenate together.

Private Sub createAnnouncement_Click()
Dim qdf As DAO.QueryDef
Dim rst As DAO.Recordset
Dim db As Database
Dim issID As String

Set db = CurrentDb
Set qdf = db.QueryDefs("nso_announce_qry")
qdf.Parameters(0) = Forms![NSO Announcements]!annID

Set rst = qdf.OpenRecordset

annSubject = rst.Fields("Issuance Title")

Do While (Not rst.EOF)
   MsgBox (rst.Fields("Issuance Detail Description").Value)
   rst.MoveNext
Loop
End Sub

should there be a annBody variable outside the Do while that you add in each value as it loops through?

Body:
You can "acumulate" the contents of the Description field for each record:

Dim concatenated as String

Do While (Not rst.EOF)
   concatenated = concatenated + rst.Fields("Issuance Detail Description") + " "
   rst.MoveNext
Loop
concatenated = Left(concatenated, Len(concatenated) - 1)


问:
How to remove

 tags in summernote value?
While entering space in staring am getting following code from summernote textarea,

```<code><p><br></p><p><br></p><p><strong style="font-family: "Open Sans", Arial, sans-serif; text-align: justify;">Lorem Ipsum</strong><span style="font-family: "Open Sans", Arial, sans-serif; text-align: justify;"> is simply dummy text of the printing and typesetting industry. </span><br></p><p><br></p><p><br></p>
</code>```

but i want to remove the starting

 before storing to db.

for example i want to store like below,

```<code><p><strong style="font-family: "Open Sans", Arial, sans-serif; text-align: justify;">Lorem Ipsum</strong><span style="font-family: "Open Sans", Arial, sans-serif; text-align: justify;"> is simply dummy text of the printing and typesetting industry. </span><br></p>
</code>```

答:
Just remove the empty element

```<code>$("p").each(function(){
    if (!$(this).text().trim().length) {
        $(this).remove();
    }
});
</code>```

https://jsfiddle.net/ox32tjwg/

ContentLicense: CC BY-SA 4.0

Title:
How to remove

 tags in summernote value?

Body:
While entering space in staring am getting following code from summernote textarea,

Lorem Ipsum is simply dummy text of the printing and typesetting industry.

but i want to remove the starting

 before storing to db.

for example i want to store like below,

Lorem Ipsum is simply dummy text of the printing and typesetting industry.

Body:
Just remove the empty element

$("p").each(function(){
    if (!$(this).text().trim().length) {
        $(this).remove();
    }
});

https://jsfiddle.net/ox32tjwg/


问:
How to prevent browser to invoke basic auth popup and handle 401 error using Jquery?
I need to send authorization request using basic auth. I have successfully implemented this using jquery. However when I get 401 error basic auth browser popup is opened and jquery ajax error callback is not called.</p>

答:
In Safari, you can use synchronous requests to avoid the browser to display the popup. Of course, synchronous requests should only be used in this case to check user credentials... You can use a such request before sending the actual request which may cause a bad user experience if the content (sent or received) is quite heavy.</p>

```<code>    var xmlhttp=new XMLHttpRequest;
    xmlhttp.withCredentials=true;
    xmlhttp.open("POST",<YOUR UR>,false,username,password);
    xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
    xmlhttp.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
</code>```

Body:
In Safari, you can use synchronous requests to avoid the browser to display the popup. Of course, synchronous requests should only be used in this case to check user credentials... You can use a such request before sending the actual request which may cause a bad user experience if the content (sent or received) is quite heavy.

    var xmlhttp=new XMLHttpRequest;
    xmlhttp.withCredentials=true;
    xmlhttp.open("POST",<YOUR UR>,false,username,password);
    xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
    xmlhttp.setRequestHeader('X-Requested-With', 'XMLHttpRequest');


问:
EntityCollection OrderBy problem
What is wrong with the following code?

List students = new List();

```<code>students = db.Students.Where(c => c.StudentCourses.OrderBy(o => o.EnrolledTo > DateTime.Now.Date)).ToList();
</code>```

I am getting error: delegate does not take 1 arguments.

Thanks

答:
I guessing a bit here, but I think that you are trying to get the latest date from each student and compare it to todays date. If you do it using OrderBy you would need a Last call to get the single value, but you should rather just use Max.

Note: Don't use DateTime.Now in a loop, as the value changes. If you run the query at midnight it may change in the middle of the loop, and you get an inconsistent result. Put the value in a variable before the loop.

```<code>DateTime today = DateTime.Today;
students = db.Students
  .Where(c => c.StudentCourses.Max(o => o.EnrolledTo) > today)
  .ToList();
</code>```

Title: EntityCollection OrderBy problem

Body:
What is wrong with the following code?

List students = new List();

students = db.Students.Where(c => c.StudentCourses.OrderBy(o => o.EnrolledTo > DateTime.Now.Date)).ToList();

I am getting error: delegate does not take 1 arguments.

Thanks

Body:
I guessing a bit here, but I think that you are trying to get the latest date from each student and compare it to todays date. If you do it using OrderBy you would need a Last call to get the single value, but you should rather just use Max.

Note: Don't use DateTime.Now in a loop, as the value changes. If you run the query at midnight it may change in the middle of the loop, and you get an inconsistent result. Put the value in a variable before the loop.

DateTime today = DateTime.Today;
students = db.Students
  .Where(c => c.StudentCourses.Max(o => o.EnrolledTo) > today)
  .ToList();


问:
Send sync message from IpcMain to IpcRenderer - Electron
In electron, It is possible to send sync message from IpcRenderer to IpcMain via ipcRenderer.sendSync('synchronous-message', 'ping').

Also possible to send async message from IpcMain to IpcRenderer using window.webContents.send('ping', 'whoooooooh!')

but is there any way to send sync message from IpcMain to IpcRenderer?

答:
There is no such functionality of ipcMain *. However, you can achieve almost the same result asynchronously with the following steps:

Place your code which you would run only after the synchronous call in an ipcMain callback.

Reply to ipc message in renderer process with the result using event.sender.send

A dummy example of sum using this approach looks like the following:

main.js

const {app, BrowserWindow, ipcMain} = require('electron')
const path = require('path')

app.once('ready', () => {
  let win = new BrowserWindow()
  // have to run "sync", that is only after result is ready
  const doJobWithResult = (res) => {
    console.log(res)
  }
  win.webContents.once('dom-ready', () => {
    win.webContents
    .send('sum-request', 23, 98, 3, 61)
    ipcMain.once('sum-reply', (event, sum) => {
      doJobWithResult(sum)
    })
  })
  win.loadURL(path.resolve(__dirname, 'test.html'))
})
```

<p><em>renderer.js (referred from test.html)</em></p>

<pre class="lang-js prettyprint-override"><code>const {ipcRenderer} = require('electron')

window.onload = () => {
  const add = (a, b) => {
    return a + b
  }
  ipcRenderer.on('sum-request', (event, ...args) => {
    event.sender.send('sum-reply', [...args].reduce(add, 0))
  })
}
</code>```

* I suppose it's because calling synchronously from main to renderer would block the main nodejs process which does serve renderer processes too after all.

Body:
There is no such functionality of ipcMain *. However, you can achieve almost the same result asynchronously with the following steps:

Place your code which you would run only after the synchronous call in an ipcMain callback.

Reply to ipc message in renderer process with the result using event.sender.send

A dummy example of sum using this approach looks like the following:

main.js

const {app, BrowserWindow, ipcMain} = require('electron')
const path = require('path')

app.once('ready', () => {
  let win = new BrowserWindow()
  // have to run "sync", that is only after result is ready
  const doJobWithResult = (res) => {
    console.log(res)
  }
  win.webContents.once('dom-ready', () => {
    win.webContents
    .send('sum-request', 23, 98, 3, 61)
    ipcMain.once('sum-reply', (event, sum) => {
      doJobWithResult(sum)
    })
  })
  win.loadURL(path.resolve(__dirname, 'test.html'))
})

renderer.js (referred from test.html)

const {ipcRenderer} = require('electron')

window.onload = () => {
  const add = (a, b) => {
    return a + b
  }
  ipcRenderer.on('sum-request', (event, ...args) => {
    event.sender.send('sum-reply', [...args].reduce(add, 0))
  })
}

* I suppose it's because calling synchronously from main to renderer would block the main nodejs process which does serve renderer processes too after all.


问:
shared_from_this() from another thread (a member thread function)
In my code I use boost::threads and I have a class that runs a thread via a member function called fnThread() . In this fnThread() I want to create a shared_from_this() and pass it to listening parties with a signal. But the line boost::shared_ptr<foo> p = shared_from_this() throws an exception as follows;

```<code>boost::exception_detail::clone_impl<boost::exception_detail::error_info_injector<boost::bad_weak_ptr> > at memory location 0x04c2f720.
</code>```

The offending command is shared_from_this() . Is it illegal to create a shared_from_this() from another thread or am I doing something wrong ? Any help is appreciated. Thanks !

PS: I plan on changing my signal arguments to plain pointers as it wouldn't affect my structure. But I favor shared_ptr<> and I want to hear any comments about the decision. Maybe it's a bad choice for this particular situation. What do you suggest ?

EDIT:

Here is a simple class for you to test

```<code>class foo : public boost::enable_shared_from_this<foo>
{
public:
    int start()
    {
        foo_thread.reset(new boost::thread(boost::bind(&foo::fn_foo_thread, this)));

        return 0;
    }

    ~foo()
    {
        if (foo_thread->joinable())
            foo_thread->join();
    }

private:
    boost::scoped_ptr<boost::thread> foo_thread;

    void fn_foo_thread()
    {
        boost::shared_ptr<foo> p = shared_from_this();
        std::cout << "foo thread terminated. \n" << std::endl;
    }
};
</code>```

答: shared_from_this can be used from another thread. The bad_weak_ptr exception is thrown when there exists no shared_ptr to this (as the name implies). Most likely your problem exists elsewhere in your code.

Body:
In my code I use boost::threads and I have a class that runs a thread via a member function called fnThread() . In this fnThread() I want to create a shared_from_this() and pass it to listening parties with a signal. But the line boost::shared_ptr<foo> p = shared_from_this() throws an exception as follows;

boost::exception_detail::clone_impl<boost::exception_detail::error_info_injector<boost::bad_weak_ptr> > at memory location 0x04c2f720.

The offending command is shared_from_this() . Is it illegal to create a shared_from_this() from another thread or am I doing something wrong ? Any help is appreciated. Thanks !

PS: I plan on changing my signal arguments to plain pointers as it wouldn't affect my structure. But I favor shared_ptr<> and I want to hear any comments about the decision. Maybe it's a bad choice for this particular situation. What do you suggest ?

EDIT:

Here is a simple class for you to test

class foo : public boost::enable_shared_from_this<foo>
{
public:
    int start()
    {
        foo_thread.reset(new boost::thread(boost::bind(&foo::fn_foo_thread, this)));

        return 0;
    }

    ~foo()
    {
        if (foo_thread->joinable())
            foo_thread->join();
    }

private:
    boost::scoped_ptr<boost::thread> foo_thread;

    void fn_foo_thread()
    {
        boost::shared_ptr<foo> p = shared_from_this();
        std::cout << "foo thread terminated. \n" << std::endl;
    }
};