问:
Unknown column 'User.first_name' in 'where clause' cakePHP
I have tutor_students and users table. tutor_studentscontains id, tutor_id, student_id and created. users contain id, user_id, role_id, email, first_name, last_name. tutor_students table is connected table between tutor and student. so tutor can see their student list and can add new student too.

I succeeded to display student list and add new student to tutor student list. but when i want to search student, there will be an error:

Error: SQLSTATE[42S22]: Column not found: 1054 Unknown column
  'User.email' in 'where clause'

SQL Query: SELECT TutorStudent.id, TutorStudent.tutor_id,
  TutorStudent.student_id, TutorStudent.created FROM
  virlen.tutor_students AS TutorStudent WHERE
  TutorStudent.tutor_id IS NULL AND User.email LIKE
  '%ka@mailinator.com%'

My controller:

```<code>public function admin_tutor_add_student($tutor_id = null)
{
    $user_list = '';
    $this->loadModel('TutorStudent');
    $this->set('title_for_layout','User');
    $this->User->bindModel(array(
                    'belongsTo'=>array(
                        'Standard'=>array(
                            'className'=>'Standard'
                        ),
                    )
    ),false);

    $this->User->id     =   $tutor_id;
    /*form post and check conditions*/
    // if ($this->request->is('post') || $this->request->is('put'))
    if(!empty($this->request->data) && isset($this->request->data['User']['status1']))
    {
        // pr($this->request->data);die;
        $action = $this->request->data['User']['pageAction'];
        foreach ($this->request->data['User'] AS $value) {
            if ($value != 0) {
                $ids[] = $value;
            }
        }

        // pr($ids);die;
        if (!empty($this->request->data))
        {
            if (!isset($this->request->params['_Token']['key']) || ($this->request->params['_Token']['key'] != $this->request->params['_Token']['key']))
            {
                $blackHoleCallback = $this->Security->blackHoleCallback;
                $this->$blackHoleCallback();
            }
            foreach($ids as $id)
            {
                if(!empty($id))
                {
                    if($id != 1)
                    {
                        $shift = array();
                        $shift['TutorStudent']['tutor_id'] = $tutor_id;
                        $shift['TutorStudent']['student_id'] = $id;
                        $this->TutorStudent->save($shift);
                        $this->TutorStudent->id = false;
                    }
                }
            }

            $this->Session->setFlash("Tutor has been added successfully", 'admin_flash_good');
            $this->redirect(array('controller'=>'users', 'action'=>'subadmin_tutor',$tutor_id));

        }
    }

    if (!isset($this->params['named']['page']))
    {
        $this->Session->delete('AdminSearch');
    }
    $email = '';
    $first_name = '';
    $role_id = '';
    $status = '';
    if (!empty($this->request->data))
    {
        $this->Session->delete('AdminSearch');
        if (isset($this->request->data['User']['first_name']) && $this->request->data['User']['first_name'] != '')
        {
            $first_name = trim($this->request->data['User']['first_name']);
            $this->Session->write('AdminSearch.first_name', $first_name);
        }
        if (isset($this->request->data['User']['email']) && $this->request->data['User']['email'] != '')
        {
            $email = trim($this->request->data['User']['email']);
            $this->Session->write('AdminSearch.email', $email);
        }

    }

    $filters    =   array('TutorStudent.tutor_id'=>$tutor_id);
    if ($this->Session->check('AdminSearch'))
    {
        $keywords   =   $this->Session->read('AdminSearch');
        foreach($keywords as $key=>$values)
        {
            if($key == 'email')
            {
                $email = $values;
                $filters[] = array('User.'.$key.' LIKE'=>"%".$values."%");
            }
            if($key == 'first_name')
            {
                $first_name = $values;
                $filters[] = array('User.'.$key.' LIKE'=>"%".$values."%");
            }
        }
    }

    $my_tutor_list = $this->TutorStudent->find('all',array('conditions'=>$filters));
    if(!empty($my_tutor_list))
    {
        foreach($my_tutor_list as $key=>$value)
        {
            $user_list[] = $value['TutorStudent']['student_id'];
        }
    }

    $this->paginate = array('User' => array(
        'limit' =>Configure::read('App.PageLimit'),
        'order' => array('User.id' => 'DESC'),
        'conditions'=>array('User.id !='=>$user_list,'User.role_id'=>2),
        )); //role_id 2 means student user

    $student_list = $this->paginate('User');

    // pr($student_list);die;
    $this->loadModel('Standard');
    $standards  =   $this->Standard->getStandardList();
    $this->set(compact('standards'));
    $this->set(compact('student_list','tutor_id','standard_id', 'User', 'email', 'first_name'));
    $this->set('title_for_layout', __('User', true));
}
</code>```

this is my view file:

```<code><?php echo($this->Form->create('User', array('url'=>array('controller' => 'users', 'action' => 'tutor_add_student'))));?>
            <div class="box-body table-responsive">
                <div class="box box-danger">
                    <div class="full box-header">
                        <h3 class="box-title">Search</h3>
                    </div>
                    <div class="box-body">
                        <div class="row">
                            <div class="col-xs-2">
                                <label for="exampleInputPassword1">User Email</label>
                                <?php echo($this->Form->input('User.email', array('placeholder'=>"Tutor Email",'label' => false,'value'=>$email, 'div'=>false,'class'=>'form-control'))); ?>
                            </div>
                            <div class="col-xs-2">
                                <label for="exampleInputPassword1">First Name </label>
                                <?php echo($this->Form->input('User.first_name', array('placeholder'=>"First Name",'label' => false,'value'=>$first_name, 'div'=>false,'class'=>'form-control'))); ?>
                            </div>
                            <div class="col-xs-2" style="margin-top: 5px;">
                                <br /><?php echo($this->Form->submit('Search', array('div'=>false, 'class'=>'btn btn-primary pull-left')));?>
                            </div>

                        </div>
                    </div><!-- /.box-body -->
                </div>

            </div>
         <?php echo($this->Form->end());?>
</code>```

This is my app model for user:

```<code>    <?php
/**
 * Country
 *
 * PHP version 5
 *
 * @category Model
 *
 */
// App::uses('AuthComponent', 'Controller/Component');
// App::uses('SessionComponent', 'Controller/Component');
App::uses('AppModel', 'Model');
class User extends AppModel{

    //public $primaryKey = '_id';

    /**
     * Model name
     * @var string
     * @access public
     */
    var $name = 'User';
    /**
     * Behaviors used by the Model
     *
     * @var array
     * @access public
     */

    var $actsAs = array(
       'Multivalidatable'
    );

    var $validationSets = array(
        'login'=>   array(
            'email'=>array(
                'notEmpty' => array(
                    'rule'      => 'notEmpty',
                    'message'   =>  'Email address is required'
                ),
                'R2'=>array(
                    'rule'=>array('maxLength', 50),
                    'message'=>'Email can be maximum 50 characters long.'
                ),
                'email' =>  array(
                    'rule'  =>  'email',
                    'message'   =>  'Please provide a valid email address.'
                ),
            ),
            'password'=>array(
                'R1'=>array(
                    'rule'=>'notEmpty',
                    'message' => 'Password is required.'
                ),
                'R3'=>array(
                    'rule'=>array('minLength', 6),
                    'message'=>'Password must be at least 6 characters long.'
                ),
                'R4'=>array(
                    'rule'=>array('maxLength', 20),
                    'message'=>'Password must be at least 20 characters long.'
                ),
            ),
        ),
        'add'=> array(
            'first_name'=>array(
                'R1'=>array(
                    'rule'=>'notEmpty',
                    'message' => 'First name is required.'
                ),
                'R2'=>array(
                    'rule'=>array('maxLength', 255),
                    'message'=>'First Name can be maximum 255 characters long.'
                ),
                'characters' => array(
                    'rule'     => array('custom', '/^[a-z]*$/i'),
                    'message'  => 'Alphabet characters only'
                )
            ),
            'last_name'=>array(
                'R1'=>array(
                    'rule'=>'notEmpty',
                    'message' => 'Last name is required.'
                ),
                'R2'=>array(
                    'rule'=>array('maxLength',255),
                    'message'=>'Last name can be maximum 255 characters long.'
                ),
                'characters' => array(
                    'rule'     => array('custom', '/^[a-z]*$/i'),
                    'message'  => 'Alphabet characters only'
                )
            ),
            'standard_id'=>array(
                'R1'=>array(
                    'rule'=>'notEmpty',
                    'message' => 'Standard is required.'
                )
            ),
            'role_id'=>array(
                'R1'=>array(
                    'rule'=>'notEmpty',
                    'message' => 'Role is required.'
                )
            ),
            'specilization'=>array(
                'R1' => array(
                    'rule'      => 'notEmpty',
                    'message'   =>  'Specilization is required.'
                ),
                'R2'=>array(
                    'rule'=>array('maxLength', 255),
                    'message'=>'Specilization can be 255 characters long.'
                ),
            ),
            'phone'=>array(
                'R1' => array(
                    'rule'      => 'notEmpty',
                    'message'   =>  'Phone number is required.'
                ),
                'notEmpty' => array(
                    'rule'      => 'numeric',
                    'message'   =>  'Phone number should be numeric'
                ),
                'R2'=>array(
                    'rule'=>array('minLength', 8),
                    'message'=>'Phone number shuold be minimum 8 numbers long'
                ),
                'R3'=>array(
                    'rule'=>array('maxLength', 12),
                    'message'=>'Phone number should be maximum 12 numbers long'
                ),
                /* 'R4'=>array(
                    'rule'=>array('CheckPhoneVailidation'),
                    'message'=>'Phone no should be start with 82 to 87.'
                ),   */
            ),
            'email'=>array(
                'notEmpty' => array(
                    'rule'      => 'notEmpty',
                    'message'   =>  'Email address is required'
                ),
                'R2'=>array(
                    'rule'=>array('maxLength', 50),
                    'message'=>'Email can be maximum 50 characters long.'
                ),
                'isUnique'  =>  array(
                    'rule'  =>  'isUnique',
                    'message'   =>  'Email already exists.'
                ),
                'email' =>  array(
                    'rule'  =>  'email',
                    'message'   =>  'Please provide a valid email address.'
                ),
            ),
            'new_password'=>array(
                'R1'=>array(
                    'rule'=>'notEmpty',
                    'message' => 'Password is required.'
                ),
                'R3'=>array(
                    'rule'=>array('minLength', 6),
                    'message'=>'Password must be at least 6 characters long.'
                ),
                'R4'=>array(
                    'rule'=>array('maxLength', 20),
                    'message'=>'Password must be at least 20 characters long.'
                ),
            ),
            'confirm_password'=>array(
                'identicalFieldValues' => array(
                    'rule' => array('identicalFieldValues', 'new_password'),
                    'message' => 'Password and confirm password mismatch'
                ),
                'R1' => array(
                    'rule' => 'notEmpty',
                    'message' => 'Confirm password is required.'
                )

            ),
            'image' => array(
                'R1' => array(
                    'rule' => array('checkextension'),
                    'message' => 'Please upload only image files'
                )
            ),
        )

    );
}
</code>```

