来源: stackexchange

问:
Using independent ngModel in Angular 2+ Reactive Form
I've got a reactive form on my page.

Here's a summary of the code:

```<code><div class="container">
<form [formGroup]="transactionForm" (ngSubmit)="onSubmit(transactionForm)">
     <div formGroupName="userInfoGroup" class="form-group">
          <input formControlName="name" class="form-control" placeholder="Larry" id="name">
     </div>
     ...
</form>
</div>
</code>```

Here's where it gets tricky. I want the user to be able to input the information of the person who referred them (who may or may not exist in our database). So I want to use ng-bootstrap typeahead to provide a way to search for an existing user.

So I copied the html and ts code from ng-bootstrap, and now my template looks like

```<code><div class="container">
<form [formGroup]="transactionForm" (ngSubmit)="onSubmit(transactionForm)">
     <div formGroupName="userInfoGroup" class="form-group">
          <input formControlName="name" class="form-control" placeholder="Larry" id="name">
     </div>
     <input id="typeahead-http" type="text" class="form-control" [(ngModel)]="model" [ngbTypeahead]="searchForReferrer" placeholder="Search for Referrer" />
     ...
</form>
</div>
</code>```

When I run this now I get errors:

```<code>RegisterTransaction.html:154 ERROR TypeError: Cannot read property 'lift' of undefined
    at tapOperatorFunction (tap.js:52)
    at _do (do.js:48)
    at NgbTypeahead.webpackJsonp.../../../../@ng-bootstrap/ng-bootstrap/typeahead/typeahead.js.NgbTypeahead.ngOnInit (typeahead.js:73)
    at checkAndUpdateDirectiveInline (core.es5.js:10843)
    at checkAndUpdateNodeInline (core.es5.js:12341)
    at checkAndUpdateNode (core.es5.js:12284)
    at debugCheckAndUpdateNode (core.es5.js:13141)
    at debugCheckDirectivesFn (core.es5.js:13082)
    at Object.View_RegisterTransaction_0._co [as updateDirectives] (RegisterTransaction.html:163)
    at Object.debugUpdateDirectives [as updateDirectives] (core.es5.js:13067)
  [1]: https://ng-bootstrap.github.io/#/components/typeahead/examples
</code>```

and if I just remove [ngbTypeahead]="searchForReferrer"  I get

```<code>RegisterTransaction.html:154 ERROR Error:
      ngModel cannot be used to register form controls with a parent formGroup directive.  Try using
      formGroup's partner directive "formControlName" instead.  Example:

    <div [formGroup]="myGroup">
      <input formControlName="firstName">
    </div>

    In your class:

    this.myGroup = new FormGroup({
       firstName: new FormControl()
    });

      Or, if you'd like to avoid registering this form control, indicate that it's standalone in ngModelOptions:

      Example:

    <div [formGroup]="myGroup">
       <input formControlName="firstName">
       <input [(ngModel)]="showMoreControls" [ngModelOptions]="{standalone: true}">
    </div>

    at Function.webpackJsonp.../../../forms/@angular/forms.es5.js.TemplateDrivenErrors.modelParentException (forms.es5.js:4110)
    at NgModel.webpackJsonp.../../../forms/@angular/forms.es5.js.NgModel._checkParentType (forms.es5.js:4430)
    at NgModel.webpackJsonp.../../../forms/@angular/forms.es5.js.NgModel._checkForErrors (forms.es5.js:4417)
    at NgModel.webpackJsonp.../../../forms/@angular/forms.es5.js.NgModel.ngOnChanges (forms.es5.js:4324)
    at checkAndUpdateDirectiveInline (core.es5.js:10840)
    at checkAndUpdateNodeInline (core.es5.js:12341)
    at checkAndUpdateNode (core.es5.js:12284)
    at debugCheckAndUpdateNode (core.es5.js:13141)
    at debugCheckDirectivesFn (core.es5.js:13082)
    at Object.View_RegisterTransaction_0._co [as updateDirectives] (RegisterTransaction.html:163)
</code>```

How do I properly use this search ahead inside an existing reactive form?

答:
Thanks to @Aluan Haddad, who prodded me to ensure my code was exactly the same as the sample code, I eventually realized it was indeed not the same. I had inadvertently added curly braces around the return portion of the arrow function.

So instead of

```<code>search = (text$: Observable<string>) =>
    text$
      .debounceTime(300)
      .distinctUntilChanged()
      .do(() => this.searching = true)
      .switchMap(term =>
        this._service.search(term)
          .do(() => this.searchFailed = false)
          .catch(() => {
            this.searchFailed = true;
            return Observable.of([]);
          }))
      .do(() => this.searching = false)
      .merge(this.hideSearchingWhenUnsubscribed);
</code>```

I had

```<code>search = (text$: Observable<string>) => {
    text$
      .debounceTime(300)
      .distinctUntilChanged()
      .do(() => this.searching = true)
      .switchMap(term =>
        this._service.search(term)
          .do(() => this.searchFailed = false)
          .catch(() => {
            this.searchFailed = true;
            return Observable.of([]);
          }))
      .do(() => this.searching = false)
      .merge(this.hideSearchingWhenUnsubscribed);
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I've got a reactive form on my page.

Here's a summary of the code:

<form [formGroup]="transactionForm" (ngSubmit)="onSubmit(transactionForm)">

          <input formControlName="name" class="form-control" placeholder="Larry" id="name">

     ...
</form>

Here's where it gets tricky. I want the user to be able to input the information of the person who referred them (who may or may not exist in our database). So I want to use ng-bootstrap typeahead to provide a way to search for an existing user.

So I copied the html and ts code from ng-bootstrap, and now my template looks like

<form [formGroup]="transactionForm" (ngSubmit)="onSubmit(transactionForm)">

          <input formControlName="name" class="form-control" placeholder="Larry" id="name">

     <input id="typeahead-http" type="text" class="form-control" [(ngModel)]="model" [ngbTypeahead]="searchForReferrer" placeholder="Search for Referrer" />
     ...
</form>

When I run this now I get errors:

RegisterTransaction.html:154 ERROR TypeError: Cannot read property 'lift' of undefined
    at tapOperatorFunction (tap.js:52)
    at _do (do.js:48)
    at NgbTypeahead.webpackJsonp.../../../../@ng-bootstrap/ng-bootstrap/typeahead/typeahead.js.NgbTypeahead.ngOnInit (typeahead.js:73)
    at checkAndUpdateDirectiveInline (core.es5.js:10843)
    at checkAndUpdateNodeInline (core.es5.js:12341)
    at checkAndUpdateNode (core.es5.js:12284)
    at debugCheckAndUpdateNode (core.es5.js:13141)
    at debugCheckDirectivesFn (core.es5.js:13082)
    at Object.View_RegisterTransaction_0._co [as updateDirectives] (RegisterTransaction.html:163)
    at Object.debugUpdateDirectives [as updateDirectives] (core.es5.js:13067)
  [1]: https://ng-bootstrap.github.io/#/components/typeahead/examples

and if I just remove [ngbTypeahead]="searchForReferrer"  I get

RegisterTransaction.html:154 ERROR Error:
      ngModel cannot be used to register form controls with a parent formGroup directive.  Try using
      formGroup's partner directive "formControlName" instead.  Example:

      <input formControlName="firstName">

    In your class:

    this.myGroup = new FormGroup({
       firstName: new FormControl()
    });

      Or, if you'd like to avoid registering this form control, indicate that it's standalone in ngModelOptions:

      Example:

       <input formControlName="firstName">
       <input [(ngModel)]="showMoreControls" [ngModelOptions]="{standalone: true}">

    at Function.webpackJsonp.../../../forms/@angular/forms.es5.js.TemplateDrivenErrors.modelParentException (forms.es5.js:4110)
    at NgModel.webpackJsonp.../../../forms/@angular/forms.es5.js.NgModel._checkParentType (forms.es5.js:4430)
    at NgModel.webpackJsonp.../../../forms/@angular/forms.es5.js.NgModel._checkForErrors (forms.es5.js:4417)
    at NgModel.webpackJsonp.../../../forms/@angular/forms.es5.js.NgModel.ngOnChanges (forms.es5.js:4324)
    at checkAndUpdateDirectiveInline (core.es5.js:10840)
    at checkAndUpdateNodeInline (core.es5.js:12341)
    at checkAndUpdateNode (core.es5.js:12284)
    at debugCheckAndUpdateNode (core.es5.js:13141)
    at debugCheckDirectivesFn (core.es5.js:13082)
    at Object.View_RegisterTransaction_0._co [as updateDirectives] (RegisterTransaction.html:163)

How do I properly use this search ahead inside an existing reactive form?

Body:
Thanks to @Aluan Haddad, who prodded me to ensure my code was exactly the same as the sample code, I eventually realized it was indeed not the same. I had inadvertently added curly braces around the return portion of the arrow function.

So instead of

search = (text$: Observable<string>) =>
    text$
      .debounceTime(300)
      .distinctUntilChanged()
      .do(() => this.searching = true)
      .switchMap(term =>
        this._service.search(term)
          .do(() => this.searchFailed = false)
          .catch(() => {
            this.searchFailed = true;
            return Observable.of([]);
          }))
      .do(() => this.searching = false)
      .merge(this.hideSearchingWhenUnsubscribed);

I had

search = (text$: Observable<string>) => {
    text$
      .debounceTime(300)
      .distinctUntilChanged()
      .do(() => this.searching = true)
      .switchMap(term =>
        this._service.search(term)
          .do(() => this.searchFailed = false)
          .catch(() => {
            this.searchFailed = true;
            return Observable.of([]);
          }))
      .do(() => this.searching = false)
      .merge(this.hideSearchingWhenUnsubscribed);
}


问:
Getting Emacs `spacemacs` to accept function that changes latex compiler based upon orgmode header
I used the latest master version 0.200.10.x Spacemacs on emacs 25.3. I was trying to implement a function that is recommended by the orgmode documentation for allowing the user to define which Latex compiler he/she wants to use. I implemented the function but it did not seem to work. The latex compilation step keeps using pdflatex instead of xelatex as specified in the file header. So I was trying to figure out what adjustment to make.

```<code>;; Originally taken from Bruno Tavernier: http://thread.gmane.org/gmane.emacs.orgmode/31150/focus=31432
;; but adapted to use latexmk 4.20 or higher.
(defun my-auto-tex-cmd ()
  "When exporting from .org with latex, automatically run latex,
     pdflatex, or xelatex as appropriate, using latexmk."
  (let ((texcmd)))
  ;; default command: oldstyle latex via dvi
  (setq texcmd "latexmk -dvi -pdfps -quiet %f")
  ;; pdflatex -> .pdf
  (if (string-match "LATEX_CMD: pdflatex" (buffer-string))
      (setq texcmd "latexmk -pdf -quiet %f"))
  ;; xelatex -> .pdf
  (if (string-match "LATEX_CMD: xelatex" (buffer-string))
      (setq texcmd "latexmk -pdflatex=xelatex -pdf -quiet %f"))
  ;; LaTeX compilation command
  (setq org-latex-to-pdf-process (list texcmd)))

(add-hook 'org-export-latex-after-initial-vars-hook 'my-auto-tex-cmd)
</code>```

According to the Spacemacs issues list I need to make a change in the spacemacs-configuration-layers setting a la:

```<code>dotspacemacs-configuration-layers '(
  (latex :variables latex-build-command "LaTeX"))
