问:
FeatureModule fails during an AOT build when static forRoot has arguments
I am encountering an AOT build issue using Angular@5.1.0.

The error is:

```<code>ERROR in Error during template compile of 'AppModule'
  Function calls are not supported in decorators but 'FeatureModule' was called.
</code>```

feature.module.ts

```<code>@NgModule({
    imports: [
        BrowserModule,
        RouterModule.forRoot([])
    ],
    declarations: [
        ...
    ],
    exports: [
        ...
    ]
})
export class FeatureModule{
    static forRoot(items:any[]): ModuleWithProviders {
        const routes:Routes = items.map(t=> {
            return { path: t.name, component: t.component };
        });

        return {
            ngModule: FeatureModule,
            providers: [
                provideRoutes(routes)
            ]
        }
    }
}
</code>```

This compiles successfully in non-aot builds. This seems to only be a problem for AOT builds.

Why is this error happening?

答:
Ok, it took me a while to figure this out.
TLDR: the forRoot method must dead simple, otherwise the AOT compiler complains.

To make it simple, I had to:

Remove branching logic and function calls from the forRoot method.

Implement the logic to map the items to routes into a factory provider, rather than inlining it inside the forRoot method.

Use Router.resetConfig to add the routes dynamically within the factory impelmentation.

Add an ANALYZE_FOR_ENTRY_COMPONENTS provider so that any components passed in would be added to entryComponents automatically as part of the module.

Import RouterModule.forChild([]) into FeatureModule because I use the components from @angular/router.

Import RouterModule.forRoot([]) into AppModule because it provides the application-wide Router service.

Final Solution

```<code>export const Items = new InjectionToken<any[]>('items');
export function InitMyService(router:Router, items:any[]) {
     var routes:Routes =  items.map(t=> { return { path: t.name, component: t.component, outlet: 'modal' }});
     var r = router.config.concat(routes);
     router.resetConfig(r);
     return new MyService(router);
}

@NgModule({
    imports: [
        CommonModule,
        RouterModule.forChild([])
    ],
    declarations: [
        MyComponent
    ],
    exports: [
        MyComponent
    ],
    providers: [

    ]
})
export class FeatureModule {
    static forRoot(items:any[]): ModuleWithProviders {
        return {
            ngModule: FeatureModule,
            providers: [
                { provide: Items, useValue: items},
                { provide: ANALYZE_FOR_ENTRY_COMPONENTS, multi: true, useValue: items},
                { provide: MyService, useFactory: InitMyService, deps:[Router, Items] }
            ]
        }
    }
}
</code>```

app.module.ts

```<code>@NgModule({
  imports:      [
      BrowserModule,
      RouterModule.forRoot([]),
      FeatureModule.forRoot([{name: 'test', component: TestComponent}])
    ],
  declarations: [ AppComponent, TestComponent ],
  bootstrap:    [ AppComponent ],
  providers: [
  ],
  exports: [AppComponent]
})
export class AppModule {
}
</code>```

The key to solving this was the realization that RouterModule.forChild() does not register any router services. This is intentional so that any module can import the RouterModule and take advantage of its components, without actually registering any services.  At the AppModule level, I still needed to register the Router service as a singleton by importing RouterModule.forRoot() into AppModule.

Body:
I am encountering an AOT build issue using Angular@5.1.0.

The error is:

ERROR in Error during template compile of 'AppModule'
  Function calls are not supported in decorators but 'FeatureModule' was called.

feature.module.ts

@NgModule({
    imports: [
        BrowserModule,
        RouterModule.forRoot([])
    ],
    declarations: [
        ...
    ],
    exports: [
        ...
    ]
})
export class FeatureModule{
    static forRoot(items:any[]): ModuleWithProviders {
        const routes:Routes = items.map(t=> {
            return { path: t.name, component: t.component };
        });

        return {
            ngModule: FeatureModule,
            providers: [
                provideRoutes(routes)
            ]
        }
    }
}

This compiles successfully in non-aot builds. This seems to only be a problem for AOT builds.

Why is this error happening?

Body:
Ok, it took me a while to figure this out.
TLDR: the forRoot method must dead simple, otherwise the AOT compiler complains.

To make it simple, I had to:

Remove branching logic and function calls from the forRoot method.

Implement the logic to map the items to routes into a factory provider, rather than inlining it inside the forRoot method.

Use Router.resetConfig to add the routes dynamically within the factory impelmentation.

Add an ANALYZE_FOR_ENTRY_COMPONENTS provider so that any components passed in would be added to entryComponents automatically as part of the module.

Import RouterModule.forChild([]) into FeatureModule because I use the components from @angular/router.

Import RouterModule.forRoot([]) into AppModule because it provides the application-wide Router service.

Final Solution

export const Items = new InjectionToken<any[]>('items');
export function InitMyService(router:Router, items:any[]) {
     var routes:Routes =  items.map(t=> { return { path: t.name, component: t.component, outlet: 'modal' }});
     var r = router.config.concat(routes);
     router.resetConfig(r);
     return new MyService(router);
}

@NgModule({
    imports: [
        CommonModule,
        RouterModule.forChild([])
    ],
    declarations: [
        MyComponent
    ],
    exports: [
        MyComponent
    ],
    providers: [

    ]
})
export class FeatureModule {
    static forRoot(items:any[]): ModuleWithProviders {
        return {
            ngModule: FeatureModule,
            providers: [
                { provide: Items, useValue: items},
                { provide: ANALYZE_FOR_ENTRY_COMPONENTS, multi: true, useValue: items},
                { provide: MyService, useFactory: InitMyService, deps:[Router, Items] }
            ]
        }
    }
}

app.module.ts

@NgModule({
  imports:      [
      BrowserModule,
      RouterModule.forRoot([]),
      FeatureModule.forRoot([{name: 'test', component: TestComponent}])
    ],
  declarations: [ AppComponent, TestComponent ],
  bootstrap:    [ AppComponent ],
  providers: [
  ],
  exports: [AppComponent]
})
export class AppModule {
}

The key to solving this was the realization that RouterModule.forChild() does not register any router services. This is intentional so that any module can import the RouterModule and take advantage of its components, without actually registering any services.  At the AppModule level, I still needed to register the Router service as a singleton by importing RouterModule.forRoot() into AppModule.


来源: stackexchange

问:
Zend framework 3 Class 'Album\Controller\AlbumController' not found
enter image description herei'm trying to add a new module named as Album in Zend Skeleton application but however while accessing it through URL it throws an error below.i have spent almost 5 hours but did not find any solution.Any help will be appreciated.

File:/var/www/zf2-tutorial/vendor/zendframework/zend-servicemanager/src/Factory/InvokableFactory.php:30

Message:Class Album/Controller/AlbumController not found.

stack trace
      #0 /var/www/zf2-tutorial/vendor/zendframework/zend-
      servicemanager/src/ServiceManager.php(758):
      Zend\ServiceManager\Factory\InvokableFactory-
  __invoke(Object(Zend\ServiceManager\ServiceManager),
       'Album\Controlle...', NULL)
       #1 /var/www/zf2-tutorial/vendor/zendframework/zend-
       servicemanager/src/ServiceManager.php(200):
      Zend\ServiceManager\ServiceManager->doCreate('Album\Controlle...')
      #2 /var/www/zf2-tutorial/vendor/zendframework/zend-
       servicemanager/src/AbstractPluginManager.php(141):
       Zend\ServiceManager\ServiceManager->get('Album\Controlle...')
       #3 /var/www/zf2-tutorial/vendor/zendframework/zend-

       mvc/src/DispatchListener.php(95):
       Zend\ServiceManager\AbstractPluginManager->get('Album\Controlle...')
       #4 /var/www/zf2-tutorial/vendor/zendframework/zend-
       eventmanager/src/EventManager.php(322): Zend\Mvc\DispatchListener-
  onDispatch(Object(Zend\Mvc\MvcEvent))
       #5 /var/www/zf2-tutorial/vendor/zendframework/zend-
       eventmanager/src/EventManager.php(179):
      Zend\EventManager\EventManager-
  triggerListeners(Object(Zend\Mvc\MvcEvent), Object(Closure))
       #6 /var/www/zf2-tutorial/vendor/zendframework/zend-
        mvc/src/Application.php(332): Zend\EventManager\EventManager-
  triggerEventUntil(Object(Closure), Object(Zend\Mvc\MvcEvent))
       #7 /var/www/zf2-tutorial/public/index.php(48): Zend\Mvc\Application-
  run()
       #8 {main}