答:
You need to contain the User model in your find query:-

```<code>$this->TutorStudent->find('all', array(
    'conditions' => $filters,
    'contain' => array('User')
);
</code>```

Body:
I have tutor_students and users table. tutor_studentscontains id, tutor_id, student_id and created. users contain id, user_id, role_id, email, first_name, last_name. tutor_students table is connected table between tutor and student. so tutor can see their student list and can add new student too.

I succeeded to display student list and add new student to tutor student list. but when i want to search student, there will be an error:

Error: SQLSTATE[42S22]: Column not found: 1054 Unknown column
  'User.email' in 'where clause'

SQL Query: SELECT TutorStudent.id, TutorStudent.tutor_id,
  TutorStudent.student_id, TutorStudent.created FROM
  virlen.tutor_students AS TutorStudent WHERE
  TutorStudent.tutor_id IS NULL AND User.email LIKE
  '%ka@mailinator.com%'

My controller:

public function admin_tutor_add_student($tutor_id = null)
{
    $user_list = '';
    $this->loadModel('TutorStudent');
    $this->set('title_for_layout','User');
    $this->User->bindModel(array(
                    'belongsTo'=>array(
                        'Standard'=>array(
                            'className'=>'Standard'
                        ),
                    )
    ),false);

    $this->User->id     =   $tutor_id;
    /*form post and check conditions*/
    // if ($this->request->is('post') || $this->request->is('put'))
    if(!empty($this->request->data) && isset($this->request->data['User']['status1']))
    {
        // pr($this->request->data);die;
        $action = $this->request->data['User']['pageAction'];
        foreach ($this->request->data['User'] AS $value) {
            if ($value != 0) {
                $ids[] = $value;
            }
        }

        // pr($ids);die;
        if (!empty($this->request->data))
        {
            if (!isset($this->request->params['_Token']['key']) || ($this->request->params['_Token']['key'] != $this->request->params['_Token']['key']))
            {
                $blackHoleCallback = $this->Security->blackHoleCallback;
                $this->$blackHoleCallback();
            }
            foreach($ids as $id)
            {
                if(!empty($id))
                {
                    if($id != 1)
                    {
                        $shift = array();
                        $shift['TutorStudent']['tutor_id'] = $tutor_id;
                        $shift['TutorStudent']['student_id'] = $id;
                        $this->TutorStudent->save($shift);
                        $this->TutorStudent->id = false;
                    }
                }
            }

            $this->Session->setFlash("Tutor has been added successfully", 'admin_flash_good');
            $this->redirect(array('controller'=>'users', 'action'=>'subadmin_tutor',$tutor_id));

        }
    }

    if (!isset($this->params['named']['page']))
    {
        $this->Session->delete('AdminSearch');
    }
    $email = '';
    $first_name = '';
    $role_id = '';
    $status = '';
    if (!empty($this->request->data))
    {
        $this->Session->delete('AdminSearch');
        if (isset($this->request->data['User']['first_name']) && $this->request->data['User']['first_name'] != '')
        {
            $first_name = trim($this->request->data['User']['first_name']);
            $this->Session->write('AdminSearch.first_name', $first_name);
        }
        if (isset($this->request->data['User']['email']) && $this->request->data['User']['email'] != '')
        {
            $email = trim($this->request->data['User']['email']);
            $this->Session->write('AdminSearch.email', $email);
        }

    }

    $filters    =   array('TutorStudent.tutor_id'=>$tutor_id);
    if ($this->Session->check('AdminSearch'))
    {
        $keywords   =   $this->Session->read('AdminSearch');
        foreach($keywords as $key=>$values)
        {
            if($key == 'email')
            {
                $email = $values;
                $filters[] = array('User.'.$key.' LIKE'=>"%".$values."%");
            }
            if($key == 'first_name')
            {
                $first_name = $values;
                $filters[] = array('User.'.$key.' LIKE'=>"%".$values."%");
            }
        }
    }

    $my_tutor_list = $this->TutorStudent->find('all',array('conditions'=>$filters));
    if(!empty($my_tutor_list))
    {
        foreach($my_tutor_list as $key=>$value)
        {
            $user_list[] = $value['TutorStudent']['student_id'];
        }
    }

    $this->paginate = array('User' => array(
        'limit' =>Configure::read('App.PageLimit'),
        'order' => array('User.id' => 'DESC'),
        'conditions'=>array('User.id !='=>$user_list,'User.role_id'=>2),
        )); //role_id 2 means student user

    $student_list = $this->paginate('User');

    // pr($student_list);die;
    $this->loadModel('Standard');
    $standards  =   $this->Standard->getStandardList();
    $this->set(compact('standards'));
    $this->set(compact('student_list','tutor_id','standard_id', 'User', 'email', 'first_name'));
    $this->set('title_for_layout', __('User', true));
}

this is my view file:

<?php echo($this->Form->create('User', array('url'=>array('controller' => 'users', 'action' => 'tutor_add_student'))));?>

Search

                                User Email
                                <?php echo($this->Form->input('User.email', array('placeholder'=>"Tutor Email",'label' => false,'value'=>$email, 'div'=>false,'class'=>'form-control'))); ?>

                                First Name
                                <?php echo($this->Form->input('User.first_name', array('placeholder'=>"First Name",'label' => false,'value'=>$first_name, 'div'=>false,'class'=>'form-control'))); ?>

<?php echo($this->Form->submit('Search', array('div'=>false, 'class'=>'btn btn-primary pull-left')));?>

         <?php echo($this->Form->end());?>

This is my app model for user:

    <?php
/**
 * Country
 *
 * PHP version 5
 *
 * @category Model
 *
 */
// App::uses('AuthComponent', 'Controller/Component');
// App::uses('SessionComponent', 'Controller/Component');
App::uses('AppModel', 'Model');
class User extends AppModel{

    //public $primaryKey = '_id';

    /**
     * Model name
     * @var string
     * @access public
     */
    var $name = 'User';
    /**
     * Behaviors used by the Model
     *
     * @var array
     * @access public
     */

    var $actsAs = array(
       'Multivalidatable'
    );

    var $validationSets = array(
        'login'=>   array(
            'email'=>array(
                'notEmpty' => array(
                    'rule'      => 'notEmpty',
                    'message'   =>  'Email address is required'
                ),
                'R2'=>array(
                    'rule'=>array('maxLength', 50),
                    'message'=>'Email can be maximum 50 characters long.'
                ),
                'email' =>  array(
                    'rule'  =>  'email',
                    'message'   =>  'Please provide a valid email address.'
                ),
            ),
            'password'=>array(
                'R1'=>array(
                    'rule'=>'notEmpty',
                    'message' => 'Password is required.'
                ),
                'R3'=>array(
                    'rule'=>array('minLength', 6),
                    'message'=>'Password must be at least 6 characters long.'
                ),
                'R4'=>array(
                    'rule'=>array('maxLength', 20),
                    'message'=>'Password must be at least 20 characters long.'
                ),
            ),
        ),
        'add'=> array(
            'first_name'=>array(
                'R1'=>array(
                    'rule'=>'notEmpty',
                    'message' => 'First name is required.'
                ),
                'R2'=>array(
                    'rule'=>array('maxLength', 255),
                    'message'=>'First Name can be maximum 255 characters long.'
                ),
                'characters' => array(
                    'rule'     => array('custom', '/^[a-z]*$/i'),
                    'message'  => 'Alphabet characters only'
                )
            ),
            'last_name'=>array(
                'R1'=>array(
                    'rule'=>'notEmpty',
                    'message' => 'Last name is required.'
                ),
                'R2'=>array(
                    'rule'=>array('maxLength',255),
                    'message'=>'Last name can be maximum 255 characters long.'
                ),
                'characters' => array(
                    'rule'     => array('custom', '/^[a-z]*$/i'),
                    'message'  => 'Alphabet characters only'
                )
            ),
            'standard_id'=>array(
                'R1'=>array(
                    'rule'=>'notEmpty',
                    'message' => 'Standard is required.'
                )
            ),
            'role_id'=>array(
                'R1'=>array(
                    'rule'=>'notEmpty',
                    'message' => 'Role is required.'
                )
            ),
            'specilization'=>array(
                'R1' => array(
                    'rule'      => 'notEmpty',
                    'message'   =>  'Specilization is required.'
                ),
                'R2'=>array(
                    'rule'=>array('maxLength', 255),
                    'message'=>'Specilization can be 255 characters long.'
                ),
            ),
            'phone'=>array(
                'R1' => array(
                    'rule'      => 'notEmpty',
                    'message'   =>  'Phone number is required.'
                ),
                'notEmpty' => array(
                    'rule'      => 'numeric',
                    'message'   =>  'Phone number should be numeric'
                ),
                'R2'=>array(
                    'rule'=>array('minLength', 8),
                    'message'=>'Phone number shuold be minimum 8 numbers long'
                ),
                'R3'=>array(
                    'rule'=>array('maxLength', 12),
                    'message'=>'Phone number should be maximum 12 numbers long'
                ),
                /* 'R4'=>array(
                    'rule'=>array('CheckPhoneVailidation'),
                    'message'=>'Phone no should be start with 82 to 87.'
                ),   */
            ),
            'email'=>array(
                'notEmpty' => array(
                    'rule'      => 'notEmpty',
                    'message'   =>  'Email address is required'
                ),
                'R2'=>array(
                    'rule'=>array('maxLength', 50),
                    'message'=>'Email can be maximum 50 characters long.'
                ),
                'isUnique'  =>  array(
                    'rule'  =>  'isUnique',
                    'message'   =>  'Email already exists.'
                ),
                'email' =>  array(
                    'rule'  =>  'email',
                    'message'   =>  'Please provide a valid email address.'
                ),
            ),
            'new_password'=>array(
                'R1'=>array(
                    'rule'=>'notEmpty',
                    'message' => 'Password is required.'
                ),
                'R3'=>array(
                    'rule'=>array('minLength', 6),
                    'message'=>'Password must be at least 6 characters long.'
                ),
                'R4'=>array(
                    'rule'=>array('maxLength', 20),
                    'message'=>'Password must be at least 20 characters long.'
                ),
            ),
            'confirm_password'=>array(
                'identicalFieldValues' => array(
                    'rule' => array('identicalFieldValues', 'new_password'),
                    'message' => 'Password and confirm password mismatch'
                ),
                'R1' => array(
                    'rule' => 'notEmpty',
                    'message' => 'Confirm password is required.'
                )

            ),
            'image' => array(
                'R1' => array(
                    'rule' => array('checkextension'),
                    'message' => 'Please upload only image files'
                )
            ),
        )

    );
}

