问:
In C++/CLI what is the easiest way to pass internal variables to delegate?
I am trying to set a delegate that takes a local variable as a parameter. The declaration looks like this:

```<code>ref class Main
{
private:
    Func<String^>^ _expensiveMethodDelegate;

public:
    property Func<String^>^ ExpensiveMethodDelegate
    {
        Func<String^>^ get() { return this->_expensiveMethodDelegate; }
        void set(Func<String^>^ value) { this->_expensiveMethodDelegate = value; }
    };

    void DoWork()
    {
        String^ result = this->_expensiveMethodDelegate();
        Debug::WriteLine(result);
    }
};
</code>```

In C# the code will look like this:

```<code>string parameter = "value";

Main main = new Main();
main.ExpensiveMethodDelegate = () =>
{
    Thread.Sleep(1000); // do expensive work
    return parameter + "1";
};

main.DoWork();
</code>```

What is the easiest way of achieving this goal using managed C++ (VS 2015)? Note: I read articles Workaround for not having lambdas that can capture managed variables and Lambda expressions as CLR (.NET) delegates / event handlers in Visual C++ 2010 and still cannot figure out what is the solution.

I tried code like this (using make_delegate from the second article), but it fails to compile:

```<code>String^ parameter = L"value";

Main^ main = gcnew Main();
main->ExpensiveMethodDelegate = make_delegate(
    [](String^ parameter) -> String^
    {
        Threading::Thread::Sleep(1000); // do work
        return parameter + L"1";
    });

main->DoWork();
</code>```

答:
This is what I came up with:

```<code>#pragma once

#include <new>

using namespace std::tr1;
using namespace System;

namespace helper
{
    private struct return_type_helper
    {
    private:

        template<class D>
        struct dependent_false { enum { value = false }; };

        template <class D>
        struct illegal_delegate_type
        {
            static_assert(dependent_false<D>::value, "Delegates with more than 2 parameters, or with parameters of tracking reference types (T%), are not supported.");
        };

        struct anything
        {
            template<class T>
            operator T() const;
        };

    public:
        template<class D>
        static decltype(static_cast<D^>(nullptr)(anything())) dummy(int(*)[2]);

        template<class D>
        static decltype(static_cast<D^>(nullptr)(anything(), anything())) dummy(int(*)[3]);
    };

    template<class Func, class Aligner = char, bool Match = (alignment_of<Func>::value == alignment_of<Aligner>::value)>
    struct aligner
    {
        static_assert(Match, "Function object has unsupported alignment");
    };

    template<class Func, class Aligner>
    private struct aligner<Func, Aligner, true>
    {
        typedef Aligner type;
    };

    template<class F>
    private ref class lambda_wrapper
    {
    public:
        lambda_wrapper(const F& f)
        {
            pin_ptr<F> pf = (interior_ptr<F>)&f_storage;
            new(pf) F(f);
        }

        ~lambda_wrapper()
        {
            pin_ptr<F> pf = (interior_ptr<F>)&f_storage;
            pf->~F();
        }

        template <class D>
        operator D ^ ()
        {
            D^ d = nullptr;
            return gcnew D(this, &lambda_wrapper<F>::invoke<decltype(return_type_helper::dummy<D>(0))>);
        }

    private:
        template<class T>
        [System::Runtime::InteropServices::StructLayout(System::Runtime::InteropServices::LayoutKind::Sequential, Size = sizeof(T))]
        value struct embedded_storage
        {
        private:
            typename aligner<T>::type dummy;
        };

        embedded_storage<F> f_storage;

        template<class R, class A1>
        R invoke(A1 a1)
        {
            pin_ptr<F> pf = (interior_ptr<F>)&f_storage;
            return (*pf)(a1);
        }

        template<class R, class A1, class A2>
        R invoke(A1 a1, A2 a2)
        {
            pin_ptr<F> pf = (interior_ptr<F>)&f_storage;
            return (*pf)(a1, a2);
        }
    };

    template <typename...>
    ref class DelegateHelper;

    template<class TParam1, class TResult>
    ref class DelegateHelper<TParam1, TResult>
    {
    private:
        Func<TParam1, TResult>^ _lambda;
        TParam1 _param1;

        TResult Execute()
        {
            return this->_lambda(this->_param1);
        }

    public:
        template<class TLambda>
        DelegateHelper(TLambda lambda, TParam1 param1)
        {
            this->_lambda = gcnew helper::lambda_wrapper<TLambda>(lambda);
            this->_param1 = param1;
        }

        static operator Func<TResult> ^ (DelegateHelper<TParam1, TResult>^ value)
        {
            return gcnew Func<TResult>(value, &DelegateHelper<TParam1, TResult>::Execute);
        }
    };

    template<class TParam1, class TParam2, class TResult>
    ref class DelegateHelper<TParam1, TParam2, TResult>
    {
    private:
        Func<TParam1, TParam2, TResult>^ _lambda;
        TParam1 _param1;
        TParam2 _param2;

        TResult Execute()
        {
            return this->_lambda(this->_param1, this->_param2);
        }

    public:
        template<class TLambda>
        DelegateHelper(TLambda lambda, TParam1 param1, TParam2 param2)
        {
            this->_lambda = gcnew helper::lambda_wrapper<TLambda>(lambda);
            this->_param1 = param1;
            this->_param2 = param2;
        }

        static operator Func<TResult> ^ (DelegateHelper<TParam1, TParam2, TResult>^ value)
        {
            return gcnew Func<TResult>(value, &DelegateHelper<TParam1, TParam2, TResult>::Execute);
        }
    };
}
</code>```

This is how to use it:

```<code>String^ parameter1 = L"value1";
String^ parameter2 = L"value2";
Main^ main = gcnew Main();

auto lambda1 = [](String^ parameter) -> String^
{
    Threading::Thread::Sleep(1000);
    return parameter;
};

main->ExpensiveMethodDelegate = gcnew helper::DelegateHelper<String^, String^>(lambda1, parameter1);

main->DoWork();

auto lambda2 = [](String^ parameter1, String^ parameter2) -> String^
{
    Threading::Thread::Sleep(1000);
    return parameter1 + parameter2;
};

main->ExpensiveMethodDelegate = gcnew helper::DelegateHelper<String^, String^, String^>(lambda2, parameter1, parameter2);

main->DoWork();
</code>```

Not sure if it is the most elegant way, but it does the work I was looking for.

Body:
I am trying to set a delegate that takes a local variable as a parameter. The declaration looks like this:

ref class Main
{
private:
    Func<String^>^ _expensiveMethodDelegate;

public:
    property Func<String^>^ ExpensiveMethodDelegate
    {
        Func<String^>^ get() { return this->_expensiveMethodDelegate; }
        void set(Func<String^>^ value) { this->_expensiveMethodDelegate = value; }
    };

    void DoWork()
    {
        String^ result = this->_expensiveMethodDelegate();
        Debug::WriteLine(result);
    }
};

In C# the code will look like this:

string parameter = "value";

Main main = new Main();
main.ExpensiveMethodDelegate = () =>
{
    Thread.Sleep(1000); // do expensive work
    return parameter + "1";
};

main.DoWork();

What is the easiest way of achieving this goal using managed C++ (VS 2015)? Note: I read articles Workaround for not having lambdas that can capture managed variables and Lambda expressions as CLR (.NET) delegates / event handlers in Visual C++ 2010 and still cannot figure out what is the solution.

I tried code like this (using make_delegate from the second article), but it fails to compile:

String^ parameter = L"value";

Main^ main = gcnew Main();
main->ExpensiveMethodDelegate = make_delegate(
    [](String^ parameter) -> String^
    {
        Threading::Thread::Sleep(1000); // do work
        return parameter + L"1";
    });

main->DoWork();

Body:
This is what I came up with:

#pragma once

#include <new>

using namespace std::tr1;
using namespace System;

namespace helper
{
    private struct return_type_helper
    {
    private:

        template<class D>
        struct dependent_false { enum { value = false }; };

        template <class D>
        struct illegal_delegate_type
        {
            static_assert(dependent_false<D>::value, "Delegates with more than 2 parameters, or with parameters of tracking reference types (T%), are not supported.");
        };

        struct anything
        {
            template<class T>
            operator T() const;
        };

    public:
        template<class D>
        static decltype(static_cast<D^>(nullptr)(anything())) dummy(int(*)[2]);

        template<class D>
        static decltype(static_cast<D^>(nullptr)(anything(), anything())) dummy(int(*)[3]);
    };

    template<class Func, class Aligner = char, bool Match = (alignment_of<Func>::value == alignment_of<Aligner>::value)>
    struct aligner
    {
        static_assert(Match, "Function object has unsupported alignment");
    };

    template<class Func, class Aligner>
    private struct aligner<Func, Aligner, true>
    {
        typedef Aligner type;
    };

    template<class F>
    private ref class lambda_wrapper
    {
    public:
        lambda_wrapper(const F& f)
        {
            pin_ptr<F> pf = (interior_ptr<F>)&f_storage;
            new(pf) F(f);
        }

        ~lambda_wrapper()
        {
            pin_ptr<F> pf = (interior_ptr<F>)&f_storage;
            pf->~F();
        }

        template <class D>
        operator D ^ ()
        {
            D^ d = nullptr;
            return gcnew D(this, &lambda_wrapper<F>::invoke<decltype(return_type_helper::dummy<D>(0))>);
        }

    private:
        template<class T>
        [System::Runtime::InteropServices::StructLayout(System::Runtime::InteropServices::LayoutKind::Sequential, Size = sizeof(T))]
        value struct embedded_storage
        {
        private:
            typename aligner<T>::type dummy;
        };

        embedded_storage<F> f_storage;

        template<class R, class A1>
        R invoke(A1 a1)
        {
            pin_ptr<F> pf = (interior_ptr<F>)&f_storage;
            return (*pf)(a1);
        }

        template<class R, class A1, class A2>
        R invoke(A1 a1, A2 a2)
        {
            pin_ptr<F> pf = (interior_ptr<F>)&f_storage;
            return (*pf)(a1, a2);
        }
    };

    template <typename...>
    ref class DelegateHelper;

    template<class TParam1, class TResult>
    ref class DelegateHelper<TParam1, TResult>
    {
    private:
        Func<TParam1, TResult>^ _lambda;
        TParam1 _param1;

        TResult Execute()
        {
            return this->_lambda(this->_param1);
        }

    public:
        template<class TLambda>
        DelegateHelper(TLambda lambda, TParam1 param1)
        {
            this->_lambda = gcnew helper::lambda_wrapper<TLambda>(lambda);
            this->_param1 = param1;
        }

        static operator Func<TResult> ^ (DelegateHelper<TParam1, TResult>^ value)
        {
            return gcnew Func<TResult>(value, &DelegateHelper<TParam1, TResult>::Execute);
        }
    };