```<code>**module.config.php**
<?php
namespace Album;

  return array(
  'controllers' => array(
    'invokables' => array(
        'Album\Controller\Album' => Controller\AlbumController::class

    ),
),

'router' => array(
    'routes' => array(
        'album' => array(
            'type'    => 'segment',
            'options' => array(
                'route'    => '/album[/:action][/:id]',
                'defaults' => array(
                    'controller' => Controller\Album::class,
                    'action'     => 'index',
                ),
                'constraints' => array(
                    'controller' => '[a-zA-Z][a-zA-Z0-9_-]*',
                    'action' => '[a-zA-Z][a-zA-Z0-9_-]*',
                    'id'     => '[0-9]+',
                ),

            ),
        ),
    ),
),

'view_manager' => array(
    'template_path_stack' => array(
        'album' => __DIR__ . '/../view',
    ),
),
);
 ?>

**AlbumController.php**
<?php
namespace Album;

use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;

class AlbumController extends AbstractActionController
{
protected $albumTable;
public function getAlbumTable()
{
    if (! $this->albumTable) {
        $sm = $this->getServiceLocator();
        $this->albumTable = $sm->get('Album\Model\AlbumTable');
    }
    return $this->albumTable;
}

public function indexAction()
{
    return new ViewModel(array(
        'albums' => '',
    ));
}

public function addAction()
{

}

public function editAction()
{

}

public function deleteAction()
{

}

}

**Album.php**
 <?php
namespace Album\Model;

class Album
{

public $id;

public $artist;

public $title;

public function exchangeArray($data)
{
    $this->id = (! empty($data['id'])) ? $data['id'] : null;
    $this->artist = (! empty($data['artist'])) ? $data['artist'] :
     null;
    $this->title = (! empty($data['title'])) ? $data['title'] : null;
 }
 }

 **AlbumTable.php**
<?php
 use Zend\Db\TableGateway\TableGateway;

class AlbumTable
{

protected $tableGateway;

public function __construct(TableGateway $tableGateway)
{
    $this->tableGateway = $tableGateway;
}

public function fetchAll()
{
    $resultSet = $this->tableGateway->select();
    return $resultSet;
}

public function getAlbum($id)
{
    $id = (int) $id;
    $rowset = $this->tableGateway->select(array(
        'id' => $id
    ));
    $row = $rowset->current();
    if (! $row) {
        throw new \Exception("Could not find row $id");
    }
    return $row;
}

public function saveAlbum(Album $album)
{
    $data = array(
        'artist' => $album->artist,
        'title' => $album->title
    );

    $id = (int) $album->id;
    if ($id == 0) {
        $this->tableGateway->insert($data);
    } else {
        if ($this->getAlbum($id)) {
            $this->tableGateway->update($data, array(
                'id' => $id
            ));
        } else {
            throw new \Exception('Album id does not exist');
        }
    }
}

public function deleteAlbum($id)
{
    $this->tableGateway->delete(array(
        'id' => (int) $id
    ));
  }
  }

   **Module.php**
<?php
 namespace Album;

 use Zend\ModuleManager\Feature\AutoloaderProviderInterface;
 use Zend\ModuleManager\Feature\ConfigProviderInterface;
 u    se Album\Model\Album;
 use Album\Model\AlbumTable;
 use Zend\Db\ResultSet\ResultSet;
 use Zend\Db\TableGateway\TableGateway;

 class Module implements AutoloaderProviderInterface,
 ConfigProviderInterface
   {

public function getAutoloaderConfig()
{
    return array(
        'Zend\Loader\ClassMapAutoloader' => array(
            __DIR__ . '/autoload_classmap.php'
        ),
        'Zend\Loader\StandardAutoloader' => array(
            'namespaces' => array(
                __NAMESPACE__ => __DIR__ . '/src/' . __NAMESPACE__
            )
        )

    );
}

public function getConfig()
{
    return include __DIR__ . '/config/module.config.php';

}

public function getServiceConfig()
{
     return array(
        'factories' => array(
            'Album\Model\AlbumTable' => function ($sm) {
                $tableGateway = $sm->get('AlbumTableGateway');
                $table = new AlbumTable($tableGateway);
                return $table;
            },
            'AlbumTableGateway' => function ($sm) {
                $dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
                $resultSetPrototype = new ResultSet();
                $resultSetPrototype->setArrayObjectPrototype(new
              Album());
                return new TableGateway('album', $dbAdapter, null,
     $resultSetPrototype);
            }
        )
    );
}
public function getControllerConfig()
 {
    return [
        'factories' => [
            Controller\AlbumController::class => function($container)
  {
                return new Controller\AlbumController(
                    $container->get(Model\AlbumTable::class)
                    );
            },
            ],
            ];
  }
 }

  ?>
 **composer.json**

{
"name" : "zendframework/skeleton-application",
"description" : "Skeleton Application for Zend Framework zend-mvc
 applications",
"type" : "project",
"license" : "BSD-3-Clause",
"keywords" : [
    "framework",
    "mvc",
    "zf"
],
"homepage" : "http://framework.zend.com/",
"minimum-stability" : "dev",
"prefer-stable" : true,
"require" : {
    "php" : "^5.6 || ^7.0",
    "zendframework/zend-component-installer" : "^1.0 || ^0.7 ||
 ^1.0.0-dev@dev",
    "zendframework/zend-mvc" : "^3.0.1",
    "zfcampus/zf-development-mode" : "^3.0"
},
"autoload" : {
    "psr-4" : {
        "Application\\" : "module/Application/src/"

 }
},
"autoload-dev" : {
    "psr-4" : {
        "ApplicationTest\\" : "module/Application/test/"
    }
},
"extra" : {
    "zend-skeleton-installer" : [{
            "name" : "zendframework/zend-developer-tools",
            "constraint" : "^1.1.0",
            "prompt" : "Would you like to install the developer
   toolbar?",
            "module" : true,
            "dev" : true
        }, {
            "name" : "zendframework/zend-cache",
            "constraint" : "^2.7.1",
            "prompt" : "Would you like to install caching support?",
            "module" : true
        }, {
            "name" : "zendframework/zend-db",
            "constraint" : "^2.8.1",
            "prompt" : "Would you like to install database support
    (installs zend-db)?",
            "module" : true
        }, {
            "name" : "zendframework/zend-mvc-form",
            "constraint" : "^1.0",
            "prompt" : "Would you like to install forms support?",
            "module" : true
        }, {
            "name" : "zendframework/zend-json",
            "constraint" : "^3.0",
            "prompt" : "Would you like to install JSON
     de/serialization support?"
        }, {
            "name" : "zendframework/zend-log",
            "constraint" : "^2.9",
            "prompt" : "Would you like to install logging support?",
            "module" : true
        }, {
            "name" : "zendframework/zend-mvc-console",
            "constraint" : "^1.1.10",
            "prompt" : "Would you like to install MVC-based console
  support? (We recommend migrating to zf-console, symfony/console, or
  Aura.CLI)",
            "module" : true
        }, {
            "name" : "zendframework/zend-mvc-i18n",
            "constraint" : "^1.0",
            "prompt" : "Would you like to install i18n support?",
            "module" : true
        }, {
            "name" : "zendframework/zend-mvc-plugins",
            "constraint" : "^1.0.1",
            "prompt" : "Would you like to install the official MVC
  plugins, including PRG support, identity, and flash messages?",
            "module" : true
        }, {
            "name" : "zendframework/zend-psr7bridge",
            "constraint" : "^0.2.2",
            "prompt" : "Would you like to use the PSR-7 middleware
   dispatcher?"
        }, {
            "name" : "zendframework/zend-session",
            "constraint" : "^2.7.1",
            "prompt" : "Would you like to install sessions support?",
            "module" : true
        }, {
            "name" : "zendframework/zend-test",
            "constraint" : "^3.0.1",
            "prompt" : "Would you like to install MVC testing
     support?",
            "dev" : true
        }, {
            "name" : "zendframework/zend-servicemanager-di",
            "constraint" : "^1.0",
            "prompt" : "Would you like to install the zend-di
  integration for zend-servicemanager?",
            "module" : true
        }
    ]
  },
"scripts" : {
    "cs-check" : "phpcs",
    "cs-fix" : "phpcbf",
    "development-disable" : "zf-development-mode disable",
    "development-enable" : "zf-development-mode enable",
    "development-status" : "zf-development-mode status",
    "post-create-project-cmd" : "@development-enable",
    "serve" : "php -S 0.0.0.0:8080 -t public public/index.php",
    "test" : "phpunit"
  }
 }
</code>```

答:
There are several problems within your configuration.

You should change the way you register your controllers. It is now only registered as an invokable with the string you've given. It is not registered by its FQCN as you try to use it within your route configuration. Nevertheless you use the wrong FQCN within the route config. You are using Controller\Album::class but the class is called: AlbumController so change that to Controller\AlbumController::class.

This is what your config should've been looking like:

```<code>return array(
    'controllers' => array(
        'aliases' => array(
            'Album\Controller\Album' => Controller\AlbumController::class
        ),
        'factories' => array(
            Controller\AlbumController::class => \Zend\ServiceManager\Factory\InvokableFactory::class,
        ),
    ),

    'router' => array(
        'routes' => array(
            'album' => array(
                'type'    => 'segment',
                'options' => array(
                    'route'    => '/album[/:action][/:id]',
                    'defaults' => array(
                        'controller' => Controller\AlbumController::class,
                        'action'     => 'index',
                    ),
                    'constraints' => array(
                        'action' => '[a-zA-Z][a-zA-Z0-9_-]*',
                        'id'     => '[0-9]+',
                    ),

                ),
            ),
        ),
    ),

    'view_manager' => array(
        'template_path_stack' => array(
            'album' => __DIR__ . '/../view',
        ),
    ),
);
</code>```

As we've registered an alias you can replace the controller option within the route defaults. You can thus use 'Album\Controller\Album' instead of the FQCN, but I rather use the FQCN within configurations. As it is easier to maintain your code.

One next thing you might bump into is that you are trying to use getServiceLocator() within your controller but this is no longer supported. Check this out: ZendFramework: ServiceManager - Factories

ContentLicense: CC BY-SA 3.0

Body:
enter image description herei'm trying to add a new module named as Album in Zend Skeleton application but however while accessing it through URL it throws an error below.i have spent almost 5 hours but did not find any solution.Any help will be appreciated.

File:/var/www/zf2-tutorial/vendor/zendframework/zend-servicemanager/src/Factory/InvokableFactory.php:30

Message:Class Album/Controller/AlbumController not found.

stack trace
      #0 /var/www/zf2-tutorial/vendor/zendframework/zend-
      servicemanager/src/ServiceManager.php(758):
      Zend\ServiceManager\Factory\InvokableFactory-
  __invoke(Object(Zend\ServiceManager\ServiceManager),
       'Album\Controlle...', NULL)
       #1 /var/www/zf2-tutorial/vendor/zendframework/zend-
       servicemanager/src/ServiceManager.php(200):
      Zend\ServiceManager\ServiceManager->doCreate('Album\Controlle...')
      #2 /var/www/zf2-tutorial/vendor/zendframework/zend-
       servicemanager/src/AbstractPluginManager.php(141):
       Zend\ServiceManager\ServiceManager->get('Album\Controlle...')
       #3 /var/www/zf2-tutorial/vendor/zendframework/zend-

       mvc/src/DispatchListener.php(95):
       Zend\ServiceManager\AbstractPluginManager->get('Album\Controlle...')
       #4 /var/www/zf2-tutorial/vendor/zendframework/zend-
       eventmanager/src/EventManager.php(322): Zend\Mvc\DispatchListener-
  onDispatch(Object(Zend\Mvc\MvcEvent))
       #5 /var/www/zf2-tutorial/vendor/zendframework/zend-
       eventmanager/src/EventManager.php(179):
      Zend\EventManager\EventManager-
  triggerListeners(Object(Zend\Mvc\MvcEvent), Object(Closure))
       #6 /var/www/zf2-tutorial/vendor/zendframework/zend-
        mvc/src/Application.php(332): Zend\EventManager\EventManager-
  triggerEventUntil(Object(Closure), Object(Zend\Mvc\MvcEvent))
       #7 /var/www/zf2-tutorial/public/index.php(48): Zend\Mvc\Application-
  run()
       #8 {main}

**module.config.php**
<?php
namespace Album;

  return array(
  'controllers' => array(
    'invokables' => array(
        'Album\Controller\Album' => Controller\AlbumController::class

    ),
),

'router' => array(
    'routes' => array(
        'album' => array(
            'type'    => 'segment',
            'options' => array(
                'route'    => '/album[/:action][/:id]',
                'defaults' => array(
                    'controller' => Controller\Album::class,
                    'action'     => 'index',
                ),
                'constraints' => array(
                    'controller' => '[a-zA-Z][a-zA-Z0-9_-]*',
                    'action' => '[a-zA-Z][a-zA-Z0-9_-]*',
                    'id'     => '[0-9]+',
                ),

            ),
        ),
    ),
),

'view_manager' => array(
    'template_path_stack' => array(
        'album' => __DIR__ . '/../view',
    ),
),
);
 ?>

