问:
Input Format to pcolormesh
I'm attempting to make heat/intensity map using Basemap. My inputs are a set of lats, lons, and intensity at that point. The dataset looks like this:

```<code>lat[0], lon[0] = intensity[0]
lat[1], lon[1] = intensity[1]
...
lat[n], lon[n] = intensity[n]
</code>```

At each index the lat and lon correspond to the correct sensor reading. My code looks something like this:

```<code>fig = plt.figure(figsize=(10, 8))

# Set title
fig.suptitle("Intensities {} {}".format(start_time, stop_time))

# US Centered Map
map_axis = fig.add_subplot(111)
map = Basemap(
    ax = map_axis,
    lat_0 = 40, lon_0 = -95,
    width = 6500e3, height = 6500e3,
    projection = 'stere',
    resolution = 'l'
)
map.drawcoastlines()

lats = ...
lons = ...
intn = ...

# Convert coordinates
lons, lats = map(lons, lats)

LONS, LATS = np.meshgrid(lons, lats)
map.pcolormesh(
    LONS, LATS,
    intn,
    vmin = 0, vmax = 100
)

fig.savefig(file_name)
plt.close(fig)
</code>```

This code never completes. I've successfully plotted the Basemap by itself. The pcolormesh is what is failing. The program crashes with this error.

```<code>    $ ./plot_intensities.py
    Running 2013-04-10 00:02:30 2013-04-10 00:02:45
    Traceback (most recent call last):
      File "./plot_intensities.py", line 151, in <module>
        make_maps(samples)
      File "./plot_intensities.py", line 144, in make_maps
        make_map(bin_samples, start, walk)
      File "./plot_intensities.py", line 117, in make_map
        vmin = 0, vmax = 100
      File "/usr/lib/python3/dist-packages/mpl_toolkits/basemap/__init__.py", line 521, in with_transform
        return plotfunc(self,x,y,data,*args,**kwargs)
      File "/usr/lib/python3/dist-packages/mpl_toolkits/basemap/__init__.py", line 3418, in pcolormesh
        ret =  ax.pcolormesh(x,y,data,**kwargs)
      File "/usr/lib/python3/dist-packages/matplotlib/__init__.py", line 1814, in inner
        return func(ax, *args, **kwargs)
      File "/usr/lib/python3/dist-packages/matplotlib/axes/_axes.py", line 5395, in pcolormesh
        X, Y, C = self._pcolorargs('pcolormesh', *args, allmatch=allmatch)
      File "/usr/lib/python3/dist-packages/matplotlib/axes/_axes.py", line 4995, in _pcolorargs
        numRows, numCols = C.shape
    ValueError: not enough values to unpack (expected 2, got 1)
</code>```

I understand that my data, the third argument intn is not formatted correctly. I cannot find any documentation as to how I should shape that list. How do I format it to the correct shape?

Thanks.

答:
As you know, pcolormesh is used to plot a quadrilateral mesh by creating a pseudocolor plot of a 2-D array. The error details indeed indicated that: at line numRows, numCols = C.shape, it expect C to be a 2-D array, while the C you provided seems to be a 1-D array, judging from ValueError: not enough values to unpack (expected 2, got 1). The dataset you introduced seems to me having only intensity values on the diagonal (where lat == lon). To get a colormesh, you need to at least extend intensity data into 2-D array and somehow fill in missing values. For example:

```<code>import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap
import numpy as np

fig = plt.figure(figsize=(10, 8))
# Set title
fig.suptitle("Intensities {} {}".format('start_time', 'stop_time'))
# US Centered Map
map_axis = fig.add_subplot(111)
map = Basemap(
    ax = map_axis,
    lat_0 = 40, lon_0 = -95,
    width = 6500e3, height = 6500e3,
    projection = 'stere',
    resolution = 'l'
)
map.drawcoastlines()

# Tried my best to simulate your data example. Don't be surprise if the result is ugly ...
nstep = 1
lats = np.arange(map.latmin, map.latmax, nstep)
lons = np.arange(map.lonmin, map.lonmax, nstep)
l = min(len(lats), len(lons))
lats = lats[:l]
lons = lons[:l]
intn = np.random.randint(0, 100, size=l)

# Convert coordinates
lons, lats = map(lons, lats)
LONS, LATS = np.meshgrid(lons, lats)

# The following 3 lines are just an example of the minimum you got to do before it works.
intn_array = np.zeros(LONS.shape)
for i in range(l):
    intn_array[i, i] = intn[i]
intn = intn_array

map.pcolormesh(
    LONS, LATS,
    intn_array,
    vmin = 0, vmax = 100
)

plt.show()
</code>```

Title: Input Format to pcolormesh

Body:
I'm attempting to make heat/intensity map using Basemap. My inputs are a set of lats, lons, and intensity at that point. The dataset looks like this:

lat[0], lon[0] = intensity[0]
lat[1], lon[1] = intensity[1]
...
lat[n], lon[n] = intensity[n]

At each index the lat and lon correspond to the correct sensor reading. My code looks something like this:

fig = plt.figure(figsize=(10, 8))

# Set title
fig.suptitle("Intensities {} {}".format(start_time, stop_time))

# US Centered Map
map_axis = fig.add_subplot(111)
map = Basemap(
    ax = map_axis,
    lat_0 = 40, lon_0 = -95,
    width = 6500e3, height = 6500e3,
    projection = 'stere',
    resolution = 'l'
)
map.drawcoastlines()

lats = ...
lons = ...
intn = ...

# Convert coordinates
lons, lats = map(lons, lats)

LONS, LATS = np.meshgrid(lons, lats)
map.pcolormesh(
    LONS, LATS,
    intn,
    vmin = 0, vmax = 100
)

fig.savefig(file_name)
plt.close(fig)

This code never completes. I've successfully plotted the Basemap by itself. The pcolormesh is what is failing. The program crashes with this error.

    $ ./plot_intensities.py
    Running 2013-04-10 00:02:30 2013-04-10 00:02:45
    Traceback (most recent call last):
      File "./plot_intensities.py", line 151, in <module>
        make_maps(samples)
      File "./plot_intensities.py", line 144, in make_maps
        make_map(bin_samples, start, walk)
      File "./plot_intensities.py", line 117, in make_map
        vmin = 0, vmax = 100
      File "/usr/lib/python3/dist-packages/mpl_toolkits/basemap/__init__.py", line 521, in with_transform
        return plotfunc(self,x,y,data,*args,**kwargs)
      File "/usr/lib/python3/dist-packages/mpl_toolkits/basemap/__init__.py", line 3418, in pcolormesh
        ret =  ax.pcolormesh(x,y,data,**kwargs)
      File "/usr/lib/python3/dist-packages/matplotlib/__init__.py", line 1814, in inner
        return func(ax, *args, **kwargs)
      File "/usr/lib/python3/dist-packages/matplotlib/axes/_axes.py", line 5395, in pcolormesh
        X, Y, C = self._pcolorargs('pcolormesh', *args, allmatch=allmatch)
      File "/usr/lib/python3/dist-packages/matplotlib/axes/_axes.py", line 4995, in _pcolorargs
        numRows, numCols = C.shape
    ValueError: not enough values to unpack (expected 2, got 1)

I understand that my data, the third argument intn is not formatted correctly. I cannot find any documentation as to how I should shape that list. How do I format it to the correct shape?

Thanks.

Body:
As you know, pcolormesh is used to plot a quadrilateral mesh by creating a pseudocolor plot of a 2-D array. The error details indeed indicated that: at line numRows, numCols = C.shape, it expect C to be a 2-D array, while the C you provided seems to be a 1-D array, judging from ValueError: not enough values to unpack (expected 2, got 1). The dataset you introduced seems to me having only intensity values on the diagonal (where lat == lon). To get a colormesh, you need to at least extend intensity data into 2-D array and somehow fill in missing values. For example:

import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap
import numpy as np

fig = plt.figure(figsize=(10, 8))
# Set title
fig.suptitle("Intensities {} {}".format('start_time', 'stop_time'))
# US Centered Map
map_axis = fig.add_subplot(111)
map = Basemap(
    ax = map_axis,
    lat_0 = 40, lon_0 = -95,
    width = 6500e3, height = 6500e3,
    projection = 'stere',
    resolution = 'l'
)
map.drawcoastlines()

# Tried my best to simulate your data example. Don't be surprise if the result is ugly ...
nstep = 1
lats = np.arange(map.latmin, map.latmax, nstep)
lons = np.arange(map.lonmin, map.lonmax, nstep)
l = min(len(lats), len(lons))
lats = lats[:l]
lons = lons[:l]
intn = np.random.randint(0, 100, size=l)

# Convert coordinates
lons, lats = map(lons, lats)
LONS, LATS = np.meshgrid(lons, lats)

# The following 3 lines are just an example of the minimum you got to do before it works.
intn_array = np.zeros(LONS.shape)
for i in range(l):
    intn_array[i, i] = intn[i]
intn = intn_array

map.pcolormesh(
    LONS, LATS,
    intn_array,
    vmin = 0, vmax = 100
)

plt.show()


来源: stackexchange

问:
Retrofit2 - Sending Array of Type T in a GET request
I need to send an array of type User[] in the body of a GET request using retrofit2. This is what the final payload must look like:

```<code>body: {
  "data_id": 1,
  "data_provider": "string_value",
  "users": [
    {
      user_id: 1,
      name: 'name'
    },
    {
      user_id: 1,
      name: 'name'
    },
    ...
  ]
}
</code>```

Current API implementation looks like this:

```<code>@GET("api/users/submit.json")
Call<UserData> submitData(@Query("data_id") int data_id, @Query("data_provider") String data_provider, @Query("users[]") User[] users);
</code>```

Arraylist code:

```<code>//Converting the ArrayList<User> usersList to an array
User[] userArray = usersList.toArray(new User[0]);
//The userArray is passed to the retrofit API along with the other request values (data_id, data_provider)
</code>```

Upon logging the retrofit request, data_id and data_provider are correctly sent except for the User array. The user array looks like this:

api/users/submit.json?data_id=1&data_provider=test&users[]=com.testapp.models.User@7d57487

How can I send an array of type User in the GET request body?

答:
For this payload:-

```<code>body: {
  "data_id": 1,
  "data_provider": "string_value",
  "users": [
    {
      user_id: 1,
      name: 'name'
    },
    {
      user_id: 1,
      name: 'name'
    },
    ...
  ]
}
</code>```

Api structure should be like this:-

```<code>public class ReqBody{
    int data_id;
    String data_provider;
    User[] users;
}

@POST("api/users/submit.json")
Call<UserData> submitData(@Body ReqBody reqBody);
</code>```

If your requirement is something else please attach the proper details for API as at some point you want to send data_id and data_provider in Query param and in the structure you have defined them as part of the body.
If they are part of the body then it should be work like this.

ContentLicense: CC BY-SA 3.0

Body:
I need to send an array of type User[] in the body of a GET request using retrofit2. This is what the final payload must look like:

body: {
  "data_id": 1,
  "data_provider": "string_value",
  "users": [
    {
      user_id: 1,
      name: 'name'
    },
    {
      user_id: 1,
      name: 'name'
    },
    ...
  ]
}