    template<class TParam1, class TParam2, class TResult>
    ref class DelegateHelper<TParam1, TParam2, TResult>
    {
    private:
        Func<TParam1, TParam2, TResult>^ _lambda;
        TParam1 _param1;
        TParam2 _param2;

        TResult Execute()
        {
            return this->_lambda(this->_param1, this->_param2);
        }

    public:
        template<class TLambda>
        DelegateHelper(TLambda lambda, TParam1 param1, TParam2 param2)
        {
            this->_lambda = gcnew helper::lambda_wrapper<TLambda>(lambda);
            this->_param1 = param1;
            this->_param2 = param2;
        }

        static operator Func<TResult> ^ (DelegateHelper<TParam1, TParam2, TResult>^ value)
        {
            return gcnew Func<TResult>(value, &DelegateHelper<TParam1, TParam2, TResult>::Execute);
        }
    };
}

This is how to use it:

String^ parameter1 = L"value1";
String^ parameter2 = L"value2";
Main^ main = gcnew Main();

auto lambda1 = [](String^ parameter) -> String^
{
    Threading::Thread::Sleep(1000);
    return parameter;
};

main->ExpensiveMethodDelegate = gcnew helper::DelegateHelper<String^, String^>(lambda1, parameter1);

main->DoWork();

auto lambda2 = [](String^ parameter1, String^ parameter2) -> String^
{
    Threading::Thread::Sleep(1000);
    return parameter1 + parameter2;
};

main->ExpensiveMethodDelegate = gcnew helper::DelegateHelper<String^, String^, String^>(lambda2, parameter1, parameter2);

main->DoWork();

Not sure if it is the most elegant way, but it does the work I was looking for.


来源: stackexchange

问:
Storing and extracting data in hashes with cucumber/capybara
I have a lot of tests with different login credentials on cucumber/capybara/site_prism, which are quite messy. I want to unify them as much as possible; this solution seemed to be nice https://blog.jayway.com/2012/04/03/cucumber-data-driven-testing-tips/

But when following the example I run into this for the very first line of step definition

```<code>Your block takes 1 argument, but the Regexp matched 2 arguments.
</code>```

Apparently, I misunderstand how hashes should be handled; could somebody help please? My code with less test data is below
Cucumber

```<code>Given I login as "ad" with the following data:
    |role|usern       |userpass     |
    |ad  |adcccount   |adpassword   |
    |ml  |mlaccount   |mlpassword   |
</code>```

step definition

```<code>Given /^I login as "(ad|ml)" with the following data:/ do |user|
 temp_hash = {}
    if (user == "ad")
      temp_hash = $ad
    elsif (user == "ml")
      temp_hash = $ml
    end

    usern = temp_hash["usern"]
    userpass = temp_hash["userpass"]

 @app = App.new
  @app.login.load
  @app.login.username.set usern
  @app.login.password.set userpass
  @app.login.btn_login.click
end
</code>```

答:
You're getting that error because the second parameter being matched is the data_table.  Your step definition would need to be

```<code>Given /^I login as "(ad|ml)" with the following data:/ do |user, data_table|
  ...
</code>```

If you look at the Given /I create new user named "(user_1|user_2|user_3)" with the following data:/ do |user, data_table| step in the article you linked you can see the same thing, although that doesn't use multiple entries in the data_table so I'm not 100% sure what you're trying to do in your example.

ContentLicense: CC BY-SA 3.0

Body:
I have a lot of tests with different login credentials on cucumber/capybara/site_prism, which are quite messy. I want to unify them as much as possible; this solution seemed to be nice https://blog.jayway.com/2012/04/03/cucumber-data-driven-testing-tips/

But when following the example I run into this for the very first line of step definition

Your block takes 1 argument, but the Regexp matched 2 arguments.

Apparently, I misunderstand how hashes should be handled; could somebody help please? My code with less test data is below
Cucumber

Given I login as "ad" with the following data:
    |role|usern       |userpass     |
    |ad  |adcccount   |adpassword   |
    |ml  |mlaccount   |mlpassword   |

step definition

Given /^I login as "(ad|ml)" with the following data:/ do |user|
 temp_hash = {}
    if (user == "ad")
      temp_hash = $ad
    elsif (user == "ml")
      temp_hash = $ml
    end

    usern = temp_hash["usern"]
    userpass = temp_hash["userpass"]

 @app = App.new
  @app.login.load
  @app.login.username.set usern
  @app.login.password.set userpass
  @app.login.btn_login.click
end

Body:
You're getting that error because the second parameter being matched is the data_table.  Your step definition would need to be

Given /^I login as "(ad|ml)" with the following data:/ do |user, data_table|
  ...

If you look at the Given /I create new user named "(user_1|user_2|user_3)" with the following data:/ do |user, data_table| step in the article you linked you can see the same thing, although that doesn't use multiple entries in the data_table so I'm not 100% sure what you're trying to do in your example.


问:
Impala: return day of the built-in function trunc()
When I use trunc(timestamp, 'D') , it always gives me the Monday of that week. Is it possible to ask the function to return other day of the week, such as Tuesday? Thanks!

答:
You should use trunc(timestamp, 'J'). See the documentation for Day, you're using 'Starting day of the week':

```<code>trunc(timestamp, string unit)
Purpose: Strips off fields from a TIMESTAMP value.
Unit argument: The unit argument value is case-sensitive. This argument string can be one of:
SYYYY, YYYY, YEAR, SYEAR, YYY, YY, Y: Year.
Q: Quarter.
MONTH, MON, MM, RM: Month.
WW, W: Same day of the week as the first day of the month.
DDD, DD, J: Day.
DAY, DY, D: Starting day of the week. (Not necessarily the current day.)
HH, HH12, HH24: Hour. A TIMESTAMP value truncated to the hour is always represented in 24-hour notation, even for the HH12 argument string.
MI: Minute.
</code>```

https://www.cloudera.com/documentation/enterprise/latest/topics/impala_datetime_functions.html

Body:
You should use trunc(timestamp, 'J'). See the documentation for Day, you're using 'Starting day of the week':

trunc(timestamp, string unit)
Purpose: Strips off fields from a TIMESTAMP value.
Unit argument: The unit argument value is case-sensitive. This argument string can be one of:
SYYYY, YYYY, YEAR, SYEAR, YYY, YY, Y: Year.
Q: Quarter.
MONTH, MON, MM, RM: Month.
WW, W: Same day of the week as the first day of the month.
DDD, DD, J: Day.
DAY, DY, D: Starting day of the week. (Not necessarily the current day.)
HH, HH12, HH24: Hour. A TIMESTAMP value truncated to the hour is always represented in 24-hour notation, even for the HH12 argument string.
MI: Minute.

https://www.cloudera.com/documentation/enterprise/latest/topics/impala_datetime_functions.html


问:
How do I use Glimmer components inside an Ember app?
The Glimmer website states:

Just drop your Glimmer components into an Ember app. You won’t need to change a thing.

I’ve been following the official Ember quick start tutorial. I replaced the contents of the generated people-list.js component with this:

```<code>import Component from '@glimmer/component';

export default class PeopleList extends Component {

}
</code>```

and I get an error in the browser console stating that @glimmer/component is undefined. After I run yarn add @glimmer/component to add the dependency, I get a new error from Broccoli.

Additionally, whenever I use '@' before a variable in the people-list.hbs template, the template fails to compile. How do I get the Glimmer component to work in my Ember app?

答:
Currently you can't use it for existing ember app. but you can try it brand new app. By installing ember new my-glimmer-app -b https://github.com/glimmerjs/glimmer-blueprint.git

If you go with yarn global add ember-cli/ember-cli this way then you need to uninstall existing ember-cli (npm uninstall -g ember-cli)

Body:
The Glimmer website states:

Just drop your Glimmer components into an Ember app. You won’t need to change a thing.

I’ve been following the official Ember quick start tutorial. I replaced the contents of the generated people-list.js component with this:

import Component from '@glimmer/component';

export default class PeopleList extends Component {

}

and I get an error in the browser console stating that @glimmer/component is undefined. After I run yarn add @glimmer/component to add the dependency, I get a new error from Broccoli.

Additionally, whenever I use '@' before a variable in the people-list.hbs template, the template fails to compile. How do I get the Glimmer component to work in my Ember app?


问:
WordPress: Why Isn't add_rewrite_rule Working?

Goal

A visible URL of:

```<code>/products/building-automation/details/productSKU
</code>```

Should point to the real WordPress page of:

```<code>/products/details/?SKU=productSKU
</code>```

Code

```<code>public function setup_frontend() {

    add_rewrite_rule(
        'products/(building-automation|lighting-controls)/details/([^/]*)',
        'products/details/?SKU=$matches[2]',
        'top'
    );

    // Other code logic...

}
</code>```

From what I can tell, the $matches points to the portions of the regex that are in (), so in the example, $matches[1] would be building-automation, and $matches[2] would be productSKU.

I have tried the flushing the rules, many times. This is being called from inside a class, but that doesn't appear to be the issue. I'm attaching the function to the init event.

What is Happening

I am getting the 404 template. What am I doing wrong?

Edit

Turns out, the second part of the parameter HAS to be index.php. Since I was trying to point to products/..., it broke. So I've updated to this:

```<code>    add_rewrite_rule(
        'products/(building-automation|lighting-controls)/details/([^/]*)',
        '?pagename=products/details&SKU=$matches[2]',
        'top'
    );
</code>```

It's not working and point to the right page and template. However, the $matches part is still not coming through. In fact, $_GET['SKU'] is coming through as '$matches[2]'.

答:
1) Try to update permalinks.

Go to Dashboard->Setting->Permalinks-> button "Save changes"

2) Add action to your function

```<code>add_action('init', 'setup_frontend');
function setup_frontend() {

add_rewrite_rule(
    'products/(building-automation|lighting-controls)/details/([^/]*)',
    'products/details/?SKU=$matches[2]',
    'top'
);

// Other code logic...
</code>```

}

Body:
Goal

A visible URL of:

/products/building-automation/details/productSKU

Should point to the real WordPress page of:

/products/details/?SKU=productSKU

Code

public function setup_frontend() {

    add_rewrite_rule(
        'products/(building-automation|lighting-controls)/details/([^/]*)',
        'products/details/?SKU=$matches[2]',
        'top'
    );

    // Other code logic...

}

From what I can tell, the $matches points to the portions of the regex that are in (), so in the example, $matches[1] would be building-automation, and $matches[2] would be productSKU.

I have tried the flushing the rules, many times. This is being called from inside a class, but that doesn't appear to be the issue. I'm attaching the function to the init event.

What is Happening

I am getting the 404 template. What am I doing wrong?

Edit

Turns out, the second part of the parameter HAS to be index.php. Since I was trying to point to products/..., it broke. So I've updated to this:

    add_rewrite_rule(
        'products/(building-automation|lighting-controls)/details/([^/]*)',
        '?pagename=products/details&SKU=$matches[2]',
        'top'
    );