**AlbumController.php**
<?php
namespace Album;

use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;

class AlbumController extends AbstractActionController
{
protected $albumTable;
public function getAlbumTable()
{
    if (! $this->albumTable) {
        $sm = $this->getServiceLocator();
        $this->albumTable = $sm->get('Album\Model\AlbumTable');
    }
    return $this->albumTable;
}

public function indexAction()
{
    return new ViewModel(array(
        'albums' => '',
    ));
}

public function addAction()
{

}

public function editAction()
{

}

public function deleteAction()
{

}

}

**Album.php**
 <?php
namespace Album\Model;

class Album
{

public $id;

public $artist;

public $title;

public function exchangeArray($data)
{
    $this->id = (! empty($data['id'])) ? $data['id'] : null;
    $this->artist = (! empty($data['artist'])) ? $data['artist'] :
     null;
    $this->title = (! empty($data['title'])) ? $data['title'] : null;
 }
 }

 **AlbumTable.php**
<?php
 use Zend\Db\TableGateway\TableGateway;

class AlbumTable
{

protected $tableGateway;

public function __construct(TableGateway $tableGateway)
{
    $this->tableGateway = $tableGateway;
}

public function fetchAll()
{
    $resultSet = $this->tableGateway->select();
    return $resultSet;
}

public function getAlbum($id)
{
    $id = (int) $id;
    $rowset = $this->tableGateway->select(array(
        'id' => $id
    ));
    $row = $rowset->current();
    if (! $row) {
        throw new \Exception("Could not find row $id");
    }
    return $row;
}

public function saveAlbum(Album $album)
{
    $data = array(
        'artist' => $album->artist,
        'title' => $album->title
    );

    $id = (int) $album->id;
    if ($id == 0) {
        $this->tableGateway->insert($data);
    } else {
        if ($this->getAlbum($id)) {
            $this->tableGateway->update($data, array(
                'id' => $id
            ));
        } else {
            throw new \Exception('Album id does not exist');
        }
    }
}

public function deleteAlbum($id)
{
    $this->tableGateway->delete(array(
        'id' => (int) $id
    ));
  }
  }

   **Module.php**
<?php
 namespace Album;

 use Zend\ModuleManager\Feature\AutoloaderProviderInterface;
 use Zend\ModuleManager\Feature\ConfigProviderInterface;
 u    se Album\Model\Album;
 use Album\Model\AlbumTable;
 use Zend\Db\ResultSet\ResultSet;
 use Zend\Db\TableGateway\TableGateway;

 class Module implements AutoloaderProviderInterface,
 ConfigProviderInterface
   {

public function getAutoloaderConfig()
{
    return array(
        'Zend\Loader\ClassMapAutoloader' => array(
            __DIR__ . '/autoload_classmap.php'
        ),
        'Zend\Loader\StandardAutoloader' => array(
            'namespaces' => array(
                __NAMESPACE__ => __DIR__ . '/src/' . __NAMESPACE__
            )
        )

    );
}

public function getConfig()
{
    return include __DIR__ . '/config/module.config.php';

}

public function getServiceConfig()
{
     return array(
        'factories' => array(
            'Album\Model\AlbumTable' => function ($sm) {
                $tableGateway = $sm->get('AlbumTableGateway');
                $table = new AlbumTable($tableGateway);
                return $table;
            },
            'AlbumTableGateway' => function ($sm) {
                $dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
                $resultSetPrototype = new ResultSet();
                $resultSetPrototype->setArrayObjectPrototype(new
              Album());
                return new TableGateway('album', $dbAdapter, null,
     $resultSetPrototype);
            }
        )
    );
}
public function getControllerConfig()
 {
    return [
        'factories' => [
            Controller\AlbumController::class => function($container)
  {
                return new Controller\AlbumController(
                    $container->get(Model\AlbumTable::class)
                    );
            },
            ],
            ];
  }
 }

  ?>
 **composer.json**

{
"name" : "zendframework/skeleton-application",
"description" : "Skeleton Application for Zend Framework zend-mvc
 applications",
"type" : "project",
"license" : "BSD-3-Clause",
"keywords" : [
    "framework",
    "mvc",
    "zf"
],
"homepage" : "http://framework.zend.com/",
"minimum-stability" : "dev",
"prefer-stable" : true,
"require" : {
    "php" : "^5.6 || ^7.0",
    "zendframework/zend-component-installer" : "^1.0 || ^0.7 ||
 ^1.0.0-dev@dev",
    "zendframework/zend-mvc" : "^3.0.1",
    "zfcampus/zf-development-mode" : "^3.0"
},
"autoload" : {
    "psr-4" : {
        "Application\\" : "module/Application/src/"

 }
},
"autoload-dev" : {
    "psr-4" : {
        "ApplicationTest\\" : "module/Application/test/"
    }
},
"extra" : {
    "zend-skeleton-installer" : [{
            "name" : "zendframework/zend-developer-tools",
            "constraint" : "^1.1.0",
            "prompt" : "Would you like to install the developer
   toolbar?",
            "module" : true,
            "dev" : true
        }, {
            "name" : "zendframework/zend-cache",
            "constraint" : "^2.7.1",
            "prompt" : "Would you like to install caching support?",
            "module" : true
        }, {
            "name" : "zendframework/zend-db",
            "constraint" : "^2.8.1",
            "prompt" : "Would you like to install database support
    (installs zend-db)?",
            "module" : true
        }, {
            "name" : "zendframework/zend-mvc-form",
            "constraint" : "^1.0",
            "prompt" : "Would you like to install forms support?",
            "module" : true
        }, {
            "name" : "zendframework/zend-json",
            "constraint" : "^3.0",
            "prompt" : "Would you like to install JSON
     de/serialization support?"
        }, {
            "name" : "zendframework/zend-log",
            "constraint" : "^2.9",
            "prompt" : "Would you like to install logging support?",
            "module" : true
        }, {
            "name" : "zendframework/zend-mvc-console",
            "constraint" : "^1.1.10",
            "prompt" : "Would you like to install MVC-based console
  support? (We recommend migrating to zf-console, symfony/console, or
  Aura.CLI)",
            "module" : true
        }, {
            "name" : "zendframework/zend-mvc-i18n",
            "constraint" : "^1.0",
            "prompt" : "Would you like to install i18n support?",
            "module" : true
        }, {
            "name" : "zendframework/zend-mvc-plugins",
            "constraint" : "^1.0.1",
            "prompt" : "Would you like to install the official MVC
  plugins, including PRG support, identity, and flash messages?",
            "module" : true
        }, {
            "name" : "zendframework/zend-psr7bridge",
            "constraint" : "^0.2.2",
            "prompt" : "Would you like to use the PSR-7 middleware
   dispatcher?"
        }, {
            "name" : "zendframework/zend-session",
            "constraint" : "^2.7.1",
            "prompt" : "Would you like to install sessions support?",
            "module" : true
        }, {
            "name" : "zendframework/zend-test",
            "constraint" : "^3.0.1",
            "prompt" : "Would you like to install MVC testing
     support?",
            "dev" : true
        }, {
            "name" : "zendframework/zend-servicemanager-di",
            "constraint" : "^1.0",
            "prompt" : "Would you like to install the zend-di
  integration for zend-servicemanager?",
            "module" : true
        }
    ]
  },
"scripts" : {
    "cs-check" : "phpcs",
    "cs-fix" : "phpcbf",
    "development-disable" : "zf-development-mode disable",
    "development-enable" : "zf-development-mode enable",
    "development-status" : "zf-development-mode status",
    "post-create-project-cmd" : "@development-enable",
    "serve" : "php -S 0.0.0.0:8080 -t public public/index.php",
    "test" : "phpunit"
  }
 }

Body:
There are several problems within your configuration.

You should change the way you register your controllers. It is now only registered as an invokable with the string you've given. It is not registered by its FQCN as you try to use it within your route configuration. Nevertheless you use the wrong FQCN within the route config. You are using Controller\Album::class but the class is called: AlbumController so change that to Controller\AlbumController::class.

This is what your config should've been looking like:

return array(
    'controllers' => array(
        'aliases' => array(
            'Album\Controller\Album' => Controller\AlbumController::class
        ),
        'factories' => array(
            Controller\AlbumController::class => \Zend\ServiceManager\Factory\InvokableFactory::class,
        ),
    ),

    'router' => array(
        'routes' => array(
            'album' => array(
                'type'    => 'segment',
                'options' => array(
                    'route'    => '/album[/:action][/:id]',
                    'defaults' => array(
                        'controller' => Controller\AlbumController::class,
                        'action'     => 'index',
                    ),
                    'constraints' => array(
                        'action' => '[a-zA-Z][a-zA-Z0-9_-]*',
                        'id'     => '[0-9]+',
                    ),

                ),
            ),
        ),
    ),

    'view_manager' => array(
        'template_path_stack' => array(
            'album' => __DIR__ . '/../view',
        ),
    ),
);

As we've registered an alias you can replace the controller option within the route defaults. You can thus use 'Album\Controller\Album' instead of the FQCN, but I rather use the FQCN within configurations. As it is easier to maintain your code.

One next thing you might bump into is that you are trying to use getServiceLocator() within your controller but this is no longer supported. Check this out: ZendFramework: ServiceManager - Factories


问:
Sound metering react-native
Im building a react-native application.
Im trying to meter the current sound level (in decibel).

Libraries in use: react-native-audio and react-native-sound.

There is anybody familiar with this feature?

Thank you.

答:
You can use react-native-audio currentMetering value - in order to get the sound level in real-time.

First, you will have to initialise your recorder (which i will assume youve done). I use prepareRecordingAtPath in a similar way to below

```<code>AudioRecorder.prepareRecordingAtPath(audioPath, {
  SampleRate: 22050,
  Channels: 1,
  AudioQuality: "Low",
  AudioEncoding: "aac",
  MeteringEnabled: true
});
</code>```

then once you've called AudioRecorder.startRecording(); (Note you have access to .pause() and .stop() methods also

Now for handling the audio level, you are going to have to retrieve the data that is returned by the onProgress method. From what i remember, there should be some currentMetering value that you can access. Note that defining this behaviour will trigger the action every time a different decibel reading is retrieved. Like so

```<code>AudioRecorder.onProgress = data => {
    let decibels = Math.floor(data.currentMetering);

    //DO STUFF
  };
</code>```

Hope this helps,

Title: Sound metering react-native

Body:
You can use react-native-audio currentMetering value - in order to get the sound level in real-time.

First, you will have to initialise your recorder (which i will assume youve done). I use prepareRecordingAtPath in a similar way to below

AudioRecorder.prepareRecordingAtPath(audioPath, {
  SampleRate: 22050,
  Channels: 1,
  AudioQuality: "Low",
  AudioEncoding: "aac",
  MeteringEnabled: true
});