</code>```

The problem is that making a change in the dotspacemacs-configuration-layers does not seem to let me apply the change based upon file specific settings.

Does anyone know the right way to implement this function above (my-auto-tex-cmd) in spacemacs?

答:
I found the solution in a blog post .

The actual elisp code is:

```<code>;; Default packages included in every tex file, pdflatex or xelatex
(setq org-latex-packages-alist
      '(("" "graphicx" t)
        ("" "longtable" nil)
        ("" "float" nil)))

;; source: https://lists.gnu.org/archive/html/emacs-orgmode/2013-06/msg00240.html
(defun my-auto-tex-cmd (backend)
  "When exporting from .org with latex,
  automatically run latex, pdflatex, or xelatex as appropriate,
  using latexmk."
  (let ((texcmd))
    (setq texcmd "latexmk -pdf %f")
    (if (string-match "LATEX_CMD: pdflatex" (buffer-string))
        (progn
          (setq texcmd "latexmk -pdf -pdflatex='pdflatex -file-line-error --shell-escape -synctex=1' %f")
          (setq org-latex-default-packages-alist
                '(("AUTO" "inputenc" t)
                  ("T1"   "fontenc"   t)
                  (""     "fixltx2e"  nil)
                  (""     "wrapfig"   nil)
                  (""     "soul"      t)
                  (""     "textcomp"  t)
                  (""     "marvosym"  t)
                  (""     "wasysym"   t)
                  (""     "latexsym"  t)
                  (""     "amssymb"   t)
                  (""     "hyperref"  nil)))))
    (if (string-match "LATEX_CMD: xelatex" (buffer-string))
        (progn
          (setq texcmd "latexmk -pdflatex='xelatex -file-line-error --shell-escape -synctex=1' -pdf %f")
          (setq org-latex-default-packages-alist
                '(("" "fontspec" t)
                  ("" "xunicode" t)
                  ("" "url" t)
                  ;; ("" "rotating" t)
                  ;; ("" "memoir-article-styles" t)
                  ;; ("american" "babel" t)
                  ;; ("babel" "csquotes" t)
                  ;; ("" "listings" nil)
                  ("svgnames" "xcolor" t)
                  ("" "soul" t)
                  ("xetex, colorlinks=true, urlcolor=FireBrick, plainpages=false, pdfpagelabels, bookmarksnumbered" "hyperref" nil)
                  ))
          (setq org-latex-classes
                (cons '("memarticle"
                        "\\documentclass[11pt,oneside,article]{memoir}"
                        ("\\section{%s}" . "\\section*{%s}")
                        ("\\subsection{%s}" . "\\subsection*{%s}")
                        ("\\subsubsection{%s}" . "\\subsubsection*{%s}")
                        ("\\paragraph{%s}" . "\\paragraph*{%s}")
                        ("\\subparagraph{%s}" . "\\subparagraph*{%s}"))
                      org-latex-classes))))

    (setq org-latex-pdf-process (list texcmd))))
(add-hook 'org-export-before-parsing-hook 'my-auto-tex-cmd)
</code>```

Body:
I used the latest master version 0.200.10.x Spacemacs on emacs 25.3. I was trying to implement a function that is recommended by the orgmode documentation for allowing the user to define which Latex compiler he/she wants to use. I implemented the function but it did not seem to work. The latex compilation step keeps using pdflatex instead of xelatex as specified in the file header. So I was trying to figure out what adjustment to make.

;; Originally taken from Bruno Tavernier: http://thread.gmane.org/gmane.emacs.orgmode/31150/focus=31432
;; but adapted to use latexmk 4.20 or higher.
(defun my-auto-tex-cmd ()
  "When exporting from .org with latex, automatically run latex,
     pdflatex, or xelatex as appropriate, using latexmk."
  (let ((texcmd)))
  ;; default command: oldstyle latex via dvi
  (setq texcmd "latexmk -dvi -pdfps -quiet %f")
  ;; pdflatex -> .pdf
  (if (string-match "LATEX_CMD: pdflatex" (buffer-string))
      (setq texcmd "latexmk -pdf -quiet %f"))
  ;; xelatex -> .pdf
  (if (string-match "LATEX_CMD: xelatex" (buffer-string))
      (setq texcmd "latexmk -pdflatex=xelatex -pdf -quiet %f"))
  ;; LaTeX compilation command
  (setq org-latex-to-pdf-process (list texcmd)))

(add-hook 'org-export-latex-after-initial-vars-hook 'my-auto-tex-cmd)

According to the Spacemacs issues list I need to make a change in the spacemacs-configuration-layers setting a la:

dotspacemacs-configuration-layers '(
  (latex :variables latex-build-command "LaTeX"))

The problem is that making a change in the dotspacemacs-configuration-layers does not seem to let me apply the change based upon file specific settings.

Does anyone know the right way to implement this function above (my-auto-tex-cmd) in spacemacs?

Body:
I found the solution in a blog post .

The actual elisp code is:

;; Default packages included in every tex file, pdflatex or xelatex
(setq org-latex-packages-alist
      '(("" "graphicx" t)
        ("" "longtable" nil)
        ("" "float" nil)))

;; source: https://lists.gnu.org/archive/html/emacs-orgmode/2013-06/msg00240.html
(defun my-auto-tex-cmd (backend)
  "When exporting from .org with latex,
  automatically run latex, pdflatex, or xelatex as appropriate,
  using latexmk."
  (let ((texcmd))
    (setq texcmd "latexmk -pdf %f")
    (if (string-match "LATEX_CMD: pdflatex" (buffer-string))
        (progn
          (setq texcmd "latexmk -pdf -pdflatex='pdflatex -file-line-error --shell-escape -synctex=1' %f")
          (setq org-latex-default-packages-alist
                '(("AUTO" "inputenc" t)
                  ("T1"   "fontenc"   t)
                  (""     "fixltx2e"  nil)
                  (""     "wrapfig"   nil)
                  (""     "soul"      t)
                  (""     "textcomp"  t)
                  (""     "marvosym"  t)
                  (""     "wasysym"   t)
                  (""     "latexsym"  t)
                  (""     "amssymb"   t)
                  (""     "hyperref"  nil)))))
    (if (string-match "LATEX_CMD: xelatex" (buffer-string))
        (progn
          (setq texcmd "latexmk -pdflatex='xelatex -file-line-error --shell-escape -synctex=1' -pdf %f")
          (setq org-latex-default-packages-alist
                '(("" "fontspec" t)
                  ("" "xunicode" t)
                  ("" "url" t)
                  ;; ("" "rotating" t)
                  ;; ("" "memoir-article-styles" t)
                  ;; ("american" "babel" t)
                  ;; ("babel" "csquotes" t)
                  ;; ("" "listings" nil)
                  ("svgnames" "xcolor" t)
                  ("" "soul" t)
                  ("xetex, colorlinks=true, urlcolor=FireBrick, plainpages=false, pdfpagelabels, bookmarksnumbered" "hyperref" nil)
                  ))
          (setq org-latex-classes
                (cons '("memarticle"
                        "\\documentclass[11pt,oneside,article]{memoir}"
                        ("\\section{%s}" . "\\section*{%s}")
                        ("\\subsection{%s}" . "\\subsection*{%s}")
                        ("\\subsubsection{%s}" . "\\subsubsection*{%s}")
                        ("\\paragraph{%s}" . "\\paragraph*{%s}")
                        ("\\subparagraph{%s}" . "\\subparagraph*{%s}"))
                      org-latex-classes))))

    (setq org-latex-pdf-process (list texcmd))))
(add-hook 'org-export-before-parsing-hook 'my-auto-tex-cmd)


问:
Node js Application- Getting 'command not found' after connecting project to github
I made a node js application and I was using nodemon to restart the server whenever I made changes, I made a repository on github and connected my node project. Now I can't run nodemon because it says command not found. I'm not sure about how to fix it. </p>

答:
install nodeman globally and try again,
hopes you do have configuration file and package.json

npm install nodeman -g


问:
referring to vector vs row with grouped data in dplyr (R)
I'm having some trouble with advanced operations in dplyr with grouped data. I'm not sure how to specify if I want to refer to an observation-level value, and when I can specifically refer to the entire vector.

Sample data frame:

```<code>df <- as.data.frame(
  rbind(
    c(11990, 2011, 1, 1, 2010),
    c(11990, 2015, 1, 0, NA),
    c(11990, 2017, 2, 1, NA),
    c(11990, 2018, 2, 1, 2016),
    c(11990, 2019, 2, 1, 2019),
    c(11990, 2020, 1, 0, NA),
    c(22880, 2013, 1, 1, NA),
    c(22880, 2014, 1, 0, 2011),
    c(22880, 2015, 1, 1, NA),
    c(22880, 2018, 2, 0, 2014),
    c(22880, 2020, 2, 0, 1979)))
names(df) <- c("id", "year", "house_apt", "moved", "year_moved")

# > df
#       id year house_apt moved year_moved
# 1  11990 2011         1     1       2010
# 2  11990 2015         1     0         NA
# 3  11990 2017         2     1         NA
# 4  11990 2018         2     1       2016
# 5  11990 2019         2     1       2019
# 6  11990 2020         1     0         NA
# 7  22880 2013         1     1         NA
# 8  22880 2014         1     0       2011
# 9  22880 2015         1     1         NA
# 10 22880 2018         2     0       2014
# 11 22880 2020         2     0       1979
</code>```

If I do simple mutate operations:

```<code>library(dplyr)
df %>% mutate(year+2)
df %>% group_by(id) %>% mutate(year+2)
</code>```

It's pretty obvious that "year" here refers to each individual row value. This is the case even if I were to (for some reason) do it with a grouping. However, if I were to do the following two operations which involve a vector operation:

```<code>df %>% mutate(sum(year))
df %>% group_by(id) %>% mutate(sum(year))
</code>```

dplyr understands "year" as the entire vector of year values for that whole group.

However, now I am having a lot of trouble with an operation where it is ambiguous whether I want mutate to use the row-value or the entire vector. With my data frame, I want to create a variable a guessed moving year for individuals who moved but didn't record the moving date until a later survey instance. Note the data is extremely messy, with some nonsensical moving dates that we want to ignore.

Therefore, I want to create a "guess" value for each row where a person moved but no move_year is recorded. I want the operation to look through the entire vector of moving dates for each individual, subset to include only the ones earlier than the current year, and pick out the one that is the closest to the year for the current row. Granular example: If we look at row #3, the individual moved in that year, but there is no move date. Therefore we want to look at the entire year_moved vector for that person (2010, NA, NA, 2016, 2019, NA) and choose the one that is the closest to and preferably earlier than the row #3 value of year (2017). The guess value, therefore, would be 2016.

Getting the value we want with a given year and vector of values is simple:

```<code>year <- 2017
year_moved <- c(2010, 2016, 2017)
year_moved[which.min(year-(year_moved[year_moved<year & !is.na(year_moved)]))]
# [1] 2016
rm(year, year_moved)
</code>```

However, when I try this within a mutate function, it doesn't give me the same result.

```<code>df %>%
  group_by(id) %>%
  mutate(
    year_guess = ifelse(moved==1 & is.na(year_moved),
                        year_moved[which.min(year-(year_moved[year_moved<year]))],
                        NA))