It's not working and point to the right page and template. However, the $matches part is still not coming through. In fact, $_GET['SKU'] is coming through as '$matches[2]'.

Body:
1) Try to update permalinks.

Go to Dashboard->Setting->Permalinks-> button "Save changes"

2) Add action to your function

add_action('init', 'setup_frontend');
function setup_frontend() {

add_rewrite_rule(
    'products/(building-automation|lighting-controls)/details/([^/]*)',
    'products/details/?SKU=$matches[2]',
    'top'
);

// Other code logic...

}


问:
Draw Straight line between two points in vertical orientation using Opencv and C++
I have tried to draw a straight line using two reference points and I got some problems on vertical orientation.

That's the current source code:

```<code>cv::Mat img = cv::Mat::zeros(600,600,CV_8UC3);
cv::Point p1(306,41);
cv::Point p2(304,8);

cv::Point p(0,0), q(img.cols, img.rows);
if (p1.x != p2.x) {
    double m = (double) (p1.y - p2.y) / (double) (p1.x - p2.x);
    double b = p1.y - (m * p1.x);
    p.y = m * p.x + b;
    q.y = m * q.x + b;
} else {
    p.x = q.x = p2.x;
    p.y = 0;
    q.y = img.rows;
}

cv::circle(img, p1, 4, cv::Scalar(255,0,255), -1);
cv::circle(img, p2, 4, cv::Scalar(255,0,255), -1);
cv::line(img, p, q, cv::Scalar(0,0,255), 2);
</code>```

This is the following output:

What am I doing wrong?

答:
I'm not able to reproduce the error with your code. This code (copied & pasted from yours) works well:

```<code>#include <opencv2\opencv.hpp>

using namespace std;
using namespace cv;

int main() {

    cv::Mat img = cv::Mat::zeros(600,600,CV_8UC3);
    cv::Point p1(301,49);
    cv::Point p2(303,460);

    cv::Point p(0,0), q(img.cols, img.rows);
    if (p1.x != p2.x) {
        double m = (double) (p1.y - p2.y) / (double) (p1.x - p2.x);
        double b = p1.y - (m * p1.x);
        p.y = m * p.x + b;
        q.y = m * q.x + b;
    } else {
        p.x = q.x = p2.x;
        p.y = 0;
        q.y = img.rows;
    }

    cv::circle(img, p1, 4, cv::Scalar(255,0,255), -1);
    cv::circle(img, p2, 4, cv::Scalar(255,0,255), -1);
    cv::line(img, p, q, cv::Scalar(0,0,255), 2);

    imshow("Result", img);
    waitKey();

    return 0;
}
</code>```

Body:
I have tried to draw a straight line using two reference points and I got some problems on vertical orientation.

That's the current source code:

cv::Mat img = cv::Mat::zeros(600,600,CV_8UC3);
cv::Point p1(306,41);
cv::Point p2(304,8);

cv::Point p(0,0), q(img.cols, img.rows);
if (p1.x != p2.x) {
    double m = (double) (p1.y - p2.y) / (double) (p1.x - p2.x);
    double b = p1.y - (m * p1.x);
    p.y = m * p.x + b;
    q.y = m * q.x + b;
} else {
    p.x = q.x = p2.x;
    p.y = 0;
    q.y = img.rows;
}

cv::circle(img, p1, 4, cv::Scalar(255,0,255), -1);
cv::circle(img, p2, 4, cv::Scalar(255,0,255), -1);
cv::line(img, p, q, cv::Scalar(0,0,255), 2);

This is the following output:

What am I doing wrong?

Body:
I'm not able to reproduce the error with your code. This code (copied & pasted from yours) works well:

#include <opencv2\opencv.hpp>

using namespace std;
using namespace cv;

int main() {

    cv::Mat img = cv::Mat::zeros(600,600,CV_8UC3);
    cv::Point p1(301,49);
    cv::Point p2(303,460);

    cv::Point p(0,0), q(img.cols, img.rows);
    if (p1.x != p2.x) {
        double m = (double) (p1.y - p2.y) / (double) (p1.x - p2.x);
        double b = p1.y - (m * p1.x);
        p.y = m * p.x + b;
        q.y = m * q.x + b;
    } else {
        p.x = q.x = p2.x;
        p.y = 0;
        q.y = img.rows;
    }

    cv::circle(img, p1, 4, cv::Scalar(255,0,255), -1);
    cv::circle(img, p2, 4, cv::Scalar(255,0,255), -1);
    cv::line(img, p, q, cv::Scalar(0,0,255), 2);

    imshow("Result", img);
    waitKey();

    return 0;
}


问:
How to send request to endpoint with Boto
I am trying to list items in a S3 container with the following code.

```<code>import boto.s3
from boto.s3.connection import OrdinaryCallingFormat

conn = boto.connect_s3(calling_format=OrdinaryCallingFormat())
mybucket = conn.get_bucket('Container001')

for key in mybucket.list():
    print key.name.encode('utf-8')
</code>```

Then I get the following error.

```<code>Traceback (most recent call last):
  File "test.py", line 5, in <module>
    mybucket = conn.get_bucket('Container001')
  File "/usr/lib/python2.7/dist-packages/boto/s3/connection.py", line 370, in get_bucket
bucket.get_all_keys(headers, maxkeys=0)
File "/usr/lib/python2.7/dist-packages/boto/s3/bucket.py", line 358, in get_all_keys
'', headers, **params)
File "/usr/lib/python2.7/dist-packages/boto/s3/bucket.py", line 325, in _get_all
response.status, response.reason, body)
boto.exception.S3ResponseError: S3ResponseError: 301 Moved Permanently
<?xml version="1.0" encoding="UTF-8"?>
PermanentRedirectThe bucket you are attempting to access  must be addressed using the  specified endpoint. Please send all future requests to this endpoint.99EBDB9DE3B6E3AF
Container001
<HostId>5El9MLfgHZmZ1UNw8tjUDAl+XltYelHu6d/JUNQsG3OaM70LFlpRchEJi9oepeMy</HostId><Endpoint>Container001.s3.amazonaws.com</Endpoint></Error>
</code>```

I tried to search for how to send requests to the specified end point, but couldn't find useful information.

How do I avoid this error?

答:
in terminal run

nano ~/.boto

if there is some configs try to comment or rename file and connect again. (it helps me)

http://boto.cloudhackers.com/en/latest/boto_config_tut.html

there is boto config file directories. take a look one by one and clean them all, it will work by default configs. also configs may be in .bash_profile, .bash_source...
I guess you must allow only KEY-SECRET

also try to use

calling_format = boto.s3.connection.OrdinaryCallingFormat()

Body:
I am trying to list items in a S3 container with the following code.

import boto.s3
from boto.s3.connection import OrdinaryCallingFormat

conn = boto.connect_s3(calling_format=OrdinaryCallingFormat())
mybucket = conn.get_bucket('Container001')

for key in mybucket.list():
    print key.name.encode('utf-8')

Then I get the following error.

Traceback (most recent call last):
  File "test.py", line 5, in <module>
    mybucket = conn.get_bucket('Container001')
  File "/usr/lib/python2.7/dist-packages/boto/s3/connection.py", line 370, in get_bucket
bucket.get_all_keys(headers, maxkeys=0)
File "/usr/lib/python2.7/dist-packages/boto/s3/bucket.py", line 358, in get_all_keys
'', headers, **params)
File "/usr/lib/python2.7/dist-packages/boto/s3/bucket.py", line 325, in _get_all
response.status, response.reason, body)
boto.exception.S3ResponseError: S3ResponseError: 301 Moved Permanently
<?xml version="1.0" encoding="UTF-8"?>
PermanentRedirectThe bucket you are attempting to access  must be addressed using the  specified endpoint. Please send all future requests to this endpoint.99EBDB9DE3B6E3AF
Container001
<HostId>5El9MLfgHZmZ1UNw8tjUDAl+XltYelHu6d/JUNQsG3OaM70LFlpRchEJi9oepeMy</HostId><Endpoint>Container001.s3.amazonaws.com</Endpoint></Error>

I tried to search for how to send requests to the specified end point, but couldn't find useful information.

How do I avoid this error?


问:
How do I use an expression with md-colors directive?
I am using AngularJS Material and I would like to apply md-colors="" values based on an expression the same way an expression can be used with ng-class="".  I have not been able to get this working.

Here's an example :

```<code><md-button md-colors="{background:'accent-900-0.43' : mode == 'development'}" ng-click="setMode('development')">
development
</md-button>
</code>```

The desired output is that the md-button will take on the accent-900 background color if the condition mode=='development' is true.

Can md-colors be used this way?

答:
you can use ternary operation inside md-color to assign styles

```<code><md-button md-colors="mode == 'development' ? {background:'accent-900-0.43'} : {background:'whatever_condition_false_color'} " ng-click="setMode('development')">
development
</md-button>
</code>```

Body:
I am using AngularJS Material and I would like to apply md-colors="" values based on an expression the same way an expression can be used with ng-class="".  I have not been able to get this working.

Here's an example :

<md-button md-colors="{background:'accent-900-0.43' : mode == 'development'}" ng-click="setMode('development')">
development
</md-button>

The desired output is that the md-button will take on the accent-900 background color if the condition mode=='development' is true.

Can md-colors be used this way?

Body:
you can use ternary operation inside md-color to assign styles

<md-button md-colors="mode == 'development' ? {background:'accent-900-0.43'} : {background:'whatever_condition_false_color'} " ng-click="setMode('development')">
development
</md-button>


问:
creating external table from compressed (gz format) files without selecting all fields
I have gz files in a folder. I need only 3 columns from these files, but each line has over 100 of them. At the moment I create a view this way.

```<code>drop table MAK_CHARGE_RCR;
create external table MAK_CHARGE_RCR
(LINE string)
STORED as SEQUENCEFILE
LOCATION '/apps/hive/warehouse/mydb.db/file_rcr';

drop view VW_MAK_CHARGE_RCR;
create view VW_MAK_CHARGE_RCR as
Select LINE[57] as CREATE_DATE, LINE[64] as SUBS_KEY, LINE[63] as RC_TERM_NAME
from
    (Select split(LINE, '\\|') as LINE
    from MAK_CHARGE_RCR) a;
</code>```

The view has the fields I need. Now I have to do the same, but without CTAS and I am not sure how to go about it. What can I do?

I was told the table must look like this

```<code>create external table MAK_CHARGE_RCR
(CREATE_DATE string, SUBS_KEY string, RC_TERM_NAME etc)
</code>```

I could split the line like this

```<code>ROW FORMAT DELIMITED
  FIELDS TERMINATED BY '\\|'
</code>```

but I'll need to list every column. I have another group of files with over 1000 columns. All of them I'll need to list. This just seems a bit excessive, so I wondered if it is possible to do

