问:
Fetch data from a Core Controller in CodeIgniter
I'm working on a Social Network app.
I'm facing a problem in which I'm trying to get the name and username from a table called users in my database.
To be able to do this without accessing to all the controllers individually I had to create a Core controller with the name of MY_Controller.

Here is the problem(MY_Controller without the public $users):

```<code><?php

class MY_Controller extends CI_Controller
{

//public $users = array('username' => $this->input->post('username'));

    function __construct()
    {
        parent::__construct();

        //Get user data to make it available for both Admin and Public Controllers
        $this->load->model('User_model');
        $this->users = $this->User_model->get_list();

        //Load Menu Library
        $this->load->library('menu');
        $this->pages = $this->menu->get_pages();

        // Brand/Logo
        $this->favicon = 'https://blogpersonal.net/wp-content/uploads/2017/08/favicon-v2-150x150.png';
        $this->brand = 'Some Name';
        $this->description = 'Some Description';
        $this->credits = 'https://blogpersonal.net/';
        $this->version = '1.1.1';
    }
}

class Admin_Controller extends MY_Controller
{

    function __construct()
    {
        parent::__construct();

        if (!$this->session->is_admin) {
            redirect('admin/login');
        }

        //some code here

    }
}

class Public_Controller extends MY_Controller{
    function __construct(){
        parent::__construct();

        //some code here

    }

}

class Social_Controller extends MY_Controller
{

    function __construct()
    {
        parent::__construct();

        if (!$this->session->is_member) {
            redirect('dashboard/login');
        }

        //some code here

    }
}
</code>```

As you can see I loaded the User_model using the __construct function to make it available and use it in all controllers.

I want to fetch data in a folder called templates.
views>templates>any document but when I try to fetch it in a view like this:

```<code>    <?php if($this->users) : ?>
        <li class="dropdown user user-menu">
          <!-- Menu Toggle Button -->
          <a href="#" class="dropdown-toggle" data-toggle="dropdown">
            <!-- The user image in the navbar-->
            <img src="<?php echo base_url(); ?>assets/img/user2-160x160.jpg" class="user-image" alt="User Image">
            <!-- hidden-xs hides the username on small devices so only the image appears. -->
            <span class="hidden-xs"><?php echo $this->users['username']; ?></span>
          </a>

        </li>
    <?php endif; ?>
</code>```

THIS IS THE OLD ERROR. it shows me an error. Am I doing something wrong? Can somebody explain me how to fix it. This is the first time in which I'm unable to fetch data.

This is the result that I get:

A PHP Error was encountered

Severity: Notice

Message: Undefined variable: users

Filename: Templates/public.php

Line Number: 161

Backtrace:

File:
  C:\xampp\htdocs\codeigniter\application\views\Templates\public.php
  Line: 161 Function: _error_handler

File: C:\xampp\htdocs\codeigniter\application\libraries\Template.php
  Line: 34 Function: view

File: C:\xampp\htdocs\codeigniter\application\controllers\Pages.php
  Line: 12 Function: load

File: C:\xampp\htdocs\codeigniter\index.php Line: 315 Function:
  require_once

Here is my model(User_model) in case you might need it:

```<code><?php

class User_model extends CI_MODEL
{

    function __construct()
    {
        parent::__construct();
        $this->table = 'users';
    }

    public function get_list()
    {
        $query = $this->db->get($this->table);
        return $query->result();
    }

    public function get($id)
    {
        $this->db->where('id', $id);
        $query = $this->db->get($this->table);
        return $query->row();
    }

    public function add($data)
    {
        $this->db->insert($this->table, $data);
    }

    public function update($id, $data)
    {
        $this->db->where('id', $id);
        $this->db->update($this->table, $data);
    }

    public function delete($id)
    {
        $this->db->where('id', $id);
        $this->db->delete($this->table);
    }

    public function login($username, $password)
    {
        $this->db->select('*');
        $this->db->from($this->table);
        $this->db->where('username', $username);
        $this->db->where('password', $password);
        $this->db->limit(1);

        $query = $this->db->get();

        if ($query->num_rows() == 1) {
            return $query->row()->id;
        } else {
            return false;
        }
    }
}
</code>```

Now with the changes that were suggested to me, it now shows a new error:

The New error:

A PHP Error was encountered

Severity: Notice Message:  Undefined index: username Filename:
  Templates/public.php Line Number: 168

Backtrace:

File:
  C:\xampp\htdocs\codeigniter\application\views\Templates\public.php
  Line: 168 Function: _error_handler

File: C:\xampp\htdocs\codeigniter\application\libraries\Template.php
  Line: 34 Function: view

File:
  C:\xampp\htdocs\codeigniter\application\controllers\public\Dashboard.php
  Line: 13 Function: load

File: C:\xampp\htdocs\codeigniter\index.php Line: 315 Function:
  require_once

Now if a un-comment the public $users in the Core controller(MY_Controller) ,it shows me a new error as well:

New error with public $users out of __construct function

Fatal error: Constant expression contains invalid operations in
  C:\xampp\htdocs\codeigniter\application\core\MY_Controller.php on line
  6 A PHP Error was encountered

Severity: Compile Error

Message: Constant expression contains invalid operations

Filename: core/MY_Controller.php

Line Number: 6

Backtrace:

Here is a picture in which I'm trying to get the data to:

Am I doing something wrong? thanks for helping.

Here is the view (public.php) file:

```<code><ul class="nav navbar-nav">
          <?php if(!$this->session->is_member) : ?>
          <li><?php echo anchor('public/users/login', 'Login'); ?></li>
          <li><?php echo anchor('public/users/register', 'Register'); ?></li>
          <?php else : ?>
            <!-- Messages: style can be found in dropdown.less-->
            <li class="dropdown messages-menu">
              <!-- Menu toggle button -->
              <a href="#" class="dropdown-toggle" data-toggle="dropdown">
                <i class="fa fa-envelope-o"></i>
                <span class="label label-success">4</span>
              </a>
              <ul class="dropdown-menu">
                <li class="header">You have 4 messages</li>
                <li>
                  <!-- inner menu: contains the messages -->
                  <ul class="menu">
                    <li><!-- start message -->
                      <a href="#">
                        <div class="pull-left">
                          <!-- User Image -->
                          <img src="<?php echo base_url(); ?>assets/img/user2-160x160.jpg" class="img-circle" alt="User Image">
                        </div>
                        <!-- Message title and timestamp -->
                        <h4>
                          Support Team
                          <small><i class="fa fa-clock-o"></i> 5 mins</small>
                        </h4>
                        <!-- The message -->
                        <p>Why not buy a new awesome theme?</p>
                      </a>
                    </li>
                    <!-- end message -->
                  </ul>
                  <!-- /.menu -->
                </li>
                <li class="footer"><a href="#">See All Messages</a></li>
              </ul>
            </li>
            <!-- /.messages-menu -->
            <!-- Notifications Menu -->
            <li class="dropdown notifications-menu">
              <!-- Menu toggle button -->
              <a href="#" class="dropdown-toggle" data-toggle="dropdown">
                <i class="fa fa-bell-o"></i>
                <span class="label label-warning">10</span>
              </a>
              <ul class="dropdown-menu">
                <li class="header">You have 10 notifications</li>
                <li>
                  <!-- Inner Menu: contains the notifications -->
                  <ul class="menu">
                    <li><!-- start notification -->
                      <a href="#">
                        <i class="fa fa-users text-aqua"></i> 5 new members joined today
                      </a>
                    </li>
                    <!-- end notification -->
                  </ul>
                </li>
                <li class="footer"><a href="#">View all</a></li>
              </ul>
            </li>
            <!-- Tasks Menu -->
            <li class="dropdown tasks-menu">
              <!-- Menu Toggle Button -->
              <a href="#" class="dropdown-toggle" data-toggle="dropdown">
                <i class="fa fa-flag-o"></i>
                <span class="label label-danger">9</span>
              </a>
              <ul class="dropdown-menu">
                <li class="header">You have 9 tasks</li>
                <li>
                  <!-- Inner menu: contains the tasks -->
                  <ul class="menu">
                    <li><!-- Task item -->
                      <a href="#">
                        <!-- Task title and progress text -->
                        <h3>
                          Design some buttons
                          <small class="pull-right">20%</small>
                        </h3>
                        <!-- The progress bar -->
                        <div class="progress xs">
                          <!-- Change the css width attribute to simulate progress -->
                          <div class="progress-bar progress-bar-aqua" style="width: 20%" role="progressbar" aria-valuenow="20" aria-valuemin="0" aria-valuemax="100">
                            <span class="sr-only">20% Complete</span>
                          </div>
                        </div>
                      </a>
                    </li>
                    <!-- end task item -->
                  </ul>
                </li>
                <li class="footer">
                  <a href="#">View all tasks</a>
                </li>
              </ul>
            </li>
            <!-- User Account Menu -->
            <?php if($this->users) : ?>
                <li class="dropdown user user-menu">
                  <!-- Menu Toggle Button -->
                  <a href="#" class="dropdown-toggle" data-toggle="dropdown">
                    <!-- The user image in the navbar-->
                    <img src="<?php echo base_url(); ?>assets/img/user2-160x160.jpg" class="user-image" alt="User Image">
                    <!-- hidden-xs hides the username on small devices so only the image appears. -->
                    <span class="hidden-xs"><?php echo $this->users['username']; ?></span>
                  </a>
                  <ul class="dropdown-menu">
                    <!-- The user image in the menu -->
                    <li class="user-header">
                    <img src="<?php echo base_url(); ?>assets/img/user2-160x160.jpg" class="img-circle" alt="User Image">
                      <p><?php echo $this->users['name']; ?> - Web Developer<small>Member since Nov. 2012</small></p>
                    </li>
                    <!-- Menu Body -->
                    <li class="user-body">
                      <div class="row">
                        <div class="col-xs-4 text-center">
                          <a href="#">Followers</a>
                        </div>
                        <div class="col-xs-4 text-center">
                          <a href="#">Sales</a>
                        </div>
                        <div class="col-xs-4 text-center">
                          <a href="#">Friends</a>
                        </div>
                      </div>
                      <!-- /.row -->
                    </li>
                    <!-- Menu Footer-->
                    <li class="user-footer">
                      <div class="pull-left">
                        <a href="#" class="btn btn-default btn-flat">Profile</a>
                      </div>
                      <div class="pull-right">
                        <a href="<?php echo base_url(); ?>public/users/logout" class="btn btn-default btn-flat">Sign out</a>
                      </div>
                    </li>
                  </ul>
                </li>
            <?php endif; ?>
            <li>
                <a href="#" data-toggle="control-sidebar"><i class="fa fa-gears"></i></a>
            </li>
          <?php endif; ?>
          </ul>
</code>```

答:
you currently have this.