Current API implementation looks like this:

@GET("api/users/submit.json")
Call<UserData> submitData(@Query("data_id") int data_id, @Query("data_provider") String data_provider, @Query("users[]") User[] users);

Arraylist code:

//Converting the ArrayList<User> usersList to an array
User[] userArray = usersList.toArray(new User[0]);
//The userArray is passed to the retrofit API along with the other request values (data_id, data_provider)

Upon logging the retrofit request, data_id and data_provider are correctly sent except for the User array. The user array looks like this:

api/users/submit.json?data_id=1&data_provider=test&users[]=com.testapp.models.User@7d57487

How can I send an array of type User in the GET request body?

Body:
For this payload:-

body: {
  "data_id": 1,
  "data_provider": "string_value",
  "users": [
    {
      user_id: 1,
      name: 'name'
    },
    {
      user_id: 1,
      name: 'name'
    },
    ...
  ]
}

Api structure should be like this:-

public class ReqBody{
    int data_id;
    String data_provider;
    User[] users;
}

@POST("api/users/submit.json")
Call<UserData> submitData(@Body ReqBody reqBody);

If your requirement is something else please attach the proper details for API as at some point you want to send data_id and data_provider in Query param and in the structure you have defined them as part of the body.
If they are part of the body then it should be work like this.


问:
Visio Drawing Control in VB.net
The Visio Drawing Control was successfully added into a form in VB.net. The issue faced was how can I display the 'Shapes' window. I checked the child for Microsoft.Office.Interop.Visio.Window and don't see any to display the 'Shapes' window.

答:
In VB.net, to show the 'Shapes' window at the Microsoft Visio Drawing Control:

Dim vsoWindow As Visio.Window

vsoWindow = AxDrawingControl1.Window
vsoWindow.Application.DoCmd(1669)
```

Title: Visio Drawing Control in VB.net


问:
Implementing Primary NTP Server (GPS Receiver)
I'm trying to implement an NTP server based on an NMEA GPS Receiver. I'm not sure what to fill the root delay field with.

I've read the NTPv4 specification and it's written that root delay is the total round-trip delay to the reference clock.

If I'm working with a secondary server, root delay can be calculated from the time difference between the timestamps when making the packet requests with the reference server (am I correct?).

But I'm not sure what to fill it with if I'm using a GPS Receiver as the reference clock, should I fill it with 0 instead?

答:
It will depend largely on how you're setting the time in your server from the GPS. If you're reading the NMEA sentence, interpreting it and setting the clock, the root delay would be the time taken to do that. But it wouldn't be a very good clock; there's a lot of non-deterministic delays (jitter) involved in reading RS232 (assuming that is how you're connected to the GPS).

You can use the 1 pulse per second output of a GPS receiver to fix that. It's normally on the Data Carrier Detect pin. Using a proper RS232 port (not a USB one) you can have the server's clock synchronised to that (DCD can be used to raise an interrupt), so now you get very good alignment to GPS time. This could certainly be done in Solaris (a native part of the kernel), and in Linux too (http://support.ntp.org/bin/view/Support/ConfiguringNMEARefclocks). If you're doing this then I think that the root delay would be small, but there's the matter of the OS and hardware's response time to interrupts.

EDIT

According to this NTP docs page,

Root Delay

This is the total roundtrip delay to the primary reference source at
  the root of the synchronization subnet, in seconds. Note that this
  variable can take on both positive and negative values, depending on
  clock Precision and Skew.

So with 1PPS it's going to be pretty low. So far as I can tell it's a field that a secondary NTP server uses to tell its clients what its delay to a reference clock is. So if you have a 1PPS locked GPS time source, you are a reference clock. In which case, perhaps zero is correct enough; I don't think that NTP can achieve cross-network time synchronisation accuracies (1ms at best) better than the IRQ response time of a computer (< 50us hopefully with a good CONFIG_PREEMPT_RT linux kernel with nothing else going on).


问:
setInterval() does not works in codeigniter
setInterval() function works perfectly on corePHP, but the function have no response in codeigniter. I want to get data from another controller without reload the page

CONTROLLERS

home.php

```<code><?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Home extends CI_Controller{
    public function index(){
         $this->load->view('home_view');
    }
}
?>
</code>```

new1.php

```<code><?php
    defined('BASEPATH') OR exit('No direct script access allowed');

    class New1 extends CI_Controller{
        public function index(){
            echo time()."-Time";
        }
    }
?>
</code>```

home_view.php

```<code><!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
  function sendMail(){
    xmlhttp = new XMLHttpRequest();
    xmlhttp.open("GET","<?php echo site_url('new1/'); ?>",false);
    xmlhttp.send(null);
    document.getElementById("getdata").innerHTML=xmlhttp.responseText;
  }
  sendMail();
 setInterval(function(){ sendMail(); },2000);
   </script>
</head>
<body>
<div id="getdata"></div>
</body>
</html>
</code>```

答:
your error is you are redirecting to a view file. you have to create a controller and function

home.php

```<code><?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Home extends CI_Controller{
    public function index(){
         $this->load->view('home_view');
    }
}
?>
</code>```

home_view.php

```<code><body>

        <div id="getdata"></div>
        <script>
            function sendMail() {
                 xmlhttp = new XMLHttpRequest();
                 xmlhttp.open("GET","<?php echo site_url('Ajax/sendmail'); ?>",false);
                 xmlhttp.send(null);
//                 console.log(xmlhttp.responseText);
//                document.getElementById("getdata").innerHTML = Date();
                document.getElementById("getdata").innerHTML = xmlhttp.responseText;
            }
            //sendMail();
            setInterval(function () {
                sendMail();
            }, 2000);
        </script>
    </body>
</code>```

Ajax.php (A controller page)

```<code><?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Ajax extends CI_Controller {

    /**
     * Index Page for this controller.
     *
     * Maps to the following URL
     *      http://example.com/index.php/welcome
     *  - or -
     *      http://example.com/index.php/welcome/index
     *  - or -
     * Since this controller is set as the default controller in
     * config/routes.php, it's displayed at http://example.com/
     *
     * So any other public methods not prefixed with an underscore will
     * map to /index.php/welcome/<method_name>
     * @see https://codeigniter.com/user_guide/general/urls.html
     */
    public function sendmail()
    {
//      $this->load->view('y');
            echo  'testing';
    }
}
</code>```

Also you have to set base_url in the config file.
config->config.php
set  $config['base_ulr'] to something like that

```<code>$config['base_url'] = 'http://localhost/test/';
</code>```

Body:
setInterval() function works perfectly on corePHP, but the function have no response in codeigniter. I want to get data from another controller without reload the page

CONTROLLERS

home.php

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Home extends CI_Controller{
    public function index(){
         $this->load->view('home_view');
    }
}
?>

new1.php

<?php
    defined('BASEPATH') OR exit('No direct script access allowed');

    class New1 extends CI_Controller{
        public function index(){
            echo time()."-Time";
        }
    }
?>

home_view.php

<!DOCTYPE html>

Body:
your error is you are redirecting to a view file. you have to create a controller and function

home.php

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Home extends CI_Controller{
    public function index(){
         $this->load->view('home_view');
    }
}
?>

home_view.php

<body>

        <div id="getdata"></div>
        <script>
            function sendMail() {
                 xmlhttp = new XMLHttpRequest();
                 xmlhttp.open("GET","<?php echo site_url('Ajax/sendmail'); ?>",false);
                 xmlhttp.send(null);
//                 console.log(xmlhttp.responseText);
//                document.getElementById("getdata").innerHTML = Date();
                document.getElementById("getdata").innerHTML = xmlhttp.responseText;
            }
            //sendMail();
            setInterval(function () {
                sendMail();
            }, 2000);
        </script>
    </body>

Ajax.php (A controller page)

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Ajax extends CI_Controller {

    /**
     * Index Page for this controller.
     *
     * Maps to the following URL
     *      http://example.com/index.php/welcome
     *  - or -
     *      http://example.com/index.php/welcome/index
     *  - or -
     * Since this controller is set as the default controller in
     * config/routes.php, it's displayed at http://example.com/
     *
     * So any other public methods not prefixed with an underscore will
     * map to /index.php/welcome/<method_name>
     * @see https://codeigniter.com/user_guide/general/urls.html
     */
    public function sendmail()
    {
//      $this->load->view('y');
            echo  'testing';
    }
}

Also you have to set base_url in the config file.
config->config.php
set  $config['base_ulr'] to something like that

$config['base_url'] = 'http://localhost/test/';


问:
If else statement depending on textfield (swif3)
I would like my code to simply display a label if and only if there is text in the textfiled if there is no text the label should be hidden. Thats it. My code below does not do what I have described above.</p>

```<code>   import UIKit
class ViewController: UIViewController {