```<code>create external table arstel.MAK_CHARGE_RCR
(split(LINE, '\\|')[57] string,
split(LINE, '\\|')[64] string
etc)
</code>```

This doesn't work obviously, but maybe there are work arounds?

答:
RegexSerDe

For educational purposes

P.s.

I intend to create an enhanced version of the CSV SerDe that excepts an additional parameter with the positions of the requested columns.

Demo

bash

```<code>echo {a..c}{1..100} | xargs -n 100 | tr ' ' '|'  | \
hdfs dfs -put - /user/hive/warehouse/mytable/data.txt
</code>```

hive

```<code>create external table mytable
(
    col58   string
   ,col64   string
   ,col65   string
)
row format serde 'org.apache.hadoop.hive.serde2.RegexSerDe'
with serdeproperties ("input.regex" = "^(?:([^|]*)\\|){58}(?:([^|]*)\\|){6}([^|]*)\\|.*$")
stored as textfile
location '/user/hive/warehouse/mytable'
;
</code>```

```<code>select * from mytable
;
</code>```

```<code>+---------------+---------------+---------------+
| mytable.col58 | mytable.col64 | mytable.col65 |
+---------------+---------------+---------------+
| a58           | a64           | a65           |
| b58           | b64           | b65           |
| c58           | c64           | c65           |
+---------------+---------------+---------------+
</code>```

Body:
I have gz files in a folder. I need only 3 columns from these files, but each line has over 100 of them. At the moment I create a view this way.

drop table MAK_CHARGE_RCR;
create external table MAK_CHARGE_RCR
(LINE string)
STORED as SEQUENCEFILE
LOCATION '/apps/hive/warehouse/mydb.db/file_rcr';

drop view VW_MAK_CHARGE_RCR;
create view VW_MAK_CHARGE_RCR as
Select LINE[57] as CREATE_DATE, LINE[64] as SUBS_KEY, LINE[63] as RC_TERM_NAME
from
    (Select split(LINE, '\\|') as LINE
    from MAK_CHARGE_RCR) a;

The view has the fields I need. Now I have to do the same, but without CTAS and I am not sure how to go about it. What can I do?

I was told the table must look like this

create external table MAK_CHARGE_RCR
(CREATE_DATE string, SUBS_KEY string, RC_TERM_NAME etc)

I could split the line like this

ROW FORMAT DELIMITED
  FIELDS TERMINATED BY '\\|'

but I'll need to list every column. I have another group of files with over 1000 columns. All of them I'll need to list. This just seems a bit excessive, so I wondered if it is possible to do

create external table arstel.MAK_CHARGE_RCR
(split(LINE, '\\|')[57] string,
split(LINE, '\\|')[64] string
etc)

This doesn't work obviously, but maybe there are work arounds?

Body:
RegexSerDe

For educational purposes

P.s.

I intend to create an enhanced version of the CSV SerDe that excepts an additional parameter with the positions of the requested columns.

Demo

bash

echo {a..c}{1..100} | xargs -n 100 | tr ' ' '|'  | \
hdfs dfs -put - /user/hive/warehouse/mytable/data.txt

hive

create external table mytable
(
    col58   string
   ,col64   string
   ,col65   string
)
row format serde 'org.apache.hadoop.hive.serde2.RegexSerDe'
with serdeproperties ("input.regex" = "^(?:([^|]*)\\|){58}(?:([^|]*)\\|){6}([^|]*)\\|.*$")
stored as textfile
location '/user/hive/warehouse/mytable'
;

select * from mytable
;

+---------------+---------------+---------------+
| mytable.col58 | mytable.col64 | mytable.col65 |
+---------------+---------------+---------------+
| a58           | a64           | a65           |
| b58           | b64           | b65           |
| c58           | c64           | c65           |
+---------------+---------------+---------------+


问:
How to use the same PHP script to fetch data for mobile app and website?
So, I have a website that hits up a very simple PHP script to display data from a database in an HTML table.

My question is simple; is it possible to write the PHP script in such a way that I can use the same script to get the same data and return it in JSON for the android app that will need it (without a single if(onMobileApp) type god statment which is basically equivalent to writing two scripts anyways)?

Or do I have to have two scripts, like

```<code>get_songs_web.php
get_songs_android.php
</code>```

It should be noted that speed of development is crucial here; I'm learning this skill for a 24h competition, so I'm writing procedural PHP, not OO.

As an example of the type of scripts I have, so that you can use it as an example in your responses, here is one of the ones used in the webpage:

```<code><?php
    // Connect to database
    $db_connection = mysqli_connect('localhost', 'root', '', 'songs_list_data')
    or die('Error connecting to MySQL server!');

    // Get data from HTML form
    $name = $_POST["song"];
    $artist = $_POST["artist"];

    // Add song to database
    $add_song_query = $db_connection->prepare("INSERT INTO songs"
            . "(artist, name)"
            . "VALUES (?, ?)");
    $add_song_query->bind_param("ss", $artist, $name);
    $add_song_query->execute();
    $add_song_query->close();
?>

<html>
    <table id="results">
        <?php
            $results_query = $db_connection->prepare("SELECT *"
                    . "FROM songs");
            mysqli_stmt_execute($results_query);
            $result = mysqli_stmt_get_result($results_query);
            $row_num = 1;
            while($row = mysqli_fetch_array($result, MYSQLI_ASSOC))
            {
                echo '<tr class="songs_table_row">';
                    echo '<td class="row_num">' . $row_num . '</td>';
                    echo '<td class="artst">' . $row['artist'] . '</td>';
                    echo '<td class="name">' . $row['name'] . '</td>';
                echo '</tr>';
                $row_num++;
            }
            mysqli_stmt_close($results_query);
        ?>
    </table>
</html>

<?php
    // Close database connection
    mysqli_close($db_connection);
?>
</code>```

答:
You should never rely on the user agent to determine if the data should be send as html, json or any other format. The problem with the user agent is that it could vary between OS and Browser versions, the API doing html requests might change the used user agent, ... . E.g. you might accidentally interpret a mobile browser with an App or an App with a browser, and therefore display the content in the wrong format.

One of the following techniques should be preferred:

A. Using rewrite rules

Create a rewrite rule on the server that will map get_songs.html and get_songs.json to get_songs.php and then determine base on the suffix of the request url what kind of data you want to send. That way the suffix will clearly indicate what kind of data is requested.

B. Using the Accept header

If a browser sends a request to the server and expects html as result then the value Accept header will look something like this:

```<code>text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
</code>```

If you request data from you android app then you could set the value of the Accept header to:

```<code>application/json
</code>```

C. Using an url parameter

If none of the above is possible then you should use an url parameter. The the parameter is not present return the default type, if the parameter (e.g. type=json)  is available, then return it in the JSON format.

With those techniques you can reliable determine what content type has to be returned.

Based on that information you can use the technique as described in the answer of Bloafer

If you use a technique that returns different data for the same URL, then you should also return the Vary header. With Accept or User-Agent as value depending on what information you use to determine the returned format. Otherwise an intermediate caching proxy might cache only one of the version and return this even if the header changes for a followup request of another client.

Body:
So, I have a website that hits up a very simple PHP script to display data from a database in an HTML table.

My question is simple; is it possible to write the PHP script in such a way that I can use the same script to get the same data and return it in JSON for the android app that will need it (without a single if(onMobileApp) type god statment which is basically equivalent to writing two scripts anyways)?

Or do I have to have two scripts, like

get_songs_web.php
get_songs_android.php

It should be noted that speed of development is crucial here; I'm learning this skill for a 24h competition, so I'm writing procedural PHP, not OO.

As an example of the type of scripts I have, so that you can use it as an example in your responses, here is one of the ones used in the webpage:

<?php
    // Connect to database
    $db_connection = mysqli_connect('localhost', 'root', '', 'songs_list_data')
    or die('Error connecting to MySQL server!');

    // Get data from HTML form
    $name = $_POST["song"];
    $artist = $_POST["artist"];

    // Add song to database
    $add_song_query = $db_connection->prepare("INSERT INTO songs"
            . "(artist, name)"
            . "VALUES (?, ?)");
    $add_song_query->bind_param("ss", $artist, $name);
    $add_song_query->execute();
    $add_song_query->close();
?>

        <?php
            $results_query = $db_connection->prepare("SELECT *"
                    . "FROM songs");
            mysqli_stmt_execute($results_query);
            $result = mysqli_stmt_get_result($results_query);
            $row_num = 1;
            while($row = mysqli_fetch_array($result, MYSQLI_ASSOC))
            {
                echo '
';
                    echo '' . $row_num . '	';
                    echo '' . $row['artist'] . '	';
                    echo '' . $row['name'] . '	';
                echo '
';
                $row_num++;
            }
            mysqli_stmt_close($results_query);
        ?>

<?php
    // Close database connection
    mysqli_close($db_connection);
?>

Body:
You should never rely on the user agent to determine if the data should be send as html, json or any other format. The problem with the user agent is that it could vary between OS and Browser versions, the API doing html requests might change the used user agent, ... . E.g. you might accidentally interpret a mobile browser with an App or an App with a browser, and therefore display the content in the wrong format.

One of the following techniques should be preferred:

A. Using rewrite rules

Create a rewrite rule on the server that will map get_songs.html and get_songs.json to get_songs.php and then determine base on the suffix of the request url what kind of data you want to send. That way the suffix will clearly indicate what kind of data is requested.

B. Using the Accept header

If a browser sends a request to the server and expects html as result then the value Accept header will look something like this:

text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8

If you request data from you android app then you could set the value of the Accept header to:

application/json

C. Using an url parameter

If none of the above is possible then you should use an url parameter. The the parameter is not present return the default type, if the parameter (e.g. type=json)  is available, then return it in the JSON format.

With those techniques you can reliable determine what content type has to be returned.

Based on that information you can use the technique as described in the answer of Bloafer

If you use a technique that returns different data for the same URL, then you should also return the Vary header. With Accept or User-Agent as value depending on what information you use to determine the returned format. Otherwise an intermediate caching proxy might cache only one of the version and return this even if the header changes for a followup request of another client.


问:
Assigning Values based on row value
I have a large vector (column of a data frame) where values containing integers 1 to 30. I want to replace numbers from 1 to 5 with 1, 6 to 10 with 5, 11 to 15 with 9...

```<code>> x3 <- sample(1:30, 100, rep=TRUE)
> x3
  [1] 13 24 16 30 10  6 15 10  3 17 18 22 11 13 29  7 25 28 17 27  1  5  6 20 15 15  8 10 13 26 27 24  3 24  5  7 10  6 28 27  1  4 22 25 14 13  2 10  4 29 23 24 30 24 29 11  2 28 23  1  1  2
 [63]  3 23 13 26 21 22 11  4  8 26 17 11 20 23  6 14 24  5 15 21 11 13  6 14 20 11 22  9  6 29  4 30 20 30  4 24 23 29
</code>```