then once you've called AudioRecorder.startRecording(); (Note you have access to .pause() and .stop() methods also

Now for handling the audio level, you are going to have to retrieve the data that is returned by the onProgress method. From what i remember, there should be some currentMetering value that you can access. Note that defining this behaviour will trigger the action every time a different decibel reading is retrieved. Like so

AudioRecorder.onProgress = data => {
    let decibels = Math.floor(data.currentMetering);

    //DO STUFF
  };

Hope this helps,


问:
How to count number of records in yii2 framework?
I am new in Yii framework.
I have a page frontend/site/home.php, I want to display the number of records from companies table at home.php.(DB name yii2advanced) </p>

答:
Simply use count function to get count of records from a table, like -

```<code>$count = YourModel::find()->count();
echo $count;
</code>```

Body:
Simply use count function to get count of records from a table, like -

$count = YourModel::find()->count();
echo $count;


问:
Python- The Word Game "Ghost", File I/O, and List question
I want to create computer for the word-game Ghost.   However, I'm having problems thinking of a good way to deal with accessing the huge word list.  Here's my current implementation (which doesn't work):

```<code>import os, random, sys, math, string

def main():

    #Contains a huge wordlist-- opened up for reading
    dictionary = open("wordlist.txt", "r")
    wordlist = []
    win= 0
    turn= 0
    firstrun = 0
    word = ""

    #while nobody has won the game
    while win==0:
        if turn == 0:
            #get first letter from input
            foo = raw_input("Choose a letter: ")[0]
            word+=foo
            print "**Current word**: "+ word
            #Computer's turn
            turn = 1
        if turn == 1:
            #During the first run the program gets all definitively
            #winning words (words that have odd-number lengths)
            #from the "dictionary" file and puts them in a list
            if firstrun== 0:
                for line in dictionary:
                    #if the line in the dictionary starts with the current
                    #word and has an odd-number of letters
                    if str(line).startswith(word) and len(line)%2 == 0:
                        wordlist.append(line[0: len(line)-1])
                print "first run complete... size = "+str(len(wordlist))
                firstrun = 1
            else:   #This is run after the second computer move
                for line in wordlist:
                    #THIS DOES NOT WORK-- THIS IS THE PROBLEM.
                    #I want it to remove from the list every single
                    #word that does not conform to the current limitations
                    #of the "word" variable.
                    if not line.startswith(word):
                        wordlist.remove(line)
                print "removal complete... size = "+str(len(wordlist))

            turn = 0

if __name__ == "__main__":
    main()
</code>```

I have demarcated the problem area in the code.  I have no idea why it doesn't work.  What should happen: Imagine the list is populated with all words that start with 'a.' The user then picks the letter 'b.' The target word then must have the starting letters 'ab.' What should happen is that all 'a' words that are in the list that are not directly followed with a 'b' should be removed.

I also would appreciate it if somebody could let me know a more efficient way of doing this then making a huge initial list.

答: If you want to work for ITA you'd be better off writing this in clisp... or clojure.</p>

ContentLicense: CC BY-SA 2.5

Body:
I want to create computer for the word-game Ghost.   However, I'm having problems thinking of a good way to deal with accessing the huge word list.  Here's my current implementation (which doesn't work):

import os, random, sys, math, string

def main():

    #Contains a huge wordlist-- opened up for reading
    dictionary = open("wordlist.txt", "r")
    wordlist = []
    win= 0
    turn= 0
    firstrun = 0
    word = ""

    #while nobody has won the game
    while win==0:
        if turn == 0:
            #get first letter from input
            foo = raw_input("Choose a letter: ")[0]
            word+=foo
            print "**Current word**: "+ word
            #Computer's turn
            turn = 1
        if turn == 1:
            #During the first run the program gets all definitively
            #winning words (words that have odd-number lengths)
            #from the "dictionary" file and puts them in a list
            if firstrun== 0:
                for line in dictionary:
                    #if the line in the dictionary starts with the current
                    #word and has an odd-number of letters
                    if str(line).startswith(word) and len(line)%2 == 0:
                        wordlist.append(line[0: len(line)-1])
                print "first run complete... size = "+str(len(wordlist))
                firstrun = 1
            else:   #This is run after the second computer move
                for line in wordlist:
                    #THIS DOES NOT WORK-- THIS IS THE PROBLEM.
                    #I want it to remove from the list every single
                    #word that does not conform to the current limitations
                    #of the "word" variable.
                    if not line.startswith(word):
                        wordlist.remove(line)
                print "removal complete... size = "+str(len(wordlist))

            turn = 0

if __name__ == "__main__":
    main()

I have demarcated the problem area in the code.  I have no idea why it doesn't work.  What should happen: Imagine the list is populated with all words that start with 'a.' The user then picks the letter 'b.' The target word then must have the starting letters 'ab.' What should happen is that all 'a' words that are in the list that are not directly followed with a 'b' should be removed.

I also would appreciate it if somebody could let me know a more efficient way of doing this then making a huge initial list.


问:
Apply a trained Tensorflow
During the training process, I split the dataset into training and testing data with train_test_split(): </p>

```<code>from sklearn.model_selection import train_test_split
import tensorflow as tf
import numpy as np

X_train, X_test, y_train, y_test = train_test_split(data, labels, test_size=0.33, random_state=28)

with tf.Session(graph=graph) as sess:
    sess.run(tf.global_variables_initializer())
    print ('History length: ',history)
    saver = tf.train.Saver()
    writer = tf.summary.FileWriter("logs", sess.graph)

    plt.ion()
    plt.show()

    for epoch in range(num_epochs):
        shuffle_ind=np.random.permutation(X_train.shape[0])
        y_train=y_train.iloc[shuffle_ind,:]
        X_train=X_train[shuffle_ind,:]

        for batch_no in range(X_train.shape[0]//batch_size):
            seq_len=[history]*batch_size

            batch_X=X_train[batch_no*batch_size:(batch_no+1)*batch_size,:]
            batch_y=y_train.iloc[batch_no*batch_size:(batch_no+1)*batch_size,:]

            feed = {data_pl: batch_X, target_pl: batch_y.iloc[:,1:], seq_len_pl:seq_len,keep_prob_pl:0.5} #1.0
            _,batch_loss = sess.run([train_op,tf_loss], feed_dict=feed)

        feed = {data_pl: X_test, target_pl: y_test.iloc[:,1:], seq_len_pl:[history]*X_test.shape[0],keep_prob_pl:0.5}
        test_loss,predictions,acc_np = sess.run([tf_loss,preds,tf_acc], feed_dict=feed)

        p_=np.argmax(predictions, axis=1)
        l_=np.argmax(np.array(y_test.iloc[:,1:]),axis=1)
        acc = sum(p_==l_)/float(len(p_))

        print ("train_acc: ", acc, "test_acc: ", acc_np)

        feed = {data_pl: X_train, target_pl: y_train.iloc[:,1:], seq_len_pl:[history]*X_train.shape[0],keep_prob_pl:0.5}
        train_loss = sess.run(tf_loss, feed_dict=feed)

        print ("Train loss: ",train_loss," Test loss: ",test_loss)
</code>```

<p>After training and getting the accuracy rates, how to apply this trained model on the entire dataset rather than only the testing data? </p>

答:
Suppose that the ‘OutPut’ is an export of the neural network; thus, the ‘InPut’ is where you can feed your data in. Then, you run the network with the same session that you were training in. The ‘OutPutData’ will be the computing result.</p>

```<code>OutPutData = session.run(OutPut, feed_dict={ InPut: Data})
</code>```

Title: Apply a trained Tensorflow

Body:
During the training process, I split the dataset into training and testing data with train_test_split():

from sklearn.model_selection import train_test_split
import tensorflow as tf
import numpy as np

X_train, X_test, y_train, y_test = train_test_split(data, labels, test_size=0.33, random_state=28)

with tf.Session(graph=graph) as sess:
    sess.run(tf.global_variables_initializer())
    print ('History length: ',history)
    saver = tf.train.Saver()
    writer = tf.summary.FileWriter("logs", sess.graph)

    plt.ion()
    plt.show()

    for epoch in range(num_epochs):
        shuffle_ind=np.random.permutation(X_train.shape[0])
        y_train=y_train.iloc[shuffle_ind,:]
        X_train=X_train[shuffle_ind,:]

        for batch_no in range(X_train.shape[0]//batch_size):
            seq_len=[history]*batch_size

            batch_X=X_train[batch_no*batch_size:(batch_no+1)*batch_size,:]
            batch_y=y_train.iloc[batch_no*batch_size:(batch_no+1)*batch_size,:]

            feed = {data_pl: batch_X, target_pl: batch_y.iloc[:,1:], seq_len_pl:seq_len,keep_prob_pl:0.5} #1.0
            _,batch_loss = sess.run([train_op,tf_loss], feed_dict=feed)

        feed = {data_pl: X_test, target_pl: y_test.iloc[:,1:], seq_len_pl:[history]*X_test.shape[0],keep_prob_pl:0.5}
        test_loss,predictions,acc_np = sess.run([tf_loss,preds,tf_acc], feed_dict=feed)

        p_=np.argmax(predictions, axis=1)
        l_=np.argmax(np.array(y_test.iloc[:,1:]),axis=1)
        acc = sum(p_==l_)/float(len(p_))

        print ("train_acc: ", acc, "test_acc: ", acc_np)

        feed = {data_pl: X_train, target_pl: y_train.iloc[:,1:], seq_len_pl:[history]*X_train.shape[0],keep_prob_pl:0.5}
        train_loss = sess.run(tf_loss, feed_dict=feed)

        print ("Train loss: ",train_loss," Test loss: ",test_loss)

After training and getting the accuracy rates, how to apply this trained model on the entire dataset rather than only the testing data?

Body:
Suppose that the ‘OutPut’ is an export of the neural network; thus, the ‘InPut’ is where you can feed your data in. Then, you run the network with the same session that you were training in. The ‘OutPutData’ will be the computing result.

OutPutData = session.run(OutPut, feed_dict={ InPut: Data})


问:
Angular - dynamically set model property of object bound to radio button based on its state
I'm trying to figure out how to dynamically set the model property of an object that is bound to the radio button, based on the state of the radio button.

To give some context, the page is creating a True/False question for a quiz, with a radio button for True and a radio button for False. I want the object property of the radio button to change based on its state. The reason for doing this is because the value is tied to answer.is_correct in the model, which is a boolean that indicates which answer is correct. If the question being asked is true, then the correct option should be True. But if the question being asked is false, then the correct option should be False.

As such, my requirements are:

If the True radio button is selected:

answer.is_correct should be true for True radio button

answer.is_correct should be false for False radio button

If the False radio button is selected:

answer.is_correct should be false for True radio button

answer.is_correct should be true for the False radio button

Here is a snippet of the current code, which is incorrect because if the user goes back to edit a previously created question (the form for creating and editing a question uses the same view), changing the correct answer from True to False does not set answer.is_correct to false for the True option. Instead, both True and False options have answer.is_correct as true, which is not want I want.

```<code>  <div ng-repeat="answer in question.answers" class="answer">
    <label>
      <input type="radio" ng-value="true" name="true_false_choice" ng-model="answer.is_correct">
      {{answer.choice}}
    </label>
  </div>
</code>```

答:
```<code>I had a similar problem in AngularJS and here is the angular version of mannykary solution.
</code>```

controller:

using controllerAs, I use vm as a representation of the binding scope

```<code>function setTrueFalseRadioState(answer) {
     angular.forEach(vm.files, function (a) {
        if (a.IsMyChoice !== answer.IsMyChoice) {
            a.IsMyChoice = false;
        }
     });
 };

 vm.setTrueFalseRadioState = setTrueFalseRadioState;
</code>```

html:

Notice, I use "ng-change" and "get" for binding to the scope due to the controllerAs syntax in the controller

```<code><input type="radio"
           id="isChoice_{{$index + 1}}"
           name="response"
           ng-value="{{$index + 1}}"
           ng-required="!file.IsMyChoice"
           ng-change="get.setTrueFalseRadioState(file)"
           data-ng-model="file.IsMyChoice" />
</code>```

Body:
I'm trying to figure out how to dynamically set the model property of an object that is bound to the radio button, based on the state of the radio button.

To give some context, the page is creating a True/False question for a quiz, with a radio button for True and a radio button for False. I want the object property of the radio button to change based on its state. The reason for doing this is because the value is tied to answer.is_correct in the model, which is a boolean that indicates which answer is correct. If the question being asked is true, then the correct option should be True. But if the question being asked is false, then the correct option should be False.

As such, my requirements are:

If the True radio button is selected:

answer.is_correct should be true for True radio button

answer.is_correct should be false for False radio button

If the False radio button is selected:

answer.is_correct should be false for True radio button

answer.is_correct should be true for the False radio button

Here is a snippet of the current code, which is incorrect because if the user goes back to edit a previously created question (the form for creating and editing a question uses the same view), changing the correct answer from True to False does not set answer.is_correct to false for the True option. Instead, both True and False options have answer.is_correct as true, which is not want I want.

      <input type="radio" ng-value="true" name="true_false_choice" ng-model="answer.is_correct">
      {{answer.choice}}

Body:
I had a similar problem in AngularJS and here is the angular version of mannykary solution.

controller:

using controllerAs, I use vm as a representation of the binding scope

function setTrueFalseRadioState(answer) {
     angular.forEach(vm.files, function (a) {
        if (a.IsMyChoice !== answer.IsMyChoice) {
            a.IsMyChoice = false;
        }
     });
 };

 vm.setTrueFalseRadioState = setTrueFalseRadioState;

html:

Notice, I use "ng-change" and "get" for binding to the scope due to the controllerAs syntax in the controller

<input type="radio"
           id="isChoice_{{$index + 1}}"
           name="response"
           ng-value="{{$index + 1}}"
           ng-required="!file.IsMyChoice"
           ng-change="get.setTrueFalseRadioState(file)"
           data-ng-model="file.IsMyChoice" />


问:
how to access prototype functions in console
I created a javascript and added it to a page like this:

```<code>(function (window, google, List){
var myfunction = (function(){}
myfunction.prototype = {
hint: function(){alert('a good advise');}
})
}(window, google, List))
</code>```

I added the needed js files, and it works! it will show the result after loading when instatination id like

```<code>var myfancything = myfunction.create();
</code>```

I am getting the result after page load.
BUT! I would expect that if i then open the console and type

```<code>myfancything.hint();
</code>```

I would see the alert.
I know I was able to do that the other day, but I don't know how I achieved it!

so I would like to use the prototypes in the browser console, can you guys give me a hint how to do that?

答: Since you declared myfunction as a local variable inside the IIFE, it's not accessible outside that scope. Get rid of the IIFE if you want to make it global, or assign to window.myfunction.

Body:
I created a javascript and added it to a page like this:

(function (window, google, List){
var myfunction = (function(){}
myfunction.prototype = {
hint: function(){alert('a good advise');}
})
}(window, google, List))

I added the needed js files, and it works! it will show the result after loading when instatination id like

var myfancything = myfunction.create();

I am getting the result after page load.
BUT! I would expect that if i then open the console and type

myfancything.hint();

I would see the alert.
I know I was able to do that the other day, but I don't know how I achieved it!

so I would like to use the prototypes in the browser console, can you guys give me a hint how to do that?


问:
Cozyroc MailTask script not working
I am trying to use CozyRoc's script to perform mail server tasks like moving emails from one mail folder to another. I am using the script found here:

CozyRoc Mailtask Script

So far it doesn't work. The error i get is that my connection manager is not found, which makes no sense. In a different package I have set up a fetch mail attachments process with success, so my connection is tested and working. Anyone used it before with success?

答: Creating a new project from scratch with the exact same setup i used in the previous one solved the problem. I was unable to figure out why, but this solved the problem.</p>

Title: Cozyroc MailTask script not working


问:
How to solve - Error creating bean with name 'defaultController'
I am new to Spring MVC and Hibernate. For several days i am trying to make a simple spring project but got some error there. The error says org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'CustomerDAOImp'

Here is my error

HTTP Status 500 - Internal Server Error

type Exception report

messageInternal Server Error

descriptionThe server encountered an internal error that prevented it
  from fulfilling this request.

exception

javax.servlet.ServletException: Servlet.init() for servlet dispatcher
  threw exception root cause

org.springframework.beans.factory.UnsatisfiedDependencyException:
  Error creating bean with name 'CustomerDAOImp': Unsatisfied dependency
  expressed through field 'sessionFactory'; nested exception is
  org.springframework.beans.factory.NoSuchBeanDefinitionException: No
  qualifying bean of type 'org.hibernate.SessionFactory' available:
  expected at least 1 bean which qualifies as autowire candidate.
  Dependency annotations:
  {@org.springframework.beans.factory.annotation.Autowired(required=true)}
  root cause

org.springframework.beans.factory.NoSuchBeanDefinitionException: No
  qualifying bean of type 'org.hibernate.SessionFactory' available:
  expected at least 1 bean which qualifies as autowire candidate.
  Dependency annotations:
  {@org.springframework.beans.factory.annotation.Autowired(required=true)}
  note The full stack traces of the exception and its root causes are
  available in the GlassFish Server Open Source Edition 4.1.1 logs.

GlassFish Server Open Source Edition 4.1.1

I have used maven multi module to done this project. Here 'CustomerDAOImp' is the name of repository that i have defined in the CustomerDAOImp class. This is the java class that extends GenericImp class and implements CustomerDAO interface and further CustomerDAO extends the GenericDAO interface.

CustomerDAOImp

```<code>@Repository(value = "CustomerDAOImp")
public class CustomerDAOImp extends GenericDAOImp<Customer> implements CustomerDAO{

}
</code>```

CustomerDAO

```<code>public interface CustomerDAO extends GenericDAO<Customer>{

}
</code>```

GenericDAO

```<code>public interface GenericDAO<T> {
    void insert(T t);
    void update(T t);
    boolean delete(int id);
    List<T> getAll();
    T getById(int id);
}
</code>```

And my controller for mapping jsp page

```<code>@Controller
public class DefaultController {
    @Autowired
    CustomerDAOImp customerDaoImp;

    @RequestMapping(value = "/", method = RequestMethod.GET)
    public String index() {
        return "user/dairy/index";
    }

    @RequestMapping(value = "/customer", method = RequestMethod.GET)
    public String customer(Model model) {
        model.addAttribute("customer", customerDaoImp.getAll());
        return "user/dairy/customer";
    }
}
</code>```

dispatcher-servlet.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:p="http://www.springframework.org/schema/p"

       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
          http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
          http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
">

    <context:component-scan base-package="com.nishan.dairy"/>
    <mvc:annotation-driven/>
    <mvc:resources mapping="/static/**" location="/WEB-INF/assets/"/>

    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"
    p:prefix="/WEB-INF/views/" p:suffix=".jsp"/>

</beans>
</code>```

applicationContext.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:security="http://www.springframework.org/schema/security"

       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
            http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security.xsd
">
    <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
    p:location="/WEB-INF/db/jdbc.properties"/>

    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"
    p:driverClassName="${jdbc.driverClassName}" p:url="${jdbc.url}"
    p:username="${jdbc.username}" p:password="${jdbc.password}"/>

    <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="packagesToScan" value="com.nishan.dairyreport.entity"/>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">
                    org.hibernate.dialect.MySQLDialect
                </prop>
                <prop key="hibernate.show_sql">true</prop>
            </props>
        </property>
    </bean>

</beans>
</code>```

Here is my project structure

Hoping for the positive response thanks...........

答:
How have you created the ApplicationContext?
Have you created it programmatically in your program or are expecting your Spring declarations to take care of it?

From what you have provided, it looks like the failure is occuring during dispatcher initialization and the corresponding DAO dependency injection.
And the DAO dependencies have been defined in applicationContext.xml which is different from dispatcher-servlet.xml.
So seems like applicationContext.xml is not being loaded while dispatcher-servlet.xml is loading up.

Check your web.xml to ensure that you have a ContextLoader that automatically instantiates your root and web application contexts for Spring MVC app.

These lines should be present:

```<code><listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
</code>```

You can initialize your contexts as above or do it programmatically; refer to below for more details:
https://docs.spring.io/spring/docs/current/spring-framework-reference/web.html#mvc-servlet-context-hierarchy
and
https://docs.spring.io/spring/docs/current/spring-framework-reference/core.html#context-introduction

You can also check if the contexts are loading properly in the logs. They would provide details on the bean initialization.
Share your log messages during the app initialization and servlet loading phase.

Some references for logging:
https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-logging.html

Body:
I am new to Spring MVC and Hibernate. For several days i am trying to make a simple spring project but got some error there. The error says org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'CustomerDAOImp'

Here is my error

HTTP Status 500 - Internal Server Error

type Exception report

messageInternal Server Error

descriptionThe server encountered an internal error that prevented it
  from fulfilling this request.

exception

javax.servlet.ServletException: Servlet.init() for servlet dispatcher
  threw exception root cause

org.springframework.beans.factory.UnsatisfiedDependencyException:
  Error creating bean with name 'CustomerDAOImp': Unsatisfied dependency
  expressed through field 'sessionFactory'; nested exception is
  org.springframework.beans.factory.NoSuchBeanDefinitionException: No
  qualifying bean of type 'org.hibernate.SessionFactory' available:
  expected at least 1 bean which qualifies as autowire candidate.
  Dependency annotations:
  {@org.springframework.beans.factory.annotation.Autowired(required=true)}
  root cause

org.springframework.beans.factory.NoSuchBeanDefinitionException: No
  qualifying bean of type 'org.hibernate.SessionFactory' available:
  expected at least 1 bean which qualifies as autowire candidate.
  Dependency annotations:
  {@org.springframework.beans.factory.annotation.Autowired(required=true)}
  note The full stack traces of the exception and its root causes are
  available in the GlassFish Server Open Source Edition 4.1.1 logs.

GlassFish Server Open Source Edition 4.1.1

I have used maven multi module to done this project. Here 'CustomerDAOImp' is the name of repository that i have defined in the CustomerDAOImp class. This is the java class that extends GenericImp class and implements CustomerDAO interface and further CustomerDAO extends the GenericDAO interface.

CustomerDAOImp

@Repository(value = "CustomerDAOImp")
public class CustomerDAOImp extends GenericDAOImp<Customer> implements CustomerDAO{

}

CustomerDAO

public interface CustomerDAO extends GenericDAO<Customer>{

}

GenericDAO

public interface GenericDAO<T> {
    void insert(T t);
    void update(T t);
    boolean delete(int id);
    List<T> getAll();
    T getById(int id);
}

And my controller for mapping jsp page

@Controller
public class DefaultController {
    @Autowired
    CustomerDAOImp customerDaoImp;

    @RequestMapping(value = "/", method = RequestMethod.GET)
    public String index() {
        return "user/dairy/index";
    }

    @RequestMapping(value = "/customer", method = RequestMethod.GET)
    public String customer(Model model) {
        model.addAttribute("customer", customerDaoImp.getAll());
        return "user/dairy/customer";
    }
}

dispatcher-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:p="http://www.springframework.org/schema/p"

       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
          http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
          http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
">

    <context:component-scan base-package="com.nishan.dairy"/>
    <mvc:annotation-driven/>
    <mvc:resources mapping="/static/**" location="/WEB-INF/assets/"/>

    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"
    p:prefix="/WEB-INF/views/" p:suffix=".jsp"/>

</beans>

applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:security="http://www.springframework.org/schema/security"

       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
            http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security.xsd
">
    <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
    p:location="/WEB-INF/db/jdbc.properties"/>

    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"
    p:driverClassName="${jdbc.driverClassName}" p:url="${jdbc.url}"
    p:username="${jdbc.username}" p:password="${jdbc.password}"/>

    <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="packagesToScan" value="com.nishan.dairyreport.entity"/>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">
                    org.hibernate.dialect.MySQLDialect
                </prop>
                <prop key="hibernate.show_sql">true</prop>
            </props>
        </property>
    </bean>

</beans>

Here is my project structure

Hoping for the positive response thanks...........

Body:
How have you created the ApplicationContext?
Have you created it programmatically in your program or are expecting your Spring declarations to take care of it?

From what you have provided, it looks like the failure is occuring during dispatcher initialization and the corresponding DAO dependency injection.
And the DAO dependencies have been defined in applicationContext.xml which is different from dispatcher-servlet.xml.
So seems like applicationContext.xml is not being loaded while dispatcher-servlet.xml is loading up.

Check your web.xml to ensure that you have a ContextLoader that automatically instantiates your root and web application contexts for Spring MVC app.

These lines should be present:

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

You can initialize your contexts as above or do it programmatically; refer to below for more details:
https://docs.spring.io/spring/docs/current/spring-framework-reference/web.html#mvc-servlet-context-hierarchy
and
https://docs.spring.io/spring/docs/current/spring-framework-reference/core.html#context-introduction

You can also check if the contexts are loading properly in the logs. They would provide details on the bean initialization.
Share your log messages during the app initialization and servlet loading phase.

Some references for logging:
https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-logging.html


问:
[Python]; Parser error: Too many columns specified
I just want to read a simple .csv file with a header specifying the column types.
The following is the code:

```<code>import pandas as pd
url="https://www.dropbox.com/s/n6yt908tgetuq63/LasVegasTripAdvisorReviews-Dataset.csv?dl=0"
names=['User country','Nr. reviews','Nr. hotel reviews','Helpful
votes','Score','Period of stay','Traveler Type','Pool','Gym','Tennis
court','Spa','Casino','Free internet','Hotel name','Hotel stars','Nr.
rooms','User continent','Member years','Review month','Review weekday']
data=pd.read_csv(url, names=names, header=0, delimiter=';',
error_bad_lines=False)
print(data.shape)
</code>```

OUT:-

ParserError: Too many columns specified: expected 20 and found 2

P.S:The URL is public and can be accessed

答:
In dropbox url just replace 0 with 1 as below
https://www.dropbox.com/s/n6yt908tgetuq63/LasVegasTripAdvisorReviews-Dataset.csv?dl=1

Which makes the file to be downloaded directly

Body:
I just want to read a simple .csv file with a header specifying the column types.
The following is the code:

import pandas as pd
url="https://www.dropbox.com/s/n6yt908tgetuq63/LasVegasTripAdvisorReviews-Dataset.csv?dl=0"
names=['User country','Nr. reviews','Nr. hotel reviews','Helpful
votes','Score','Period of stay','Traveler Type','Pool','Gym','Tennis
court','Spa','Casino','Free internet','Hotel name','Hotel stars','Nr.
rooms','User continent','Member years','Review month','Review weekday']
data=pd.read_csv(url, names=names, header=0, delimiter=';',
error_bad_lines=False)
print(data.shape)

OUT:-

ParserError: Too many columns specified: expected 20 and found 2

P.S:The URL is public and can be accessed


问:
How best to do a JavaScript array with non-consecutive indexes?
I'm writing a Google Chrome extension, in JavaScript, and I want to use an array to store a bunch of objects, but I want the indexes to be specific non-consecutive ID numbers.

(This is because I need to be able to efficiently look up the values later, using an ID number that comes from another source outside my control.)

For example:

```<code>var myObjects = [] ;

myObjects[471] = {foo: "bar"} ;

myObjects[3119] = {hello: "goodbye"}
</code>```

When I do console.log(myObjects), in the console I see the entire array printed out, with all the thousands of 'missing' indexes showing undefined.

My question is: does this matter? Is this wasting any memory?

And even if it's not wasting memory, surely whenever I loop over the array, it wastes CPU if I have to manually skip over every missing value?

I tried using an object instead of an array, but it seems you can't use numbers as object keys. I'm hoping there's a better way to achieve this?

答:
I would use an object to store these. You can use numbers for properties using subscript notation but you can't using dot notation; the object passed as the key using subscript notation has toString() called on it.

```<code>var obj = {};
obj[471] = {foo: "bar"} ;
</code>```

Body:
I'm writing a Google Chrome extension, in JavaScript, and I want to use an array to store a bunch of objects, but I want the indexes to be specific non-consecutive ID numbers.

(This is because I need to be able to efficiently look up the values later, using an ID number that comes from another source outside my control.)

For example:

var myObjects = [] ;

myObjects[471] = {foo: "bar"} ;

myObjects[3119] = {hello: "goodbye"}

When I do console.log(myObjects), in the console I see the entire array printed out, with all the thousands of 'missing' indexes showing undefined.

My question is: does this matter? Is this wasting any memory?

And even if it's not wasting memory, surely whenever I loop over the array, it wastes CPU if I have to manually skip over every missing value?

I tried using an object instead of an array, but it seems you can't use numbers as object keys. I'm hoping there's a better way to achieve this?

Body:
I would use an object to store these. You can use numbers for properties using subscript notation but you can't using dot notation; the object passed as the key using subscript notation has toString() called on it.

var obj = {};
obj[471] = {foo: "bar"} ;


问:
How to make a navigation drawer appear in multiple activities?
BaseActivity.java

```<code>public class BaseActivity extends AppCompatActivity
    implements NavigationView.OnNavigationItemSelectedListener {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_base);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
        }
    });

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
            this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    drawer.setDrawerListener(toggle);
    toggle.syncState();

    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);
}

@Override
public void onBackPressed() {
    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    if (drawer.isDrawerOpen(GravityCompat.START)) {
        drawer.closeDrawer(GravityCompat.START);
    } else {
        super.onBackPressed();
    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.base, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
    // Handle navigation view item clicks here.
    int id = item.getItemId();

    if (id == R.id.nav_camera) {
        // Handle the camera action
    } else if (id == R.id.nav_gallery) {

    } else if (id == R.id.nav_slideshow) {

    } else if (id == R.id.nav_manage) {

    } else if (id == R.id.nav_share) {

    } else if (id == R.id.nav_send) {

    }

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawer.closeDrawer(GravityCompat.START);
    return true;
}
}
</code>```

I am trying to make appear my BaseActivity in my MainActivity. But i am not able to do it....I tried to extend the BaseActivity from the MainActivity but still didn't work...

MainActivity.java

```<code>public class MainActivity extends BaseActivity {

private static final String TAG = "MainActivity";
private SectionsPageAdapter mSectionsPageAdapter;
private ViewPager mViewPager;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Log.d(TAG, "onCreate: Starting.");

    mSectionsPageAdapter = new SectionsPageAdapter(getSupportFragmentManager());

    // Set up the ViewPager with the sections adapter.
    mViewPager = (ViewPager) findViewById(R.id.container);
    setupViewPager(mViewPager);

    TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
    tabLayout.setupWithViewPager(mViewPager);
}

private void setupViewPager(ViewPager viewPager) {
    SectionsPageAdapter adapter = new SectionsPageAdapter(getSupportFragmentManager());
    adapter.addFragment(new Tab1Fragment(), "STATUS");
    adapter.addFragment(new Tab2Fragment(), "CHATS");
    //adapter.addFragment(new Tab3Fragment(), "CONTACTS");
    viewPager.setAdapter(adapter);
}

}
</code>```

What should i do to make it work?

The app opens successfully but it doesnt show the navigation drawer...
Please help!!!

答: Using the same NavigationDrawer Java objects is not possible. You have to setup the drawer in the layout file and in the Java code for each activity again.</p>

Body:
BaseActivity.java

public class BaseActivity extends AppCompatActivity
    implements NavigationView.OnNavigationItemSelectedListener {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_base);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
        }
    });

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
            this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    drawer.setDrawerListener(toggle);
    toggle.syncState();

    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);
}