# # A tibble: 11 x 6
# # Groups:   id [2]
#       id  year house_apt moved year_moved guess
#    <dbl> <dbl>     <dbl> <dbl>      <dbl> <dbl>
#  1 11990  2011         1     1       2010    NA
#  2 11990  2015         1     0         NA    NA
#  3 11990  2017         2     1         NA    NA
#  4 11990  2018         2     1       2016    NA
#  5 11990  2019         2     1       2019    NA
#  6 11990  2020         1     0         NA    NA
#  7 22880  2013         1     1         NA  2011
#  8 22880  2014         1     0       2011    NA
#  9 22880  2015         1     1         NA  2011
# 10 22880  2018         2     0       2014    NA
# 11 22880  2020         2     0       1979    NA
# Warning message:
# In year - (year_moved[year_moved < year & !is.na(year_moved)]) :
#   longer object length is not a multiple of shorter object length
</code>```

(Row 3 should be 2016 and Row 9 should be 2014.) I think part of it is my inability to specify whether I am interested in a row-value or a vector. Note that the first time I refer to "year_moved" (is.na(year_moved)), I am referring to the value in that row. When I refer to it within the which.min, I am trying to refer to the groupwise vector. When I refer to "year", I'm trying to refer to the value of the individual row I'm working in. Clearly things are a little muddled, and it's a broader problem I've been running into with many different applications. Can anyone provide guidance?

I've been writing my whole project using tidyverse so would like to continue if possible.

答:
I think the most straightforward way to modify your current attempt to get the right results is to wrap the guessing operation in sapply so that a guess is separately calculated for each year:

```<code>df %>%
    group_by(id) %>%
    mutate(
        year_guess = ifelse(
            moved==1 & is.na(year_moved),
            sapply(year, function(x) year_moved[which.min(x-(year_moved[year_moved < x]))]),
            NA)
        )
</code>```

I haven't been able to fully unpack the logic of how this works but I think as written your guessing procedure is a little bit complex to be easily vectorized (although it probably can be if you approach it in a slightly different way).

Output:

```<code># A tibble: 11 x 6
# Groups:   id [2]
      id  year house_apt moved year_moved year_guess
   <dbl> <dbl>     <dbl> <dbl>      <dbl>      <dbl>
 1 11990  2011         1     1       2010         NA
 2 11990  2015         1     0         NA         NA
 3 11990  2017         2     1         NA       2016
 4 11990  2018         2     1       2016         NA
 5 11990  2019         2     1       2019         NA
 6 11990  2020         1     0         NA         NA
 7 22880  2013         1     1         NA       2011
 8 22880  2014         1     0       2011         NA
 9 22880  2015         1     1         NA       2014
10 22880  2018         2     0       2014         NA
11 22880  2020         2     0       1979         NA
</code>```

Body:
I'm having some trouble with advanced operations in dplyr with grouped data. I'm not sure how to specify if I want to refer to an observation-level value, and when I can specifically refer to the entire vector.

Sample data frame:

df <- as.data.frame(
  rbind(
    c(11990, 2011, 1, 1, 2010),
    c(11990, 2015, 1, 0, NA),
    c(11990, 2017, 2, 1, NA),
    c(11990, 2018, 2, 1, 2016),
    c(11990, 2019, 2, 1, 2019),
    c(11990, 2020, 1, 0, NA),
    c(22880, 2013, 1, 1, NA),
    c(22880, 2014, 1, 0, 2011),
    c(22880, 2015, 1, 1, NA),
    c(22880, 2018, 2, 0, 2014),
    c(22880, 2020, 2, 0, 1979)))
names(df) <- c("id", "year", "house_apt", "moved", "year_moved")

# > df
#       id year house_apt moved year_moved
# 1  11990 2011         1     1       2010
# 2  11990 2015         1     0         NA
# 3  11990 2017         2     1         NA
# 4  11990 2018         2     1       2016
# 5  11990 2019         2     1       2019
# 6  11990 2020         1     0         NA
# 7  22880 2013         1     1         NA
# 8  22880 2014         1     0       2011
# 9  22880 2015         1     1         NA
# 10 22880 2018         2     0       2014
# 11 22880 2020         2     0       1979

If I do simple mutate operations:

library(dplyr)
df %>% mutate(year+2)
df %>% group_by(id) %>% mutate(year+2)

It's pretty obvious that "year" here refers to each individual row value. This is the case even if I were to (for some reason) do it with a grouping. However, if I were to do the following two operations which involve a vector operation:

df %>% mutate(sum(year))
df %>% group_by(id) %>% mutate(sum(year))

dplyr understands "year" as the entire vector of year values for that whole group.

However, now I am having a lot of trouble with an operation where it is ambiguous whether I want mutate to use the row-value or the entire vector. With my data frame, I want to create a variable a guessed moving year for individuals who moved but didn't record the moving date until a later survey instance. Note the data is extremely messy, with some nonsensical moving dates that we want to ignore.

Therefore, I want to create a "guess" value for each row where a person moved but no move_year is recorded. I want the operation to look through the entire vector of moving dates for each individual, subset to include only the ones earlier than the current year, and pick out the one that is the closest to the year for the current row. Granular example: If we look at row #3, the individual moved in that year, but there is no move date. Therefore we want to look at the entire year_moved vector for that person (2010, NA, NA, 2016, 2019, NA) and choose the one that is the closest to and preferably earlier than the row #3 value of year (2017). The guess value, therefore, would be 2016.

Getting the value we want with a given year and vector of values is simple:

year <- 2017
year_moved <- c(2010, 2016, 2017)
year_moved[which.min(year-(year_moved[year_moved<year & !is.na(year_moved)]))]
# [1] 2016
rm(year, year_moved)

However, when I try this within a mutate function, it doesn't give me the same result.

df %>%
  group_by(id) %>%
  mutate(
    year_guess = ifelse(moved==1 & is.na(year_moved),
                        year_moved[which.min(year-(year_moved[year_moved<year]))],
                        NA))
# # A tibble: 11 x 6
# # Groups:   id [2]
#       id  year house_apt moved year_moved guess
#    <dbl> <dbl>     <dbl> <dbl>      <dbl> <dbl>
#  1 11990  2011         1     1       2010    NA
#  2 11990  2015         1     0         NA    NA
#  3 11990  2017         2     1         NA    NA
#  4 11990  2018         2     1       2016    NA
#  5 11990  2019         2     1       2019    NA
#  6 11990  2020         1     0         NA    NA
#  7 22880  2013         1     1         NA  2011
#  8 22880  2014         1     0       2011    NA
#  9 22880  2015         1     1         NA  2011
# 10 22880  2018         2     0       2014    NA
# 11 22880  2020         2     0       1979    NA
# Warning message:
# In year - (year_moved[year_moved < year & !is.na(year_moved)]) :
#   longer object length is not a multiple of shorter object length

(Row 3 should be 2016 and Row 9 should be 2014.) I think part of it is my inability to specify whether I am interested in a row-value or a vector. Note that the first time I refer to "year_moved" (is.na(year_moved)), I am referring to the value in that row. When I refer to it within the which.min, I am trying to refer to the groupwise vector. When I refer to "year", I'm trying to refer to the value of the individual row I'm working in. Clearly things are a little muddled, and it's a broader problem I've been running into with many different applications. Can anyone provide guidance?

I've been writing my whole project using tidyverse so would like to continue if possible.

Body:
I think the most straightforward way to modify your current attempt to get the right results is to wrap the guessing operation in sapply so that a guess is separately calculated for each year:

df %>%
    group_by(id) %>%
    mutate(
        year_guess = ifelse(
            moved==1 & is.na(year_moved),
            sapply(year, function(x) year_moved[which.min(x-(year_moved[year_moved < x]))]),
            NA)
        )

I haven't been able to fully unpack the logic of how this works but I think as written your guessing procedure is a little bit complex to be easily vectorized (although it probably can be if you approach it in a slightly different way).

Output:

# A tibble: 11 x 6
# Groups:   id [2]
      id  year house_apt moved year_moved year_guess
   <dbl> <dbl>     <dbl> <dbl>      <dbl>      <dbl>
 1 11990  2011         1     1       2010         NA
 2 11990  2015         1     0         NA         NA
 3 11990  2017         2     1         NA       2016
 4 11990  2018         2     1       2016         NA
 5 11990  2019         2     1       2019         NA
 6 11990  2020         1     0         NA         NA
 7 22880  2013         1     1         NA       2011
 8 22880  2014         1     0       2011         NA
 9 22880  2015         1     1         NA       2014
10 22880  2018         2     0       2014         NA
11 22880  2020         2     0       1979         NA


问:
Take a number input, iterate up to the top of a given range and output numbers into a file
I'm hoping to get my Ruby script to start at an inputted number, say 100, and itterate all the way up to the end of the range; 1000. Having all the numbers in between saved to a file.

This is a code I have so far:

```<code>#!/usr/bin/env ruby

if ARGV.length ==0;
 puts "Enter the start number"
 else puts ARGV.size
ARGV.each do |a|

for i in 0..1000 do
 puts i;

     end
 end
end
</code>```

To run it I'm typing:

```<code>ruby increment.rb 100 > increment.txt
</code>```

However, it ignores the input number and starts at 1 regardless.

What am I doing wrong?

答:
ARGV is an array and the first argument is stored in ARGV[0] second in ARGV[1] etc</p>

```<code>if ARGV[0]
  start = ARGV[0].to_i
else
  puts "Enter the start number"
  start = gets.to_i
end

(start .. 1000).each do |i|
  puts i
end
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I'm hoping to get my Ruby script to start at an inputted number, say 100, and itterate all the way up to the end of the range; 1000. Having all the numbers in between saved to a file.

This is a code I have so far:

#!/usr/bin/env ruby

if ARGV.length ==0;
 puts "Enter the start number"
 else puts ARGV.size
ARGV.each do |a|

for i in 0..1000 do
 puts i;

     end
 end
end

To run it I'm typing:

ruby increment.rb 100 > increment.txt

However, it ignores the input number and starts at 1 regardless.

What am I doing wrong?

Body:
ARGV is an array and the first argument is stored in ARGV[0] second in ARGV[1] etc

if ARGV[0]
  start = ARGV[0].to_i
else
  puts "Enter the start number"
  start = gets.to_i
end

(start .. 1000).each do |i|
  puts i
end


问:
Magento 1.7.0.2 - One Page Checkout Continue Button not Working
good morning everyone. I'm having trouble solving this problem with magento. The error shown is as follows:

```<code>Uncaught TypeError: Cannot read property 'setMethod' of undefined
at HTMLButtonElement.onclick ((index):824)
</code>```

It occurs every time i click in continue button on the onepagecheckout page and it will not let me advance to make the purchase as a gust or to register a new acc.
Can anybody help me? I've tried so much and nothing seems to work.

答:
Please go to the admin panel.

System->Configurations->Sales->ShippingMethods

And then disable the below methods:

UPS
USPS
FedEx
DHL (Deprecated)
DHL

It should work after.

Body:
good morning everyone. I'm having trouble solving this problem with magento. The error shown is as follows:

Uncaught TypeError: Cannot read property 'setMethod' of undefined
at HTMLButtonElement.onclick ((index):824)

It occurs every time i click in continue button on the onepagecheckout page and it will not let me advance to make the purchase as a gust or to register a new acc.
Can anybody help me? I've tried so much and nothing seems to work.


