问:
Forcing usermod with running program
I've been looking for a way to force usermod to modify the password/group/... files despite the user being in use.

What I do get now is this:

```<code>!! Failed to execute 'usermod --home '...' --password '...' --shell '/bin/false' 'zabbix' 2>&1':
usermod: user zabbix is currently used by process 518
</code>```

I know that for being secure I need to restart the service. But this is done within a setup script. I am restarting all services at the end.

Is there any way to say --force? (well, except for modifying all necessary files.)

Thanks

答:
If you can get root rights via sudo and are confident enough to change system files using vi then I would change the files manually.

Only a few things need to be changed in

```<code>- /etc/passwd
  here you could change UID, GID, Homedirectory, Shell ...
- /etc/group
  here you might need to change UID/GID as well for the username if there was a change
</code>```

The File /etc/shadow will be changed automatically when using passwd to set a new password. This you can directly perform if you are root: "passwd username"

Title: Forcing usermod with running program

Body:
I've been looking for a way to force usermod to modify the password/group/... files despite the user being in use.

What I do get now is this:

!! Failed to execute 'usermod --home '...' --password '...' --shell '/bin/false' 'zabbix' 2>&1':
usermod: user zabbix is currently used by process 518

I know that for being secure I need to restart the service. But this is done within a setup script. I am restarting all services at the end.

Is there any way to say --force? (well, except for modifying all necessary files.)

Thanks

Body:
If you can get root rights via sudo and are confident enough to change system files using vi then I would change the files manually.

Only a few things need to be changed in

- /etc/passwd
  here you could change UID, GID, Homedirectory, Shell ...
- /etc/group
  here you might need to change UID/GID as well for the username if there was a change

The File /etc/shadow will be changed automatically when using passwd to set a new password. This you can directly perform if you are root: "passwd username"


来源: stackexchange

问:
loopback with async library get in serial callback issue while sending one result callback to other
I'm using the loopback for backend API, here for fetching the data from MySQL, here while performing the operation on it I am using the async npm library,

to perform block-level functional execution, while doing these facing setback with an autocallBack functional issue.

Unhandled rejection TypeError: autoCallback is not a function

here is my pseudo code.

```<code>ModalName.remoteMethod = function (data, cb) {
    async.auto({
      firstCallingFunction: function (autoCallback) {
        ModalName.find({
          id: 1
        }, yourResult => {
            if (err) {
                return cb({
                success: false,
                msg: 'Insufficient parameters',
                data: err,
                });
            } else {
                return autoCallback(null, yourResult);
            }
            });
        },
        secondCallingFunction: ['firstCallingFunction', function (autoCallback, result) {
            console.log('result=====>', result)
            ModalName.find({id: result['id']})
            .then(function(dbResult) {
            if (dbResult) {
                console.log('dbResult==========>', dbResult.toJSON());
                return autoCallback(null, dbResult);
            }
            });
        }],
    }, function (error, autoResult) {
      if (error) {
        return cb(null, error);
      } else {
        return cb(null, {
          success: true,
          msg: 'result fetched',
          data: autoResult.secondCallingFunction,
        });
      }
    });
  };
</code>```

Get in ==> err in autoResult's object function is undefined.

Any solution for that issue, please send.

Thanks.

答:
Here is the solution, I just changed the function arguments and it works for me!</p>

```<code>ModalName.remoteMethod = function (data, cb) {
    async.auto({
      firstCallingFunction: function (autoCallback) {
        ModalName.find({
          id: 1
        }, yourResult => {
            if (err) {
                return autoCallback({
                success: false,
                msg: 'Insufficient parameters',
                data: err,
                });
            } else {
                return autoCallback(null, yourResult);
            }
            });
        },
        secondCallingFunction: ['firstCallingFunction', function (result, autoCallback) {
            console.log('result=====>', result)
            ModalName.find({id: result['id']})
            .then(function(dbResult) {
            if (dbResult) {
                console.log('dbResult==========>', dbResult.toJSON());
                return autoCallback(null, dbResult);
            }
            });
        }],
    }, function (error, autoResult) {
      if (error) {
        return cb(null, error);
      } else {
        return cb(null, {
          success: true,
          msg: 'result fetched',
          data: autoResult.secondCallingFunction,
        });
      }
    });
  };
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm using the loopback for backend API, here for fetching the data from MySQL, here while performing the operation on it I am using the async npm library,

to perform block-level functional execution, while doing these facing setback with an autocallBack functional issue.

Unhandled rejection TypeError: autoCallback is not a function

here is my pseudo code.

ModalName.remoteMethod = function (data, cb) {
    async.auto({
      firstCallingFunction: function (autoCallback) {
        ModalName.find({
          id: 1
        }, yourResult => {
            if (err) {
                return cb({
                success: false,
                msg: 'Insufficient parameters',
                data: err,
                });
            } else {
                return autoCallback(null, yourResult);
            }
            });
        },
        secondCallingFunction: ['firstCallingFunction', function (autoCallback, result) {
            console.log('result=====>', result)
            ModalName.find({id: result['id']})
            .then(function(dbResult) {
            if (dbResult) {
                console.log('dbResult==========>', dbResult.toJSON());
                return autoCallback(null, dbResult);
            }
            });
        }],
    }, function (error, autoResult) {
      if (error) {
        return cb(null, error);
      } else {
        return cb(null, {
          success: true,
          msg: 'result fetched',
          data: autoResult.secondCallingFunction,
        });
      }
    });
  };

Get in ==> err in autoResult's object function is undefined.

Any solution for that issue, please send.

Thanks.

Body:
Here is the solution, I just changed the function arguments and it works for me!

ModalName.remoteMethod = function (data, cb) {
    async.auto({
      firstCallingFunction: function (autoCallback) {
        ModalName.find({
          id: 1
        }, yourResult => {
            if (err) {
                return autoCallback({
                success: false,
                msg: 'Insufficient parameters',
                data: err,
                });
            } else {
                return autoCallback(null, yourResult);
            }
            });
        },
        secondCallingFunction: ['firstCallingFunction', function (result, autoCallback) {
            console.log('result=====>', result)
            ModalName.find({id: result['id']})
            .then(function(dbResult) {
            if (dbResult) {
                console.log('dbResult==========>', dbResult.toJSON());
                return autoCallback(null, dbResult);
            }
            });
        }],
    }, function (error, autoResult) {
      if (error) {
        return cb(null, error);
      } else {
        return cb(null, {
          success: true,
          msg: 'result fetched',
          data: autoResult.secondCallingFunction,
        });
      }
    });
  };


问:
First attempt at Django (2.0) models resulting in AttributeError when making migrations
As a complete beginner, I really hope I'm missing something obvious here, and that someone with experience can easily point out my mistake.

I'm in the first steps of creating some Django models, and can't figure out how to resolve an error I get when I try to make migrations. From my research, it looks like this error is vague. I have no idea what it means by saying there's no attribute 'model'.

Here's the traceback:

```<code>Traceback (most recent call last):
File "manage.py", line 22, in <module>
execute_from_command_line(sys.argv)
File "C:\Program Files (x86)\Python36-32\lib\site-packages\django\core\management\__init__.py", line 371, in execute_from_command_line
utility.execute()
File "C:\Program Files (x86)\Python36-32\lib\site-packages\django\core\management\__init__.py", line 365, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "C:\Program Files (x86)\Python36-32\lib\site-packages\django\core\management\base.py", line 288, in run_from_argv
self.execute(*args, **cmd_options)
File "C:\Program Files (x86)\Python36-32\lib\site-packages\django\core\management\base.py", line 332, in execute
self.check()
File "C:\Program Files (x86)\Python36-32\lib\site-packages\django\core\management\base.py", line 364, in check
include_deployment_checks=include_deployment_checks,
File "C:\Program Files (x86)\Python36-32\lib\site-packages\django\core\management\base.py", line 351, in _run_checks
return checks.run_checks(**kwargs)
File "C:\Program Files (x86)\Python36-32\lib\site-packages\django\core\checks\registry.py", line 73, in run_checks
new_errors = check(app_configs=app_configs)
File "C:\Program Files (x86)\Python36-32\lib\site-packages\django\contrib\admin\checks.py", line 22, in check_admin_app
errors.extend(site.check(app_configs))
File "C:\Program Files (x86)\Python36-32\lib\site-packages\django\contrib\admin\sites.py", line 79, in check
if modeladmin.model._meta.app_config in app_configs:
AttributeError: 'Book' object has no attribute 'model'
</code>```

And here's the model code:

```<code>class Author(models.Model):
    name = models.CharField(max_length=80, blank=False, null=False, unique=True)

class Book(models.Model):
    title = models.CharField(max_length=150)
    description = models.TextField(blank=True, null=True)
    series = models.CharField(max_length=150, blank=True, null=True)
    authors = models.ManyToManyField(Author, blank=True)
    finished = models.BooleanField(default=False, verbose_name="Finished")
    # image = models.ImageField()

    def list_authors(self):
        return ", ".join([author.name for author in self.authors.all()])

class Narrator(models.Model):
    narrator = models.CharField(max_length=80)

class Audiobook(Book):
    length = models.TimeField(blank=False, null=False)
    narrator = models.ForeignKey(Narrator, on_delete=models.SET_NULL, blank=False, null=True)
</code>```

I've gone through a few tutorials, and read whatever Django documentation I thought might be relevant, but I'm still missing something. Any ideas, or general pointers would be greatly appreciated.

EDIT: Adding my admin.py. I commented this all out and the migration worked fine, but I still find the same error when trying to run another migration, and a similar error, but instead of saying there's no attribute 'models', it says there's no attribute 'urls'

```<code>from django.contrib import admin
from .models import (Author, Book, Narrator, Audiobook)

# Register your models here.

admin.site.register(Author, Book)
admin.site.register(Narrator, Audiobook)
</code>```

答:
Try register models one by one like following:</p>

```<code>admin.site.register(Author)
admin.site.register(Narrator)
admin.site.register(Book)
admin.site.register(Audiobook)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
As a complete beginner, I really hope I'm missing something obvious here, and that someone with experience can easily point out my mistake.

I'm in the first steps of creating some Django models, and can't figure out how to resolve an error I get when I try to make migrations. From my research, it looks like this error is vague. I have no idea what it means by saying there's no attribute 'model'.

Here's the traceback:

Traceback (most recent call last):
File "manage.py", line 22, in <module>
execute_from_command_line(sys.argv)
File "C:\Program Files (x86)\Python36-32\lib\site-packages\django\core\management\__init__.py", line 371, in execute_from_command_line
utility.execute()
File "C:\Program Files (x86)\Python36-32\lib\site-packages\django\core\management\__init__.py", line 365, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "C:\Program Files (x86)\Python36-32\lib\site-packages\django\core\management\base.py", line 288, in run_from_argv
self.execute(*args, **cmd_options)
File "C:\Program Files (x86)\Python36-32\lib\site-packages\django\core\management\base.py", line 332, in execute
self.check()
File "C:\Program Files (x86)\Python36-32\lib\site-packages\django\core\management\base.py", line 364, in check
include_deployment_checks=include_deployment_checks,
File "C:\Program Files (x86)\Python36-32\lib\site-packages\django\core\management\base.py", line 351, in _run_checks
return checks.run_checks(**kwargs)
File "C:\Program Files (x86)\Python36-32\lib\site-packages\django\core\checks\registry.py", line 73, in run_checks
new_errors = check(app_configs=app_configs)
File "C:\Program Files (x86)\Python36-32\lib\site-packages\django\contrib\admin\checks.py", line 22, in check_admin_app
errors.extend(site.check(app_configs))
File "C:\Program Files (x86)\Python36-32\lib\site-packages\django\contrib\admin\sites.py", line 79, in check
if modeladmin.model._meta.app_config in app_configs:
AttributeError: 'Book' object has no attribute 'model'

And here's the model code:

class Author(models.Model):
    name = models.CharField(max_length=80, blank=False, null=False, unique=True)

class Book(models.Model):
    title = models.CharField(max_length=150)
    description = models.TextField(blank=True, null=True)
    series = models.CharField(max_length=150, blank=True, null=True)
    authors = models.ManyToManyField(Author, blank=True)
    finished = models.BooleanField(default=False, verbose_name="Finished")
    # image = models.ImageField()

    def list_authors(self):
        return ", ".join([author.name for author in self.authors.all()])