  @IBOutlet var label: UILabel!
  @IBOutlet var txtfield: UITextField!
 override func viewDidLoad() {
super.viewDidLoad()
appear()

  }
   func appear() {

if (txtfield.text?.isEmpty)! {
    label.isHidden = true

}
else {
    label.isHidden = false
}}}
</code>```

答:
Use the code below .

```<code> override func viewWillAppear(_ animated: Bool)
    {
        textChanged(txtField)
    }

    func textChanged(_ textField: UITextField) {

        if textField.text == ""
        {
            textField.isHidden = true
        }
        else
        {
            textField.isHidden = false
        }
        print("Hello")
    }

    override func viewDidLoad()
    {
        super.viewDidLoad()
        txtField.addTarget(self, action: #selector(textChanged(_:)),for: .allEvents)
    }
</code>```

func textChanged will hide your textField if it is empty .

Adding it to viewWillAppear will check textField at the screen appearing time .

In viewDidLoad target (textChanged) is added to textField for every events .

Body:
I would like my code to simply display a label if and only if there is text in the textfiled if there is no text the label should be hidden. Thats it. My code below does not do what I have described above.

   import UIKit
class ViewController: UIViewController {

  @IBOutlet var label: UILabel!
  @IBOutlet var txtfield: UITextField!
 override func viewDidLoad() {
super.viewDidLoad()
appear()

  }
   func appear() {

if (txtfield.text?.isEmpty)! {
    label.isHidden = true

}
else {
    label.isHidden = false
}}}

Body:
Use the code below .

 override func viewWillAppear(_ animated: Bool)
    {
        textChanged(txtField)
    }

    func textChanged(_ textField: UITextField) {

        if textField.text == ""
        {
            textField.isHidden = true
        }
        else
        {
            textField.isHidden = false
        }
        print("Hello")
    }

    override func viewDidLoad()
    {
        super.viewDidLoad()
        txtField.addTarget(self, action: #selector(textChanged(_:)),for: .allEvents)
    }

func textChanged will hide your textField if it is empty .

Adding it to viewWillAppear will check textField at the screen appearing time .

In viewDidLoad target (textChanged) is added to textField for every events .


问:
How to deal with cp932 encoding error trying to print the filename by file list
I am working on a script that randomly chooses a file and asks the user whether to execute it. I recently got the error shown below, and I'm confused about how to change my script to fix this.

```<code>Traceback (most recent call last):
File ".\randomplay.py", line 33, in <module>
    print(file)
UnicodeEncodeError: 'cp932' codec can't encode character '\u8138' in position 1: illegal multibyte sequence
</code>```

The code below works in Python 2.x. However, I'm required to implement this function in Python 3.x. Can anyone advise me how to do it? I want to make it work the same as before.

```<code>import sys
import os,io
import random
import subprocess
import msvcrt

if __name__ == '__main__':
    indir = os.path.realpath("./")
    for root, dirs, files in os.walk(indir):
        random.shuffle(files)
        #print(files)
        for file in files:
            cmd="\""+file+"\""
            print(file)
            print("OK with it?")
            c = msvcrt.getch()
            print(str(ord(c)))
            if ord(c) == 27:
                exit()
            elif ord(c) == 13:
                print("executing...")
                subprocess.Popen(cmd,shell=True)
                exit()
            else:
                print("How about this?")
                pass
</code>```

答:
By @eryksun

By upgrading python to 3.6.X seems to be the most fast way to deal with this problem without change any script!
Now it works!

Thanks!

Body:
I am working on a script that randomly chooses a file and asks the user whether to execute it. I recently got the error shown below, and I'm confused about how to change my script to fix this.

Traceback (most recent call last):
File ".\randomplay.py", line 33, in <module>
    print(file)
UnicodeEncodeError: 'cp932' codec can't encode character '\u8138' in position 1: illegal multibyte sequence

The code below works in Python 2.x. However, I'm required to implement this function in Python 3.x. Can anyone advise me how to do it? I want to make it work the same as before.

import sys
import os,io
import random
import subprocess
import msvcrt

if __name__ == '__main__':
    indir = os.path.realpath("./")
    for root, dirs, files in os.walk(indir):
        random.shuffle(files)
        #print(files)
        for file in files:
            cmd="\""+file+"\""
            print(file)
            print("OK with it?")
            c = msvcrt.getch()
            print(str(ord(c)))
            if ord(c) == 27:
                exit()
            elif ord(c) == 13:
                print("executing...")
                subprocess.Popen(cmd,shell=True)
                exit()
            else:
                print("How about this?")
                pass


答:
You can send User object in request body using @Body annotation

Roughly it would look like this:

Your User Model

```<code>class User {
}
</code>```

Users class which stores the list of Users

```<code>class RequestBody {
int data_id;
String data_provider;
List<User> users;
}

@POST("api/users/submit.json")
Call<UserData> submitData(@Body RequestBody requestbody);
</code>```

You can read more about it in details here:

https://futurestud.io/tutorials/retrofit-send-objects-in-request-body

Title: Retrofit2 - Sending Array of Type T in a GET request

Body:
You can send User object in request body using @Body annotation

Roughly it would look like this:

Your User Model

class User {
}

Users class which stores the list of Users

class RequestBody {
int data_id;
String data_provider;
List<User> users;
}

@POST("api/users/submit.json")
Call<UserData> submitData(@Body RequestBody requestbody);

You can read more about it in details here:

https://futurestud.io/tutorials/retrofit-send-objects-in-request-body


问:
How to set the textBox position Using Relative position?
In listbox contains multiple listitem, it will show first 5 record in listbox based on listbox height. If I scroll the listbox item 7th record or any in first position.  if user scroll the listboxitem, I need to find out the listbox selected item which position is visible(with in 5 records displaying in listbox based on height)

Edit:

```<code>lstbxindex.ItemContainerGenerator.ContainerFromItem(lstbxindex.SelectedItem);

            System.Windows.Point relativePoint = lstbxindex.TransformToVisual(listBoxItem)
                               .Transform(new System.Windows.Point(0, 0));
</code>```

Using this code I got the relative position of listbox selecteditem. if user scroll the listbox item after scroll need to overlay the textbox to the particular selected item position in listbox. So I check the condition like,

```<code>Listbox firstItem x=-2,y-2
Listbox secondItem x=-2,y=-56
Listbox thirdItem x=-2,y=-110
etc
relative position y increasing 54.
</code>```

so I check

```<code>if(relativePoint.Y==56)
{
**//how to set the textbox to that relative position in listbox**
}
</code>```

答:
In winforms you could access the top visible item by using Listbox.TopIndex Property please check whether it is implemented in WPF !! below is the sample code in WINFORM App.</p>

```<code>lstbxindex.Items[lstbxindex.TopIndex].ToString()
</code>```

Body:
In listbox contains multiple listitem, it will show first 5 record in listbox based on listbox height. If I scroll the listbox item 7th record or any in first position.  if user scroll the listboxitem, I need to find out the listbox selected item which position is visible(with in 5 records displaying in listbox based on height)

Edit:

lstbxindex.ItemContainerGenerator.ContainerFromItem(lstbxindex.SelectedItem);

            System.Windows.Point relativePoint = lstbxindex.TransformToVisual(listBoxItem)
                               .Transform(new System.Windows.Point(0, 0));

Using this code I got the relative position of listbox selecteditem. if user scroll the listbox item after scroll need to overlay the textbox to the particular selected item position in listbox. So I check the condition like,

Listbox firstItem x=-2,y-2
Listbox secondItem x=-2,y=-56
Listbox thirdItem x=-2,y=-110
etc
relative position y increasing 54.

so I check

if(relativePoint.Y==56)
{
**//how to set the textbox to that relative position in listbox**
}

Body:
In winforms you could access the top visible item by using Listbox.TopIndex Property please check whether it is implemented in WPF !! below is the sample code in WINFORM App.

lstbxindex.Items[lstbxindex.TopIndex].ToString()


问:
How can I make manage screen behave like android singleTask mode?
Suppose the following screens:

AScreen --> BScreen --> CScreen --> ASreen

Then use the back action go into home (identical on Android and IoS).

How can I make this behave like android's singleTask mode, when using:

("react-navigation": "^1.0.0-beta.11" )

答:
You can use react navigation to achieve this.

Use navigate for navigation to screens A and B. Then on Screen C you can use Backhandler to catch the back button press. Then reset the router which will pop the existing screens except the root (that is screen A).

The reset code would look like this:

```<code>import { NavigationActions } from 'react-navigation'

const resetAction = NavigationActions.reset({
  index: 0,
  actions: [
    NavigationActions.navigate({ routeName: 'Profile'}),
    NavigationActions.navigate({ routeName: 'Settings'})
  ]
})
this.props.navigation.dispatch(resetAction)
</code>```

Setting index to 0 will reset it to Profile. Setting it to 1 will reset to Settings Page. See the documentation on navigation actions.

Body:
You can use react navigation to achieve this.

Use navigate for navigation to screens A and B. Then on Screen C you can use Backhandler to catch the back button press. Then reset the router which will pop the existing screens except the root (that is screen A).

The reset code would look like this:

import { NavigationActions } from 'react-navigation'

const resetAction = NavigationActions.reset({
  index: 0,
  actions: [
    NavigationActions.navigate({ routeName: 'Profile'}),
    NavigationActions.navigate({ routeName: 'Settings'})
  ]
})
this.props.navigation.dispatch(resetAction)

Setting index to 0 will reset it to Profile. Setting it to 1 will reset to Settings Page. See the documentation on navigation actions.


问:
How to convert Base64 data and NSData into string
i am new in IOS and i am making a project in which i receive Base64 data from web service. how to convert Base64 data into string and how to open a pdf view in swift and also check that is there any pdf owner application install or not in iPhone .and i want to know that how to convert NSDATA in string swift.Help me
example like this is Base64 data
JVBERi0xLjQKJcfsj6IKNSAwIG9iago8PC9MZW5ndGggNiAwIFIvRmlsdGVyIC9GbGF0ZURlY29kZT4+CnN0cmVhbQp4nLVcza8ct5GH1rK9ejIU24lkO5GtJ8vWm5E87eY3uXtbYLHAYi8JdItySrABAjhA8v8fUuwmu35kF2fmxbsWDMxjk8VisapYX+TfbudJ6ds5/6s//vj

Like this is nsdata
<25504446 2d312e34 0a25c7ec 8fa20a35 2030206f 626a0a3c 3c2f4c65 6e677468 20362030 20522f46 696c7465 72202f46 6c617465 4465636f 64653e3e 0a737472 65616d0a 789cb55c cdaf1cb7 9187d6b2 bd7a3214 db89643b 91ad27cb d69b913c

答:
There are two parts to this question. First, converting the base 64 string into a Data/NSData. But you've done that already, so you don't need help there.

Second, converting that Data/NSData into a string. But, if you look at that file carefully, you'll see that data is a PDF file, not a text string. For example, if I save that as a file and look at it in a hex editor, I can clearly see it's a PDF:

You can't just convert that PDF binary data to a string. (In fact, that's why it was base64-encoded in the first place, because it was complex binary data.)

But you can, for example, use UIDocumentInteractionController to preview the PDF file that you saved to a file.

For example:

```<code>// convert base 64 string to data

let base64 = "JVBERi0xLjQKJcfsj6IKNSAwIG9iago8PC9MZW5ndGggNiAwIFIvRmlsdGVyIC9GbGF0ZURlY29kZT4+CnN0cmVhbQp4nLVcza8ct5GH1rK9ejIU24lkO5GtJ8vWm5E87eY3uXtbYLHAYi8JdItySrABAjhA8v8fUuwmu35kF2fmxbsWDMxjk8VisapYX+TfbudJ6ds5/6s/"
guard let data = Data(base64Encoded: base64) else {
    print("unable to convert base 64 string to data")
    return
}

// given the data was PDF, let's save it as such

let fileURL = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
    .appendingPathComponent("test.pdf")
try! data.write(to: fileURL)

// if it was a string, you could convert the data to string, but this will fail
// because the data is a PDF, not a text string
//
// guard let string = String(data: data, encoding: .utf8) else {
//     print("Unable to convert data into string")
//     return
// }
// print(string)

// So, instead, let's use `UIDocumentInteractionController` to preview the PDF:

let controller = UIDocumentInteractionController(url: fileURL)
controller.delegate = self
controller.presentPreview(animated: true)
</code>```

Where, the view controller conforms to UIDocumentInteractionControllerDelegate:

```<code>extension ViewController: UIDocumentInteractionControllerDelegate {

    func documentInteractionControllerViewControllerForPreview(_ controller: UIDocumentInteractionController) -> UIViewController {
        return self

        // or, if this view controller is already in navigation controller, don't
        // return `self`, like above, but instead return the navigation controller itself
        //
        // return navigationController!
    }

}
</code>```

Body:
There are two parts to this question. First, converting the base 64 string into a Data/NSData. But you've done that already, so you don't need help there.

Second, converting that Data/NSData into a string. But, if you look at that file carefully, you'll see that data is a PDF file, not a text string. For example, if I save that as a file and look at it in a hex editor, I can clearly see it's a PDF:

You can't just convert that PDF binary data to a string. (In fact, that's why it was base64-encoded in the first place, because it was complex binary data.)

But you can, for example, use UIDocumentInteractionController to preview the PDF file that you saved to a file.

For example:

// convert base 64 string to data

let base64 = "JVBERi0xLjQKJcfsj6IKNSAwIG9iago8PC9MZW5ndGggNiAwIFIvRmlsdGVyIC9GbGF0ZURlY29kZT4+CnN0cmVhbQp4nLVcza8ct5GH1rK9ejIU24lkO5GtJ8vWm5E87eY3uXtbYLHAYi8JdItySrABAjhA8v8fUuwmu35kF2fmxbsWDMxjk8VisapYX+TfbudJ6ds5/6s/"
guard let data = Data(base64Encoded: base64) else {
    print("unable to convert base 64 string to data")
    return
}

// given the data was PDF, let's save it as such

let fileURL = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
    .appendingPathComponent("test.pdf")
try! data.write(to: fileURL)

// if it was a string, you could convert the data to string, but this will fail
// because the data is a PDF, not a text string
//
// guard let string = String(data: data, encoding: .utf8) else {
//     print("Unable to convert data into string")
//     return
// }
// print(string)

// So, instead, let's use `UIDocumentInteractionController` to preview the PDF:

let controller = UIDocumentInteractionController(url: fileURL)
controller.delegate = self
controller.presentPreview(animated: true)

Where, the view controller conforms to UIDocumentInteractionControllerDelegate:

extension ViewController: UIDocumentInteractionControllerDelegate {

    func documentInteractionControllerViewControllerForPreview(_ controller: UIDocumentInteractionController) -> UIViewController {
        return self

        // or, if this view controller is already in navigation controller, don't
        // return `self`, like above, but instead return the navigation controller itself
        //
        // return navigationController!
    }

}


问:
Redirect all urls exactly, just change domain name
I have a website with roughly 1K URLs. The website is moving to a different domain name. The URLs will be the exact same though, otherwise. I'd like to incorporate an htaccess or some kind of rule that does a 301 redirect for all URLs in one fell swoop. It would essentially replace the domain name as a 301 redirect.

Example:

Current URL:  domain.example/blog/post-1.html

Redirect To:  newdomain.example/blog/post-1.html

And that performed as a 301 redirect. How would I do that?

答:
With www or without

RewriteEngine On

RewriteCond %{HTTP_HOST} (w*)domain\.example$ [NC]
RewriteRule ^ http://newdomain.example%{REQUEST_URI} [L,R=301]
```

ContentLicense: CC BY-SA 4.0


问:
Transform Observable<any> to Observable<any[]>
iam working on an ionic3 app using the firebase real time database. Therefore i use angularfire2. The app allows an user to store links. A link consists of an url and associated tags. This is how my database structure looks like:

All links are located at /links/.
For an user the links are stored as referencing keys, located at /users/this.user/links/.

In the view i want to list all links of a certain user.
Template detail:

```<code>   <ion-item *ngFor="let item of items | async">
      <h3>{{item.url}}</h3>
      <!-- TODO: add tags and other meta information -->
    </ion-item>
</code>```

This is what happens in the components constructor:

```<code>this.items = this.db.list('/users/' + this.user + '/links/')
    .flatMap(x => x)
    .flatMap(x => {
        let y: any = x;
        return this.db.list('/links/' + y.$key);
    })
    .map(res => {
        let url: string;
        let tags: string[] = [];

        for (let r of res) {

                // filter out tags
                if (r.$key === 'tags') {
                    for (let key in r)
                        if (key) tags.push(key);
                }

                // filter out url
                if (r.$key === 'url') {
                    for (let key in r) {
                        url = r[key];
                        break;
                    }
                }
            }
        } // for (let r of res)

        let link: Link = new Link(url, tags);
        return link;
    });

this.items.subscribe(res => {
    console.log(res);
});
</code>```

This way my final observable emits the users link objects. The console.log(res) in the component subscription shows the desired result:

But since i emit Link objects Angular tells me that ngFor only supports iterables:

Finally, my questions are:

How can i transform the items observable to something iterable by ngFor in the template?

Is there a better way of using rxjs operators to do my desired filtering?

Thanks a lot in advance!

答:
This is how you need to do it in Rx. I am assuming you want to get rid of all the data in the response and only get tags and url </p>

```<code>const linkFromRaw = linkList => linkList
    .map(linkResponse => new Link(linkResponse.url, linkResponse.tags);

const linkToDetail = link => this.db.list('/links/' + link.$key))

this.items = this.db.list('/users/' + this.user + '/links/')
  .flatMap( links => Observable.forkJoin(links.map(linkToDetail))
     .reduce(
       (finalResponse, linkResponseArr) =>[...finalResponse, ...linkResponseArr],
       []
     )
  )
  .map(links => links.map(linkFromRaw));
</code>```

Body:
iam working on an ionic3 app using the firebase real time database. Therefore i use angularfire2. The app allows an user to store links. A link consists of an url and associated tags. This is how my database structure looks like:

All links are located at /links/.
For an user the links are stored as referencing keys, located at /users/this.user/links/.

In the view i want to list all links of a certain user.
Template detail:

   <ion-item *ngFor="let item of items | async">

{{item.url}}

    </ion-item>

This is what happens in the components constructor:

this.items = this.db.list('/users/' + this.user + '/links/')
    .flatMap(x => x)
    .flatMap(x => {
        let y: any = x;
        return this.db.list('/links/' + y.$key);
    })
    .map(res => {
        let url: string;
        let tags: string[] = [];

        for (let r of res) {

                // filter out tags
                if (r.$key === 'tags') {
                    for (let key in r)
                        if (key) tags.push(key);
                }

                // filter out url
                if (r.$key === 'url') {
                    for (let key in r) {
                        url = r[key];
                        break;
                    }
                }
            }
        } // for (let r of res)

        let link: Link = new Link(url, tags);
        return link;
    });