问:
LLVM Optimization Using C++ API
I'm trying to figure out how to perform all optimizations on an LLVM Module (e.g., all -O3 optimizations).  I've tried the following but I'm not sure that all possible optimizations are being applied (e.g., inlining).

```<code>//take string "llvm" (LLVM IR) and return "output_llvm" (optimized LLVM IR)
static string optimize(string llvm) {
    LLVMContext &ctx = getGlobalContext();
    SMDiagnostic err;
    Module *ir = ParseIR(MemoryBuffer::getMemBuffer(llvm), err, ctx);
    PassManager *pm = new PassManager();
    PassManagerBuilder builder;
    builder.OptLevel = 3;
    builder.populateModulePassManager(*pm);
    pm->run(*ir);
    delete pm;
    string output_llvm;
    raw_string_ostream buff(output_llvm);
    ir->print(buff, NULL);
    return output_llvm;
}
</code>```

Is there anything else I can do to improve the performance of the output LLVM IR?

EDIT: I have tried to add all of the optimizations from the AddOptimizationPasses() function in opt.cpp, as shown below:

```<code>PassManager *pm = new PassManager();
int optLevel = 3;
int sizeLevel = 0;
PassManagerBuilder builder;
builder.OptLevel = optLevel;
builder.SizeLevel = sizeLevel;
builder.Inliner = createFunctionInliningPass(optLevel, sizeLevel);
builder.DisableUnitAtATime = false;
builder.DisableUnrollLoops = false;
builder.LoopVectorize = true;
builder.SLPVectorize = true;
builder.populateModulePassManager(*pm);
pm->run(*module);
</code>```

Also, I create a FunctionPassManager before I create the PassManager and add several passes like so:

```<code>FunctionPassManager *fpm = new FunctionPassManager(module);
// add several passes
fpm->doInitialization();
for (Function &f : *ir)
    fpm->run(f);
fpm->doFinalization();
</code>```

However, the performance is the same as running on the command line with -O1 whereas I can get much better performance on the command line using -O3.  Any suggestions?

答:
While looking into LLVM optimization I found this information on pass ordering and I think it's potentially telling for why someone might encounter this situation.

Depending on your language and the optimizations you're expecting, you may need to specifically tune your optimizing passes to your use-cases.  In particular, the ordering of those passes may be important.  For example, if your better -O3 code was optimizing completely un-optimized code or code that was already partially optimized by your program, it may just be that you need to re-order or duplicate some passes in order to the expected final result.

Given the specific wording here and the fact that Eli's answer was accepted I'm not 100% sure if this is what the OP was seeing but this knowledge may be helpful for others with similar questions who find this answer like I did.

Title: LLVM Optimization Using C++ API

Body:
I'm trying to figure out how to perform all optimizations on an LLVM Module (e.g., all -O3 optimizations).  I've tried the following but I'm not sure that all possible optimizations are being applied (e.g., inlining).

//take string "llvm" (LLVM IR) and return "output_llvm" (optimized LLVM IR)
static string optimize(string llvm) {
    LLVMContext &ctx = getGlobalContext();
    SMDiagnostic err;
    Module *ir = ParseIR(MemoryBuffer::getMemBuffer(llvm), err, ctx);
    PassManager *pm = new PassManager();
    PassManagerBuilder builder;
    builder.OptLevel = 3;
    builder.populateModulePassManager(*pm);
    pm->run(*ir);
    delete pm;
    string output_llvm;
    raw_string_ostream buff(output_llvm);
    ir->print(buff, NULL);
    return output_llvm;
}

Is there anything else I can do to improve the performance of the output LLVM IR?

EDIT: I have tried to add all of the optimizations from the AddOptimizationPasses() function in opt.cpp, as shown below:

PassManager *pm = new PassManager();
int optLevel = 3;
int sizeLevel = 0;
PassManagerBuilder builder;
builder.OptLevel = optLevel;
builder.SizeLevel = sizeLevel;
builder.Inliner = createFunctionInliningPass(optLevel, sizeLevel);
builder.DisableUnitAtATime = false;
builder.DisableUnrollLoops = false;
builder.LoopVectorize = true;
builder.SLPVectorize = true;
builder.populateModulePassManager(*pm);
pm->run(*module);

Also, I create a FunctionPassManager before I create the PassManager and add several passes like so:

FunctionPassManager *fpm = new FunctionPassManager(module);
// add several passes
fpm->doInitialization();
for (Function &f : *ir)
    fpm->run(f);
fpm->doFinalization();

However, the performance is the same as running on the command line with -O1 whereas I can get much better performance on the command line using -O3.  Any suggestions?


问:
error in grunt-saas, even though saas is installed?
I am using Mac OSX.
gem install saas is done.
ruby is also update.
still show Warning: spawn sass ENOENT
Couldn't understand why?

答:
have you updated your xcode?

Here's what worked for me. From "iamcubcs"

https://github.com/oklai/koala/issues/679

Open Terminal

Install Homebrew:

 ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

Do not close Terminal, open Mac Appstore and check Update, install all XCode Command Line Tools updates OR in my case, XCode Command Line Tools started install automaticly throught Terminal right after step 2.

Back to Terminal

Install Ruby:

brew install rbenv ruby-build

Install SASS gem:

sudo gem install -n /usr/local/bin sass


问:
Excel does not Quit C#
I am writing this particular code in C# to write to an excel file.

```<code>public partial class WriteExcelForm : Form
{
    public WriteExcelForm()
    {
        InitializeComponent();
    }

    private void writeExcelButton_Click(object sender, EventArgs e)
    {
        Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
        if (xlApp == null)
        {
            MessageBox.Show("Excel is not installed!!!");
            return;
        }

        Excel.Workbooks xlWorkBooks = xlApp.Workbooks;
        Excel.Workbook xlWorkBook = xlWorkBooks.Add(Type.Missing);
        Excel.Worksheet xlWorkSheet = xlWorkBook.ActiveSheet;
        xlWorkSheet.Name = "sample";

        Excel.Range range1 = (Excel.Range)xlWorkSheet.Cells[1, 1];
        range1.Value = "dhiraj";

        Excel.Range range2 = xlWorkSheet.Range["A2"];
        range2.Value = "dhiraj";

        xlWorkBook.SaveAs("C:\\output.xlsx");

        //Properly closing the excel app
        GC.Collect();
        GC.WaitForPendingFinalizers();

        xlWorkBook.Close(false, Type.Missing, Type.Missing);
        xlApp.Quit();

        Marshal.FinalReleaseComObject(range1);
        Marshal.FinalReleaseComObject(range2);
        Marshal.FinalReleaseComObject(xlWorkSheet);
        Marshal.FinalReleaseComObject(xlWorkBook);
        Marshal.FinalReleaseComObject(xlWorkBooks);
        Marshal.FinalReleaseComObject(xlApp);
    }
}
</code>```

If I run this code, the excel.exe does not quit, but keeps on hanging around in the background.

However, if I comment out this particular line

```<code>        Excel.Range range1 = (Excel.Range)xlWorkSheet.Cells[1, 1];
        range1.Value = "dhiraj";
</code>```

the excel.exe quits elegantly.

What am I missing here?

EDIT:
I have solved my issue. Posting my findings as answer.

P.S: Do not know why I was down voted, I did research a lot before posting this question.

答:
So, I continued my research after asking the question, and I found this particular link
How do I properly clean up Excel interop objects?

Now in this particular link, three answers which when put together helped me out.

First answer is this particular one https://stackoverflow.com/a/158752/2241802
It says to avoid using "Never use two dots with COM objects".

Second answer is this one https://stackoverflow.com/a/159419/2241802
This answer refers to how to use excel object practically and it is very important to follow this, since I will not be the only developer working on my piece of code.

The third answer https://stackoverflow.com/a/1893653/2241802
talks about the how Garbage Collector behavior differs in Release mode and Debug mode.

So that was my problem, when i ran the code pasted in the question in Release mode, it worked fine and the excel.exe quit gracefully.

However, to make it work in the Debug mode I took the suggestion of the Thrid Answer link above and created a function which implemented the excel writing stuff.

Title: Excel does not Quit C#

Body:
I am writing this particular code in C# to write to an excel file.

public partial class WriteExcelForm : Form
{
    public WriteExcelForm()
    {
        InitializeComponent();
    }

    private void writeExcelButton_Click(object sender, EventArgs e)
    {
        Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
        if (xlApp == null)
        {
            MessageBox.Show("Excel is not installed!!!");
            return;
        }

        Excel.Workbooks xlWorkBooks = xlApp.Workbooks;
        Excel.Workbook xlWorkBook = xlWorkBooks.Add(Type.Missing);
        Excel.Worksheet xlWorkSheet = xlWorkBook.ActiveSheet;
        xlWorkSheet.Name = "sample";

        Excel.Range range1 = (Excel.Range)xlWorkSheet.Cells[1, 1];
        range1.Value = "dhiraj";

        Excel.Range range2 = xlWorkSheet.Range["A2"];
        range2.Value = "dhiraj";

        xlWorkBook.SaveAs("C:\\output.xlsx");

        //Properly closing the excel app
        GC.Collect();
        GC.WaitForPendingFinalizers();

        xlWorkBook.Close(false, Type.Missing, Type.Missing);
        xlApp.Quit();

        Marshal.FinalReleaseComObject(range1);
        Marshal.FinalReleaseComObject(range2);
        Marshal.FinalReleaseComObject(xlWorkSheet);
        Marshal.FinalReleaseComObject(xlWorkBook);
        Marshal.FinalReleaseComObject(xlWorkBooks);
        Marshal.FinalReleaseComObject(xlApp);
    }
}

If I run this code, the excel.exe does not quit, but keeps on hanging around in the background.

However, if I comment out this particular line

        Excel.Range range1 = (Excel.Range)xlWorkSheet.Cells[1, 1];
        range1.Value = "dhiraj";

the excel.exe quits elegantly.

What am I missing here?

EDIT:
I have solved my issue. Posting my findings as answer.

P.S: Do not know why I was down voted, I did research a lot before posting this question.


问:
Required validator not working with async field
I'm having a problem that seems to be caused by the "required" validator not working with a form field that is updated asynchronously from an AngularFire database.  When I try to edit an existing user, even though the "username" and "email" inputs both contain the existing user's values, Angular seems to be considering each <input> empty until I type in them.  I can see that behavior because the Submit button is disabled until I type in each <input>.

Here's my component

```<code>import { Component } from '@angular/core';
import { FormBuilder, FormGroup, ReactiveFormsModule, Validators } from '@angular/forms';
import { Router, ActivatedRoute } from '@angular/router';
import { AngularFireDatabase } from 'angularfire2/database';

import { User } from './user';

@Component({
    selector: 'user-form',
    templateUrl: 'user-form.component.html'
})
export class UserFormComponent {
    key;
    item;
    form: FormGroup;
    user = new User();

    constructor(fb: FormBuilder, private _router: Router, private _route:ActivatedRoute, private db: AngularFireDatabase) {
        this.form = fb.group({
            username: ['', Validators.required],
            email: ['', Validators.required]
        })
    };

    ngOnInit() {
        this._route.params.subscribe(params => {
            this.key = params["key"];
        })

        if (!this.key) {
            this.title = "New User";
        }
        else {
            // This is the path that is followed for editing an existing user
            this.title = "Edit User";
            this.item = this.db.object(this.key).valueChanges();
        }
    }
}
</code>```