```<code>class MY_Controller extends CI_Controller
{

function __construct()
{
    parent::__construct();

    //Get user data to make it available for both Admin and Public Controllers
    $this->load->model('User_model');
    $data['users'] = $this->User_model->get_list();
</code>```

you should use $this->data['users'] in place of $data

```<code>class MY_Controller extends CI_Controller
{

function __construct()
{
    parent::__construct();

    //Get user data to make it available for both Admin and Public Controllers
    $this->load->model('User_model');
    $this->data['users'] = $this->User_model->get_list();
</code>```

when you load your view use the code below

```<code>$this->load->view('view_name',$this->data);
</code>```

it will show all your variable(in view) stored in parent classes construct function

Body:
I'm working on a Social Network app.
I'm facing a problem in which I'm trying to get the name and username from a table called users in my database.
To be able to do this without accessing to all the controllers individually I had to create a Core controller with the name of MY_Controller.

Here is the problem(MY_Controller without the public $users):

<?php

class MY_Controller extends CI_Controller
{

//public $users = array('username' => $this->input->post('username'));

    function __construct()
    {
        parent::__construct();

        //Get user data to make it available for both Admin and Public Controllers
        $this->load->model('User_model');
        $this->users = $this->User_model->get_list();

        //Load Menu Library
        $this->load->library('menu');
        $this->pages = $this->menu->get_pages();

        // Brand/Logo
        $this->favicon = 'https://blogpersonal.net/wp-content/uploads/2017/08/favicon-v2-150x150.png';
        $this->brand = 'Some Name';
        $this->description = 'Some Description';
        $this->credits = 'https://blogpersonal.net/';
        $this->version = '1.1.1';
    }
}

class Admin_Controller extends MY_Controller
{

    function __construct()
    {
        parent::__construct();

        if (!$this->session->is_admin) {
            redirect('admin/login');
        }

        //some code here

    }
}

class Public_Controller extends MY_Controller{
    function __construct(){
        parent::__construct();

        //some code here

    }

}

class Social_Controller extends MY_Controller
{

    function __construct()
    {
        parent::__construct();

        if (!$this->session->is_member) {
            redirect('dashboard/login');
        }

        //some code here

    }
}

As you can see I loaded the User_model using the __construct function to make it available and use it in all controllers.

I want to fetch data in a folder called templates.
views>templates>any document but when I try to fetch it in a view like this:

    <?php if($this->users) : ?>

            <img src="<?php echo base_url(); ?>assets/img/user2-160x160.jpg" class="user-image" alt="User Image">

            <?php echo $this->users['username']; ?>

    <?php endif; ?>

THIS IS THE OLD ERROR. it shows me an error. Am I doing something wrong? Can somebody explain me how to fix it. This is the first time in which I'm unable to fetch data.

This is the result that I get:

A PHP Error was encountered

Severity: Notice

Message: Undefined variable: users

Filename: Templates/public.php

Line Number: 161

Backtrace:

File:
  C:\xampp\htdocs\codeigniter\application\views\Templates\public.php
  Line: 161 Function: _error_handler

File: C:\xampp\htdocs\codeigniter\application\libraries\Template.php
  Line: 34 Function: view

File: C:\xampp\htdocs\codeigniter\application\controllers\Pages.php
  Line: 12 Function: load

File: C:\xampp\htdocs\codeigniter\index.php Line: 315 Function:
  require_once

Here is my model(User_model) in case you might need it:

<?php

class User_model extends CI_MODEL
{

    function __construct()
    {
        parent::__construct();
        $this->table = 'users';
    }

    public function get_list()
    {
        $query = $this->db->get($this->table);
        return $query->result();
    }

    public function get($id)
    {
        $this->db->where('id', $id);
        $query = $this->db->get($this->table);
        return $query->row();
    }

    public function add($data)
    {
        $this->db->insert($this->table, $data);
    }

    public function update($id, $data)
    {
        $this->db->where('id', $id);
        $this->db->update($this->table, $data);
    }

    public function delete($id)
    {
        $this->db->where('id', $id);
        $this->db->delete($this->table);
    }

    public function login($username, $password)
    {
        $this->db->select('*');
        $this->db->from($this->table);
        $this->db->where('username', $username);
        $this->db->where('password', $password);
        $this->db->limit(1);

        $query = $this->db->get();

        if ($query->num_rows() == 1) {
            return $query->row()->id;
        } else {
            return false;
        }
    }
}

Now with the changes that were suggested to me, it now shows a new error:

The New error:

A PHP Error was encountered

Severity: Notice Message:  Undefined index: username Filename:
  Templates/public.php Line Number: 168

Backtrace:

File:
  C:\xampp\htdocs\codeigniter\application\views\Templates\public.php
  Line: 168 Function: _error_handler

File: C:\xampp\htdocs\codeigniter\application\libraries\Template.php
  Line: 34 Function: view

File:
  C:\xampp\htdocs\codeigniter\application\controllers\public\Dashboard.php
  Line: 13 Function: load

File: C:\xampp\htdocs\codeigniter\index.php Line: 315 Function:
  require_once

Now if a un-comment the public $users in the Core controller(MY_Controller) ,it shows me a new error as well:

New error with public $users out of __construct function

Fatal error: Constant expression contains invalid operations in
  C:\xampp\htdocs\codeigniter\application\core\MY_Controller.php on line
  6 A PHP Error was encountered

Severity: Compile Error

Message: Constant expression contains invalid operations

Filename: core/MY_Controller.php

Line Number: 6

Backtrace:

Here is a picture in which I'm trying to get the data to:

Am I doing something wrong? thanks for helping.

Here is the view (public.php) file:

          <?php if(!$this->session->is_member) : ?>

<?php echo anchor('public/users/login', 'Login'); ?>

<?php echo anchor('public/users/register', 'Register'); ?>

          <?php else : ?>

                4

You have 4 messages

                          <img src="<?php echo base_url(); ?>assets/img/user2-160x160.jpg" class="img-circle" alt="User Image">

                          Support Team
                           5 mins

Why not buy a new awesome theme?

See All Messages

                10

You have 10 notifications

                         5 new members joined today

View all

                9

You have 9 tasks

                          Design some buttons
                          20%

                            20% Complete

                  View all tasks

            <?php if($this->users) : ?>

                    <img src="<?php echo base_url(); ?>assets/img/user2-160x160.jpg" class="user-image" alt="User Image">

                    <?php echo $this->users['username']; ?>

                    <img src="<?php echo base_url(); ?>assets/img/user2-160x160.jpg" class="img-circle" alt="User Image">

<?php echo $this->users['name']; ?> - Web DeveloperMember since Nov. 2012

                          Followers

                          Sales

                          Friends

                        Profile

                        <a href="<?php echo base_url(); ?>public/users/logout" class="btn btn-default btn-flat">Sign out

            <?php endif; ?>

          <?php endif; ?>

Body:
you currently have this.