Body:
You need to contain the User model in your find query:-

$this->TutorStudent->find('all', array(
    'conditions' => $filters,
    'contain' => array('User')
);


来源: stackexchange

问:
Custom sorting columns in multi level pandas dataframe

Background

I have a big data frame with 2 levels columns, but 1 level rows, and I am trying to sort it as follows:
level 0: alphabetically;
level 1: custom sort.

Example

```<code>import pandas as pd
dictionary = {'A' : {'M': [1,2,3,4,5],
                     'L': [6,7,8,9,1],
                     'F': [3,5,1,3,5]  },
              'C' : {'M': [2,3,4,5,6],
                     'L': [7,8,9,1,2],
                     'F': [0,1,6,3,5]  },
              'B' : {'M': [1,5,2,5,3],
                     'L': [9,5,6,3,4],
                     'F': [6,2,7,1,5] }
         }
reform = {(outerKey, innerKey): values for outerKey, innerDict in dictionary.iteritems() for innerKey, values in innerDict.iteritems()}
pd.DataFrame(reform,index=['g','h','i','j','k'])
</code>```

What I have then is

```<code>#        A          B           C
#        F  L   M   F   L   M   F   L   M
#    g  3   6   1   6   9   1   0   7   2
#    h  5   7   2   2   5   5   1   8   3
#    i  1   8   3   7   6   2   6   9   4
#    j  3   9   4   1   3   5   3   1   5
#    k  5   1   5   5   4   3   5   2   6
</code>```

Question

How can I specify the order of columns to be A, B, C on level 0 and F, M, L on level 1?

```<code>### OUT
#        A          B           C
#        F  M   L   F   M   L   F   M   L
</code>```

I was trying with pd.IndexSlice and .loc, but I still get only alphabetic order.

答:
Setting index on dataframe creation

If you do not want to change the dataframe afterwards, you can give the pd.DataFrame constructor an index where you define the order already.

Explicit solution

```<code>columns = pd.Index([('A', 'F'), ('A', 'M'), ('A', 'L'), ('B', 'F'), ('B', 'M'), ('B', 'L'),('C', 'F'), ('C', 'M'), ('C', 'L')])
pd.DataFrame(reform,index=['g','h','i','j','k'], columns=columns)
</code>```

Composite solution

```<code>columns = pd.Index([(level_0, level_1) for level_0 in "ABC" for level_1 in "FML"])
pd.DataFrame(reform,index=['g','h','i','j','k'], columns=columns)
</code>```

Both gives

```<code>   A        B        C
   F  M  L  F  M  L  F  M  L
g  3  1  6  6  1  9  0  2  7
h  5  2  7  2  5  5  1  3  8
i  1  3  8  7  2  6  6  4  9
j  3  4  9  1  5  3  3  5  1
k  5  5  1  5  3  4  5  6  2
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Background

I have a big data frame with 2 levels columns, but 1 level rows, and I am trying to sort it as follows:
level 0: alphabetically;
level 1: custom sort.

Example

import pandas as pd
dictionary = {'A' : {'M': [1,2,3,4,5],
                     'L': [6,7,8,9,1],
                     'F': [3,5,1,3,5]  },
              'C' : {'M': [2,3,4,5,6],
                     'L': [7,8,9,1,2],
                     'F': [0,1,6,3,5]  },
              'B' : {'M': [1,5,2,5,3],
                     'L': [9,5,6,3,4],
                     'F': [6,2,7,1,5] }
         }
reform = {(outerKey, innerKey): values for outerKey, innerDict in dictionary.iteritems() for innerKey, values in innerDict.iteritems()}
pd.DataFrame(reform,index=['g','h','i','j','k'])

What I have then is

#        A          B           C
#        F  L   M   F   L   M   F   L   M
#    g  3   6   1   6   9   1   0   7   2
#    h  5   7   2   2   5   5   1   8   3
#    i  1   8   3   7   6   2   6   9   4
#    j  3   9   4   1   3   5   3   1   5
#    k  5   1   5   5   4   3   5   2   6

Question

How can I specify the order of columns to be A, B, C on level 0 and F, M, L on level 1?

### OUT
#        A          B           C
#        F  M   L   F   M   L   F   M   L

I was trying with pd.IndexSlice and .loc, but I still get only alphabetic order.

Body:
Setting index on dataframe creation

If you do not want to change the dataframe afterwards, you can give the pd.DataFrame constructor an index where you define the order already.

Explicit solution

columns = pd.Index([('A', 'F'), ('A', 'M'), ('A', 'L'), ('B', 'F'), ('B', 'M'), ('B', 'L'),('C', 'F'), ('C', 'M'), ('C', 'L')])
pd.DataFrame(reform,index=['g','h','i','j','k'], columns=columns)

Composite solution

columns = pd.Index([(level_0, level_1) for level_0 in "ABC" for level_1 in "FML"])
pd.DataFrame(reform,index=['g','h','i','j','k'], columns=columns)

Both gives

   A        B        C
   F  M  L  F  M  L  F  M  L
g  3  1  6  6  1  9  0  2  7
h  5  2  7  2  5  5  1  3  8
i  1  3  8  7  2  6  6  4  9
j  3  4  9  1  5  3  3  5  1
k  5  5  1  5  3  4  5  6  2


问:
When are Crashlytics custom logs sent?
I have a BaseActivity that I use as a parent for all my Activities. I'd like to log Activity events (onCreate(), onStart(), onResume(), etc.) to Crashlytics, so when a crash happens, I know what the user was doing and what Activities were currently alive. I added the following code to all the methods that I want to log:

```<code>CrashlyticsCore.getInstance().log(getClass().getSimpleName() + ".onResume()");
</code>```

I'm wondering if it's a good idea to do it. Are the logs only sent when a crash happens? Will I not spam the server and produce unnecessary network calls for the users? Perhaps there's a better method of implementing bread crumbs with Crashlytics?

答:
As the name subtly suggests, Crashlytics will only trigger a report (and send a log) after a crash, and will only contain up to 64kb of log history as stated in the docs: "To make sure that sending crash reports has the smallest impact on your user’s devices, Crashlytics logs have a maximum size of 64 KB. When a log exceeds 64 KB, the earliest logged values will be dropped in order to maintain this threshold."

If you ask my personal opinion, it's not good practice or useful to log every onCreate, onResume. A Crashlytics report will already contain the stacktrace giving you insight on the error.

If you have caught exceptions and want to log those, you can do so as explain here, by calling Crashlytics.logException(e);. Again only 8 of these will be stored: "For any individual app session, only the most recent 8 logged exceptions are stored".

Title: When are Crashlytics custom logs sent?

Body:
I have a BaseActivity that I use as a parent for all my Activities. I'd like to log Activity events (onCreate(), onStart(), onResume(), etc.) to Crashlytics, so when a crash happens, I know what the user was doing and what Activities were currently alive. I added the following code to all the methods that I want to log:

CrashlyticsCore.getInstance().log(getClass().getSimpleName() + ".onResume()");

I'm wondering if it's a good idea to do it. Are the logs only sent when a crash happens? Will I not spam the server and produce unnecessary network calls for the users? Perhaps there's a better method of implementing bread crumbs with Crashlytics?


问:
Closing file descriptor while performing ioctl
I'm writing a Linux Kernel Module, and my userland app is looping on a parallel ioctl call (to get info from the kernel module). But when I want to close the file descriptor (linked to my kernel module), the release function is not executed until the ioctl function has not exited.

I can't find anything on why it behaves like that. Do you have an idea on why it happens, and how I can avoid this blocking ? I'd basically like to have my ioctl and close functions being executed simultaneously in my kernel module.

Thank you ! :)

答:
I'd basically like to have my ioctl and close functions being executed simultaneously in my kernel module.

You cannot.

Calling .release() method means that the file object isn't used anymore. So it cannot be executed while ioctl for given file is in progress.


问:
Tablesaw headers not shown on mobile
According to their examples and documentation you should be able to see the headers when you are on a mobile phone:

tablesaw doc

table-saw demo

However when i attempt this with the following table:

```<code><table id="table-client" class="table table-responsive tablesaw tablesaw-stack" data-tablesaw-mode="stack"
</code>```

i get this:

As you can see without the headers.

I searched around and saw a guy on github having the same problem however he did not have any luck with solving the issue.

My question to you guys is, has anyone ever encountered the problem and know of a way to fix it?

答:
Without seeing your html table's structure it is impossible to say why the headers are not showing up. But this is the code from the demo site, so just match what they have done here and it should work.

Make sure you're including their library's CSS. It looks like you might not be, and that could be the problem.

They are using a later version of jQuery (v3.1.1) than the one I selected (v2.1.1), but it doesn't appear to matter.

<link rel="stylesheet" href="http://filamentgroup.github.io/tablesaw/dist/tablesaw.css">

      Movie Title
      Rank
      Year
      Rating
      Gross

      Movie TitleAvatar
      Rank1
      Year2009
      Rating83%
      Gross$2.7B

      Movie TitleTitanic
      Rank2
      Year1997
      Rating88%
      Gross$2.1B

      Movie TitleThe Avengers
      Rank3
      Year2012
      Rating92%
      Gross$1.5B

      Movie TitleHarry Potter and the Deathly Hallows—Part 2
      Rank4
      Year2011
      Rating96%
      Gross$1.3B

      Movie TitleFrozen
      Rank5
      Year2013
      Rating89%
      Gross$1.2B

      Movie TitleIron Man 3
      Rank6
      Year2013
      Rating78%
      Gross$1.2B

      Movie TitleTransformers: Dark of the Moon
      Rank7
      Year2011
      Rating36%
      Gross$1.1B

      Movie TitleThe Lord of the Rings: The Return of the King
      Rank8
      Year2003
      Rating95%
      Gross$1.1B

      Movie TitleSkyfall
      Rank9
      Year2012
      Rating92%
      Gross$1.1B

      Movie TitleTransformers: Age of Extinction
      Rank10
      Year2014
      Rating18%
      Gross$1.0B

```

Title: Tablesaw headers not shown on mobile

Body:
According to their examples and documentation you should be able to see the headers when you are on a mobile phone:

tablesaw doc

table-saw demo

However when i attempt this with the following table:

<table id="table-client" class="table table-responsive tablesaw tablesaw-stack" data-tablesaw-mode="stack"

i get this:

As you can see without the headers.

I searched around and saw a guy on github having the same problem however he did not have any luck with solving the issue.

My question to you guys is, has anyone ever encountered the problem and know of a way to fix it?

Body:
Without seeing your html table's structure it is impossible to say why the headers are not showing up. But this is the code from the demo site, so just match what they have done here and it should work.

Make sure you're including their library's CSS. It looks like you might not be, and that could be the problem.

They are using a later version of jQuery (v3.1.1) than the one I selected (v2.1.1), but it doesn't appear to matter.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://filamentgroup.github.io/tablesaw/dist/tablesaw.js"></script>
<script src="https://filamentgroup.github.io/tablesaw/dist/tablesaw-init.js"></script>
<link rel="stylesheet" href="http://filamentgroup.github.io/tablesaw/dist/tablesaw.css">

<table class="tablesaw tablesaw-stack" data-tablesaw-mode="stack" id="tablesaw-5335">
  <thead>
    <tr>
      <th scope="col" data-tablesaw-priority="persist">Movie Title</th>
      <th scope="col" data-tablesaw-sortable-default-col="" data-tablesaw-priority="3">Rank</th>
      <th scope="col" data-tablesaw-priority="2">Year</th>
      <th scope="col" data-tablesaw-priority="1"><abbr title="Rotten Tomato Rating">Rating</abbr></th>
      <th scope="col" data-tablesaw-priority="4">Gross</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td class="title"><b class=" tablesaw-cell-label">Movie Title</b><span class="tablesaw-cell-content"><a href="http://en.wikipedia.org/wiki/Avatar_(2009_film)">Avatar</a></span></td>
      <td><b class=" tablesaw-cell-label">Rank</b><span class="tablesaw-cell-content">1</span></td>
      <td><b class=" tablesaw-cell-label">Year</b><span class="tablesaw-cell-content">2009</span></td>
      <td><b class=" tablesaw-cell-label"><abbr title="Rotten Tomato Rating">Rating</abbr></b><span class="tablesaw-cell-content">83%</span></td>
      <td><b class=" tablesaw-cell-label">Gross</b><span class="tablesaw-cell-content">$2.7B</span></td>
    </tr>
    <tr>
      <td class="title"><b class=" tablesaw-cell-label">Movie Title</b><span class="tablesaw-cell-content"><a href="http://en.wikipedia.org/wiki/Titanic_(1997_film)">Titanic</a></span></td>
      <td><b class=" tablesaw-cell-label">Rank</b><span class="tablesaw-cell-content">2</span></td>
      <td><b class=" tablesaw-cell-label">Year</b><span class="tablesaw-cell-content">1997</span></td>
      <td><b class=" tablesaw-cell-label"><abbr title="Rotten Tomato Rating">Rating</abbr></b><span class="tablesaw-cell-content">88%</span></td>
      <td><b class=" tablesaw-cell-label">Gross</b><span class="tablesaw-cell-content">$2.1B</span></td>
    </tr>
    <tr>
      <td class="title"><b class=" tablesaw-cell-label">Movie Title</b><span class="tablesaw-cell-content"><a href="http://en.wikipedia.org/wiki/The_Avengers_(2012_film)">The Avengers</a></span></td>
      <td><b class=" tablesaw-cell-label">Rank</b><span class="tablesaw-cell-content">3</span></td>
      <td><b class=" tablesaw-cell-label">Year</b><span class="tablesaw-cell-content">2012</span></td>
      <td><b class=" tablesaw-cell-label"><abbr title="Rotten Tomato Rating">Rating</abbr></b><span class="tablesaw-cell-content">92%</span></td>
      <td><b class=" tablesaw-cell-label">Gross</b><span class="tablesaw-cell-content">$1.5B</span></td>
    </tr>
    <tr>
      <td class="title"><b class=" tablesaw-cell-label">Movie Title</b><span class="tablesaw-cell-content"><a href="http://en.wikipedia.org/wiki/Harry_Potter_and_the_Deathly_Hallows_%E2%80%93_Part_2">Harry Potter and the Deathly Hallows—Part 2</a></span></td>
      <td><b class=" tablesaw-cell-label">Rank</b><span class="tablesaw-cell-content">4</span></td>
      <td><b class=" tablesaw-cell-label">Year</b><span class="tablesaw-cell-content">2011</span></td>
      <td><b class=" tablesaw-cell-label"><abbr title="Rotten Tomato Rating">Rating</abbr></b><span class="tablesaw-cell-content">96%</span></td>
      <td><b class=" tablesaw-cell-label">Gross</b><span class="tablesaw-cell-content">$1.3B</span></td>
    </tr>
    <tr>
      <td class="title"><b class=" tablesaw-cell-label">Movie Title</b><span class="tablesaw-cell-content"><a href="http://en.wikipedia.org/wiki/Frozen_(2013_film)">Frozen</a></span></td>
      <td><b class=" tablesaw-cell-label">Rank</b><span class="tablesaw-cell-content">5</span></td>
      <td><b class=" tablesaw-cell-label">Year</b><span class="tablesaw-cell-content">2013</span></td>
      <td><b class=" tablesaw-cell-label"><abbr title="Rotten Tomato Rating">Rating</abbr></b><span class="tablesaw-cell-content">89%</span></td>
      <td><b class=" tablesaw-cell-label">Gross</b><span class="tablesaw-cell-content">$1.2B</span></td>
    </tr>
    <tr>
      <td class="title"><b class=" tablesaw-cell-label">Movie Title</b><span class="tablesaw-cell-content"><a href="http://en.wikipedia.org/wiki/Iron_Man_3">Iron Man 3</a></span></td>
      <td><b class=" tablesaw-cell-label">Rank</b><span class="tablesaw-cell-content">6</span></td>
      <td><b class=" tablesaw-cell-label">Year</b><span class="tablesaw-cell-content">2013</span></td>
      <td><b class=" tablesaw-cell-label"><abbr title="Rotten Tomato Rating">Rating</abbr></b><span class="tablesaw-cell-content">78%</span></td>
      <td><b class=" tablesaw-cell-label">Gross</b><span class="tablesaw-cell-content">$1.2B</span></td>
    </tr>
    <tr>
      <td class="title"><b class=" tablesaw-cell-label">Movie Title</b><span class="tablesaw-cell-content"><a href="http://en.wikipedia.org/wiki/Transformers:_Dark_of_the_Moon">Transformers: Dark of the Moon</a></span></td>
      <td><b class=" tablesaw-cell-label">Rank</b><span class="tablesaw-cell-content">7</span></td>
      <td><b class=" tablesaw-cell-label">Year</b><span class="tablesaw-cell-content">2011</span></td>
      <td><b class=" tablesaw-cell-label"><abbr title="Rotten Tomato Rating">Rating</abbr></b><span class="tablesaw-cell-content">36%</span></td>
      <td><b class=" tablesaw-cell-label">Gross</b><span class="tablesaw-cell-content">$1.1B</span></td>
    </tr>
    <tr>
      <td class="title"><b class=" tablesaw-cell-label">Movie Title</b><span class="tablesaw-cell-content"><a href="http://en.wikipedia.org/wiki/The_Lord_of_the_Rings:_The_Return_of_the_King">The Lord of the Rings: The Return of the King</a></span></td>
      <td><b class=" tablesaw-cell-label">Rank</b><span class="tablesaw-cell-content">8</span></td>
      <td><b class=" tablesaw-cell-label">Year</b><span class="tablesaw-cell-content">2003</span></td>
      <td><b class=" tablesaw-cell-label"><abbr title="Rotten Tomato Rating">Rating</abbr></b><span class="tablesaw-cell-content">95%</span></td>
      <td><b class=" tablesaw-cell-label">Gross</b><span class="tablesaw-cell-content">$1.1B</span></td>
    </tr>
    <tr>
      <td class="title"><b class=" tablesaw-cell-label">Movie Title</b><span class="tablesaw-cell-content"><a href="http://en.wikipedia.org/wiki/Skyfall">Skyfall</a></span></td>
      <td><b class=" tablesaw-cell-label">Rank</b><span class="tablesaw-cell-content">9</span></td>
      <td><b class=" tablesaw-cell-label">Year</b><span class="tablesaw-cell-content">2012</span></td>
      <td><b class=" tablesaw-cell-label"><abbr title="Rotten Tomato Rating">Rating</abbr></b><span class="tablesaw-cell-content">92%</span></td>
      <td><b class=" tablesaw-cell-label">Gross</b><span class="tablesaw-cell-content">$1.1B</span></td>
    </tr>
    <tr>
      <td class="title"><b class=" tablesaw-cell-label">Movie Title</b><span class="tablesaw-cell-content"><a href="http://en.wikipedia.org/wiki/Transformers:_Age_of_Extinction">Transformers: Age of Extinction</a></span></td>
      <td><b class=" tablesaw-cell-label">Rank</b><span class="tablesaw-cell-content">10</span></td>
      <td><b class=" tablesaw-cell-label">Year</b><span class="tablesaw-cell-content">2014</span></td>
      <td><b class=" tablesaw-cell-label"><abbr title="Rotten Tomato Rating">Rating</abbr></b><span class="tablesaw-cell-content">18%</span></td>
      <td><b class=" tablesaw-cell-label">Gross</b><span class="tablesaw-cell-content">$1.0B</span></td>
    </tr>
  </tbody>
</table>


问:
Using Microsoft.AspNetCore.Mvc in .NetStandard 1.4 or below class library
I have requirement to create a .Netstandard library which should support .Net core and .NetFramework 4.5.2.
And I must have to use Microsoft.AspNetCore.Mvc in both the targets(.net core app and .NetFramework 4.5.2)

But Microsoft.AspNetCore.Mvc is supported on .Netstandard 1.6 on wards and .Netframework 4.5.1.

I can build .Netstandard 1.6 calss library an consume in .Net 4.5.2. (this is not working below is the problem)

I cannot consume .Netstandard 1.6 from .NetFramework 4.5.2. (I am getting below exception during run Could not load file or assembly 'System.Runtime, Version=4.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The system cannot find the file specified)

same question is posted on github too but no solutions yet.(https://github.com/aspnet/Mvc/issues/6028#issuecomment-289606346)

Thanks in advance.

答:
You can find the matrix of what versions of .NET standard are supported by which framework here:

https://learn.microsoft.com/en-us/dotnet/articles/standard/library

So no, .net standard 1.6 is not supported by 4.5.2.

Essentially this stuff is still in development, and until .net standard 2.0 is here you'll continue to run into these kinds of issues.

The way we get around this is to build two libs from the same source code, one targeting netcoreapp or .Net standard, the other targeting the full framework. You have two vcproj files, but a single set of code. Not ideal, but the best you can likely do right now.


问:
VBA macro outlook generating email
I have the below code, which send an outlook email by grabbing data from my Excel sheet.

This email is sent automatically as soon as I click the button to allow access to my email.

I would like to change this so that the email is generated and I have to physically press send on each email before it is sent.

Can someone please help as to how I need to change the code to do this, code below,

```<code>Sub Mail_Selection_Range_Outlook_Body()
'For Tips see: http://www.rondebruin.nl/win/winmail/Outlook/tips.htm
'Don't forget to copy the function RangetoHTML in the module.
'Working in Excel 2000-2016
    Dim rng As Range
    Dim OutApp As Object
    Dim OutMail As Object
    Dim cell As Range
    Dim StrBody As String

    Set rng = Nothing
    On Error Resume Next
    'Only the visible cells in the selection
    Set rng = Selection.SpecialCells(xlCellTypeVisible)
    'You can also use a fixed range if you want
    Set rng = Range("ZCCollar").SpecialCells(xlCellTypeVisible)

    On Error GoTo 0

    If rng Is Nothing Then
        MsgBox "The selection is not a range or the sheet is protected" & _
               vbNewLine & "please correct and try again.", vbOKOnly
        Exit Sub
    End If

    With Application
        .EnableEvents = False
        .ScreenUpdating = False
    End With

     StrBody = Sheets("MailInfo").Range("E1").Value & "<br><br>" & _
              Sheets("MailInfo").Range("E2").Value & "<br>" & _
              Sheets("MailInfo").Range("E3").Value

    Set OutApp = CreateObject("Outlook.Application")

On Error Resume Next
For Each cell In Sheets("MailInfo").Columns("B").Cells.SpecialCells(xlCellTypeConstants)
    If cell.Value Like "?*@?*.?*" And _
       LCase(Cells(cell.Row, "C").Value) = "yes" Then

        Set OutMail = OutApp.CreateItem(0)
        On Error Resume Next
        With OutMail
            .To = cell.Value
            .Subject = "Index Option RFQ"

            .HTMLBody = StrBody & RangetoHTML(rng) & "<br>" & "Thanks"

            'You can add files also like this
            '.Attachments.Add ("C:\test.txt")
            .Send  'Or use Display
        End With
        On Error GoTo 0
        Set OutMail = Nothing
    End If
Next cell

    With Application
        .EnableEvents = True
        .ScreenUpdating = True
    End With

    Set OutMail = Nothing
    Set OutApp = Nothing
End Sub

Function RangetoHTML(rng As Range)
' Changed by Ron de Bruin 28-Oct-2006
' Working in Office 2000-2016
    Dim fso As Object
    Dim ts As Object
    Dim TempFile As String
    Dim TempWB As Workbook

    TempFile = Environ$("temp") & "\" & Format(Now, "dd-mm-yy h-mm-ss") & ".htm"

    'Copy the range and create a new workbook to past the data in
    rng.Copy
    Set TempWB = Workbooks.Add(1)
    With TempWB.Sheets(1)
        .Cells(1).PasteSpecial Paste:=8
        .Cells(1).PasteSpecial xlPasteValues, , False, False
        .Cells(1).PasteSpecial xlPasteFormats, , False, False
        .Cells(1).Select
        Application.CutCopyMode = False
        On Error Resume Next
        .DrawingObjects.Visible = True
        .DrawingObjects.Delete
        On Error GoTo 0
    End With

    'Publish the sheet to a htm file
    With TempWB.PublishObjects.Add( _
         SourceType:=xlSourceRange, _
         Filename:=TempFile, _
         Sheet:=TempWB.Sheets(1).Name, _
         Source:=TempWB.Sheets(1).UsedRange.Address, _
         HtmlType:=xlHtmlStatic)
        .Publish (True)
    End With

    'Read all data from the htm file into RangetoHTML
    Set fso = CreateObject("Scripting.FileSystemObject")
    Set ts = fso.GetFile(TempFile).OpenAsTextStream(1, -2)
    RangetoHTML = ts.readall
    ts.Close
    RangetoHTML = Replace(RangetoHTML, "align=center x:publishsource=", _
                          "align=left x:publishsource=")

    'Close TempWB
    TempWB.Close savechanges:=False

    'Delete the htm file we used in this function
    Kill TempFile

    Set ts = Nothing
    Set fso = Nothing
    Set TempWB = Nothing
End Function
</code>```

答:
Change

.Send

to

.Display

inside the With OutMail block.

In this way the email will be generated, displayed, but not sent, waiting for you to click send

Title: VBA macro outlook generating email

Body:
I have the below code, which send an outlook email by grabbing data from my Excel sheet.

This email is sent automatically as soon as I click the button to allow access to my email.

I would like to change this so that the email is generated and I have to physically press send on each email before it is sent.

Can someone please help as to how I need to change the code to do this, code below,

Sub Mail_Selection_Range_Outlook_Body()
'For Tips see: http://www.rondebruin.nl/win/winmail/Outlook/tips.htm
'Don't forget to copy the function RangetoHTML in the module.
'Working in Excel 2000-2016
    Dim rng As Range
    Dim OutApp As Object
    Dim OutMail As Object
    Dim cell As Range
    Dim StrBody As String

    Set rng = Nothing
    On Error Resume Next
    'Only the visible cells in the selection
    Set rng = Selection.SpecialCells(xlCellTypeVisible)
    'You can also use a fixed range if you want
    Set rng = Range("ZCCollar").SpecialCells(xlCellTypeVisible)

    On Error GoTo 0

    If rng Is Nothing Then
        MsgBox "The selection is not a range or the sheet is protected" & _
               vbNewLine & "please correct and try again.", vbOKOnly
        Exit Sub
    End If

    With Application
        .EnableEvents = False
        .ScreenUpdating = False
    End With

     StrBody = Sheets("MailInfo").Range("E1").Value & "

" & _
              Sheets("MailInfo").Range("E2").Value & "
" & _
              Sheets("MailInfo").Range("E3").Value

    Set OutApp = CreateObject("Outlook.Application")

On Error Resume Next
For Each cell In Sheets("MailInfo").Columns("B").Cells.SpecialCells(xlCellTypeConstants)
    If cell.Value Like "?*@?*.?*" And _
       LCase(Cells(cell.Row, "C").Value) = "yes" Then

        Set OutMail = OutApp.CreateItem(0)
        On Error Resume Next
        With OutMail
            .To = cell.Value
            .Subject = "Index Option RFQ"

            .HTMLBody = StrBody & RangetoHTML(rng) & "
" & "Thanks"

            'You can add files also like this
            '.Attachments.Add ("C:\test.txt")
            .Send  'Or use Display
        End With
        On Error GoTo 0
        Set OutMail = Nothing
    End If
Next cell

    With Application
        .EnableEvents = True
        .ScreenUpdating = True
    End With

    Set OutMail = Nothing
    Set OutApp = Nothing
End Sub

Function RangetoHTML(rng As Range)
' Changed by Ron de Bruin 28-Oct-2006
' Working in Office 2000-2016
    Dim fso As Object
    Dim ts As Object
    Dim TempFile As String
    Dim TempWB As Workbook

    TempFile = Environ$("temp") & "\" & Format(Now, "dd-mm-yy h-mm-ss") & ".htm"

    'Copy the range and create a new workbook to past the data in
    rng.Copy
    Set TempWB = Workbooks.Add(1)
    With TempWB.Sheets(1)
        .Cells(1).PasteSpecial Paste:=8
        .Cells(1).PasteSpecial xlPasteValues, , False, False
        .Cells(1).PasteSpecial xlPasteFormats, , False, False
        .Cells(1).Select
        Application.CutCopyMode = False
        On Error Resume Next
        .DrawingObjects.Visible = True
        .DrawingObjects.Delete
        On Error GoTo 0
    End With

    'Publish the sheet to a htm file
    With TempWB.PublishObjects.Add( _
         SourceType:=xlSourceRange, _
         Filename:=TempFile, _
         Sheet:=TempWB.Sheets(1).Name, _
         Source:=TempWB.Sheets(1).UsedRange.Address, _
         HtmlType:=xlHtmlStatic)
        .Publish (True)
    End With

    'Read all data from the htm file into RangetoHTML
    Set fso = CreateObject("Scripting.FileSystemObject")
    Set ts = fso.GetFile(TempFile).OpenAsTextStream(1, -2)
    RangetoHTML = ts.readall
    ts.Close
    RangetoHTML = Replace(RangetoHTML, "align=center x:publishsource=", _
                          "align=left x:publishsource=")

    'Close TempWB
    TempWB.Close savechanges:=False

    'Delete the htm file we used in this function
    Kill TempFile

    Set ts = Nothing
    Set fso = Nothing
    Set TempWB = Nothing
End Function


问:
log4net: how to customize data to be stored
I have few different web services exposed by my web site. Here is a goals I want to reach:

Store all data in DB in one table;

Each record should have text field with 'service/component' name;

It is necessary to store all income parameters when any method is called;

It is necessary to store all outcome parameters AND error messages if any exception is occurred.

My original intention was to use log4net. But from these walk-through (http://sadi02.wordpress.com/2008/09/15/how-to-store-log-in-database-using-log4net/, http://logging.apache.org/log4net/release/config-examples.html) I don't see an easy way to add custom data into log table.

Is it feasible to use log4net for such purposes? How can I change logging table schema to store custom data? Should I modify source code of log4net library? Probably would be better to write a custom functionality to store such kind of data?

Thanks.

答:
Looking at the log4net documentation, can you figure out how to get your custom data logged to a file?  If so, you should also be able to get that same data logged to the database.  Just add more columns in your table, more columns in the <command text> node of the AdoNetAppender, and more <parameter> nodes.

I think that you will have some work to do to get your incoming and outgoing parameters logged.  Do you need them logged in separate columns (probably not easy to do cleanly)?  Is it ok if they are logged together with the message?

For example, if you have the following method that you want put logging into:

```<code>public void DoSomething(int x, int y)
{
  log.Info("Inside DoSomething");
}
</code>```

What do you want your output to look like?  Do you want the "standard" log4net info to appear in separate columns (timestamp, loggername, level, message)?  What about the parameters?  Should x and y appear in separate columns (probably not very easy to do unless every method has the same number of parameters) or would it ok if the parameters were logged like this:

```<code>public void DoSomething(int x, int y)
{
  ILog log = LogManager.GetLogger("abc");
  log.InfoFormat("Parameters: x = {0}, y = {1}", x, y);
  log.Info("Inside DoSomething");
}
</code>```

The log statements will generate messages that will look something like this:

```<code>11/29/2010 16:36:00 | abc | INFO | Parameters: x = 10, y = 20
11/29/2010 16:36:00 | abc | INFO | Inside DoSomething
</code>```

I have used the | character to show what the fields would be with a pattern layout that shows the timestamp, loggername, log level, and message.

Looking at an AOP solution like PostSharp might help you because you could relatively easily add enter/exit logging without "polluting" your application source code with logging statements.  Inside of the logging "aspect" you would have access to the parameters to the method.

I might be missing something, but I suspect that if you want to maintain your method parameters as individual columns in the database then you are going to find it hard to do.  If you are satisfied with combining all parameters (manually) for each method as a single column (essentially a formatted string), then that will be easier.  One price you will have to pay is that you will have to explicitly log all parameters (unless you go the AOP route).

If you are considering using log4net, you should also consider using NLog.  It won't necessarily help you with the issues that I described above, but I think that it is a worthy competitor to log4net.

[EDIT]

To get the "component name" logged by log4net, you should name your loggers for your components.  When you call LogManager.GetLogger(name), you can pass any name (or type).  A common pattern is to have code like this in each class:

```<code>public class MyClass
{
  private static readonly ILog logger = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

  public void DoSomething(int x)
  {
    logger.InfoFormat("Inside DoSomething.  x = {0}", x);
  }
}
</code>```

This will get a logger named with the fully qualified class name (namespace + class name).  If you do this in every class, then you can control logging (level, which appender it goes to, etc) per class.  So, you could easily turn logging for Class1 to Info and logging for Class2 Off, etc.  This gives you the potential for the greatest degree of control of your logging.

Now, in your config file, you are not obligated to list each logger (i.e. each fully qualified class name) explicitly.  You could just configure the root logger and then those settings would be applied to every logger.  You could control you logging by namespace.  For example, if you work for CompanyX and you have explicit namespace rules, your namespaces might look like:

```<code>CompanyX
CompanyX.DataAccess
CompanyX.DataAccess.Read
CompanyX.DataAccess.Write
CompanyX.GUI
CompanyX.Forms
CompanyX.Controls
</code>```

Within each namespace, you might have various class (like several different data readers, helper classes, data writers, etc).  With you classes organized like this and with your classes getting loggers as above, you could easily configure logging for all classes in CompanyX, or all loggers in CompanyX.DataAccess, or CompanyX.DataAccess.Read, etc.  You could even turn all logging off, but turn it on for that one troublesome class that is giving you problems.

You can also get your loggers by arbitrary names (i.e. you do not have to use class name if you don't want to).  You could define functional areas in your app(s) and get loggers based on that:

```<code>ILog logger = LogManager.GetLogger("DataAccess");
ILog logger = LogManager.GetLogger("Performance");
ILog logger = LogManager.GetLogger("UI");
</code>```

And so on.  I don't see that this gives much benefit over using the fully qualified class name.  If your namespace(s) are well organized, then your ability to configure your logging will have maximum flexibility with minimum effort on your part.

Another word on NLog...  NLog is very similar to log4net.  It does have the useful feature of being able to automatically return a logger for the current class:

```<code>Logger logger = NLog.LogManager.GetCurrentClassLogger();
</code>```

This at least saves some typing on your part.  NLog has also just come out with a new release (currently in beta).

Don't know if any of this helped, but I hope it did!

Good luck!

ContentLicense: CC BY-SA 2.5

Body:
Looking at the log4net documentation, can you figure out how to get your custom data logged to a file?  If so, you should also be able to get that same data logged to the database.  Just add more columns in your table, more columns in the <command text> node of the AdoNetAppender, and more <parameter> nodes.

I think that you will have some work to do to get your incoming and outgoing parameters logged.  Do you need them logged in separate columns (probably not easy to do cleanly)?  Is it ok if they are logged together with the message?

For example, if you have the following method that you want put logging into:

public void DoSomething(int x, int y)
{
  log.Info("Inside DoSomething");
}

What do you want your output to look like?  Do you want the "standard" log4net info to appear in separate columns (timestamp, loggername, level, message)?  What about the parameters?  Should x and y appear in separate columns (probably not very easy to do unless every method has the same number of parameters) or would it ok if the parameters were logged like this:

public void DoSomething(int x, int y)
{
  ILog log = LogManager.GetLogger("abc");
  log.InfoFormat("Parameters: x = {0}, y = {1}", x, y);
  log.Info("Inside DoSomething");
}

The log statements will generate messages that will look something like this:

11/29/2010 16:36:00 | abc | INFO | Parameters: x = 10, y = 20
11/29/2010 16:36:00 | abc | INFO | Inside DoSomething

I have used the | character to show what the fields would be with a pattern layout that shows the timestamp, loggername, log level, and message.

Looking at an AOP solution like PostSharp might help you because you could relatively easily add enter/exit logging without "polluting" your application source code with logging statements.  Inside of the logging "aspect" you would have access to the parameters to the method.

I might be missing something, but I suspect that if you want to maintain your method parameters as individual columns in the database then you are going to find it hard to do.  If you are satisfied with combining all parameters (manually) for each method as a single column (essentially a formatted string), then that will be easier.  One price you will have to pay is that you will have to explicitly log all parameters (unless you go the AOP route).

If you are considering using log4net, you should also consider using NLog.  It won't necessarily help you with the issues that I described above, but I think that it is a worthy competitor to log4net.

[EDIT]

To get the "component name" logged by log4net, you should name your loggers for your components.  When you call LogManager.GetLogger(name), you can pass any name (or type).  A common pattern is to have code like this in each class:

public class MyClass
{
  private static readonly ILog logger = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

  public void DoSomething(int x)
  {
    logger.InfoFormat("Inside DoSomething.  x = {0}", x);
  }
}

This will get a logger named with the fully qualified class name (namespace + class name).  If you do this in every class, then you can control logging (level, which appender it goes to, etc) per class.  So, you could easily turn logging for Class1 to Info and logging for Class2 Off, etc.  This gives you the potential for the greatest degree of control of your logging.

Now, in your config file, you are not obligated to list each logger (i.e. each fully qualified class name) explicitly.  You could just configure the root logger and then those settings would be applied to every logger.  You could control you logging by namespace.  For example, if you work for CompanyX and you have explicit namespace rules, your namespaces might look like:

CompanyX
CompanyX.DataAccess
CompanyX.DataAccess.Read
CompanyX.DataAccess.Write
CompanyX.GUI
CompanyX.Forms
CompanyX.Controls

Within each namespace, you might have various class (like several different data readers, helper classes, data writers, etc).  With you classes organized like this and with your classes getting loggers as above, you could easily configure logging for all classes in CompanyX, or all loggers in CompanyX.DataAccess, or CompanyX.DataAccess.Read, etc.  You could even turn all logging off, but turn it on for that one troublesome class that is giving you problems.

You can also get your loggers by arbitrary names (i.e. you do not have to use class name if you don't want to).  You could define functional areas in your app(s) and get loggers based on that:

ILog logger = LogManager.GetLogger("DataAccess");
ILog logger = LogManager.GetLogger("Performance");
ILog logger = LogManager.GetLogger("UI");

And so on.  I don't see that this gives much benefit over using the fully qualified class name.  If your namespace(s) are well organized, then your ability to configure your logging will have maximum flexibility with minimum effort on your part.

Another word on NLog...  NLog is very similar to log4net.  It does have the useful feature of being able to automatically return a logger for the current class:

Logger logger = NLog.LogManager.GetCurrentClassLogger();

This at least saves some typing on your part.  NLog has also just come out with a new release (currently in beta).

Don't know if any of this helped, but I hope it did!

Good luck!


问:
How to avoid having 2 times | async in this situation (4.0.0)?
I would like to avoid to use .subscribe() in this component.
I tried *ngIf="user$ | async as user" but it did not work.

How can I make a local variable with user$ | async un order to use it at different places in this view?

<app-xpbar *ngIf="user$ | async"></app-xpbar>

  <app-header-common
    (onSearch)="searching($event)">
  </app-header-common>

  <app-header-user
    [user]="user$ | async"
    (onLogin)="login($event)"
    (onTrial)="trial($event)">
  </app-header-user>

```

答:
You can try to create structural directive like:

ng-async.directive.ts

```<code>@Directive({ selector: '[ngAsync]' })
export class NgAsync {
   constructor(private vcRef: ViewContainerRef, private templateRef: TemplateRef<any>) {}

   @Input()
   set ngAsync(variable: any) {
      this.vcRef.clear();
      this.vcRef.createEmbeddedView(this.templateRef, { $implicit: variable });
   }
}
</code>```

Then you can use it the following way

view.html

```<code><ng-container *ngAsync="user$ | async; let user">
  <app-xpbar *ngIf="user"></app-xpbar>

  <header class="header">

    <app-header-common
      (onSearch)="searching($event)">
    </app-header-common>

    <app-header-user
      [user]="user"
      (onLogin)="login($event)"
      (onTrial)="trial($event)">
    </app-header-user>

  </header>
</ng-container>
</code>```

Body:
You can try to create structural directive like:

ng-async.directive.ts

@Directive({ selector: '[ngAsync]' })
export class NgAsync {
   constructor(private vcRef: ViewContainerRef, private templateRef: TemplateRef<any>) {}

   @Input()
   set ngAsync(variable: any) {
      this.vcRef.clear();
      this.vcRef.createEmbeddedView(this.templateRef, { $implicit: variable });
   }
}

Then you can use it the following way

view.html

<ng-container *ngAsync="user$ | async; let user">
  <app-xpbar *ngIf="user"></app-xpbar>

  <header class="header">

    <app-header-common
      (onSearch)="searching($event)">
    </app-header-common>

    <app-header-user
      [user]="user"
      (onLogin)="login($event)"
      (onTrial)="trial($event)">
    </app-header-user>

  </header>
</ng-container>


问:
Gulp SASS watch command destination path with wildcard
I have a gulp watch command on my SASS (SCSS) files in many directories (each directory is a separate project)

```<code>var gulp = require('gulp');
var sass = require('gulp-sass');

gulp.task('sass', function(){
  gulp.src('**/Masters/**/assets/scss/*.scss')
  .pipe(sass({
    outputStyle: 'compressed'
  }).on('error', sass.logError))
  .pipe(gulp.dest('**/Masters/**/assets/css'));
})

gulp.task('sass:watch', function () {
  gulp.watch('**/Masters/**/assets/scss/*.scss', ['sass']);
});
</code>```

I am stuck with specifying the destination path dynamically.  I want to run 1 watch command on the parent directory and then watch each child directory for changes, if there are changes compile the sass and move css file to the css directory in each project folder.

The code i have now is watching each directory as required but the destination doesn't work as expected, the command creates a directory called ** instead of using the ** as a wildcard.

Does anyone know how to dynamically specify the dest path?

答:
You need to setbase ingulp.src and dest as the current directory. This will use the input dir as the output.

Then use gulp-rename to add ../css to the directory path. This will direct the output to a cssdir that is a sibling to the input dir.

```<code>gulp.task('sass', function(){
  gulp.src('**/Masters/**/assets/scss/*.scss', {base: "./"})
  .pipe(sass({
    outputStyle: 'compressed'
  }).on('error', sass.logError))

  .pipe(rename(function (path) {
    path.dirname += "/../css";
  }))

  .pipe(gulp.dest('./'));
})
</code>```

Body:
I have a gulp watch command on my SASS (SCSS) files in many directories (each directory is a separate project)

var gulp = require('gulp');
var sass = require('gulp-sass');

gulp.task('sass', function(){
  gulp.src('**/Masters/**/assets/scss/*.scss')
  .pipe(sass({
    outputStyle: 'compressed'
  }).on('error', sass.logError))
  .pipe(gulp.dest('**/Masters/**/assets/css'));
})

gulp.task('sass:watch', function () {
  gulp.watch('**/Masters/**/assets/scss/*.scss', ['sass']);
});

I am stuck with specifying the destination path dynamically.  I want to run 1 watch command on the parent directory and then watch each child directory for changes, if there are changes compile the sass and move css file to the css directory in each project folder.

The code i have now is watching each directory as required but the destination doesn't work as expected, the command creates a directory called ** instead of using the ** as a wildcard.

Does anyone know how to dynamically specify the dest path?

Body:
You need to setbase ingulp.src and dest as the current directory. This will use the input dir as the output.

Then use gulp-rename to add ../css to the directory path. This will direct the output to a cssdir that is a sibling to the input dir.

gulp.task('sass', function(){
  gulp.src('**/Masters/**/assets/scss/*.scss', {base: "./"})
  .pipe(sass({
    outputStyle: 'compressed'
  }).on('error', sass.logError))

  .pipe(rename(function (path) {
    path.dirname += "/../css";
  }))

  .pipe(gulp.dest('./'));
})


问:
Global variable (Class)
I've made a really simple class,

user.class.js

```<code>'use strict';

class User {

constructor(id) {
    this.id = id;
}

getUserId() {
    return this.id;
}

}
</code>```

and in my main controller, when someone logs in, I want to create a new instance of that class like this

```<code>const user = new User(2);
</code>```

but how can I access this user from another controller?

Thank you

答: For share variables in AngularJS between Controllers, you should to use services</p>

Title: Global variable (Class)

Body:
I've made a really simple class,

user.class.js

'use strict';

class User {

constructor(id) {
    this.id = id;
}

getUserId() {
    return this.id;
}

}

and in my main controller, when someone logs in, I want to create a new instance of that class like this

const user = new User(2);

but how can I access this user from another controller?

Thank you


问:
Abort NSUrlConnection during his "connecting" state
First of all, I don't think that this question already exists, but I agree there is similar posts, please keep reading.

My question is: how abort a NSUrlConnection in his "is connecting" state? I mean, after the connection is made, we can use NSUrlConnection cancel method to cancel requests. But how abort it in "connecting" state, before it reaches the timeout when the server doesn't provide a response (before receiving any delegate calls)?

Thanks for your time!

EDIT

Should I use NSURLSessionTask instead of NSUrlConnection to do that (with its method cancel)?

EDIT 2 - code sample

```<code>NSURLConnection* m_connection;
m_connection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:NO];
if(m_connection){
    [m_connection start];

    m_timer = [NSTimer scheduledTimerWithTimeInterval: FLT_MAX
                                               target: self selector: @selector(doNothing:)
                                             userInfo: nil repeats:YES];
    m_runLoop = [NSRunLoop currentRunLoop];
    [m_runLoop addTimer:m_timer forMode:NSDefaultRunLoopMode];
    while (m_bRunLoop && [m_runLoop runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]]);

    [m_connection cancel];
}
</code>```

I use my connection to stream data. As you can see, for now I abort my connection setting m_bRunLoop to false and it's ok. But my question is : how abort my connection before the server send an response, without wait for the entire timeout?

答:
You can still call [NSURLConnection cancel] to cancel connection and have no further delegate calls. Remember that you have to create a new connection object if you want to reconnect. From your question I deduce rather that you have a problem how to make this cancel call before receiving any delegate calls, is that the case?

Also, consider using NSURLSession API with data tasks as this is probably better way to handle networking in most cases.

EDIT (as you added code):

First of all, note that adding a timer to your run loop doesn't change anything in here as NSTimer is not considered as input source for the run loop (if you really "do nothing").

Second - if you set m_bRunLoop to false you do it somewhere, though you didn't provide the code - but this will be the place to cancel your connection, so let's name this place "cancelConnection" method.

Modify your code as follows:

```<code>m_connection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:NO];
if(m_connection){
    yourConnectionThread = [NSThread currentThread]; // store your thread in instance variable
    [m_connection start];

    m_timer = [NSTimer scheduledTimerWithTimeInterval: FLT_MAX
                                               target: self selector: @selector(doNothing:)
                                             userInfo: nil repeats:YES];
    m_runLoop = [NSRunLoop currentRunLoop];
    [m_runLoop addTimer:m_timer forMode:NSDefaultRunLoopMode];

}
</code>```

and implement method where you cancel connection, remember that you need to call cancel on a thread on which you started connection:

```<code>- (void)cancelConnection {
    //m_bRunLoop = false <- this was before here
    [m_connection performSelector:@selector(cancel) onThread:yourConnectionThread withObject:nil waitUntilDone:YES];

}
</code>```

Last, but rather as a comment - remember that NSRunLoop is not thread safe and you should not call it's methods from different threads.

Body:
First of all, I don't think that this question already exists, but I agree there is similar posts, please keep reading.

My question is: how abort a NSUrlConnection in his "is connecting" state? I mean, after the connection is made, we can use NSUrlConnection cancel method to cancel requests. But how abort it in "connecting" state, before it reaches the timeout when the server doesn't provide a response (before receiving any delegate calls)?

Thanks for your time!

EDIT

Should I use NSURLSessionTask instead of NSUrlConnection to do that (with its method cancel)?

EDIT 2 - code sample

NSURLConnection* m_connection;
m_connection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:NO];
if(m_connection){
    [m_connection start];

    m_timer = [NSTimer scheduledTimerWithTimeInterval: FLT_MAX
                                               target: self selector: @selector(doNothing:)
                                             userInfo: nil repeats:YES];
    m_runLoop = [NSRunLoop currentRunLoop];
    [m_runLoop addTimer:m_timer forMode:NSDefaultRunLoopMode];
    while (m_bRunLoop && [m_runLoop runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]]);

    [m_connection cancel];
}

I use my connection to stream data. As you can see, for now I abort my connection setting m_bRunLoop to false and it's ok. But my question is : how abort my connection before the server send an response, without wait for the entire timeout?

Body:
You can still call [NSURLConnection cancel] to cancel connection and have no further delegate calls. Remember that you have to create a new connection object if you want to reconnect. From your question I deduce rather that you have a problem how to make this cancel call before receiving any delegate calls, is that the case?

Also, consider using NSURLSession API with data tasks as this is probably better way to handle networking in most cases.

EDIT (as you added code):

First of all, note that adding a timer to your run loop doesn't change anything in here as NSTimer is not considered as input source for the run loop (if you really "do nothing").

Second - if you set m_bRunLoop to false you do it somewhere, though you didn't provide the code - but this will be the place to cancel your connection, so let's name this place "cancelConnection" method.

Modify your code as follows:

m_connection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:NO];
if(m_connection){
    yourConnectionThread = [NSThread currentThread]; // store your thread in instance variable
    [m_connection start];

    m_timer = [NSTimer scheduledTimerWithTimeInterval: FLT_MAX
                                               target: self selector: @selector(doNothing:)
                                             userInfo: nil repeats:YES];
    m_runLoop = [NSRunLoop currentRunLoop];
    [m_runLoop addTimer:m_timer forMode:NSDefaultRunLoopMode];

}

and implement method where you cancel connection, remember that you need to call cancel on a thread on which you started connection:

- (void)cancelConnection {
    //m_bRunLoop = false <- this was before here
    [m_connection performSelector:@selector(cancel) onThread:yourConnectionThread withObject:nil waitUntilDone:YES];

}

Last, but rather as a comment - remember that NSRunLoop is not thread safe and you should not call it's methods from different threads.


答:
Use the following approach:</p>

```<code>$result = [];
foreach ($order->items as $item) {
    if (isset($result[$item['change']])) {
        // check if nested array is a single item(not multidimensional)
        if (isset($result[$item['change']]['change'])) {
            $result[$item['change']] = [$result[$item['change']], $item];
        } else {
            $result[$item['change']][] = $item;
        }
    } else {
        $result[$item['change']] = $item;
    }
}

$result = array_values($result);
</code>```

Title: PHP compare element values and push to array

Body:
I need to compare elements in array which have same elment value ex. $array[0]['change'] == $array[1]['change'] and if it true than make array push.

I have array like this

[
    (int) 0 => [
        'id' => (int) 2,
        'uuid' => 'c876e544-eca5-4ce1-8563-ed48ac74ebc2',
        'change' => 'c876e544-eca5-4ce1-8563-ed48ac74ebc2',
        'company_id' => (int) 18
    ],
    (int) 1 => [
        'id' => (int) 3,
        'uuid' => 'c3f388bc-9efb-4c72-b50e-3b6a9075d919',
        'change' => 'c876e544-eca5-4ce1-8563-ed48ac74ebc2',
        'company_id' => (int) 11
    ],
    (int) 2 => [
        'id' => (int) 4,
        'uuid' => 'fa37e5a4-3b5a-4f7d-915e-4807caa5949e',
        'change' => 'fa37e5a4-3b5a-4f7d-915e-4807caa5949e',
        'company_id' => (int) 17
    ],
    (int) 3 => [
        'id' => (int) 5,
        'uuid' => '52732822-11a9-4c00-8685-2493b88983f8',
        'change' => 'fa37e5a4-3b5a-4f7d-915e-4807caa5949e',
        'company_id' => (int) 19
    ],
    (int) 4 => [
        'id' => (int) 6,
        'uuid' => '9a356688-d08b-42ee-b26d-19d76bf6543b',
        'change' => '9a356688-d08b-42ee-b26d-19d76bf6543b',
        'company_id' => (int) 10
    ],
    (int) 5 => [
        'id' => (int) 7,
        'uuid' => '8dbe1a81-d722-4261-9b13-ef0b68cbb759',
        'change' => '8a356688-d08b-42ee-b26d-19d76bf6543b',
        'company_id' => (int) 18
    ],
    (int) 6 => [
        'id' => (int) 8,
        'uuid' => '701a896a-7d19-4cdd-80a4-f9ca7042945b',
        'change' => '701a896a-7d19-4cdd-80a4-f9ca7042945b',
        'company_id' => (int) 19
    ],
    (int) 7 => [
        'id' => (int) 9,
        'uuid' => '64e146bf-5d76-483f-992c-274cde1202ce',
        'change' => '601a896a-7d19-4cdd-80a4-f9ca7042945b',
        'company_id' => (int) 20
    ]
]

I need to get result like this

[
    (int) 0 => [
        (int) 0 => [
            'id' => (int) 2,
            'uuid' => 'c876e544-eca5-4ce1-8563-ed48ac74ebc2',
            'change' => 'c876e544-eca5-4ce1-8563-ed48ac74ebc2',
            'company_id' => (int) 18
        ],
        (int) 1 => [
            'id' => (int) 3,
            'uuid' => 'c3f388bc-9efb-4c72-b50e-3b6a9075d919',
            'change' => 'c876e544-eca5-4ce1-8563-ed48ac74ebc2',
            'company_id' => (int) 18
        ],
    ],
    (int) 1 => [
        (int) 0 => [
            'id' => (int) 4,
            'uuid' => 'fa37e5a4-3b5a-4f7d-915e-4807caa5949e',
            'change' => 'fa37e5a4-3b5a-4f7d-915e-4807caa5949e',
            'company_id' => (int) 18
        ],
        (int) 1 => [
            'id' => (int) 5,
            'uuid' => '52732822-11a9-4c00-8685-2493b88983f8',
            'change' => 'fa37e5a4-3b5a-4f7d-915e-4807caa5949e',
            'company_id' => (int) 18
        ],
    ],
    (int) 2 => [
        'id' => (int) 6,
        'uuid' => '9a356688-d08b-42ee-b26d-19d76bf6543b',
        'change' => '9a356688-d08b-42ee-b26d-19d76bf6543b',
        'company_id' => (int) 18
    ],
    (int) 3 => [
        'id' => (int) 7,
        'uuid' => '8dbe1a81-d722-4261-9b13-ef0b68cbb759',
        'change' => '8a356688-d08b-42ee-b26d-19d76bf6543b',
        'company_id' => (int) 18
    ],
    .
    .
    .
]

I have tried to make 2 arrays one with same values and another with different values, than make merge but the result is not as I want... and I hope so that there is "nicer" solution (maybe more readable logic).

    $exchange_array = [];
    $item_array = [];
    foreach ($order->items as $item) {
      foreach ($order->items as $exchange) {
        if (
          isset($item->change) && isset($exchange->change) &&
          $item->change == $exchange->change &&
          $item->id != $exchange->id
        ) {
          $exchange_array[] = $exchange;
        }
        if (
          !isset($item->change) && !isset($exchange->change) &&
          $item->id != $exchange->id
        ) {
          $item_array[] = $exchange;
        }

      }
    }

    $item = array_merge($exchange_array,$item_array);

Thank you!

Body:
Use the following approach:

$result = [];
foreach ($order->items as $item) {
    if (isset($result[$item['change']])) {
        // check if nested array is a single item(not multidimensional)
        if (isset($result[$item['change']]['change'])) {
            $result[$item['change']] = [$result[$item['change']], $item];
        } else {
            $result[$item['change']][] = $item;
        }
    } else {
        $result[$item['change']] = $item;
    }
}

$result = array_values($result);


问:
When to return vector iterator instead of vector?
Let's say we have a function 1 :

```<code>vector<T>::iterator GetSomething()
{
 vector<T> vec;

 // Update vec with something...

 return vec.begin();
}
</code>```

And another function 2:

```<code>vector<T> GetSomething()
{
 vector<T> vec;

 // Update vec with something...

 return vec;
}
</code>```

In what situations would we prefer function 1 ?
Also, what would be the lifetime of that vector object ?
How would we know if the iterator is pointing to empty vector ? Probably need to pass pair of iterators to determine begin / end.

答:
The lifetime of vector, just like all other automatic variables ends with the scope of the block it was declared in.

As such, if you return the iterator, it will point to freed memory and do all kinds of funny things like crash your program.

If you return the vector itself, it is copied with all of its content, but the original vector still 'dies' at the end of the block.

Body:
Let's say we have a function 1 :

vector<T>::iterator GetSomething()
{
 vector<T> vec;

 // Update vec with something...

 return vec.begin();
}

And another function 2:

vector<T> GetSomething()
{
 vector<T> vec;

 // Update vec with something...

 return vec;
}

In what situations would we prefer function 1 ?
Also, what would be the lifetime of that vector object ?
How would we know if the iterator is pointing to empty vector ? Probably need to pass pair of iterators to determine begin / end.


问:
Resolving variables in XSLT
I'm having problems with resolving variables in XSLT. I have a working XSL file with fixed values that I now want to make dynamic (the variale declarations will be move outside the XSL-file once it works). My current problem is to use variable $beginning in the starts-with function. This is the way all the googling has lead me to believe it should look, but it will not compile. It works how I use it in the substring-after function. How should this be done?</p>

```<code><?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes"/>

<xsl:variable name="oldRoot" select="'top'" />
<xsl:variable name="beginning" select="concat('$.',$oldRoot)" />
<xsl:variable name="newRoot" select="'newRoot'" />

    <xsl:template match="node()|@*">
        <xsl:copy>
            <xsl:apply-templates select="node()|@*"/>
        </xsl:copy>
    </xsl:template>

<xsl:template match="bind/@ref[starts-with(., $beginning)]">
    <xsl:attribute name="ref">
        <xsl:text>$.newRoot.</xsl:text><xsl:value-of select="$oldRoot"></xsl:value-of>
        <xsl:value-of select="substring-after(., $beginning)" />
    </xsl:attribute>
</xsl:template>
</xsl:stylesheet>
</code>```

答:
In XSLT 1.0 it is considered an error for a template match expression to contain a variable (See https://www.w3.org/TR/xslt#section-Defining-Template-Rules), so this line is failing

```<code><xsl:template match="bind/@ref[starts-with(., $beginning)]">
</code>```

(I believe some processors may allow it, but if they were following the spec, they shouldn't. It is allowed in XSLT 2.0 though).

What you can do is move the condition inside the template, and handle it with an xsl:choose

Try this XSLT

```<code><xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes"/>

<xsl:variable name="oldRoot" select="'top'" />
<xsl:variable name="beginning" select="concat('$.',$oldRoot)" />
<xsl:variable name="newRoot" select="'newRoot'" />

<xsl:template match="node()|@*">
    <xsl:copy>
        <xsl:apply-templates select="node()|@*"/>
    </xsl:copy>
</xsl:template>

<xsl:template match="bind/@ref">
    <xsl:choose>
        <xsl:when test="starts-with(., $beginning)">
            <xsl:attribute name="ref">
                <xsl:text>$.newRoot.</xsl:text><xsl:value-of select="$oldRoot"></xsl:value-of>
                <xsl:value-of select="substring-after(., $beginning)" />
            </xsl:attribute>
        </xsl:when>
        <xsl:otherwise>
            <xsl:copy-of select="." />
        </xsl:otherwise>
    </xsl:choose>
</xsl:template>
</xsl:stylesheet>
</code>```

Title: Resolving variables in XSLT

Body:
I'm having problems with resolving variables in XSLT. I have a working XSL file with fixed values that I now want to make dynamic (the variale declarations will be move outside the XSL-file once it works). My current problem is to use variable $beginning in the starts-with function. This is the way all the googling has lead me to believe it should look, but it will not compile. It works how I use it in the substring-after function. How should this be done?

<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes"/>

<xsl:variable name="oldRoot" select="'top'" />
<xsl:variable name="beginning" select="concat('$.',$oldRoot)" />
<xsl:variable name="newRoot" select="'newRoot'" />

    <xsl:template match="node()|@*">
        <xsl:copy>
            <xsl:apply-templates select="node()|@*"/>
        </xsl:copy>
    </xsl:template>

<xsl:template match="bind/@ref[starts-with(., $beginning)]">
    <xsl:attribute name="ref">
        <xsl:text>$.newRoot.</xsl:text><xsl:value-of select="$oldRoot"></xsl:value-of>
        <xsl:value-of select="substring-after(., $beginning)" />
    </xsl:attribute>
</xsl:template>
</xsl:stylesheet>

Body:
In XSLT 1.0 it is considered an error for a template match expression to contain a variable (See https://www.w3.org/TR/xslt#section-Defining-Template-Rules), so this line is failing

<xsl:template match="bind/@ref[starts-with(., $beginning)]">

(I believe some processors may allow it, but if they were following the spec, they shouldn't. It is allowed in XSLT 2.0 though).

What you can do is move the condition inside the template, and handle it with an xsl:choose

Try this XSLT

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes"/>

<xsl:variable name="oldRoot" select="'top'" />
<xsl:variable name="beginning" select="concat('$.',$oldRoot)" />
<xsl:variable name="newRoot" select="'newRoot'" />

<xsl:template match="node()|@*">
    <xsl:copy>
        <xsl:apply-templates select="node()|@*"/>
    </xsl:copy>
</xsl:template>

<xsl:template match="bind/@ref">
    <xsl:choose>
        <xsl:when test="starts-with(., $beginning)">
            <xsl:attribute name="ref">
                <xsl:text>$.newRoot.</xsl:text><xsl:value-of select="$oldRoot"></xsl:value-of>
                <xsl:value-of select="substring-after(., $beginning)" />
            </xsl:attribute>
        </xsl:when>
        <xsl:otherwise>
            <xsl:copy-of select="." />
        </xsl:otherwise>
    </xsl:choose>
</xsl:template>
</xsl:stylesheet>


问:
How to loop a function till a new mqtt message arrives?
I'm writing a mqtt app in C++ with Paho. I'm using Paho.mqtt C library that can be found here.

When I receive a message in the callback function, it calls another function to print the message. I want to be able to loop that function until a new message arrives.

```<code>bool start = false;
void loopMessage(std::string message){
   start = true;
   while(start){
       std::out << "message: " << message;
   }
}
int messageArrivedCallback(mqtt message){
   start = false;
   loopMessage(message);
}
</code>```

The code above is not working; I can receive one message and run the while loop in the loopMessage function. After that the client disconnects. I think this is because it is in blocking mode and the broker disconnects the client after the keep alive interval (I'm using MQTTClient). If I quickly send a new message before disconnection, the client doesn't receive it.

I tried to use the asynchronus client version (MQTTAsync) but it is giving me the same problem.

Any suggestions on how to do this?

答:
The Paho client will start a thread to handle the network loop and collect new messages so just remove the loopMessage function and print the message in the messageArrivedCallback.

You should not make blocking calls (which is what this infinite loop does) in the messageArrivedCallback because it has to return to allow the client to continue to receive messages.

If you want to print the message content over and over agian until a new message arrives then you need to do it on a separate thread.

Body:
I'm writing a mqtt app in C++ with Paho. I'm using Paho.mqtt C library that can be found here.

When I receive a message in the callback function, it calls another function to print the message. I want to be able to loop that function until a new message arrives.

bool start = false;
void loopMessage(std::string message){
   start = true;
   while(start){
       std::out << "message: " << message;
   }
}
int messageArrivedCallback(mqtt message){
   start = false;
   loopMessage(message);
}

The code above is not working; I can receive one message and run the while loop in the loopMessage function. After that the client disconnects. I think this is because it is in blocking mode and the broker disconnects the client after the keep alive interval (I'm using MQTTClient). If I quickly send a new message before disconnection, the client doesn't receive it.

I tried to use the asynchronus client version (MQTTAsync) but it is giving me the same problem.

Any suggestions on how to do this?