@Override
public void onBackPressed() {
    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    if (drawer.isDrawerOpen(GravityCompat.START)) {
        drawer.closeDrawer(GravityCompat.START);
    } else {
        super.onBackPressed();
    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.base, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
    // Handle navigation view item clicks here.
    int id = item.getItemId();

    if (id == R.id.nav_camera) {
        // Handle the camera action
    } else if (id == R.id.nav_gallery) {

    } else if (id == R.id.nav_slideshow) {

    } else if (id == R.id.nav_manage) {

    } else if (id == R.id.nav_share) {

    } else if (id == R.id.nav_send) {

    }

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawer.closeDrawer(GravityCompat.START);
    return true;
}
}

I am trying to make appear my BaseActivity in my MainActivity. But i am not able to do it....I tried to extend the BaseActivity from the MainActivity but still didn't work...

MainActivity.java

public class MainActivity extends BaseActivity {

private static final String TAG = "MainActivity";
private SectionsPageAdapter mSectionsPageAdapter;
private ViewPager mViewPager;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Log.d(TAG, "onCreate: Starting.");

    mSectionsPageAdapter = new SectionsPageAdapter(getSupportFragmentManager());

    // Set up the ViewPager with the sections adapter.
    mViewPager = (ViewPager) findViewById(R.id.container);
    setupViewPager(mViewPager);

    TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
    tabLayout.setupWithViewPager(mViewPager);
}

private void setupViewPager(ViewPager viewPager) {
    SectionsPageAdapter adapter = new SectionsPageAdapter(getSupportFragmentManager());
    adapter.addFragment(new Tab1Fragment(), "STATUS");
    adapter.addFragment(new Tab2Fragment(), "CHATS");
    //adapter.addFragment(new Tab3Fragment(), "CONTACTS");
    viewPager.setAdapter(adapter);
}

}

What should i do to make it work?

The app opens successfully but it doesnt show the navigation drawer...
Please help!!!


问:
Wrong color when using CopyRect to copy from large image to smaller canvas
I was writing a function to shrink a source image (JPG file) according to a 170 x 200px picture. The source JPG image was loaded into a TImage (Image1, fixed size of 400 x 400px, stretched to fit with aspect ration maintained), then the user will make a selection rectangle to set the area to copy, and then the image will be copied using CopyRect() onto the destination TImage (Image2).

```<code>void __fastcall TSizePhotoForm::Button3Click(TObject *Sender)
{
    float scale, base  = 400.0f;
    TRect crect; // copy rect

    Image2->Width  = 170;
    Image2->Height = 200;

    Image2->Canvas->CopyMode = cmSrcCopy;
    TJPEGImage *img = new TJPEGImage();
    img->LoadFromFile(fname);
    Graphics::TBitmap *bmp = new Graphics::TBitmap;
    bmp->Assign(img);
    scale = (float)img->Width / base;
    crect.Left   = srect.Left * scale; // srect = source rect
    crect.Top    = srect.Top  * scale;
    crect.Right  = crect.Left + (srect.Width()  * scale);
    crect.Bottom = crect.Top  + (srect.Height() * scale);
    Image2->Canvas->CopyRect(TRect(0, 0, w, h), bmp->Canvas, crect);
    delete img;
    delete bmp;
}
</code>```