class MY_Controller extends CI_Controller
{

function __construct()
{
    parent::__construct();

    //Get user data to make it available for both Admin and Public Controllers
    $this->load->model('User_model');
    $data['users'] = $this->User_model->get_list();

you should use $this->data['users'] in place of $data

class MY_Controller extends CI_Controller
{

function __construct()
{
    parent::__construct();

    //Get user data to make it available for both Admin and Public Controllers
    $this->load->model('User_model');
    $this->data['users'] = $this->User_model->get_list();

when you load your view use the code below

$this->load->view('view_name',$this->data);

it will show all your variable(in view) stored in parent classes construct function


来源: stackexchange

问:
How to identify the docker host ip to use when running a jenkins container
I have docker machine installed on windows OS and have pulled in Jenkins image from docker hub. I then run the below commands:

```<code>docker volume created myjenkins-data
docker run -p 8080:8080 -p 50000:50000 -v myjenkins-data:/var/jenkins_home jenkins
</code>```

I received the admin key for Jenkins in the logs. I've confirmed that my container is still running status:

```<code>$ docker ps -a
CONTAINER ID        IMAGE               COMMAND                  CREATED              STATUS              PORTS                                              NAMES
2854c7d83879        jenkins             "/bin/tini -- /usr..."   About a minute ago   Up About a minute   0.0.0.0:8080->8080/tcp, 0.0.0.0:50000->50000/tcp   quizzical_cray
</code>```

Now, I need to log into 8080 port to view the Jenkins web app. But I do not know which host ip to use. I identified the docker host ip with the command "docker-machine ip" and got the ip address: 192.168.99.100. But using 192.168.99.100:8080 did not bring up Jenkins app. I also tried using docker inspect to get the container's ip, but port 8080 didn't work on those ips as well. Which ip address do i use to see the Jenkins app that is running in the container?

答:
First, double-check if http://localhost:8080 is not enough.

Hyper-V (through vpnkit, if you are using Docker for Windows) should have done the port-forwarding for you.

If you are using the legacy docker toolbox (VirtualBox), then you need port-forwarding (issue 4115).

ContentLicense: CC BY-SA 3.0

Body:
I have docker machine installed on windows OS and have pulled in Jenkins image from docker hub. I then run the below commands:

docker volume created myjenkins-data
docker run -p 8080:8080 -p 50000:50000 -v myjenkins-data:/var/jenkins_home jenkins

I received the admin key for Jenkins in the logs. I've confirmed that my container is still running status:

$ docker ps -a
CONTAINER ID        IMAGE               COMMAND                  CREATED              STATUS              PORTS                                              NAMES
2854c7d83879        jenkins             "/bin/tini -- /usr..."   About a minute ago   Up About a minute   0.0.0.0:8080->8080/tcp, 0.0.0.0:50000->50000/tcp   quizzical_cray

Now, I need to log into 8080 port to view the Jenkins web app. But I do not know which host ip to use. I identified the docker host ip with the command "docker-machine ip" and got the ip address: 192.168.99.100. But using 192.168.99.100:8080 did not bring up Jenkins app. I also tried using docker inspect to get the container's ip, but port 8080 didn't work on those ips as well. Which ip address do i use to see the Jenkins app that is running in the container?


问:
Shadow rate on UITableViewCell contenview increasing while scrolling
In my app, I'm using dynamic height cells using auto layout. So for creating cardview effect I've to use tableview willdisplaycell method. It only add shadow only once to cell. But I don't know why shadow increasing while scrolling.

Here's my code

```<code>func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        //setup card view style on cell
        if !cellArray.contains(indexPath.row) {
            cell.contentView.backgroundColor = UIColor.clear
            let whiteRoundedView : UIView = UIView(frame: CGRect(x: 5.0, y: 5.0, width: cell.contentView.frame.size.width-10, height: cell.contentView.frame.size.height-10))
            whiteRoundedView.layer.backgroundColor = UIColor.white.cgColor
            whiteRoundedView.layer.masksToBounds = false
            whiteRoundedView.layer.cornerRadius = 5.0
            whiteRoundedView.layer.shadowOffset = CGSize(width: -1, height: 1)
            whiteRoundedView.layer.shadowOpacity = 0.5
            cell.contentView.addSubview(whiteRoundedView)
            cell.contentView.sendSubview(toBack: whiteRoundedView)
            cellArray.add(indexPath.row)
        }
    }
</code>```

答:
You can add your code here

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

    var cell = tableView.dequeueReusableCell(withIdentifier: <idenitfier>, for: indexPath) as? JobListTableViewCell

    if cell == nil {

        //Initialization and setting of shadow

    }
    return cell
}
</code>```

Hope this helps

Body:
In my app, I'm using dynamic height cells using auto layout. So for creating cardview effect I've to use tableview willdisplaycell method. It only add shadow only once to cell. But I don't know why shadow increasing while scrolling.

Here's my code

func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        //setup card view style on cell
        if !cellArray.contains(indexPath.row) {
            cell.contentView.backgroundColor = UIColor.clear
            let whiteRoundedView : UIView = UIView(frame: CGRect(x: 5.0, y: 5.0, width: cell.contentView.frame.size.width-10, height: cell.contentView.frame.size.height-10))
            whiteRoundedView.layer.backgroundColor = UIColor.white.cgColor
            whiteRoundedView.layer.masksToBounds = false
            whiteRoundedView.layer.cornerRadius = 5.0
            whiteRoundedView.layer.shadowOffset = CGSize(width: -1, height: 1)
            whiteRoundedView.layer.shadowOpacity = 0.5
            cell.contentView.addSubview(whiteRoundedView)
            cell.contentView.sendSubview(toBack: whiteRoundedView)
            cellArray.add(indexPath.row)
        }
    }

Body:
You can add your code here

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

    var cell = tableView.dequeueReusableCell(withIdentifier: <idenitfier>, for: indexPath) as? JobListTableViewCell

    if cell == nil {

        //Initialization and setting of shadow

    }
    return cell
}

Hope this helps


答:
this piece of line is the causing the issue.

cell.contentView.addSubview(whiteRoundedView)

whenever willDisplayCell gets called, you will be adding the view everytime. That is the reason shadow is getting increased while scrolling. The solution is,

```<code>1. check the cell content view if the view is already added or not. If not, then add the view. use view tag to do it.

2. otherwise, create a shadow view and initialize the specific things in the -(void)awakeFromNib, which will get called only once.
</code>```

but personally, i prefer option 2, which will isolate your view render logic from view controller or cell.

add the below code to your custom cell class. In this case, i have given leading-trialing-top-bottom constraints as 15-15-15-15. If you wish you can set it to 0. but make sure that it should in sync with the background constraints.

```<code>override func awakeFromNib() {
    super.awakeFromNib()
    contentView.backgroundColor = UIColor.clear
    let whiteRoundedView : UIView = UIView(frame: CGRect(x: 5.0, y: 5.0, width: contentView.frame.size.width-10, height: contentView.frame.size.height-10))
    whiteRoundedView.layer.backgroundColor = UIColor.white.cgColor
    whiteRoundedView.layer.masksToBounds = false
    whiteRoundedView.layer.cornerRadius = 5.0
    whiteRoundedView.layer.shadowOffset = CGSize(width: -1, height: 1)
    whiteRoundedView.layer.shadowOpacity = 0.5
    whiteRoundedView.tag = shadowTag
    whiteRoundedView.translatesAutoresizingMaskIntoConstraints=false
    contentView.addSubview(whiteRoundedView)
    contentView.sendSubview(toBack: whiteRoundedView)
    let leading = NSLayoutConstraint(item: whiteRoundedView,
                                     attribute: .leading,
                                     relatedBy: .equal,
                                     toItem: contentView,
                                     attribute: .leading,
                                     multiplier: 1.0,
                                     constant: 15.0)
    let trailing = NSLayoutConstraint(item: whiteRoundedView,
                                      attribute: .trailing,
                                      relatedBy: .equal,
                                      toItem: contentView,
                                      attribute: .trailing,
                                      multiplier: 1.0,
                                      constant: -15.0)

    let top = NSLayoutConstraint(item: whiteRoundedView,
                                 attribute: .top,
                                 relatedBy: .equal,
                                 toItem: contentView,
                                 attribute: .top,
                                 multiplier: 1.0,
                                 constant: 15.0)

    let bottom = NSLayoutConstraint(item: whiteRoundedView,
                                    attribute: .bottom,
                                    relatedBy: .equal,
                                    toItem: contentView,
                                    attribute: .bottom,
                                    multiplier: 1.0,
                                    constant: -15.0)

    contentView.addConstraint(leading)
    contentView.addConstraint(trailing)
    contentView.addConstraint(top)
    contentView.addConstraint(bottom)
}
</code>```

Ref screenshot :

Title: Shadow rate on UITableViewCell contenview increasing while scrolling

Body:
this piece of line is the causing the issue.

cell.contentView.addSubview(whiteRoundedView)

whenever willDisplayCell gets called, you will be adding the view everytime. That is the reason shadow is getting increased while scrolling. The solution is,

1. check the cell content view if the view is already added or not. If not, then add the view. use view tag to do it.

2. otherwise, create a shadow view and initialize the specific things in the -(void)awakeFromNib, which will get called only once.

but personally, i prefer option 2, which will isolate your view render logic from view controller or cell.

add the below code to your custom cell class. In this case, i have given leading-trialing-top-bottom constraints as 15-15-15-15. If you wish you can set it to 0. but make sure that it should in sync with the background constraints.

override func awakeFromNib() {
    super.awakeFromNib()
    contentView.backgroundColor = UIColor.clear
    let whiteRoundedView : UIView = UIView(frame: CGRect(x: 5.0, y: 5.0, width: contentView.frame.size.width-10, height: contentView.frame.size.height-10))
    whiteRoundedView.layer.backgroundColor = UIColor.white.cgColor
    whiteRoundedView.layer.masksToBounds = false
    whiteRoundedView.layer.cornerRadius = 5.0
    whiteRoundedView.layer.shadowOffset = CGSize(width: -1, height: 1)
    whiteRoundedView.layer.shadowOpacity = 0.5
    whiteRoundedView.tag = shadowTag
    whiteRoundedView.translatesAutoresizingMaskIntoConstraints=false
    contentView.addSubview(whiteRoundedView)
    contentView.sendSubview(toBack: whiteRoundedView)
    let leading = NSLayoutConstraint(item: whiteRoundedView,
                                     attribute: .leading,
                                     relatedBy: .equal,
                                     toItem: contentView,
                                     attribute: .leading,
                                     multiplier: 1.0,
                                     constant: 15.0)
    let trailing = NSLayoutConstraint(item: whiteRoundedView,
                                      attribute: .trailing,
                                      relatedBy: .equal,
                                      toItem: contentView,
                                      attribute: .trailing,
                                      multiplier: 1.0,
                                      constant: -15.0)

    let top = NSLayoutConstraint(item: whiteRoundedView,
                                 attribute: .top,
                                 relatedBy: .equal,
                                 toItem: contentView,
                                 attribute: .top,
                                 multiplier: 1.0,
                                 constant: 15.0)

    let bottom = NSLayoutConstraint(item: whiteRoundedView,
                                    attribute: .bottom,
                                    relatedBy: .equal,
                                    toItem: contentView,
                                    attribute: .bottom,
                                    multiplier: 1.0,
                                    constant: -15.0)

    contentView.addConstraint(leading)
    contentView.addConstraint(trailing)
    contentView.addConstraint(top)
    contentView.addConstraint(bottom)
}

Ref screenshot :


问:
loop in J language ^:
Assume that I have 10 random points on 2D graph, and each point is connected with a spring. So every points is converging to the center of the force for every iterations.

What I am trying to make is a loop that adds a random vector to an existing vector set after each iteration.

So it starts from

```<code>v=: <(? 10 2 $ 20)   NB. 10 random vectors
n=: <(? 1 2 $ 20)    NB. new random vector
force v              NB. force function moves the vectors toward to the center
add n                NB. add n into v, then #v = 11
force v
add n
force v
add n
...
</code>```

I'm still working on the force function which seems like to be not hard, but I got really stuck on the add section. Can anyone help me on this?
My final goal is to make a loop repeating add force section like 100 times

Thank you!

Title: loop in J language ^:

Body:
Assume that I have 10 random points on 2D graph, and each point is connected with a spring. So every points is converging to the center of the force for every iterations.

What I am trying to make is a loop that adds a random vector to an existing vector set after each iteration.

So it starts from

v=: <(? 10 2 $ 20)   NB. 10 random vectors
n=: <(? 1 2 $ 20)    NB. new random vector
force v              NB. force function moves the vectors toward to the center
add n                NB. add n into v, then #v = 11
force v
add n
force v
add n
...

I'm still working on the force function which seems like to be not hard, but I got really stuck on the add section. Can anyone help me on this?
My final goal is to make a loop repeating add force section like 100 times

Thank you!

Body:
It looks as if what you want to do is to unbox v and n then , (Append). The way to do this is to use each=: &.> which uses &. (Under) and > (Open).

, each  Opens, performs the Append operation, then closes.

   v=.<(? 10 2 $ 20)
   v
+-----+
| 9 11|
| 1  4|
| 8  3|
| 3 12|
| 5  4|
| 7 11|
|10 11|
| 9 10|
| 0  8|
| 6 16|
+-----+
   n=: <(? 1 2 $ 20)
   n
+----+
|13 8|
+----+
   n , each v
+-----+
|13  8|
| 9 11|
| 1  4|
| 8  3|
| 3 12|
| 5  4|
| 7 11|
|10 11|
| 9 10|
| 0  8|
| 6 16|
+-----+
   each
&.>


问:
Load configurable variables into a bat file
I have the below configuration file

```<code>[CLIENT1]
drive='C:/CLIENT1'
client='1'
[CLIENT2]
drive='C:/CLIENT2'
client='2'
</code>```

I am trying to pass in a parameter to my bat file from the command line that will  either be CLIENT1 or CLIENT2. The aim is to load in the drive and clientid into the bat script to change the current working directory.

Something like this

```<code>@ECHO OFF

set param=CLIENT1

for /f "delims=" %%x in (config.txt) do (
   IF "%%x" == "[%PARAM%]"
      (
         # Load the next two lines of code to set the variables
         set var1=line1
         set var2=line2
      )
)

echo var1 var2
pause
</code>```

I am having trouble coming up with the correct way to load in the variables after identifying I have found the record the bat file has been run for.

Any advice?

答:
@ECHO OFF
setlocal
SET "sourcedir=U:\sourcedir"
SET "filename1=%sourcedir%\q47707478.txt"
FOR %%a IN (drive client assign) DO SET "%%a="
FOR /f "usebackqtokens=1*delims==" %%a IN ("%filename1%") DO (
 IF /i "%%a"=="[%1]" (
  SET "assign=Y"
 ) ELSE IF DEFINED assign (
  FOR %%v IN (drive client) DO IF /i "%%a"=="%%v" SET "%%a=%%b"
  IF "%%b"=="" SET "assign="
 )
)
IF DEFINED drive SET "drive=%drive:'=%"
IF DEFINED client SET "client=%client:'=%"
endlocal&SET "drive=%drive%"&SET "client=%client%"
GOTO :EOF
```

<p>You would need to change the setting of <code>sourcedir</code> to suit your circumstances.</p>

<p>I used a file named <code>q47707478.txt</code> containing your data for my testing.</p>

<p>I simply used <code>sourcedir</code> and <code>filename1</code> to suit my testing - use a fixed name for <code>filename1</code> if you prefer.</p>

<p><code>filename1</code> only needs to be quoted if it contains separators like <kbd>Space</kbd>. If it is not quoted, remove the <code>usebackq</code> option (which tells <code>for</code> that the quoted name is a filename)</p>

<p>first establish <code>drive,client,assign</code> to <em>nothing</em> in case they already have values.</p>

<p>Then read the file, assigning the first token to <code>%%a</code> and the rest-of-line to <code>%%b</code> using <code>=</code> as delimiter.</p>

<p>If we find the target string, set <code>assign</code> to <em>a value</em> - no matter <em>what</em> value, just <em>not nothing</em></p>

<p>If the target string is not found, then if it has already been found (so <code>assign</code> is defined) then see whether <code>%%a</code> is one of the required strings. Assign if so.</p>

<p>If there is no second token (in <code>%%b</code>) then we've found the next <code>[sectionname]</code> and therefore we've finished the target section, so set <code>assign</code> to <em>nothing</em> to prevent further assignments.</p>

<p>Finally, remove the <code>'</code> characters from the assigned variables (if required).</p>

<p>Notes:</p>

<p>The <code>/i</code> in the <code>if</code> statements make the comparisons case-insensitive. remove if required.</p>

<p>The "overly complex" operation with <code>%%v</code> allows the returned list of variables to be extended easily (with matching changes in the obvious places).</p>

<p>The <code>endlocal</code> would dispose of any environment changes made by the routine since the <code>setlocal</code>, but the apparently-superfluous assignment (which <strong>must</strong> be on the same physical line) transfers the variables from the local environment to the main environment using <code>cmd</code>'s parsing characteristic.</p>

<p>If you want to return <code>id</code> from the value in <code>client</code>, simply change <code>endlocal&SE..."&SET "client=%client%"</code> to <code>endlocal&SE..."&SET "id=%client%"</code></p>

<p>If you want to return windows-standard <code>\</code> for directory-separators (<code>/</code> is a switch-indicator) then add a new line before the <code>endlocal</code> line</p>

```IF DEFINED drive SET "drive=%drive:/=\%"
```

ContentLicense: CC BY-SA 4.0

Body:
I have the below configuration file

[CLIENT1]
drive='C:/CLIENT1'
client='1'
[CLIENT2]
drive='C:/CLIENT2'
client='2'

I am trying to pass in a parameter to my bat file from the command line that will  either be CLIENT1 or CLIENT2. The aim is to load in the drive and clientid into the bat script to change the current working directory.

Something like this

@ECHO OFF

set param=CLIENT1

for /f "delims=" %%x in (config.txt) do (
   IF "%%x" == "[%PARAM%]"
      (
         # Load the next two lines of code to set the variables
         set var1=line1
         set var2=line2
      )
)

echo var1 var2
pause

I am having trouble coming up with the correct way to load in the variables after identifying I have found the record the bat file has been run for.

Any advice?

Body:
@ECHO OFF
setlocal
SET "sourcedir=U:\sourcedir"
SET "filename1=%sourcedir%\q47707478.txt"
FOR %%a IN (drive client assign) DO SET "%%a="
FOR /f "usebackqtokens=1*delims==" %%a IN ("%filename1%") DO (
 IF /i "%%a"=="[%1]" (
  SET "assign=Y"
 ) ELSE IF DEFINED assign (
  FOR %%v IN (drive client) DO IF /i "%%a"=="%%v" SET "%%a=%%b"
  IF "%%b"=="" SET "assign="
 )
)
IF DEFINED drive SET "drive=%drive:'=%"
IF DEFINED client SET "client=%client:'=%"
endlocal&SET "drive=%drive%"&SET "client=%client%"
GOTO :EOF

You would need to change the setting of sourcedir to suit your circumstances.

I used a file named q47707478.txt containing your data for my testing.

I simply used sourcedir and filename1 to suit my testing - use a fixed name for filename1 if you prefer.

filename1 only needs to be quoted if it contains separators like Space. If it is not quoted, remove the usebackq option (which tells for that the quoted name is a filename)

first establish drive,client,assign to nothing in case they already have values.

Then read the file, assigning the first token to %%a and the rest-of-line to %%b using = as delimiter.

If we find the target string, set assign to a value - no matter what value, just not nothing

If the target string is not found, then if it has already been found (so assign is defined) then see whether %%a is one of the required strings. Assign if so.

If there is no second token (in %%b) then we've found the next [sectionname] and therefore we've finished the target section, so set assign to nothing to prevent further assignments.

Finally, remove the ' characters from the assigned variables (if required).

Notes:

The /i in the if statements make the comparisons case-insensitive. remove if required.

The "overly complex" operation with %%v allows the returned list of variables to be extended easily (with matching changes in the obvious places).

The endlocal would dispose of any environment changes made by the routine since the setlocal, but the apparently-superfluous assignment (which must be on the same physical line) transfers the variables from the local environment to the main environment using cmd's parsing characteristic.

If you want to return id from the value in client, simply change endlocal&SE..."&SET "client=%client%" to endlocal&SE..."&SET "id=%client%"

If you want to return windows-standard \ for directory-separators (/ is a switch-indicator) then add a new line before the endlocal line

IF DEFINED drive SET "drive=%drive:/=\%"


问:
How to divide a Certain Model into two parts in Razor View?
I am using Articulate plugin in Umbraco for Blog Style and I need to show something default inside every Articulate Post.
Here is what is happening now.

```<code><section class="post-content">
   @Model.Body
</section>
</code>```

And I need to do something below

```<code><section class="post-content">
   @Model.Body.part1
   "Something Very Important"
   @Model.Body.part2
</section>
</code>```

Thanks in advance.

答:
Create two partial views and pass the same model to both. On each view just render the part you want.

```<code><section class="post-content">
   @* the model will be passed to the partial view *@
   @Html.Partial("~/Views/Partial/PartialView1.cshtml");

   <p>Something very important here</p>

   @Html.Partial("~/Views/Partial/PartialView2.cshtml");
</section>
</code>```

Then your partial views would be something like:

PartialView1.cshtml

```<code><div>
   @Model.Body.part1
</div>
</code>```

PartialView2.cshtml

```<code><div>
   @Model.Body.part2
</div>
</code>```

You don't really need the
 but you get the point, right?

Body:
I am using Articulate plugin in Umbraco for Blog Style and I need to show something default inside every Articulate Post.
Here is what is happening now.

   @Model.Body

And I need to do something below

   @Model.Body.part1
   "Something Very Important"
   @Model.Body.part2

Thanks in advance.

Body:
Create two partial views and pass the same model to both. On each view just render the part you want.

<section class="post-content">
   @* the model will be passed to the partial view *@
   @Html.Partial("~/Views/Partial/PartialView1.cshtml");

   <p>Something very important here</p>

   @Html.Partial("~/Views/Partial/PartialView2.cshtml");
</section>

Then your partial views would be something like:

PartialView1.cshtml

<div>
   @Model.Body.part1
</div>

PartialView2.cshtml

<div>
   @Model.Body.part2
</div>

You don't really need the <div> but you get the point, right?


问:
goto vs. switch vs. your own way!! which is your choice for readability
you can notice that it may be flowchart or state machine transition

I am wondering which is the better option to implement the above flowchart of a algorithm.

I think go to is better solution.

How do you think so? I want to know your opinions.

[goto version]

```<code>main () {
    if ( condition == a )
        goto A:
    elif ( condition == b )
        B();
    elif ( condition == c )
        C();
    elif (condition == e )
        E();

    A:
    // do something

    B:
    if ( condition == c )
        // do something
        goto C;
    elif ( condition == d )
        // do somthing
        goto D;

    C:
    if ( condition == d )
        // do something
        goto D;

    D:
    if ( condition == a)
        // do something
        goto A;
    elif ( condition == e)
        // do something
        goto E;

    E:
        // do something

    return;
}
</code>```

[function call version with switch case grammar]

```<code>main () {
    switch (condition) {
        case a:
            A();
            break;
        case b:
            B();
            break;
        case c:
            C();
            break;
        case e:
            E();
            break;
    }
}

fuction A() {
    // do something

    switch (condition) {
        case b:
            B();
            break;
    }
}

function B() {
    // do something

    switch (condition) {
        case c:
            C();
            break;
        case d:
            D();
            break;
    }

}

function C() {
    // do something

    switch (condition) {
        case d:
            D();
            break;
        }

}

function D() {
    // do something

    switch (condition) {
        case a:
            A();
            break;
        case e:
            E();
            break;
    }
}

function E() {
    // do something
    return ;
}
</code>```

[add your way to implement and handle all the execution path]

答:
I write the better version compare to the my goto version
I call it 2nd verion of go to.

I think It is more better readability.

How do you think about that?

[the 2nd version using goto]

```<code>main () {
    if ( condition == a )
        goto A:
    elif ( condition == b )
        B();
    elif ( condition == c )
        C();
    elif (condition == e )
        E();

    A:
    // do something

    B:
    if ( condition == d )
        // do somthing
        goto D;

    C:
        // do something

    D:
    if ( condition == a)
        // do something
        goto A;

    E:
        // do something

    return;
}
</code>```

Body:
you can notice that it may be flowchart or state machine transition

I am wondering which is the better option to implement the above flowchart of a algorithm.

I think go to is better solution.

How do you think so? I want to know your opinions.

[goto version]

main () {
    if ( condition == a )
        goto A:
    elif ( condition == b )
        B();
    elif ( condition == c )
        C();
    elif (condition == e )
        E();

    A:
    // do something

    B:
    if ( condition == c )
        // do something
        goto C;
    elif ( condition == d )
        // do somthing
        goto D;

    C:
    if ( condition == d )
        // do something
        goto D;

    D:
    if ( condition == a)
        // do something
        goto A;
    elif ( condition == e)
        // do something
        goto E;

    E:
        // do something

    return;
}

[function call version with switch case grammar]

main () {
    switch (condition) {
        case a:
            A();
            break;
        case b:
            B();
            break;
        case c:
            C();
            break;
        case e:
            E();
            break;
    }
}

fuction A() {
    // do something

    switch (condition) {
        case b:
            B();
            break;
    }
}

function B() {
    // do something

    switch (condition) {
        case c:
            C();
            break;
        case d:
            D();
            break;
    }

}

function C() {
    // do something

    switch (condition) {
        case d:
            D();
            break;
        }

}

function D() {
    // do something

    switch (condition) {
        case a:
            A();
            break;
        case e:
            E();
            break;
    }
}

function E() {
    // do something
    return ;
}

[add your way to implement and handle all the execution path]

Body:
I write the better version compare to the my goto version
I call it 2nd verion of go to.

I think It is more better readability.

How do you think about that?

[the 2nd version using goto]

main () {
    if ( condition == a )
        goto A:
    elif ( condition == b )
        B();
    elif ( condition == c )
        C();
    elif (condition == e )
        E();

    A:
    // do something

    B:
    if ( condition == d )
        // do somthing
        goto D;

    C:
        // do something

    D:
    if ( condition == a)
        // do something
        goto A;

    E:
        // do something

    return;
}


问:
How to play video from YouTube URL like VLC?
I'm using Qt with Phonon, I'd like the program I'm writing to be able to play a YouTube video from a URL, I've tried googling it but none of the methods I found work. If you put a YouTube URL on VLC, it will play it. Can anyone please tell me how they do this?

Thanks in advance.

答: download the video (qnetworkacess) and then play it.</p>

ContentLicense: CC BY-SA 2.5


问:
Ldap connection failed in php?
HI Am trying to connect and unbind  the server and port  ldap connection using php.

Here is my code:

```<code>$hostname = 'ldaps://www.google.com';
$port = 636;
echo "ldap check";
$lp = ldap_connect($hostname,$port);
echo "servername";
echo $_SERVER['PHP_AUTH_USER'];
$username = $_SERVER['PHP_AUTH_USER'];
$password = $_SERVER['PHP_AUTH_PW'];
if ($bind = @ldap_bind($lp, $username.$hostname, $password)){
    echo "Hello";
    ldap_unbind($lp,$username,$password);
}
</code>```

Failure:

But am not connecting with the ldap connection.PLease help me to fix the code.

答:
When I read your code right, there are two issues:

The port you are giving will never be used in the ldap_connect. The docs clearly state that using the port as second argument to ldap_connect is deprecated and will only be used when you pass a servername or IP. But you are passing a URI, so that needs to include the port as well.

You are trying to bind as $username . $hostname. So you are tying to conntect 'someuser' as someuserldaps://www.google.com - I doubt that that will ever work. You probably want something like someuser@www.google.com...

Title: Ldap connection failed in php?

Body:
HI Am trying to connect and unbind  the server and port  ldap connection using php.

Here is my code:

$hostname = 'ldaps://www.google.com';
$port = 636;
echo "ldap check";
$lp = ldap_connect($hostname,$port);
echo "servername";
echo $_SERVER['PHP_AUTH_USER'];
$username = $_SERVER['PHP_AUTH_USER'];
$password = $_SERVER['PHP_AUTH_PW'];
if ($bind = @ldap_bind($lp, $username.$hostname, $password)){
    echo "Hello";
    ldap_unbind($lp,$username,$password);
}

Failure:

But am not connecting with the ldap connection.PLease help me to fix the code.


问:
How to use ServerName to rename localhost to www.domain.com in Apache 2.4?
I am trying to configure the httpd.conf to rename localhost:80/webapp to www.domain.com/webapp. The current configuration I have now is:

```<code><VirtualHost *:80>
  ServerName  www.domain.com
  ServerAlias domain.com
  ProxyPass        /webapp http://localhost:8080/webapp/
  ProxyPassReverse /webapp http://localhost:8080/webapp/
</VirtualHost>
</code>```

I used this configuration but whenever I tried to browse "www.domain.com/webapp" it goes to some other website, the normal www.domain.com website and somewhere outside the VirtualHost tag I have

```<code>ServerName localhost:80
</code>```

The Web App is a Spring MVC project using JSP, do I need to set the  documentroot to the Spring MVC project ? How do I do that ?

Do I need to buy a domain for this to work ?

How should I configure the httpd.conf to rename localhost:80/webapp to www.domain.com/webapp?

答:
Edit the configuration file /etc/hosts with nano:

```<code>sudo nano /etc/hosts
</code>```

Add the ip and domain to the /etc/hosts file. For example:

```<code>172.15.12.123 domain.com
</code>```

or

```<code>127.0.0.1 domain.com
</code>```

in case the server is running on your local machine.

Body:
I am trying to configure the httpd.conf to rename localhost:80/webapp to www.domain.com/webapp. The current configuration I have now is:

<VirtualHost *:80>
  ServerName  www.domain.com
  ServerAlias domain.com
  ProxyPass        /webapp http://localhost:8080/webapp/
  ProxyPassReverse /webapp http://localhost:8080/webapp/
</VirtualHost>

I used this configuration but whenever I tried to browse "www.domain.com/webapp" it goes to some other website, the normal www.domain.com website and somewhere outside the VirtualHost tag I have

ServerName localhost:80

The Web App is a Spring MVC project using JSP, do I need to set the  documentroot to the Spring MVC project ? How do I do that ?

Do I need to buy a domain for this to work ?

How should I configure the httpd.conf to rename localhost:80/webapp to www.domain.com/webapp?

Body:
Edit the configuration file /etc/hosts with nano:

sudo nano /etc/hosts

Add the ip and domain to the /etc/hosts file. For example:

172.15.12.123 domain.com

or

127.0.0.1 domain.com

in case the server is running on your local machine.


问:
Zendesk Nodejs API attachments using node-zendesk
I have a Nodejs app and I'm using "node-zendesk" NPM package for using Zendesk API. The official Zendesk NPM package "zendesk-node-api" is not useful and because of that i'm using "node-zendesk".
My problem is when I want to create ticket with API inclouding attachments.

This is the example of that:

```<code>client.attachments.upload(file, { filepath: 'dog.jpg' }, function () {
  // if no error
  client.tickets.create(ticket, function () {
     res.status(200).end();
  }
}
</code>```

My question is:

I need an example of "file" object. What should be inside that?

And for "filepath", Should I put the image full filepath on my server starting by 'http....' ? Should I use Multer? Could you please give me a clear example?

答:
have you tried the example provided in the library here - https://github.com/blakmatrix/node-zendesk/blob/master/examples/upload-attachment.js#L13-L24</p>

```<code>client.attachments.upload(path.resolve(
  './examples/busey.gif'),
  {
    filename: 'busey.gif'
  },
  function (err, req, result) {
    if (err) {
      console.log(err);
      return;
    }
    console.log(JSON.stringify(result, null, 2, true));
});
</code>```

<p>'filepath' looks like it's relative to the file or absolute file path, up to you.  can start with file:// or whatever your local environment requires.  Probably not https because that's accessing across the web and not locally.  </p>

Body:
I have a Nodejs app and I'm using "node-zendesk" NPM package for using Zendesk API. The official Zendesk NPM package "zendesk-node-api" is not useful and because of that i'm using "node-zendesk".
My problem is when I want to create ticket with API inclouding attachments.

This is the example of that:

client.attachments.upload(file, { filepath: 'dog.jpg' }, function () {
  // if no error
  client.tickets.create(ticket, function () {
     res.status(200).end();
  }
}

My question is:

I need an example of "file" object. What should be inside that?

And for "filepath", Should I put the image full filepath on my server starting by 'http....' ? Should I use Multer? Could you please give me a clear example?

Body:
have you tried the example provided in the library here - https://github.com/blakmatrix/node-zendesk/blob/master/examples/upload-attachment.js#L13-L24

client.attachments.upload(path.resolve(
  './examples/busey.gif'),
  {
    filename: 'busey.gif'
  },
  function (err, req, result) {
    if (err) {
      console.log(err);
      return;
    }
    console.log(JSON.stringify(result, null, 2, true));
});

'filepath' looks like it's relative to the file or absolute file path, up to you.  can start with file:// or whatever your local environment requires.  Probably not https because that's accessing across the web and not locally.


问:
How do I sort a bunch of letters and their corresponding frequencies from a string?
I am trying to write a function that can analyze a string and print the letters in the string and their corresponding frequencies. This part isn't too much of a challenge because I can just use ascii_lowercase to sort through the string then the count() method available in ascii. The difficult part is sorting the frequencies so that the most frequent letter is the beginning, and the least frequent is at the end. Here is what I have written so far:

```<code>def analyze(codebook):
lst = []
tmp = []
for c in ascii_lowercase:
   count = codebook.count(c)
   print("('%s', %d)" % (c.upper(), count), end=" ")
   lst.append(count)
   tmp.append(c)
lst.sort()
lst.reverse()
print(lst)
print(tmp)
</code>```

All this does is print the letter and it's corresponding frequencies in the order of the alphabet. Here is an example of the string that I am using:

```<code>pooiiiuuuuyyyyyttttttrrrrrrreeeeeeeewwwwwwwwwqqqqqqqqqq
</code>```

And here is an example of my desired output:

```<code>('Q', 10) ('W', 9) ('E', 8) ('R', 7) ('T', 6) ('Y', 5) ('U', 4) ('I', 3)

('O', 2) ('P', 1) ('A', 0) ('B', 0) ('C', 0) ('D', 0) ('F', 0) ('G', 0)

('H', 0) ('J', 0) ('K', 0) ('L', 0) ('M', 0) ('N', 0) ('S', 0) ('V', 0)

('X', 0) ('Z', 0)
</code>```

I have also tried using collections; however, that got confusing very quickly. Any help would be appreciated!

答:
You had the right idea with the Collections module. Use a Counter, it's their purpose:

```<code>from collections import Counter
s = 'pooiiiuuuuyyyyyttttttrrrrrrreeeeeeeewwwwwwwwwqqqqqqqqqq'
c = Counter(s)
c
Counter({'q': 10, 'w': 9, 'e': 8, 'r': 7, 't': 6, 'y': 5, 'u': 4, 'i': 3, 'o': 2, 'p': 1})
</code>```

It's already ordered by most frequent.

If you need the results as an ordered tuple:

```<code>c.most_common()

[('q', 10),
 ('w', 9),
 ('e', 8),
 ('r', 7),
 ('t', 6),
 ('y', 5),
 ('u', 4),
 ('i', 3),
 ('o', 2),
 ('p', 1)]
</code>```

Body:
I am trying to write a function that can analyze a string and print the letters in the string and their corresponding frequencies. This part isn't too much of a challenge because I can just use ascii_lowercase to sort through the string then the count() method available in ascii. The difficult part is sorting the frequencies so that the most frequent letter is the beginning, and the least frequent is at the end. Here is what I have written so far:

def analyze(codebook):
lst = []
tmp = []
for c in ascii_lowercase:
   count = codebook.count(c)
   print("('%s', %d)" % (c.upper(), count), end=" ")
   lst.append(count)
   tmp.append(c)
lst.sort()
lst.reverse()
print(lst)
print(tmp)

All this does is print the letter and it's corresponding frequencies in the order of the alphabet. Here is an example of the string that I am using:

pooiiiuuuuyyyyyttttttrrrrrrreeeeeeeewwwwwwwwwqqqqqqqqqq

And here is an example of my desired output:

('Q', 10) ('W', 9) ('E', 8) ('R', 7) ('T', 6) ('Y', 5) ('U', 4) ('I', 3)

('O', 2) ('P', 1) ('A', 0) ('B', 0) ('C', 0) ('D', 0) ('F', 0) ('G', 0)

('H', 0) ('J', 0) ('K', 0) ('L', 0) ('M', 0) ('N', 0) ('S', 0) ('V', 0)

('X', 0) ('Z', 0)

I have also tried using collections; however, that got confusing very quickly. Any help would be appreciated!

Body:
You had the right idea with the Collections module. Use a Counter, it's their purpose:

from collections import Counter
s = 'pooiiiuuuuyyyyyttttttrrrrrrreeeeeeeewwwwwwwwwqqqqqqqqqq'
c = Counter(s)
c
Counter({'q': 10, 'w': 9, 'e': 8, 'r': 7, 't': 6, 'y': 5, 'u': 4, 'i': 3, 'o': 2, 'p': 1})

It's already ordered by most frequent.

If you need the results as an ordered tuple:

c.most_common()

[('q', 10),
 ('w', 9),
 ('e', 8),
 ('r', 7),
 ('t', 6),
 ('y', 5),
 ('u', 4),
 ('i', 3),
 ('o', 2),
 ('p', 1)]


问:
database design for updating data weekly
I find it very difficult to explain what I want to ask, So I created a hypothetical question (taking ex of temp), Maybe my question is still not very clear, But pls take a look. let me know if you need any clarification

I want to compare the temp of last Sunday and temp of temp 3 weeks ago (Sunday),
So it should show something like this. There would be two dates in select option so I want to analyze temp on Sunday before last Sunday,

<select>
 <option> Last  Sunday (2017-12-03) </option>
 <option> Previous Sunday (2017-11-26) </option>
</select>

 Temp on 2017-12-03

 24 C

 temp 3 weeks ago (2017-11-12)

 24.4 C

 Change in temp

 .4
```
</div>
</div>
</p>

<p>Assume I can get the temp only current Sunday, So I need to update this database on weekly basis (on every sunday)</p>

```city_id    sunday_temp   temp_pre_week1   temp_pre_week2  temp_pre_week3 last_sunday_date
  1          24.0                24.3              35.2               24.4   2017-12-03
 1           24.3                35.2               24.4               28.0  2017-11-26
 2           3.0                 4.0                2.0                6.0  2017-12-03
 2           4.0                 2.0                6.0                7.0  2017-11-26
 .
 .
around 2000 rows
```

<p>Another option that i thought would be saving the data for 4 weeks, So when user select the Sunday before last Sunday I would be able to use 4th-week column,
Something like this</p>

```city_id    sunday_temp   temp_pre_week1   temp_pre_week2   temp_pre_week3  temp_pre_week4 last_sunday_date
 1           24.0                24.3              35.2           24.4       28.0              2017-12-03
 2           3.0                 4.0                2.0           6.0        7.0               2017-12-03
 .
 .
```

I only want to  analyze two Sundays not more than that, So i think adding one more column would be more efficient,

Thanks :)

答:
Don't store all the data for a query in each row. Let the database do the work for you. Your database structure should just include city_id, date,temp. If you only have Sundays included, that's OK. You can then use something like

```<code>SELECT `temp`,`date` FROM `citydata` WHERE (`city_id` = 1) and (`date` <= '2017-12-03') ORDER BY `date` DESC LIMIT 4
</code>```

which will retrieve the last 4 records available for city 1 that are on or before 2017-12-03. If you have data for every Sunday, that will get you the specific date ("last Sunday") plus the 3 previous weeks. If you decide you want more - just change the LIMIT to 5 or 6 or whatever you want. If you later decide to add different days of the week you won't have to change the database structure (though you will need to adjust your queries a bit). Most importantly, you won't need to look to previous records when you are collecting new data - you just add the new records and get the previous weeks of data when you actually need them.

Body:
I find it very difficult to explain what I want to ask, So I created a hypothetical question (taking ex of temp), Maybe my question is still not very clear, But pls take a look. let me know if you need any clarification

I want to compare the temp of last Sunday and temp of temp 3 weeks ago (Sunday),
So it should show something like this. There would be two dates in select option so I want to analyze temp on Sunday before last Sunday,

<select>
 <option> Last  Sunday (2017-12-03) </option>
 <option> Previous Sunday (2017-11-26) </option>
</select>

 Temp on 2017-12-03

 24 C

 temp 3 weeks ago (2017-11-12)

 24.4 C

 Change in temp

 .4

Assume I can get the temp only current Sunday, So I need to update this database on weekly basis (on every sunday)

city_id    sunday_temp   temp_pre_week1   temp_pre_week2  temp_pre_week3 last_sunday_date
  1          24.0                24.3              35.2               24.4   2017-12-03
 1           24.3                35.2               24.4               28.0  2017-11-26
 2           3.0                 4.0                2.0                6.0  2017-12-03
 2           4.0                 2.0                6.0                7.0  2017-11-26
 .
 .
around 2000 rows

Another option that i thought would be saving the data for 4 weeks, So when user select the Sunday before last Sunday I would be able to use 4th-week column,
Something like this

city_id    sunday_temp   temp_pre_week1   temp_pre_week2   temp_pre_week3  temp_pre_week4 last_sunday_date
 1           24.0                24.3              35.2           24.4       28.0              2017-12-03
 2           3.0                 4.0                2.0           6.0        7.0               2017-12-03
 .
 .

I only want to  analyze two Sundays not more than that, So i think adding one more column would be more efficient,

Thanks :)

Body:
Don't store all the data for a query in each row. Let the database do the work for you. Your database structure should just include city_id, date,temp. If you only have Sundays included, that's OK. You can then use something like

SELECT `temp`,`date` FROM `citydata` WHERE (`city_id` = 1) and (`date` <= '2017-12-03') ORDER BY `date` DESC LIMIT 4

which will retrieve the last 4 records available for city 1 that are on or before 2017-12-03. If you have data for every Sunday, that will get you the specific date ("last Sunday") plus the 3 previous weeks. If you decide you want more - just change the LIMIT to 5 or 6 or whatever you want. If you later decide to add different days of the week you won't have to change the database structure (though you will need to adjust your queries a bit). Most importantly, you won't need to look to previous records when you are collecting new data - you just add the new records and get the previous weeks of data when you actually need them.


问:
Bootstrap 4 flex alignment of columns
I am totally confused. I had this figured out and then refreshed the jsfiddle and somehow the solution changed. I have a row with two columns in the row. I can't get the two columns to align on the same row. I tried using justify-content-around and it is not working. Help would be appreciated.

```<code><div class="container-fluid">
  <div class="d-flex flex-row justify-content-around my-flex-container">
    <div class="d-flex flex-column my-flex-container-column">
      <div class="flex-row my-flex-container">Row 1</div>
      <div class="flex-row my-flex-container">Row 2</div>
      <div class="flex-row my-flex-container">Row 3</div>
      <div class="flex-row my-flex-container">Row 4</div>
    </div>
    <div class="d-flex flex-column my-flex-container-column">
      <div class="d-flex flex-row my-flex-container">
        <div class="flex-column my-flex-container-column">
           <div class="flex-row my-flex-container">Row 1
           </div>
           <div class="flex-row my-flex-container">Row 2
           </div>
        </div>
      </div>
      <div class="d-flex flex-row flex-1 my-flex-container">
        <div class="my-auto">ROW 3</div>
      </div>

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

jsfiddle here

答:
You need to update your Bootstrap version from Alpha to Beta release, you can get it here.

  .my-flex-container {
    border: 2px solid green;
  }
   .my-flex-container-column {
    border: 2px solid green;
  }
  .flex-1{
    flex: 1;
  }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" rel="stylesheet"/>
<div class="container-fluid">
  <div class="d-flex flex-row justify-content-around my-flex-container">
    <div class="d-flex flex-column my-flex-container-column">
      <div class="flex-row my-flex-container">Row 1</div>
      <div class="flex-row my-flex-container">Row 2</div>
      <div class="flex-row my-flex-container">Row 3</div>
      <div class="flex-row my-flex-container">Row 4</div>
    </div>
    <div class="d-flex flex-column my-flex-container-column">
      <div class="d-flex flex-row my-flex-container">
        <div class="flex-column my-flex-container-column">
           <div class="flex-row my-flex-container">Row 1
           </div>
           <div class="flex-row my-flex-container">Row 2
           </div>
        </div>
      </div>
      <div class="d-flex flex-row flex-1 my-flex-container">
        <div class="my-auto">ROW 3</div>
      </div>

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

Title: Bootstrap 4 flex alignment of columns

Body:
I am totally confused. I had this figured out and then refreshed the jsfiddle and somehow the solution changed. I have a row with two columns in the row. I can't get the two columns to align on the same row. I tried using justify-content-around and it is not working. Help would be appreciated.

Row 1

Row 2

Row 3

Row 4

Row 1

Row 2

ROW 3

jsfiddle here

Body:
You need to update your Bootstrap version from Alpha to Beta release, you can get it here.

  .my-flex-container {
    border: 2px solid green;
  }
   .my-flex-container-column {
    border: 2px solid green;
  }
  .flex-1{
    flex: 1;
  }

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" rel="stylesheet"/>
<div class="container-fluid">
  <div class="d-flex flex-row justify-content-around my-flex-container">
    <div class="d-flex flex-column my-flex-container-column">
      <div class="flex-row my-flex-container">Row 1</div>
      <div class="flex-row my-flex-container">Row 2</div>
      <div class="flex-row my-flex-container">Row 3</div>
      <div class="flex-row my-flex-container">Row 4</div>
    </div>
    <div class="d-flex flex-column my-flex-container-column">
      <div class="d-flex flex-row my-flex-container">
        <div class="flex-column my-flex-container-column">
           <div class="flex-row my-flex-container">Row 1
           </div>
           <div class="flex-row my-flex-container">Row 2
           </div>
        </div>
      </div>
      <div class="d-flex flex-row flex-1 my-flex-container">
        <div class="my-auto">ROW 3</div>
      </div>

    </div>
  </div>
</div>


问:
Java Complex Sorting
I am stuck in that I have an Object Book that got three variables

```<code>String title
int Year
String authorName
</code>```

I must sort the books by one, two or all three of the variables in ascending or descending order, I implemented the title ordering but I am stuck as to what to do when people choose more than one variable to order.

Here is some of my code:

Book Class:

```<code>import java.util.ArrayList;

public class Book{

String title;
String authorName;
int editionYear;

public Book(String title, String authorName, int editionYear){
    this.title = title;
    this.authorName = authorName;
    this.editionYear = editionYear;

}

public String getBookInfo(){

    ArrayList bookInfo = new ArrayList();
    bookInfo.add(this.title);
    bookInfo.add(this.authorName);
    bookInfo.add(this.editionYear);
    return bookInfo.toString();
}

}
</code>```

BookSorter Class:

```<code>import java.util.Arrays;
import java.util.Comparator;

public class BookSorter{

private String sortkey;
private String order;
Book[] Books;

public BookSorter(Book Book1, Book Book2, Book Book3, Book Book4){
    this.Books = new Book[] {Book1, Book2, Book3, Book4};
}

public Book[] sortByTitle(boolean sortorder){
    Comparator<Book> byTitle = new TitleComparator(sortorder);
    Arrays.sort(Books, byTitle);
    for(int i=0;i<4;i++) System.out.println(Books[i].title);
    return Books;
}
}
</code>```

TitleComparator:

```<code>import java.util.Comparator;

class TitleComparator implements Comparator<Book> {

boolean ascending;

public TitleComparator(boolean ascending){
    this.ascending = ascending;
}

public int compare(Book Book1, Book Book2){
    if(ascending == true){
        if(Book1.title.compareToIgnoreCase(Book2.title) > 0) return 1;
        else if(Book1.title.compareToIgnoreCase(Book2.title) < 0) return -1;
        else return 0;
    }else{
        if(Book2.title.compareToIgnoreCase(Book1.title) < 0) return -1;
        else if(Book2.title.compareToIgnoreCase(Book1.title) > 0) return 1;
        else return 0;
    }
}
}
</code>```

I though I could work a little more on the comparator but I am really stuck on how to model such a thing, Thanks in advance

答:
Write 3 comparator classes that each compare a specific attribute  and then an overall comparator class that takes an ordered list of comparators.

Or use some a convenience class from a library like org.apache.commons.collections.comparators.ComparatorChain.

Edit:

OP asks:

how could I write that overall comparator:

Something like:

```<code>// private List<Comparator<?>> comparators;  // initialized in constructor

// compare method(book1, book2):
//     note that while result == 0, books have had equal attributes so far
//     once result is != 0, the books are now ordered - no need to compare further
//     if we run out of comparators and result still == 0, books are equal.

//     initialize iterator to list of comparators
//     int result = 0;
//     while result == 0 && still more comparators
//         get current comparator from iterator
//         result = comparator.compare(book1, book2); // compare current attribute
//     end-while
//     return result
</code>```

Title: Java Complex Sorting

Body:
I am stuck in that I have an Object Book that got three variables

String title
int Year
String authorName

I must sort the books by one, two or all three of the variables in ascending or descending order, I implemented the title ordering but I am stuck as to what to do when people choose more than one variable to order.

Here is some of my code:

Book Class:

import java.util.ArrayList;

public class Book{

String title;
String authorName;
int editionYear;

public Book(String title, String authorName, int editionYear){
    this.title = title;
    this.authorName = authorName;
    this.editionYear = editionYear;

}

public String getBookInfo(){

    ArrayList bookInfo = new ArrayList();
    bookInfo.add(this.title);
    bookInfo.add(this.authorName);
    bookInfo.add(this.editionYear);
    return bookInfo.toString();
}

}

BookSorter Class:

import java.util.Arrays;
import java.util.Comparator;

public class BookSorter{

private String sortkey;
private String order;
Book[] Books;

public BookSorter(Book Book1, Book Book2, Book Book3, Book Book4){
    this.Books = new Book[] {Book1, Book2, Book3, Book4};
}

public Book[] sortByTitle(boolean sortorder){
    Comparator<Book> byTitle = new TitleComparator(sortorder);
    Arrays.sort(Books, byTitle);
    for(int i=0;i<4;i++) System.out.println(Books[i].title);
    return Books;
}
}

TitleComparator:

import java.util.Comparator;

class TitleComparator implements Comparator<Book> {

boolean ascending;

public TitleComparator(boolean ascending){
    this.ascending = ascending;
}

public int compare(Book Book1, Book Book2){
    if(ascending == true){
        if(Book1.title.compareToIgnoreCase(Book2.title) > 0) return 1;
        else if(Book1.title.compareToIgnoreCase(Book2.title) < 0) return -1;
        else return 0;
    }else{
        if(Book2.title.compareToIgnoreCase(Book1.title) < 0) return -1;
        else if(Book2.title.compareToIgnoreCase(Book1.title) > 0) return 1;
        else return 0;
    }
}
}

I though I could work a little more on the comparator but I am really stuck on how to model such a thing, Thanks in advance

Body:
Write 3 comparator classes that each compare a specific attribute  and then an overall comparator class that takes an ordered list of comparators.

Or use some a convenience class from a library like org.apache.commons.collections.comparators.ComparatorChain.

Edit:

OP asks:

how could I write that overall comparator:

Something like:

// private List<Comparator<?>> comparators;  // initialized in constructor

// compare method(book1, book2):
//     note that while result == 0, books have had equal attributes so far
//     once result is != 0, the books are now ordered - no need to compare further
//     if we run out of comparators and result still == 0, books are equal.

//     initialize iterator to list of comparators
//     int result = 0;
//     while result == 0 && still more comparators
//         get current comparator from iterator
//         result = comparator.compare(book1, book2); // compare current attribute
//     end-while
//     return result


问:
Xcode 9.1 (and 9.2) - Referenced sprites are not executing Actions added in Scene Editor
I have come across some unexpected behaviour when using the SpriteKit Scene Editor, and wonder if anyone else is having the same issue.

I created a sprite in a scene and added Actions to move it around using the Scene Editor. The Actions play fine when I click the animate button on the editor. I add a reference to this scene to the main scene using the SKReferenceNode object in the Scene Editor, and the sprite appears in the main scene as expected in the Editor. When I build and run the app however, the sprite appears but no Actions run. I have tried this on the Xcode 9.2 beta and get the same result.
If I load the sprite scene directly from the main view controller, all the Actions execute as expected, so it seems to be an issue with referenced nodes.
I also found that if I override didMove(to:) in the main scene swift class, and put a breakpoint in it, then just hit continue when it hit the breakpoint, all Actions play on referenced sprites as expected. If I disable the breakpoint, no Actions play on referenced sprites.
(So my workaround is to simply use the breakpoint, and hit the continue button)

Another interesting observation. I opened a sample project created with an older version of Xcode, and referenced sprites executed their Actions fine. I copied this older SKS file into my project and Actions worked fine...until I edited the SKS file (added another Action), then they never worked again.

答:
I asked a similar question just the other day:
XCode 9: SKEditorReference doesn't allow animations?

The only way I was able to get this to work was to put the isPaused on the exact sprite node I was trying to animate (within a ref node - I had created an entire sks scene/file and drag-dropped that into my main scene).

I tried isPaused=false at the top level, main scene didMove to view to no effect, and then added isPaused=false to the main reference node, to no effect. It worked only when I added isPaused=false the actual sprite I was trying to animate. I removed isPaused=false from the the main & ref nodes, and as long as it was still on the sprite node (within the ref node) I was trying to animate: success.

Bottom line seems to be that isPaused=false is required on any sprites within a reference node.


问:
running mule from maven not seeing mule-app.properties
Here is my exec config:

```<code>        <plugin>
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>exec-maven-plugin</artifactId>
            <version>1.2.1</version>
            <executions>
                <execution>
                    <goals>
                        <goal>java</goal>
                    </goals>
                </execution>
            </executions>
            <configuration>
                <mainClass>org.mule.MuleServer</mainClass>
                <arguments>
                    <argument>-config</argument>
                    <argument>src/main/app/prioritisation-api.xml</argument>
                    <argument>-classpath</argument>
                    <argument>src/main/app</argument>
                </arguments>
                <classpathScope>compile</classpathScope>
            </configuration>
        </plugin>
</code>```

And the error I get

org.springframework.beans.MethodInvocationException: Property 'protocol' threw exception; nested exception is java.lang.IllegalArgumentException: Address '${prioritisation.api.console.endpoint}' for protocol 'http' should start with http://

This suggests to me that the mule-app.properties are not being resolved properly.  The thing is this all works in Anypoint Studio when I do Run As Maven Mule Project.  What am I missing?

EDIT:

I am trying to run mule using: mvn exec:java -DrunMule

Mule version: <mule.version>3.4.0</mule.version>

Properties are in: src/main/app/mule-app.properties

Maven version: Apache Maven 3.2.1

答: I think you need to add your properties to a file with name environment.properties in the src/main/resources folder and add its reference using <context:property-placeholder location="environment.properties"/>

Body:
Here is my exec config:

        <plugin>
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>exec-maven-plugin</artifactId>
            <version>1.2.1</version>
            <executions>
                <execution>
                    <goals>
                        <goal>java</goal>
                    </goals>
                </execution>
            </executions>
            <configuration>
                <mainClass>org.mule.MuleServer</mainClass>
                <arguments>
                    <argument>-config</argument>
                    <argument>src/main/app/prioritisation-api.xml</argument>
                    <argument>-classpath</argument>
                    <argument>src/main/app</argument>
                </arguments>
                <classpathScope>compile</classpathScope>
            </configuration>
        </plugin>

And the error I get

org.springframework.beans.MethodInvocationException: Property 'protocol' threw exception; nested exception is java.lang.IllegalArgumentException: Address '${prioritisation.api.console.endpoint}' for protocol 'http' should start with http://

This suggests to me that the mule-app.properties are not being resolved properly.  The thing is this all works in Anypoint Studio when I do Run As Maven Mule Project.  What am I missing?

EDIT:

I am trying to run mule using: mvn exec:java -DrunMule

Mule version: <mule.version>3.4.0</mule.version>

Properties are in: src/main/app/mule-app.properties

Maven version: Apache Maven 3.2.1


问:
extend UserManager to search User by relation (symfony3)
I installed FOSUserbundle and HWI Oauth bundle.
My problem is: I want to access data from my user entity that is stored in a relation. I'd like to access the data from the fields social_network_slug and social_identifier from UserInSocialNetworks within the FOSUserProvider.
The idea was, that one user can have more that one social network logins. (1:n)- When I log in with my google/facebook etc login, I want to check the table user_in_social_networks if the Id with the social network already exists.

```<code>/*
 * This is the User class, depending on fos_userBundle
 */

namespace AppBundle\Entity\Registration;

use Doctrine\Common\Collections\ArrayCollection as ArrayCollection;
use FOS\UserBundle\Model\User as BaseUser;
use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity
 * @ORM\Table(name="user")
 */
class User extends BaseUser
{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * One User can have many social networks
     * @ORM\OneToMany(targetEntity="UserInSocialNetworks", mappedBy="user", cascade={"remove"})
     */
    private $socialnetworks; ....
</code>```

the Entity Class to store all User's social media logins:

```<code><?php

namespace AppBundle\Entity\Registration;

use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;

/**
 * UserInSocialNetworks
 *
 * @ORM\Table(name="user_in_social_networks")
 * @ORM\Entity(repositoryClass="AppBundle\Repository\Registration\UserInSocialNetworksRepository")
 */
class UserInSocialNetworks
{
    /**
     * @var int
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * Many Socialnetwork Logins have one User
     * @ORM\ManyToOne(targetEntity="AppBundle\Entity\Registration\User", inversedBy="socialnetworks")
     * @ORM\JoinColumn(name="user_id", referencedColumnName="id")
     *
     */
    private $user;

    /**
     * @var int
     *
     * @ORM\Column(name="social_network_slug", type="string", length=255, nullable=true)
     */
    private $socialNetworkSlug;

    /**
     * @var string
     *
     * @ORM\Column(name="social_identifier", type="string", length=255, nullable=true)
     */
    private $socialIdentifier;
</code>```

The extended FOSUBUserProvider class:

```<code>    <?php
    namespace AppBundle\Entity\Registration;

    use HWI\Bundle\OAuthBundle\OAuth\Response\UserResponseInterface;
    use HWI\Bundle\OAuthBundle\Security\Core\User\FOSUBUserProvider as BaseClass;
    use Symfony\Component\Security\Core\User\UserInterface;

    class FOSUBUserProvider extends BaseClass
    {
    /**
         * {@inheritDoc}
         */
        public function loadUserByOAuthUserResponse(UserResponseInterface $response)
        {
            // get user_id and socialnetworkname from response
            $userIdInSocialNetwork = $response->getUsername();
            $socialnetwork = $response->getResourceOwner()->getName();
// Here I'd like to search for an existing $userIdInSocialNetwork
</code>```

What I checked since now: I can't access the entitymanager in FOSUBUserProvider class, and I can't search that way:

```<code>$user = $this->userManager->findUserBy(array(
                'socialIdentifier' => $userIdInSocialNetwork,
                'social_network_slug' => $socialnetwork)
</code>```

because it's a relation.
Thanks for any idea!

答:
As you mentioned that you have extended FOSUBUserProvider i assume you have defined a new service for this, If so then you can pass doctrine's entity manager to your class @doctrine.orm.entity_manager. Following HWIOAuthBundle documentation for FOSUserBundle you can pass entity manager as

```<code>services:
    my.custom.user_provider:
        class:        MyBundle\Security\Core\User\MyFOSUBUserProvider
        arguments: ['@fos_user.user_manager', { facebook: facebook_id }, @doctrine.orm.entity_manager]
</code>```

And then in your class you can use this service as

```<code>use Doctrine\ORM\EntityManager;
use FOS\UserBundle\Model\UserManagerInterface;
//.... other use statements

class FOSUBUserProvider extends BaseClass
{
    private $em;

    public function __construct(UserManagerInterface $userManager, array $properties, EntityManager $em)
    {
        $this->em = $em;
        parent::__construct($userManager, $properties); /* pass dependencies to parent */
    }

    public function loadUserByOAuthUserResponse(UserResponseInterface $response)
    {
        $this->em->getRepository('AppBundle\Entity\Registration\UserInSocialNetworks')->findBy(....);

        /* Do your stuff here */
    }
}
</code>```

Body:
I installed FOSUserbundle and HWI Oauth bundle.
My problem is: I want to access data from my user entity that is stored in a relation. I'd like to access the data from the fields social_network_slug and social_identifier from UserInSocialNetworks within the FOSUserProvider.
The idea was, that one user can have more that one social network logins. (1:n)- When I log in with my google/facebook etc login, I want to check the table user_in_social_networks if the Id with the social network already exists.

/*
 * This is the User class, depending on fos_userBundle
 */

namespace AppBundle\Entity\Registration;

use Doctrine\Common\Collections\ArrayCollection as ArrayCollection;
use FOS\UserBundle\Model\User as BaseUser;
use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity
 * @ORM\Table(name="user")
 */
class User extends BaseUser
{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * One User can have many social networks
     * @ORM\OneToMany(targetEntity="UserInSocialNetworks", mappedBy="user", cascade={"remove"})
     */
    private $socialnetworks; ....

the Entity Class to store all User's social media logins:

<?php

namespace AppBundle\Entity\Registration;

use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;

/**
 * UserInSocialNetworks
 *
 * @ORM\Table(name="user_in_social_networks")
 * @ORM\Entity(repositoryClass="AppBundle\Repository\Registration\UserInSocialNetworksRepository")
 */
class UserInSocialNetworks
{
    /**
     * @var int
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * Many Socialnetwork Logins have one User
     * @ORM\ManyToOne(targetEntity="AppBundle\Entity\Registration\User", inversedBy="socialnetworks")
     * @ORM\JoinColumn(name="user_id", referencedColumnName="id")
     *
     */
    private $user;

    /**
     * @var int
     *
     * @ORM\Column(name="social_network_slug", type="string", length=255, nullable=true)
     */
    private $socialNetworkSlug;

    /**
     * @var string
     *
     * @ORM\Column(name="social_identifier", type="string", length=255, nullable=true)
     */
    private $socialIdentifier;

The extended FOSUBUserProvider class:

    <?php
    namespace AppBundle\Entity\Registration;

    use HWI\Bundle\OAuthBundle\OAuth\Response\UserResponseInterface;
    use HWI\Bundle\OAuthBundle\Security\Core\User\FOSUBUserProvider as BaseClass;
    use Symfony\Component\Security\Core\User\UserInterface;

    class FOSUBUserProvider extends BaseClass
    {
    /**
         * {@inheritDoc}
         */
        public function loadUserByOAuthUserResponse(UserResponseInterface $response)
        {
            // get user_id and socialnetworkname from response
            $userIdInSocialNetwork = $response->getUsername();
            $socialnetwork = $response->getResourceOwner()->getName();
// Here I'd like to search for an existing $userIdInSocialNetwork

What I checked since now: I can't access the entitymanager in FOSUBUserProvider class, and I can't search that way:

$user = $this->userManager->findUserBy(array(
                'socialIdentifier' => $userIdInSocialNetwork,
                'social_network_slug' => $socialnetwork)

because it's a relation.
Thanks for any idea!

Body:
As you mentioned that you have extended FOSUBUserProvider i assume you have defined a new service for this, If so then you can pass doctrine's entity manager to your class @doctrine.orm.entity_manager. Following HWIOAuthBundle documentation for FOSUserBundle you can pass entity manager as

services:
    my.custom.user_provider:
        class:        MyBundle\Security\Core\User\MyFOSUBUserProvider
        arguments: ['@fos_user.user_manager', { facebook: facebook_id }, @doctrine.orm.entity_manager]

And then in your class you can use this service as

use Doctrine\ORM\EntityManager;
use FOS\UserBundle\Model\UserManagerInterface;
//.... other use statements

class FOSUBUserProvider extends BaseClass
{
    private $em;

    public function __construct(UserManagerInterface $userManager, array $properties, EntityManager $em)
    {
        $this->em = $em;
        parent::__construct($userManager, $properties); /* pass dependencies to parent */
    }

    public function loadUserByOAuthUserResponse(UserResponseInterface $response)
    {
        $this->em->getRepository('AppBundle\Entity\Registration\UserInSocialNetworks')->findBy(....);

        /* Do your stuff here */
    }
}


问:
Indirect modification of overloaded property has no effect
When I run the below API I got this error

"Indirect modification of overloaded property App\User::$attendance has no effect".

I still cannot figure it out for so long. Could you please someone help me on this.

```<code>public function apiPresent( $id, Request $request )
{
    $tokenuser = User::with('attendance')
                    ->where('token', $request->input('token'))->first();
    $present   = $request->input('present');
    $user      = User::with('attendance')->find($id);

    if( $user && $tokenuser == $user )
    {
        $user->attendance->present = $present;
        $user->attendance->date    = Carbon::now()->format('d-m-Y');
        $user->attendance->time    = Carbon::now()->format('H-i');
        $user->attendance->save();

        return response()->json([
                    'status'  => 'Ok',
                    'message' => 'Present Changed',
                    'Present' => $user->attendance->present
        ]);
    }
    else
    {
        return response()->json([
                    'status'  => 'Fail',
                    'message' => 'Your state does not changed'
        ]);
    }
}
</code>```

答:
If i understand your problem. You are saving the attendance.

Try this:

```<code>use App\Attendance; // Add before controller declaration

public function apiPresent( $id, Request $request )
{
    $tokenuser = User::where('token', $request->input('token'))->first();
    $present   = $request->input('present');
    $user      = User::find($id);

    if( $user && $tokenuser->id == $user->id ){
        $attendance = new Attendance;
        $attendance->present = $present;
        $attendance->date    = Carbon::now()->format('d-m-Y');
        $attendance->time    = Carbon::now()->format('H-i');
        $attendance->save();

        return response()->json([
                'status'  => 'Ok',
                'message' => 'Present Changed',
                'Present' => $present
       ]);
    }
    else {
        return response()->json([
                'status'  => 'Fail',
                'message' => 'Your state does not changed'
       ]);
    }
}
</code>```

Hope it helps!

Body:
When I run the below API I got this error

"Indirect modification of overloaded property App\User::$attendance has no effect".

I still cannot figure it out for so long. Could you please someone help me on this.

public function apiPresent( $id, Request $request )
{
    $tokenuser = User::with('attendance')
                    ->where('token', $request->input('token'))->first();
    $present   = $request->input('present');
    $user      = User::with('attendance')->find($id);

    if( $user && $tokenuser == $user )
    {
        $user->attendance->present = $present;
        $user->attendance->date    = Carbon::now()->format('d-m-Y');
        $user->attendance->time    = Carbon::now()->format('H-i');
        $user->attendance->save();

        return response()->json([
                    'status'  => 'Ok',
                    'message' => 'Present Changed',
                    'Present' => $user->attendance->present
        ]);
    }
    else
    {
        return response()->json([
                    'status'  => 'Fail',
                    'message' => 'Your state does not changed'
        ]);
    }
}

Body:
If i understand your problem. You are saving the attendance.

Try this:

use App\Attendance; // Add before controller declaration

public function apiPresent( $id, Request $request )
{
    $tokenuser = User::where('token', $request->input('token'))->first();
    $present   = $request->input('present');
    $user      = User::find($id);

    if( $user && $tokenuser->id == $user->id ){
        $attendance = new Attendance;
        $attendance->present = $present;
        $attendance->date    = Carbon::now()->format('d-m-Y');
        $attendance->time    = Carbon::now()->format('H-i');
        $attendance->save();

        return response()->json([
                'status'  => 'Ok',
                'message' => 'Present Changed',
                'Present' => $present
       ]);
    }
    else {
        return response()->json([
                'status'  => 'Fail',
                'message' => 'Your state does not changed'
       ]);
    }
}

Hope it helps!