this.items.subscribe(res => {
    console.log(res);
});

This way my final observable emits the users link objects. The console.log(res) in the component subscription shows the desired result:

But since i emit Link objects Angular tells me that ngFor only supports iterables:

Finally, my questions are:

How can i transform the items observable to something iterable by ngFor in the template?

Is there a better way of using rxjs operators to do my desired filtering?

Thanks a lot in advance!

Body:
This is how you need to do it in Rx. I am assuming you want to get rid of all the data in the response and only get tags and url

const linkFromRaw = linkList => linkList
    .map(linkResponse => new Link(linkResponse.url, linkResponse.tags);

const linkToDetail = link => this.db.list('/links/' + link.$key))

this.items = this.db.list('/users/' + this.user + '/links/')
  .flatMap( links => Observable.forkJoin(links.map(linkToDetail))
     .reduce(
       (finalResponse, linkResponseArr) =>[...finalResponse, ...linkResponseArr],
       []
     )
  )
  .map(links => links.map(linkFromRaw));


问:
Tmux window or pane name won't change in GNOME Terminal
Using Fedora 25 and GNOME Terminal. I have used Tmux for a few years in Ubuntu with a long customized .tmux.conf file. Recently installed Tmux and Tmuxinator in Fedora.

When I open the Terminal. I see that the title is set to tom@localhost:~. When I create a new Tmux session such as tmux new -s panes. The title of the pane is still tom@localhost:~.

Inside the Tmux session. When I open a new window with name console like this new-window -n console. The title won't change to console and keeps saying tom@localhost:~.

I thought maybe tmux is not overriding the titles so I added this to the tmux.conf file:

```<code>set-option -g set-titles on
set -g terminal-overrides "xterm*:XT:smcup@:rmcup@"
</code>```

That still doesn't do anything.

The Terminal settings. I have Profile/Command/When terminal commands set their own titles set to Replace initial title.

I cannot figure this out. What am I doing wrong here?

答:
I am not exactly sure why it works. But this solves my problem.

Inside the .tmux.conf file I added the line set-option -g allow-rename off. At the top of the file I had the line set -g default -terminal "xterm". I removed this line.

Body:
Using Fedora 25 and GNOME Terminal. I have used Tmux for a few years in Ubuntu with a long customized .tmux.conf file. Recently installed Tmux and Tmuxinator in Fedora.

When I open the Terminal. I see that the title is set to tom@localhost:~. When I create a new Tmux session such as tmux new -s panes. The title of the pane is still tom@localhost:~.

Inside the Tmux session. When I open a new window with name console like this new-window -n console. The title won't change to console and keeps saying tom@localhost:~.

I thought maybe tmux is not overriding the titles so I added this to the tmux.conf file:

set-option -g set-titles on
set -g terminal-overrides "xterm*:XT:smcup@:rmcup@"

That still doesn't do anything.

The Terminal settings. I have Profile/Command/When terminal commands set their own titles set to Replace initial title.

I cannot figure this out. What am I doing wrong here?


问:
Is faster than 10 screenshots per second possible with Python?
Right now I'm in need of a really fast screenshotter to feed screenshot into a CNN that will update mouse movement based on the screenshot. I'm looking to model the same kind of behavior presented in this paper, and similarly do the steps featured in Figure 6 (without the polar conversion). As a result of needing really fast input, I've searched around a bit and have been able to get this script from here slightly modified that outputs 10fps

```<code>from PIL import ImageGrab
from datetime import datetime

while True:
    im = ImageGrab.grab([320, 180, 1600, 900])
    dt = datetime.now()
    fname = "pic_{}.{}.png".format(dt.strftime("%H%M_%S"), dt.microsecond // 100000)
    im.save(fname, 'png')
</code>```

Can I expect anything faster? I'd be fine with using a different program if it's available.

答:
Writing to disk is very slow, and is probably a big part of what's making your loop take so long. Try commenting out the im.save() line and seeing how many screenshots can be captured (add a counter variable or something similar to count how many screenshots are being captured).

Assuming the disk I/O is the bottleneck, you'll want to split these two tasks up. Have one loop that just captures the screenshots and stores them in memory (e.g. to a dictionary with the timestamp as the key), then in a separate thread pull elements out of the dictionary and write them to disk.

See this question for pointers on threading in Python if you haven't done much of that before.

Body:
Right now I'm in need of a really fast screenshotter to feed screenshot into a CNN that will update mouse movement based on the screenshot. I'm looking to model the same kind of behavior presented in this paper, and similarly do the steps featured in Figure 6 (without the polar conversion). As a result of needing really fast input, I've searched around a bit and have been able to get this script from here slightly modified that outputs 10fps

from PIL import ImageGrab
from datetime import datetime