The problem is, the resulting image color is not right, and I observed that the larger the source image, the resulting image color shifting is more worse.

Here is the screenshot of the result:

Any Idea what's wrong and how do I get rid of this color shifting problem? Thanks in advance.

答:
Ok I tried to recreate your problem And it looks your Image2 pixel format is the problem. I assume you got pf8bit set and jpg is pf24bit so it truncates to greenish... Also Copy rectangle is choppy and StretchDraw is way much smoother. Here comparison:

And the updated code of yours (Assuming Image1 is the source left image and Image2 the zoom image in the right):

As you can see the StretchDraw is the best not sure why they do not use the same Scaling techniques.

int h,w;
float scale, base  = 400.0f;
TRect crect; // copy rect
TRect srect; // I assume some mouse selected rectangle I set it manualy instead
// init and load
Image2->Canvas->CopyMode = cmSrcCopy;
TJPEGImage *img = new TJPEGImage();
img->LoadFromFile("in.jpg");
Graphics::TBitmap *bmp = new Graphics::TBitmap;
bmp->Assign(img);
// I assume this is how you are rendering/store your left (source) image
Image1->Width  = bmp->Width;            // set dersired size
Image1->Height = bmp->Height;
Image1->Left   = 10;
Image1->Top    = 10;
Image1->Canvas->Draw(0,0,bmp);
// I assume this is your mouse selection
srect=TRect(90,34,192,154);
h=120; w=102;
// just render into Image1 for visual check
Image1->Canvas->Pen->Color=clYellow;
Image1->Canvas->Pen->Style=psDashDot;
Image1->Canvas->Brush->Style=bsClear;
Image1->Canvas->Rectangle(srect);
Image1->Canvas->Pen->Style=psSolid;
Image1->Canvas->Brush->Style=bsSolid;
// place and resize Image2 next to Image1
Image2->Top=10;
Image2->Left=Image1->Width+20;
Image2->Width  = 170;
Image2->Height = 200;
// scaling
scale = (float)img->Width / base;
crect.Left   = srect.Left * scale; // srect = source rect
crect.Top    = srect.Top  * scale;
crect.Right  = crect.Left + (srect.Width()  * scale);
crect.Bottom = crect.Top  + (srect.Height() * scale);
// this is how you change the pixelformat
Image2->Picture->Bitmap->PixelFormat=pf32bit;

// your copy rect alternative
// Image2->Canvas->CopyRect(TRect(0,0,h,w), bmp->Canvas, crect);

// my stretch draw alternative
Graphics::TBitmap *tmp=new Graphics::TBitmap;
tmp->PixelFormat=pf32bit;
tmp->SetSize(srect.Width(),srect.Height());
tmp->Canvas->CopyRect(TRect(0,0,srect.Width(),srect.Height()), bmp->Canvas, srect);
Image2->Canvas->StretchDraw(TRect(0,0,srect.Width(),srect.Height()),tmp);
delete tmp;

// exit
delete img;
delete bmp;
```

If you want to know more about bitmap pixel format and fast direct pixel format see:

Display an array of color in C

Also take in mind that Assign and LoadFrom... calls change the pixel format ...

The 8bit preview image is a bit different from yours but I did not have your input image instead I use the screenshot you posted encoded as PNG cropped and reencode as JPG so on per pixel basis there are most likelly diferences in color and may be even in position +/-1px

As you noticed the larger the area the more distortions in color. That is due to that on 8bit pixel formats you got only 256 colors in the palette and if your image contains more colors more of them got truncated. The bigger the selected area the more pixels and hence distinct colors are present in the image. GDI has a bit poor color quantization resulting in what you see...  If you want something better (in case you using 8bit images as output) try these:

Effective gif/image color quantization?

Simple Dithering

Also as you can see the CopyRect did not fit the selection rectangle most likely due to the scaling truncation (looks like they do some poor integer math instead of subdivided DDA or bi-linear filtering to "optimize" the speed)

Body:
I was writing a function to shrink a source image (JPG file) according to a 170 x 200px picture. The source JPG image was loaded into a TImage (Image1, fixed size of 400 x 400px, stretched to fit with aspect ration maintained), then the user will make a selection rectangle to set the area to copy, and then the image will be copied using CopyRect() onto the destination TImage (Image2).

void __fastcall TSizePhotoForm::Button3Click(TObject *Sender)
{
    float scale, base  = 400.0f;
    TRect crect; // copy rect

    Image2->Width  = 170;
    Image2->Height = 200;

    Image2->Canvas->CopyMode = cmSrcCopy;
    TJPEGImage *img = new TJPEGImage();
    img->LoadFromFile(fname);
    Graphics::TBitmap *bmp = new Graphics::TBitmap;
    bmp->Assign(img);
    scale = (float)img->Width / base;
    crect.Left   = srect.Left * scale; // srect = source rect
    crect.Top    = srect.Top  * scale;
    crect.Right  = crect.Left + (srect.Width()  * scale);
    crect.Bottom = crect.Top  + (srect.Height() * scale);
    Image2->Canvas->CopyRect(TRect(0, 0, w, h), bmp->Canvas, crect);
    delete img;
    delete bmp;
}

The problem is, the resulting image color is not right, and I observed that the larger the source image, the resulting image color shifting is more worse.

Here is the screenshot of the result:

Any Idea what's wrong and how do I get rid of this color shifting problem? Thanks in advance.

Body:
Ok I tried to recreate your problem And it looks your Image2 pixel format is the problem. I assume you got pf8bit set and jpg is pf24bit so it truncates to greenish... Also Copy rectangle is choppy and StretchDraw is way much smoother. Here comparison:

And the updated code of yours (Assuming Image1 is the source left image and Image2 the zoom image in the right):

As you can see the StretchDraw is the best not sure why they do not use the same Scaling techniques.

int h,w;
float scale, base  = 400.0f;
TRect crect; // copy rect
TRect srect; // I assume some mouse selected rectangle I set it manualy instead
// init and load
Image2->Canvas->CopyMode = cmSrcCopy;
TJPEGImage *img = new TJPEGImage();
img->LoadFromFile("in.jpg");
Graphics::TBitmap *bmp = new Graphics::TBitmap;
bmp->Assign(img);
// I assume this is how you are rendering/store your left (source) image
Image1->Width  = bmp->Width;            // set dersired size
Image1->Height = bmp->Height;
Image1->Left   = 10;
Image1->Top    = 10;
Image1->Canvas->Draw(0,0,bmp);
// I assume this is your mouse selection
srect=TRect(90,34,192,154);
h=120; w=102;
// just render into Image1 for visual check
Image1->Canvas->Pen->Color=clYellow;
Image1->Canvas->Pen->Style=psDashDot;
Image1->Canvas->Brush->Style=bsClear;
Image1->Canvas->Rectangle(srect);
Image1->Canvas->Pen->Style=psSolid;
Image1->Canvas->Brush->Style=bsSolid;
// place and resize Image2 next to Image1
Image2->Top=10;
Image2->Left=Image1->Width+20;
Image2->Width  = 170;
Image2->Height = 200;
// scaling
scale = (float)img->Width / base;
crect.Left   = srect.Left * scale; // srect = source rect
crect.Top    = srect.Top  * scale;
crect.Right  = crect.Left + (srect.Width()  * scale);
crect.Bottom = crect.Top  + (srect.Height() * scale);
// this is how you change the pixelformat
Image2->Picture->Bitmap->PixelFormat=pf32bit;

// your copy rect alternative
// Image2->Canvas->CopyRect(TRect(0,0,h,w), bmp->Canvas, crect);

// my stretch draw alternative
Graphics::TBitmap *tmp=new Graphics::TBitmap;
tmp->PixelFormat=pf32bit;
tmp->SetSize(srect.Width(),srect.Height());
tmp->Canvas->CopyRect(TRect(0,0,srect.Width(),srect.Height()), bmp->Canvas, srect);
Image2->Canvas->StretchDraw(TRect(0,0,srect.Width(),srect.Height()),tmp);
delete tmp;

// exit
delete img;
delete bmp;

If you want to know more about bitmap pixel format and fast direct pixel format see:

Display an array of color in C

Also take in mind that Assign and LoadFrom... calls change the pixel format ...

The 8bit preview image is a bit different from yours but I did not have your input image instead I use the screenshot you posted encoded as PNG cropped and reencode as JPG so on per pixel basis there are most likelly diferences in color and may be even in position +/-1px

As you noticed the larger the area the more distortions in color. That is due to that on 8bit pixel formats you got only 256 colors in the palette and if your image contains more colors more of them got truncated. The bigger the selected area the more pixels and hence distinct colors are present in the image. GDI has a bit poor color quantization resulting in what you see...  If you want something better (in case you using 8bit images as output) try these:

Effective gif/image color quantization?

Simple Dithering

Also as you can see the CopyRect did not fit the selection rectangle most likely due to the scaling truncation (looks like they do some poor integer math instead of subdivided DDA or bi-linear filtering to "optimize" the speed)


问:
How to minimize this equation by using cvxpy in python?
i am new to CVXPY and would like to do some optimization,

this is my code:

```<code>from numpy.linalg import pinv
AA=pinv(A)  #m*n
AAT=AA.T    #n*m
i1=np.transpose(np.matrix([1,0])) #m*1
i2=np.transpose(np.matrix([0,1])) #m*1