class Narrator(models.Model):
    narrator = models.CharField(max_length=80)

class Audiobook(Book):
    length = models.TimeField(blank=False, null=False)
    narrator = models.ForeignKey(Narrator, on_delete=models.SET_NULL, blank=False, null=True)

I've gone through a few tutorials, and read whatever Django documentation I thought might be relevant, but I'm still missing something. Any ideas, or general pointers would be greatly appreciated.

EDIT: Adding my admin.py. I commented this all out and the migration worked fine, but I still find the same error when trying to run another migration, and a similar error, but instead of saying there's no attribute 'models', it says there's no attribute 'urls'

from django.contrib import admin
from .models import (Author, Book, Narrator, Audiobook)

# Register your models here.

admin.site.register(Author, Book)
admin.site.register(Narrator, Audiobook)

Body:
Try register models one by one like following:

admin.site.register(Author)
admin.site.register(Narrator)
admin.site.register(Book)
admin.site.register(Audiobook)


问:
Override "readonly" attribute of a field in one2many relation
Let's suppose the following code :

```<code><field name="object_ids" attrs="{'readonly': [('state', 'not in', ['A', 'B'])]}">
    <form string="My object" version="7.0">
        <field name="object_name"/>
        <field name="object_description"/>
    </form>
</field>
</code>```

This is an example, just to illustrate a definition of a form view for a one2many field.

Is there a way to override the readonly attribute set in the object_ids child fields (object_name) ?

In this case, my whole form view will be readonly for the states specified, but I would like to bypass / override this attribute for a specific field. For example :

```<code>...
<field name="object_name" attrs="{'readonly': False}"> <!-- overrides the readonly set -->
...
</code>```

Is there a way to do this ? Or do I have to remove the attribute from the one2many field and add it to each field ? The goal here is to avoid having this attribute repeated for each field (time consuming, error prone because of inherits of views).

答:
Yes this should be possible.

For your simple example you even don't need XPath syntax:

<field name="object_ids" position="attributes">
    <attribute name="attrs">{'readonly': 0}</attribute>
</field>
```

<p>This sets readonly to false. But if you want to remove the <code>attrs</code> attribute, because it's not needed anymore:</p>

<pre class="lang-xml prettyprint-override"><code><field name="object_ids" position="attributes">
    <attribute name="attrs" />
</field>
</code>```

And the first example with XPath (second is also possible):

```<code><xpath expr="//field[@name='object_ids'" position="attributes">
    <attribute name="attrs">{'readonly': 0}</attribute>
</field>
</code>```

Body:
Let's suppose the following code :

<field name="object_ids" attrs="{'readonly': [('state', 'not in', ['A', 'B'])]}">
    <form string="My object" version="7.0">
        <field name="object_name"/>
        <field name="object_description"/>
    </form>
</field>

This is an example, just to illustrate a definition of a form view for a one2many field.

Is there a way to override the readonly attribute set in the object_ids child fields (object_name) ?

In this case, my whole form view will be readonly for the states specified, but I would like to bypass / override this attribute for a specific field. For example :

...
<field name="object_name" attrs="{'readonly': False}">
...

Is there a way to do this ? Or do I have to remove the attribute from the one2many field and add it to each field ? The goal here is to avoid having this attribute repeated for each field (time consuming, error prone because of inherits of views).

Body:
Yes this should be possible.

For your simple example you even don't need XPath syntax:

<field name="object_ids" position="attributes">
    <attribute name="attrs">{'readonly': 0}</attribute>
</field>

This sets readonly to false. But if you want to remove the attrs attribute, because it's not needed anymore:

<field name="object_ids" position="attributes">
    <attribute name="attrs" />
</field>

And the first example with XPath (second is also possible):

<xpath expr="//field[@name='object_ids'" position="attributes">
    <attribute name="attrs">{'readonly': 0}</attribute>
</field>


问:
Swift: How many of the same object in array
I have a CollectionView with items like...

```<code>Fruit(name: String, price: Int, imageUrl: String)
</code>```

The user can select multiple Fruits and then proceed to a "checkout" which is a UITableView with all the fruits selected.
The UITableViewCell contains: amountLabel, fruitLabel, priceLabel.

I want to show how many of each fruit and the total price is, in this view.

What is the best way to do this?

What I see now :

```<code>Banana - 1$
Orange - 3$
Banana - 1$
Apple - 2$
Apple - 2$
Banana - 1$
Orange - 3$
Orange - 3$

total: 16$
</code>```

What I want to see:

```<code>3x Banana - 3$
2x Apple - 4$
3x Orange - 9$

total: 16$
</code>```

答:
You could group the array and sum up the prices</p>

```<code>let grouped = Dictionary(grouping: fruits, by: {$0.name})
var total = 0
for (key, value) in grouped {
    let price = value.reduce(0, {$0 + $1.price})
    print(value.count, key, "\(price)$")
    total += price
}
print("total: \(total)$")
</code>```

Body:
I have a CollectionView with items like...

Fruit(name: String, price: Int, imageUrl: String)

The user can select multiple Fruits and then proceed to a "checkout" which is a UITableView with all the fruits selected.
The UITableViewCell contains: amountLabel, fruitLabel, priceLabel.

I want to show how many of each fruit and the total price is, in this view.

What is the best way to do this?

What I see now :

Banana - 1$
Orange - 3$
Banana - 1$
Apple - 2$
Apple - 2$
Banana - 1$
Orange - 3$
Orange - 3$

total: 16$

What I want to see:

3x Banana - 3$
2x Apple - 4$
3x Orange - 9$

total: 16$

Body:
You could group the array and sum up the prices

let grouped = Dictionary(grouping: fruits, by: {$0.name})
var total = 0
for (key, value) in grouped {
    let price = value.reduce(0, {$0 + $1.price})
    print(value.count, key, "\(price)$")
    total += price
}
print("total: \(total)$")


问:
Uncaught (in promise): Error: Can't resolve all parameters for LocalStorageService
I try to upgrade to latest Angular, and I got the error on my component and going to URL /login

it something like this :
ERROR Error: "Uncaught (in promise): Error: Can't resolve all parameters for LocalStorageService: (?).

my pages/login/login.component something like this :

```<code>import { Component, OnInit } from "@angular/core";
import { LocalStorageService } from "ngx-webstorage";
import { Router } from "@angular/router";
import { NgForm } from "@angular/forms";
import {
  SnotifyService,
  SnotifyPosition,
  SnotifyToastConfig
} from "ng-snotify";

import { AuthenticationService }
  constructor(
    private authenticationService: AuthenticationService,
    private router: Router,
    private localStorageService: LocalStorageService,
    private snotifyService: SnotifyService
  ) {}
</code>```

and on pages/login/login.module

```<code>import { NgModule } from "@angular/core";
import { RouterModule, Routes } from "@angular/router";
import { CommonModule } from "@angular/common";
import { LoginComponent } from "./login.component";
import { AuthService } from "../../../services/base-services/auth.service";
import { AuthenticationService } from "../../../services/authentication.service";
import { SnotifyModule, SnotifyService, ToastDefaults } from "ng-snotify";
import { FormsModule } from "@angular/forms";
import { LocalStorageService } from "ngx-webstorage";

export const LoginRoutes: Routes = [
  {
    path: "",
    data: {
      breadcrumb: "Login"
    },
    children: [
      {
        path: "",
        component: LoginComponent,
        data: {
          breadcrumb: "Login"
        }
      }
    ]
  }
];

@NgModule({
  declarations: [LoginComponent],
  imports: [
    CommonModule,
    RouterModule.forChild(LoginRoutes),
    SnotifyModule,
    FormsModule
  ],
  providers: [
    LocalStorageService,
    AuthenticationService,
    AuthService,
    SnotifyService,
    { provide: "SnotifyToastConfig", useValue: ToastDefaults }
  ]
})
export class LoginModule {}
</code>```

and on my app.module is something like this

```<code>import { BrowserModule } from "@angular/platform-browser";
import { NgModule } from "@angular/core";
import { AuthComponent } from "./layout/auth/auth.component";
import { HttpClientModule } from "@angular/common/http";
import { AuthGuardService } from "./services/base-services/auth-guard.service";
import { AuthenticationService } from "./services/authentication.service";
import { BreadcrumbsComponent } from "./layout/admin/breadcrumbs/breadcrumbs.component";
import { FormsModule } from "@angular/forms";

import { AppRoutingModule } from "./app-routing.module";
import { AppComponent } from "./app.component";

@NgModule({
  declarations: [AppComponent, AuthComponent, BreadcrumbsComponent],
  imports: [BrowserModule, AppRoutingModule, FormsModule, HttpClientModule],
  providers: [AuthGuardService, AuthenticationService],
  bootstrap: [AppComponent]
})
export class AppModule {}
</code>```

is there something wrong for import and put services on my files ?? or any missing syntax on my component ??

my package.json

```<code>{
  "name": "kontrak-hukum-front-end",
  "version": "0.0.0",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
  },
  "private": true,
  "dependencies": {
    "@agm/core": "^1.0.0-beta.5",
    "@angular/animations": "^8.0.0-rc.4",
    "@angular/common": "^8.0.0-rc.4",
    "@angular/compiler": "^8.0.0-rc.4",
    "@angular/core": "^8.0.0-rc.4",
    "@angular/forms": "^8.0.0-rc.4",
    "@angular/platform-browser": "^8.0.0-rc.4",
    "@angular/platform-browser-dynamic": "^8.0.0-rc.4",
    "@angular/platform-server": "^8.0.0-rc.4",
    "@angular/router": "^8.0.0-rc.4",
    "@fortawesome/angular-fontawesome": "^0.3.0",
    "@ng-bootstrap/ng-bootstrap": "^4.1.3",
    "@ng-select/ng-select": "^2.20.0",
    "@nicky-lenaers/ngx-scroll-to": "^2.0.0",
    "@swimlane/ngx-datatable": "^14.0.0",
    "@types/googlemaps": "^3.36.0",
    "angular-2-local-storage": "^3.0.2",
    "angular-froala-wysiwyg": "^3.0.0-beta.1",
    "angular-io-slimscroll": "^2.3.3",
    "angular2-chartjs": "^0.5.1",
    "angular2-datatable": "^0.6.0",
    "angular2-material-datepicker": "^0.5.0",
    "angular2-notifications": "^2.0.0",
    "angular2-wizard": "^0.4.0",
    "bootstrap": "^4.3.1",
    "c3": "^0.7.0",
    "core-js": "^3.1.2",
    "css-animator": "^2.3.1",
    "d3": "^5.9.2",
    "echarts": "^4.2.1",
    "famfamfam-flags": "^1.0.0",
    "font-awesome": "^4.7.0",
    "jquery": "^3.4.1",
    "jquery-sparkline": "^2.4.0",
    "ng-auto-complete": "^4.1.7",
    "ng-click-outside": "^4.0.0",
    "ng-snotify": "^4.3.1",
    "ng2-auto-complete": "^0.12.0",
    "ng2-ckeditor": "^1.2.2",
    "ng2-currency-mask": "^5.3.1",
    "ng2-file-upload": "^1.3.0",
    "ng2-google-charts": "^4.0.0",
    "ng2-nvd3": "^2.0.0",
    "ng2-order-pipe": "^0.1.5",
    "ng2-search-filter": "^0.5.1",
    "ng2-toasty": "^4.0.3",
    "ng2-ui-switch": "^1.0.2",
    "ng2-validation": "^4.2.0",
    "ngx-bootstrap": "^4.3.0",
    "ngx-chips": "^2.0.0-beta.0",
    "ngx-color-picker": "^7.5.0",
    "ngx-echarts": "^4.1.1",
    "ngx-order-pipe": "^2.0.2",
    "ngx-pagination": "^3.2.1",
    "ngx-quill": "^5.1.0",
    "ngx-quill-editor": "^2.2.2",
    "ngx-webstorage": "^3.0.2",
    "npm": "^6.9.0",
    "peity": "^3.3.0",
    "rxjs": "^6.5.2",
    "screenfull": "^4.2.0",
    "squeezebox": "^1.4.1",
    "sweetalert2": "^8.11.4",
    "ti-icons": "^0.1.2",
    "tslib": "^1.9.0",
    "wijmo": "^5.20191.606",
    "zone.js": "~0.9.1"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "~0.800.0-rc.4",
    "@angular/cli": "^8.0.0-rc.4",
    "@angular/compiler-cli": "^8.0.0-rc.4",
    "@angular/language-service": "^8.0.0-rc.4",
    "@types/jasmine": "~3.3.12",
    "@types/jasminewd2": "~2.0.3",
    "@types/node": "~12.0.2",
    "codelyzer": "^5.0.1",
    "jasmine-core": "~3.4.0",
    "jasmine-spec-reporter": "~4.2.1",
    "karma": "~4.1.0",
    "karma-chrome-launcher": "~2.2.0",
    "karma-coverage-istanbul-reporter": "~2.0.1",
    "karma-jasmine": "~2.0.1",
    "karma-jasmine-html-reporter": "^1.4.2",
    "protractor": "~5.4.0",
    "ts-node": "~8.1.0",
    "tslint": "~5.11.0",
    "typescript": "3.4.5"
  }
}
</code>```