Here's my view

```<code><form [formGroup]="form" (ngSubmit)="submit()">
    <div class="form-group">
        <label for="username">Username</label>
        <input [(ngModel)]="user.username" type="text" class="form-control" formControlName="username" value={{(item|async)?.name}}>
        <div *ngIf="form.controls.username.touched && !form.controls.username.valid" class="alert alert-danger">
            Username is required
        </div>
    </div>
    <div class="form-group">
        <label for="email">Email</label>
        <input [(ngModel)]="user.email" type="text" class="form-control" formControlName="email" value={{(item|async)?.email}}>
        <div *ngIf="form.controls.email.touched && !form.controls.email.valid" class="alert alert-danger">
            Email is required
        </div>
    </div>
    <button [disabled]="!form.valid" class="btn btn-primary" type="submit">Submit</button>
</form>
</code>```

I can further confirm that Angular sees my <input>s as empty because if I tab into one of the fields and then tab out of it without typing anything, the
 that shows the error message appears.

Why does Angular consider both of my <input>s empty when I'm editing an existing user?  Is there a different way that I have to handle the "required" validator since I'm using the async pipe?

答:
I'm certain your console should be full of errors. You're not allowed to use ngModel within a FormGroup. You either use template driven forms (FormsModule) or model driven forms (ReactiveFormsModule), but you can't use both within each other.

Remove the ngModel and value stuff. To set the value of a form when using ReactiveFormsModule, you use the methods setValue() or patchValue():

```<code>this.form.setValue({
    username: 'example',
    email: 'example@gmail.com'
});
</code>```

Or you can set a single FormControl value:

```<code>this.form.get('username').setValue('example')
</code>```

Body:
I'm having a problem that seems to be caused by the "required" validator not working with a form field that is updated asynchronously from an AngularFire database.  When I try to edit an existing user, even though the "username" and "email" inputs both contain the existing user's values, Angular seems to be considering each <input> empty until I type in them.  I can see that behavior because the Submit button is disabled until I type in each <input>.

Here's my component

import { Component } from '@angular/core';
import { FormBuilder, FormGroup, ReactiveFormsModule, Validators } from '@angular/forms';
import { Router, ActivatedRoute } from '@angular/router';
import { AngularFireDatabase } from 'angularfire2/database';

import { User } from './user';

@Component({
    selector: 'user-form',
    templateUrl: 'user-form.component.html'
})
export class UserFormComponent {
    key;
    item;
    form: FormGroup;
    user = new User();

    constructor(fb: FormBuilder, private _router: Router, private _route:ActivatedRoute, private db: AngularFireDatabase) {
        this.form = fb.group({
            username: ['', Validators.required],
            email: ['', Validators.required]
        })
    };

    ngOnInit() {
        this._route.params.subscribe(params => {
            this.key = params["key"];
        })

        if (!this.key) {
            this.title = "New User";
        }
        else {
            // This is the path that is followed for editing an existing user
            this.title = "Edit User";
            this.item = this.db.object(this.key).valueChanges();
        }
    }
}

Here's my view

<form [formGroup]="form" (ngSubmit)="submit()">

        Username
        <input [(ngModel)]="user.username" type="text" class="form-control" formControlName="username" value={{(item|async)?.name}}>

            Username is required

        Email
        <input [(ngModel)]="user.email" type="text" class="form-control" formControlName="email" value={{(item|async)?.email}}>

            Email is required

    <button [disabled]="!form.valid" class="btn btn-primary" type="submit">Submit</button>
</form>

I can further confirm that Angular sees my <input>s as empty because if I tab into one of the fields and then tab out of it without typing anything, the
 that shows the error message appears.

Why does Angular consider both of my <input>s empty when I'm editing an existing user?  Is there a different way that I have to handle the "required" validator since I'm using the async pipe?

Body:
I'm certain your console should be full of errors. You're not allowed to use ngModel within a FormGroup. You either use template driven forms (FormsModule) or model driven forms (ReactiveFormsModule), but you can't use both within each other.

Remove the ngModel and value stuff. To set the value of a form when using ReactiveFormsModule, you use the methods setValue() or patchValue():

this.form.setValue({
    username: 'example',
    email: 'example@gmail.com'
});

Or you can set a single FormControl value:

this.form.get('username').setValue('example')


问:
Consolidate / Manipulate array of objects
I have an array of objects like the following:

```<code>[{
  animal: "cat",
  dateString: "2017-01-03"
},{
  animal: "dog",
  dateString: "2017-02-05"
},{
  animal: "cat",
  dateString: "2017-03-04"
}]
</code>```

and I'd like to create a new array that looks like:

```<code>[{
  animal: "cat",
  values: [
    "2017-01-03",
    "2017-03-04"
  ]
},{
  animal: "dog",
  values: [
    "2017-02-05"
  ]
}]
</code>```

How can I consolidate the individual object properties into an array of values?

答:
You can use array#reduce to store your object in a new object where values will be grouped on based on animal name. Then, use Object.values to get the result.

var data = [{ animal: "cat", dateString: "2017-01-03" },{ animal: "dog", dateString: "2017-02-05" },{ animal: "cat", dateString: "2017-03-04" }];

var result = data.reduce((o, {animal, dateString}) => {
  o[animal] ? o[animal].values.push(dateString) : o[animal] = {animal, values: [dateString]}
  return o;
},{});

var output = Object.values(result);
console.log(output);```

Body:
I have an array of objects like the following:

[{
  animal: "cat",
  dateString: "2017-01-03"
},{
  animal: "dog",
  dateString: "2017-02-05"
},{
  animal: "cat",
  dateString: "2017-03-04"
}]

and I'd like to create a new array that looks like:

[{
  animal: "cat",
  values: [
    "2017-01-03",
    "2017-03-04"
  ]
},{
  animal: "dog",
  values: [
    "2017-02-05"
  ]
}]

How can I consolidate the individual object properties into an array of values?


问:
images wont line up and the text wont go under the img
I am trying to get some images to line up in my content box, but they wont go side by side. Instead they go on each their line. The text are also supposed to go under the image and not to the right of it. Can anyone see the reason why?

I also need to find a way to get them lined up horizontally even if the text under the image are in different lengths up to 30 characters.

Fiddle link: https://fiddle.jshell.net/jkyq9y0u/

```<code><div id="content_box">
  <div id="img">
    <a href="link" class="style_title" target="_blank">
      <div id="image_id" class="image_box">
        <img class="movie_img" src="https://images-na.ssl-images-amazon.com/images/M/MV5BOGNkMzliMGMtMDI5Ni00OTZkLTgyMTYtNzk5ZTY1NjVhYjVmXkEyXkFqcGdeQXVyNTAzMTY4MDA@._V1_UY209_CR0,0,140,209_AL_.jpg">
      </div>
      <div class="title">The Disaster Artist (2017)</div>
    </a>
    <a href="link" class="style_title" target="_blank">
      <div id="image_id" class="image_box">
        <img class="movie_img" src="https://images-na.ssl-images-amazon.com/images/M/MV5BOGNkMzliMGMtMDI5Ni00OTZkLTgyMTYtNzk5ZTY1NjVhYjVmXkEyXkFqcGdeQXVyNTAzMTY4MDA@._V1_UY209_CR0,0,140,209_AL_.jpg">
      </div>
      <div class="title">The Disaster Artist (2017)</div>
    </a>
    <a href="link" class="style_title" target="_blank">
      <div id="image_id" class="image_box">
        <img class="movie_img" src="https://images-na.ssl-images-amazon.com/images/M/MV5BOGNkMzliMGMtMDI5Ni00OTZkLTgyMTYtNzk5ZTY1NjVhYjVmXkEyXkFqcGdeQXVyNTAzMTY4MDA@._V1_UY209_CR0,0,140,209_AL_.jpg">
      </div>
      <div class="title">The Disaster Artist (2017)</div>
    </a>
    <a href="link" class="style_title" target="_blank">
      <div id="image_id" class="image_box">
        <img class="movie_img" src="https://images-na.ssl-images-amazon.com/images/M/MV5BOGNkMzliMGMtMDI5Ni00OTZkLTgyMTYtNzk5ZTY1NjVhYjVmXkEyXkFqcGdeQXVyNTAzMTY4MDA@._V1_UY209_CR0,0,140,209_AL_.jpg">
      </div>
      <div class="title">The Disaster Artist (2017)</div>
    </a>
    <a href="link" class="style_title" target="_blank">
      <div id="image_id" class="image_box">
        <img class="movie_img" src="https://images-na.ssl-images-amazon.com/images/M/MV5BOGNkMzliMGMtMDI5Ni00OTZkLTgyMTYtNzk5ZTY1NjVhYjVmXkEyXkFqcGdeQXVyNTAzMTY4MDA@._V1_UY209_CR0,0,140,209_AL_.jpg">
      </div>
      <div class="title">The Disaster Artist (2017)</div>
    </a>
    <a href="link" class="style_title" target="_blank">
      <div id="image_id" class="image_box">
        <img class="movie_img" src="https://images-na.ssl-images-amazon.com/images/M/MV5BOGNkMzliMGMtMDI5Ni00OTZkLTgyMTYtNzk5ZTY1NjVhYjVmXkEyXkFqcGdeQXVyNTAzMTY4MDA@._V1_UY209_CR0,0,140,209_AL_.jpg">
      </div>
      <div class="title">The Disaster Artist (2017)</div>
    </a>
  </div>
</div>

#content_box {
  background-color: #ffffff;
  min-width: 100%;
  min-height: 75vh;
  text-align: center;
  overflow-y: auto;
  display: inline-block;
}

/* styling for the movie images and titles */

#img {
  min-height: 100%;
  max-width: 60%;
  display: inline-block;
}

.image_box {
  min-width: 100%;
  min-height: 100%;
  display: inline-block;
}

.movie_img {
  max-width: 20%;
  height: auto;
  border-radius: 10px;
  display: inline-block;
}

