问:
Drawing contours using cv2.approxPolyDP() in python
I'm unable to draw complete contours of a shape using cv2.approxPolyDP().

I'm getting the following result:

But I want output like this:

Here's my code:

```<code>import cv2
im = cv2.imread('C:\Python27\Test\Targets\s1.jpg') # read picture

imgray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY) # BGR to grayscale

ret, thresh = cv2.threshold(imgray, 200, 255, cv2.THRESH_BINARY)

countours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

epsilon = 0.1 * cv2.arcLength(countours[0], True)
approx = cv2.approxPolyDP(countours[0], epsilon, True)

cv2.drawContours(im, approx, -1, (0, 255, 0), 3)
cv2.imshow("Contour", im)

cv2.waitKey(0)
cv2.destroyAllWindows()
</code>```

答:
In Java this works</p>

```<code>MatOfPoint2f  newContour = new MatOfPoint2f();
largestContour.convertTo(newContour, CvType.CV_32F);
double arcLength = Imgproc.arcLength(newContour, closed);
double epsilon = 0.2 * arcLength;
MatOfPoint2f approxCurve = new MatOfPoint2f();
Imgproc.approxPolyDP(newContour, approxCurve, epsilon, closed);

// convert back to form that can be plotted by drawContours
MatOfPoint largestOutline = new  MatOfPoint();
approxCurve.convertTo(largestOutline, CvType.CV_32S);
</code>```

Body:
I'm unable to draw complete contours of a shape using cv2.approxPolyDP().

I'm getting the following result:

But I want output like this:

Here's my code:

import cv2
im = cv2.imread('C:\Python27\Test\Targets\s1.jpg') # read picture

imgray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY) # BGR to grayscale

ret, thresh = cv2.threshold(imgray, 200, 255, cv2.THRESH_BINARY)

countours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

epsilon = 0.1 * cv2.arcLength(countours[0], True)
approx = cv2.approxPolyDP(countours[0], epsilon, True)

cv2.drawContours(im, approx, -1, (0, 255, 0), 3)
cv2.imshow("Contour", im)

cv2.waitKey(0)
cv2.destroyAllWindows()

Body:
In Java this works

MatOfPoint2f  newContour = new MatOfPoint2f();
largestContour.convertTo(newContour, CvType.CV_32F);
double arcLength = Imgproc.arcLength(newContour, closed);
double epsilon = 0.2 * arcLength;
MatOfPoint2f approxCurve = new MatOfPoint2f();
Imgproc.approxPolyDP(newContour, approxCurve, epsilon, closed);

// convert back to form that can be plotted by drawContours
MatOfPoint largestOutline = new  MatOfPoint();
approxCurve.convertTo(largestOutline, CvType.CV_32S);


来源: stackexchange

问:
Removing/disabling backticks on variable in Active Record query in CodeIgniter
I'm trying to make a "between" query on my database using the Query Class of CodeIgniter, however, when adding a variable to the where clause, it adds backticks to the variable.

```<code>$this->db->select(TABLE_DISCOUNTSCARRIER.'.discount')->select(TABLE_DISCOUNTSCARRIER.'.idCarrier')
$this->db->from(TABLE_DISCOUNTSCARRIER);
$this->db->join(TABLE_DISCOUNTS, TABLE_DISCOUNTSCARRIER.'.idDiscount='.TABLE_DISCOUNTS.'.idDiscount');
$this->db->where(TABLE_DISCOUNTSCARRIER.'.idCarrier', $carrier);
$this->db->where($data['from'].' BETWEEN '.TABLE_DISCOUNTS.'.from AND '.TABLE_DISCOUNTS.'.to');
$this->db->or_where($data['to'].' BETWEEN '.TABLE_DISCOUNTS.'.from AND '.TABLE_DISCOUNTS.'.to');
</code>```

Which is being parsed into this (the last two lines)

```<code>SELECT
    discountbycarrier.discount,
    discountbycarrier.idCarrier
FROM (discountbycarrier)
JOIN discounts
ON discountbycarrier.idDiscount=discounts.idDiscount
WHERE `discountbycarrier`.`idCarrier` = '6'
AND `5` BETWEEN discounts.from AND discounts.to
OR `10` BETWEEN discounts.from AND discounts.to
</code>```

Already tried setting the $this->db->_protect_identifiers=false; but it removes the backticks on the rest of the statements but not the variables. Already tried using the intval() of the variable but neither this works.
As you can see the variable $carrier is correctly being parsed as integer.
Any ideas? Thanks in advance.

答:
add this before the query</p>

```<code>$this->db->_protect_identifiers=false;
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to make a "between" query on my database using the Query Class of CodeIgniter, however, when adding a variable to the where clause, it adds backticks to the variable.

$this->db->select(TABLE_DISCOUNTSCARRIER.'.discount')->select(TABLE_DISCOUNTSCARRIER.'.idCarrier')
$this->db->from(TABLE_DISCOUNTSCARRIER);
$this->db->join(TABLE_DISCOUNTS, TABLE_DISCOUNTSCARRIER.'.idDiscount='.TABLE_DISCOUNTS.'.idDiscount');
$this->db->where(TABLE_DISCOUNTSCARRIER.'.idCarrier', $carrier);
$this->db->where($data['from'].' BETWEEN '.TABLE_DISCOUNTS.'.from AND '.TABLE_DISCOUNTS.'.to');
$this->db->or_where($data['to'].' BETWEEN '.TABLE_DISCOUNTS.'.from AND '.TABLE_DISCOUNTS.'.to');

Which is being parsed into this (the last two lines)

SELECT
    discountbycarrier.discount,
    discountbycarrier.idCarrier
FROM (discountbycarrier)
JOIN discounts
ON discountbycarrier.idDiscount=discounts.idDiscount
WHERE `discountbycarrier`.`idCarrier` = '6'
AND `5` BETWEEN discounts.from AND discounts.to
OR `10` BETWEEN discounts.from AND discounts.to

Already tried setting the $this->db->_protect_identifiers=false; but it removes the backticks on the rest of the statements but not the variables. Already tried using the intval() of the variable but neither this works.
As you can see the variable $carrier is correctly being parsed as integer.
Any ideas? Thanks in advance.

Body:
add this before the query

$this->db->_protect_identifiers=false;


问:
Printing Grid Component
I have a MultiGrid component with a single fixed row. I would like to print the result, but since multiple columns overflow on the x-axis, the print output gets truncated.

Is it possible to wrap each row in another element and then use display table-cell/table-row to get the desired, table-like behavior? The added benefit is that a table can easily stretch the entire page, even if the number of columns is low.

答:
Is it possible to wrap each row in another element

Yes. It would be possible to wrap rows by injecting your own cellRangeRenderer property. That being said, I don't really recommend it. RV doesn't really have "rows" or "columns"- just positioned cells. Wrapping would add extra elements which could slow down scroll performance. (Probably not much, but every little bit counts for scrolling.)

and then use display table-cell/table-row to get the desired,
  table-like behavior?

If you're using MultiGrid I assume you have enough columns to warrant windowing horizontal data as well as vertical? In which case, I don't think display:table would really work for you. I'm not sure what it would buy you.

Have you considered just rendering a non-RV layout specifically printing? I Haven't done this myself but maybe you could tap into beforeprint/afterprint and setState to render a different result? Alternately you could try setting overflowColumnCount really high when print mode is enabled to just render the entire horizontal axis.

I don't really have much experience with this unfortunately. It might require a little of experimentation on your part for the best performing solution. :)

Title: Printing Grid Component


问:
How can i Optimize my sql query

I have a the table above calls and user and i have this query

to get the incoming and outgoing

```<code>      SELECT username ,
      ( Select count(*) from calls where type = 'incoming' and user_id = user.id) as incoming,
      ( Select count(*) from calls where type = 'outgoing' and user_id = user.id) as outgoing
      from user
      join calls on user.id = calls.user_id
      group by user_id
</code>```

i got the correct data but is there much better way to do this query?

this the result of the query

答:
Just use conditional aggregation:

```<code> select u.username,
        sum(case when c.type = 'incoming' then 1 else 0 end) as  incoming,
        sum(case when c.type = 'outgoing' then 1 else 0 end) as  outgoing
 from user u join
      calls c
      on u.id = c.user_id
 group by u.username;
</code>```

Note other changes:

The tables have abbreviations, called table aliases.

All columns are qualified, so they identify the table they are coming from.

The group by column matches the select column.

Title: How can i Optimize my sql query

Body:
I have a the table above calls and user and i have this query

to get the incoming and outgoing

      SELECT username ,
      ( Select count(*) from calls where type = 'incoming' and user_id = user.id) as incoming,
      ( Select count(*) from calls where type = 'outgoing' and user_id = user.id) as outgoing
      from user
      join calls on user.id = calls.user_id
      group by user_id

i got the correct data but is there much better way to do this query?

this the result of the query

Body:
Just use conditional aggregation:

 select u.username,
        sum(case when c.type = 'incoming' then 1 else 0 end) as  incoming,
        sum(case when c.type = 'outgoing' then 1 else 0 end) as  outgoing
 from user u join
      calls c
      on u.id = c.user_id
 group by u.username;

Note other changes:

The tables have abbreviations, called table aliases.

All columns are qualified, so they identify the table they are coming from.

The group by column matches the select column.


问:
Set Session With Post Data
So I'm trying to use laravel-based login table, which is the hash that I can't even compare it with basic php hash login. No, you can't make hash exactly look like laravel. But I use the remember_token that is come from users table.

Here is the code on my laravel view:

```<code><form action="http://localhost/log/index.php" method="post">
       <input type="hidden" value="{{ Auth::user()->remember_token }}" name="wex">
       <button type="submit" class="btn btn-default">Check</button>
</form>
</code>```

As you can see, I'm trying to POST remember_token value, that will received on my http://localhost/log/index.php as variable.

Index.php (Keep in mind, this is not using laravel):

```<code><?php
    include "koneksi.php";

    if (isset($_POST['wex'])) {
        $token = $_POST['wex'];
        $query = "SELECT * FROM users WHERE remember_token = '". $token ."'" ;
        $result = mysqli_query($db_link,$query);

        if (mysqli_num_rows($result) != 1) {
            header("Location: http://localhost/laralearn/public/login");
        }

        session_start();
        $_SESSION['user'] = "member";
    }
    else{

        if(!isset($_SESSION['user'])){
            header("Location: http://localhost/laralearn/public/login");
        }
    }