答:
Your LocalStorageService has a dependency that is unmet. You will need to add that dependency to your login.module.

As you stated; the LocalStorageService is an external package.

Instead of providing the LocalStorageService yourself, maybe you should import the Module it belongs to. Probably the LocalStorageModule, you may consider putting this in your app.module so you can provide the service to your locally scoped modules.

Edit: From their README:

https://www.npmjs.com/package/ngx-webstorage

```<code>import {NgxWebstorageModule} from 'ngx-webstorage';

@NgModule({
    declarations: [...],
    imports: [
        ...,
        NgxWebstorageModule.forRoot(),
        ...
    ]
})
</code>```

Then you don't have to provide the service yourself, you can just use it in your constructor() and it'll be injected.

Body:
I try to upgrade to latest Angular, and I got the error on my component and going to URL /login

it something like this :
ERROR Error: "Uncaught (in promise): Error: Can't resolve all parameters for LocalStorageService: (?).

my pages/login/login.component something like this :

import { Component, OnInit } from "@angular/core";
import { LocalStorageService } from "ngx-webstorage";
import { Router } from "@angular/router";
import { NgForm } from "@angular/forms";
import {
  SnotifyService,
  SnotifyPosition,
  SnotifyToastConfig
} from "ng-snotify";

import { AuthenticationService }
  constructor(
    private authenticationService: AuthenticationService,
    private router: Router,
    private localStorageService: LocalStorageService,
    private snotifyService: SnotifyService
  ) {}

and on pages/login/login.module

import { NgModule } from "@angular/core";
import { RouterModule, Routes } from "@angular/router";
import { CommonModule } from "@angular/common";
import { LoginComponent } from "./login.component";
import { AuthService } from "../../../services/base-services/auth.service";
import { AuthenticationService } from "../../../services/authentication.service";
import { SnotifyModule, SnotifyService, ToastDefaults } from "ng-snotify";
import { FormsModule } from "@angular/forms";
import { LocalStorageService } from "ngx-webstorage";

export const LoginRoutes: Routes = [
  {
    path: "",
    data: {
      breadcrumb: "Login"
    },
    children: [
      {
        path: "",
        component: LoginComponent,
        data: {
          breadcrumb: "Login"
        }
      }
    ]
  }
];

@NgModule({
  declarations: [LoginComponent],
  imports: [
    CommonModule,
    RouterModule.forChild(LoginRoutes),
    SnotifyModule,
    FormsModule
  ],
  providers: [
    LocalStorageService,
    AuthenticationService,
    AuthService,
    SnotifyService,
    { provide: "SnotifyToastConfig", useValue: ToastDefaults }
  ]
})
export class LoginModule {}

and on my app.module is something like this

import { BrowserModule } from "@angular/platform-browser";
import { NgModule } from "@angular/core";
import { AuthComponent } from "./layout/auth/auth.component";
import { HttpClientModule } from "@angular/common/http";
import { AuthGuardService } from "./services/base-services/auth-guard.service";
import { AuthenticationService } from "./services/authentication.service";
import { BreadcrumbsComponent } from "./layout/admin/breadcrumbs/breadcrumbs.component";
import { FormsModule } from "@angular/forms";

import { AppRoutingModule } from "./app-routing.module";
import { AppComponent } from "./app.component";

@NgModule({
  declarations: [AppComponent, AuthComponent, BreadcrumbsComponent],
  imports: [BrowserModule, AppRoutingModule, FormsModule, HttpClientModule],
  providers: [AuthGuardService, AuthenticationService],
  bootstrap: [AppComponent]
})
export class AppModule {}

is there something wrong for import and put services on my files ?? or any missing syntax on my component ??

my package.json

{
  "name": "kontrak-hukum-front-end",
  "version": "0.0.0",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
  },
  "private": true,
  "dependencies": {
    "@agm/core": "^1.0.0-beta.5",
    "@angular/animations": "^8.0.0-rc.4",
    "@angular/common": "^8.0.0-rc.4",
    "@angular/compiler": "^8.0.0-rc.4",
    "@angular/core": "^8.0.0-rc.4",
    "@angular/forms": "^8.0.0-rc.4",
    "@angular/platform-browser": "^8.0.0-rc.4",
    "@angular/platform-browser-dynamic": "^8.0.0-rc.4",
    "@angular/platform-server": "^8.0.0-rc.4",
    "@angular/router": "^8.0.0-rc.4",
    "@fortawesome/angular-fontawesome": "^0.3.0",
    "@ng-bootstrap/ng-bootstrap": "^4.1.3",
    "@ng-select/ng-select": "^2.20.0",
    "@nicky-lenaers/ngx-scroll-to": "^2.0.0",
    "@swimlane/ngx-datatable": "^14.0.0",
    "@types/googlemaps": "^3.36.0",
    "angular-2-local-storage": "^3.0.2",
    "angular-froala-wysiwyg": "^3.0.0-beta.1",
    "angular-io-slimscroll": "^2.3.3",
    "angular2-chartjs": "^0.5.1",
    "angular2-datatable": "^0.6.0",
    "angular2-material-datepicker": "^0.5.0",
    "angular2-notifications": "^2.0.0",
    "angular2-wizard": "^0.4.0",
    "bootstrap": "^4.3.1",
    "c3": "^0.7.0",
    "core-js": "^3.1.2",
    "css-animator": "^2.3.1",
    "d3": "^5.9.2",
    "echarts": "^4.2.1",
    "famfamfam-flags": "^1.0.0",
    "font-awesome": "^4.7.0",
    "jquery": "^3.4.1",
    "jquery-sparkline": "^2.4.0",
    "ng-auto-complete": "^4.1.7",
    "ng-click-outside": "^4.0.0",
    "ng-snotify": "^4.3.1",
    "ng2-auto-complete": "^0.12.0",
    "ng2-ckeditor": "^1.2.2",
    "ng2-currency-mask": "^5.3.1",
    "ng2-file-upload": "^1.3.0",
    "ng2-google-charts": "^4.0.0",
    "ng2-nvd3": "^2.0.0",
    "ng2-order-pipe": "^0.1.5",
    "ng2-search-filter": "^0.5.1",
    "ng2-toasty": "^4.0.3",
    "ng2-ui-switch": "^1.0.2",
    "ng2-validation": "^4.2.0",
    "ngx-bootstrap": "^4.3.0",
    "ngx-chips": "^2.0.0-beta.0",
    "ngx-color-picker": "^7.5.0",
    "ngx-echarts": "^4.1.1",
    "ngx-order-pipe": "^2.0.2",
    "ngx-pagination": "^3.2.1",
    "ngx-quill": "^5.1.0",
    "ngx-quill-editor": "^2.2.2",
    "ngx-webstorage": "^3.0.2",
    "npm": "^6.9.0",
    "peity": "^3.3.0",
    "rxjs": "^6.5.2",
    "screenfull": "^4.2.0",
    "squeezebox": "^1.4.1",
    "sweetalert2": "^8.11.4",
    "ti-icons": "^0.1.2",
    "tslib": "^1.9.0",
    "wijmo": "^5.20191.606",
    "zone.js": "~0.9.1"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "~0.800.0-rc.4",
    "@angular/cli": "^8.0.0-rc.4",
    "@angular/compiler-cli": "^8.0.0-rc.4",
    "@angular/language-service": "^8.0.0-rc.4",
    "@types/jasmine": "~3.3.12",
    "@types/jasminewd2": "~2.0.3",
    "@types/node": "~12.0.2",
    "codelyzer": "^5.0.1",
    "jasmine-core": "~3.4.0",
    "jasmine-spec-reporter": "~4.2.1",
    "karma": "~4.1.0",
    "karma-chrome-launcher": "~2.2.0",
    "karma-coverage-istanbul-reporter": "~2.0.1",
    "karma-jasmine": "~2.0.1",
    "karma-jasmine-html-reporter": "^1.4.2",
    "protractor": "~5.4.0",
    "ts-node": "~8.1.0",
    "tslint": "~5.11.0",
    "typescript": "3.4.5"
  }
}

Body:
Your LocalStorageService has a dependency that is unmet. You will need to add that dependency to your login.module.

As you stated; the LocalStorageService is an external package.

Instead of providing the LocalStorageService yourself, maybe you should import the Module it belongs to. Probably the LocalStorageModule, you may consider putting this in your app.module so you can provide the service to your locally scoped modules.

Edit: From their README:

https://www.npmjs.com/package/ngx-webstorage

import {NgxWebstorageModule} from 'ngx-webstorage';

@NgModule({
    declarations: [...],
    imports: [
        ...,
        NgxWebstorageModule.forRoot(),
        ...
    ]
})

Then you don't have to provide the service yourself, you can just use it in your constructor() and it'll be injected.


问:
restore a factor variable original values
I have factor variable (Accuracy w/2 levels: "0", "1"). However, I have mistakenly converted to a numeric using the

Task_df_Acc_Exp$Accuracy <- as.numeric(Task_df_Acc_Exp$Accuracy)

Now when look up the variable, it looks like that the underlying internal coding  (1, 2) has overwritten the factor original values.

```<code>Accuracy: Factor w/ 2 levels "1","2": 1 1 1 2 1 2 2 2 2 1 ...
</code>```

I have tried to converted back to a factor variable, but the variable still the internal coding of (1, 2). Is there anyway I could converted to  factor and restored the original values back?
Do you think that this might affect any subsequent logistic analysis?

dput

```<code>Accuracy = structure(c(1L, 1L, 1L, 2L, 1L, 2L), .Label = c("1", "2"), class = "factor")
</code>```

答:
Try this:

```<code># decrease by one while it's numeric
Task_df_Acc_Exp$Accuracy = Task_df_Acc_Exp$Accuracy - 1

# convert back to factor
Task_df_Acc_Exp$Accuracy <- as.factor(Task_df_Acc_Exp$Accuracy)
</code>```

Let me know if it works or not.

Body:
I have factor variable (Accuracy w/2 levels: "0", "1"). However, I have mistakenly converted to a numeric using the

Task_df_Acc_Exp$Accuracy <- as.numeric(Task_df_Acc_Exp$Accuracy)

Now when look up the variable, it looks like that the underlying internal coding  (1, 2) has overwritten the factor original values.

Accuracy: Factor w/ 2 levels "1","2": 1 1 1 2 1 2 2 2 2 1 ...

I have tried to converted back to a factor variable, but the variable still the internal coding of (1, 2). Is there anyway I could converted to  factor and restored the original values back?
Do you think that this might affect any subsequent logistic analysis?

dput

Accuracy = structure(c(1L, 1L, 1L, 2L, 1L, 2L), .Label = c("1", "2"), class = "factor")

Body:
Try this:

# decrease by one while it's numeric
Task_df_Acc_Exp$Accuracy = Task_df_Acc_Exp$Accuracy - 1

# convert back to factor
Task_df_Acc_Exp$Accuracy <- as.factor(Task_df_Acc_Exp$Accuracy)

Let me know if it works or not.


问:
Docker: I can't map ports other than 80 to my WordPress container
I want to map some random port on my computer e.g. localhost:7006 to my WordPress docker container's port 80.When I change the port of WordPress from 80:80 to 7006:80 it's not only stops working on localhost(port 80) but also don't respond on localhost:7006.