from cvxpy import *
import numpy as np
from numpy import *

#construct the problem
x=Variable(1,5) #1*n
wx=np.matrix([x[0],x[1],x[2],x[3],x[4]])

#consraints
constraints = [x[0]+x[1]+x[2]+x[3]+x[4]==1]
for i in range(5):
constraints += [
    x[i] <= 1,
    x[i] >= 0,
    ]
Q=wx*A*i1*wx*a*AAT*i1
P=wx*A*i2*wx*a*AAT*i2
objective =  Minimize(Q-P)
result=prob.solve()
print(x.value)
</code>```

where

```<code>wx is  1 by n matrix (the variable matrix, unknown, to be solved)
A is n by m (known),i1 is m by 1 (known),i2 is m by 1 (known)
a is n by n (known), AAT is n by m (known)
</code>```

I have A(n by m),and a(n by n):

```<code>A=[[-4.10272297 -1.94100278]
[-0.07551063  0.00533883]
[-0.27742026 -0.17370814]
[ 0.07785536 -1.02386256]
[ 0.77757854  0.04405759]]

a=[[ 80.81155556   0.82893333   2.87077778   2.97862222 -18.59855556]
[  0.82893333   0.01547111   0.04784444  -0.05957111  -0.09624444]
[  2.87077778   0.04784444   0.20449444  -0.00278333  -0.3157    ]
[  2.97862222  -0.05957111  -0.00278333   4.68989889  -3.28908889]
[-18.59855556  -0.09624444  -0.3157      -3.28908889   9.14991111]]
</code>```

BUT i get the following error:

```<code>TypeError: <class 'cvxpy.atoms.affine.add_expr.AddExpression'> is not a valid type for a Constant value.
</code>```

it seems I am not solving a convex problem, so the CVXPY doesn't work
How can I handle this?

I am new to CVXPY so please be specific!Thanks!

答: other people having your problem seem to be getting it because of the array casting. change all your data types to numpy, see if it solves anything</p>

Body:
i am new to CVXPY and would like to do some optimization,

this is my code:

from numpy.linalg import pinv
AA=pinv(A)  #m*n
AAT=AA.T    #n*m
i1=np.transpose(np.matrix([1,0])) #m*1
i2=np.transpose(np.matrix([0,1])) #m*1

from cvxpy import *
import numpy as np
from numpy import *

#construct the problem
x=Variable(1,5) #1*n
wx=np.matrix([x[0],x[1],x[2],x[3],x[4]])

#consraints
constraints = [x[0]+x[1]+x[2]+x[3]+x[4]==1]
for i in range(5):
constraints += [
    x[i] <= 1,
    x[i] >= 0,
    ]
Q=wx*A*i1*wx*a*AAT*i1
P=wx*A*i2*wx*a*AAT*i2
objective =  Minimize(Q-P)
result=prob.solve()
print(x.value)

where

wx is  1 by n matrix (the variable matrix, unknown, to be solved)
A is n by m (known),i1 is m by 1 (known),i2 is m by 1 (known)
a is n by n (known), AAT is n by m (known)

I have A(n by m),and a(n by n):

A=[[-4.10272297 -1.94100278]
[-0.07551063  0.00533883]
[-0.27742026 -0.17370814]
[ 0.07785536 -1.02386256]
[ 0.77757854  0.04405759]]

a=[[ 80.81155556   0.82893333   2.87077778   2.97862222 -18.59855556]
[  0.82893333   0.01547111   0.04784444  -0.05957111  -0.09624444]
[  2.87077778   0.04784444   0.20449444  -0.00278333  -0.3157    ]
[  2.97862222  -0.05957111  -0.00278333   4.68989889  -3.28908889]
[-18.59855556  -0.09624444  -0.3157      -3.28908889   9.14991111]]

BUT i get the following error:

TypeError: <class 'cvxpy.atoms.affine.add_expr.AddExpression'> is not a valid type for a Constant value.

it seems I am not solving a convex problem, so the CVXPY doesn't work
How can I handle this?

I am new to CVXPY so please be specific!Thanks!


问:
UI5 bind new data to model from controller
I am trying to replace data in my model with an array that that i have manually done work on to filter myself. I get this data from model.read(). The problem is none of the documented ways of updating data in a model in ui5 are working or even seem to respond to being called. I am using odata v2 but all these techniques are documented to work for the v2 model: https://openui5.hana.ondemand.com/docs/topics/6c47b2b39db9404582994070ec3d57a2.html

```<code>filterFeed: function() {
    var model = this.getOwnerComponent().getModel();
    var view = this.getView();

    model.read("/assessmentFeed", {
        success: function(odata) {
            var comments = odata.results;
            var results = [];

            // ...  do work to fill 'results'

            model.setProperty('/assessmentFeed', results);

            var json = new sap.ui.model.json.JSONModel(results);
            view.setModel(json, "/assessmentFeed");

            var list = view.byId("feedList");
            list.bindAggregation("items", "/assessmentFeed", new sap.m.FeedListItem());
        }
    });
},
</code>```

This is the feed list in my xml view

```<code><layout:content>
    <m:FeedInput post="onFeedPost" class="sapUiSmallMarginTopBottom"/>
    <m:List id="feedList" showSeparators="Inner" items="{path: '/assessmentFeed', sorter: {path: 'DATE', descending: true}}">
        <m:FeedListItem sender="{MEMBERID}" timestamp="{DATE}" text="{COMMENT}" convertLinksToAnchorTags="All"/>
    </m:List>
</layout:content>
</code>```

I don't get any errors but no discernible effect after calling all the above functions.

This is from the model's aBindings array showing that assessmentFeed is in the model's bindings from the chrome debugger.

答:
Why you're trying to put your data in a JSON model and in the oData model?

Controller:

```<code>        filterFeed: function() {
            var model = this.getOwnerComponent().getModel();
            var view = this.getView();
            var json = new sap.ui.model.json.JSONModel(); //New JSON model

            model.read("/assessmentFeed", {
                success: function(odata) {
                    var comments = odata.results;
                    var results = [];

                    // ...  do work to fill 'results'

                    view.setModel(json, "JSON"); //Set json model and name it JSON
                    json.setProperty("/assessmentFeed", results); //Push results into your json model with path /assessmentFeed
                }
            });
</code>```

View: Binding Path is JSON>/assessmentFeed

```<code><layout:content>
    <m:FeedInput post="onFeedPost" class="sapUiSmallMarginTopBottom"/>
    <m:List id="feedList" showSeparators="Inner" items="{path: 'JSON>/assessmentFeed', sorter: {path: 'DATE', descending: true}}">
        <m:FeedListItem sender="{JSON>MEMBERID}" timestamp="{JSON>DATE}" text="{JSON>COMMENT}" convertLinksToAnchorTags="All"/>
    </m:List>
</layout:content>
</code>```

Body:
I am trying to replace data in my model with an array that that i have manually done work on to filter myself. I get this data from model.read(). The problem is none of the documented ways of updating data in a model in ui5 are working or even seem to respond to being called. I am using odata v2 but all these techniques are documented to work for the v2 model: https://openui5.hana.ondemand.com/docs/topics/6c47b2b39db9404582994070ec3d57a2.html

filterFeed: function() {
    var model = this.getOwnerComponent().getModel();
    var view = this.getView();

    model.read("/assessmentFeed", {
        success: function(odata) {
            var comments = odata.results;
            var results = [];

            // ...  do work to fill 'results'

            model.setProperty('/assessmentFeed', results);

            var json = new sap.ui.model.json.JSONModel(results);
            view.setModel(json, "/assessmentFeed");

            var list = view.byId("feedList");
            list.bindAggregation("items", "/assessmentFeed", new sap.m.FeedListItem());
        }
    });
},

This is the feed list in my xml view

<layout:content>
    <m:FeedInput post="onFeedPost" class="sapUiSmallMarginTopBottom"/>
    <m:List id="feedList" showSeparators="Inner" items="{path: '/assessmentFeed', sorter: {path: 'DATE', descending: true}}">
        <m:FeedListItem sender="{MEMBERID}" timestamp="{DATE}" text="{COMMENT}" convertLinksToAnchorTags="All"/>
    </m:List>
</layout:content>

I don't get any errors but no discernible effect after calling all the above functions.

This is from the model's aBindings array showing that assessmentFeed is in the model's bindings from the chrome debugger.

Body:
Why you're trying to put your data in a JSON model and in the oData model?

Controller:

        filterFeed: function() {
            var model = this.getOwnerComponent().getModel();
            var view = this.getView();
            var json = new sap.ui.model.json.JSONModel(); //New JSON model

            model.read("/assessmentFeed", {
                success: function(odata) {
                    var comments = odata.results;
                    var results = [];

                    // ...  do work to fill 'results'

                    view.setModel(json, "JSON"); //Set json model and name it JSON
                    json.setProperty("/assessmentFeed", results); //Push results into your json model with path /assessmentFeed
                }
            });

View: Binding Path is JSON>/assessmentFeed

<layout:content>
    <m:FeedInput post="onFeedPost" class="sapUiSmallMarginTopBottom"/>
    <m:List id="feedList" showSeparators="Inner" items="{path: 'JSON>/assessmentFeed', sorter: {path: 'DATE', descending: true}}">
        <m:FeedListItem sender="{JSON>MEMBERID}" timestamp="{JSON>DATE}" text="{JSON>COMMENT}" convertLinksToAnchorTags="All"/>
    </m:List>
</layout:content>