?>
</code>```

The variable and page redirect if the remember_token isn't valid (working), but I can't set the session. When I tried to open the index.php on new tab, it's redirecting which is meaning the session isn't settled.

Can you tell me where am I doing something wrong? It would be nice if you explain it and tell me what the code should look like.

Thank you.

答: Put session_start(); right under the PHP tag. It must be called before there is any output and just to be on the safe side, include it before there is anything else called either.

Title: Set Session With Post Data

Body:
So I'm trying to use laravel-based login table, which is the hash that I can't even compare it with basic php hash login. No, you can't make hash exactly look like laravel. But I use the remember_token that is come from users table.

Here is the code on my laravel view:

<form action="http://localhost/log/index.php" method="post">
       <input type="hidden" value="{{ Auth::user()->remember_token }}" name="wex">
       <button type="submit" class="btn btn-default">Check</button>
</form>

As you can see, I'm trying to POST remember_token value, that will received on my http://localhost/log/index.php as variable.

Index.php (Keep in mind, this is not using laravel):

<?php
    include "koneksi.php";

    if (isset($_POST['wex'])) {
        $token = $_POST['wex'];
        $query = "SELECT * FROM users WHERE remember_token = '". $token ."'" ;
        $result = mysqli_query($db_link,$query);

        if (mysqli_num_rows($result) != 1) {
            header("Location: http://localhost/laralearn/public/login");
        }

        session_start();
        $_SESSION['user'] = "member";
    }
    else{

        if(!isset($_SESSION['user'])){
            header("Location: http://localhost/laralearn/public/login");
        }
    }

?>

The variable and page redirect if the remember_token isn't valid (working), but I can't set the session. When I tried to open the index.php on new tab, it's redirecting which is meaning the session isn't settled.

Can you tell me where am I doing something wrong? It would be nice if you explain it and tell me what the code should look like.

Thank you.


问:
httprequest.GetResponse() hang?
I meet a issue that is related to the following code , anyone know how to fix it?

code snippet

```<code> using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
            using (Stream dataStream = response.GetResponseStream())
            {
                StreamReader reader = new StreamReader(dataStream);
                responseString = reader.ReadToEnd();
            }
</code>```

答:
Look into "Aysncronous HttpWebResponse"'s

http://www.informit.com/guides/content.aspx?g=dotnet&seqNum=582

ContentLicense: CC BY-SA 2.5

Title: httprequest.GetResponse() hang?

Body:
I meet a issue that is related to the following code , anyone know how to fix it?

code snippet

 using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
            using (Stream dataStream = response.GetResponseStream())
            {
                StreamReader reader = new StreamReader(dataStream);
                responseString = reader.ReadToEnd();
            }


问:
Two dimensional array in python
I want to know how to declare a two dimensional array in Python.

```<code>arr = [[]]

arr[0].append("aa1")
arr[0].append("aa2")
arr[1].append("bb1")
arr[1].append("bb2")
arr[1].append("bb3")
</code>```

The first two assignments work fine. But when I try to do, arr[1].append("bb1"), I get the following error:

```<code>IndexError: list index out of range.
</code>```

Am I doing anything silly in trying to declare the 2-D array?

Edit:

but I do not know the number of elements in the array (both rows and columns).

答:
For compititve programming

1) For input the value in an 2D-Array

```<code>row=input()
main_list=[]
for i in range(0,row):
    temp_list=map(int,raw_input().split(" "))
    main_list.append(temp_list)