.title {
  min-height: 100px;
  max-width: 100%;
  margin-bottom: 100px;
  display: inline-block;
}
</code>```

答:
You just need to make some changes in you css.
I've updated your code

#content_box {
  background-color: #ffffff;
  min-width: 100%;
  min-height: 75vh;
  text-align: center;
  overflow-y: auto;
  display: inline-block;
}

/* styling for the movie images and titles */

#img {
  min-height: 100%;
  max-width: 100%;
  display: inline-block;
  float: left;
}

.image_box {
  min-width: 100%;
  height: auto;
  display: inline-block;
}

.movie_img {
  max-width: 100%;
  height: auto;
  border-radius: 10px;
  display: inline-block;
}

.title {
  min-height: 100px;
  max-width: 100%;
  margin-bottom: 100px;
  display: inline-block;
}
#content{float: left;width: 100%;}
.style_title{width: 25%;float: left;padding: 5px;}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="content">
  <div id="img">

      <div id="image_id" class="image_box">
        <img class="movie_img" src="https://images-na.ssl-images-amazon.com/images/M/MV5BOGNkMzliMGMtMDI5Ni00OTZkLTgyMTYtNzk5ZTY1NjVhYjVmXkEyXkFqcGdeQXVyNTAzMTY4MDA@._V1_UY209_CR0,0,140,209_AL_.jpg">
      </div>
      <div class="title">The Disaster Artist (2017)</div>

      <div id="image_id" class="image_box">
        <img class="movie_img" src="https://images-na.ssl-images-amazon.com/images/M/MV5BOGNkMzliMGMtMDI5Ni00OTZkLTgyMTYtNzk5ZTY1NjVhYjVmXkEyXkFqcGdeQXVyNTAzMTY4MDA@._V1_UY209_CR0,0,140,209_AL_.jpg">
      </div>
      <div class="title">The Disaster Artist (2017)</div>

      <div id="image_id" class="image_box">
        <img class="movie_img" src="https://images-na.ssl-images-amazon.com/images/M/MV5BOGNkMzliMGMtMDI5Ni00OTZkLTgyMTYtNzk5ZTY1NjVhYjVmXkEyXkFqcGdeQXVyNTAzMTY4MDA@._V1_UY209_CR0,0,140,209_AL_.jpg">
      </div>
      <div class="title">The Disaster Artist (2017)</div>

      <div id="image_id" class="image_box">
        <img class="movie_img" src="https://images-na.ssl-images-amazon.com/images/M/MV5BOGNkMzliMGMtMDI5Ni00OTZkLTgyMTYtNzk5ZTY1NjVhYjVmXkEyXkFqcGdeQXVyNTAzMTY4MDA@._V1_UY209_CR0,0,140,209_AL_.jpg">
      </div>
      <div class="title">The Disaster Artist (2017)</div>

      <div id="image_id" class="image_box">
        <img class="movie_img" src="https://images-na.ssl-images-amazon.com/images/M/MV5BOGNkMzliMGMtMDI5Ni00OTZkLTgyMTYtNzk5ZTY1NjVhYjVmXkEyXkFqcGdeQXVyNTAzMTY4MDA@._V1_UY209_CR0,0,140,209_AL_.jpg">
      </div>
      <div class="title">The Disaster Artist (2017)</div>

      <div id="image_id" class="image_box">
        <img class="movie_img" src="https://images-na.ssl-images-amazon.com/images/M/MV5BOGNkMzliMGMtMDI5Ni00OTZkLTgyMTYtNzk5ZTY1NjVhYjVmXkEyXkFqcGdeQXVyNTAzMTY4MDA@._V1_UY209_CR0,0,140,209_AL_.jpg">
      </div>
      <div class="title">The Disaster Artist (2017)</div>

  </div>
</div></code>```

ContentLicense: CC BY-SA 4.0

Body:
I am trying to get some images to line up in my content box, but they wont go side by side. Instead they go on each their line. The text are also supposed to go under the image and not to the right of it. Can anyone see the reason why?

I also need to find a way to get them lined up horizontally even if the text under the image are in different lengths up to 30 characters.

Fiddle link: https://fiddle.jshell.net/jkyq9y0u/

The Disaster Artist (2017)

The Disaster Artist (2017)

The Disaster Artist (2017)

The Disaster Artist (2017)

The Disaster Artist (2017)

The Disaster Artist (2017)

#content_box {
  background-color: #ffffff;
  min-width: 100%;
  min-height: 75vh;
  text-align: center;
  overflow-y: auto;
  display: inline-block;
}

/* styling for the movie images and titles */

#img {
  min-height: 100%;
  max-width: 60%;
  display: inline-block;
}

.image_box {
  min-width: 100%;
  min-height: 100%;
  display: inline-block;
}

.movie_img {
  max-width: 20%;
  height: auto;
  border-radius: 10px;
  display: inline-block;
}

.title {
  min-height: 100px;
  max-width: 100%;
  margin-bottom: 100px;
  display: inline-block;
}

Body:
You just need to make some changes in you css.
I've updated your code

#content_box {
  background-color: #ffffff;
  min-width: 100%;
  min-height: 75vh;
  text-align: center;
  overflow-y: auto;
  display: inline-block;
}

/* styling for the movie images and titles */

#img {
  min-height: 100%;
  max-width: 100%;
  display: inline-block;
  float: left;
}

.image_box {
  min-width: 100%;
  height: auto;
  display: inline-block;
}

.movie_img {
  max-width: 100%;
  height: auto;
  border-radius: 10px;
  display: inline-block;
}

.title {
  min-height: 100px;
  max-width: 100%;
  margin-bottom: 100px;
  display: inline-block;
}
#content{float: left;width: 100%;}
.style_title{width: 25%;float: left;padding: 5px;}

<div id="content">
  <div id="img">
    <a href="link" class="style_title" target="_blank">
      <div id="image_id" class="image_box">
        <img class="movie_img" src="https://images-na.ssl-images-amazon.com/images/M/MV5BOGNkMzliMGMtMDI5Ni00OTZkLTgyMTYtNzk5ZTY1NjVhYjVmXkEyXkFqcGdeQXVyNTAzMTY4MDA@._V1_UY209_CR0,0,140,209_AL_.jpg">
      </div>
      <div class="title">The Disaster Artist (2017)</div>
    </a>
    <a href="link" class="style_title" target="_blank">
      <div id="image_id" class="image_box">
        <img class="movie_img" src="https://images-na.ssl-images-amazon.com/images/M/MV5BOGNkMzliMGMtMDI5Ni00OTZkLTgyMTYtNzk5ZTY1NjVhYjVmXkEyXkFqcGdeQXVyNTAzMTY4MDA@._V1_UY209_CR0,0,140,209_AL_.jpg">
      </div>
      <div class="title">The Disaster Artist (2017)</div>
    </a>
    <a href="link" class="style_title" target="_blank">
      <div id="image_id" class="image_box">
        <img class="movie_img" src="https://images-na.ssl-images-amazon.com/images/M/MV5BOGNkMzliMGMtMDI5Ni00OTZkLTgyMTYtNzk5ZTY1NjVhYjVmXkEyXkFqcGdeQXVyNTAzMTY4MDA@._V1_UY209_CR0,0,140,209_AL_.jpg">
      </div>
      <div class="title">The Disaster Artist (2017)</div>
    </a>
    <a href="link" class="style_title" target="_blank">
      <div id="image_id" class="image_box">
        <img class="movie_img" src="https://images-na.ssl-images-amazon.com/images/M/MV5BOGNkMzliMGMtMDI5Ni00OTZkLTgyMTYtNzk5ZTY1NjVhYjVmXkEyXkFqcGdeQXVyNTAzMTY4MDA@._V1_UY209_CR0,0,140,209_AL_.jpg">
      </div>
      <div class="title">The Disaster Artist (2017)</div>
    </a>
    <a href="link" class="style_title" target="_blank">
      <div id="image_id" class="image_box">
        <img class="movie_img" src="https://images-na.ssl-images-amazon.com/images/M/MV5BOGNkMzliMGMtMDI5Ni00OTZkLTgyMTYtNzk5ZTY1NjVhYjVmXkEyXkFqcGdeQXVyNTAzMTY4MDA@._V1_UY209_CR0,0,140,209_AL_.jpg">
      </div>
      <div class="title">The Disaster Artist (2017)</div>
    </a>
    <a href="link" class="style_title" target="_blank">
      <div id="image_id" class="image_box">
        <img class="movie_img" src="https://images-na.ssl-images-amazon.com/images/M/MV5BOGNkMzliMGMtMDI5Ni00OTZkLTgyMTYtNzk5ZTY1NjVhYjVmXkEyXkFqcGdeQXVyNTAzMTY4MDA@._V1_UY209_CR0,0,140,209_AL_.jpg">
      </div>
      <div class="title">The Disaster Artist (2017)</div>
    </a>
  </div>
</div>


问:
Custom UItableViewCell not loading Image? Swift 4
I'm new at Xcode and swift and ran into this bug. I've searched around a bit and could not find anything on this topic. I have an extension for UIImage that allows me to cache images to the phone here :

```<code>import UIKit

let imageCache = NSCache<AnyObject, AnyObject>()

extension UIImageView{

func loadImageUsingCacheWithUrlString(urlString : String)
{
    self.image = nil;
    // check cache for image first

    if let cachedImage = imageCache.object(forKey: urlString as AnyObject)  as? UIImage {
        self.image = cachedImage;
        return
    }

    let url = URL(string: urlString)
    URLSession.shared.dataTask(with: url!, completionHandler: { (data, response, error) in

        //download hit an error
        if error != nil {
            print(error!)
            return
        }
        DispatchQueue.main.async {

            if  let downloadedImage = UIImage(data: data!){
                imageCache.setObject(downloadedImage, forKey: urlString as AnyObject)
                self.image = downloadedImage
            }

        }
    }).resume()
  }
}
</code>```

It is not loading the image into a table views image view:( Ignore random text )

Table view not loading image

Here is also the UItableView from the main.storyboard:

Updated main.storyboard screen shot

Here is my cellForRowAt: indexPath method where the image is suppose to be loaded:

```<code> func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: "cellid" , for: indexPath) as! CustomChatTableViewCell;
    let gray = UIColor(red:0.94, green:0.94, blue:0.94, alpha:1.0)
    let red = UIColor(red:1.00, green:0.22, blue:0.37, alpha:1.0)

    let message = messages[indexPath.item]

    if message.toId == user?.toId{

    cell.messageBackground.backgroundColor = red
        cell.messageLabel.textColor = UIColor.white
    }
    else{
        cell.messageBackground.backgroundColor = gray
        cell.messageLabel.textColor = UIColor.black
    }

    cell.messageLabel.text = message.text

    if let imageUrl = message.imageUrl{
        print(imageUrl)
        cell.messageImage.loadImageUsingCacheWithUrlString(urlString: imageUrl)

        cell.messageImage.isHidden = false;
        cell.messageLabel.isHidden = true
        //cell.messageBackground.isHidden = true;
    }
    else
    {
        cell.messageImage.isHidden = true;
        cell.messageLabel.isHidden = false
        cell.messageBackground.isHidden = false;
    }

    return cell;
}
</code>```

Expected Result:

Images load into cells

Observed Result