while True:
    im = ImageGrab.grab([320, 180, 1600, 900])
    dt = datetime.now()
    fname = "pic_{}.{}.png".format(dt.strftime("%H%M_%S"), dt.microsecond // 100000)
    im.save(fname, 'png')

Can I expect anything faster? I'd be fine with using a different program if it's available.


问:
Align vertical text next to the image
I'm trying to create exactly like what is shown in the picture below. So far, it's not looking good for me.

Here's the JSFiddle: https://jsfiddle.net/6o3nz6g9/

HTML:

```<code><h1>This is Sparta!</h1>
<div class="container">
<div class="row">
    <div class="col-xs-4">
        <div class="services__text">Title Text Here</div>
        <img src="https://image.ibb.co/hccDVF/sample.jpg" class="img-responsive" alt=""/>
    </div>
    <div class="col-xs-4">
        <div class="services__text">Title Text Here</div>
        <img src="https://image.ibb.co/hccDVF/sample.jpg" class="img-responsive" alt=""/>
    </div>
  <div class="col-xs-4">
        <div class="services__text">Title Text Here</div>
        <img src="https://image.ibb.co/hccDVF/sample.jpg" class="img-responsive" alt=""/>
    </div>
</div>
</div>
</code>```

CSS:

```<code>.services__text {
    -ms-transform: rotate(-90deg);
    -moz-transform: rotate(-90deg);
    -webkit-transform: rotate(-90deg);
    transform: rotate(-90deg);
    -ms-transform-origin: right top 0;
    -moz-transform-origin: right top 0;
    -webkit-transform-origin: right top 0;
    transform-origin: right top 0;
    padding: 10px;
    float: left;
}
</code>```

How do I do to get this desired effect? FYI: I'm working on Bootstrap framework.

答:
You can change positioning of .services__text and then using translate align that before image.

.services__text {
  position: absolute;
  left: 0;
  top: 0;
  transform: rotate(-90deg) translate(-40%, -200%);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<h1>This is Sparta!</h1>
<div class="container">
  <div class="row">
    <div class="col-xs-4">
      <div class="services__text">Title Text Here</div>
      <img src="https://image.ibb.co/hccDVF/sample.jpg" class="img-responsive" alt="" />
    </div>
    <div class="col-xs-4">
      <div class="services__text">Title Text Here</div>
      <img src="https://image.ibb.co/hccDVF/sample.jpg" class="img-responsive" alt="" />
    </div>
    <div class="col-xs-4">
      <div class="services__text">Title Text Here</div>
      <img src="https://image.ibb.co/hccDVF/sample.jpg" class="img-responsive" alt="" />
    </div>
  </div>
</div></code>```

Title: Align vertical text next to the image

Body:
I'm trying to create exactly like what is shown in the picture below. So far, it's not looking good for me.

Here's the JSFiddle: https://jsfiddle.net/6o3nz6g9/

HTML:

This is Sparta!

Title Text Here

Title Text Here

Title Text Here

CSS:

.services__text {
    -ms-transform: rotate(-90deg);
    -moz-transform: rotate(-90deg);
    -webkit-transform: rotate(-90deg);
    transform: rotate(-90deg);
    -ms-transform-origin: right top 0;
    -moz-transform-origin: right top 0;
    -webkit-transform-origin: right top 0;
    transform-origin: right top 0;
    padding: 10px;
    float: left;
}

How do I do to get this desired effect? FYI: I'm working on Bootstrap framework.

Body:
You can change positioning of .services__text and then using translate align that before image.

.services__text {
  position: absolute;
  left: 0;
  top: 0;
  transform: rotate(-90deg) translate(-40%, -200%);
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<h1>This is Sparta!</h1>
<div class="container">
  <div class="row">
    <div class="col-xs-4">
      <div class="services__text">Title Text Here</div>
      <img src="https://image.ibb.co/hccDVF/sample.jpg" class="img-responsive" alt="" />
    </div>
    <div class="col-xs-4">
      <div class="services__text">Title Text Here</div>
      <img src="https://image.ibb.co/hccDVF/sample.jpg" class="img-responsive" alt="" />
    </div>
    <div class="col-xs-4">
      <div class="services__text">Title Text Here</div>
      <img src="https://image.ibb.co/hccDVF/sample.jpg" class="img-responsive" alt="" />
    </div>
  </div>
</div>


问:
How to show form validation message for particular field in codeigniter
Here I want to show validation message for different fields

```<code>$this->form_validation->set_rules('email','Email','trim|required|valid_email');
$this->form_validation->set_rules('password', 'Password', 'required');

if ($this->form_validation->run('email') == FALSE)
        {
            print_r('Enter email');
        }

if ($this->form_validation->run('password') == FALSE)
        {
            print_r('Enter password ');
        }
</code>```

if i give password and leave email field empty, both messages are showing in rest api

Can anyone help me

答:
```<code>if($this->form_validation->run()==FALSE){
             $errors = $this->form_validation->error_array();
             echo json_encode($errors);
        }
</code>```

The above code also works fine, it also shows the correct error messages in rest server codeigniter

Body:
Here I want to show validation message for different fields

$this->form_validation->set_rules('email','Email','trim|required|valid_email');
$this->form_validation->set_rules('password', 'Password', 'required');

if ($this->form_validation->run('email') == FALSE)
        {
            print_r('Enter email');
        }

if ($this->form_validation->run('password') == FALSE)
        {
            print_r('Enter password ');
        }

if i give password and leave email field empty, both messages are showing in rest api

Can anyone help me

Body:
if($this->form_validation->run()==FALSE){
             $errors = $this->form_validation->error_array();
             echo json_encode($errors);
        }

The above code also works fine, it also shows the correct error messages in rest server codeigniter


问:
Menu bar Malfunctioning with AngularJs
I am bit new to AngularJs so I have got stuck into the problem.
Let me explain what I want to achieve.

I have design two div with child and parent relation.

```<code>  // first parent div
 <div>
    <div>
        child div  // show/hide content of this div
    </div>

</div>

 // second parent div
<div>
    <div>
        child div  // show/hide content of this div
    </div>

</div>
</code>```

When I hover or move the mouse over parent  div  it should hide/show the respective child div.

But with my code on hover it hides/shows the content of both the child div.What changes do I have to do in code?

See complete code

```<code><body ng-app="app">
 <div ng-app="headermain" ng-controller="headerController">
    <div class="top-menu col-xs-36 ">

           // parent div one

        <div class="menu-item col-xs-6"  ng-mouseover="hoverIn()" style="background-color:pink">
            <span >Parent one</span>

            // child div, want to hide/show content of this div

            <div class="drop-down;col-xs-10" ng-show="showMe" ng-mouseleave="hoverOut()" style="background-color:pink">
                <ul>
                    <li>child one details</li>
                    <li>parent one detail</li>
                </ul>
            </div>

        </div>

          // parent div two
        <div class="menu-item col-xs-6" ng-mouseover="hoverIn()">
            <span >Parent two</span>

                 // child div, want to hide/show content of this div

            <div class="drop-down;col-xs-10" ng-show="showMe" ng-mouseleave="hoverOut()">
                <ul>
                    <li>child two  Details</li>
                    <li>parent two detail</li>
                </ul>
            </div>

        </div>

    </div>

</div>
</code>```

Controller for this code, see below

```<code> var app = angular.module("app", []);
 app.controller("headerController",function($scope){

    $scope.hoverIn = function(){
   this.showMe = true;

      };

    $scope.hoverOut = function(){
    this.showMe = false;
      };

 });
</code>```

Css file

```<code>    .top-menu {
overflow: hidden;
 }

.top-menu .drop-down {

position: absolute;
top: 20px;
z-index: 10000;
background-color: white;
box-shadow: 0px 0px 3px rgb(241, 241, 241);
border: 1px solid #d1d1d1;
}

.top-menu .drop-down ul {
padding: 0px;
margin: 0px;
list-style-type: none;
min-width: 180px;
}
</code>```

答:
You have to change the name of your functions since both div's are using the same function and changing the same attribute showMe.

HTML:

```<code><body ng-app="app">
    <div ng-app="headermain" ng-controller="headerController">
        <div class="top-menu col-xs-36 ">

            // parent div one

            <div class="menu-item col-xs-6" ng-mouseover="hoverIn(1)" style="background-color:pink">
                <span>Parent one</span> // child div, want to hide/show content of this div

                <div class="drop-down;col-xs-10" ng-show="showMe[1]" ng-mouseleave="hoverOut(1)" style="background-color:pink">
                    <ul>
                        <li>child one details</li>
                        <li>parent one detail</li>
                    </ul>
                </div>

            </div>

            // parent div two
            <div class="menu-item col-xs-6" ng-mouseover="hoverIn(2)">
                <span>Parent two</span> // child div, want to hide/show content of this div

                <div class="drop-down;col-xs-10" ng-show="showMe[2]" ng-mouseleave="hoverOut(2)">
                    <ul>
                        <li>child two Details</li>
                        <li>parent two detail</li>
                    </ul>
                </div>

            </div>

        </div>

    </div>
</code>```

JS:

```<code>  $scope.showMe=[];
  $scope.hoverIn = function(id) {
         $scope.showMe[id] = true;
     };
     $scope.hoverOut = function() {
         $scope.showMe[id] = false;
     };
</code>```

Title: Menu bar Malfunctioning with AngularJs

Body:
I am bit new to AngularJs so I have got stuck into the problem.
Let me explain what I want to achieve.

I have design two div with child and parent relation.

  // first parent div

        child div  // show/hide content of this div

 // second parent div

        child div  // show/hide content of this div

When I hover or move the mouse over parent  div  it should hide/show the respective child div.

But with my code on hover it hides/shows the content of both the child div.What changes do I have to do in code?

See complete code

           // parent div one

            Parent one

            // child div, want to hide/show content of this div

child one details

parent one detail

          // parent div two

            Parent two

                 // child div, want to hide/show content of this div

child two  Details

parent two detail

Controller for this code, see below

 var app = angular.module("app", []);
 app.controller("headerController",function($scope){

    $scope.hoverIn = function(){
   this.showMe = true;

      };

    $scope.hoverOut = function(){
    this.showMe = false;
      };

 });

Css file

    .top-menu {
overflow: hidden;
 }

.top-menu .drop-down {

position: absolute;
top: 20px;
z-index: 10000;
background-color: white;
box-shadow: 0px 0px 3px rgb(241, 241, 241);
border: 1px solid #d1d1d1;
}

.top-menu .drop-down ul {
padding: 0px;
margin: 0px;
list-style-type: none;
min-width: 180px;
}

Body:
You have to change the name of your functions since both div's are using the same function and changing the same attribute showMe.

HTML:

<body ng-app="app">
    <div ng-app="headermain" ng-controller="headerController">
        <div class="top-menu col-xs-36 ">

            // parent div one

            <div class="menu-item col-xs-6" ng-mouseover="hoverIn(1)" style="background-color:pink">
                <span>Parent one</span> // child div, want to hide/show content of this div

                <div class="drop-down;col-xs-10" ng-show="showMe[1]" ng-mouseleave="hoverOut(1)" style="background-color:pink">
                    <ul>
                        <li>child one details</li>
                        <li>parent one detail</li>
                    </ul>
                </div>

            </div>

            // parent div two
            <div class="menu-item col-xs-6" ng-mouseover="hoverIn(2)">
                <span>Parent two</span> // child div, want to hide/show content of this div

                <div class="drop-down;col-xs-10" ng-show="showMe[2]" ng-mouseleave="hoverOut(2)">
                    <ul>
                        <li>child two Details</li>
                        <li>parent two detail</li>
                    </ul>
                </div>

            </div>

        </div>

    </div>

JS:

  $scope.showMe=[];
  $scope.hoverIn = function(id) {
         $scope.showMe[id] = true;
     };
     $scope.hoverOut = function() {
         $scope.showMe[id] = false;
     };


问:
Choosing a simple web application framework
I'm evaluating web application frameworks for a hobby project I'm starting, and am beginning to go crazy trying to decide among the vast number of frameworks available to choose. The framework language isn't helping me filter out frameworks as I have varying levels of experience with Java, Python, Ruby and C#, and don't mind frameworks in any of these languages. </p>

<p>I'm looking for help in narrowing the choice down to a few that I can then investigate in more detail. </p>

答:
rails is a good choice - it is simple for simple things, while allowing more complex things to be possible (always a good sign). There is a little bit of learning curve initially, but that's true of all frameworks.

If you're happier in Java, you could also look at Groovy + Grails, a very similar framework with a Java slant (groovy is kind of like a cross between java and ruby, and you can mix and match Java and Groovy classes in the same project).

OwnerDisplayName: nagul

ContentLicense: CC BY-SA 2.5

Body:
I'm evaluating web application frameworks for a hobby project I'm starting, and am beginning to go crazy trying to decide among the vast number of frameworks available to choose. The framework language isn't helping me filter out frameworks as I have varying levels of experience with Java, Python, Ruby and C#, and don't mind frameworks in any of these languages.

I'm looking for help in narrowing the choice down to a few that I can then investigate in more detail.

LastEditorDisplayName: Marko Dumic

OwnerDisplayName: frankodwyer


问:
select 10 parents with all of their childs
I have a simple table: id, parent_id, content

items with parent_id = 0 are parents, and items with parent_id > 0 are children

Now I want to select 10 parents with all of their children

With 2 query its simple to get parents in query 1 and then all children in query 2

but I want it be done in 1 query

I have written this, but it's not working:

```<code>select *
from blogs
where parent_id in (select id
                    from blogs
                    where parent_id = 0
                    order by id desc
                    limit 10)
union all
select *
from blogs
where parent_id = 0
order by id
desc limit 10
</code>```

答:
Please check below mentioned solution.

```<code>SELECT
    t1.id as parent_id,
    t1.content as parent,
    GROUP_CONCAT(t2.content) as children
from blogs t1
INNER JOIN blogs t2 ON t2.parent_id = t1.id
WHERE t1.parent_id = 0
GROUP BY t1.id
LIMIT 10;
</code>```

Please change table_name and field_name in above query.
Let me know if it not work for you.

Body:
I have a simple table: id, parent_id, content

items with parent_id = 0 are parents, and items with parent_id > 0 are children

Now I want to select 10 parents with all of their children

With 2 query its simple to get parents in query 1 and then all children in query 2

but I want it be done in 1 query

I have written this, but it's not working:

select *
from blogs
where parent_id in (select id
                    from blogs
                    where parent_id = 0
                    order by id desc
                    limit 10)
union all
select *
from blogs
where parent_id = 0
order by id
desc limit 10

Body:
Please check below mentioned solution.

SELECT
    t1.id as parent_id,
    t1.content as parent,
    GROUP_CONCAT(t2.content) as children
from blogs t1
INNER JOIN blogs t2 ON t2.parent_id = t1.id
WHERE t1.parent_id = 0
GROUP BY t1.id
LIMIT 10;

Please change table_name and field_name in above query.
Let me know if it not work for you.


问:
how to post account/update_profile_image in twitter c#
I am having trouble implementing Twitter's [update profile image] method. Does anyone have any sample code for passing an image as raw multiart data to the Twitter API?</p>

答:
Using the API directly for this is straightforward it only requires that you perform a POST request to the api endpoint and append the base64 of the image as the value of the image query string.

POST https://api.twitter.com/1.1/account/update_profile_image.json?image=base64data

Reading an image file and converting it to base64 is straightforward as well.

```<code>string base64Data = Convert.ToBase64String(File.ReadAllBytes("image.jpg"));
string url= "https://api.twitter.com/1.1/account/update_profile_image.json?image=" + base64Data
</code>```

The more complicated part is authenticating against the API in the first place. Assuming you are already doing that the code above will will satisfy your needs.

If not you need to look at a library or an SDK such as LinqToTwitter. There are numerous examples on the wiki.

If you are going to be manually coding the request, see the API documentation for how requests should be constucted: https://dev.twitter.com/oauth/overview/authorizing-requests

Using Tweetinvi: https://github.com/linvi/tweetinvi/

```<code>private class AuthCredentials
{
    public string ConsumerKey = "ConsumerKey";
    public string ConsumerSecret = "ConsumerSecret";
    public string AccessToken = "AccessToken";
    public string AccessTokenSecret = "AccessTokenSecret";
}

static void Main(string[] args)
{
    var creds = new AuthCredentials();
    Auth.SetUserCredentials(creds.ConsumerKey, creds.ConsumerSecret, creds.AccessToken, creds.AccessTokenSecret);
    var data = File.ReadAllText("myimage.jpg");
    Account.UpdateProfileImage(data);
}
</code>```

Twitter's API documents has a list of libraries for a variety of languages: https://dev.twitter.com/resources/twitter-libraries

Body:
Using the API directly for this is straightforward it only requires that you perform a POST request to the api endpoint and append the base64 of the image as the value of the image query string.

POST https://api.twitter.com/1.1/account/update_profile_image.json?image=base64data

Reading an image file and converting it to base64 is straightforward as well.

string base64Data = Convert.ToBase64String(File.ReadAllBytes("image.jpg"));
string url= "https://api.twitter.com/1.1/account/update_profile_image.json?image=" + base64Data

The more complicated part is authenticating against the API in the first place. Assuming you are already doing that the code above will will satisfy your needs.

If not you need to look at a library or an SDK such as LinqToTwitter. There are numerous examples on the wiki.

If you are going to be manually coding the request, see the API documentation for how requests should be constucted: https://dev.twitter.com/oauth/overview/authorizing-requests

Using Tweetinvi: https://github.com/linvi/tweetinvi/

private class AuthCredentials
{
    public string ConsumerKey = "ConsumerKey";
    public string ConsumerSecret = "ConsumerSecret";
    public string AccessToken = "AccessToken";
    public string AccessTokenSecret = "AccessTokenSecret";
}

static void Main(string[] args)
{
    var creds = new AuthCredentials();
    Auth.SetUserCredentials(creds.ConsumerKey, creds.ConsumerSecret, creds.AccessToken, creds.AccessTokenSecret);
    var data = File.ReadAllText("myimage.jpg");
    Account.UpdateProfileImage(data);
}

Twitter's API documents has a list of libraries for a variety of languages: https://dev.twitter.com/resources/twitter-libraries


问:
making new tuple from list and dictionary
I am trying to make a new tuple by splicing together a dictionary key and a numpy array turned into a list. However, I get this error

```<code>TypeError: list indices must be integers, not tuple
</code>```

Here is my code

```<code>import numpy
import random

print(ly)
{(1, 3): 2, (5, 2): 1, (10, 1): 0}

def myFun(layout):
    possibilities = numpy.zeros(shape=(4,2))
    possibilities[0] = [1, 0]
    possibilities[1] = [-1, 0]
    possibilities[2] = [0, 1]
    possibilities[3] = [0, -1]

    newLayout = tuple()
    for i in layout:
        randomDirection = random.choice( possibilities )
        newLayout = newLayout + layout.keys()[i] + list(randomDirection)
</code>```

the interpreter shows this line

```<code>newLayout = newLayout + layout.keys()[i] + list(randomDirection)
</code>```

as being problematic but I do not understand why

答:
instead of in your code newLayout = newLayout + layout.keys()[i] + list(randomDirection)

Use following,
newLayout = newLayout + layout[i] + list(randomDirection)

will solve your problem

Body:
I am trying to make a new tuple by splicing together a dictionary key and a numpy array turned into a list. However, I get this error

TypeError: list indices must be integers, not tuple

Here is my code

import numpy
import random

print(ly)
{(1, 3): 2, (5, 2): 1, (10, 1): 0}

def myFun(layout):
    possibilities = numpy.zeros(shape=(4,2))
    possibilities[0] = [1, 0]
    possibilities[1] = [-1, 0]
    possibilities[2] = [0, 1]
    possibilities[3] = [0, -1]

    newLayout = tuple()
    for i in layout:
        randomDirection = random.choice( possibilities )
        newLayout = newLayout + layout.keys()[i] + list(randomDirection)

the interpreter shows this line

newLayout = newLayout + layout.keys()[i] + list(randomDirection)

as being problematic but I do not understand why


答:
You are getting an error because the subquery returns more than one ID(multiple records) where as an equal operator can take only one value. Use an IN operator instead of Equal operator and your error will be removed.

```<code>select sum(connection) from connection
where connection.member_id IN (select id from member where status=1)
</code>```

Title: sql select sum with condition 2 tables?

Body:
I have 2 table

Table Connection
----------------------------------------
|  ID       |  Member_ID  |  Connection|
----------------------------------------
|  1        |  100        |  22        |
----------------------------------------
|  2        |  101        |  15        |
----------------------------------------
|  3        |  102        |  19        |
----------------------------------------
|  4        |  103        |  21        |

Table Member
---------------------------
|  ID         |  Status     |
---------------------------
|  100        |  0          |
----------------------------
|  101        |  1          |
----------------------------
|  102        |  1          |
---------------------------
|  103        |  0          |

I want to get sum of Connection has status =1.
The result in example should be 15+19 = 34.

Body:
You are getting an error because the subquery returns more than one ID(multiple records) where as an equal operator can take only one value. Use an IN operator instead of Equal operator and your error will be removed.

select sum(connection) from connection
where connection.member_id IN (select id from member where status=1)


问:
Keras save checkpoints
I am following this blog and I am having trouble to implement saving checkpoints as it's used in linked blog. At line 23 it used:

filepath="weights-improvement-{epoch:02d}-{val_acc:.2f}.hdf5".

So I tried to tweak the code a little bit to be more dynamic:

filepath = '{0}/checkpoints/checkpoint-{epoch:02d}-{val_loss:.2f}.hdf5'.format(directory).

Where I want to store all checkpoints of given architecture in 1 directory, e.g.: ./architecture1/checkpoints/

But I get the following error: KeyError: 'epoch'. What am I doing wrong here?

P.S.: filepath = "./checkpoints/checkpoint-{epoch:02d}-{val_loss:.2f}.hdf5" works, but it saves all checkpoints in 1 directory which I don't want.

答:
If you want to use format, the proper way is to escape the brackets like this:

```<code>filepath = '{0}/checkpoints/checkpoint-{{epoch:02d}}-{{val_loss:.2f}}.hdf5'.format(directory)
</code>```

So if directory = 'weights', filepath would be 'weights/checkpoints/checkpoint-{epoch:02d}-{val_loss:.2f}.hdf5'.

(Take care if directory contains {})

Title: Keras save checkpoints

Body:
If you want to use format, the proper way is to escape the brackets like this:

filepath = '{0}/checkpoints/checkpoint-{{epoch:02d}}-{{val_loss:.2f}}.hdf5'.format(directory)

So if directory = 'weights', filepath would be 'weights/checkpoints/checkpoint-{epoch:02d}-{val_loss:.2f}.hdf5'.

(Take care if directory contains {})


问:
Remove tiny scroll bar - Ionic 3
You can see that there is a tiny scroll bar as shown below.Can you tell me how to remove that? This is Ionic 3 app. I have tried many ways.But no luck yet.

Please see how bad it is on the device :(

This on the browser:

.sass

```<code> .height-70 {
        height: 70px;
        overflow: hidden;
    }
</code>```

.html

```<code><ion-content padding>
  <ion-grid>
    <ion-row>
      <ion-col class="height-70" col-12>
        <ion-content>
          <button ion-button icon-left full (click)="loginWithLinkedin()" class="background-color-linkedin"><ion-icon name="logo-linkedin" class="margin-top-minus-4"></ion-icon><span>Continue with Linkedin</span></button>
        </ion-content>
      </ion-col>
    </ion-row>
  </ion-grid>
</ion-content>
</code>```

Chrome css(run time): below padding:16px is the problem.But how can I remove it? Because I need padding too.Any workaround?

答:
Try out the following,

```<code><ion-content overflow-scroll="false">
</code>```

1.bounce,

```<code><ion-content no-bounce></ion-content>
</code>```

2.

```<code>.content > .scroll-content::before {
    bottom: 0;
}

.content > .scroll-content::after {
    top: 0;
}
</code>```

3.

```<code>.scroll-content {
   overflow-y: auto !important;
}
</code>```

4.

```<code><ion-content>
   <div ion-fixed>
   </div>
</ion-content>
</code>```

Title: Remove tiny scroll bar - Ionic 3

Body:
You can see that there is a tiny scroll bar as shown below.Can you tell me how to remove that? This is Ionic 3 app. I have tried many ways.But no luck yet.

Please see how bad it is on the device :(

This on the browser:

.sass

 .height-70 {
        height: 70px;
        overflow: hidden;
    }

.html

<ion-content padding>
  <ion-grid>
    <ion-row>
      <ion-col class="height-70" col-12>
        <ion-content>
          <button ion-button icon-left full (click)="loginWithLinkedin()" class="background-color-linkedin"><ion-icon name="logo-linkedin" class="margin-top-minus-4"></ion-icon>Continue with Linkedin</button>
        </ion-content>
      </ion-col>
    </ion-row>
  </ion-grid>
</ion-content>

Chrome css(run time): below padding:16px is the problem.But how can I remove it? Because I need padding too.Any workaround?

Body:
Try out the following,

<ion-content overflow-scroll="false">

1.bounce,

<ion-content no-bounce></ion-content>

2.

.content > .scroll-content::before {
    bottom: 0;
}

.content > .scroll-content::after {
    top: 0;
}

3.

.scroll-content {
   overflow-y: auto !important;
}

4.

<ion-content>
   <div ion-fixed>
   </div>
</ion-content>


问:
What's the right way to add haml to a rails application?
While looking for a way to add haml as the templating engine to my rails app I came upon two distinct ways to do it.

The first one is to just add 'gem "haml-rails"' to the Gemfile.

The second one is to add this code to config/application.rb:

```<code>config.generators do |g|
  g.template_engine :haml
end
</code>```

Is there a reason to prefer one over the other?

答:
I prefer the gem because it adds the generators.

Update: The 'haml-rails' gem provides the generators. You'll still need to set the template_engine to haml if you want haml templates by default.

Body:
While looking for a way to add haml as the templating engine to my rails app I came upon two distinct ways to do it.

The first one is to just add 'gem "haml-rails"' to the Gemfile.

The second one is to add this code to config/application.rb:

config.generators do |g|
  g.template_engine :haml
end

Is there a reason to prefer one over the other?


问:
Faild composer network deploy with time out
I executed this command.

```<code>composer network deploy -a basic-sample-network.bna -p defaultProfile -i admin -s Xurw3yU9zI0l
</code>```

But,faild with time out..

Here is log.

```<code>Deploying business network from archive: basic-sample-network.bna
Business network definition:
    Identifier: basic-sample-network@0.0.10
    Description: The Hello World of Hyperledger Composer samples

✖ Deploying business network definition. This may take a minute...

timed out waiting for transaction to complete
Command failed
</code>```

Colud you tell me the way to composer network deploy with no time out.

答:
Thank you for your answer.

I use Hyperledger Fabric v0.6 environment.

```<code>vagrant@ubuntu:~/composer/bna$ docker ps -a
CONTAINER ID        IMAGE                                                COMMAND                  CREATED             STATUS              PORTS                                                                                NAMES
3f3f0b3b6156        hyperledger/fabric-peer:x86_64-0.6.1-preview         "sh -c 'sleep 5; p..."   5 minutes ago       Up 5 minutes        0.0.0.0:7150->7050/tcp, 0.0.0.0:7151->7051/tcp, 0.0.0.0:7152->7052/tcp, 0.0.0.0:7153->7053/tcp   fabricconfig_vp1_1
f9819ca1fc89        hyperledger/composer-playground                      "pm2-docker compos..."   5 minutes ago       Up 5 minutes        0.0.0.0:8080->8080/tcp                                                                           fabricconfig_composer_1
6488421e4878        hyperledger/fabric-peer:x86_64-0.6.1-preview         "sh -c 'sleep 5; p..."   5 minutes ago       Up 5 minutes        0.0.0.0:7350->7050/tcp, 0.0.0.0:7351->7051/tcp, 0.0.0.0:7352->7052/tcp, 0.0.0.0:7353->7053/tcp   fabricconfig_vp3_1
886c5594bba2        hyperledger/fabric-peer:x86_64-0.6.1-preview         "sh -c 'sleep 5; p..."   5 minutes ago       Up 5 minutes        0.0.0.0:7250->7050/tcp, 0.0.0.0:7251->7051/tcp, 0.0.0.0:7252->7052/tcp, 0.0.0.0:7253->7053/tcp   fabricconfig_vp2_1
1c407073c7ec        hyperledger/fabric-peer:x86_64-0.6.1-preview         "sh -c 'sleep 5; p..."   5 minutes ago       Up 5 minutes        0.0.0.0:7050-7053->7050-7053/tcp                                                                 fabricconfig_vp0_1
ae2cd708ecc1        hyperledger/fabric-membersrvc:x86_64-0.6.1-preview   "membersrvc"             5 minutes ago       Up 5 minutes        0.0.0.0:7054->7054/tcp                                                                           fabricconfig_membersrvc_1
</code>```

thanks

Body:
I executed this command.

composer network deploy -a basic-sample-network.bna -p defaultProfile -i admin -s Xurw3yU9zI0l

But,faild with time out..

Here is log.

Deploying business network from archive: basic-sample-network.bna
Business network definition:
    Identifier: basic-sample-network@0.0.10
    Description: The Hello World of Hyperledger Composer samples

✖ Deploying business network definition. This may take a minute...

timed out waiting for transaction to complete
Command failed

Colud you tell me the way to composer network deploy with no time out.

Body:
Thank you for your answer.

I use Hyperledger Fabric v0.6 environment.

vagrant@ubuntu:~/composer/bna$ docker ps -a
CONTAINER ID        IMAGE                                                COMMAND                  CREATED             STATUS              PORTS                                                                                NAMES
3f3f0b3b6156        hyperledger/fabric-peer:x86_64-0.6.1-preview         "sh -c 'sleep 5; p..."   5 minutes ago       Up 5 minutes        0.0.0.0:7150->7050/tcp, 0.0.0.0:7151->7051/tcp, 0.0.0.0:7152->7052/tcp, 0.0.0.0:7153->7053/tcp   fabricconfig_vp1_1
f9819ca1fc89        hyperledger/composer-playground                      "pm2-docker compos..."   5 minutes ago       Up 5 minutes        0.0.0.0:8080->8080/tcp                                                                           fabricconfig_composer_1
6488421e4878        hyperledger/fabric-peer:x86_64-0.6.1-preview         "sh -c 'sleep 5; p..."   5 minutes ago       Up 5 minutes        0.0.0.0:7350->7050/tcp, 0.0.0.0:7351->7051/tcp, 0.0.0.0:7352->7052/tcp, 0.0.0.0:7353->7053/tcp   fabricconfig_vp3_1
886c5594bba2        hyperledger/fabric-peer:x86_64-0.6.1-preview         "sh -c 'sleep 5; p..."   5 minutes ago       Up 5 minutes        0.0.0.0:7250->7050/tcp, 0.0.0.0:7251->7051/tcp, 0.0.0.0:7252->7052/tcp, 0.0.0.0:7253->7053/tcp   fabricconfig_vp2_1
1c407073c7ec        hyperledger/fabric-peer:x86_64-0.6.1-preview         "sh -c 'sleep 5; p..."   5 minutes ago       Up 5 minutes        0.0.0.0:7050-7053->7050-7053/tcp                                                                 fabricconfig_vp0_1
ae2cd708ecc1        hyperledger/fabric-membersrvc:x86_64-0.6.1-preview   "membersrvc"             5 minutes ago       Up 5 minutes        0.0.0.0:7054->7054/tcp                                                                           fabricconfig_membersrvc_1

thanks


问:
Angular directive loses its style when bound to value inside ngFor
My directive is losing it's style when a value is passed to it dynamically inside a ngFor loop.

I have this directive for a datatable column, where I set the name of the column.

```<code>@Directive({ selector: '[my-dt-column]' })
export class MyDTColumn{
    @Output() onSort: EventEmitter<any> = new EventEmitter();

    @HostBinding('class.sorted-asc') sortedAsc;
    @HostBinding('class.sorted-desc') sortedDesc;
    _sortOrder: string;
    public sort(order?: string){
        this._sortOrder = order !== undefined ? order: (!this._sortOrder || this._sortOrder=='desc') ? 'asc' : 'desc'
        this.sortedAsc = this.sortOrder === 'asc';
        this.sortedDesc = this.sortOrder === 'desc';
    }
    get sortOrder(): string{
        return this._sortOrder;
    }
    get isSorted(): boolean{
        return this._sortOrder !== undefined && this._sortOrder !== null && this._sortOrder !== '';
    }
    column: string;
    @Input('my-dt-column')
    set setItem(column: any){
        this.column = column;

    }

    @HostListener('click') onClick(){
        this.sort();
        this.onSort.emit({orderBy:this.column, sortOrder:this._sortOrder});
    }

    constructor(private el: ElementRef){}
}
</code>```

And some style for it, which basically sets the direction of an arrow-icon, indicating if the column is sorted or not, and its order.

```<code>:host >>>> table [my-dt-column]{
    cursor: pointer;
}
:host >>>> table  [my-dt-column] md-icon{
    font-size: 10px;
    height: 16px;
    line-height: 16px;
    vertical-align: middle;
    opacity: 0;
    color: rgba(0, 0, 0, 0.38);
    transition: transform .25s, opacity .25s;
    transform-origin: center center;
    text-align: center;
}
:host >>>> table [my-dt-column].sorted-asc,
:host >>>> table [my-dt-column].sorted-desc{
    color: rgba(0, 0, 0, 0.87);
}
:host >>>> table [my-dt-column].sorted-asc md-icon,
:host >>>> table [my-dt-column].sorted-desc md-icon{
    opacity: 1;
    color: rgba(0, 0, 0, 0.87);
}
:host >>>> table [my-dt-column].sorted-asc md-icon{
    transform: rotate(0deg);
}
:host >>>> table [my-dt-column].sorted-desc md-icon{
    transform: rotate(180deg);
}
:host >>>> table [my-dt-column]:hover md-icon{
    opacity: 1;
}
</code>```

I was adding table headers with this directive manually in html, to something like this:

```<code><th my-dt-column="ColumnName">some code</th>
<th my-dt-column="Column2Name">some code</th>
<th my-dt-column="Column3Name">some code</th>
<th my-dt-column="Column4Name">some code</th>
</code>```

But in order to prevent typing errors, I decided to make an array in my parent component with the name of my columns, and added dynamically in html with ngFor.
So my code became something like this:

Style over directive won't work, but the column's name is set.

```<code><ng-container *ngFor="let column of columns">
   <th [my-dt-column]="column.name">some code</th>
</ng-container>
</code>```

But suddenly my style over this directive stopped working. If I change the above code directive to some random string, my style will work, but the name of the column won't be correct.

Style over directive work, but the column name is incorrect.

```<code><ng-container *ngFor="let column of columns">
   <th my-dt-column="randomstring">some code</th>
</ng-container>
</code>```

I couldn't find any answer for a problem like this, and any help would be nice.

EDIT:
1 more clue: when I bind a random string to this directive, it is set in my HTML(my-dt-column directive):

```<code><th _ngcontent-c11="" mdtooltipposition="right" my-dt-column="randomstring" ng-reflect-position="right" ng-reflect-message="" ng-reflect-set-item="randomstring" class="">some code</th>
</code>```

but when I try to pass the name of my column generated by ngFor, it won't set EVEN in HTML (note that in the example below, my-dt-column directive is missing.

```<code><th _ngcontent-c11="" mdtooltipposition="right" ng-reflect-position="right" ng-reflect-message="" ng-reflect-set-item="InstrumentTypeName" class="">some code</th>
</code>```

答:
If you want to keep attribute i can advice you use @HostBinding like

```<code>import { HostBinding } from '@angular/core';

....
column: string;
@HostBinding('attr.my-dt-column') @Input('my-dt-column')
set setItem(column: any){
    this.column = column;
}
get setItem() {
  return this.column
}
</code>```

as you can see you also have to declare getter.

Plunker Example

Another approach is using host property on your component

```<code>host: {
  '[attr.my-dt-column]': 'column'
}
</code>```

Plunker Example

Body:
My directive is losing it's style when a value is passed to it dynamically inside a ngFor loop.

I have this directive for a datatable column, where I set the name of the column.

@Directive({ selector: '[my-dt-column]' })
export class MyDTColumn{
    @Output() onSort: EventEmitter<any> = new EventEmitter();

    @HostBinding('class.sorted-asc') sortedAsc;
    @HostBinding('class.sorted-desc') sortedDesc;
    _sortOrder: string;
    public sort(order?: string){
        this._sortOrder = order !== undefined ? order: (!this._sortOrder || this._sortOrder=='desc') ? 'asc' : 'desc'
        this.sortedAsc = this.sortOrder === 'asc';
        this.sortedDesc = this.sortOrder === 'desc';
    }
    get sortOrder(): string{
        return this._sortOrder;
    }
    get isSorted(): boolean{
        return this._sortOrder !== undefined && this._sortOrder !== null && this._sortOrder !== '';
    }
    column: string;
    @Input('my-dt-column')
    set setItem(column: any){
        this.column = column;

    }

    @HostListener('click') onClick(){
        this.sort();
        this.onSort.emit({orderBy:this.column, sortOrder:this._sortOrder});
    }

    constructor(private el: ElementRef){}
}

And some style for it, which basically sets the direction of an arrow-icon, indicating if the column is sorted or not, and its order.

:host >>>> table [my-dt-column]{
    cursor: pointer;
}
:host >>>> table  [my-dt-column] md-icon{
    font-size: 10px;
    height: 16px;
    line-height: 16px;
    vertical-align: middle;
    opacity: 0;
    color: rgba(0, 0, 0, 0.38);
    transition: transform .25s, opacity .25s;
    transform-origin: center center;
    text-align: center;
}
:host >>>> table [my-dt-column].sorted-asc,
:host >>>> table [my-dt-column].sorted-desc{
    color: rgba(0, 0, 0, 0.87);
}
:host >>>> table [my-dt-column].sorted-asc md-icon,
:host >>>> table [my-dt-column].sorted-desc md-icon{
    opacity: 1;
    color: rgba(0, 0, 0, 0.87);
}
:host >>>> table [my-dt-column].sorted-asc md-icon{
    transform: rotate(0deg);
}
:host >>>> table [my-dt-column].sorted-desc md-icon{
    transform: rotate(180deg);
}
:host >>>> table [my-dt-column]:hover md-icon{
    opacity: 1;
}

I was adding table headers with this directive manually in html, to something like this:

some code
some code
some code
some code

But in order to prevent typing errors, I decided to make an array in my parent component with the name of my columns, and added dynamically in html with ngFor.
So my code became something like this:

Style over directive won't work, but the column's name is set.

<ng-container *ngFor="let column of columns">
   some code
</ng-container>

But suddenly my style over this directive stopped working. If I change the above code directive to some random string, my style will work, but the name of the column won't be correct.

Style over directive work, but the column name is incorrect.

<ng-container *ngFor="let column of columns">
   some code
</ng-container>

I couldn't find any answer for a problem like this, and any help would be nice.

EDIT:
1 more clue: when I bind a random string to this directive, it is set in my HTML(my-dt-column directive):

some code

but when I try to pass the name of my column generated by ngFor, it won't set EVEN in HTML (note that in the example below, my-dt-column directive is missing.

some code

Body:
If you want to keep attribute i can advice you use @HostBinding like

import { HostBinding } from '@angular/core';

....
column: string;
@HostBinding('attr.my-dt-column') @Input('my-dt-column')
set setItem(column: any){
    this.column = column;
}
get setItem() {
  return this.column
}

as you can see you also have to declare getter.

Plunker Example

Another approach is using host property on your component

host: {
  '[attr.my-dt-column]': 'column'
}

Plunker Example


问:
Rails Console not showing data present in mongodb
I am working on rails with MongoDB using mongoid gem. I have set up MongoDB on OSX using brew.I took the data dump from the server and restored it on local machine. I can view data present in my database using mongo shell. But when I am using rails console to get the data it returns nothing.

Example when I run this command in rails console  I get the result as  [].The same command on the server gives 1 record.

```<code>Network.all.to_a
</code>```

Whereas in the database there is 1 record which belongs to Network collection.
The database mentioned in the mongoid.yml is the same as that shown in mongo shell.

The network model is described as

```<code>class Network
 include Mongoid::Document
 include Mongoid::Timestamps
 has_many :network_devices
 field :network_id, type: String
 field :node_mac, type: String
 field :version, type: String
end
</code>```

答: So it may seem very weird but restarting my laptop solved the problem.</p>

Body:
I am working on rails with MongoDB using mongoid gem. I have set up MongoDB on OSX using brew.I took the data dump from the server and restored it on local machine. I can view data present in my database using mongo shell. But when I am using rails console to get the data it returns nothing.

Example when I run this command in rails console  I get the result as  [].The same command on the server gives 1 record.

Network.all.to_a

Whereas in the database there is 1 record which belongs to Network collection.
The database mentioned in the mongoid.yml is the same as that shown in mongo shell.

The network model is described as

class Network
 include Mongoid::Document
 include Mongoid::Timestamps
 has_many :network_devices
 field :network_id, type: String
 field :node_mac, type: String
 field :version, type: String
end


问:
Swift Protocol Delegate return nil
```<code>protocol testDelegate: class {
    func open(channel: String, vc: UIViewController)
}

class test: UIViewController{

    weak var delegate: testDelegate?
}
override func viewDidLoad() {
        super.viewDidLoad()
        if self.delegate != nil {
        print("hello")
        self.delegate?.openGroupChannel(channel: channel!, vc: self)

}
</code>```

that is Class Test! protocol init in Test class as well

```<code>class calling:testDelegate{

override func viewDidLoad() {
        //blah blah
    }

func func open(channel: String, vc: UIViewController){
    print("calling")
}
</code>```

This is calling class.

I want to call open func in calling class but it does not calling at all,
even print("hello") in test class is not calling it keeps return nil therefore does not call calling function as well.

答:
You need to set your calling as delegate of test ViewController.
In your calling class create object of test class before navigation and set calling class as delegate of your test class as

```<code>override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if let testVc = segue.destinationViewController as? test {
    testVc .delegate = self
    }
}
</code>```

Hope it helps.. Happy Coding!!

Title: Swift Protocol Delegate return nil

Body:
protocol testDelegate: class {
    func open(channel: String, vc: UIViewController)
}

class test: UIViewController{

    weak var delegate: testDelegate?
}
override func viewDidLoad() {
        super.viewDidLoad()
        if self.delegate != nil {
        print("hello")
        self.delegate?.openGroupChannel(channel: channel!, vc: self)

}

that is Class Test! protocol init in Test class as well

class calling:testDelegate{

override func viewDidLoad() {
        //blah blah
    }

func func open(channel: String, vc: UIViewController){
    print("calling")
}

This is calling class.

I want to call open func in calling class but it does not calling at all,
even print("hello") in test class is not calling it keeps return nil therefore does not call calling function as well.

Body:
You need to set your calling as delegate of test ViewController.
In your calling class create object of test class before navigation and set calling class as delegate of your test class as

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if let testVc = segue.destinationViewController as? test {
    testVc .delegate = self
    }
}

Hope it helps.. Happy Coding!!


问:
does microsoft have its own external grid controls?
Except those which are available in Visual Studio, are there any official external Microsoft's grid controls? For example, Telerik has controls for .net. Does Microsoft have similar ones?

EDIT: It's for webforms...

Thanks,

Ilija

答:
The controls you reference (like Telerik) are made to be used inside of VS with .Net. Since Microsoft built .Net (and VS) they had no reasons to make 'external' controls.

If you look around places like CodePlex and Sourceforge then you can find 'external' grids, but most of them are not offically supported Microsoft controls.


问:
How to resolve SFErrorDomain Code=1 error
I am trying to making a blocker for Mac,I have follow these steps(link)

and then using this code

```<code>[SFContentBlockerManager reloadContentBlockerWithIdentifier:APP_EXTENSION_NAME completionHandler:^(NSError * _Nullable error) {

            NSLog(@"%@",error);
 }];
</code>```

It's print

Error Domain=SFErrorDomain Code=1 "(null)"

I done googling and found that means of this error is

"noExtensionFound error."

But I am not getting any solution for How to resolve this error.

答:
I solved this error, what a silly mistake.

This error is coming because in new Xcode Content Blocker Extension comes with a different option next to safari extension option, and I chooses safari extension, and I am trying to make Content Blocker.So that's why "noExtensionFound error" is coming.

Body:
I am trying to making a blocker for Mac,I have follow these steps(link)

and then using this code

[SFContentBlockerManager reloadContentBlockerWithIdentifier:APP_EXTENSION_NAME completionHandler:^(NSError * _Nullable error) {

            NSLog(@"%@",error);
 }];

It's print

Error Domain=SFErrorDomain Code=1 "(null)"

I done googling and found that means of this error is

"noExtensionFound error."

But I am not getting any solution for How to resolve this error.