</code>```

2) For displaying 2D Array

```<code>for i in range(0,row):
    for j in range(0,len(main_list[0]):
        print main_list[i][j],
        print
</code>```

ContentLicense: CC BY-SA 4.0

Title: Two dimensional array in python

Body:
I want to know how to declare a two dimensional array in Python.

arr = [[]]

arr[0].append("aa1")
arr[0].append("aa2")
arr[1].append("bb1")
arr[1].append("bb2")
arr[1].append("bb3")

The first two assignments work fine. But when I try to do, arr[1].append("bb1"), I get the following error:

IndexError: list index out of range.

Am I doing anything silly in trying to declare the 2-D array?

Edit:

but I do not know the number of elements in the array (both rows and columns).

Body:
For compititve programming

1) For input the value in an 2D-Array

row=input()
main_list=[]
for i in range(0,row):
    temp_list=map(int,raw_input().split(" "))
    main_list.append(temp_list)

2) For displaying 2D Array

for i in range(0,row):
    for j in range(0,len(main_list[0]):
        print main_list[i][j],
        print


问:
Using an SKAction to change position of an SKShapeNode
I have a game in which I need an SKAction that moves the position of a SKShapeNode 64 units up. This is the code for the object that I need to move up.

```<code>var rect = SKShapeNode(rectOfSize(CGSizeMake(200,200))
rect.position = CGPointMake(0,0)
</code>```

I want to make it so that every few seconds, 64 units is added to the rect's y value. So:

```<code>rect.position = CGPointMake(0,64)
</code>```

And Then

```<code>rect.position = CGPointMake(0,128)
</code>```

Any help would be appreciated.

答:
```<code>let move = SKAction.moveTo(y: rect.position.y+64, duration: 1.0)
move.timingMode = SKActionTimingMode.easeInEaseOut
rect.run(move)
</code>```

Body:
I have a game in which I need an SKAction that moves the position of a SKShapeNode 64 units up. This is the code for the object that I need to move up.

var rect = SKShapeNode(rectOfSize(CGSizeMake(200,200))
rect.position = CGPointMake(0,0)

I want to make it so that every few seconds, 64 units is added to the rect's y value. So:

rect.position = CGPointMake(0,64)

And Then

rect.position = CGPointMake(0,128)

Any help would be appreciated.


问:
What's the issue with this 1000th prime number code?
```<code>count=5 #Nth prime number
i=10  #number to be checked
while (count!=1000):  #until its not 1000th
 if i%2==0 or i%3==0 or i%5==0 or i%7==0:  #to check non prime
  i=i+1 #next number initialized
 else: #for prime
  count=count+1 #move to next position
if count==1000: #if is 1000th position
 print i," is 1000th prime." #print prime
</code>```

I am considering 2,3,5,7 are already known as prime and starting from 10.

It gives "11 is 1000th prime" as output.
There is a logical error somewhere, I guess.

答:
As others have mentioned in comments, your criteria for deciding if a number is prime is very wrong. You're only testing whether it's divisible by the first 4 primes, but this is not sufficient for numbers larger than 120 (121 is divisible by 11, but not any of the smaller primes). You need to check all the primes found previously (look up "Sieve of Eratosthenes").

The other problem is that you're not incrementing i when the number is prime. So once you get to 11, you keep incrementing count, but not i. When count gets to 1000 you print i as the 1,000th prime. Take i = i + 1 out of the if block, it should be done every time.

Also, since even numbers can never be prime (except for 2), you can start with i = 11 and increment it by 2 -- don't waste time checking the even numbers. And then you can take i % 2 == 0 out of the test.

Body:
count=5 #Nth prime number
i=10  #number to be checked
while (count!=1000):  #until its not 1000th
 if i%2==0 or i%3==0 or i%5==0 or i%7==0:  #to check non prime
  i=i+1 #next number initialized
 else: #for prime
  count=count+1 #move to next position
if count==1000: #if is 1000th position
 print i," is 1000th prime." #print prime

I am considering 2,3,5,7 are already known as prime and starting from 10.

It gives "11 is 1000th prime" as output.
There is a logical error somewhere, I guess.


问:
How to define the default exe in a webjob that has multiple console app projects?
I have a console app solution with multiple projects that I deploy as Azure Webobs. The deployment goes through fine but the webjob doesn't know anything about the startup project in solution. When executing the webjob it picks the first .exe file from the list and runs it. this is not correct and need to know how can I enforce the startup project to webjobs. Want to mention that I can run the startup exe from azure webjob console manually but scheduled process doesn't know about the startup exe when running.</p>

答:
We could get  answer from the official document.The following is the snippet from the document. If we want to run .exe firstly, we could name it run.exe.

we use the following logic to decide which file is the script to run within the job's directory:
  Per file type we look first for a file named: run.{file type extension} (for example run.cmd or run.exe).
  If it doesn't exists for all file types, we'll then look for the first file with a supported file type extension.
  The order of file types extension used is: .cmd, .bat, .exe, .ps1, .sh, .php, .py, .js.

The following file types are accepted as runnable scripts that can be used as a job:

fsx (using the F# fsi.exe interactive compiler)

cmd, .bat, .exe (using windows cmd)

ps1 (using powershell)

sh (using bash)

php (using php)

py (using python)

js (using node)


问:
Move packaged_task into lambda
I want to move and call a boost::packaged_task inside a lambda.

However, I can't figure out an elegant solution.

e.g. This won't compile.

```<code>        template<typename Func>
        auto begin_invoke(Func&& func) -> boost::unique_future<decltype(func())> // noexcept
        {
            typedef boost::packaged_task<decltype(func())> task_type;

            auto task = task_type(std::forward<Func>(func));
            auto future = task.get_future();

            execution_queue_.try_push([=]
            {
                try{task();}
                catch(boost::task_already_started&){}
            });

            return std::move(future);
        }

    int _tmain(int argc, _TCHAR* argv[])
    {
        executor ex;
        ex.begin_invoke([]{std::cout << "Hello world!";});
       //error C3848: expression having type 'const boost::packaged_task<R>' would lose some const-volatile qualifiers in order to call 'void boost::packaged_task<R>::operator ()(void)'
//          with
//          [
//              R=void
//          ]
        return 0;
    }
</code>```

My rather ugly solution:

```<code>    struct task_adaptor_t
    {
        // copy-constructor acts as move constructor
        task_adaptor_t(const task_adaptor_t& other) : task(std::move(other.task)){}
        task_adaptor_t(task_type&& task) : task(std::move(task)){}
        void operator()() const { task(); }
        mutable task_type task;
    } task_adaptor(std::move(task));

    execution_queue_.try_push([=]
    {
        try{task_adaptor();}
        catch(boost::task_already_started&){}
    });
</code>```

What is the "proper" way to move a packaged_task into a lambda which calls it?

答:
With a proper implementation of std::bind (or something equivalent with respect to move-enabled types) you should be able to combine bind and a C++0x lambda like this:

```<code>task_type task (std::forward<Func>(func));
auto future = task.get_future();

execution_queue_.try_push(std::bind([](task_type const& task)
{
    try{task();}
    catch(boost::task_already_started&){}
},std::move(task)));

return future;
</code>```

btw: You don't need a std::move around future because future is a local object. As such, it's already subject to potential copy elision and if the compiler is not able to do that elision it has to move construct the return value from 'future'. The explicit use of std::move in this case may actually inhibit a copy/move elision.

Title: Move packaged_task into lambda

Body:
I want to move and call a boost::packaged_task inside a lambda.

However, I can't figure out an elegant solution.

e.g. This won't compile.

        template<typename Func>
        auto begin_invoke(Func&& func) -> boost::unique_future<decltype(func())> // noexcept
        {
            typedef boost::packaged_task<decltype(func())> task_type;

            auto task = task_type(std::forward<Func>(func));
            auto future = task.get_future();

            execution_queue_.try_push([=]
            {
                try{task();}
                catch(boost::task_already_started&){}
            });

            return std::move(future);
        }

    int _tmain(int argc, _TCHAR* argv[])
    {
        executor ex;
        ex.begin_invoke([]{std::cout << "Hello world!";});
       //error C3848: expression having type 'const boost::packaged_task<R>' would lose some const-volatile qualifiers in order to call 'void boost::packaged_task<R>::operator ()(void)'
//          with
//          [
//              R=void
//          ]
        return 0;
    }

My rather ugly solution:

    struct task_adaptor_t
    {
        // copy-constructor acts as move constructor
        task_adaptor_t(const task_adaptor_t& other) : task(std::move(other.task)){}
        task_adaptor_t(task_type&& task) : task(std::move(task)){}
        void operator()() const { task(); }
        mutable task_type task;
    } task_adaptor(std::move(task));

    execution_queue_.try_push([=]
    {
        try{task_adaptor();}
        catch(boost::task_already_started&){}
    });

What is the "proper" way to move a packaged_task into a lambda which calls it?

Body:
With a proper implementation of std::bind (or something equivalent with respect to move-enabled types) you should be able to combine bind and a C++0x lambda like this:

task_type task (std::forward<Func>(func));
auto future = task.get_future();

execution_queue_.try_push(std::bind([](task_type const& task)
{
    try{task();}
    catch(boost::task_already_started&){}
},std::move(task)));

return future;

btw: You don't need a std::move around future because future is a local object. As such, it's already subject to potential copy elision and if the compiler is not able to do that elision it has to move construct the return value from 'future'. The explicit use of std::move in this case may actually inhibit a copy/move elision.


答:
The logic you write to calculate prime number is wrong. I think you can store all prime number you calculated in previous test then test next number by dividing all previous prime number or just test next number simply according to the definition of prime number

In loop, if i == 11, then you will increase counter, however, i won't be increased, so for following loops, you will just test if 11 is the prime number. That's why you print 11 as 1000th number. Actually, you will print 11 as Nth prime number. I think you should always increase i.

Title: What's the issue with this 1000th prime number code?


问:
SSHD Gives error could not open Authorized Keys, although permissions seem correct
I'm unable to login to SSH because of the following error in /var/log/secure (according to the debug logs):

```<code>Dec 19 18:01:05 hostname sshd[25119]: debug1: trying public key file /root/.ssh/authorized_keys
Dec 19 18:01:05 hostname sshd[25119]: debug1: Could not open authorized keys '/root/.ssh/authorized_keys': Permission denied
</code>```

I have the following permissions set on root

```<code>chmod 700 ~/.ssh
chmod 600 ~/.ssh/authorized_keys
chmod go-wrx ~
</code>```

ls -lah gives the following output for those directories:

```<code>drwx------.   6 root root 4.0K Dec 19 17:46 root
drwx------.  2 root root 4.0K Dec 19 17:41 .ssh
-rw-------. 1 root root  416 Dec 19 17:12 authorized_keys
</code>```

I know the key I'm using is correct, as I just setup another server with it without any problems.

I'm running: CentOS release 6.4 (Final)

I've added my sshd config in case there's something misconfigured in there that might be causing the issue:

```<code>#       $OpenBSD: sshd_config,v 1.80 2008/07/02 02:24:18 djm Exp $

# This is the sshd server system-wide configuration file.  See
# sshd_config(5) for more information.

# This sshd was compiled with PATH=/usr/local/bin:/bin:/usr/bin

# The strategy used for options in the default sshd_config shipped with
# OpenSSH is to specify options with their default value where
# possible, but leave them commented.  Uncommented options change a
# default value.

#Port 22
#AddressFamily any
#ListenAddress 0.0.0.0
#ListenAddress ::

# Disable legacy (protocol version 1) support in the server for new
# installations. In future the default will change to require explicit
# activation of protocol 1
Protocol 2

# HostKey for protocol version 1
#HostKey /etc/ssh/ssh_host_key
# HostKeys for protocol version 2
#HostKey /etc/ssh/ssh_host_rsa_key
#HostKey /etc/ssh/ssh_host_dsa_key

# Lifetime and size of ephemeral version 1 server key
#KeyRegenerationInterval 1h
#ServerKeyBits 1024

# Logging
# obsoletes QuietMode and FascistLogging
#SyslogFacility AUTH
SyslogFacility AUTHPRIV
LogLevel DEBUG

# Authentication:

#LoginGraceTime 2m
PermitRootLogin yes
StrictModes no
#MaxAuthTries 6
#MaxSessions 10

RSAAuthentication yes
PubkeyAuthentication yes
AuthorizedKeysFile      .ssh/authorized_keys
#AuthorizedKeysCommand none
#AuthorizedKeysCommandRunAs nobody

# For this to work you will also need host keys in /etc/ssh/ssh_known_hosts
#RhostsRSAAuthentication no
# similar for protocol version 2
#HostbasedAuthentication no
# Change to yes if you don't trust ~/.ssh/known_hosts for
# RhostsRSAAuthentication and HostbasedAuthentication
#IgnoreUserKnownHosts no
# Don't read the user's ~/.rhosts and ~/.shosts files
IgnoreRhosts yes

# To disable tunneled clear text passwords, change to no here!
#PasswordAuthentication yes
#PermitEmptyPasswords no
PasswordAuthentication yes

# Change to no to disable s/key passwords
#ChallengeResponseAuthentication yes
ChallengeResponseAuthentication no

# Kerberos options
#KerberosAuthentication no
#KerberosOrLocalPasswd yes
#KerberosTicketCleanup yes
#KerberosGetAFSToken no
#KerberosUseKuserok yes

# GSSAPI options
#GSSAPIAuthentication no
GSSAPIAuthentication yes
#GSSAPICleanupCredentials yes
GSSAPICleanupCredentials yes
#GSSAPIStrictAcceptorCheck yes
#GSSAPIKeyExchange no

# Set this to 'yes' to enable PAM authentication, account processing,
# and session processing. If this is enabled, PAM authentication will
# be allowed through the ChallengeResponseAuthentication and
# PasswordAuthentication.  Depending on your PAM configuration,
# PAM authentication via ChallengeResponseAuthentication may bypass
# the setting of "PermitRootLogin without-password".
# If you just want the PAM account and session checks to run without
# PAM authentication, then enable this but set PasswordAuthentication
# and ChallengeResponseAuthentication to 'no'.
#UsePAM no
UsePAM yes

# Accept locale-related environment variables
AcceptEnv LANG LC_CTYPE LC_NUMERIC LC_TIME LC_COLLATE LC_MONETARY LC_MESSAGES
AcceptEnv LC_PAPER LC_NAME LC_ADDRESS LC_TELEPHONE LC_MEASUREMENT
AcceptEnv LC_IDENTIFICATION LC_ALL LANGUAGE
AcceptEnv XMODIFIERS

#AllowAgentForwarding yes
#AllowTcpForwarding yes
#GatewayPorts no
#X11Forwarding no
X11Forwarding yes
#X11DisplayOffset 10
#X11UseLocalhost yes
#PrintMotd yes
#PrintLastLog yes
#TCPKeepAlive yes
#UseLogin no
#UsePrivilegeSeparation yes
#PermitUserEnvironment no
#Compression delayed
#ClientAliveInterval 0
#ClientAliveCountMax 3
#ShowPatchLevel no
UseDNS no
#PidFile /var/run/sshd.pid
#MaxStartups 10:30:100
#PermitTunnel no
#ChrootDirectory none

# no default banner path
#Banner none

# override default of no subsystems
Subsystem       sftp    /usr/libexec/openssh/sftp-server

# Example of overriding settings on a per-user basis
#Match User anoncvs
#       X11Forwarding no
#       AllowTcpForwarding no
#       ForceCommand cvs server
</code>```

Any ideas would be much appreciated.

答:
I encountered this same issue and got it solved by changing both .ssh and authorized_keys's owner at the same time:
chown MyUsername:Myusername .ssh
chown MyUsername:Myusername .ssh/authorized_keys

Thanks to @niclaslindgren.

And BTW, it's no matter with whether there is ^M in authorized_keys or not, I had tested and proved it, it works with both the ways

Body:
I'm unable to login to SSH because of the following error in /var/log/secure (according to the debug logs):

Dec 19 18:01:05 hostname sshd[25119]: debug1: trying public key file /root/.ssh/authorized_keys
Dec 19 18:01:05 hostname sshd[25119]: debug1: Could not open authorized keys '/root/.ssh/authorized_keys': Permission denied

I have the following permissions set on root

chmod 700 ~/.ssh
chmod 600 ~/.ssh/authorized_keys
chmod go-wrx ~

ls -lah gives the following output for those directories:

drwx------.   6 root root 4.0K Dec 19 17:46 root
drwx------.  2 root root 4.0K Dec 19 17:41 .ssh
-rw-------. 1 root root  416 Dec 19 17:12 authorized_keys

I know the key I'm using is correct, as I just setup another server with it without any problems.

I'm running: CentOS release 6.4 (Final)

I've added my sshd config in case there's something misconfigured in there that might be causing the issue:

#       $OpenBSD: sshd_config,v 1.80 2008/07/02 02:24:18 djm Exp $

# This is the sshd server system-wide configuration file.  See
# sshd_config(5) for more information.

# This sshd was compiled with PATH=/usr/local/bin:/bin:/usr/bin

# The strategy used for options in the default sshd_config shipped with
# OpenSSH is to specify options with their default value where
# possible, but leave them commented.  Uncommented options change a
# default value.

#Port 22
#AddressFamily any
#ListenAddress 0.0.0.0
#ListenAddress ::

# Disable legacy (protocol version 1) support in the server for new
# installations. In future the default will change to require explicit
# activation of protocol 1
Protocol 2

# HostKey for protocol version 1
#HostKey /etc/ssh/ssh_host_key
# HostKeys for protocol version 2
#HostKey /etc/ssh/ssh_host_rsa_key
#HostKey /etc/ssh/ssh_host_dsa_key

# Lifetime and size of ephemeral version 1 server key
#KeyRegenerationInterval 1h
#ServerKeyBits 1024

# Logging
# obsoletes QuietMode and FascistLogging
#SyslogFacility AUTH
SyslogFacility AUTHPRIV
LogLevel DEBUG

# Authentication:

#LoginGraceTime 2m
PermitRootLogin yes
StrictModes no
#MaxAuthTries 6
#MaxSessions 10

RSAAuthentication yes
PubkeyAuthentication yes
AuthorizedKeysFile      .ssh/authorized_keys
#AuthorizedKeysCommand none
#AuthorizedKeysCommandRunAs nobody

# For this to work you will also need host keys in /etc/ssh/ssh_known_hosts
#RhostsRSAAuthentication no
# similar for protocol version 2
#HostbasedAuthentication no
# Change to yes if you don't trust ~/.ssh/known_hosts for
# RhostsRSAAuthentication and HostbasedAuthentication
#IgnoreUserKnownHosts no
# Don't read the user's ~/.rhosts and ~/.shosts files
IgnoreRhosts yes

# To disable tunneled clear text passwords, change to no here!
#PasswordAuthentication yes
#PermitEmptyPasswords no
PasswordAuthentication yes

# Change to no to disable s/key passwords
#ChallengeResponseAuthentication yes
ChallengeResponseAuthentication no

# Kerberos options
#KerberosAuthentication no
#KerberosOrLocalPasswd yes
#KerberosTicketCleanup yes
#KerberosGetAFSToken no
#KerberosUseKuserok yes

# GSSAPI options
#GSSAPIAuthentication no
GSSAPIAuthentication yes
#GSSAPICleanupCredentials yes
GSSAPICleanupCredentials yes
#GSSAPIStrictAcceptorCheck yes
#GSSAPIKeyExchange no

# Set this to 'yes' to enable PAM authentication, account processing,
# and session processing. If this is enabled, PAM authentication will
# be allowed through the ChallengeResponseAuthentication and
# PasswordAuthentication.  Depending on your PAM configuration,
# PAM authentication via ChallengeResponseAuthentication may bypass
# the setting of "PermitRootLogin without-password".
# If you just want the PAM account and session checks to run without
# PAM authentication, then enable this but set PasswordAuthentication
# and ChallengeResponseAuthentication to 'no'.
#UsePAM no
UsePAM yes

# Accept locale-related environment variables
AcceptEnv LANG LC_CTYPE LC_NUMERIC LC_TIME LC_COLLATE LC_MONETARY LC_MESSAGES
AcceptEnv LC_PAPER LC_NAME LC_ADDRESS LC_TELEPHONE LC_MEASUREMENT
AcceptEnv LC_IDENTIFICATION LC_ALL LANGUAGE
AcceptEnv XMODIFIERS

#AllowAgentForwarding yes
#AllowTcpForwarding yes
#GatewayPorts no
#X11Forwarding no
X11Forwarding yes
#X11DisplayOffset 10
#X11UseLocalhost yes
#PrintMotd yes
#PrintLastLog yes
#TCPKeepAlive yes
#UseLogin no
#UsePrivilegeSeparation yes
#PermitUserEnvironment no
#Compression delayed
#ClientAliveInterval 0
#ClientAliveCountMax 3
#ShowPatchLevel no
UseDNS no
#PidFile /var/run/sshd.pid
#MaxStartups 10:30:100
#PermitTunnel no
#ChrootDirectory none

# no default banner path
#Banner none

# override default of no subsystems
Subsystem       sftp    /usr/libexec/openssh/sftp-server

# Example of overriding settings on a per-user basis
#Match User anoncvs
#       X11Forwarding no
#       AllowTcpForwarding no
#       ForceCommand cvs server

Any ideas would be much appreciated.


问:
How do forwarding types apply to IoC?
I'm still learning Castle Windsor and I see that it supports forwarded types - a term I was unfamiliar with.

Quick Google search and I found this article that explains it pretty throughly however I still don't understand how this applies to IoC or how I would use them from a container and for what reason.

Can anyone explain?

答:
Oh man, just did a google search on 'Castle Windsor "Forwarded Types"' and got redirected right back to SO:

Using Castle Windsor configuration files is it possible to delegate to another item declaration?

and from there:

What are “ForwardedTypes” in the context of Castle Windsor component registration?

Maybe Jeff and the team should just give up on trying to have their own search and use google's.

OwnerDisplayName: George Mauer

Title: How do forwarding types apply to IoC?


问:
EF4 CTP5 Code First approach ignores Table attributes
I'm using EF4 CTP5 code first approach but am having trouble getting it to work. I have a class called "Company" and a database table called "CompanyTable". I want to map the Company class to the CompanyTable table, so have code like this:

```<code>[Table(Name = "CompanyTable")]
    public class Company
    {
        [Key]
        [Column(Name = "CompanyIdNumber", DbType = "int")]
        public int CompanyNumber { get; set; }

        [Column(Name = "CompanyName", DbType = "varchar")]
        public string CompanyName { get; set; }
    }
</code>```

I then call it like so:

```<code>var db = new Users();
            var companies = (from c in db.Companies
                            select c).ToList();
</code>```

However it errors out:

Invalid object name 'dbo.Companies'.

It's obviously not respecting the Table attribute on the class, even though it says here that Table attribute is supported. Also it's pluralizing the name it's searching for (Companies instead of Company.) How do I map the class to the table name?

答: Forgot to add a reference to the ctp5 dll to my schemas project, it was using System.Data.Linq.Mapping instead.</p>

Body:
I'm using EF4 CTP5 code first approach but am having trouble getting it to work. I have a class called "Company" and a database table called "CompanyTable". I want to map the Company class to the CompanyTable table, so have code like this:

[Table(Name = "CompanyTable")]
    public class Company
    {
        [Key]
        [Column(Name = "CompanyIdNumber", DbType = "int")]
        public int CompanyNumber { get; set; }

        [Column(Name = "CompanyName", DbType = "varchar")]
        public string CompanyName { get; set; }
    }

I then call it like so:

var db = new Users();
            var companies = (from c in db.Companies
                            select c).ToList();

However it errors out:

Invalid object name 'dbo.Companies'.

It's obviously not respecting the Table attribute on the class, even though it says here that Table attribute is supported. Also it's pluralizing the name it's searching for (Companies instead of Company.) How do I map the class to the table name?


问:
Ruby's Single Inheritance Issue
I need some help defining an example that illustrates why single inheritance in Ruby is a problem.
The problem cannot be solved with single class inheritance.

Consider this an abstract example of the limitations Ruby faces with OO. I've tried to come up with a few examples but keep coming up short.

The idea is to then use a Module to provide a workaround to this issue that Ruby faces.

Any help is greatly appreciated. If you see my example below, it be great to get any feedback on whether it proves the above question or not.

Person superclass and Pet superclass don't belong to the same class hierarchy but share the same instance method swim. For that reason, the swim instance method is placed within a module and mixin to each superclass.

```<code>module Swimming
    def swim
      puts 'I can swim'.
    end
end

class Person

    include Swimming

    def initialize(name)
      @name = name
    end
end

class Boy < Person
end

class Pet
    include Swimming

    def initialize(name)
      @name = name
    end
end

class Fish < Pet
end

new_boy = Boy.new('Oliver')
new_fish = Fish.new('Ronald')
</code>```

答:
Mixins are used any time you want to include functionality from multiple places. Some other languages use multiple inheritance instead.

```<code>module Swimming; end
module Bicycling; end

class Person
  include Swimming
  include Bicycling
end
</code>```

If there was a class which used only one mixin, then it could easily be changed to an inheritance-based implementation:

```<code>class Swimming; end # not a module
class Amoeba < Swimming
end
</code>```

But something similar couldn't be done for the Person class without creating an intermediary class which wraps the modules.

```<code>class SwimmingAndBicycling
  include Swimming
  include Bicycling
end
class Person < SwimmingAndBicycling
end
</code>```

So modules are really the only simple way to combine 2+ pieces of functionality into a third. Ruby is a pretty flexible language and there are ways to get around this such as manually copying methods from one class to another. But this is the standard approach.

Also it's worth mentioning that classes and modules have some pragmatic differences which I'm not covering here. For example, in inheritance all instance and class methods are copied over, but with modules this depends on whether include or extend is called.

Title: Ruby's Single Inheritance Issue

Body:
I need some help defining an example that illustrates why single inheritance in Ruby is a problem.
The problem cannot be solved with single class inheritance.

Consider this an abstract example of the limitations Ruby faces with OO. I've tried to come up with a few examples but keep coming up short.

The idea is to then use a Module to provide a workaround to this issue that Ruby faces.

Any help is greatly appreciated. If you see my example below, it be great to get any feedback on whether it proves the above question or not.

Person superclass and Pet superclass don't belong to the same class hierarchy but share the same instance method swim. For that reason, the swim instance method is placed within a module and mixin to each superclass.

module Swimming
    def swim
      puts 'I can swim'.
    end
end

class Person

    include Swimming

    def initialize(name)
      @name = name
    end
end

class Boy < Person
end

class Pet
    include Swimming

    def initialize(name)
      @name = name
    end
end

class Fish < Pet
end

new_boy = Boy.new('Oliver')
new_fish = Fish.new('Ronald')

Body:
Mixins are used any time you want to include functionality from multiple places. Some other languages use multiple inheritance instead.

module Swimming; end
module Bicycling; end

class Person
  include Swimming
  include Bicycling
end

If there was a class which used only one mixin, then it could easily be changed to an inheritance-based implementation:

class Swimming; end # not a module
class Amoeba < Swimming
end

But something similar couldn't be done for the Person class without creating an intermediary class which wraps the modules.

class SwimmingAndBicycling
  include Swimming
  include Bicycling
end
class Person < SwimmingAndBicycling
end

So modules are really the only simple way to combine 2+ pieces of functionality into a third. Ruby is a pretty flexible language and there are ways to get around this such as manually copying methods from one class to another. But this is the standard approach.

Also it's worth mentioning that classes and modules have some pragmatic differences which I'm not covering here. For example, in inheritance all instance and class methods are copied over, but with modules this depends on whether include or extend is called.


问:
How to perform conditional required validation ussing ozzo validation in golang?
In Golang ozzo-validation, how can I validate a field which is dependent on another field ?

For example, if I have the following:

```<code>return validation.ValidateStruct(&c,
      validation.Field(&c.Name, validation.Required, validation.Length(5, 20)),

      validation.Field(&c.Gender, validation.In("Female", "Male")),

      validation.Field(&c.Email, is.Email),

      validation.Field(&c.Address),
</code>```

How can I add a validation that the Address is required only if email is not empty?

答:
You can achieve it in two ways-

<s>Adding your own custom rules</s>

Conditionally add FieldRules based on precondition-value i.e check Email while creating field rules then supply it to validation.ValidateStruct

For e.g.:

```<code>type Sample struct {
    Name    string
    Gender  string
    Email   string
    Address Address
}

type Address struct {
    // ... fields
}

func (s Sample) Validate() error {
    var fieldRules []*validation.FieldRules

    fieldRules = append(fieldRules, validation.Field(&s.Name, validation.Required, validation.Length(5, 20)))
    fieldRules = append(fieldRules, validation.Field(&s.Gender, validation.In("Female", "Male")))
    fieldRules = append(fieldRules, validation.Field(&s.Email, is.Email))

    if len(strings.TrimSpace(s.Email)) > 0 {
        fieldRules = append(fieldRules, validation.Field(&s.Address, validation.Required))
        fieldRules = append(fieldRules, validation.Field(&s.Address))
    }

    return validation.ValidateStruct(&s, fieldRules...)
}
</code>```

Body:
In Golang ozzo-validation, how can I validate a field which is dependent on another field ?

For example, if I have the following:

return validation.ValidateStruct(&c,
      validation.Field(&c.Name, validation.Required, validation.Length(5, 20)),

      validation.Field(&c.Gender, validation.In("Female", "Male")),

      validation.Field(&c.Email, is.Email),

      validation.Field(&c.Address),

How can I add a validation that the Address is required only if email is not empty?

Body:
You can achieve it in two ways-

<s>Adding your own custom rules</s>

Conditionally add FieldRules based on precondition-value i.e check Email while creating field rules then supply it to validation.ValidateStruct

For e.g.:

type Sample struct {
    Name    string
    Gender  string
    Email   string
    Address Address
}

type Address struct {
    // ... fields
}

func (s Sample) Validate() error {
    var fieldRules []*validation.FieldRules

    fieldRules = append(fieldRules, validation.Field(&s.Name, validation.Required, validation.Length(5, 20)))
    fieldRules = append(fieldRules, validation.Field(&s.Gender, validation.In("Female", "Male")))
    fieldRules = append(fieldRules, validation.Field(&s.Email, is.Email))

    if len(strings.TrimSpace(s.Email)) > 0 {
        fieldRules = append(fieldRules, validation.Field(&s.Address, validation.Required))
        fieldRules = append(fieldRules, validation.Field(&s.Address))
    }

    return validation.ValidateStruct(&s, fieldRules...)
}


问:
Swift - Use of unresolved identifier 'self' - from Closure in a Class
I am trying to reference a property in my class from a closure declared in my class. I cannot access self from inside my closure, and I'm assuming self would refer to the Class API from within my closure.

I want to declare a closure that I use later as a parameter to pass to a URLSession dataTask (It works without the one error line). I get the error listed in the title.

Use of unresolved identifier 'self'

I've been writing swift for an entire day now and am just trying things out as a sandbox, so I fully expect some criticism.

```<code>class Api {

    struct Location {
        var name = String()
        var author = String()
        var averageRating: String?
        var id = Int()
        var lat = Double()
        var lon = Double()
        var type = String()
    }

    var locations = [Location]()

    var doSomething = {(data: Data?, response: URLResponse?, error: Error?) -> Void in
        if error != nil {
            print(error!.localizedDescription)
        } else {
            do {
                if let json = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [String: Any] {
                    let myResult = json["results"] as! [[String: Any]]
                    var location : Location! = Location()
                    for jsonLocation in myResult {
                        if let name = jsonLocation["name"]{location.name = name as! String}
                        if let author = jsonLocation["author"]{location.author = author as! String}
                        if let id = jsonLocation["id"]{location.id = id as! Int}
                        if let lat = jsonLocation["lat"]{location.lat = lat as! Double}
                        if let lon = jsonLocation["lon"]{location.lon = lon as! Double}
                        if let type = jsonLocation["type"]{location.type = type as! String}

                        //ERROR IS HERE, Why does self not reference class API?
                        self.locations.append(location)
                    }
                }
            } catch {
                print("error in JSONSerialization")
            }
        }
    }
}
</code>```

I have found this, but this example is different so I wasn't sure if it was the same bug or me not understanding swift.

答:
Rahul's explanation is correct, but the suggested answer is ever so slightly incomplete.

Here is a complete solution:

Declare the doSomething property as lazy as Rahul suggested. A lazy stored property is a property whose initial value is not calculated until the first time it is used. In other words this closure will not be evaluated until the doSomething property is called at run-time, at which point self is guaranteed to exist. See Lazy Stored Properties in the Swift Programming Language for more details.

Add a type annotation to the doSomething property so the compiler doesn't have to infer the type at compile time, which apparently it can't do because the closure includes self. See Type Safety and Type Inference in the Swift Programming Language for more details.

So the complete declaration is:

```<code>...
lazy var doSomething: (Data?, URLResponse?, Error?) -> Void = { (data: Data?, response: URLResponse?, error: Error?) -> Void in
...
</code>```

ps. Welcome to Swift programming! It's a fantastic language and really fun. I hope you enjoy it as much as I do.

Body:
I am trying to reference a property in my class from a closure declared in my class. I cannot access self from inside my closure, and I'm assuming self would refer to the Class API from within my closure.

I want to declare a closure that I use later as a parameter to pass to a URLSession dataTask (It works without the one error line). I get the error listed in the title.

Use of unresolved identifier 'self'

I've been writing swift for an entire day now and am just trying things out as a sandbox, so I fully expect some criticism.

class Api {

    struct Location {
        var name = String()
        var author = String()
        var averageRating: String?
        var id = Int()
        var lat = Double()
        var lon = Double()
        var type = String()
    }

    var locations = [Location]()

    var doSomething = {(data: Data?, response: URLResponse?, error: Error?) -> Void in
        if error != nil {
            print(error!.localizedDescription)
        } else {
            do {
                if let json = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [String: Any] {
                    let myResult = json["results"] as! [[String: Any]]
                    var location : Location! = Location()
                    for jsonLocation in myResult {
                        if let name = jsonLocation["name"]{location.name = name as! String}
                        if let author = jsonLocation["author"]{location.author = author as! String}
                        if let id = jsonLocation["id"]{location.id = id as! Int}
                        if let lat = jsonLocation["lat"]{location.lat = lat as! Double}
                        if let lon = jsonLocation["lon"]{location.lon = lon as! Double}
                        if let type = jsonLocation["type"]{location.type = type as! String}

                        //ERROR IS HERE, Why does self not reference class API?
                        self.locations.append(location)
                    }
                }
            } catch {
                print("error in JSONSerialization")
            }
        }
    }
}

I have found this, but this example is different so I wasn't sure if it was the same bug or me not understanding swift.

Body:
Rahul's explanation is correct, but the suggested answer is ever so slightly incomplete.

Here is a complete solution:

Declare the doSomething property as lazy as Rahul suggested. A lazy stored property is a property whose initial value is not calculated until the first time it is used. In other words this closure will not be evaluated until the doSomething property is called at run-time, at which point self is guaranteed to exist. See Lazy Stored Properties in the Swift Programming Language for more details.

Add a type annotation to the doSomething property so the compiler doesn't have to infer the type at compile time, which apparently it can't do because the closure includes self. See Type Safety and Type Inference in the Swift Programming Language for more details.

So the complete declaration is:

...
lazy var doSomething: (Data?, URLResponse?, Error?) -> Void = { (data: Data?, response: URLResponse?, error: Error?) -> Void in
...

ps. Welcome to Swift programming! It's a fantastic language and really fun. I hope you enjoy it as much as I do.


问:
Error with Actions observable in @ngrx/effects using TypeScript 2.4.1

After updating to TypeScript 2.4.1, compiling projects that use the Actions observable from @ngrx/effects (version 2.0.3) sees the following error thrown:

Error TS2684: The 'this' context of type 'Actions' is not assignable to method's 'this' of type 'Observable<any>'.
Error TS7006: Parameter 'action' implicitly has an 'any' type.
Error TS2345: Argument of type 'Actions' is not assignable to parameter of type 'Observable<Action>'.
  Types of property 'lift' are incompatible.
    Type '(operator: Operator<any, Action>) => Observable<Action>' is not assignable to type '<R>(operator: Operator<Action, R>) => Observable<R>'.
      Types of parameters 'operator' and 'operator' are incompatible.
        Type 'Operator<Action, R>' is not assignable to type 'Operator<any, Action>'.
          Type 'R' is not assignable to type 'Action'.
```

How can this be resovled?

答:
TypeScript 2.4.1 more strictly enforces the the generic signature of the lift method in Observable and the Actions observable's implementation of lift fails the check.

The check can be disabled using the --noStrictGenericChecks command line flag or the noStrictGenericChecks compiler option (as a parameter in tsconfig.json's "compilerOptions" object).

An alternative to disabling the checks is to use TypeScript's interface augmentation to specify a correct signature:

import { Action } from "@ngrx/store";
import { Observable } from "rxjs/Observable";
import { Operator } from "rxjs/Operator";

declare module "@ngrx/effects/src/actions" {
    interface Actions {
        lift<R>(operator: Operator<Action, R>): Observable<R>;
    }
}
```

Note that the full path to the module/file must be used; it's not sufficient to specify @ngrx/effects as the module name.

This has been resolved with the release of @ngrx/effects 2.0.4.

Body:
After updating to TypeScript 2.4.1, compiling projects that use the Actions observable from @ngrx/effects (version 2.0.3) sees the following error thrown:

Error TS2684: The 'this' context of type 'Actions' is not assignable to method's 'this' of type 'Observable<any>'.
Error TS7006: Parameter 'action' implicitly has an 'any' type.
Error TS2345: Argument of type 'Actions' is not assignable to parameter of type 'Observable<Action>'.
  Types of property 'lift' are incompatible.
    Type '(operator: Operator<any, Action>) => Observable<Action>' is not assignable to type '<R>(operator: Operator<Action, R>) => Observable<R>'.
      Types of parameters 'operator' and 'operator' are incompatible.
        Type 'Operator<Action, R>' is not assignable to type 'Operator<any, Action>'.
          Type 'R' is not assignable to type 'Action'.

How can this be resovled?

Body:
TypeScript 2.4.1 more strictly enforces the the generic signature of the lift method in Observable and the Actions observable's implementation of lift fails the check.

The check can be disabled using the --noStrictGenericChecks command line flag or the noStrictGenericChecks compiler option (as a parameter in tsconfig.json's "compilerOptions" object).

An alternative to disabling the checks is to use TypeScript's interface augmentation to specify a correct signature:

import { Action } from "@ngrx/store";
import { Observable } from "rxjs/Observable";
import { Operator } from "rxjs/Operator";

declare module "@ngrx/effects/src/actions" {
    interface Actions {
        lift<R>(operator: Operator<Action, R>): Observable<R>;
    }
}

Note that the full path to the module/file must be used; it's not sufficient to specify @ngrx/effects as the module name.

This has been resolved with the release of @ngrx/effects 2.0.4.


问:
Visual Studio for Mac throwing MTOUCH MT0008 error "You should provide one root assembly only"
Recently upgraded from Xamarin Studio to Visual Studio for Mac. Trying to build an existing iOS project I'm receiving the following build error:

/Projects/ACME Networks/Alpha Xamarin/iOS/MTOUCH: Error MT0008: You should provide one root assembly only, found 3 assemblies: 'Networks/Alpha', 'Xamarin/iOS/obj/iPhoneSimulator/Debug/device-builds/iphone9.1-10.3/Entitlements.xcent/', '/Projects/ACME Networks/Alpha Xamarin/iOS/bin/iPhoneSimulator/Debug/MyNetApp.iOS.exe' (MT0008) (App)

It appears to me that something in the IDE is getting confused because the path to the solution includes folders that have spaces in them, "ACME Networks" and "Alpha Xamarin".

I've got no clue how to fix this. Tried cleaning and rebuilding.

答:
Usually this problem means that you have spaces in the directory names of your project.

Visual Studio for Windows allow us to create projects with spaces in the directory names, but Xamarin or Visual Studio for Mac doesn't. When you copy a project from Windows to Mac, it should work right away as they say. But it doesn't, and this is one of the problems.

You can change the spaces to a different character like "_" or "-" or just remove the spaces.

Be sure to edit yourproject.sln file lines pointing to your .csproj files to the new path and you should be good.


问:
Autodesk Data Management API 403-Error
I am trying to receive data via Autodesk Data Management API. So far I've created an Forge-App and connected it with a BIM360 Integration.
Then I wanted to get a list of all hubs, but when I do so, I receive an JSON-Object which contains a warning:

```<code>warnings: [{
     "AboutLink":null,
     "Detail":""You don't have permission to access this API",
     "ErrorCode": "BIM360DM_ERROR",
     "HttpStatusCode": "403",
     ...
}]
</code>```

I called the webservice via AJAX wich looks like that:

```<code>this.getToken(function(token) {
        $.ajax({
            url: "https://developer.api.autodesk.com/project/v1/hubs",
            beforeSend: function(xhr) {
                xhr.setRequestHeader("Authorization", "Bearer "+token);
            }
        }).done(...);
</code>```

The token is a 3-legged one. I am not sure which API I do not have permission for because I am pretty sure, that I have permission for BIM360.(I created the Integration as an administrator).

答:
Does everything else work fine? For example, can you get all the hubs successfully? I just verified on my side, and I can see the response including the same warning as you mentioned, but the hubs are listed correctly, and you can get the projects/items/versions without problem. I pasted my postman response as follow.

If you check the blog https://forge.autodesk.com/blog/tutorial-using-curl-3-legged-authentication-bim-360-docs-upload, it also has the same warning, but seems no impact to the following operation. I am not exactly sure what the warning means, l will check and update the details, but so far, it seems you can ignore it for now.

Title: Autodesk Data Management API 403-Error

Body:
I am trying to receive data via Autodesk Data Management API. So far I've created an Forge-App and connected it with a BIM360 Integration.
Then I wanted to get a list of all hubs, but when I do so, I receive an JSON-Object which contains a warning:

warnings: [{
     "AboutLink":null,
     "Detail":""You don't have permission to access this API",
     "ErrorCode": "BIM360DM_ERROR",
     "HttpStatusCode": "403",
     ...
}]

I called the webservice via AJAX wich looks like that:

this.getToken(function(token) {
        $.ajax({
            url: "https://developer.api.autodesk.com/project/v1/hubs",
            beforeSend: function(xhr) {
                xhr.setRequestHeader("Authorization", "Bearer "+token);
            }
        }).done(...);

The token is a 3-legged one. I am not sure which API I do not have permission for because I am pretty sure, that I have permission for BIM360.(I created the Integration as an administrator).


问:
Failed to read SQLite-net.dll during debugging symbols
When I try build application using xamarin forms in visual studio and deploy on android emulator this warning appears.

Failed to read 'G:\ApkiC-Sharp\GNote\GNote\GNote.Android\obj\Debug\android\assets\SQLite-net.dll' with debugging symbols. Retrying to load it without it. Error details are logged below. GNote.Android

Details Bellow:

Severity  Code    Description Project File    Line    Suppression State
  Warning     Mono.CompilerServices.SymbolWriter.MonoSymbolFileException: Symbol file G:\ApkiC-Sharp\GNote\GNote\GNote.Android\obj\Debug\android\assets\SQLite-net.dll.mdb' does not match assembly
     at Mono.CompilerServices.SymbolWriter.MonoSymbolFile.ReadSymbolFile(String mdbFilename, Guid assemblyGuid)
     at Mono.Cecil.Mdb.MdbReaderProvider.GetSymbolReader(ModuleDefinition module, String fileName)
     at Mono.Cecil.Cil.DefaultSymbolReaderProvider.GetSymbolReader(ModuleDefinition module, String fileName)
     at Mono.Cecil.ModuleReader.ReadSymbols(ModuleDefinition module, ReaderParameters parameters)
     at Mono.Cecil.ModuleReader.CreateModule(Image image, ReaderParameters parameters)
     at Mono.Cecil.ModuleDefinition.ReadModule(Disposable1 stream, String fileName, ReaderParameters parameters)
     at Mono.Cecil.ModuleDefinition.ReadModule(String fileName, ReaderParameters parameters)
     at Mono.Cecil.AssemblyDefinition.ReadAssembly(String fileName, ReaderParameters parameters)
     at Java.Interop.Tools.Cecil.DirectoryAssemblyResolver.ReadAssembly(String file)  GNote.Android

How can I fix it?

Thank you

答:
Try it:
Right click your android project
Properties -> Android Options -> drop down "Linking" to None.

It will include the symbols on package, but will increase your app size.

I'm trying to find another better solution, but this works for now.


问:
Any feature in BigQuery that can migrate a whole dataset in another project w/o executing copy data?
While our project grows, at some point we realized that we need to create new projects and reorganize our dataset. One case is that we need to isolate one dataset from others into another new project. I know that I can do it by copying tables one by one through API and then delete the old ones. But when it comes to over a thousand of tables, it's really consumes a lot of time as the copying api is executed as a job and it takes time. Is it possible to just change reference(or path) of a dataset?

Follow up
I tried copy tables using batch request. I got 200 OK in all request, but the tables just didn't get copied. I wonder why and how to get the real result. Here's my code:

```<code>    public async Task CopyTableToProjectInBatchAsync(IList<TableList.TablesData> fromTables, string toProjectId)
    {
        var request = new BatchRequest(BigQueryService);
        foreach (var tableData in fromTables)
        {
            string fromDataset = tableData.TableReference.DatasetId;
            string fromTableId = tableData.TableReference.TableId;
            Logger.Info("copying table {0}...",tableData.Id);
            request.Queue<JobReference>(CreateTableCopyRequest(fromDataset, fromTableId, toProjectId),
            (content, error, i, message) =>
            {
                Logger.Info("#content:\n" + content);
                Logger.Info("#error:\n" + error);
                Logger.Info("#i:\n" + i);
                Logger.Info("#message:\n" + message);
            });
        }
        await request.ExecuteAsync();
    }

   private IClientServiceRequest CreateTableCopyRequest(string fromDatasetId, string fromTableId, string toProjectId,
        string toDatasetId=null, string toTableId=null)
    {
        if (toDatasetId == null)
            toDatasetId = fromDatasetId;
        if (toTableId == null)
            toTableId = fromTableId;
        TableReference sourceTableReference = new TableReference
        {
            ProjectId = _account.ProjectId,
            DatasetId = fromDatasetId,
            TableId = fromTableId
        };
        TableReference targetTableReference = new TableReference
        {
            ProjectId = toProjectId,
            DatasetId = toDatasetId,
            TableId = toTableId
        };
        JobConfigurationTableCopy copyConfig = new JobConfigurationTableCopy
        {
            CreateDisposition = "WRITE_TRUNCATE",
            DestinationTable = targetTableReference,
            SourceTable = sourceTableReference
        };
        JobReference jobRef = new JobReference {JobId = GenerateJobID("copyTable"), ProjectId = _account.ProjectId};
        JobConfiguration jobConfig = new JobConfiguration {Copy = copyConfig};
        Job job = new Job {Configuration = jobConfig, JobReference = jobRef};

        return BigQueryService.Jobs.Insert(job, _account.ProjectId);
    }
</code>```

答:
A short shell script which copies all tables from a dataset to another dataset:</p>

```<code>export SOURCE_DATASET=$1  # project1:dataset
export DEST_PREFIX=$2  # project2:dataset2.any_prefix_
for f in `bq ls $SOURCE_DATASET |grep TABLE | awk '{print $1}'`
do
  export CP_COMMAND="bq cp $SOURCE_DATASET.$f $DEST_PREFIX$f"
  echo $CP_COMMAND
  echo `$CP_COMMAND`
done
</code>```

Body:
While our project grows, at some point we realized that we need to create new projects and reorganize our dataset. One case is that we need to isolate one dataset from others into another new project. I know that I can do it by copying tables one by one through API and then delete the old ones. But when it comes to over a thousand of tables, it's really consumes a lot of time as the copying api is executed as a job and it takes time. Is it possible to just change reference(or path) of a dataset?

Follow up
I tried copy tables using batch request. I got 200 OK in all request, but the tables just didn't get copied. I wonder why and how to get the real result. Here's my code:

    public async Task CopyTableToProjectInBatchAsync(IList<TableList.TablesData> fromTables, string toProjectId)
    {
        var request = new BatchRequest(BigQueryService);
        foreach (var tableData in fromTables)
        {
            string fromDataset = tableData.TableReference.DatasetId;
            string fromTableId = tableData.TableReference.TableId;
            Logger.Info("copying table {0}...",tableData.Id);
            request.Queue<JobReference>(CreateTableCopyRequest(fromDataset, fromTableId, toProjectId),
            (content, error, i, message) =>
            {
                Logger.Info("#content:\n" + content);
                Logger.Info("#error:\n" + error);
                Logger.Info("#i:\n" + i);
                Logger.Info("#message:\n" + message);
            });
        }
        await request.ExecuteAsync();
    }

   private IClientServiceRequest CreateTableCopyRequest(string fromDatasetId, string fromTableId, string toProjectId,
        string toDatasetId=null, string toTableId=null)
    {
        if (toDatasetId == null)
            toDatasetId = fromDatasetId;
        if (toTableId == null)
            toTableId = fromTableId;
        TableReference sourceTableReference = new TableReference
        {
            ProjectId = _account.ProjectId,
            DatasetId = fromDatasetId,
            TableId = fromTableId
        };
        TableReference targetTableReference = new TableReference
        {
            ProjectId = toProjectId,
            DatasetId = toDatasetId,
            TableId = toTableId
        };
        JobConfigurationTableCopy copyConfig = new JobConfigurationTableCopy
        {
            CreateDisposition = "WRITE_TRUNCATE",
            DestinationTable = targetTableReference,
            SourceTable = sourceTableReference
        };
        JobReference jobRef = new JobReference {JobId = GenerateJobID("copyTable"), ProjectId = _account.ProjectId};
        JobConfiguration jobConfig = new JobConfiguration {Copy = copyConfig};
        Job job = new Job {Configuration = jobConfig, JobReference = jobRef};

        return BigQueryService.Jobs.Insert(job, _account.ProjectId);
    }

Body:
A short shell script which copies all tables from a dataset to another dataset:

export SOURCE_DATASET=$1  # project1:dataset
export DEST_PREFIX=$2  # project2:dataset2.any_prefix_
for f in `bq ls $SOURCE_DATASET |grep TABLE | awk '{print $1}'`
do
  export CP_COMMAND="bq cp $SOURCE_DATASET.$f $DEST_PREFIX$f"
  echo $CP_COMMAND
  echo `$CP_COMMAND`
done


问:
TFS2015 Visual Studio Test: Could not load file or assembly
I have an "old" XAML Build Definition, made in Visual Studio; which builds a solution and following runs unit tests.
Now I've tried to make the same in the new TFS 2015 web surface.
I've created a build task, following Visual Studio Test.

But now the Test-Task exit with code 1 and gives me a lot of
"System.IO.FileNotFoundException: Could not load file or assembly" errors.
And also "Warning: MSTestAdapter failed to discover tests in class ..."

All the DLLs are where they have to be, the new definition has the same directory structure like the old one, but the test-task says there are missing assemblys.

Any ideas?

Update:
No, I still have the same error messages:

```<code>Warning: Unable to load types from the test source 'J:\xyz-Tests.dll'. Some or all of the tests in this source may not be discovered. If you are running unit tests for Windows Store apps and referencing custom WinMD type then please visit http://go.microsoft.com/fwlink/?LinkId=238340 for more info. Error details: System.IO.FileNotFoundException: Could not load file or assembly 'xyz_Commons, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The system cannot find the file specified.
System.IO.FileNotFoundException: Could not load file or assembly 'xyz_Processing, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The system cannot find the file specified.
System.IO.FileNotFoundException: Could not load file or assembly 'xyzCommons, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The system cannot find the file specified.
</code>```

答:
This should exactly be the issue mentioned in below article, please try following the workaround to fix it:

Running Coded UI Tests built using Visual Studio 2013 with Team Foundation Server 2015

Test execution is failing in this scenario because test execution
engine is not able to resolve the old version binaries while executing
tests in a 14.0 environment (TFS 2015).

So, you need to update the projects to reference the new versions of the assemblies (VS 2015 in this scenario) using the assembly bindings in the test projects config file.

As a workaround to this issue, add an ‘app.config’ file to your
solution (See how to add app.config
https://msdn.microsoft.com/en-in/library/ms184658.aspx) and update the
contents of the file with the shared on OneDrive . The updated
configuration files contain assembly redirects from version 12.0 to
14.0, which will make sure that the test agent machine is able to resolve the framework assemblies. Check-in the updated configuration
file into the source control repository and run the BDT scenario once
again. The tests should run fine this time.   If the test execution
again throws an error complaining version mismatch for some other
assembly, add the assembly to the app.config file and retry.

You can also reference this article :
http://www.dotnetcatch.com/2015/10/01/tfs-2010-to-2015-upgrade-codedui-feature-test-builds/

Body:
I have an "old" XAML Build Definition, made in Visual Studio; which builds a solution and following runs unit tests.
Now I've tried to make the same in the new TFS 2015 web surface.
I've created a build task, following Visual Studio Test.

But now the Test-Task exit with code 1 and gives me a lot of
"System.IO.FileNotFoundException: Could not load file or assembly" errors.
And also "Warning: MSTestAdapter failed to discover tests in class ..."

All the DLLs are where they have to be, the new definition has the same directory structure like the old one, but the test-task says there are missing assemblys.

Any ideas?

Update:
No, I still have the same error messages:

Warning: Unable to load types from the test source 'J:\xyz-Tests.dll'. Some or all of the tests in this source may not be discovered. If you are running unit tests for Windows Store apps and referencing custom WinMD type then please visit http://go.microsoft.com/fwlink/?LinkId=238340 for more info. Error details: System.IO.FileNotFoundException: Could not load file or assembly 'xyz_Commons, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The system cannot find the file specified.
System.IO.FileNotFoundException: Could not load file or assembly 'xyz_Processing, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The system cannot find the file specified.
System.IO.FileNotFoundException: Could not load file or assembly 'xyzCommons, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The system cannot find the file specified.


问:
Using CHAR(13) in a FOR XML SELECT
I'm trying to use CHAR(13) to force a new line, but the problem is, I'm doing this within a FOR XML Select statement:

```<code>SELECT
    STUFF((SELECT CHAR(13) + Comment
FROM
   myTable
FOR XML PATH ('')) , 1, 1, '')
</code>```

The problem with this, is that I don't get an actual new line.  Instead, I get:

```<code>#x0D;
</code>```

So the data literally looks like this:

```<code>#x0D;First Line of Data#x0D;Second Line of Data#x0D;Etc
</code>```

So I tried to just replace #x0D; with CHAR(13) outside of the FOR XML:

```<code>REPLACE(SELECT
    STUFF((SELECT CHAR(13) + Comment
FROM
   myTable
FOR XML PATH ('')) , 1, 1, '')), '#x0D;', CHAR(13))
</code>```

This gets me close.  It DOES add in the line breaks, but it also includes an & at the end of each line, and the start of each line after the first:

```<code>First Line of Data&
&Second Line of Data&
&Etc
</code>```

答:
I think this is cleaner.  Basically start with line feeds (or some other special character) then replace them with carriage returns plus line feeds if you want.</p>

```<code>Select REPLACE(STUFF((SELECT CHAR(10) + Comment
                      FROM myTable FOR XML PATH ('')) , 1, 1, ''),
              CHAR(10), CHAR(13)+CHAR(10))
</code>```

Title: Using CHAR(13) in a FOR XML SELECT

Body:
I'm trying to use CHAR(13) to force a new line, but the problem is, I'm doing this within a FOR XML Select statement:

SELECT
    STUFF((SELECT CHAR(13) + Comment
FROM
   myTable
FOR XML PATH ('')) , 1, 1, '')

The problem with this, is that I don't get an actual new line.  Instead, I get:

#x0D;

So the data literally looks like this:

#x0D;First Line of Data#x0D;Second Line of Data#x0D;Etc

So I tried to just replace #x0D; with CHAR(13) outside of the FOR XML:

REPLACE(SELECT
    STUFF((SELECT CHAR(13) + Comment
FROM
   myTable
FOR XML PATH ('')) , 1, 1, '')), '#x0D;', CHAR(13))

This gets me close.  It DOES add in the line breaks, but it also includes an & at the end of each line, and the start of each line after the first:

First Line of Data&
&Second Line of Data&
&Etc

Body:
I think this is cleaner.  Basically start with line feeds (or some other special character) then replace them with carriage returns plus line feeds if you want.

Select REPLACE(STUFF((SELECT CHAR(10) + Comment
                      FROM myTable FOR XML PATH ('')) , 1, 1, ''),
              CHAR(10), CHAR(13)+CHAR(10))


问:
'Task' does not contain a definition for 'CompletedTask' for C#
I'm following the tutorial at https://discord.foxbot.me/docs/guides/getting_started/intro.html to a tee, and yet I'm getting an error when I try to use

```<code>return Task.CompletedTask
</code>```

and I get this error

```<code>'Task' does not contain a definition for 'CompletedTask'
</code>```

I am

```<code>using System.Threading.Tasks
</code>```

答:
Task.CompletedTask is a static property added in .NET 4.6.  Here is its source, and here is its MSDN page which shows the minimum framework version.

Just for completeness, here is how you change the .NET Framework version you are using in your project.

Body:
I'm following the tutorial at https://discord.foxbot.me/docs/guides/getting_started/intro.html to a tee, and yet I'm getting an error when I try to use

return Task.CompletedTask

and I get this error

'Task' does not contain a definition for 'CompletedTask'

I am

using System.Threading.Tasks


问:
how to create multiple udp clients listenning to the same port in java nio?
for normal io ,  I can do it like this:

```<code>s1=new DatagramSocket(1234)
s2=new DatagramSocket(1234)

bytes=xxxxxx
packet = DatagramPacket(bytes, bytes.size,InetSocketAddress("localhost",1234))
new DatagramSocket().send(packet)
//  and then the s1 and s2 can receive the packet.
</code>```

but in nio.  how to do this? I tried like this:

first:

```<code>s1=DatagramChannel.open()
s1.bind(new Inetsocketaddress("localhost",1234)

s2=DatagramChannel.open()
s2.bind(new Inetsocketaddress("localhost",1234)// will throw an exception
</code>```

second:

```<code>s1=DatagramChannel.open()
s1.setOption(StandardSocketOptions.SO_REUSEADDR, true);
s1.bind(new Inetsocketaddress("localhost",1234)

s2=DatagramChannel.open()
s2.setOption(StandardSocketOptions.SO_REUSEADDR, true);
s2.bind(new Inetsocketaddress("localhost",1234)

//these code will not throw exception. but s2 cannot receive any data.
// when i close s1,  then s2 will receive data.
</code>```

答:
I know the reason.

The Unicast can only be received by one client,if several clients listen the same port, only the first client will receive the data.

If you want several clients receive the data, you should use Multicast or Broadcast.

If you use the Broadcast, the packet should be sent to 255.255.255:port,so all the clients listening the port will receive the data.
and the clients bind address could not use localhost or 127.0.0.1.  you should use 0.0.0.0 or InetSocketAddress(port) or your local address like 192.168.100.123

If any other application bind a port without 'reuseAddress', then you can not bind the port too.

the kotlin code:

```<code>fun main(args: Array<String>) {
    val selector = Selector.open()
    val reader = DatagramChannel.open()
    val sender = DatagramChannel.open()

    reader.configureBlocking(false)
    reader.socket().reuseAddress = true
//    reader.bind(InetSocketAddress("0.0.0.0", 1234))
//    reader.bind(InetSocketAddress("192.168.100.37", 1234))
    reader.bind(InetSocketAddress(1234))
    reader.register(selector, SelectionKey.OP_READ)

    sender.socket().broadcast = true

    val t = Thread {
        while (true) {
            val line = readLine()
            if (line != null) {
                val buffer = ByteBuffer.wrap(line.toByteArray())
                sender.send(buffer, InetSocketAddress("255.255.255.255", 1234))
            }
        }
    }
    t.isDaemon = true
    t.start()

    while (selector.isOpen) {
        val n = selector.select()
        if (n == 0) continue
        val keys = selector.selectedKeys().iterator()
        while (keys.hasNext()) {
            val key = keys.next()
            keys.remove()
            if (key.isReadable) {
                val buffer = ByteBuffer.allocateDirect(1024)
                val channel = key.channel() as DatagramChannel
                val address = channel.receive(buffer)
                buffer.flip()
                val s = Charsets.UTF_8.decode(buffer)
                println("$address says : $s")
            }
        }
    }
}
</code>```

Body:
for normal io ,  I can do it like this:

s1=new DatagramSocket(1234)
s2=new DatagramSocket(1234)

bytes=xxxxxx
packet = DatagramPacket(bytes, bytes.size,InetSocketAddress("localhost",1234))
new DatagramSocket().send(packet)
//  and then the s1 and s2 can receive the packet.

but in nio.  how to do this? I tried like this:

first:

s1=DatagramChannel.open()
s1.bind(new Inetsocketaddress("localhost",1234)

s2=DatagramChannel.open()
s2.bind(new Inetsocketaddress("localhost",1234)// will throw an exception

second:

s1=DatagramChannel.open()
s1.setOption(StandardSocketOptions.SO_REUSEADDR, true);
s1.bind(new Inetsocketaddress("localhost",1234)

s2=DatagramChannel.open()
s2.setOption(StandardSocketOptions.SO_REUSEADDR, true);
s2.bind(new Inetsocketaddress("localhost",1234)

//these code will not throw exception. but s2 cannot receive any data.
// when i close s1,  then s2 will receive data.

Body:
I know the reason.

The Unicast can only be received by one client,if several clients listen the same port, only the first client will receive the data.

If you want several clients receive the data, you should use Multicast or Broadcast.

If you use the Broadcast, the packet should be sent to 255.255.255:port,so all the clients listening the port will receive the data.
and the clients bind address could not use localhost or 127.0.0.1.  you should use 0.0.0.0 or InetSocketAddress(port) or your local address like 192.168.100.123

If any other application bind a port without 'reuseAddress', then you can not bind the port too.

the kotlin code:

fun main(args: Array<String>) {
    val selector = Selector.open()
    val reader = DatagramChannel.open()
    val sender = DatagramChannel.open()

    reader.configureBlocking(false)
    reader.socket().reuseAddress = true
//    reader.bind(InetSocketAddress("0.0.0.0", 1234))
//    reader.bind(InetSocketAddress("192.168.100.37", 1234))
    reader.bind(InetSocketAddress(1234))
    reader.register(selector, SelectionKey.OP_READ)

    sender.socket().broadcast = true

    val t = Thread {
        while (true) {
            val line = readLine()
            if (line != null) {
                val buffer = ByteBuffer.wrap(line.toByteArray())
                sender.send(buffer, InetSocketAddress("255.255.255.255", 1234))
            }
        }
    }
    t.isDaemon = true
    t.start()

    while (selector.isOpen) {
        val n = selector.select()
        if (n == 0) continue
        val keys = selector.selectedKeys().iterator()
        while (keys.hasNext()) {
            val key = keys.next()
            keys.remove()
            if (key.isReadable) {
                val buffer = ByteBuffer.allocateDirect(1024)
                val channel = key.channel() as DatagramChannel
                val address = channel.receive(buffer)
                buffer.flip()
                val s = Charsets.UTF_8.decode(buffer)
                println("$address says : $s")
            }
        }
    }
}


问:
Converting an image to base64 in angular 2
Converting an image to base64 in angular 2, image is uploaded from local . Current am using fileLoadedEvent.target.result. The problem is, when I send this base64 string through REST services to java, it is not able to decode it. When i try this base64 string with free online encoder-decoder, there also I cannot see decoded image. I tried using canvas also. Am not getting proper result. One thing is sure the base64 string what am getting is not proper one, do I need to add any package for this ? Or in angular 2 is there any perticular way to encode the image to base64 as it was there in angular 1 - angular-base64-upload package.

Pls find below my sample code

```<code>onFileChangeEncodeImageFileAsURL(event:any,imgLogoUpload:any,imageForLogo:any,imageDiv:any)
{
    var filesSelected = imgLogoUpload.files;
    var self = this;
    if (filesSelected.length > 0) {
      var fileToLoad = filesSelected[0];

      //Reading Image file, encode and display
       var  reader: FileReader = new FileReader();
       reader.onloadend = function(fileLoadedEvent:any) {

       //SECOND METHO
       var imgSrcData = fileLoadedEvent.target.result; // <--- data: base64

        var newImage = imageForLogo;
        newImage.src = imgSrcData;
        imageDiv.innerHTML = newImage.outerHTML;

      }
      reader.readAsDataURL(fileToLoad);
    }
}
</code>```

答:
another solution thats works for base64 is something like this post
https://stackoverflow.com/a/36281449/6420568

in my case, i did

```<code>getImagem(readerEvt, midia){
    //console.log('change no input file', readerEvt);
    let file = readerEvt.target.files[0];
    var reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = function () {
        //console.log('base64 do arquivo',reader.result);
        midia.binario = btoa(reader.result);
        //console.log('base64 do arquivo codificado',midia.binario);
    };
    reader.onerror = function (error) {
        console.log('Erro ao ler a imagem : ', error);
    };
}
</code>```

and html component

```<code><input type="file" class="form-control"  (change)="getImagem($event, imagem)">

<img class="img-responsive"  src="{{imagem.binario | decode64 }}" alt="imagem..." style="width: 200px;"/>
</code>```

to display the image, i created the pipe decode64

```<code>@Pipe({
  name: 'decode64'
})
export class Decode64Pipe implements PipeTransform {
  transform(value: any, args?: any): any {
    let a = '';
    if(value){
       a = atob(value);
    }
    return a;
  }
}
</code>```

Body:
Converting an image to base64 in angular 2, image is uploaded from local . Current am using fileLoadedEvent.target.result. The problem is, when I send this base64 string through REST services to java, it is not able to decode it. When i try this base64 string with free online encoder-decoder, there also I cannot see decoded image. I tried using canvas also. Am not getting proper result. One thing is sure the base64 string what am getting is not proper one, do I need to add any package for this ? Or in angular 2 is there any perticular way to encode the image to base64 as it was there in angular 1 - angular-base64-upload package.

Pls find below my sample code

onFileChangeEncodeImageFileAsURL(event:any,imgLogoUpload:any,imageForLogo:any,imageDiv:any)
{
    var filesSelected = imgLogoUpload.files;
    var self = this;
    if (filesSelected.length > 0) {
      var fileToLoad = filesSelected[0];

      //Reading Image file, encode and display
       var  reader: FileReader = new FileReader();
       reader.onloadend = function(fileLoadedEvent:any) {

       //SECOND METHO
       var imgSrcData = fileLoadedEvent.target.result; // <--- data: base64

        var newImage = imageForLogo;
        newImage.src = imgSrcData;
        imageDiv.innerHTML = newImage.outerHTML;

      }
      reader.readAsDataURL(fileToLoad);
    }
}

Body:
another solution thats works for base64 is something like this post
https://stackoverflow.com/a/36281449/6420568

in my case, i did

getImagem(readerEvt, midia){
    //console.log('change no input file', readerEvt);
    let file = readerEvt.target.files[0];
    var reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = function () {
        //console.log('base64 do arquivo',reader.result);
        midia.binario = btoa(reader.result);
        //console.log('base64 do arquivo codificado',midia.binario);
    };
    reader.onerror = function (error) {
        console.log('Erro ao ler a imagem : ', error);
    };
}

and html component

<input type="file" class="form-control"  (change)="getImagem($event, imagem)">

<img class="img-responsive"  src="{{imagem.binario | decode64 }}" alt="imagem..." style="width: 200px;"/>

to display the image, i created the pipe decode64

@Pipe({
  name: 'decode64'
})
export class Decode64Pipe implements PipeTransform {
  transform(value: any, args?: any): any {
    let a = '';
    if(value){
       a = atob(value);
    }
    return a;
  }
}


问:
CSS issue - disable scroll on x-direction and fit in the center
One of the pages in my website is having an issue where the page is scrollable on x-position which results the content to be cutoff. Other pages on this website is fine except for this one. I've fiddled with the classes and margin but for some reason I can't get it right.

(Live preview on responsive mode [mobile phones]: http://hub.mymagic.my/idea/frontend/explore)

Need another eye for this. Any help is greatly appreciated.

答:
using chrome's toggle device toolbar + inspect source code, i was able to trace this CSS line on frontend.css:

```<code>.cbp .cbp-item {
    width: 350px;
...
...
...
}
</code>```

It seems that this width is making the content to extend beyond the size of mobile browser thus making it appear to be scrollable. I guess you can play or override this value somewhere or replace it with max-width attribute.

Body:
using chrome's toggle device toolbar + inspect source code, i was able to trace this CSS line on frontend.css:

.cbp .cbp-item {
    width: 350px;
...
...
...
}

It seems that this width is making the content to extend beyond the size of mobile browser thus making it appear to be scrollable. I guess you can play or override this value somewhere or replace it with max-width attribute.


问:
How do I take max value of a pandas dataframe column and find the corresponding value in another column?
I want to take max value of a pandas dataframe column and find the corresponding value in another column? Let's assume there are not duplicates in the maximum value, so you are always returning only one value. For example,

```<code>GPA   ID
2.3  Tina1
3.4  Bob1
3.6  Lia1
2.9  Tina2
4.0  Blake1
4.5  Conor2
</code>```

Here the max GPA is 4.5, but I want to return the corresponding id for the max GPA, so I would return Conor2. I am unsure of how to do this, so help would be greatly appreciated :) Thanks!

答:
You can use

```<code>df.loc[df.GPA == df.GPA.max(), 'ID']
</code>```

You get

```<code>5    Conor2
</code>```

If you don't want the index but just the value, try

```<code>df.loc[df.GPA == df.GPA.max(), 'ID'].values[0]
</code>```

You get

```<code>'Conor2'
</code>```

Body:
I want to take max value of a pandas dataframe column and find the corresponding value in another column? Let's assume there are not duplicates in the maximum value, so you are always returning only one value. For example,

GPA   ID
2.3  Tina1
3.4  Bob1
3.6  Lia1
2.9  Tina2
4.0  Blake1
4.5  Conor2

Here the max GPA is 4.5, but I want to return the corresponding id for the max GPA, so I would return Conor2. I am unsure of how to do this, so help would be greatly appreciated :) Thanks!

Body:
You can use

df.loc[df.GPA == df.GPA.max(), 'ID']

You get

5    Conor2

If you don't want the index but just the value, try

df.loc[df.GPA == df.GPA.max(), 'ID'].values[0]

You get

'Conor2'


问:
Group objects sharing same key and cast them in another object
These are my classes:

```<code>class Schedule
{
    Int32 Id {get; set;}
    String CustomerName {get; set;}
    DateTime SchedStartDate {get; set;}
    DateTime SchedEndDate {get; set;}
    List<Body> Body {get; set;}
}

class Body
{
    Int32 Id {get; set;}
    String ProductBarcode {get; set;}
    Int32 ProductItemId {get; set;}
    DateTime DtEvaluation {get; set;}
    List<History> History {get; set;}
}

class History
{
    Int32 ActionId { get; set; }
    String Description { get; set; }
    String Picture { get; set; }
    String Observation { get; set; }
    Int32 EvalItemId { get; set; }
    Int32 EvalCriteriaId { get; set; }
}
</code>```

I have an Schedule object and the string Body.ProductBarcode is repeated on the Schedule.Body list. Also, sometimes the list Body.History is empty and sometimes it is not.

The Body.ProductBarcode repetition is correct from the application's point of view, but it is giving  me some trouble when I try to consolidate the data, as I want it to be cast the Schedule object in another class (that I find easier to work with):

```<code>class EmailSchedule
{
    String Id { get; set; }
    Int32 ProductId { get; set; }
    DateTime DtEvaluation { get; set; }
    List<EmailHistory> History { get; set; }
}
class EmailHistory
{
    Int32 ActionId { get; set; }
    String Description { get; set; }
    String Picture { get; set; }
    String Observation { get; set; }
    String EvalItemId { get; set; }
    Int32 EvalCriteriaId { get; set; }
}
</code>```

Keep in mind that, at this point, the only thing that interests me is the Body.ProductBarcode key and each of it's Body.History lists. Schedules's properties are already safe and sound and the other Body's properties are useless.

This is an example of a JSON that will be converted into the Schedule object

My problem is that, as there are repeated Body.ProductBarcode I need to group the occurrences where the Body.ProductBarcode match and, after that bring all the Body.History lists to the same EmailSchedule.History list.

I've tried to use LINQ, but as I'm not familiar with it, I wasn't able to make it work.

答:
I am still not 100% sure what structure you're looking for, but could you try this and let me know if its anywhere close to what you want?

Based on your feedback I can tweak it. (schd is your schedule object)

```<code>var scheduleList = schd.Body.GroupBy(b => b.ProductBarcode).Select(b => b.Select(bod => new EmailSchedule
{
    Id = s.Id.ToString(),
    DtEvaluation = bod.DtEvaluation,
    ProductId = bod.ProductItemId,
    History = bod.History
})).SelectMany(b => b);      //flatten to single list
</code>```

p.s. for your classes, using public would be good since otherwise it won't deserialize from json, and since the EmailHistory and History classes are identical, I just use History. If you actually do need to cast it to EmailHistory, you'd need to add code to the line History = bod.History.

Body:
These are my classes:

class Schedule
{
    Int32 Id {get; set;}
    String CustomerName {get; set;}
    DateTime SchedStartDate {get; set;}
    DateTime SchedEndDate {get; set;}
    List Body {get; set;}
}

class Body
{
    Int32 Id {get; set;}
    String ProductBarcode {get; set;}
    Int32 ProductItemId {get; set;}
    DateTime DtEvaluation {get; set;}
    List<History> History {get; set;}
}

class History
{
    Int32 ActionId { get; set; }
    String Description { get; set; }
    String Picture { get; set; }
    String Observation { get; set; }
    Int32 EvalItemId { get; set; }
    Int32 EvalCriteriaId { get; set; }
}

I have an Schedule object and the string Body.ProductBarcode is repeated on the Schedule.Body list. Also, sometimes the list Body.History is empty and sometimes it is not.

The Body.ProductBarcode repetition is correct from the application's point of view, but it is giving  me some trouble when I try to consolidate the data, as I want it to be cast the Schedule object in another class (that I find easier to work with):

class EmailSchedule
{
    String Id { get; set; }
    Int32 ProductId { get; set; }
    DateTime DtEvaluation { get; set; }
    List<EmailHistory> History { get; set; }
}
class EmailHistory
{
    Int32 ActionId { get; set; }
    String Description { get; set; }
    String Picture { get; set; }
    String Observation { get; set; }
    String EvalItemId { get; set; }
    Int32 EvalCriteriaId { get; set; }
}

Keep in mind that, at this point, the only thing that interests me is the Body.ProductBarcode key and each of it's Body.History lists. Schedules's properties are already safe and sound and the other Body's properties are useless.

This is an example of a JSON that will be converted into the Schedule object

My problem is that, as there are repeated Body.ProductBarcode I need to group the occurrences where the Body.ProductBarcode match and, after that bring all the Body.History lists to the same EmailSchedule.History list.

I've tried to use LINQ, but as I'm not familiar with it, I wasn't able to make it work.

Body:
I am still not 100% sure what structure you're looking for, but could you try this and let me know if its anywhere close to what you want?

Based on your feedback I can tweak it. (schd is your schedule object)

var scheduleList = schd.Body.GroupBy(b => b.ProductBarcode).Select(b => b.Select(bod => new EmailSchedule
{
    Id = s.Id.ToString(),
    DtEvaluation = bod.DtEvaluation,
    ProductId = bod.ProductItemId,
    History = bod.History
})).SelectMany(b => b);      //flatten to single list

p.s. for your classes, using public would be good since otherwise it won't deserialize from json, and since the EmailHistory and History classes are identical, I just use History. If you actually do need to cast it to EmailHistory, you'd need to add code to the line History = bod.History.