Images dont load into the cells :(
these lines of code :

```<code>if let imageUrl = message.imageUrl{
        print(imageUrl)
        cell.messageImage.loadImageUsingCacheWithUrlString(urlString: imageUrl)
</code>```

Actually print a valid URL string for an image on my firebase database, which is confusing because It is not loading the image.

Important

I use the loadImageUsingCacheWithUrlString method in other parts of my project and it works fine so I don't think its the method.... whats going on?? thank you so much if you can solve this you are an amazing coder!!

I can put an image in the main.storyboard and it works... so I dont know what could be going wrong... :(

screen shot of updated main.storyboard

Image seems to be fine in Extension :

code with breakpoint and console showing

Not sure If the image Is being covered Up in Capture View Hierarchy :

View Hierarchy

答:
In your storyboard, the imageView messageImage is a subview of the view messageBackground. In your if-statement in cellForRow method, you are setting the messageBackground to be hidden

```<code>if let imageUrl = message.imageUrl{
    print(imageUrl)
    cell.messageImage.loadImageUsingCacheWithUrlString(urlString: imageUrl)

    cell.messageImage.isHidden = false;
    cell.messageLabel.isHidden = true
    cell.messageBackground.isHidden = true;  //THIS IS THE CULPRIT

}
</code>```

Since messageBackground is hidden, it's subviews are hidden as well. Might need to rethink your business logic here.

Body:
I'm new at Xcode and swift and ran into this bug. I've searched around a bit and could not find anything on this topic. I have an extension for UIImage that allows me to cache images to the phone here :

import UIKit

let imageCache = NSCache<AnyObject, AnyObject>()

extension UIImageView{

func loadImageUsingCacheWithUrlString(urlString : String)
{
    self.image = nil;
    // check cache for image first

    if let cachedImage = imageCache.object(forKey: urlString as AnyObject)  as? UIImage {
        self.image = cachedImage;
        return
    }

    let url = URL(string: urlString)
    URLSession.shared.dataTask(with: url!, completionHandler: { (data, response, error) in

        //download hit an error
        if error != nil {
            print(error!)
            return
        }
        DispatchQueue.main.async {

            if  let downloadedImage = UIImage(data: data!){
                imageCache.setObject(downloadedImage, forKey: urlString as AnyObject)
                self.image = downloadedImage
            }

        }
    }).resume()
  }
}

It is not loading the image into a table views image view:( Ignore random text )

Table view not loading image

Here is also the UItableView from the main.storyboard:

Updated main.storyboard screen shot

Here is my cellForRowAt: indexPath method where the image is suppose to be loaded:

 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: "cellid" , for: indexPath) as! CustomChatTableViewCell;
    let gray = UIColor(red:0.94, green:0.94, blue:0.94, alpha:1.0)
    let red = UIColor(red:1.00, green:0.22, blue:0.37, alpha:1.0)

    let message = messages[indexPath.item]

    if message.toId == user?.toId{

    cell.messageBackground.backgroundColor = red
        cell.messageLabel.textColor = UIColor.white
    }
    else{
        cell.messageBackground.backgroundColor = gray
        cell.messageLabel.textColor = UIColor.black
    }

    cell.messageLabel.text = message.text

    if let imageUrl = message.imageUrl{
        print(imageUrl)
        cell.messageImage.loadImageUsingCacheWithUrlString(urlString: imageUrl)

        cell.messageImage.isHidden = false;
        cell.messageLabel.isHidden = true
        //cell.messageBackground.isHidden = true;
    }
    else
    {
        cell.messageImage.isHidden = true;
        cell.messageLabel.isHidden = false
        cell.messageBackground.isHidden = false;
    }

    return cell;
}

Expected Result:

Images load into cells

Observed Result