docker-compose.yml file looks like this:

```<code>        version: '3'
    services:
      wordpress:
        depends_on:
          - db
        image: wordpress:4.7.1
        restart: always
        volumes:
          - ./wp-content:/var/www/html/wp-content
        environment:
          WORDPRESS_DB_HOST: db:3306
          WORDPRESS_DB_PASSWORD: p4ssw0rd!
        ports:
          - 80:80 # Expose http and https
          - 8443:443
        networks:
          - wp_nwk
      db:
        image: mysql:5.7
        restart: always
        volumes:
           - db_data:/var/lib/mysql
        environment:
          MYSQL_ROOT_PASSWORD: p4ssw0rd!
        networks:
          - wp_nwk
      phpmyadmin:
        depends_on:
          - db
        image: phpmyadmin/phpmyadmin
        restart: always
        ports:
          - 7005:80
        environment:
          PMA_HOST: db
          MYSQL_ROOT_PASSWORD: p4ssw0rd!
        networks:
          - wp_nwk
    networks:
      wp_nwk:
    volumes:
      db_data:
</code>```

答:
I|f you want to change the port, you need to do the follow step. I successfully changed my WordPress port

run WordPress with default docker-compose.yml

```<code>version: '3.3'

services:
   db:
     image: mysql:5.7
     volumes:
       - db_data:/var/lib/mysql
     restart: always
     environment:
       MYSQL_ROOT_PASSWORD: somewordpress
       MYSQL_DATABASE: wordpress
       MYSQL_USER: wordpress
       MYSQL_PASSWORD: wordpress

   wordpress:
     depends_on:
       - db
     image: wordpress:latest
     ports:
       - "8000:80"
     restart: always
     environment:
       WORDPRESS_DB_HOST: db:3306
       WORDPRESS_DB_USER: wordpress
       WORDPRESS_DB_PASSWORD: wordpress
       WORDPRESS_DB_NAME: wordpress
volumes:
    db_data: {}
</code>```

login wordpress and change site url and home in setting to you want

use follow command in wordpress container

```<code>docker exec -it *wordpres_container_id* bash
</code>```

add the follow line to wp_config.php

```<code>define( 'WP_HOME', 'http://example.com' );
define( 'WP_SITEURL', 'http://example.com' );
</code>```

change docker-compose.yml ports to 80

restart container use follow command

```<code>docker-compose down
docker-compose up -d
</code>```

Body:
I want to map some random port on my computer e.g. localhost:7006 to my WordPress docker container's port 80.When I change the port of WordPress from 80:80 to 7006:80 it's not only stops working on localhost(port 80) but also don't respond on localhost:7006.

docker-compose.yml file looks like this:

        version: '3'
    services:
      wordpress:
        depends_on:
          - db
        image: wordpress:4.7.1
        restart: always
        volumes:
          - ./wp-content:/var/www/html/wp-content
        environment:
          WORDPRESS_DB_HOST: db:3306
          WORDPRESS_DB_PASSWORD: p4ssw0rd!
        ports:
          - 80:80 # Expose http and https
          - 8443:443
        networks:
          - wp_nwk
      db:
        image: mysql:5.7
        restart: always
        volumes:
           - db_data:/var/lib/mysql
        environment:
          MYSQL_ROOT_PASSWORD: p4ssw0rd!
        networks:
          - wp_nwk
      phpmyadmin:
        depends_on:
          - db
        image: phpmyadmin/phpmyadmin
        restart: always
        ports:
          - 7005:80
        environment:
          PMA_HOST: db
          MYSQL_ROOT_PASSWORD: p4ssw0rd!
        networks:
          - wp_nwk
    networks:
      wp_nwk:
    volumes:
      db_data:

Body:
I|f you want to change the port, you need to do the follow step. I successfully changed my WordPress port

run WordPress with default docker-compose.yml

version: '3.3'

services:
   db:
     image: mysql:5.7
     volumes:
       - db_data:/var/lib/mysql
     restart: always
     environment:
       MYSQL_ROOT_PASSWORD: somewordpress
       MYSQL_DATABASE: wordpress
       MYSQL_USER: wordpress
       MYSQL_PASSWORD: wordpress

   wordpress:
     depends_on:
       - db
     image: wordpress:latest
     ports:
       - "8000:80"
     restart: always
     environment:
       WORDPRESS_DB_HOST: db:3306
       WORDPRESS_DB_USER: wordpress
       WORDPRESS_DB_PASSWORD: wordpress
       WORDPRESS_DB_NAME: wordpress
volumes:
    db_data: {}

login wordpress and change site url and home in setting to you want

use follow command in wordpress container

docker exec -it *wordpres_container_id* bash

add the follow line to wp_config.php

define( 'WP_HOME', 'http://example.com' );
define( 'WP_SITEURL', 'http://example.com' );

change docker-compose.yml ports to 80

restart container use follow command

docker-compose down
docker-compose up -d


问:
Material Design - stepper how to remove/disable steps?
I'm using Material - Angular2 Stepper, and I have additional steps that I want to add/enable depending on what the user selects in the first step.

I tried the following:

- Load the additional forms into an array,

- then loop through it in the template with *ngFor

```<code><mat-vertical-stepper linear>
  <mat-step [stepControl]="firstForm" label="First">
    <!-- Some form controls -->
  </mat-step>
  <mat-step *ngFor="let f of additionalForms" [stepControl]="f.form"
      [label]="f.label">
    <!-- Additional Steps -->
  </mat-step>
</mat-vertical-stepper>
</code>```

This works well for adding new steps, the problem is I can't remove them. If the user happened to come back to first form, and uncheck something, these additional steps wouldn't be required.

So trying something like: this.additionalForms = [] doesn't remove the steps. (until you click on one of the "removed" steps, then it throws an error: Cannot read property 'editable' of undefined, and only then, they're removed visually)

I also tried doing ChangeDetectorRef.detectChanges()

and tried wrapping into the NgZone.run()

but made no difference

Any solutions for this?

答:
Also, If you want to do not return the privously, you can use stepper's editable property as below

```<code><mat-vertical-stepper linear>
  <mat-step [stepControl]="firstForm" label="First" [editable]="false">
    <!-- Some form controls -->
  </mat-step>
  <mat-step *ngFor="let f of additionalForms" [stepControl]="f.form"
      [label]="f.label">
    <!-- Additional Steps -->
  </mat-step>
</mat-vertical-stepper>
</code>```

based on https://material.angular.io/components/stepper/overview#editable-step

Body:
I'm using Material - Angular2 Stepper, and I have additional steps that I want to add/enable depending on what the user selects in the first step.

I tried the following:

- Load the additional forms into an array,

- then loop through it in the template with *ngFor

<mat-vertical-stepper linear>
  <mat-step [stepControl]="firstForm" label="First">

  </mat-step>
  <mat-step *ngFor="let f of additionalForms" [stepControl]="f.form"
      [label]="f.label">

  </mat-step>
</mat-vertical-stepper>

This works well for adding new steps, the problem is I can't remove them. If the user happened to come back to first form, and uncheck something, these additional steps wouldn't be required.

So trying something like: this.additionalForms = [] doesn't remove the steps. (until you click on one of the "removed" steps, then it throws an error: Cannot read property 'editable' of undefined, and only then, they're removed visually)

I also tried doing ChangeDetectorRef.detectChanges()

and tried wrapping into the NgZone.run()

but made no difference

Any solutions for this?

Body:
Also, If you want to do not return the privously, you can use stepper's editable property as below

<mat-vertical-stepper linear>
  <mat-step [stepControl]="firstForm" label="First" [editable]="false">
    <!-- Some form controls -->
  </mat-step>
  <mat-step *ngFor="let f of additionalForms" [stepControl]="f.form"
      [label]="f.label">
    <!-- Additional Steps -->
  </mat-step>
</mat-vertical-stepper>

based on https://material.angular.io/components/stepper/overview#editable-step


问:
Error Using Phusion Passenger - Could not find sqlite3-ruby-1.2.5 in any of the sources (Bundler::GemNotFound)
I have finally got RoR set up on my server using Phusion Passenger and the default RoR applicatioon page shows, however when I click 'About your application’s environment' I get an error saying 'Ruby (Rack) application could not be started' and under the Error Message bit 'Could not find sqlite3-ruby-1.2.5 in any of the sources (Bundler::GemNotFound)'.

If I do 'bundle install' at the command line I get a list of 'Using x (y)' style messages including this:

Using sqlite3-ruby (1.2.5)

(I had to downgrade to 1.2.5 due to an issue with the latest one)

I really dont understand why I am getting the error above as sqlite3-ruby is obviously there.

Stack Trace On Error Page:

```<code>0   /opt/ruby-enterprise-1.8.7-2011.03/lib/ruby/gems/1.8/gems/bundler-1.0.12/lib/bundler/spec_set.rb    87  in `materialize'
1   /opt/ruby-enterprise-1.8.7-2011.03/lib/ruby/gems/1.8/gems/bundler-1.0.12/lib/bundler/spec_set.rb    81  in `map!'
2   /opt/ruby-enterprise-1.8.7-2011.03/lib/ruby/gems/1.8/gems/bundler-1.0.12/lib/bundler/spec_set.rb    81  in `materialize'
3   /opt/ruby-enterprise-1.8.7-2011.03/lib/ruby/gems/1.8/gems/bundler-1.0.12/lib/bundler/definition.rb  90  in `specs'
4   /opt/ruby-enterprise-1.8.7-2011.03/lib/ruby/gems/1.8/gems/bundler-1.0.12/lib/bundler/definition.rb  135     in `specs_for'
5   /opt/ruby-enterprise-1.8.7-2011.03/lib/ruby/gems/1.8/gems/bundler-1.0.12/lib/bundler/definition.rb  124     in `requested_specs'
6   /opt/ruby-enterprise-1.8.7-2011.03/lib/ruby/gems/1.8/gems/bundler-1.0.12/lib/bundler/environment.rb     23  in `requested_specs'
7   /opt/ruby-enterprise-1.8.7-2011.03/lib/ruby/gems/1.8/gems/bundler-1.0.12/lib/bundler/runtime.rb     11  in `setup'
8   /opt/ruby-enterprise-1.8.7-2011.03/lib/ruby/gems/1.8/gems/bundler-1.0.12/lib/bundler.rb     107     in `setup'
9   /usr/local/lib/ruby/gems/1.9.1/gems/passenger-3.0.6/lib/phusion_passenger/utils.rb  326     in `prepare_app_process'
10  /usr/local/lib/ruby/gems/1.9.1/gems/passenger-3.0.6/lib/phusion_passenger/rack/application_spawner.rb   155     in `initialize_server'
11  /usr/local/lib/ruby/gems/1.9.1/gems/passenger-3.0.6/lib/phusion_passenger/utils.rb  572     in `report_app_init_status'
12  /usr/local/lib/ruby/gems/1.9.1/gems/passenger-3.0.6/lib/phusion_passenger/rack/application_spawner.rb   153     in `initialize_server'
13  /usr/local/lib/ruby/gems/1.9.1/gems/passenger-3.0.6/lib/phusion_passenger/abstract_server.rb    204     in `start_synchronously'
14  /usr/local/lib/ruby/gems/1.9.1/gems/passenger-3.0.6/lib/phusion_passenger/abstract_server.rb    180     in `start'
15  /usr/local/lib/ruby/gems/1.9.1/gems/passenger-3.0.6/lib/phusion_passenger/rack/application_spawner.rb   128     in `start'
16  /usr/local/lib/ruby/gems/1.9.1/gems/passenger-3.0.6/lib/phusion_passenger/spawn_manager.rb  253     in `spawn_rack_application'
17  /usr/local/lib/ruby/gems/1.9.1/gems/passenger-3.0.6/lib/phusion_passenger/abstract_server_collection.rb     132     in `lookup_or_add'
18  /usr/local/lib/ruby/gems/1.9.1/gems/passenger-3.0.6/lib/phusion_passenger/spawn_manager.rb  246     in `spawn_rack_application'
19  /usr/local/lib/ruby/gems/1.9.1/gems/passenger-3.0.6/lib/phusion_passenger/abstract_server_collection.rb     82  in `synchronize'
20  /usr/local/lib/ruby/gems/1.9.1/gems/passenger-3.0.6/lib/phusion_passenger/abstract_server_collection.rb     79  in `synchronize'
21  /usr/local/lib/ruby/gems/1.9.1/gems/passenger-3.0.6/lib/phusion_passenger/spawn_manager.rb  244     in `spawn_rack_application'
22  /usr/local/lib/ruby/gems/1.9.1/gems/passenger-3.0.6/lib/phusion_passenger/spawn_manager.rb  137     in `spawn_application'
23  /usr/local/lib/ruby/gems/1.9.1/gems/passenger-3.0.6/lib/phusion_passenger/spawn_manager.rb  275     in `handle_spawn_application'
24  /usr/local/lib/ruby/gems/1.9.1/gems/passenger-3.0.6/lib/phusion_passenger/abstract_server.rb    357     in `__send__'
25  /usr/local/lib/ruby/gems/1.9.1/gems/passenger-3.0.6/lib/phusion_passenger/abstract_server.rb    357     in `server_main_loop'
26  /usr/local/lib/ruby/gems/1.9.1/gems/passenger-3.0.6/lib/phusion_passenger/abstract_server.rb    206     in `start_synchronously'
27  /usr/local/lib/ruby/gems/1.9.1/gems/passenger-3.0.6/helper-scripts/passenger-spawn-server   99
</code>```

Edit:

This is my passenger.conf file.

```<code>LoadModule passenger_module /usr/local/lib/ruby/gems/1.9.1/gems/passenger-3.0.6/ext/apache2/mod_passenger.so
PassengerRoot /usr/local/lib/ruby/gems/1.9.1/gems/passenger-3.0.6
PassengerRuby /opt/ruby-enterprise-1.8.7-2011.03/bin/ruby
PassengerMaxPoolSize 2
</code>```

答:
You seems to have two versions(ruby-enterprise-1.8.7 and 1.9.1) of ruby runtimes installed. Make sure you install the sqlite3-ruby gem (and passenger) on the same runtime.

You have installed the passenger gem in 1.9.1 ruby runtime however you are setting the PassengerRuby to 1.8. I think you shouldn't do that. Set it to 1.9.1. And make sure you run bundle install (inside your rails project folder) with ruby 1.9.1, so that it installed all needed gems to the 1.9.1 runtime.

```<code>PassengerRuby /path/to/1.9.1/here/bin/ruby
</code>```

If you want to manage different versions of ruby runtimes with ease i suggest looking at RVM

Body:
I have finally got RoR set up on my server using Phusion Passenger and the default RoR applicatioon page shows, however when I click 'About your application’s environment' I get an error saying 'Ruby (Rack) application could not be started' and under the Error Message bit 'Could not find sqlite3-ruby-1.2.5 in any of the sources (Bundler::GemNotFound)'.

If I do 'bundle install' at the command line I get a list of 'Using x (y)' style messages including this:

Using sqlite3-ruby (1.2.5)

(I had to downgrade to 1.2.5 due to an issue with the latest one)

I really dont understand why I am getting the error above as sqlite3-ruby is obviously there.

Stack Trace On Error Page:

0   /opt/ruby-enterprise-1.8.7-2011.03/lib/ruby/gems/1.8/gems/bundler-1.0.12/lib/bundler/spec_set.rb    87  in `materialize'
1   /opt/ruby-enterprise-1.8.7-2011.03/lib/ruby/gems/1.8/gems/bundler-1.0.12/lib/bundler/spec_set.rb    81  in `map!'
2   /opt/ruby-enterprise-1.8.7-2011.03/lib/ruby/gems/1.8/gems/bundler-1.0.12/lib/bundler/spec_set.rb    81  in `materialize'
3   /opt/ruby-enterprise-1.8.7-2011.03/lib/ruby/gems/1.8/gems/bundler-1.0.12/lib/bundler/definition.rb  90  in `specs'
4   /opt/ruby-enterprise-1.8.7-2011.03/lib/ruby/gems/1.8/gems/bundler-1.0.12/lib/bundler/definition.rb  135     in `specs_for'
5   /opt/ruby-enterprise-1.8.7-2011.03/lib/ruby/gems/1.8/gems/bundler-1.0.12/lib/bundler/definition.rb  124     in `requested_specs'
6   /opt/ruby-enterprise-1.8.7-2011.03/lib/ruby/gems/1.8/gems/bundler-1.0.12/lib/bundler/environment.rb     23  in `requested_specs'
7   /opt/ruby-enterprise-1.8.7-2011.03/lib/ruby/gems/1.8/gems/bundler-1.0.12/lib/bundler/runtime.rb     11  in `setup'
8   /opt/ruby-enterprise-1.8.7-2011.03/lib/ruby/gems/1.8/gems/bundler-1.0.12/lib/bundler.rb     107     in `setup'
9   /usr/local/lib/ruby/gems/1.9.1/gems/passenger-3.0.6/lib/phusion_passenger/utils.rb  326     in `prepare_app_process'
10  /usr/local/lib/ruby/gems/1.9.1/gems/passenger-3.0.6/lib/phusion_passenger/rack/application_spawner.rb   155     in `initialize_server'
11  /usr/local/lib/ruby/gems/1.9.1/gems/passenger-3.0.6/lib/phusion_passenger/utils.rb  572     in `report_app_init_status'
12  /usr/local/lib/ruby/gems/1.9.1/gems/passenger-3.0.6/lib/phusion_passenger/rack/application_spawner.rb   153     in `initialize_server'
13  /usr/local/lib/ruby/gems/1.9.1/gems/passenger-3.0.6/lib/phusion_passenger/abstract_server.rb    204     in `start_synchronously'
14  /usr/local/lib/ruby/gems/1.9.1/gems/passenger-3.0.6/lib/phusion_passenger/abstract_server.rb    180     in `start'
15  /usr/local/lib/ruby/gems/1.9.1/gems/passenger-3.0.6/lib/phusion_passenger/rack/application_spawner.rb   128     in `start'
16  /usr/local/lib/ruby/gems/1.9.1/gems/passenger-3.0.6/lib/phusion_passenger/spawn_manager.rb  253     in `spawn_rack_application'
17  /usr/local/lib/ruby/gems/1.9.1/gems/passenger-3.0.6/lib/phusion_passenger/abstract_server_collection.rb     132     in `lookup_or_add'
18  /usr/local/lib/ruby/gems/1.9.1/gems/passenger-3.0.6/lib/phusion_passenger/spawn_manager.rb  246     in `spawn_rack_application'
19  /usr/local/lib/ruby/gems/1.9.1/gems/passenger-3.0.6/lib/phusion_passenger/abstract_server_collection.rb     82  in `synchronize'
20  /usr/local/lib/ruby/gems/1.9.1/gems/passenger-3.0.6/lib/phusion_passenger/abstract_server_collection.rb     79  in `synchronize'
21  /usr/local/lib/ruby/gems/1.9.1/gems/passenger-3.0.6/lib/phusion_passenger/spawn_manager.rb  244     in `spawn_rack_application'
22  /usr/local/lib/ruby/gems/1.9.1/gems/passenger-3.0.6/lib/phusion_passenger/spawn_manager.rb  137     in `spawn_application'
23  /usr/local/lib/ruby/gems/1.9.1/gems/passenger-3.0.6/lib/phusion_passenger/spawn_manager.rb  275     in `handle_spawn_application'
24  /usr/local/lib/ruby/gems/1.9.1/gems/passenger-3.0.6/lib/phusion_passenger/abstract_server.rb    357     in `__send__'
25  /usr/local/lib/ruby/gems/1.9.1/gems/passenger-3.0.6/lib/phusion_passenger/abstract_server.rb    357     in `server_main_loop'
26  /usr/local/lib/ruby/gems/1.9.1/gems/passenger-3.0.6/lib/phusion_passenger/abstract_server.rb    206     in `start_synchronously'
27  /usr/local/lib/ruby/gems/1.9.1/gems/passenger-3.0.6/helper-scripts/passenger-spawn-server   99

Edit:

This is my passenger.conf file.

LoadModule passenger_module /usr/local/lib/ruby/gems/1.9.1/gems/passenger-3.0.6/ext/apache2/mod_passenger.so
PassengerRoot /usr/local/lib/ruby/gems/1.9.1/gems/passenger-3.0.6
PassengerRuby /opt/ruby-enterprise-1.8.7-2011.03/bin/ruby
PassengerMaxPoolSize 2

Body:
You seems to have two versions(ruby-enterprise-1.8.7 and 1.9.1) of ruby runtimes installed. Make sure you install the sqlite3-ruby gem (and passenger) on the same runtime.

You have installed the passenger gem in 1.9.1 ruby runtime however you are setting the PassengerRuby to 1.8. I think you shouldn't do that. Set it to 1.9.1. And make sure you run bundle install (inside your rails project folder) with ruby 1.9.1, so that it installed all needed gems to the 1.9.1 runtime.

PassengerRuby /path/to/1.9.1/here/bin/ruby

If you want to manage different versions of ruby runtimes with ease i suggest looking at RVM