As I mentioned this is a column in a data frame and with above assignment I want to create a different column. If I do the following I have to do this 30 times.

```<code>myFrame$NewColumn[myFrame$oldColumn==1] <- 1
myFrame$NewColumn[myFrame$oldColumn==2] <- 1
myFrame$NewColumn[myFrame$oldColumn==3] <- 1
...
</code>```

Whats a better way to do this?

答:
We can do this with cut (suppose what you mean by '...' is 10, 11, 12):

```<code>x4 <- cut(x3,
          breaks = c(seq(1, 30, 5), 30), right = F, include.lowest = T, # generate correct intervals
          labels = 4 * (0:5) + 1) # number to fill

# x4 is factor. We should convert it to character first then to the number
x4 <- as.numeric(as.character(x4))
</code>```

Title: Assigning Values based on row value

Body:
I have a large vector (column of a data frame) where values containing integers 1 to 30. I want to replace numbers from 1 to 5 with 1, 6 to 10 with 5, 11 to 15 with 9...

> x3 <- sample(1:30, 100, rep=TRUE)
> x3
  [1] 13 24 16 30 10  6 15 10  3 17 18 22 11 13 29  7 25 28 17 27  1  5  6 20 15 15  8 10 13 26 27 24  3 24  5  7 10  6 28 27  1  4 22 25 14 13  2 10  4 29 23 24 30 24 29 11  2 28 23  1  1  2
 [63]  3 23 13 26 21 22 11  4  8 26 17 11 20 23  6 14 24  5 15 21 11 13  6 14 20 11 22  9  6 29  4 30 20 30  4 24 23 29

As I mentioned this is a column in a data frame and with above assignment I want to create a different column. If I do the following I have to do this 30 times.

myFrame$NewColumn[myFrame$oldColumn==1] <- 1
myFrame$NewColumn[myFrame$oldColumn==2] <- 1
myFrame$NewColumn[myFrame$oldColumn==3] <- 1
...

Whats a better way to do this?

Body:
We can do this with cut (suppose what you mean by '...' is 10, 11, 12):

x4 <- cut(x3,
          breaks = c(seq(1, 30, 5), 30), right = F, include.lowest = T, # generate correct intervals
          labels = 4 * (0:5) + 1) # number to fill

# x4 is factor. We should convert it to character first then to the number
x4 <- as.numeric(as.character(x4))


问:
html highlighting for .leaf files with Brackets
Title (almost) says it all. I'm using Brackets 1.9 as my text editor. Now that I'm playing around with Vapor and using Leaf as a templating language.

I would like to do syntax coloring/predicting in my .leaf files while editing them with Brackets. I don't think there is support for the leaf syntax as such, but since .leaf files consist of a lot of HTML this would already be a big help.

Anyone who can help me configuring Brackets for that?

答:
There is a Wiki here on GitHub that covers what you want. Basically, you do the following:

Create a .brackets.json file in the root of the project.

Add the JSON to configure all the files with .leaf to highlight as HTML:

```<code>{
    "language.fileExtensions": {
        "leaf": "html"
    }
}
</code>```

Body:
There is a Wiki here on GitHub that covers what you want. Basically, you do the following:

Create a .brackets.json file in the root of the project.

Add the JSON to configure all the files with .leaf to highlight as HTML:

{
    "language.fileExtensions": {
        "leaf": "html"
    }
}


问:
How to center vertically an absolutely positioned scaled element?
Without scale code works fine, but I need to center vertically an already scaled element. I am looking for solution using CSS or JS approaches.
Also I can not use transform-origin CSS property because it's unsupported in some browsers that  I need to support...

https://jsfiddle.net/o62ja9r6/17/

.container {
  position: fixed;
  border: 2px dashed blue;
  width: 400px;
  height: 300px;
}

.slide {
  position: absolute;
  width: 76px;
  height: 169px;
  background-color: red;
}

