小编Byt*_*ger的帖子

了解用户权限以及如何应用它

我正在使用使用Zend Framework的Social Engine为站点开发模块.我是Zend Framework和Social Engine的新手,但在OOP和MVC架构方面有经验,因此可以相对快速地掌握基础知识.

它是我正在开发的测试模块,所以刚刚构建了一个简单的模块,用户可以在其中创建,编辑或删除CD信息.然后有一个小部件可以显示在他们喜欢的地方,显示有CD信息.

我现在正处于需要设置CD人员可以看到的权限等的地步.所以我研究了其他模块,发现Poll模块是一个具体的例子.

看看其他模块,我意识到当你创建一些东西时,他们让用户手动设置他们的权限.

因此,将此代码添加到我的表单中以创建具有相关权限的选择框:

$auth = Engine_Api::_()->authorization()->context;
$user = Engine_Api::_()->user()->getViewer();
$viewOptions = (array) Engine_Api::_()->authorization()->getAdapter('levels')->getAllowed('ryan', $user, 'auth_view');
$viewOptions = array_intersect_key($availableLabels, array_flip($viewOptions));

$privacy = null;

if( !empty($viewOptions) && count($viewOptions) >= 1 ) {
    // Make a hidden field
    if(count($viewOptions) == 1) {
        //$this->addElement('hidden', 'auth_view', array('value' => key($viewOptions)));
        $privacy  = new Zend_Form_Element_Hidden('auth_view');
        $privacy->setValue(key($viewOptions));
        // Make select box
    } else {
        $privacy = new Zend_Form_Element_Select('auth_view');
        $privacy->setLabel('Privacy')
                ->setDescription('Who may see this CD?')
                ->setMultiOptions($viewOptions)
                ->setValue(key($viewOptions));
        /*$this->addElement('Select', 'auth_view', array(
            'label' …
Run Code Online (Sandbox Code Playgroud)

php permissions zend-framework user-permissions socialengine

5
推荐指数
1
解决办法
2689
查看次数

模拟一个在方法调用后更改实例变量的Python类?

我有一些代码,其中对方法的调用update()会更改某些实例变量的值。我使用更改后的值来留下循环。这是我的代码的简化示例:

def do_stuff(self):
    # get a new instance of A
    a = get_a()
    while True:
        a.update()
        if a.state == 'state':
            break
Run Code Online (Sandbox Code Playgroud)

这是该类的简单版本(我无法更改该类,因为它是第 3 方库):

class A(object):
    def __init__(self):
        self.state = ''

    def update(self):
        # call to external system
        self.state = extern_func()
Run Code Online (Sandbox Code Playgroud)

现在我想do_stuff()通过模拟 A 类来测试我的函数。为了测试函数的各个方面,我想要拥有 的所有不同值,state并且它应该在每次调用后发生变化a.update()(迭代不同的状态)。

我开始为我的单元测试设置此设置:

from mock import Mock, patch
import unittest

class TestClass(unittest.TestClass):

    @patch('get_a')
    def test_do_stuff(self, mock_get_a):
         mock_a = Mock(spec=A)
         mock_get_a.return_value = mock_a

         # do some assertions
Run Code Online (Sandbox Code Playgroud)

我可以通过 实现这种行为吗Mock …

python unit-testing mocking

5
推荐指数
1
解决办法
7531
查看次数

'configure'和'configureGlobal'方法之间有什么区别?

我正在研究Spring Security配置,发现配置内存身份验证的最常见方法是使用configureGlobal()method:

@Configuration
@EnableWebMvcSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

  @Autowired
  public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception{
    auth
      .inMemoryAuthentication()
        .withUser("user").password("userPwd").roles("USER");
  }
}
Run Code Online (Sandbox Code Playgroud)

但还有另一种方式,这是不太广泛使用,覆盖configure()从方法WebSecurityConfigurerAdapter

@Configuration
@EnableWebMvcSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

  @Override
  protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth
      .inMemoryAuthentication(
        .withUser("user").password("userPwd").roles("USER");
  }
}
Run Code Online (Sandbox Code Playgroud)

我只是想知道,它们之间有什么区别,使用configureGlobal()方法的重点是configure()什么?

java spring spring-security

5
推荐指数
1
解决办法
1639
查看次数

如何将Zend Framework getResultRowObject转换为数组

public function loginAction() {

   $auth = Zend_Auth::getInstance();    

   $DB = Zend_Db_Table_Abstract::getDefaultAdapter();
   $request=$this->getRequest();        

   $authAdapter = new Zend_Auth_Adapter_DbTable($DB);
   $authAdapter->setTableName('user')
               ->setIdentityColumn('uname')
               ->setCredentialColumn('password');  

   $uname = $request->getParam('uname');
   $pass = $request->getParam('password');

   $authAdapter->setIdentity($uname);
   $authAdapter->setCredential($pass);

   $result = $authAdapter->authenticate($authAdapter);
   $this->view->assign('auth',$result);
   if($result->isValid()) {

       $data = $authAdapter->getResultRowObject(null,'pass');
       $auth->getStorage()->write($data);

       //$this->view->assign('dbdata',$data);

       $userInfo = new Zend_Session_Namespace('userInfo');
       $userInfo->userType = 'admin';

       //$this->_redirect('/admin/adminhome');
   } else {

       $this->_redirect('/admin/index?fail=true');
   }    

   $data = $authAdapter->getResultRowObject(null,'pass');
Run Code Online (Sandbox Code Playgroud)

这里$data将返回一个这样的对象:

stdClass Object ( [id] => 12 [uname] => user [password] => user [type] => user )
Run Code Online (Sandbox Code Playgroud)

我想将其转换为数组.刚试过toArray()功能但是徒劳无功.我的要求是检查用户类型如下:

if($data['type']=='admin'){
do something
} else …
Run Code Online (Sandbox Code Playgroud)

php zend-framework

4
推荐指数
1
解决办法
5398
查看次数

在嵌套的playbooks之间传递变量

我有一个剧本,我用ec2模块在aws中旋转一个实例.为了更灵活,我通过提示输入主机名.我在ec2示例中找到了代码片段,它允许您使用新的spun up实例运行第二个playbook以进行进一步配置.

现在我想通过模块设置主机名,hostname但我无法访问第二个playbook中的变量.

这是我的剧本的样子:

---
- hosts: localhost
  ...

  vars_prompt:
    - name: var_hostname
      prompt: "Please enter the hostname"
      private: no

  tasks:

    - name: Spin up instance
      local_action:
        module: ec2
        ...
      register: ec2

    - name: Add new instance to host group
      add_host: hostname={{ item.public_ip }} groupname=launched
      with_items: ec2.instances

- hosts: launched
  ...

  tasks:

    - name: Set hostname
      hostname: name="{{ var_hostname }}"
Run Code Online (Sandbox Code Playgroud)

致命:[已启动] =>一个或多个未定义的变量:'var_hostname'未定义

有没有办法将变量从一个剧本传递到另一个剧本?

我找到了Ansible最佳做法,将vars传递给嵌套的剧本?但不幸的是,它没有我可以使用的解决方案.

ansible ansible-playbook

4
推荐指数
2
解决办法
9706
查看次数

更改 bash 文件备份的后缀

我一直在尝试使用该--suffix功能更改备份文件的后缀,但我不太确定该怎么做。目前这行代码

find ./$1 -name "IMG_****.JPG" -exec cp --backup=t {} ./$2 \;
Run Code Online (Sandbox Code Playgroud)

在第一个命令行参数目录中搜索IMG_****.JPG格式中的图像,并将它们复制到第二个输入的目录中,复制任何具有重复名称的文件,并将后缀添加=t到末尾给出IMG_****.JPG.~1~等。而不是.~1~我想添加类似的东西.JPG,任何关于如何使用--suffix来做到这一点的想法?

linux bash suffix

4
推荐指数
1
解决办法
3691
查看次数

jedi-vim在使用goto赋值/定义跳转后返回旧位置

我使用vim与jedi/ jedi-vim当我开发Python代码,我使用广泛<Leader>d(转到定义)和/或<Leader>g(转到分配).我可以使用''返回跳转前的行,但只能在同一个文件中.

有没有办法在不同文件之间跳转时有相同的行为?

vim jedi-vim

4
推荐指数
1
解决办法
535
查看次数

zf2路由器:一个模块使路由器无法找到另一个模块.我怎样才能使两者都有效?

我们刚刚开始使用zf2,所以其他人制作了一个Thumbnail服务器模块,然后我添加了一个Lookup服务器模块.我称之为服务器,因为它们都是RESTful apis.最初它们似乎在一起工作,但有人对我的模块进行了一些更改,现在除非从application.config.php模块列表中删除Lookup,否则缩略图服务器将无法工作.Lookup服务器无论如何都可以.查看代码,我看不到对Lookup所做的更改会如何影响Thumbnail.我得到的错误看起来像这样:

<h1>A 404 error occurred</h1>
<h2>Page not found.</h2>
<p>The requested controller was unable to dispatch the request.</p>
<dl>
<dt>Controller:</dt>
<dd>Lookup\Controller\Lookup</dd>
</dl>
Run Code Online (Sandbox Code Playgroud)

这是application.config.php看起来像:

<?php
return array(
    'modules' => array(
        'Application',
        'SanRestful',
        'Album',
        'AlbumRest',   
        'Thumbnail',         
        'Lookup',
        'AP_XmlStrategy',
    ),
    'module_listener_options' => array(
        'config_glob_paths'    => array(
            'config/autoload/{,*.}{global,local}.php',
            'config/autoload/{,*.}' . (getenv('APPLICATION_ENV') ?: 'production') . '.php',
        ),
        'module_paths' => array(
            './module',
            './vendor',
        ),
    ),
);
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,最初的专辑模块和其他一些实验模块.My Lookup模块使用Allessandro Pietrobelli提供的优秀AP_XmlStrategy模块.

下面是缩略图module.config.php.它有一个可能没有被使用的约束,因为没有名为"id"的参数,但这不应该搞乱,是吗?

<?php
return array(
    'controllers' => array( …
Run Code Online (Sandbox Code Playgroud)

zend-framework2 zend-framework-routing

3
推荐指数
1
解决办法
6362
查看次数

如何测试RSpec中是否发生了带参数的方法调用

在我的Ruby应用程序中,我试图用RSpec测试一个用控制器参数调用的模块方法.

有问题的模块是用于跟踪分析的EventTracker模块:https://github.com/doorkeeper/event_tracker

情况就是这样:

  1. 从我的控制器我从控制器调用方法如下:

    class InvestorHomeController < ApplicationController
      def do_something
        track_event 'User Action'
      end
    end
    
    Run Code Online (Sandbox Code Playgroud)
  2. track_event方法在EventTracker模块内定义,如下所示:

    module EventTracker
      module HelperMethods
        def track_event(event_name, args = {})
          (session[:event_tracker_queue] ||= []) << [event_name, args]
      end
    end
    
    Run Code Online (Sandbox Code Playgroud)

    结束

  3. 我尝试了不同的解决方案,但没有任何对我有用.喜欢:

    expect(controller).to receive(:track_event).with('User Action')
    expect(EventTracker).to receive(:track_event).with('User Action')
    
    Run Code Online (Sandbox Code Playgroud)

第一个它不起作用,因为track_event不是控制器的方法,而对于第二个我有以下错误:

RSpec::Mocks::MockExpectationError: (EventTracker).track_event("User Action")
expected: 1 time with arguments: ("User Action")
received: 0 times
Run Code Online (Sandbox Code Playgroud)

谁知道如何用RSpec测试这种方法?

感谢:D.

ruby rspec ruby-on-rails

3
推荐指数
1
解决办法
4872
查看次数

如何将基于范围的for循环与future &lt;T&gt;的向量一起使用

I have a program that calculates some values in different threads with std::packaged_task<int()>. I store the std::future I get from the packaged tasks via get_future() in a vector (defined as std::vector<std::future<int>>).

When I calculate the sum of all the tasks I use a for loop and it's working:

// set up of the tasks
std::vector<std::future<int>> results;
// store the futures in results
// each task execute in its own thread

int sum{ 0 };
for (auto i = …
Run Code Online (Sandbox Code Playgroud)

c++ stdvector c++11 std-future

1
推荐指数
1
解决办法
47
查看次数

两步到一步初始化和错误处理

这似乎是一个奇怪的问题.我目前正在将某些对象从两步骤移动到一步式初始化方案.基本上将在.initialize() .terminate()成员函数中完成的操作移动到构造函数和析构函数中.

我的问题是,重要的是要知道这些类是否正确地初始化了某些依赖于外部因素的属性.

一个例子是我的Window类,它创建一个WinAPI窗口.以前使用两步法我会initialize()返回一个是否正确创建窗口的布尔值.

if(myWindow.initialize())
{
    // proceed with application
}
else
{
    // exit
}    
Run Code Online (Sandbox Code Playgroud)

无论如何从构造函数中继这些信息而不创建并且必须调用第二种方法,例如didMyWindowInitializeCorrectly()

起初我希望有一些东西

if(Window *myWindow = new Window)
{
    // proceed with application
}
else
{
    // exit
}
Run Code Online (Sandbox Code Playgroud)

但这不起作用,因为即使窗口创建失败,Window对象仍将实例化.

唯一的解决方案是让构造函数抛出异常然后捕获并继续吗?我看了很多线程,人们对C++异常的看法似乎相当分裂,所以我不确定什么是最好的方法.

无论如何用if语句处理这种情况?

c++ constructor exception-handling initialization

0
推荐指数
1
解决办法
849
查看次数

什么是pygame.Surface.get_rect()键参数?

我正在学习pygame在我的编程课程中使用,但我对这个pygame.Surface.get_rect()方法感到困惑.我看到它可能需要一些关键字参数,但我无法找到它们的任何地方.我见过,get_rect(center=(num, num))但我正在尝试指定一个左上角坐标.有办法做到这一点吗?

python pygame

0
推荐指数
1
解决办法
3198
查看次数