问:
Sitecore Custom Index - WARN Could not map index document (field: _uniqueid
I have created my custom Index in Sitecore with FlatDataCrawler.

The Index has been created and I can see my documents in Solr.

The problem is, whenever I'm trying to get those documents in my code I see exception like this:

```<code>Object reference not set to an instance of an object.
</code>```

And in sitecore log file I see this WARN:

```<code>ManagedPoolThread #4 14:29:09 INFO  Solr Query - ?q=*:*&rows=1000000&fq=_indexname:(products_index)&wt=xml
ManagedPoolThread #4 14:29:09 WARN  Could not map index document (field: _uniqueid; Value: fae308d2-233f-4f7f-a4fd-9d880e42ff13) - Object reference not set to an instance of an object.
</code>```

This is my Index config:

```<code><?xml version="1.0" encoding="utf-8" ?>
<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/" xmlns:role="http://www.sitecore.net/xmlconfig/role/" xmlns:search="http://www.sitecore.net/xmlconfig/search/">
    <sitecore role:require="Standalone or ContentManagement" search:require="solr">
        <contentSearch>
            <configuration type="Sitecore.ContentSearch.ContentSearchConfiguration, Sitecore.ContentSearch">
                <indexes hint="list:AddIndex">
                    <index id="products_index" type="Sitecore.ContentSearch.SolrProvider.SolrSearchIndex, Sitecore.ContentSearch.SolrProvider">
                        <param desc="name">$(id)</param>
                        <param desc="core">$(id)</param>
                        <param desc="propertyStore" ref="contentSearch/indexConfigurations/databasePropertyStore" param1="$(id)" />
                        <configuration ref="contentSearch/indexConfigurations/defaultSolrIndexConfiguration">
                            <documentOptions type="Sitecore.ContentSearch.SolrProvider.SolrDocumentBuilderOptions, Sitecore.ContentSearch.SolrProvider">
                                <indexAllFields>false</indexAllFields>
                            </documentOptions>
                        </configuration>
                        <strategies hint="list:AddStrategy">
                            <strategy ref="contentSearch/indexConfigurations/indexUpdateStrategies/manual" />
                        </strategies>
                        <locations hint="list:AddCrawler">
                            <crawler type="Feature.ProductsIndex.Crawlers.CustomOrderCrawler, Feature.ProductsIndex" />
                        </locations>
                    </index>
                </indexes>
            </configuration>
        </contentSearch>
    </sitecore>
</configuration>
</code>```

This is my code:

```<code>using (var searchContext = ContentSearchManager.GetIndex("products_index").CreateSearchContext())
{
    int count = searchContext.GetQueryable<SearchResultItem>().Count(); //This works
    var results = searchContext.GetQueryable<SearchResultItem>().ToList(); //Exception here!
}
</code>```

答:
See in your schema file , if you have

```<code><uniqueKey>_uniqueid</uniqueKey>
<field name="_uniqueid" type="string" indexed="true" required="true" stored="true"/>
</code>```

if not follow this link populate solr schema  , and restart the solr service and then try to rebuild the index

Body:
I have created my custom Index in Sitecore with FlatDataCrawler.

The Index has been created and I can see my documents in Solr.

The problem is, whenever I'm trying to get those documents in my code I see exception like this:

Object reference not set to an instance of an object.

And in sitecore log file I see this WARN:

ManagedPoolThread #4 14:29:09 INFO  Solr Query - ?q=*:*&rows=1000000&fq=_indexname:(products_index)&wt=xml
ManagedPoolThread #4 14:29:09 WARN  Could not map index document (field: _uniqueid; Value: fae308d2-233f-4f7f-a4fd-9d880e42ff13) - Object reference not set to an instance of an object.

This is my Index config:

<?xml version="1.0" encoding="utf-8" ?>
<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/" xmlns:role="http://www.sitecore.net/xmlconfig/role/" xmlns:search="http://www.sitecore.net/xmlconfig/search/">
    <sitecore role:require="Standalone or ContentManagement" search:require="solr">
        <contentSearch>
            <configuration type="Sitecore.ContentSearch.ContentSearchConfiguration, Sitecore.ContentSearch">
                <indexes hint="list:AddIndex">
                    <index id="products_index" type="Sitecore.ContentSearch.SolrProvider.SolrSearchIndex, Sitecore.ContentSearch.SolrProvider">
                        <param desc="name">$(id)</param>
                        <param desc="core">$(id)</param>
                        <param desc="propertyStore" ref="contentSearch/indexConfigurations/databasePropertyStore" param1="$(id)" />
                        <configuration ref="contentSearch/indexConfigurations/defaultSolrIndexConfiguration">
                            <documentOptions type="Sitecore.ContentSearch.SolrProvider.SolrDocumentBuilderOptions, Sitecore.ContentSearch.SolrProvider">
                                <indexAllFields>false</indexAllFields>
                            </documentOptions>
                        </configuration>
                        <strategies hint="list:AddStrategy">
                            <strategy ref="contentSearch/indexConfigurations/indexUpdateStrategies/manual" />
                        </strategies>
                        <locations hint="list:AddCrawler">
                            <crawler type="Feature.ProductsIndex.Crawlers.CustomOrderCrawler, Feature.ProductsIndex" />
                        </locations>
                    </index>
                </indexes>
            </configuration>
        </contentSearch>
    </sitecore>
</configuration>

This is my code:

using (var searchContext = ContentSearchManager.GetIndex("products_index").CreateSearchContext())
{
    int count = searchContext.GetQueryable<SearchResultItem>().Count(); //This works
    var results = searchContext.GetQueryable<SearchResultItem>().ToList(); //Exception here!
}

Body:
See in your schema file , if you have

<uniqueKey>_uniqueid</uniqueKey>
<field name="_uniqueid" type="string" indexed="true" required="true" stored="true"/>

if not follow this link populate solr schema  , and restart the solr service and then try to rebuild the index


问:
How to consume Kafka Topic in Consumer MQ Topic
I have a requirement where I need to consume Kafka Topic and write it into MQ Topic. Can someone advise me the best way to do it, I am new to Kafka.

I have read about the IBM MQ Connector in confluent but could not get the idea how to implement it.

答:
Kafka has a component called Kafka Connect. It is used to read and write data to/from Kafka into other systems such as Database in your case MQ.

Kafka connect can have two kind of connectors

Source connectors - Read data from an external system and write to Kafka (For eg. Read inserted/modified rows from a table in DB and insert into a topic in Kafka)

Sink Connector - Read message from Kafka write to external system.

The link you have added is a source connector, it will read messages from the MQ and write to Kafka.

For simple use case you do not need Kafka connect. You can write a simple Kafka consumer that will read data from Kafka topic and write it to MQ.

```<code>    Properties props = new Properties();
     props.put("bootstrap.servers", "localhost:9092");
     props.put("group.id", "test");
     props.put("enable.auto.commit", "true");
     props.put("auto.commit.interval.ms", "1000");
     props.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
     props.put("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
     KafkaConsumer<String, String> consumer = new KafkaConsumer<>(props);
     consumer.subscribe(Arrays.asList("foo", "bar"));
     while (true) {
         ConsumerRecords<String, String> records = consumer.poll(100);
         for (ConsumerRecord<String, String> record : records)
//Insert code to append to MQ here
             System.out.printf("offset = %d, key = %s, value = %s%n", record.offset(), record.key(), record.value());
     }
</code>```

Body:
Kafka has a component called Kafka Connect. It is used to read and write data to/from Kafka into other systems such as Database in your case MQ.

Kafka connect can have two kind of connectors

Source connectors - Read data from an external system and write to Kafka (For eg. Read inserted/modified rows from a table in DB and insert into a topic in Kafka)

Sink Connector - Read message from Kafka write to external system.

The link you have added is a source connector, it will read messages from the MQ and write to Kafka.

For simple use case you do not need Kafka connect. You can write a simple Kafka consumer that will read data from Kafka topic and write it to MQ.

    Properties props = new Properties();
     props.put("bootstrap.servers", "localhost:9092");
     props.put("group.id", "test");
     props.put("enable.auto.commit", "true");
     props.put("auto.commit.interval.ms", "1000");
     props.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
     props.put("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
     KafkaConsumer<String, String> consumer = new KafkaConsumer<>(props);
     consumer.subscribe(Arrays.asList("foo", "bar"));
     while (true) {
         ConsumerRecords<String, String> records = consumer.poll(100);
         for (ConsumerRecord<String, String> record : records)
//Insert code to append to MQ here
             System.out.printf("offset = %d, key = %s, value = %s%n", record.offset(), record.key(), record.value());
     }


问:
changing a property value in an array
when i try to assign a new value to an array property i get the error :
Cannot assign to property: 'color' is a 'let' constant

```<code>struct car {
    let model: String
    let color: String
}

var myCars :[car] = [
    car(name:"model X", color: "black"),
    car(name:"model Y", color: "blue"),
    car(name:"roadster", color: "red"),
    car(name:"model S", color: "black"),
    car(name:"model 3", color: "black")
]

let colorFilter = dataSource.items.index(where: {$0.color == "black"})
myCars[colorFilter].color = "grey"

</code>```

replace all the items with color property set to "black" with "grey"

答:
In your car struct, you defined color with let so it is a constant. Change it to var if you want it to be variable.</p>

```<code>struct car {
    let model: String
    var color: String
}
</code>```

Title: changing a property value in an array

Body:
when i try to assign a new value to an array property i get the error :
Cannot assign to property: 'color' is a 'let' constant

struct car {
    let model: String
    let color: String
}

var myCars :[car] = [
    car(name:"model X", color: "black"),
    car(name:"model Y", color: "blue"),
    car(name:"roadster", color: "red"),
    car(name:"model S", color: "black"),
    car(name:"model 3", color: "black")
]

let colorFilter = dataSource.items.index(where: {$0.color == "black"})
myCars[colorFilter].color = "grey"

replace all the items with color property set to "black" with "grey"

Body:
In your car struct, you defined color with let so it is a constant. Change it to var if you want it to be variable.

struct car {
    let model: String
    var color: String
}


问:
Error : No instance of constructor matches the argument list
I'm making ascending sort code with reading input.txt file and saving out.txt file. I've already done that in c, but I want to use this in c++.
I'm a beginner of c++. Could someone help me? I Really want to solve this problem.

There are errors :

No instance of constructor matches the argument list ( "std::basic_ifstream<_ELEM, _Treaits>::get [대상_Elem=char, _Traits=std::char_traits]" )

"in C"

```<code>#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <stdio.h>

using namespace std;

void my_sort(int *number, int size);

void main(void)
{
    FILE* const pFile = fopen("input.txt", "r");
    if(pFile == NULL)
    {
        cout << "CAN'T OPEN!" << endl;
        return;
    }

    char szBuf[256];
    szBuf[sizeof(szBuf) - 1] = 0;
    int iSize = 0;
    while(fgets(szBuf, sizeof(szBuf) - 1, pFile))
        ++iSize;

    int* const piNumber = new int[iSize];

    rewind(pFile);

    int i = 0;
    while(fgets(szBuf, sizeof(szBuf) - 1, pFile))
    {
        const int iNumber = atoi(szBuf);
        piNumber[i++] = iNumber;
    }
    fclose(pFile);
    my_sort(piNumber, iSize);

    for(int j = 0; j < iSize; j++)
    {
        cout << piNumber[j] << " ";
    }
    cout << endl;
    delete[] piNumber;

}

void my_sort(int* number, int size)
{
     int i = 0, j = 0, temp = 0;

     for(j = 0;j < size; j++)
     {
          for(i = 0; i < size - 1; i++)
          {
               if(number[i] > number[i + 1])
               {
                    temp = number[i];
                    number[i] = number[i + 1];
                    number[i + 1] = temp;
               }
          }
     }
</code>```

"c++ with ERROR IN 'input', 'output' "

```<code>#include <iostream>
#include <fstream>
using namespace std;

void mySort(int* InputArrayPointer, int InputArraySize);

void main(void)
{
    ifstream input;
    input.open("input.txt", "r"); // ERROR
    if (input.fail())
    {
        cout << "CAN'T OPEN!" << endl;
        return;
    }

    char arr[256];
    arr[sizeof(arr) - 1] = 0;
    int size = 0;
    while (input.get(arr, sizeof(arr) - 1, input)) //ERROR
    ++size;

    int* const pointer = new int[size];

    rewind(input); //ERROR

    int i = 0;
   while (input.get(arr, sizeof(arr) - 1, input)) //ERROR
    {
        const int number = atoi(arr);
        pointer[i++] = number;
    }
    input.close();
    mySort(pointer, size);

    output.open("output.txt", "w"); //ERROR
    for (int j = 0; j < size; j++)
    {
        output << pointer[j] << endl;
    }
    delete[] pointer;
    output.close();
    }

void mySort(int* InputArrayPointer, int InputArraySize)
{
    int i = 0, j = 0, temp = 0;

    for (j = 0; j < InputArraySize; j++)
    {
        for (i = 0; i < InputArraySize - 1; i++)
        {
            if (InputArrayPointer[i] > InputArrayPointer[i + 1])
            {
                temp = InputArrayPointer[i];
                InputArrayPointer[i] = InputArrayPointer[i + 1];
                InputArrayPointer[i + 1] = temp;
            }
        }
    }
}
</code>```

ERROR----->

No instance of constructor matches the argument list ( "std::basic_ifstream<_ELEM, _Treaits>::get [대상_Elem=char, _Traits=std::char_traits]" )

答:
The mode you pass to input.open is not a string, like in C - it's a trait. Instead of

```<code>input.open("input.txt", "r"); // ERROR
</code>```

use

```<code>input.open("input.txt", ios_base::in); // ERROR
</code>```

For the output file, use ios_base::out - you also need to declare the output variable, which you don't appear to be be doing anywhere. You're also attempting to use a few functions like rewind which are used on C FILEs, rather than C++ streams.

Body:
I'm making ascending sort code with reading input.txt file and saving out.txt file. I've already done that in c, but I want to use this in c++.
I'm a beginner of c++. Could someone help me? I Really want to solve this problem.

There are errors :

No instance of constructor matches the argument list ( "std::basic_ifstream<_ELEM, _Treaits>::get [대상_Elem=char, _Traits=std::char_traits]" )

"in C"

#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <stdio.h>

using namespace std;

void my_sort(int *number, int size);

void main(void)
{
    FILE* const pFile = fopen("input.txt", "r");
    if(pFile == NULL)
    {
        cout << "CAN'T OPEN!" << endl;
        return;
    }

    char szBuf[256];
    szBuf[sizeof(szBuf) - 1] = 0;
    int iSize = 0;
    while(fgets(szBuf, sizeof(szBuf) - 1, pFile))
        ++iSize;

    int* const piNumber = new int[iSize];

    rewind(pFile);

    int i = 0;
    while(fgets(szBuf, sizeof(szBuf) - 1, pFile))
    {
        const int iNumber = atoi(szBuf);
        piNumber[i++] = iNumber;
    }
    fclose(pFile);
    my_sort(piNumber, iSize);

    for(int j = 0; j < iSize; j++)
    {
        cout << piNumber[j] << " ";
    }
    cout << endl;
    delete[] piNumber;

}

void my_sort(int* number, int size)
{
     int i = 0, j = 0, temp = 0;

     for(j = 0;j < size; j++)
     {
          for(i = 0; i < size - 1; i++)
          {
               if(number[i] > number[i + 1])
               {
                    temp = number[i];
                    number[i] = number[i + 1];
                    number[i + 1] = temp;
               }
          }
     }

"c++ with ERROR IN 'input', 'output' "

#include <iostream>
#include <fstream>
using namespace std;

void mySort(int* InputArrayPointer, int InputArraySize);

void main(void)
{
    ifstream input;
    input.open("input.txt", "r"); // ERROR
    if (input.fail())
    {
        cout << "CAN'T OPEN!" << endl;
        return;
    }

    char arr[256];
    arr[sizeof(arr) - 1] = 0;
    int size = 0;
    while (input.get(arr, sizeof(arr) - 1, input)) //ERROR
    ++size;

    int* const pointer = new int[size];

    rewind(input); //ERROR

    int i = 0;
   while (input.get(arr, sizeof(arr) - 1, input)) //ERROR
    {
        const int number = atoi(arr);
        pointer[i++] = number;
    }
    input.close();
    mySort(pointer, size);

    output.open("output.txt", "w"); //ERROR
    for (int j = 0; j < size; j++)
    {
        output << pointer[j] << endl;
    }
    delete[] pointer;
    output.close();
    }

void mySort(int* InputArrayPointer, int InputArraySize)
{
    int i = 0, j = 0, temp = 0;

    for (j = 0; j < InputArraySize; j++)
    {
        for (i = 0; i < InputArraySize - 1; i++)
        {
            if (InputArrayPointer[i] > InputArrayPointer[i + 1])
            {
                temp = InputArrayPointer[i];
                InputArrayPointer[i] = InputArrayPointer[i + 1];
                InputArrayPointer[i + 1] = temp;
            }
        }
    }
}

ERROR----->

No instance of constructor matches the argument list ( "std::basic_ifstream<_ELEM, _Treaits>::get [대상_Elem=char, _Traits=std::char_traits]" )

Body:
The mode you pass to input.open is not a string, like in C - it's a trait. Instead of

input.open("input.txt", "r"); // ERROR

use

input.open("input.txt", ios_base::in); // ERROR

For the output file, use ios_base::out - you also need to declare the output variable, which you don't appear to be be doing anywhere. You're also attempting to use a few functions like rewind which are used on C FILEs, rather than C++ streams.


问:
Python3 - Return CSV with row-level errors for missing data
New to Python. I'm importing a CSV, then if any data is missing I need to return a CSV with an additional column to indicate which rows are missing data. Colleague suggested that I import CSV into a dataframe, then create a new dataframe with a "Comments" column, fill it with a comment on the intended rows, and append it to the original dataframe. I'm stuck at the step of filling my new dataframe, "dferr", with the correct number of rows that would match up to "dfinput".

Have Googled, "pandas csv return error column where data is missing", but haven't found anything related to creating a new CSV that marks bad rows. I don't even know if the proposed way is the best way to go about this.

```<code>import pandas as pd

dfinput = None
try:
    dfinput = pd.read_csv(r"C:\file.csv")
except:
    print("Uh oh!")

if dfinput is None:
    print("Ack!")
    quit(10)

dfinput.reset_index(level=None, drop=False, inplace=True, col_level=0,
col_fill='')

dferr = pd.DataFrame(columns=['comment'])
print("Empty DataFrame", dferr, sep='\n')
</code>```

Expected results: "dferr" would have an index column with number of rows equal to "dfinput", and comments on the correct rows where "dfinput" has missing values.

Actual results: "dferr" is empty.

答:
My understanding of 'missing data' here would be null values. It seems that for every row, you want the names of null fields.

```<code>df = pd.DataFrame([[1,2,3],
                   [4,None,6],
                   [None,8,None]],
                  columns=['foo','bar','baz'])
# Create a dataframe of True/False, True where a criterion is met
# (in this case, a null value)
nulls = df.isnull()

# Iterate through every row of *nulls*,
# and extract the column names where the value is True by boolean indexing
colnames = nulls.columns
null_labels = nulls.apply(lambda s:colnames[s], axis=1)

# Now you have a pd.Series where every entry is an array
# (technically, a pd.Index object)
# Pandas arrays have a vectorized .str.join method:
df['nullcols'] = null_labels.str.join(', ')
</code>```

The .apply() method in pandas can sometimes be a bottleneck in your code; there are ways to avoid using this, but here it seemed to be the simplest solution I could think of.

EDIT: Here's an alternate one-liner (instead of using .apply) that might cut down computation time slightly:

```<code>import numpy as np
df['nullcols'] = [colnames[x] for x in nulls.values]
</code>```

This might be even faster (a bit more work is required):

```<code>np.where(df.isnull(),df.columns,'')
</code>```

Body:
New to Python. I'm importing a CSV, then if any data is missing I need to return a CSV with an additional column to indicate which rows are missing data. Colleague suggested that I import CSV into a dataframe, then create a new dataframe with a "Comments" column, fill it with a comment on the intended rows, and append it to the original dataframe. I'm stuck at the step of filling my new dataframe, "dferr", with the correct number of rows that would match up to "dfinput".

Have Googled, "pandas csv return error column where data is missing", but haven't found anything related to creating a new CSV that marks bad rows. I don't even know if the proposed way is the best way to go about this.

import pandas as pd

dfinput = None
try:
    dfinput = pd.read_csv(r"C:\file.csv")
except:
    print("Uh oh!")

if dfinput is None:
    print("Ack!")
    quit(10)

dfinput.reset_index(level=None, drop=False, inplace=True, col_level=0,
col_fill='')

dferr = pd.DataFrame(columns=['comment'])
print("Empty DataFrame", dferr, sep='\n')

Expected results: "dferr" would have an index column with number of rows equal to "dfinput", and comments on the correct rows where "dfinput" has missing values.

Actual results: "dferr" is empty.

Body:
My understanding of 'missing data' here would be null values. It seems that for every row, you want the names of null fields.

df = pd.DataFrame([[1,2,3],
                   [4,None,6],
                   [None,8,None]],
                  columns=['foo','bar','baz'])
# Create a dataframe of True/False, True where a criterion is met
# (in this case, a null value)
nulls = df.isnull()

# Iterate through every row of *nulls*,
# and extract the column names where the value is True by boolean indexing
colnames = nulls.columns
null_labels = nulls.apply(lambda s:colnames[s], axis=1)

# Now you have a pd.Series where every entry is an array
# (technically, a pd.Index object)
# Pandas arrays have a vectorized .str.join method:
df['nullcols'] = null_labels.str.join(', ')

The .apply() method in pandas can sometimes be a bottleneck in your code; there are ways to avoid using this, but here it seemed to be the simplest solution I could think of.

EDIT: Here's an alternate one-liner (instead of using .apply) that might cut down computation time slightly:

import numpy as np
df['nullcols'] = [colnames[x] for x in nulls.values]

This might be even faster (a bit more work is required):

np.where(df.isnull(),df.columns,'')


问:
Boost stack-trace not showing function names and line numbers
I was exploring the boost::stacktrace by trying a simple example to print the call stack of a recursive function.

```<code>#include "boost/stacktrace.hpp"

int factorial(int x){
    if (x < 2) {
        std::cout << boost::stacktrace::stacktrace();
        return 1;
    }
    return x * factorial(x - 1);
}

int main(int ac, char *av[]) {
    std::cout << factorial(4);
}
</code>```

However the output of the code does not include any information about the function name and line number:

```<code> 0# 0x000055A6F6B57C0F in /home/user/myapp
 1# 0x000055A6F6B57C42 in /home/user/myapp
 2# 0x000055A6F6B57C42 in /home/user/myapp
 3# 0x000055A6F6B57C42 in /home/user/myapp
 4# 0x000055A6F6B57C9D in /home/user/myapp
 5# __libc_start_main in /lib/x86_64-linux-gnu/libc.so.6
 6# 0x000055A6F6B57AEA in /home/user/myapp
</code>```

This is in contrast with the sample output from the boost website:
(copied from https://www.boost.org/doc/libs/1_68_0/doc/html/stacktrace/getting_started.html#stacktrace.getting_started.how_to_print_current_call_stack)

```<code>0# bar(int) at /path/to/source/file.cpp:70
1# bar(int) at /path/to/source/file.cpp:70
2# bar(int) at /path/to/source/file.cpp:70
3# bar(int) at /path/to/source/file.cpp:70
4# main at /path/to/main.cpp:93
5# __libc_start_main in /lib/x86_64-linux-gnu/libc.so.6
6# _start
</code>```

Why don't I see the source line numbers and function names in the stack-trace output?

I have enabled debugging information in my project-level CMakeList.txt:

```<code>set(CMAKE_BUILD_TYPE Debug)
</code>```

I can also see the symbols are present when demangling the binary file:

```<code>nm -an myapp | c++filt | grep factorial

0000000000000f40 t _GLOBAL__sub_I__Z9factoriali
00000000000010f0 T factorial(int)
</code>```

答:
I do not have enough reputation to comment, so I'll extend jordi's answer here:

Make sure that debug info is enabled: e.g., -g

Link against libdl: -ldl

Define one of the necessary macros (to get line numbers): e.g., -DBOOST_STACKTRACE_USE_ADDR2LINE

Compile and link with -no-pie and -fno-pie options.

Body:
I was exploring the boost::stacktrace by trying a simple example to print the call stack of a recursive function.

#include "boost/stacktrace.hpp"

int factorial(int x){
    if (x < 2) {
        std::cout << boost::stacktrace::stacktrace();
        return 1;
    }
    return x * factorial(x - 1);
}

int main(int ac, char *av[]) {
    std::cout << factorial(4);
}

However the output of the code does not include any information about the function name and line number:

 0# 0x000055A6F6B57C0F in /home/user/myapp
 1# 0x000055A6F6B57C42 in /home/user/myapp
 2# 0x000055A6F6B57C42 in /home/user/myapp
 3# 0x000055A6F6B57C42 in /home/user/myapp
 4# 0x000055A6F6B57C9D in /home/user/myapp
 5# __libc_start_main in /lib/x86_64-linux-gnu/libc.so.6
 6# 0x000055A6F6B57AEA in /home/user/myapp

This is in contrast with the sample output from the boost website:
(copied from https://www.boost.org/doc/libs/1_68_0/doc/html/stacktrace/getting_started.html#stacktrace.getting_started.how_to_print_current_call_stack)

0# bar(int) at /path/to/source/file.cpp:70
1# bar(int) at /path/to/source/file.cpp:70
2# bar(int) at /path/to/source/file.cpp:70
3# bar(int) at /path/to/source/file.cpp:70
4# main at /path/to/main.cpp:93
5# __libc_start_main in /lib/x86_64-linux-gnu/libc.so.6
6# _start

Why don't I see the source line numbers and function names in the stack-trace output?

I have enabled debugging information in my project-level CMakeList.txt:

set(CMAKE_BUILD_TYPE Debug)

I can also see the symbols are present when demangling the binary file:

nm -an myapp | c++filt | grep factorial

0000000000000f40 t _GLOBAL__sub_I__Z9factoriali
00000000000010f0 T factorial(int)


问:
Change screen resolution info in Geckofx
I am writing a browser application using C# Language and GeckoFX Browser library.

When i test the browser with whatismybrowser.com, it show my screen resolution (1366x768). I want to change this info like firefox responsiveUI tool.

I try the preference setting devtools.responsiveUI.currentPreset but it still not work.

I need help to change the screen resolution info, so any website will catch my custom screen resolution. Thanks!

My custom browser

Firefox responsiveUI tool

答:
GeckoFX is using the same underlying component as the Firefox Browser. If you check Firefox, it also shows your computer screen. I don't think faking the screen resolution is possible.

You didn't mention your reason. If the reason is design related, you shouldn't have to bother with the screen size, the browser size is all that matters.


问:
Training using multiple GPUs
I want to train RETURRN on LibriSpeech dataset using multiple GPUs, but don't know how to do.
Is this possible? I don't see any option to enable it in .config file.</p>

答: Yes, it is possible. You find some description in the documentation. It currently uses Horovod, and basically you have to set use_horovod = True, but please see the documentation for further details.

Title: Training using multiple GPUs


问:
How to monitor number of RXJS subscriptions?
I'm using an Observable to provide event subscription interface for clients from a global resource, and I need to manage that resource according to the number of active subscriptions:

Allocate global resource when the number of subscriptions becomes greater than 0

Release global resource when the number of subscriptions becomes 0

Adjust the resource usage strategy based on the number of subscriptions

What is the proper way in RXJS to monitor the number of active subscriptions?

How to implement the following within RXJS syntax? -

```<code>const myEvent: Observable<any> = new Observable();

myEvent.onSubscription((newCount: number, prevCount: number) => {
   if(newCount === 0) {
      // release global resource
   } else {
      // allocate global resource, if not yet allocated
   }
   // for a scalable resource usage / load,
   // re-configure it, based on newCount
});
</code>```

I wouldn't expect a guaranteed notification on each change, hence newCount + prevCount params.

UPDATE-1

This is not a duplicate to this, because I need to be notified when the number of subscriptions changes, and not just to get the counter at some point.

UPDATE-2

Without any answer so far, I quickly came up with a very ugly and limited work-around, through complete incapsulation, and specifically for type Subject. Hoping very much to find a proper solution.

UPDATE-3

After a few answers, I'm still not sure how to implement what I'm trying, which is the following:

```<code>class CustomType {

}

class CountedObservable<T> extends Observable<T> {

    private message: string; // random property

    public onCount; // magical Observable that needs to be implemented

    constructor(message: string) {
        // super(); ???
        this.message = message;
    }

    // random method
    public getMessage() {
        return this.message;
    }
}

const a = new CountedObservable<CustomType>('hello'); // can create directly

const msg = a.getMessage(); // can call methods

a.subscribe((data: CustomType) => {
    // handle subscriptions here;
});

// need that magic onCount implemented, so I can do this:
a.onCount.subscribe((newCount: number, prevCont: number) => {
    // manage some external resources
});
</code>```

How to implement such class CountedObservable above, which would let me subscribe to itself, as well as its onCount property to monitor the number of its clients/subscriptions?

UPDATE-4

All suggested solutions seemed overly complex, and even though I accepted one of the answers, I ended up with a completely custom solution one of my own.

答:
First of all, I very much appreciate how much time and effort people have committed trying to answer my question! And I am sure those answers will prove to be a useful guideline to other developers, solving similar scenarios with RXJS.

However, specifically for what I was trying to get out of RXJS, I found in the end that I am better off not using it at all. I specifically wanted the following:

A generic, easy-to-use interface for subscribing to notifications, plus monitoring subscriptions - all in one. With RXJS, the best I would end up is some workarounds that appear to be needlessly convoluted or even cryptic to developers who are not experts in RXJS. That is not what I would consider a friendly interface, more like something that rings over-engineering.

I ended up with a custom, much simpler interface that can do everything I was looking for:

```<code>export class Subscription {
    private unsub: () => void;

    constructor(unsub: () => void) {
        this.unsub = unsub;
    }

    public unsubscribe(): void {
        if (this.unsub) {
            this.unsub();
            this.unsub = null; // to prevent repeated calls
        }
    }
}

export class Observable<T = any> {
    protected subs: ((data: T) => void)[] = [];

    public subscribe(cb: (data: T) => void): Subscription {
        this.subs.push(cb);
        return new Subscription(this.createUnsub(cb));
    }

    public next(data: T): void {
        // we iterate through a safe clone, in case an un-subscribe occurs;
        // and since Node.js is the target, we are using process.nextTick:
        [...this.subs].forEach(cb => process.nextTick(() => cb(data)));
    }

    protected createUnsub(cb) {
        return () => {
            this.subs.splice(this.subs.indexOf(cb), 1);
        };
    }
}

export interface ISubCounts {
    newCount: number;
    prevCount: number;
}

export class CountedObservable<T = any> extends Observable<T> {
    readonly onCount: Observable<ISubCounts> = new Observable();

    protected createUnsub(cb) {
        const s = this.subs;
        this.onCount.next({newCount: s.length, prevCount: s.length - 1});
        return () => {
            s.splice(s.indexOf(cb), 1);
            this.onCount.next({newCount: s.length, prevCount: s.length + 1});
        };
    }
}
</code>```

It is both small and elegant, and lets me do everything I needed to begin with, in a safe and friendly manner. I can do the same subscribe and onCount.subscribe, and get all the same notifications:

```<code>const a = new CountedObservable<string>();

const countSub = a.onCount.subscribe(({newCount, prevCount}) => {
    console.log('COUNTS:', newCount, prevCount);
});

const sub1 = a.subscribe(data => {
    console.log('SUB-1:', data);
});

const sub2 = a.subscribe(data => {
    console.log('SUB-2:', data);
});

a.next('hello');

sub1.unsubscribe();
sub2.unsubscribe();
countSub.unsubscribe();
</code>```

I hope this will help somebody else also.

P.S. I further improved it as an independent module.

Body:
I'm using an Observable to provide event subscription interface for clients from a global resource, and I need to manage that resource according to the number of active subscriptions:

Allocate global resource when the number of subscriptions becomes greater than 0

Release global resource when the number of subscriptions becomes 0

Adjust the resource usage strategy based on the number of subscriptions

What is the proper way in RXJS to monitor the number of active subscriptions?

How to implement the following within RXJS syntax? -

const myEvent: Observable<any> = new Observable();

myEvent.onSubscription((newCount: number, prevCount: number) => {
   if(newCount === 0) {
      // release global resource
   } else {
      // allocate global resource, if not yet allocated
   }
   // for a scalable resource usage / load,
   // re-configure it, based on newCount
});

I wouldn't expect a guaranteed notification on each change, hence newCount + prevCount params.

UPDATE-1

This is not a duplicate to this, because I need to be notified when the number of subscriptions changes, and not just to get the counter at some point.

UPDATE-2

Without any answer so far, I quickly came up with a very ugly and limited work-around, through complete incapsulation, and specifically for type Subject. Hoping very much to find a proper solution.

UPDATE-3

After a few answers, I'm still not sure how to implement what I'm trying, which is the following:

class CustomType {

}

class CountedObservable<T> extends Observable<T> {

    private message: string; // random property

    public onCount; // magical Observable that needs to be implemented

    constructor(message: string) {
        // super(); ???
        this.message = message;
    }

    // random method
    public getMessage() {
        return this.message;
    }
}

const a = new CountedObservable<CustomType>('hello'); // can create directly

const msg = a.getMessage(); // can call methods

a.subscribe((data: CustomType) => {
    // handle subscriptions here;
});

// need that magic onCount implemented, so I can do this:
a.onCount.subscribe((newCount: number, prevCont: number) => {
    // manage some external resources
});

How to implement such class CountedObservable above, which would let me subscribe to itself, as well as its onCount property to monitor the number of its clients/subscriptions?

UPDATE-4

All suggested solutions seemed overly complex, and even though I accepted one of the answers, I ended up with a completely custom solution one of my own.

Body:
First of all, I very much appreciate how much time and effort people have committed trying to answer my question! And I am sure those answers will prove to be a useful guideline to other developers, solving similar scenarios with RXJS.

However, specifically for what I was trying to get out of RXJS, I found in the end that I am better off not using it at all. I specifically wanted the following:

A generic, easy-to-use interface for subscribing to notifications, plus monitoring subscriptions - all in one. With RXJS, the best I would end up is some workarounds that appear to be needlessly convoluted or even cryptic to developers who are not experts in RXJS. That is not what I would consider a friendly interface, more like something that rings over-engineering.

I ended up with a custom, much simpler interface that can do everything I was looking for:

export class Subscription {
    private unsub: () => void;

    constructor(unsub: () => void) {
        this.unsub = unsub;
    }

    public unsubscribe(): void {
        if (this.unsub) {
            this.unsub();
            this.unsub = null; // to prevent repeated calls
        }
    }
}

export class Observable<T = any> {
    protected subs: ((data: T) => void)[] = [];

    public subscribe(cb: (data: T) => void): Subscription {
        this.subs.push(cb);
        return new Subscription(this.createUnsub(cb));
    }

    public next(data: T): void {
        // we iterate through a safe clone, in case an un-subscribe occurs;
        // and since Node.js is the target, we are using process.nextTick:
        [...this.subs].forEach(cb => process.nextTick(() => cb(data)));
    }

    protected createUnsub(cb) {
        return () => {
            this.subs.splice(this.subs.indexOf(cb), 1);
        };
    }
}

export interface ISubCounts {
    newCount: number;
    prevCount: number;
}

export class CountedObservable<T = any> extends Observable<T> {
    readonly onCount: Observable<ISubCounts> = new Observable();

    protected createUnsub(cb) {
        const s = this.subs;
        this.onCount.next({newCount: s.length, prevCount: s.length - 1});
        return () => {
            s.splice(s.indexOf(cb), 1);
            this.onCount.next({newCount: s.length, prevCount: s.length + 1});
        };
    }
}

It is both small and elegant, and lets me do everything I needed to begin with, in a safe and friendly manner. I can do the same subscribe and onCount.subscribe, and get all the same notifications:

const a = new CountedObservable<string>();

const countSub = a.onCount.subscribe(({newCount, prevCount}) => {
    console.log('COUNTS:', newCount, prevCount);
});

const sub1 = a.subscribe(data => {
    console.log('SUB-1:', data);
});

const sub2 = a.subscribe(data => {
    console.log('SUB-2:', data);
});

a.next('hello');

sub1.unsubscribe();
sub2.unsubscribe();
countSub.unsubscribe();

I hope this will help somebody else also.

P.S. I further improved it as an independent module.


问:
Jquery plugin with api
How can I retrieve API variables from a plugin. As per the Jquery Authoring documentation, here is plugin structure:

```<code>(function( $ ){

    var methods = {

        init : function( options ) {

            return this.each(function() {
                var settings = {
                    'height' : 10,
                    'width' : 10
                };

                if ( options ) { $.extend( settings, options ); }

                $('<div>', {
                    css : {
                        height : settings.height,
                        width : settings.width,
                    }
                }).appendTo(this);
            });

        }

    };

    $.fn.myPlugin = function( method ) {

        if ( methods[method] ) {
            return methods[method].apply( this, Array.prototype.slice.call( arguments, 1 ));
        } else if ( typeof method === 'object' || ! method ) {
            return methods.init.apply( this, arguments );
        } else {
            $.error( 'Method ' +  method + ' does not exist on jQuery.element' );
        }

    };

})( jQuery );
</code>```

I would like to be able to do the following :

```<code>var element = $('div').myPlugin();
console.log(element.properties);
</code>```

In properties, I would have a function that returns the height and width of my Div. How would I go about creating the properties variable in this design ?

thanks

答:
You would get rid of...

```<code>return this.each(function() { ... });
</code>```

...and have your plugin return something such as...

```<code>return {
   'properties': {
       'width': calculatedWidth,
       'height': calculatedHeight
    }
}
</code>```

However, doing this will mean you can not chain another method.

Title: Jquery plugin with api

Body:
How can I retrieve API variables from a plugin. As per the Jquery Authoring documentation, here is plugin structure:

(function( $ ){

    var methods = {

        init : function( options ) {

            return this.each(function() {
                var settings = {
                    'height' : 10,
                    'width' : 10
                };

                if ( options ) { $.extend( settings, options ); }

                $('
', {
                    css : {
                        height : settings.height,
                        width : settings.width,
                    }
                }).appendTo(this);
            });

        }

    };

    $.fn.myPlugin = function( method ) {

        if ( methods[method] ) {
            return methods[method].apply( this, Array.prototype.slice.call( arguments, 1 ));
        } else if ( typeof method === 'object' || ! method ) {
            return methods.init.apply( this, arguments );
        } else {
            $.error( 'Method ' +  method + ' does not exist on jQuery.element' );
        }

    };

})( jQuery );

I would like to be able to do the following :

var element = $('div').myPlugin();
console.log(element.properties);

In properties, I would have a function that returns the height and width of my Div. How would I go about creating the properties variable in this design ?

thanks

Body:
You would get rid of...

return this.each(function() { ... });

...and have your plugin return something such as...

return {
   'properties': {
       'width': calculatedWidth,
       'height': calculatedHeight
    }
}

However, doing this will mean you can not chain another method.