.vertical-center {
  top: 50%;
  transform: scale(0.4) translateY(-50%);
  /* transform: translateY(-50%);  // <--- it works */
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="slide vertical-center">
  </div>
</div></code>```

答:
Order matters, swap translateY with scale.

.container {
  position: fixed;
  border: 2px dashed blue;
  width: 400px;
  height: 300px;
}

.slide {
  position: absolute;
  width: 76px;
  height: 169px;
  background-color: red;
}

.vertical-center {
  position: relative;
  top: 50%;
  transform: translateY(-50%) scale(0.4);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="slide vertical-center">
  </div>
</div></code>```

Quick Explination

If you have an element that is 100px tall and you translate it along the y-axis by -50% it will move up 50% of it's height, which would be 50px. If you scale that 100px tall element first, down to 40% of it's height, then it will be 40px tall when you try to translate it along the y-axis, which will only move it up 20px.

Body:
Order matters, swap translateY with scale.

.container {
  position: fixed;
  border: 2px dashed blue;
  width: 400px;
  height: 300px;
}

.slide {
  position: absolute;
  width: 76px;
  height: 169px;
  background-color: red;
}

.vertical-center {
  position: relative;
  top: 50%;
  transform: translateY(-50%) scale(0.4);
}

<div class="container">
  <div class="slide vertical-center">
  </div>
</div>

Quick Explination

If you have an element that is 100px tall and you translate it along the y-axis by -50% it will move up 50% of it's height, which would be 50px. If you scale that 100px tall element first, down to 40% of it's height, then it will be 40px tall when you try to translate it along the y-axis, which will only move it up 20px.


问:
Is there a way to use hashmap/list as jq tool condition building block?
I have set of jsons in a file as input

I am looking for a way to keep only those objects that meet the following (pseudo-jq) condition:

single_json[key] IN List

where List is predefined list of values (around 50k) - stored in another file (lets say one value per line)

Is smth like that possible and feasible? thanks

答:
You can read in your list of predefined values using one of the command-line options, e.g.

jq --argfile list FILEPATH ...

This makes the contents of the file available as $list

To check whether a JSON value is in an array, you could use index/1, e.g. using this helper function:

def check: . as $in | $list | index($in);

(It probably isn't necessary to use such a helper function, but it illustrates the idea.)

Without more specifics, it's difficult to be more specific, so for now let me just wish you good luck!


问:
How to use outlook SDK for nodejs to send emails
I have used custom SMTP to connect to outlook accounts as of now, but the issue is the mail sent via SMTP is not visible in sent box of outlook.

So i need to send emails using outlook sdk for nodejs.

https://github.com/jasonjoh/node-outlook/blob/master/mail-api.js

Is this the offical SDK ? If yes from where do i get token?

Need Help!

答:
Generate a client ID and secret
  Before we proceed, we need to register our app to obtain a client ID and secret. Head over to https://apps.dev.microsoft.com to quickly get a client ID and secret. Using the sign in buttons, sign in with either your Microsoft account (Outlook.com), or your work or school account (Office 365).

From this tutorial page: https://github.com/jasonjoh/node-tutorial


问:
Increasing the font size of only 1 axis value in an R plot
I was wondering how I can increase the font size of ONLY number "6" in my x-axis in the plot below? (Please see my R code below)

Here is my R code:

```<code>plot(1:10, ty = 'n', ann = F, xaxt = 'n', yaxt = 'n')

axis(side = 1, at = 1:10, font = 2)
</code>```

答:
You need to use cex.axis in another axis call exclusively for number 6.

```<code>plot(1:10, ty = 'n', ann = F, xaxt = 'n', yaxt = 'n')
axis(side = 1, at = c(1:5,7:10), font = 2)
axis(side = 1, at = 6, , font = 2, cex.axis=2)
</code>```

EDIT To move the 6 lower as requested, use line:

```<code>plot(1:10, ty = 'n', ann = F, xaxt = 'n', yaxt = 'n')
axis(side = 1, at = c(1:5,7:10), font = 2)
axis(side=1, at = 6, labels=FALSE,tick=TRUE) #draw normal tick, no label
axis(side = 1, at = 6, , font = 2, cex.axis=2, line=0.5,tick = FALSE)
</code>```

Body:
I was wondering how I can increase the font size of ONLY number "6" in my x-axis in the plot below? (Please see my R code below)

Here is my R code:

plot(1:10, ty = 'n', ann = F, xaxt = 'n', yaxt = 'n')

axis(side = 1, at = 1:10, font = 2)

Body:
You need to use cex.axis in another axis call exclusively for number 6.

plot(1:10, ty = 'n', ann = F, xaxt = 'n', yaxt = 'n')
axis(side = 1, at = c(1:5,7:10), font = 2)
axis(side = 1, at = 6, , font = 2, cex.axis=2)

EDIT To move the 6 lower as requested, use line:

plot(1:10, ty = 'n', ann = F, xaxt = 'n', yaxt = 'n')
axis(side = 1, at = c(1:5,7:10), font = 2)
axis(side=1, at = 6, labels=FALSE,tick=TRUE) #draw normal tick, no label
axis(side = 1, at = 6, , font = 2, cex.axis=2, line=0.5,tick = FALSE)


问:
My HTML page does'nt see the controller and the node js request associed
Here is my HTML code. I just have created a controller just for the part of the code.

```<code><div class="mdl-grid" ng-controller="ValueController">
          <div class="mdl-card mdl-shadow--4dp mdl-cell--12-col">
              <div class="mdl-card__title">
                <h3 class="mdl-card__title-text">Modifier seuils sur la carte</h3>
              </div>
              <div class="mdl-card__supporting-text">
              <div class="mdl-grid">
                <div class="mdl-cell--12-col mdl-grid">
                  <div class="mdl-cell--3-col mdl-grid">
                  <label class="mdl-cell--6-col">Plateforme</label>
                  <select class="mdl-cell--6-col" ng-model="platformselect" ng-change="obtainDatas()">
                    <option value="adsl">ADSL</option>
                    <option value="cable">Cable</option>
                    <option value="fibre">Fibre</option>
                    <option value="ott">OTT</option>
                    <option value="others">Others</option>
                    <option value="satellite">Satellite</option>
                    <option value="tnt">Tnt</option>
                  </select>
                 </div>
                  <div class="mdl-cell--3-col mdl-grid">
                  <label class="mdl-cell--6-col">Jour de la semaine</label>
                  <select class="mdl-cell--6-col" ng-model="dayselect" ng-change="obtainDatas()">
                    <option value="1">Lundi</option>
                    <option value="2">Mardi</option>
                    <option value="3">Mercredi</option>
                    <option value="4">Jeudi</option>
                    <option value="5">Vendredi</option>
                    <option value="6">Samedi</option>
                    <option value="0">Dimanche</option>
                 </select>
                 </div>
                  <div class="mdl-cell--3-col mdl-grid">
                  <label class="mdl-cell--6-col">Tranche horaire</label>
                  <select class="mdl-cell--6-col" ng-model="hourselect" ng-change="obtainDatas()">
                    <option value="0">0h-1h</option>
                    <option value="1">1h-2h</option>
                    <option value="2">2h-3h</option>
                    <option value="3">3h-4h</option>
                    <option value="4">4h-5h</option>
                    <option value="5">5h-6h</option>
                    <option value="6">6h-7h</option>
                    <option value="7">7h-8h</option>
                    <option value="8">8h-9h</option>
                    <option value="9">9h-10h</option>
                    <option value="10">10h-11h</option>
                    <option value="11">11h-12h</option>
                    <option value="12">12h-13h</option>
                    <option value="13">13h-14h</option>
                    <option value="14">14h-15h</option>
                    <option value="15">15h-16h</option>
                    <option value="16">16h-17h</option>
                    <option value="17">17h-18h</option>
                    <option value="18">18h-19h</option>
                    <option value="19">19h-20h</option>
                    <option value="20">20h-21h</option>
                    <option value="21">21h-22h</option>
                    <option value="22">22h-23h</option>
                    <option value="23">23h-0h</option>
                  </select>
                  </div>
                  <div class="mdl-cell--3-col mdl-grid">
                  <label class="mdl-cell--6-col">Départements</label>
                  <select class="mdl-cell--6-col" ng-model='deptselect' ng-change="obtainDatas()">
                    <option value="0">01</option>
                    <option value="1">02</option>
                    <option value="2">03</option>
                    <option value="3">04</option>
                    <option value="4">05</option>
                    <option value="5">06</option>
                    <option value="6">07</option>
                    <option value="7">08</option>
                    <option value="8">09</option>
                    <option value="9">10</option>
                    <option value="10">11</option>
                    <option value="11">12</option>
                    <option value="12">13</option>
                    <option value="13">14</option>
                    <option value="14">15</option>
                    <option value="15">16</option>
                    <option value="16">17</option>
                    <option value="17">18</option>
                    <option value="18">19</option>
                    <option value="19">2A</option>
                    <option value="20">2B</option>
                    <option value="21">21</option>
                    <option value="22">22</option>
                    <option value="23">23</option>
                    <option value="24">24</option>
                    <option value="25">25</option>
                    <option value="26">26</option>
                    <option value="27">27</option>
                    <option value="28">28</option>
                    <option value="29">29</option>
                    <option value="30">30</option>
                    <option value="31">31</option>
                    <option value="32">32</option>
                    <option value="33">33</option>
                    <option value="34">34</option>
                    <option value="35">35</option>
                    <option value="36">36</option>
                    <option value="37">37</option>
                    <option value="38">38</option>
                    <option value="39">39</option>
                    <option value="40">40</option>
                    <option value="41">41</option>
                    <option value="42">42</option>
                    <option value="43">43</option>
                    <option value="44">44</option>
                    <option value="45">45</option>
                    <option value="46">46</option>
                    <option value="47">47</option>
                    <option value="48">48</option>
                    <option value="49">49</option>
                    <option value="50">50</option>
                    <option value="51">51</option>
                    <option value="52">52</option>
                    <option value="53">53</option>
                    <option value="54">54</option>
                    <option value="55">55</option>
                    <option value="56">56</option>
                    <option value="57">57</option>
                    <option value="58">58</option>
                    <option value="59">59</option>
                    <option value="60">60</option>
                    <option value="61">61</option>
                    <option value="62">62</option>
                    <option value="63">63</option>
                    <option value="64">64</option>
                    <option value="65">65</option>
                    <option value="66">66</option>
                    <option value="67">67</option>
                    <option value="68">68</option>
                    <option value="69">69</option>
                    <option value="70">70</option>
                    <option value="71">71</option>
                    <option value="72">72</option>
                    <option value="73">73</option>
                    <option value="74">74</option>
                    <option value="75">75</option>
                    <option value="76">76</option>
                    <option value="77">77</option>
                    <option value="78">78</option>
                    <option value="79">79</option>
                    <option value="80">80</option>
                    <option value="81">81</option>
                    <option value="82">82</option>
                    <option value="83">83</option>
                    <option value="84">84</option>
                    <option value="85">85</option>
                    <option value="86">86</option>
                    <option value="87">87</option>
                    <option value="88">88</option>
                    <option value="89">89</option>
                    <option value="90">90</option>
                    <option value="91">91</option>
                    <option value="92">92</option>
                    <option value="93">93</option>
                    <option value="94">94</option>
                    <option value="95">95</option>
                  </select>
                 </div>
                </div>
              </div>
              <div class="mdl-card__actions mdl-card--border mdl-grid">
                <div class="mdl-cell--4-col mdl-grid">
                  <label class="mdl-cell--5-col">Valeur attendue</label>
                  <input class="mdl-cell--7-col" type="text" style="background-color: #66BB6A" ng-model="normalvalue"></input>
                </div>
                <div class="mdl-cell--4-col mdl-grid">
                  <label class="mdl-cell--5-col">Haute valeur</label>
                  <input class="mdl-cell--7-col" type="text" style="background-color: #FFA726" ng-model="highvalue"></input>
                </div>
                <div class="mdl-cell--4-col mdl-grid">
                  <label class="mdl-cell--5-col">Très haute valeur</label>
                  <input class="mdl-cell--7-col" type="text" style="background-color: #EF5350" ng-model="veryhighvalue"></input>
                </div>
              </div>
              <div class="mdl-card__actions mdl-card--border mdl-grid">
                <div class='mdl-cell--12-col'>
                  <button class="mdl-button mdl-js-button mdl-button--raised mdl-js-ripple-effect mdl-button--accent" style="float: right" layout-align="end center">Valider</button>
                </div>
              </div>
              </div>
        </div>
</code>```

The controller i have created :

```<code>(function() {

angular.module('app').controller('ValueController', '$scope', ['forecastValue', function(forecastValue){

    $scope.obtainDatas = function() {

    forecastValue.getResults($scope.hourselect, $scope.dayselect, $scope.deptselect, $scope.platformselect)
      .then(function(report) {
       $scope.normalvalue = report.expected, $scope.highvalue = report.higherExpected, $scope.veryhighvalue = report.muchHigherExpected;
        }).catch(function(err) {
          $scope.result = '';
          console.error('Unable to fetch forecast report: ' + err);
          });
  };

}]);
})();
</code>```

The forecast function to have the data :

```<code>(function(){

    angular.module('app')
    .factory('forecastValue', ['$http', '$q', function($http, $q){

        var apiAddr="https://something.com/app/getForecastDept";

        var forecast ={};

        forecastValue.getResults = function(hr, dy, dt, plm)
        {
            var httpParams = {
                hour: hr,
                day: dy,
                dept : dt,
                platform: plm
            };

            return $http.get(apiAddr, {
                params: httpParams,
                cache: true
            }).then(function(result) {
            return result.data;
            });

        };

        return forecast;

    }]);
})();
</code>```

And there is the part of my node js code about this function :

```<code>app.get('/app/getForecastDept', function(req, res) {
  logger.info("GET /app/getForecastDept");
  if (req.query.hour && req.query.day && req.query.dept && req.query.platform){
    getForecastDept(res, req.query);
  } else {
    badCall(res, "getForecastDept");
  }
});
</code>```

So when i launch the HTML page, i have have no function from the controller lauched. It is like if i have coded nothing.

How to explain this comportment ?

答:
You need to inject $scope into your controller.

```<code>angular.module('app').controller('ValueController', ['forecastValue', function(forecastValue){
</code>```

Becomes:

```<code>angular.module('app').controller('ValueController', ['forecastValue', '$scope', function(forecastValue, $scope){
</code>```

And you need to actually call the function you defined in ValueController. Maybe at the end of your controller code, include:

```<code> $scope.obtainDatas();
</code>```

Body:
Here is my HTML code. I just have created a controller just for the part of the code.

Modifier seuils sur la carte

                  Plateforme
                  <select class="mdl-cell--6-col" ng-model="platformselect" ng-change="obtainDatas()">
                    <option value="adsl">ADSL</option>
                    <option value="cable">Cable</option>
                    <option value="fibre">Fibre</option>
                    <option value="ott">OTT</option>
                    <option value="others">Others</option>
                    <option value="satellite">Satellite</option>
                    <option value="tnt">Tnt</option>
                  </select>

                  Jour de la semaine
                  <select class="mdl-cell--6-col" ng-model="dayselect" ng-change="obtainDatas()">
                    <option value="1">Lundi</option>
                    <option value="2">Mardi</option>
                    <option value="3">Mercredi</option>
                    <option value="4">Jeudi</option>
                    <option value="5">Vendredi</option>
                    <option value="6">Samedi</option>
                    <option value="0">Dimanche</option>
                 </select>

                  Tranche horaire
                  <select class="mdl-cell--6-col" ng-model="hourselect" ng-change="obtainDatas()">
                    <option value="0">0h-1h</option>
                    <option value="1">1h-2h</option>
                    <option value="2">2h-3h</option>
                    <option value="3">3h-4h</option>
                    <option value="4">4h-5h</option>
                    <option value="5">5h-6h</option>
                    <option value="6">6h-7h</option>
                    <option value="7">7h-8h</option>
                    <option value="8">8h-9h</option>
                    <option value="9">9h-10h</option>
                    <option value="10">10h-11h</option>
                    <option value="11">11h-12h</option>
                    <option value="12">12h-13h</option>
                    <option value="13">13h-14h</option>
                    <option value="14">14h-15h</option>
                    <option value="15">15h-16h</option>
                    <option value="16">16h-17h</option>
                    <option value="17">17h-18h</option>
                    <option value="18">18h-19h</option>
                    <option value="19">19h-20h</option>
                    <option value="20">20h-21h</option>
                    <option value="21">21h-22h</option>
                    <option value="22">22h-23h</option>
                    <option value="23">23h-0h</option>
                  </select>

                  Départements
                  <select class="mdl-cell--6-col" ng-model='deptselect' ng-change="obtainDatas()">
                    <option value="0">01</option>
                    <option value="1">02</option>
                    <option value="2">03</option>
                    <option value="3">04</option>
                    <option value="4">05</option>
                    <option value="5">06</option>
                    <option value="6">07</option>
                    <option value="7">08</option>
                    <option value="8">09</option>
                    <option value="9">10</option>
                    <option value="10">11</option>
                    <option value="11">12</option>
                    <option value="12">13</option>
                    <option value="13">14</option>
                    <option value="14">15</option>
                    <option value="15">16</option>
                    <option value="16">17</option>
                    <option value="17">18</option>
                    <option value="18">19</option>
                    <option value="19">2A</option>
                    <option value="20">2B</option>
                    <option value="21">21</option>
                    <option value="22">22</option>
                    <option value="23">23</option>
                    <option value="24">24</option>
                    <option value="25">25</option>
                    <option value="26">26</option>
                    <option value="27">27</option>
                    <option value="28">28</option>
                    <option value="29">29</option>
                    <option value="30">30</option>
                    <option value="31">31</option>
                    <option value="32">32</option>
                    <option value="33">33</option>
                    <option value="34">34</option>
                    <option value="35">35</option>
                    <option value="36">36</option>
                    <option value="37">37</option>
                    <option value="38">38</option>
                    <option value="39">39</option>
                    <option value="40">40</option>
                    <option value="41">41</option>
                    <option value="42">42</option>
                    <option value="43">43</option>
                    <option value="44">44</option>
                    <option value="45">45</option>
                    <option value="46">46</option>
                    <option value="47">47</option>
                    <option value="48">48</option>
                    <option value="49">49</option>
                    <option value="50">50</option>
                    <option value="51">51</option>
                    <option value="52">52</option>
                    <option value="53">53</option>
                    <option value="54">54</option>
                    <option value="55">55</option>
                    <option value="56">56</option>
                    <option value="57">57</option>
                    <option value="58">58</option>
                    <option value="59">59</option>
                    <option value="60">60</option>
                    <option value="61">61</option>
                    <option value="62">62</option>
                    <option value="63">63</option>
                    <option value="64">64</option>
                    <option value="65">65</option>
                    <option value="66">66</option>
                    <option value="67">67</option>
                    <option value="68">68</option>
                    <option value="69">69</option>
                    <option value="70">70</option>
                    <option value="71">71</option>
                    <option value="72">72</option>
                    <option value="73">73</option>
                    <option value="74">74</option>
                    <option value="75">75</option>
                    <option value="76">76</option>
                    <option value="77">77</option>
                    <option value="78">78</option>
                    <option value="79">79</option>
                    <option value="80">80</option>
                    <option value="81">81</option>
                    <option value="82">82</option>
                    <option value="83">83</option>
                    <option value="84">84</option>
                    <option value="85">85</option>
                    <option value="86">86</option>
                    <option value="87">87</option>
                    <option value="88">88</option>
                    <option value="89">89</option>
                    <option value="90">90</option>
                    <option value="91">91</option>
                    <option value="92">92</option>
                    <option value="93">93</option>
                    <option value="94">94</option>
                    <option value="95">95</option>
                  </select>

                  Valeur attendue
                  <input class="mdl-cell--7-col" type="text" style="background-color: #66BB6A" ng-model="normalvalue"></input>

                  Haute valeur
                  <input class="mdl-cell--7-col" type="text" style="background-color: #FFA726" ng-model="highvalue"></input>

                  Très haute valeur
                  <input class="mdl-cell--7-col" type="text" style="background-color: #EF5350" ng-model="veryhighvalue"></input>

                  <button class="mdl-button mdl-js-button mdl-button--raised mdl-js-ripple-effect mdl-button--accent" style="float: right" layout-align="end center">Valider</button>

The controller i have created :

(function() {

angular.module('app').controller('ValueController', '$scope', ['forecastValue', function(forecastValue){

    $scope.obtainDatas = function() {

    forecastValue.getResults($scope.hourselect, $scope.dayselect, $scope.deptselect, $scope.platformselect)
      .then(function(report) {
       $scope.normalvalue = report.expected, $scope.highvalue = report.higherExpected, $scope.veryhighvalue = report.muchHigherExpected;
        }).catch(function(err) {
          $scope.result = '';
          console.error('Unable to fetch forecast report: ' + err);
          });
  };

}]);
})();

The forecast function to have the data :

(function(){

    angular.module('app')
    .factory('forecastValue', ['$http', '$q', function($http, $q){

        var apiAddr="https://something.com/app/getForecastDept";

        var forecast ={};

        forecastValue.getResults = function(hr, dy, dt, plm)
        {
            var httpParams = {
                hour: hr,
                day: dy,
                dept : dt,
                platform: plm
            };

            return $http.get(apiAddr, {
                params: httpParams,
                cache: true
            }).then(function(result) {
            return result.data;
            });

        };

        return forecast;

    }]);
})();

And there is the part of my node js code about this function :

app.get('/app/getForecastDept', function(req, res) {
  logger.info("GET /app/getForecastDept");
  if (req.query.hour && req.query.day && req.query.dept && req.query.platform){
    getForecastDept(res, req.query);
  } else {
    badCall(res, "getForecastDept");
  }
});

So when i launch the HTML page, i have have no function from the controller lauched. It is like if i have coded nothing.

How to explain this comportment ?

Body:
You need to inject $scope into your controller.

angular.module('app').controller('ValueController', ['forecastValue', function(forecastValue){

Becomes:

angular.module('app').controller('ValueController', ['forecastValue', '$scope', function(forecastValue, $scope){

And you need to actually call the function you defined in ValueController. Maybe at the end of your controller code, include:

 $scope.obtainDatas();


问:
AJAX Instant messenger
Hi I am trying to make an AJAX instant messenger. I currently have a website (with user logon, admin area etc.) using PHP, MySql, Java Script etc and an AJAX chat prog with 2 chat rooms (and users in room list etc) and it works really good, but dont really know where to go from here (instant messenger wise). I have done some researh which has suggested using an AJAX listener for new messages but I cant find much information on it...or if indeed this is needed or i should use something else. If anyone has any advice where I should go next it would be very, very much appreciated, thanks :)</p>

答:
Node.js

Like a lot of people mentioned I would use node.js/socket.io for this instead of PHP. It has been created to tackle such sort of problems.

Redis

But if you really want to create somethink like this in PHP I would do it using redis(needs to be installed). It has blocking list operations which really help you create something like this. When some user sents a message to another user we push the message to corresponding blocking list of that user. The user listens to an unique blocking list(key) to receive messages.

Can not install Redis

Then you have to use MySQL insert into a table and poll table frequently, but not to much to kill your server/database.

ContentLicense: CC BY-SA 2.5

Title: AJAX Instant messenger


问:
Ionic ion-side-menus produces blank page when combined with ui-router child states
As the title states, I am having issues with using Angular ui-router together with ion-side-menus. I've seen several other very similar issues but I can't seem to identify my issue.

Before I had my base state load into ion-nav-view without using a parent state and the side bar would show up. However as soon as I changed states the side bar stopped working. Since adding the parent state app and making feed a child of it has my app showing a completely blank screen, and not running any code from either controller.

Starting with index.html my body tag is just the <ion-nav-view> tag:

```<code><body>
  <ion-nav-view></ion-nav-view>
</body>
</code>```

menu.html contains the html for the side bar menu:

```<code><ion-side-menus>
  <ion-pane ion-side-menu-content>
    <ion-nav-bar class="bar-stable">
      <ion-nav-back-button class="button-clear"><i class="icon ion-chevron-left"></i> Back</ion-nav-back-button>
    </ion-nav-bar>
    <ion-nav-view name="menuContent" animation="slide-left-right"></ion-nav-view>
  </ion-pane>
  <ion-side-menu side="left">
    <header class="bar bar-header bar-stable">
      <h1 class="title">Left</h1>
    </header>
    <ion-content class="has-header">
      <ion-list>
        <ion-item nav-clear menu-close>
          Tab 1
        </ion-item>
        <ion-item nav-clear menu-close>
          Tab 2
        </ion-item>
        <ion-item nav-clear menu-close>
          Some tab
        </ion-item>
      </ion-list>
    </ion-content>
  </ion-side-menu>
</ion-side-menus>
</code>```

Finally the piece that ties things together, is the router:

function config($stateProvider, $urlRouterProvider, $locationProvider) {

```<code>$urlRouterProvider.when('', '/feed');
$urlRouterProvider.otherwise('/feed');

$stateProvider
  .state('app', {
    url: '/app',
    abstract: true,
    templateUrl: 'views/menu/menu.html',
    controller: 'MenuController'
  })

$stateProvider
  .state('app.feed', {
    url: '/feed',
    views: {
      'menuContent': {
        templateUrl: 'views/feed/feed.html',
        controller: 'FeedController',
        controllerAs: 'ctrl',
        authenticate: true
      }
    }
  });

//Other states
</code>```

I appreciate any insight anyone can provide!

答: The issue was that $urlRouterProvider.otherwise() was pointing to /feed when it should have been /app/feed since it technically a child state.

Body:
As the title states, I am having issues with using Angular ui-router together with ion-side-menus. I've seen several other very similar issues but I can't seem to identify my issue.

Before I had my base state load into ion-nav-view without using a parent state and the side bar would show up. However as soon as I changed states the side bar stopped working. Since adding the parent state app and making feed a child of it has my app showing a completely blank screen, and not running any code from either controller.

Starting with index.html my body tag is just the <ion-nav-view> tag:

  <ion-nav-view></ion-nav-view>

menu.html contains the html for the side bar menu:

<ion-side-menus>
  <ion-pane ion-side-menu-content>
    <ion-nav-bar class="bar-stable">
      <ion-nav-back-button class="button-clear"> Back</ion-nav-back-button>
    </ion-nav-bar>
    <ion-nav-view name="menuContent" animation="slide-left-right"></ion-nav-view>
  </ion-pane>
  <ion-side-menu side="left">

Left

    <ion-content class="has-header">
      <ion-list>
        <ion-item nav-clear menu-close>
          Tab 1
        </ion-item>
        <ion-item nav-clear menu-close>
          Tab 2
        </ion-item>
        <ion-item nav-clear menu-close>
          Some tab
        </ion-item>
      </ion-list>
    </ion-content>
  </ion-side-menu>
</ion-side-menus>

Finally the piece that ties things together, is the router:

function config($stateProvider, $urlRouterProvider, $locationProvider) {

$urlRouterProvider.when('', '/feed');
$urlRouterProvider.otherwise('/feed');

$stateProvider
  .state('app', {
    url: '/app',
    abstract: true,
    templateUrl: 'views/menu/menu.html',
    controller: 'MenuController'
  })

$stateProvider
  .state('app.feed', {
    url: '/feed',
    views: {
      'menuContent': {
        templateUrl: 'views/feed/feed.html',
        controller: 'FeedController',
        controllerAs: 'ctrl',
        authenticate: true
      }
    }
  });

//Other states

I appreciate any insight anyone can provide!


问:
Best way to construct a binary tree from a list in python
Assuming each node has self.left, self.right and self.data, whats the best way to construct a binary tree, not a binary search tree (BST), from a list where the numbers are given per level.  Where the first number is level 1, next 2 are level 2, next 4 are level 3, and so on.  For example

```<code>input: [3,5,2,1,4,6,7,8,9,10,11,12,13,14]
</code>```

constructs a tree:

```<code>          3
       /     \
     5         2
    /\         /\
   1  4       6   7
  /\  /\     /\   /\
 8 9 10 11 12 13 14
</code>```

One solution is:

```<code>for node at index i,
left child index = 2i+1
right child index = 2i+2
</code>```

Wondering if there are other possible ways

答:
One way to do it is to build a fringe of the current leaves.

Assuming a Node class:

```<code>class Node(object):
    def __init__(self, data):
        self.data = data
        self.left = '*'
        self.right = '*'
    def __str__(self):
        return f'<{self.data}, {self.left}, {self.right}>'  # Py 3.6
</code>```

Then you can just manage the fringe and iterate over the data:

```<code>from collections import deque

data = [3,5,2,1,4,6,7,8,9,10,11,12,13,14]
n = iter(data)
tree = Node(next(n))
fringe = deque([tree])
while True:
    head = fringe.popleft()
    try:
        head.left = Node(next(n))
        fringe.append(head.left)
        head.right = Node(next(n))
        fringe.append(head.right)
    except StopIteration:
        break

print(tree)
# <3, <5, <1, <8, *, *>, <9, *, *>>, <4, <10, *, *>, <11, *, *>>>, <2, <6, <12, *, *>, <13, *, *>>, <7, <14, *, *>, *>>>
</code>```

Body:
Assuming each node has self.left, self.right and self.data, whats the best way to construct a binary tree, not a binary search tree (BST), from a list where the numbers are given per level.  Where the first number is level 1, next 2 are level 2, next 4 are level 3, and so on.  For example

input: [3,5,2,1,4,6,7,8,9,10,11,12,13,14]

constructs a tree:

          3
       /     \
     5         2
    /\         /\
   1  4       6   7
  /\  /\     /\   /\
 8 9 10 11 12 13 14

One solution is:

for node at index i,
left child index = 2i+1
right child index = 2i+2

Wondering if there are other possible ways

Body:
One way to do it is to build a fringe of the current leaves.

Assuming a Node class:

class Node(object):
    def __init__(self, data):
        self.data = data
        self.left = '*'
        self.right = '*'
    def __str__(self):
        return f'<{self.data}, {self.left}, {self.right}>'  # Py 3.6

Then you can just manage the fringe and iterate over the data:

from collections import deque

data = [3,5,2,1,4,6,7,8,9,10,11,12,13,14]
n = iter(data)
tree = Node(next(n))
fringe = deque([tree])
while True:
    head = fringe.popleft()
    try:
        head.left = Node(next(n))
        fringe.append(head.left)
        head.right = Node(next(n))
        fringe.append(head.right)
    except StopIteration:
        break

print(tree)
# <3, <5, <1, <8, *, *>, <9, *, *>>, <4, <10, *, *>, <11, *, *>>>, <2, <6, <12, *, *>, <13, *, *>>, <7, <14, *, *>, *>>>


问:
XSL selecting a XML document is not showing information
Why doesn't this work?

```<code><?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:template match="/">
    <html>
      <body>
        <xsl:variable name="PubDB" select="document('MSA_PublisherDatabase.XML')"/>
        <table>
          <xsl:apply-templates select="$PubDB/PublisherDatabase/Publishers/Publisher"/>
        </table>
      </body>
    </html>
  </xsl:template>
  <xsl:template match="Publisher">
    <tr>
      <td>
        <xsl:value-of select="Name"/>
      </td>
    </tr>
  </xsl:template>
</xsl:stylesheet>
</code>```

The XML file contains something like:

```<code><?xml version="1.0" encoding="utf-8"?>
<PublisherDatabase xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.publictalksoftware.co.uk/msa">
  <Publishers>
    <Publisher Gender="Male" Appointed="MinisterialServant" Serving="Publisher">
      <Name>Fred Junior</Name>
      <Notes />
      <Availability Midweek="true" Weekend="true">
        <DatesNotAvailable />
        <DefaultExclusions />
      </Availability>
      <Assignments Attendant="true" ConductorCBS="false" ReaderCBS="true" Chairman="false" Microphones="true" PlatformAttendant="true" Prayer="true" OCLM="true" Sound="true" Student="true" Demonstrations="false">
        <CustomAssignments />
      </Assignments>
    </Publisher>
  </Publishers>
</PublisherDatabase>
</code>```

In this instance I am expecting it to give me a list of names. Nothing is showing up.

I specifically am trying to select a document in to my XSL ..

答:
You have set xmlns at the beginning, of your XML, thus you are by default is the namespace where the attached URI is http://www.publictalksoftware.co.uk/msa.

If you want a quick fix, remove this xmlns declaration and your XSLT should work properly.

Otherwise, the solution would be:

declare the namespace at the beginning of your stylesheet: <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:msa="http://www.publictalksoftware.co.uk/msa"> (I use msa, but any prefix could be used)

change your XPath to <xsl:apply-templates select="$PubDB/msa:PublisherDatabase/msa:Publishers/msa:Publisher"/>

Body:
Why doesn't this work?

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:template match="/">

        <xsl:variable name="PubDB" select="document('MSA_PublisherDatabase.XML')"/>

          <xsl:apply-templates select="$PubDB/PublisherDatabase/Publishers/Publisher"/>

  </xsl:template>
  <xsl:template match="Publisher">

        <xsl:value-of select="Name"/>

  </xsl:template>
</xsl:stylesheet>

The XML file contains something like:

<?xml version="1.0" encoding="utf-8"?>
<PublisherDatabase xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.publictalksoftware.co.uk/msa">
  <Publishers>
    <Publisher Gender="Male" Appointed="MinisterialServant" Serving="Publisher">
      <Name>Fred Junior</Name>
      <Notes />
      <Availability Midweek="true" Weekend="true">
        <DatesNotAvailable />
        <DefaultExclusions />
      </Availability>
      <Assignments Attendant="true" ConductorCBS="false" ReaderCBS="true" Chairman="false" Microphones="true" PlatformAttendant="true" Prayer="true" OCLM="true" Sound="true" Student="true" Demonstrations="false">
        <CustomAssignments />
      </Assignments>
    </Publisher>
  </Publishers>
</PublisherDatabase>

In this instance I am expecting it to give me a list of names. Nothing is showing up.

I specifically am trying to select a document in to my XSL ..


问:
Position two Terminal windows
I'd like to start two Terminals and put them at specific positions on my screen. I know how to do this with one Terminal but what do I have to do to open a second Terminal and position it next to the first one?

Here is the code for one Terminal:

```<code>hs.hotkey.bind({"cmd", "alt", "ctrl"}, "2", function()
  hs.application.launchOrFocus("Terminal")
  local win = hs.window.focusedWindow()
  local f = win:frame()
  local screen = win:screen()
  local max = screen:frame()

  f.x = max.x
  f.y = max.y

  f.w = 960
  f.h = 540
  win:setFrame(f)
end)
</code>```

答: So this potentially gets quite complex, but what I would do is have the hotkey check to see if Terminal is already running. If not, launch it and put it in position 1. If it is already running, focus it, activate the menu item to open a new window, and put it in position 2.</p>

Title: Position two Terminal windows

Body:
I'd like to start two Terminals and put them at specific positions on my screen. I know how to do this with one Terminal but what do I have to do to open a second Terminal and position it next to the first one?

Here is the code for one Terminal:

hs.hotkey.bind({"cmd", "alt", "ctrl"}, "2", function()
  hs.application.launchOrFocus("Terminal")
  local win = hs.window.focusedWindow()
  local f = win:frame()
  local screen = win:screen()
  local max = screen:frame()

  f.x = max.x
  f.y = max.y

  f.w = 960
  f.h = 540
  win:setFrame(f)
end)


问:
Android: Singleton instead of a Service
I was conducting today interview with one of the candidates. I asked pretty common question: how to add to Android application possibility of playing music constantly, even when activity is destroyed when phone orientations changed. Expected answer was: create Service responsible for playing music. Instead of that candidate suggested to create some singleton in application.

Is this also a correct answer? I think it should be working - Singleton class will be load to memory and will stay in memory forever; my colleague suggest this singleton will be destroy with destroyed activity, because there won't be any reference any longer.

答:
The only way to create a background task that keeps the application's context from being destroyed is to run a Service in the foreground by displaying a persistent notification that informs the user that it is running. An example given is more or less exactly what you were asking the candidate to provide:

For example, a music player that plays music from a service should be set to run in the foreground, because the user is explicitly aware of its operation. The notification in the status bar might indicate the current song and allow the user to launch an activity to interact with the music player.

Additionally, the singleton exists in the global scope and lives for as long as global scope does - typically until Android kills your application because it's not running any foreground tasks, not when the Activity that uses it gets cleaned up.

Title: Android: Singleton instead of a Service


问:
Get name from only date and ID matched with people list
I have rawdata with only ID's and dates of transactions. Then I have a list of people; their ID, their hire date and their name.

What I want is a column in the rawdata that gives me the persons name. The problem is, that the ID is re-used if the person quits, and another one starts.

Since I have the transaction date, I figure it should be possible to check:

IF the transaction matches the period they were hired, then get the right name.

Is this possible, and then how?

```<code>Rawdata:
Column A = Transaction date
Column B = ID
Column C = Here I want their name

People list:
Column A = ID
Column B = Name
Column C = Hire date
</code>```

Example (Excel Online - can be edited):
https://1drv.ms/x/s!AjWVkb2UBexjhzAKMy-YiE5EoKwc

Screenshot:

答:
I had to name your tables People and Raw_Data to use structured table references in the formula. Additonally, I added some data and changed a few dates.

```<code>=INDEX(People[Agent Name], AGGREGATE(15,6, (ROW(People[Personal ID])-ROW(People[[#Headers],[Agent Name]]))/((People[Personal ID]=[@[Personal ID]])*(People[Hire date]=AGGREGATE(14, 6, (People[Hire date])/((People[Personal ID]=[@[Personal ID]])*(People[Hire date]<=[@[Transaction date]])), 1))), 1))
</code>```

Body:
I have rawdata with only ID's and dates of transactions. Then I have a list of people; their ID, their hire date and their name.

What I want is a column in the rawdata that gives me the persons name. The problem is, that the ID is re-used if the person quits, and another one starts.

Since I have the transaction date, I figure it should be possible to check:

IF the transaction matches the period they were hired, then get the right name.

Is this possible, and then how?

Rawdata:
Column A = Transaction date
Column B = ID
Column C = Here I want their name

People list:
Column A = ID
Column B = Name
Column C = Hire date

Example (Excel Online - can be edited):
https://1drv.ms/x/s!AjWVkb2UBexjhzAKMy-YiE5EoKwc

Screenshot:

Body:
I had to name your tables People and Raw_Data to use structured table references in the formula. Additonally, I added some data and changed a few dates.

=INDEX(People[Agent Name], AGGREGATE(15,6, (ROW(People[Personal ID])-ROW(People[[#Headers],[Agent Name]]))/((People[Personal ID]=[@[Personal ID]])*(People[Hire date]=AGGREGATE(14, 6, (People[Hire date])/((People[Personal ID]=[@[Personal ID]])*(People[Hire date]<=[@[Transaction date]])), 1))), 1))