Images dont load into the cells :(
these lines of code :

if let imageUrl = message.imageUrl{
        print(imageUrl)
        cell.messageImage.loadImageUsingCacheWithUrlString(urlString: imageUrl)

Actually print a valid URL string for an image on my firebase database, which is confusing because It is not loading the image.

Important

I use the loadImageUsingCacheWithUrlString method in other parts of my project and it works fine so I don't think its the method.... whats going on?? thank you so much if you can solve this you are an amazing coder!!

I can put an image in the main.storyboard and it works... so I dont know what could be going wrong... :(

screen shot of updated main.storyboard

Image seems to be fine in Extension :

code with breakpoint and console showing

Not sure If the image Is being covered Up in Capture View Hierarchy :

View Hierarchy

Body:
In your storyboard, the imageView messageImage is a subview of the view messageBackground. In your if-statement in cellForRow method, you are setting the messageBackground to be hidden

if let imageUrl = message.imageUrl{
    print(imageUrl)
    cell.messageImage.loadImageUsingCacheWithUrlString(urlString: imageUrl)

    cell.messageImage.isHidden = false;
    cell.messageLabel.isHidden = true
    cell.messageBackground.isHidden = true;  //THIS IS THE CULPRIT

}

Since messageBackground is hidden, it's subviews are hidden as well. Might need to rethink your business logic here.


问:
Timer_fd python ? is there an equivalent
I would like to know how to set a timer using python. I am currently using select.poll/epoll and creating a timerfd would have been the easiest method.

The other way i see it is after the loop check if any of my event passed time and execute their function.

Other method :

```<code>import select,time

timeout =0
epoll.register(rpm_file.fileno(), select.EPOLLPRI)

while True:
  events = epoll.poll(0)
  for fileno,event in events:
    #processing fd events...

  now = time.time()
  if now > timeout:
    # timeout events
</code>```

答:
This answer applies to Linux only.
You can try below python package called linuxfd, which includes a wrapper for timerfd:

https://github.com/FrankAbelbeck/linuxfd

It is indexed by python package indexes:

https://pypi.python.org/pypi/linuxfd/1.4.4

some example by the author:

https://abelbeck.wordpress.com/2014/01/24/more-on-linuxfd-an-example/

Body:
I would like to know how to set a timer using python. I am currently using select.poll/epoll and creating a timerfd would have been the easiest method.

The other way i see it is after the loop check if any of my event passed time and execute their function.

Other method :

import select,time

timeout =0
epoll.register(rpm_file.fileno(), select.EPOLLPRI)

while True:
  events = epoll.poll(0)
  for fileno,event in events:
    #processing fd events...

  now = time.time()
  if now > timeout:
    # timeout events


问:
Saving and retrieving temp files in R packages
How should I save a file in my R package?

In other words, the user of my package will download a remote text file, and I'd like that file to be available to the user the next time they load the package.

The function I've created currently saves the file using tempfile(). As it's written, the download will happen every time the function is called, and a new temp file will be created. I think this presents a problem - if the user runs the function many times, the /var folder will become bloated with temp files. To fix this, I'd like to check if the file already exists and use the existing version if it does instead of downloading it. Unfortunately, the path returned by tempfile() is lost when the function terminates, so the path is not available to check if the file exists the next time the function is called.

Can I save the file in my packge's /data directory. How do I find this directory from the user's current working directory?

Saving in a tempfile is not necessary. I'm more interested to learn how to persist data in my package.

Thank you.

答:
You can use tempdir() and then a fixed file name:

```<code>f <- file.path(tempdir(), "mypackage_thefile.csv")
if (file.exists(f)) {
   d <- read.csv(f)
} else {
   # download it and save to f
}
</code>```

These files are removed after each session (when the tempdir is deleted)
You can also provide the data with your package if it is not too large (read it with R and then save it as a compressed 'rds' file with saveRDS). But you can normally not have the user download it to the package directory (often write-protected).

To add data to a package, either put it in the data folder (use save to create a .RData file, for retrieval with data() ), or in the inst/extdata folder, in any appropriate format, for retrieval with

```<code>f <- system.file("extdata/filename", package="pkgname")
</code>```

See the writing R extensions manual

Body:
You can use tempdir() and then a fixed file name:

f <- file.path(tempdir(), "mypackage_thefile.csv")
if (file.exists(f)) {
   d <- read.csv(f)
} else {
   # download it and save to f
}

These files are removed after each session (when the tempdir is deleted)
You can also provide the data with your package if it is not too large (read it with R and then save it as a compressed 'rds' file with saveRDS). But you can normally not have the user download it to the package directory (often write-protected).

To add data to a package, either put it in the data folder (use save to create a .RData file, for retrieval with data() ), or in the inst/extdata folder, in any appropriate format, for retrieval with

f <- system.file("extdata/filename", package="pkgname")

See the writing R extensions manual


问:
Python: Is there any way to sort a dictionary by integer value
Is there any way to find value number in a dictionary, say 3, without knowing the key in python?

I do know that dictionaries do not have an order.

All i can get are arbitrary elements using
dict[dict.keys()[0]]

Thanks in advance.

答:
So, if i understand correctly, you are looking for all keys with the value 3. That can be achieved by itering through the keys and comparing:

```<code>output = []
for key, value in dict.items():
    if value == 3:
        output.append((key, value))

print(output)
</code>```

If you wanna simply sort by integer values, try:

```<code>sorted(dict.items(), key=lambda i:i[1])
</code>```

Body:
So, if i understand correctly, you are looking for all keys with the value 3. That can be achieved by itering through the keys and comparing:

output = []
for key, value in dict.items():
    if value == 3:
        output.append((key, value))

print(output)

If you wanna simply sort by integer values, try:

sorted(dict.items(), key=lambda i:i[1])


问:
Database Responding Oddly to Queries via PHP

I've currently been pulling my hair out on this problem for about a full day now. I am developing my first application. I'm actually pretty far into it (having established the login page several weeks ago, worked perfectly). Last night, I ran my app and it worked perfectly. I backed it up to my flash drive, tested it once more, and closed my laptop down for the night.

This morning I opened up the app to begin the documentation process on it -- this is a project for my capstone so I have to document/video the outcome each week -- and suddenly my tester account couldn't be authenticated. I tried registering a new one via the app, and it doesn't post the data to the database. Naturally, I assumed the database/server was having issues and contacted my host; in a two-hour long process, they verified that the database was working and it was simply in my code which hadn't been touched since the night before when it ran perfectly.

I've read that this sometimes happens with authentication through FireBase (i believe this is what it is called) and OAuth. I'm using neither and just doing the basic database reading/writing. I've not found any useful information on what to do through Google, probably due to the fact that the problem is just too complicated for a quick search... or I just don't know how to word it correctly.

```<code><?php
$connection = mysqli_connect("localhost", "SENSORED", "SENSORED", "SENSORED");

$username = $_POST["username"];
$password = $_POST["password"];

$statement = mysqli_prepare($connection, "SELECT * FROM user WHERE username = ? AND password = ?");
mysqli_stmt_bind_param($statement, "ss", $username, $password);
mysqli_stmt_execute($statement);

mysqli_stmt_store_result($statement);
mysqli_stmt_bind_result($statement, $user_id, $name, $username, $email, $company_id, $phone, $password, $leaveTime, $sickTime, $rateOfPay);

$response = array();
$response["success"] = false;

while(mysqli_stmt_fetch($statement)){
    $response["success"] = true;
    $response["user_id"] = $user_id;
    $response["name"] = $name;
    $response["username"] = $username;
    $response["email"] = $email;
    $response["company_id"] = $company_id;
    $response["phone"] = $phone;
    $response["password"] = $password;
    $response["leaveTime"] = $leaveTime;
    $response["sickTime"] = $sickTime;
    $response["rateOfPay"] = $rateOfPay;
}

echo json_encode($response);
?>
</code>```

I did set up a connection test, which verified that the PHP is indeed connecting to the database and querying it. It can tell how many tables I have and, for example, how many usernames I have in the user table. However, when I enter:

```<code>"SELECT * FROM user WHERE username = 'test'"
</code>```

being that there is a username that is just 'test', it cannot find a match. However, I can see from looking at the database that test is indeed a username and does exist in that table.

I currently am getting no results via PHP. However, if I query via PHPmyadmin, it displays the row that contains 'test' as a username. Obviously, my coding is correct, but I'm not sure what could be interfering with selecting it from the PHP since it is establishing a connection and reading from the database. Not to mention the fact that it isn't wanting to write the registration information to the database when there are no holds on that.

I've gone as far in looking for a solution as creating a whole new database with different credentials and such and receive the same problem. Google has been no help in the search for an answer, and I haven't managed to find a similar question/problem on here.

Any idea how a working database connection and reading/writing abilities can completely disappear without being edited overnight?

答:
this is how I would do it.  As I said i haven't used MySqli in a number of years so I had to do some googling, and I am not 100% sure everything is correct as I can't really test it.

But here goes.

```<code> //turn on output buffering - useful for debugging
 ob_start();
//I would use the object interface
$mysqli = new mysqli("localhost", "SENSORED", "SENSORED", "SENSORED");

//your not checking the connection success
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$username = $_POST["username"];

//are you storing passwords in plain text?
$password = password_hash($_POST["password"]);

/*
 I would not pick the password from the DB, the DB is case insensitive,
 unless you use collation UTF8_bin or such.
 Also it's harder to debug, as you don't know if the user exists or the
 password matching is wrong.
*/
$stmt = $mysqli->prepare($connection, "SELECT * FROM user WHERE username = ?");

//bind the inputs
$stmt->bind_param("s", $username);

//execute the query
$res = $stmt->execute();

  //fetch results as an associative array
$row = $res->fetch_assoc();

//set default
$response["success"] = false;

/*
 We expect exactly 1 row be returned. More then 1 should
 be impossible if your username is unique (which is should be)
  but just in case any issues happen we should check that it's exactly
  1 return row, no more no less.
*/
if($res->num_rows() != 1) {
    //always be cordial in your error messages to users
    $response['message'] = "We're sorry we could not find user {$username}";
    return $response;
}

//check the password hash using an approved crypto-logically safe method
if(!hash_equals($password, $$row['password']) {
    $response['message'] = "Unfortunately the password you entered is incorrect";
    return $response;
}

//remove the password / we no longer need it.
//security is paramount, no need to risk exposing it, even when its hashed
//eg. I just spent the weekend fixing 5 wordpress sites that were hacked
unset($row['password']);

$response['message'] = "Success!";
//put the contents of the buffer into debug. only do this on localhost
//you could switch this using the HOST or server IP
$response['debug'] = ob_get_clean();

//combine the row with the response
//caution if key matched in rows exists in response value in row
//will be replaced with that of response ( it shouldn't be a problem in this case )
$response += $row;

//set the correct content type, this allows browsers to
//know this is json, and prevents having to do JSON.parse() in some cases
header('Content-type:application/json');

//encode the responce
echo json_encode($response);
</code>```

I put some notes in there such as this

```<code>//always be cordial in your error messages to users
</code>```

There was once a young web developer who had a client that complained his error messages were to "cold".  But this young web developer took his clients criticism to heart and remembered to always be extra nice to end users. ( that was around 2009).  That said, it hasn't improved my spelling.

One thing I ran across while refactoring this, is I noticed you are not encrypting the password.  I don't know if this is by mistake or by design.

ob_start and ob_get_clean allow you to echo or print_r stuff between them without breaking the JSON response.  Normally if you create output then it will be outside of your json data

```<code> here is some output
 {"success" : false}
</code>```

Which will cause errors on the client side. With output buffering the above will look like this

```<code>{"debug" : "here is some output", "success" : false}
</code>```

I suppose it's optional, but it's the right way to do JSON or even any content type other than HTML, including (or especially) file downloads.

Hope it helps.  Even if you cant use the code in this form, it may help seeing it written a different way.  Sometimes you can be to close to the problem and overlook some simple mistake.  Looking at it in another format and having to process the logic of it, may shed light on something you missed.

Body:
I've currently been pulling my hair out on this problem for about a full day now. I am developing my first application. I'm actually pretty far into it (having established the login page several weeks ago, worked perfectly). Last night, I ran my app and it worked perfectly. I backed it up to my flash drive, tested it once more, and closed my laptop down for the night.

This morning I opened up the app to begin the documentation process on it -- this is a project for my capstone so I have to document/video the outcome each week -- and suddenly my tester account couldn't be authenticated. I tried registering a new one via the app, and it doesn't post the data to the database. Naturally, I assumed the database/server was having issues and contacted my host; in a two-hour long process, they verified that the database was working and it was simply in my code which hadn't been touched since the night before when it ran perfectly.

I've read that this sometimes happens with authentication through FireBase (i believe this is what it is called) and OAuth. I'm using neither and just doing the basic database reading/writing. I've not found any useful information on what to do through Google, probably due to the fact that the problem is just too complicated for a quick search... or I just don't know how to word it correctly.

<?php
$connection = mysqli_connect("localhost", "SENSORED", "SENSORED", "SENSORED");

$username = $_POST["username"];
$password = $_POST["password"];

$statement = mysqli_prepare($connection, "SELECT * FROM user WHERE username = ? AND password = ?");
mysqli_stmt_bind_param($statement, "ss", $username, $password);
mysqli_stmt_execute($statement);

mysqli_stmt_store_result($statement);
mysqli_stmt_bind_result($statement, $user_id, $name, $username, $email, $company_id, $phone, $password, $leaveTime, $sickTime, $rateOfPay);

$response = array();
$response["success"] = false;

while(mysqli_stmt_fetch($statement)){
    $response["success"] = true;
    $response["user_id"] = $user_id;
    $response["name"] = $name;
    $response["username"] = $username;
    $response["email"] = $email;
    $response["company_id"] = $company_id;
    $response["phone"] = $phone;
    $response["password"] = $password;
    $response["leaveTime"] = $leaveTime;
    $response["sickTime"] = $sickTime;
    $response["rateOfPay"] = $rateOfPay;
}

echo json_encode($response);
?>

I did set up a connection test, which verified that the PHP is indeed connecting to the database and querying it. It can tell how many tables I have and, for example, how many usernames I have in the user table. However, when I enter:

"SELECT * FROM user WHERE username = 'test'"

being that there is a username that is just 'test', it cannot find a match. However, I can see from looking at the database that test is indeed a username and does exist in that table.

I currently am getting no results via PHP. However, if I query via PHPmyadmin, it displays the row that contains 'test' as a username. Obviously, my coding is correct, but I'm not sure what could be interfering with selecting it from the PHP since it is establishing a connection and reading from the database. Not to mention the fact that it isn't wanting to write the registration information to the database when there are no holds on that.

I've gone as far in looking for a solution as creating a whole new database with different credentials and such and receive the same problem. Google has been no help in the search for an answer, and I haven't managed to find a similar question/problem on here.

Any idea how a working database connection and reading/writing abilities can completely disappear without being edited overnight?

Body:
this is how I would do it.  As I said i haven't used MySqli in a number of years so I had to do some googling, and I am not 100% sure everything is correct as I can't really test it.

But here goes.

 //turn on output buffering - useful for debugging
 ob_start();
//I would use the object interface
$mysqli = new mysqli("localhost", "SENSORED", "SENSORED", "SENSORED");

//your not checking the connection success
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$username = $_POST["username"];

//are you storing passwords in plain text?
$password = password_hash($_POST["password"]);

/*
 I would not pick the password from the DB, the DB is case insensitive,
 unless you use collation UTF8_bin or such.
 Also it's harder to debug, as you don't know if the user exists or the
 password matching is wrong.
*/
$stmt = $mysqli->prepare($connection, "SELECT * FROM user WHERE username = ?");

//bind the inputs
$stmt->bind_param("s", $username);

//execute the query
$res = $stmt->execute();

  //fetch results as an associative array
$row = $res->fetch_assoc();

//set default
$response["success"] = false;

/*
 We expect exactly 1 row be returned. More then 1 should
 be impossible if your username is unique (which is should be)
  but just in case any issues happen we should check that it's exactly
  1 return row, no more no less.
*/
if($res->num_rows() != 1) {
    //always be cordial in your error messages to users
    $response['message'] = "We're sorry we could not find user {$username}";
    return $response;
}

//check the password hash using an approved crypto-logically safe method
if(!hash_equals($password, $$row['password']) {
    $response['message'] = "Unfortunately the password you entered is incorrect";
    return $response;
}

//remove the password / we no longer need it.
//security is paramount, no need to risk exposing it, even when its hashed
//eg. I just spent the weekend fixing 5 wordpress sites that were hacked
unset($row['password']);

$response['message'] = "Success!";
//put the contents of the buffer into debug. only do this on localhost
//you could switch this using the HOST or server IP
$response['debug'] = ob_get_clean();

//combine the row with the response
//caution if key matched in rows exists in response value in row
//will be replaced with that of response ( it shouldn't be a problem in this case )
$response += $row;

//set the correct content type, this allows browsers to
//know this is json, and prevents having to do JSON.parse() in some cases
header('Content-type:application/json');

//encode the responce
echo json_encode($response);

I put some notes in there such as this

//always be cordial in your error messages to users

There was once a young web developer who had a client that complained his error messages were to "cold".  But this young web developer took his clients criticism to heart and remembered to always be extra nice to end users. ( that was around 2009).  That said, it hasn't improved my spelling.

One thing I ran across while refactoring this, is I noticed you are not encrypting the password.  I don't know if this is by mistake or by design.

ob_start and ob_get_clean allow you to echo or print_r stuff between them without breaking the JSON response.  Normally if you create output then it will be outside of your json data

 here is some output
 {"success" : false}

Which will cause errors on the client side. With output buffering the above will look like this

{"debug" : "here is some output", "success" : false}

I suppose it's optional, but it's the right way to do JSON or even any content type other than HTML, including (or especially) file downloads.

Hope it helps.  Even if you cant use the code in this form, it may help seeing it written a different way.  Sometimes you can be to close to the problem and overlook some simple mistake.  Looking at it in another format and having to process the logic of it, may shed light on something you missed.


问:
Write attributes to a file in Apache NiFi
Hi,
I am using GetSNMP processor to connect a radio. As per the NiFi documentation, this information is written to flow file attributes not to flow file contents. So, I used AttributesToJSON processor. After that I used PutFile processor to write these attributes to a file. Files are generated but there are not attributes written there. Only "{}" is written in each of the file. Using LogAttribute processor , I can see all attributes in the log file but I want them in a separate file.
Please guide.

Thanks,

答:
SGaur,

If incoming flow file content is empty before putFile processor then it will writes empty content in local directory.

So you have to write attributes into flowfile content using ReplaceText.

For an example, You having this attributes like

${filename}-->input.1,
${input.content.1}-->content.1,
${input.content.2}-->content.2

comes before putFile.

Now you have to write those attributes into flow file content like below.,

In ReplaceText, Just mention replacement value to be like this-->

```<code>${filename},${input.content.1},${input.content.2}
</code>```

It will replace content like below.,

```<code>input.1,content.1,content.2
</code>```

Now it will write into local file using put file processor.

Hope this helpful for you.

Body:
SGaur,

If incoming flow file content is empty before putFile processor then it will writes empty content in local directory.

So you have to write attributes into flowfile content using ReplaceText.

For an example, You having this attributes like

${filename}-->input.1,
${input.content.1}-->content.1,
${input.content.2}-->content.2

comes before putFile.

Now you have to write those attributes into flow file content like below.,

In ReplaceText, Just mention replacement value to be like this-->

${filename},${input.content.1},${input.content.2}

It will replace content like below.,

input.1,content.1,content.2

Now it will write into local file using put file processor.

Hope this helpful for you.


问:
Reduce game size in Cocos Creator cocos2d-x
I am developing a game using Cocos Creator for Android and iOS platforms. The game is small in scale and has few graphics elements.

I found that the APK and IPA file size for this game is 11.5 MB. I think these files (APK or IPA) must be containing some unnecessary files. The Asset folder's size is just 5 MB.

I have following questions:

How to reduce the game size for iOS and Android platform in Cocos Creator?

Are there any optimization techniques for reducing size of art assets (without affecting quality)?

I would appreciate any suggestions/thoughts on this topic. Thank you.

答:
In cocos creator, you can remove none used components.
Before you  build cocos creator projects, click "Project" Menu, select "Module Config", Here you can deselect components which you don't use in you game.
Hope this can help you!</p>