问:
Animate div from center of it
I have a div that pops up when a certain action appears. Instead of just popping up, I animated it so it appears to grow in size when the event happens. This is nice and all, but I would like it to instead of animating from the top left corner of the div, I want it to animate from either the center of the div, or the center-top of the div. How would I achieve this by using just Javascript and jQuery?

Below is what I have as of now.

var newsPopup = $('#news-container');
slideIntoHub(newsPopup);

// Slides any HTML object into the hub by animations
function slideIntoHub(object) {
    removeHubContents();
    object.css({'height' : '0', 'width' : '0'});
    object.appendTo('#hub');
    object.animate({width: '500', height: '200'}, 1000);
}
// Removes everything from #hub
function removeHubContents() {
    var hub = $('#hub');
    hub.children().each(function() {
        $(this).detach();
    });
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#news-container {
    background-color: white;
    border: 15px gray outset;
    border-radius: 50px;
    padding: 10px;
}
.news-firstRow {
    width: 100%;
    display: inline-block;
}
.news-icon {
    display: inline-block;
    margin: 0 auto;
    padding-right: 50px;
    vertical-align: middle;
}
.news-title {
    display: inline-block;
    margin: 0 auto;
    vertical-align: middle;
}
.news-secondRow {
    width: 100%;
    display: inline-block;
}
.news-thirdRow {
    width: 100%;
    display: inline-block;
}
.news-publishedDate {
    float: right;
    padding-bottom: 10px;
    font-size: 7px;
}</code>```

Sales booming

The team is coming up with more products everyday

Published on: 3-29-2017

```

答:
Try css3 transform: scale property for the best results

$(document).ready(function(){
  $('button').on('click', function(){
    $('div').toggleClass('scale-it');
  })
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>div{
  height: 150px;
  width: 150px;
  border: 5px solid crimson;
  transform: scale(0);
  transition: 0.5s ease-in-out all;
}
.scale-it{
  transform: scale(1);
  }</code>```

<button>click</button>

```

Title: Animate div from center of it

Body:
I have a div that pops up when a certain action appears. Instead of just popping up, I animated it so it appears to grow in size when the event happens. This is nice and all, but I would like it to instead of animating from the top left corner of the div, I want it to animate from either the center of the div, or the center-top of the div. How would I achieve this by using just Javascript and jQuery?

Below is what I have as of now.

var newsPopup = $('#news-container');
slideIntoHub(newsPopup);

// Slides any HTML object into the hub by animations
function slideIntoHub(object) {
    removeHubContents();
    object.css({'height' : '0', 'width' : '0'});
    object.appendTo('#hub');
    object.animate({width: '500', height: '200'}, 1000);
}
// Removes everything from #hub
function removeHubContents() {
    var hub = $('#hub');
    hub.children().each(function() {
        $(this).detach();
    });
}

#news-container {
    background-color: white;
    border: 15px gray outset;
    border-radius: 50px;
    padding: 10px;
}
.news-firstRow {
    width: 100%;
    display: inline-block;
}
.news-icon {
    display: inline-block;
    margin: 0 auto;
    padding-right: 50px;
    vertical-align: middle;
}
.news-title {
    display: inline-block;
    margin: 0 auto;
    vertical-align: middle;
}
.news-secondRow {
    width: 100%;
    display: inline-block;
}
.news-thirdRow {
    width: 100%;
    display: inline-block;
}
.news-publishedDate {
    float: right;
    padding-bottom: 10px;
    font-size: 7px;
}

Sales booming

The team is coming up with more products everyday

Published on: 3-29-2017

Body:
Try css3 transform: scale property for the best results

$(document).ready(function(){
  $('button').on('click', function(){
    $('div').toggleClass('scale-it');
  })
});

div{
  height: 150px;
  width: 150px;
  border: 5px solid crimson;
  transform: scale(0);
  transition: 0.5s ease-in-out all;
}
.scale-it{
  transform: scale(1);
  }

<button>click</button>
<div></div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


来源: stackexchange

问:
Working between PHP library and JS library in Mixpanel
I am new to Mixpanel and currently wondering how can i work between Mixpanel's JS library and PHP library.

Let say that i have the following (simple) JS script:

```<code>// Placed on homepage
<script type="text/javascript">
  mixpanel.track("viewed homepage");
</script>

// Placed on category page
<script type="text/javascript">
  mixpanel.track("viewed category page");
</script>

// Placed on product page
<script type="text/javascript">
  mixpanel.track("viewed product page");
</script>
</code>```

So when John Doe (jdoe@example.com) visit my website at http://example.com, he first lands on the homepage and then navigate away to category page and browse for some products (john might go back and forth between category page and product page).

As far as i know, John will be assigned with some random ID (distinct id) from Mixpanel (e.g. 123123).

I also have this PHP code:

```<code>$mp->identify("jdoe@example.com");

$mp->people->set(XYZ, array(
    '$first_name'       => "John",
    '$last_name'        => "Doe",
    '$email'            => "john.doe@example.com",
    '$phone'            => "5555555555"
));

$mp->people->increment(XYZ, "login count", 1);
</code>```

According to the Mixpanel docs here found here https://mixpanel.com/help/reference/php

"XYZ" should be Mixpanel distinct id, which in this case is set to 123123 for our John Doe.

So the question would be, how can i know the assigned distinct id set by Mixpanel to John Doe using PHP library knowing that he has previously been assigned a distinct id (via JS library) ?

I also notice that when using Mixpanel's PHP library, it doesn't automatically assigned randomly generated distinct id as compared to using JS library (see image for details):

EDIT 1

So i found this code on the docs:

```<code>// set distinct_id after the mixpanel library has loaded
mixpanel.init("YOUR PROJECT TOKEN", {
    loaded: function() {
        distinct_id = mixpanel.get_distinct_id();
    }
});
</code>```

Which basically can retrieve the distinct_id set by Mixpanel, and wondering whether it is possible to retrieve the distinct_id via PHP (presumably the distinct_id is stored in the cookies).

答:
Simply use the same session id for both libraries:

As docs says:

If you do not choose to manage distinct_id yourself, each time a user shows up in a new browser, on a new machine, or clears their cookies, they will appear to be a new unique user.

it's similar to session structure so I decided to reuse it, with Laravel I wrote the following for JS library:

```<code>mixpanel.identify("{{ session()->getId() }}");
mixpanel.track('Some event');
</code>```

And this for PHP library:

```<code>$mp->identify(session()->getId());
$mp->track('Another event');
</code>```

It's works very well for me.

ContentLicense: CC BY-SA 3.0

Body:
I am new to Mixpanel and currently wondering how can i work between Mixpanel's JS library and PHP library.

Let say that i have the following (simple) JS script:

// Placed on homepage

// Placed on category page

// Placed on product page

So when John Doe (jdoe@example.com) visit my website at http://example.com, he first lands on the homepage and then navigate away to category page and browse for some products (john might go back and forth between category page and product page).

As far as i know, John will be assigned with some random ID (distinct id) from Mixpanel (e.g. 123123).

I also have this PHP code:

$mp->identify("jdoe@example.com");

$mp->people->set(XYZ, array(
    '$first_name'       => "John",
    '$last_name'        => "Doe",
    '$email'            => "john.doe@example.com",
    '$phone'            => "5555555555"
));

$mp->people->increment(XYZ, "login count", 1);

According to the Mixpanel docs here found here https://mixpanel.com/help/reference/php

"XYZ" should be Mixpanel distinct id, which in this case is set to 123123 for our John Doe.

So the question would be, how can i know the assigned distinct id set by Mixpanel to John Doe using PHP library knowing that he has previously been assigned a distinct id (via JS library) ?

I also notice that when using Mixpanel's PHP library, it doesn't automatically assigned randomly generated distinct id as compared to using JS library (see image for details):

EDIT 1

So i found this code on the docs:

// set distinct_id after the mixpanel library has loaded
mixpanel.init("YOUR PROJECT TOKEN", {
    loaded: function() {
        distinct_id = mixpanel.get_distinct_id();
    }
});

Which basically can retrieve the distinct_id set by Mixpanel, and wondering whether it is possible to retrieve the distinct_id via PHP (presumably the distinct_id is stored in the cookies).

Body:
Simply use the same session id for both libraries:

As docs says:

If you do not choose to manage distinct_id yourself, each time a user shows up in a new browser, on a new machine, or clears their cookies, they will appear to be a new unique user.

it's similar to session structure so I decided to reuse it, with Laravel I wrote the following for JS library:

mixpanel.identify("{{ session()->getId() }}");
mixpanel.track('Some event');

And this for PHP library:

$mp->identify(session()->getId());
$mp->track('Another event');

It's works very well for me.


问:
Pyomo (GLPK, Windows) shows me weird results within 'results.yml'
Working with Pyomo 5.1.1 (CPython 2.7.10 on Windows 7), I'm trying to execute the easiest Pyomo example, the concrete model shown at https://software.sandia.gov/downloads/pub/pyomo/PyomoOnlineDocs.html#_a_simple_concrete_pyomo_model

```<code>from __future__ import division
from pyomo.environ import *
model = ConcreteModel()
model.x = Var([1,2], domain=NonNegativeReals)
model.OBJ = Objective(expr = 2*model.x[1] + 3*model.x[2])
model.Constraint1 = Constraint(expr = 3*model.x[1] + 4*model.x[2] >= 1)
</code>```

I execute:

```<code>> pyomo solve Pyomo_concrete_v1.py --solver=glpk
</code>```

According to my own calculations, the results should be:

```<code>x[1]=0
x[2]=0.25
OBJ=0.75
</code>```

However, I find the following 'results.yml':

```<code># ----------------------------------------------------------
#   Problem Information
# ----------------------------------------------------------
Problem:
- Name: unknown
  Lower bound: 0.666666666667
  Upper bound: 0.666666666667
  Number of objectives: 1
  Number of constraints: 2
  Number of variables: 3
  Number of nonzeros: 3
  Sense: minimize
# ----------------------------------------------------------
#   Solver Information
# ----------------------------------------------------------
Solver:
- Status: ok
  Termination condition: optimal
  Statistics:
    Branch and bound:
      Number of bounded subproblems: 0
      Number of created subproblems: 0
  Error rc: 0
  Time: 0.018000125885
# ----------------------------------------------------------
#   Solution Information
# ----------------------------------------------------------
Solution:
- number of solutions: 1
  number of solutions displayed: 1
- Gap: 0.0
  Status: feasible
  Message: None
  Objective:
    OBJ:
      Value: 0.666666666667
  Variable:
    x[1]:
      Value: 0.333333333333
  Constraint: No values
</code>```

I do not understand why there are "2 constraints" (there is actually only one constraint), "3 variables" (actually, 2), and the results is a vector of size 1.

This 'results.yml' changes everytime I execute 'pyomo', but the contents are always the same.

答:
This is due to a quirk in the LP file format.  Specifically, some solvers do not allow constant terms in the objective.  To work around this, Pyomo automatically adds a trivial variable (named ONE_VAR_CONSTANT) and a constraint that forces it to 1 (literally, ONE_VAR_CONSTANT == 1) to all models output in LP file format.  This generally does not impact solver performance, as solvers have presolve steps that will remove the variable and constraint from the model before solving it.

Also, note that the results you are seeing in the summary are correct: the optimal solution to your model is:

```<code>x[1]=0.3333333
x[2]=0
OBJ=0.666666
</code>```

and can be verified by substituting the answer into the constraint and objective (the constraint is active and satisfied, and the objective is lower than your hand-calculated value of 0.75).

Body:
Working with Pyomo 5.1.1 (CPython 2.7.10 on Windows 7), I'm trying to execute the easiest Pyomo example, the concrete model shown at https://software.sandia.gov/downloads/pub/pyomo/PyomoOnlineDocs.html#_a_simple_concrete_pyomo_model

from __future__ import division
from pyomo.environ import *
model = ConcreteModel()
model.x = Var([1,2], domain=NonNegativeReals)
model.OBJ = Objective(expr = 2*model.x[1] + 3*model.x[2])
model.Constraint1 = Constraint(expr = 3*model.x[1] + 4*model.x[2] >= 1)

I execute:

> pyomo solve Pyomo_concrete_v1.py --solver=glpk

According to my own calculations, the results should be:

x[1]=0
x[2]=0.25
OBJ=0.75

However, I find the following 'results.yml':

# ----------------------------------------------------------
#   Problem Information
# ----------------------------------------------------------
Problem:
- Name: unknown
  Lower bound: 0.666666666667
  Upper bound: 0.666666666667
  Number of objectives: 1
  Number of constraints: 2
  Number of variables: 3
  Number of nonzeros: 3
  Sense: minimize
# ----------------------------------------------------------
#   Solver Information
# ----------------------------------------------------------
Solver:
- Status: ok
  Termination condition: optimal
  Statistics:
    Branch and bound:
      Number of bounded subproblems: 0
      Number of created subproblems: 0
  Error rc: 0
  Time: 0.018000125885
# ----------------------------------------------------------
#   Solution Information
# ----------------------------------------------------------
Solution:
- number of solutions: 1
  number of solutions displayed: 1
- Gap: 0.0
  Status: feasible
  Message: None
  Objective:
    OBJ:
      Value: 0.666666666667
  Variable:
    x[1]:
      Value: 0.333333333333
  Constraint: No values

I do not understand why there are "2 constraints" (there is actually only one constraint), "3 variables" (actually, 2), and the results is a vector of size 1.

This 'results.yml' changes everytime I execute 'pyomo', but the contents are always the same.

Body:
This is due to a quirk in the LP file format.  Specifically, some solvers do not allow constant terms in the objective.  To work around this, Pyomo automatically adds a trivial variable (named ONE_VAR_CONSTANT) and a constraint that forces it to 1 (literally, ONE_VAR_CONSTANT == 1) to all models output in LP file format.  This generally does not impact solver performance, as solvers have presolve steps that will remove the variable and constraint from the model before solving it.

Also, note that the results you are seeing in the summary are correct: the optimal solution to your model is:

x[1]=0.3333333
x[2]=0
OBJ=0.666666

and can be verified by substituting the answer into the constraint and objective (the constraint is active and satisfied, and the objective is lower than your hand-calculated value of 0.75).


问:
Create a new dictionary with each iteration of loop
I am trying to extract positions and SNPs from a VCF file.  I have written the following so far. But how can I change the name of the dictionary so that I end up with one dictionary for each input file?

i.e.: python vcf_compare.py file1.vcf file2.vcf file3.vcf

```<code>import sys

import vcf

for variants in sys.argv[1:]:
    file1 = {}
    vcf_reader = vcf.Reader(open(variants))
    for record in vcf_reader:
        pos = record.POS
        alt = record.ALT
        ref= record.REF
        snps[pos]=ref,alt
</code>```

so for argv[1] a dictionary called file1 is created.  How can I make the dictionary change name to e.g. file two for the second iteration of the loop?

答:
You should use collections.defaultdict and also use with open(...):

```<code>from collections import defaultdict

files = defaultdict(dict)
for filename in sys.argv[1:]:
    with open(filename) as f:
        vcf_reader = vcf.Reader(f)
        for record in vcf_reader:
            files[filename][record.POS] = record.REF, record.ALT
</code>```

All these nice python tricks make the code more readable, shorter, uses less intermediate temporary variables. Also, using with open() ensures each file gets automatically closed after being read.

Also, as you can see, you can chose better variable names, and also reduce considerably the number of lines of code.

Body:
I am trying to extract positions and SNPs from a VCF file.  I have written the following so far. But how can I change the name of the dictionary so that I end up with one dictionary for each input file?

i.e.: python vcf_compare.py file1.vcf file2.vcf file3.vcf

import sys

import vcf

for variants in sys.argv[1:]:
    file1 = {}
    vcf_reader = vcf.Reader(open(variants))
    for record in vcf_reader:
        pos = record.POS
        alt = record.ALT
        ref= record.REF
        snps[pos]=ref,alt

so for argv[1] a dictionary called file1 is created.  How can I make the dictionary change name to e.g. file two for the second iteration of the loop?

Body:
You should use collections.defaultdict and also use with open(...):

from collections import defaultdict

files = defaultdict(dict)
for filename in sys.argv[1:]:
    with open(filename) as f:
        vcf_reader = vcf.Reader(f)
        for record in vcf_reader:
            files[filename][record.POS] = record.REF, record.ALT

All these nice python tricks make the code more readable, shorter, uses less intermediate temporary variables. Also, using with open() ensures each file gets automatically closed after being read.

Also, as you can see, you can chose better variable names, and also reduce considerably the number of lines of code.


问:
Recursive call to a duplicated Bash script, making it unable to access the assets
Edit : This post is now addressed in a new, as the problem as to be presented slightly differently. It's here : How can I efficiently run XSLT transformations for a large number of files in parallel?

I'm stuck in my attempts of parallelizing a process, and after some decent time spent on it I'd like to request some help ...

Basically, I have a lots of XML files to transform with a specific XSLT sheet. But the sheet uses a call to an (very slow) API to fetch additional data, and taking the whole batch of XMLs in 1 go will take (very) long.

Therefore I splitted all the files from the original "input" folder into subfolder containing each around 5000 XML files, and I copied the following Bash script inside each subfolder too:

```<code>for f in *.xml
do
  java -jar ../../saxon9he.jar -xsl:../../some-xslt-sheet.xsl -s:$f
done
</code>```

And I call each process, for each folder, from the "root" folder containing altogether the "input" folder, the Saxon library and the XSLT sheet :

```<code>find input -type d -exec sh {}/script.sh \;
</code>```

But I get this error:

```<code>Unable to access jarfile ../../saxon9he.jar
</code>```

I suppose it comes form the fact that I'm operating from the "root" folder, when the scripts being called are lower in the directories. I could solver the problem (if I'm correct) by copying all the assets in each subfolder, but I found the solution making my current approach even clumsier.

Thanks to anyone who might have an idea and make me understand this !

答:
Try it this way to enter the directory for each argument and call the script therein:</p>

```<code>for d in */script.sh
do
  (
    cd "$(basename "$d")"
    sh ./script.sh
  )
done
</code>```

Body:
Edit : This post is now addressed in a new, as the problem as to be presented slightly differently. It's here : How can I efficiently run XSLT transformations for a large number of files in parallel?

I'm stuck in my attempts of parallelizing a process, and after some decent time spent on it I'd like to request some help ...

Basically, I have a lots of XML files to transform with a specific XSLT sheet. But the sheet uses a call to an (very slow) API to fetch additional data, and taking the whole batch of XMLs in 1 go will take (very) long.

Therefore I splitted all the files from the original "input" folder into subfolder containing each around 5000 XML files, and I copied the following Bash script inside each subfolder too:

for f in *.xml
do
  java -jar ../../saxon9he.jar -xsl:../../some-xslt-sheet.xsl -s:$f
done

And I call each process, for each folder, from the "root" folder containing altogether the "input" folder, the Saxon library and the XSLT sheet :

find input -type d -exec sh {}/script.sh \;

But I get this error:

Unable to access jarfile ../../saxon9he.jar

I suppose it comes form the fact that I'm operating from the "root" folder, when the scripts being called are lower in the directories. I could solver the problem (if I'm correct) by copying all the assets in each subfolder, but I found the solution making my current approach even clumsier.

Thanks to anyone who might have an idea and make me understand this !

Body:
Try it this way to enter the directory for each argument and call the script therein:

for d in */script.sh
do
  (
    cd "$(basename "$d")"
    sh ./script.sh
  )
done


问:
Migrating from non-partitioned to Partitioned tables
In June the BQ team announced support for date-partitioned tables. But the guide is missing how to migrate old non-partitioned tables into the new style.

I am looking for a way to update several or if not all tables to the new style.

Also outside of DAY type partitioned what other options are available? Does the BQ UI show this, as I wasn't able to create such a new partitioned table from the BQ Web UI.

答:
Until the new feature is rolled out in BigQuery, there is another (much cheaper) way to partition the table(s) by using Cloud Dataflow. We used this approach instead of running hundreds of SELECT * statements, which would have cost us thousands of dollars.

Create the partitioned table in BigQuery using the normal partition command

Create a Dataflow pipeline and use a BigQuery.IO.Read sink to read the table

Use a Partition transform to partition each row

Using a max of 200 shards/sinks at a time (any more than that and you hit API limits), create a BigQuery.IO.Write sink for each day/shard that will write to the corresponding partition using the partition decorator syntax - "$YYYYMMDD"

Repeat N times until all data is processed.

Here's an example on Github to get you started.

You still have to pay for the Dataflow pipeline(s), but it's a fraction of the cost of using multiple SELECT * in BigQuery.


问:
How to do InOrder traversal with B-Tree?
```<code>struct BTreeNode {
    bool is_leaf=true;
    std::vector<int> elements;
    std::vector<BTreeNode*> children;
    BTreeNode() {}
    BTreeNode (std::vector<int> v) {
    this->elements = v;
    }
};

void traverse(BTreeNode* root) {
  for(int i = 0; i < (int)root->children.size(); ++i){
    traverse(root->children[i]);
    cout << root->elements[i] << endl;
  }
  traverse(root->children[root->children.size() -1]);
}
</code>```

My method somehow segfaults. How do we write a correct inOrder Traversal for B-Tree?

答: It's probably the last traverse call when you are at a leaf.  I don't think that this traverse is needed.</p>

Body:
struct BTreeNode {
    bool is_leaf=true;
    std::vector<int> elements;
    std::vector<BTreeNode*> children;
    BTreeNode() {}
    BTreeNode (std::vector<int> v) {
    this->elements = v;
    }
};

void traverse(BTreeNode* root) {
  for(int i = 0; i < (int)root->children.size(); ++i){
    traverse(root->children[i]);
    cout << root->elements[i] << endl;
  }
  traverse(root->children[root->children.size() -1]);
}

My method somehow segfaults. How do we write a correct inOrder Traversal for B-Tree?


问:
Why does the compiler invoke a templated copy constructor when assigning?
Consider the code below:

```<code>#include <iostream>

template<class T>
struct X
{
    X() = default;

    template<class U>
    X(const X<U>&)
    {
        std::cout << __PRETTY_FUNCTION__ << std::endl;
    }

/*
    template<class U>
    X& operator=(const X<U>&)
    {
        std::cout << __PRETTY_FUNCTION__ << std::endl;
        return *this;
    }
*/

};

int main()
{
    X<int> a;
    X<double> b;

    b = a;
}
</code>```

Live on Coliru

As you can see, the assignment operator is commented out. However, the line

```<code>b = a;
</code>```

compiles fine. I thought it should not compile, as a and b have different types, and the operator=(const X&) that is generated by default by the compiler will be instantiated by the underlying type, so it won't assign an X<int> to an X<double>.

To my surprise, the code compiles, and it seems that the templated copy constructor is being invoked. Why is this? Is it because the compiler tries first to cast the a to a b then invoke the default-generated B::operator=?

答:
If T and U are different types, template<class U> X(const X&) is not a copy constructor because it's argument is of different type. In other words, X<int> and X<double> are unrelated types, so this constructor is just a user-defined conversion between them.

Note that this code won't print anything:

```<code>X<int> a;
X<int> b { a };
</code>```

Because in this case the implicitly-declared copy constructor of the form X<int>::X(const X<int>&) will be invoked.

Body:
Consider the code below:

#include <iostream>

template<class T>
struct X
{
    X() = default;

    template<class U>
    X(const X&)
    {
        std::cout << __PRETTY_FUNCTION__ << std::endl;
    }

/*
    template<class U>
    X& operator=(const X&)
    {
        std::cout << __PRETTY_FUNCTION__ << std::endl;
        return *this;
    }
*/

};

int main()
{
    X<int> a;
    X<double> b;

    b = a;
}

Live on Coliru

As you can see, the assignment operator is commented out. However, the line

b = a;

compiles fine. I thought it should not compile, as a and b have different types, and the operator=(const X&) that is generated by default by the compiler will be instantiated by the underlying type, so it won't assign an X<int> to an X<double>.

To my surprise, the code compiles, and it seems that the templated copy constructor is being invoked. Why is this? Is it because the compiler tries first to cast the a to a b then invoke the default-generated B::operator=?

Body:
If T and U are different types, template<class U> X(const X<U>&) is not a copy constructor because it's argument is of different type. In other words, X<int> and X<double> are unrelated types, so this constructor is just a user-defined conversion between them.

Note that this code won't print anything:

X<int> a;
X<int> b { a };

Because in this case the implicitly-declared copy constructor of the form X<int>::X(const X<int>&) will be invoked.


问:
How do I go about writing new controls in VB6?
I'm looking to create controls based on text boxes that validate numeric fields and restrict them to certain ranges without having to write all the callbacks for each control on the form.

Does anyone know of a tutorial on how to create and use such things?

Or alternatively, as I can't be the first person to have this requirement, are there a set of such controls available for use anywhere?

答: I think you can use the default text box, using the Validate event, or alternatively, if you need "live" checking then you could check in the KeyPressed, Change, etc events.</p>

ContentLicense: CC BY-SA 2.5


问:
Checkpoint VPN issue: Connectivity with VPN service is lost
I have installed SecuRemote Client of checkpoint E75.30 on my computer running Windows 8.

When I try to perform any of SecuRemote functions e.g. See client, Add client, See options etc. it gives the error "Connectivity with VPN service is lost"
I checked if the Check Point Endpoint Security VPN service would start automatically, but it did not.

When I try to start it manually I get "Error 1075: Dependency service does not exist or has been marked for deletion", however Dependency service is DHCP client which is running fine.

答: I solved this issue by Right click >>> repair on the file : CheckPointVPN.msi .</p>

ContentLicense: CC BY-SA 4.0


问:
java.lang.UnsatisfiedLinkError: no rxtxSerial in java.library.path thrown while loading gnu.io.RXTXCommDriver
Fedora using right now (package is installed Package rxtx-2.2-0.5.20100211.fc15.i686 already installed and latest version
).

I have used/tried:

```<code># locate librxtxSerial
/home/sun/Downloads/rxtx-2.1-7-bins-r2/Linux/i686-unknown-linux-gnu/librxtxSerial.so
/home/sun/Downloads/rxtx-2.1-7-bins-r2/Linux/ia64-unkown-linux-gnu/librxtxSerial.so
/home/sun/Downloads/rxtx-2.1-7-bins-r2/Linux/x86_64-unknown-linux-gnu/librxtxSerial.so
/home/sun/Downloads/rxtx-2.1-7-bins-r2/Mac_OS_X/librxtxSerial.jnilib
/home/sun/Downloads/rxtx-2.1-7-bins-r2/Solaris/sparc-solaris/sparc32-sun-solaris2.8/librxtxSerial-2.1-7.so
/home/sun/Downloads/rxtx-2.1-7-bins-r2/Solaris/sparc-solaris/sparc32-sun-solaris2.8/librxtxSerial.so
/home/sun/Downloads/rxtx-2.1-7-bins-r2/Solaris/sparc-solaris/sparc64-sun-solaris2.8/librxtxSerial-2.1-7.so
/home/sun/Downloads/rxtx-2.1-7-bins-r2/Solaris/sparc-solaris/sparc64-sun-solaris2.8/librxtxSerial.so
/usr/lib/rxtx/librxtxSerial-2.2pre1.so
/usr/lib/rxtx/librxtxSerial.so
</code>```

Then used:

```<code>-Djava.library.path=/usr/lib/rxtx/librxtxSerial.so -Djava.library.path=/usr/lib/jni
</code>```

But still i get always this following:

```<code>java.lang.UnsatisfiedLinkError: no rxtxSerial in java.library.path thrown while loading gnu.io.RXTXCommDriver
Exception in thread "main" java.lang.UnsatisfiedLinkError: no rxtxSerial in java.library.path
    at java.lang.ClassLoader.loadLibrary(ClassLoader.java:1681)
    at java.lang.Runtime.loadLibrary0(Runtime.java:840)
    at java.lang.System.loadLibrary(System.java:1047)
    at gnu.io.CommPortIdentifier.<clinit>(CommPortIdentifier.java:83)
    at main.Tty.sendCommand1(Tty.java:212)
    at main.Tty.main(Tty.java:236)
</code>```

How to resolve this ?

Follow up:

WRONG:

-Djava.library.path=/usr/lib/rxtx -Djava.library.path=/usr/lib/jni

CORRECT

-Djava.library.path=/usr/lib/jni -Djava.library.path=/usr/lib/rxtx

答:
```<code>Copy RXTXcomm.jar ---> <JAVA_HOME>\jre\lib\ext
</code>```

Copy rxtxSerial.dll ---> <JAVA_HOME>\jre\bin

Copy rxtxParallel.dll ---> <JAVA_HOME>\jre\bin

Body:
Fedora using right now (package is installed Package rxtx-2.2-0.5.20100211.fc15.i686 already installed and latest version
).

I have used/tried:

# locate librxtxSerial
/home/sun/Downloads/rxtx-2.1-7-bins-r2/Linux/i686-unknown-linux-gnu/librxtxSerial.so
/home/sun/Downloads/rxtx-2.1-7-bins-r2/Linux/ia64-unkown-linux-gnu/librxtxSerial.so
/home/sun/Downloads/rxtx-2.1-7-bins-r2/Linux/x86_64-unknown-linux-gnu/librxtxSerial.so
/home/sun/Downloads/rxtx-2.1-7-bins-r2/Mac_OS_X/librxtxSerial.jnilib
/home/sun/Downloads/rxtx-2.1-7-bins-r2/Solaris/sparc-solaris/sparc32-sun-solaris2.8/librxtxSerial-2.1-7.so
/home/sun/Downloads/rxtx-2.1-7-bins-r2/Solaris/sparc-solaris/sparc32-sun-solaris2.8/librxtxSerial.so
/home/sun/Downloads/rxtx-2.1-7-bins-r2/Solaris/sparc-solaris/sparc64-sun-solaris2.8/librxtxSerial-2.1-7.so
/home/sun/Downloads/rxtx-2.1-7-bins-r2/Solaris/sparc-solaris/sparc64-sun-solaris2.8/librxtxSerial.so
/usr/lib/rxtx/librxtxSerial-2.2pre1.so
/usr/lib/rxtx/librxtxSerial.so

Then used:

-Djava.library.path=/usr/lib/rxtx/librxtxSerial.so -Djava.library.path=/usr/lib/jni

But still i get always this following:

java.lang.UnsatisfiedLinkError: no rxtxSerial in java.library.path thrown while loading gnu.io.RXTXCommDriver
Exception in thread "main" java.lang.UnsatisfiedLinkError: no rxtxSerial in java.library.path
    at java.lang.ClassLoader.loadLibrary(ClassLoader.java:1681)
    at java.lang.Runtime.loadLibrary0(Runtime.java:840)
    at java.lang.System.loadLibrary(System.java:1047)
    at gnu.io.CommPortIdentifier.<clinit>(CommPortIdentifier.java:83)
    at main.Tty.sendCommand1(Tty.java:212)
    at main.Tty.main(Tty.java:236)

How to resolve this ?

Follow up:

WRONG:

-Djava.library.path=/usr/lib/rxtx -Djava.library.path=/usr/lib/jni

CORRECT

-Djava.library.path=/usr/lib/jni -Djava.library.path=/usr/lib/rxtx

Body:
Copy RXTXcomm.jar ---> <JAVA_HOME>\jre\lib\ext

Copy rxtxSerial.dll ---> <JAVA_HOME>\jre\bin

Copy rxtxParallel.dll ---> <JAVA_HOME>\jre\bin


问:
Declaring array in Header file
I am trying to optimize a life game.
I need to change this code from the header file:

```<code>  #define MASK(col) (0x80 >> ((col) & 7))
</code>```

(The variable "col" is a variable that will save the column, it goes from 0 to 8)

To something like this:

```<code>int array[9] = { 0, 64, 32, 16, 8, 4, 2, 1};
  #define MASK(col) (array[col])

(((0) & 7) = 0, ((1) & 7) = 64, ((2) & 7) = 32, ((3) & 16)...)
</code>```

The error I am getting with this code is the following:

```<code>"#10010 errors encountered during linking "life.out" not built"
"#10056 "array" redefined: first defined in './lifelib.obj', redefined in
'./life.obj'"
</code>```

(Ps.: I've changed the name of the array to something like: "OKDPSAdiahodakDSA" and I still got the same error)

PS: This error only happens when I make this change. The entire code is working fine.

答:
I think you have defined the array in the header file and you have included it (directly or indirectly) in two C files:

life.c

lifelib.c

When the compiler generate the obj files, it sees a definition of array in each file, so it includes it in both obj files. Then, when the linker tries to generate the file it finds two duplicated arrays, one for each obj.

You should declare the variable extern in the header and define it only in one c file. You can find more information here.

Title: Declaring array in Header file

Body:
I am trying to optimize a life game.
I need to change this code from the header file:

  #define MASK(col) (0x80 >> ((col) & 7))

(The variable "col" is a variable that will save the column, it goes from 0 to 8)

To something like this:

int array[9] = { 0, 64, 32, 16, 8, 4, 2, 1};
  #define MASK(col) (array[col])

(((0) & 7) = 0, ((1) & 7) = 64, ((2) & 7) = 32, ((3) & 16)...)

The error I am getting with this code is the following:

"#10010 errors encountered during linking "life.out" not built"
"#10056 "array" redefined: first defined in './lifelib.obj', redefined in
'./life.obj'"

(Ps.: I've changed the name of the array to something like: "OKDPSAdiahodakDSA" and I still got the same error)

PS: This error only happens when I make this change. The entire code is working fine.


问:
Child directive not updated when parent directive property changes
This is follow up to these 2 questions:

Pass argument between parent and child directives

Parent directive controller undefined when passing to child directive

I have this part working; however, when the value for ng-disabled for parent directive changes, the child directive values don't get updated.

Please see thin plunkr example.

HTML:

```<code><div ng-app="myApp">
  <div ng-controller="MyController">
    {{menuStatus}}
    <tmp-menu ng-disabled="menuStatus">
      <tmp-menu-link></tmp-menu-link>
      <tmp-menu-link></tmp-menu-link>
    </tmp-menu>
    <button ng-click="updateStatus()">Update</button>
  </div>
</div>
</code>```

JavaScript(AngularJS):

```<code>angular.module('myApp', [])
.controller('MyDirectiveController', MyDirectiveController)
.controller('MyController', function($scope){
  $scope.menuStatus = false;
  $scope.updateStatus = function(){
    $scope.menuStatus = $scope.menuStatus?false:true;
  }
})
.directive('tmpMenu', function() {
  return {
    restrict: 'AE',
    replace:true,
    transclude:true,
    scope:{
      disabled: '=?ngDisabled'
    },
    controller: 'MyDirectiveController',
    template: '<div>myDirective Disabled: {{ disabled }}<ng-transclude></ng-transclude></div>',
    link: function(scope, element, attrs) {

    }
  };
})
.directive('tmpMenuLink', function() {
  return {
    restrict: 'AE',
    replace:true,
    transclude:true,
    scope:{
    },
    require:'^^tmpMenu',
    template: '<div>childDirective disabled: {{ disabled }}</div>',
    link: function(scope, element, attrs, MyDirectiveCtrl) {
      console.log(MyDirectiveCtrl);

      scope.disabled = MyDirectiveCtrl.isDisabled();

    }
  };
})

function MyDirectiveController($scope) {
  this.isDisabled = function() {
    return $scope.disabled;
  };
}
</code>```

How can I detect change in parent directive and pass it to child directive without adding angular watcher.

答:
Solution 1

i've set up a working plnkr here: https://plnkr.co/edit/fsxMJPAc05imhBqefaRk?p=preview

the reason of this behaviour is that tmpMenuLink kept a copy of the value returned from MyDirectiveCtrl.isDisabled(). no watcher is set up , so the only way to resolve this is to manually watch for any changes and then update the field.

```<code>scope.$watch(function(){
  return MyDirectiveCtrl.isDisabled();
}, function(){
   scope.disabled = MyDirectiveCtrl.isDisabled();
})
</code>```

Solution 2

An alternative without watchers is to pass the reference of an object instead of a primitive type, something like:

```<code>$scope.menuStatus = {status: false};
</code>```

new plnkr here: https://plnkr.co/edit/RGEK6TUuE7gkPDS6ygZe?p=preview

Body:
This is follow up to these 2 questions:

Pass argument between parent and child directives

Parent directive controller undefined when passing to child directive

I have this part working; however, when the value for ng-disabled for parent directive changes, the child directive values don't get updated.

Please see thin plunkr example.

HTML:

    {{menuStatus}}
    <tmp-menu ng-disabled="menuStatus">
      <tmp-menu-link></tmp-menu-link>
      <tmp-menu-link></tmp-menu-link>
    </tmp-menu>
    <button ng-click="updateStatus()">Update</button>

JavaScript(AngularJS):

angular.module('myApp', [])
.controller('MyDirectiveController', MyDirectiveController)
.controller('MyController', function($scope){
  $scope.menuStatus = false;
  $scope.updateStatus = function(){
    $scope.menuStatus = $scope.menuStatus?false:true;
  }
})
.directive('tmpMenu', function() {
  return {
    restrict: 'AE',
    replace:true,
    transclude:true,
    scope:{
      disabled: '=?ngDisabled'
    },
    controller: 'MyDirectiveController',
    template: '
myDirective Disabled: {{ disabled }}<ng-transclude></ng-transclude>
',
    link: function(scope, element, attrs) {

    }
  };
})
.directive('tmpMenuLink', function() {
  return {
    restrict: 'AE',
    replace:true,
    transclude:true,
    scope:{
    },
    require:'^^tmpMenu',
    template: '
childDirective disabled: {{ disabled }}
',
    link: function(scope, element, attrs, MyDirectiveCtrl) {
      console.log(MyDirectiveCtrl);

      scope.disabled = MyDirectiveCtrl.isDisabled();

    }
  };
})

function MyDirectiveController($scope) {
  this.isDisabled = function() {
    return $scope.disabled;
  };
}

How can I detect change in parent directive and pass it to child directive without adding angular watcher.

Body:
Solution 1

i've set up a working plnkr here: https://plnkr.co/edit/fsxMJPAc05imhBqefaRk?p=preview

the reason of this behaviour is that tmpMenuLink kept a copy of the value returned from MyDirectiveCtrl.isDisabled(). no watcher is set up , so the only way to resolve this is to manually watch for any changes and then update the field.

scope.$watch(function(){
  return MyDirectiveCtrl.isDisabled();
}, function(){
   scope.disabled = MyDirectiveCtrl.isDisabled();
})

Solution 2

An alternative without watchers is to pass the reference of an object instead of a primitive type, something like:

$scope.menuStatus = {status: false};

new plnkr here: https://plnkr.co/edit/RGEK6TUuE7gkPDS6ygZe?p=preview


问:
getElementbyId is not a function
I have a simple piece of JavaScript that changes the color of a button, but I keep getting he error that getting the button is not a function, even though the same function (with the same capitalisation and case) works just a couple of lines above.</p>

```<code>if (this.ButtonColor != "") {
      var button = document.getElementbyId('modal-close');
      button.style.backgroundColor = this.ButtonColor;
 }
</code>```

答:
Instead of using this.ButtonColor did you try</p>

```<code>var button = document.getElementById("modal-close");
button.style.backgroundColor = "the color you want rather than using "
</code>```

Title: getElementbyId is not a function

Body:
I have a simple piece of JavaScript that changes the color of a button, but I keep getting he error that getting the button is not a function, even though the same function (with the same capitalisation and case) works just a couple of lines above.

if (this.ButtonColor != "") {
      var button = document.getElementbyId('modal-close');
      button.style.backgroundColor = this.ButtonColor;
 }

Body:
Instead of using this.ButtonColor did you try

var button = document.getElementById("modal-close");
button.style.backgroundColor = "the color you want rather than using "


问:
MS Teams - Can I make a custom tab only available to my organization
I want to generate a bunch of custom tabs that are grouped together in several separate packages (manifest.json) files, but these custom tabs should only be available to people inside my organization.  From what I have read it doesn't appear that this is really possible.

It looks like the only 2 solutions that exist for this is to either side-load the files into each Team, which is not something that I want to have users doing.  Or publish it, so everybody in the world would see it, but then use authentication in the configuration tab to prevent anybody outside of my company from being able to save and add the tab.

I wanted to get confirmation that what I'm reading is correct and there is no way to limit who sees my different packages.

答: We don't have any way currently of administering tabs across multiple teams, short of adding or side-loading as you mention.  We should have a better story in the next few months.</p>


问:
board game win situation - searching algorithm
I'm looking for possibly efficient algorithm to detect "win" situation in a gomoku (five-in-a-row) game, played on a 19x19 board. Win situation happens when one of the players manages to get five and NO MORE than five "stones" in a row (horizontal, diagonal or vertical).

I have the following data easily accessible:

previous moves ("stones") of both players stored in a 2d array (can be also json notation object), with variables "B" and "W" to difference players from each other,

"coordinates" of the incoming move (move.x, move.y),

number of moves each player did

I'm doing it in javascript, but any solution that doesn't use low-level stuff like memory allocation nor higher-level (python) array operations would be good.

I've found similiar question ( Detect winning game in nought and crosses ), but solutions given there only refer to small boards (5x5 etc).

答:
untested:

```<code>int left = max(0, move.x-5), right = min(width-1, move.x+5), top = max(0, move.y-5), bottom = min(width-1, move.y+5);
// check the primary diagonal (top-left to bottom-right)
for (int x = left, y = top; x <= right && y <= bottom; x++, y++) {
    for (int count = 0; x <= right && y <= bottom && stones[x][y] == lastPlayer; x++, y++, count++) {
        if (count >= 5) return true;
    }
}
// check the secondary diagonal (top-right to bottom-left)
// ...
// check the horizontal
// ...
// check the vertical
// ...
return false;
</code>```

alternatively, if you don't like the nested loops (untested):

```<code>// check the primary diagonal (top-left to bottom-right)
int count = 0, maxCount = 0;
for (int x = left, y = top; x <= right && y <= bottom; x++, y++) {
    if (count < 5) {
        count = stones[x][y] == lastPlayer ? count + 1 : 0;
    } else {
        return true;
    }
}
</code>```

Body:
untested:

int left = max(0, move.x-5), right = min(width-1, move.x+5), top = max(0, move.y-5), bottom = min(width-1, move.y+5);
// check the primary diagonal (top-left to bottom-right)
for (int x = left, y = top; x <= right && y <= bottom; x++, y++) {
    for (int count = 0; x <= right && y <= bottom && stones[x][y] == lastPlayer; x++, y++, count++) {
        if (count >= 5) return true;
    }
}
// check the secondary diagonal (top-right to bottom-left)
// ...
// check the horizontal
// ...
// check the vertical
// ...
return false;

alternatively, if you don't like the nested loops (untested):

// check the primary diagonal (top-left to bottom-right)
int count = 0, maxCount = 0;
for (int x = left, y = top; x <= right && y <= bottom; x++, y++) {
    if (count < 5) {
        count = stones[x][y] == lastPlayer ? count + 1 : 0;
    } else {
        return true;
    }
}


问:
Self Join table to identify new records by date
I have a table that updates daily with new invoice lines by date. However, each new day will contain ALL of the invoices from the previous days. 1-1-2017 will contain all invoices as of 1-1-2017, but 1-2-2017 will contain all new invoices as well as the invoices from 1-1-2017. Here is an example below.

I want to be able to show just the new records that appear on 3/23/2017. I attempted with this code:

```<code>    SELECT
    a.[Date]
    ,b.[Date]
    ,a.[Inv Name]
    ,b.[Inv Name]
    ,a.[amt]
FROM
    [Invoice Table] a LEFT JOIN
    [Invoice Table] b ON a.[Inv Name]=b.[Inv Name]
WHERE
    --a.[customer_industry]<>b.[customer_industry] AND
    a.[Date] = '3/23/2017' AND
    b.[Date] = '3/22/2017' AND
    b.[Date] = IS NULL
</code>```

When I run this, I get zero results. Any help is much appreciated!

答:
```<code>    SELECT
    a.[Date]
    ,b.[Date]
    ,a.[Inv Name]
    ,b.[Inv Name]
    ,a.[amt]
FROM
    [Invoice Table] a LEFT JOIN
    [Invoice Table] b ON a.[Inv Name]=b.[Inv Name]
where b.[Inv Name] Is null
</code>```

Body:
I have a table that updates daily with new invoice lines by date. However, each new day will contain ALL of the invoices from the previous days. 1-1-2017 will contain all invoices as of 1-1-2017, but 1-2-2017 will contain all new invoices as well as the invoices from 1-1-2017. Here is an example below.

I want to be able to show just the new records that appear on 3/23/2017. I attempted with this code:

    SELECT
    a.[Date]
    ,b.[Date]
    ,a.[Inv Name]
    ,b.[Inv Name]
    ,a.[amt]
FROM
    [Invoice Table] a LEFT JOIN
    [Invoice Table] b ON a.[Inv Name]=b.[Inv Name]
WHERE
    --a.[customer_industry]<>b.[customer_industry] AND
    a.[Date] = '3/23/2017' AND
    b.[Date] = '3/22/2017' AND
    b.[Date] = IS NULL

When I run this, I get zero results. Any help is much appreciated!


问:
target_include_directories resulting include path
Say I have a project that looks like:

```<code> Project (dir)
   -- CMakeLists.txt
   -- MyLib (dir)
     |-- CMakeLists.txt
     |-- MyLib.h
     |-- MyLib.cpp

   -- MyOtherLib (dir)
     |-- CMakeLists.txt
     |-- MyLib.h (note that this is exactly the same name as in MyLib above)
     |-- MyLib.cpp
</code>```

If in MyLib/CMakeLists.txt I do this:

```<code>target_include_directories(MyLib PUBLIC
  $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}>
</code>```

Then anything that target_link_libraries to MyLib will have the "correct" include path to do #include "MyLib.h". However, if another executable MyExecutable depends on both libraries using target_link_libraries(MyExecutable MyLib MyOtherLib) you'd like to be able to instead specify which one is intended with #include "MyLib/MyLib.h" or #include "MyOtherLib/MyLib.h". The only way I see to do that is to instead use:

```<code>target_include_directories(MyLib PUBLIC
  $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/..>
</code>```

which kind of defeats one of the nice things about target_include_directories in that it really strongly enforces avoiding accidental header dependencies, because you literally can't include things that you aren't explicitly claiming to use.

Is there another way to get this #include "MyLib/MyLib.h" behavior?

答:
You should reconsider your directory tree as follows:

```<code>Project (dir)
   -- CMakeLists.txt
   -- MyLib (dir)
     |-- CMakeLists.txt
     |-- src (dir)
         MyLib.cpp
     |-- include/MyLib (two dirs)
         MyLib.h

   -- MyOtherLib (dir)
     |-- CMakeLists.txt
     |-- src (dir)
         MyLib.cpp
     |-- include/MyOtherLib (two dirs)
         MyLib.h
</code>```

In this way you avoid including the ../, i.e. Project, folder and everything therein, which is not a clean approach and may lead to other problem should you add other files/folders in the future.
Then, you can write in MyLib/CMakeLists.txt

```<code>target_include_directories(MyLib PUBLIC
    $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}>/include)
</code>```

and in MyOtherLib/CMakeLists.txt

```<code>target_include_directories(MyOtherLib PUBLIC
    $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}>/include)
</code>```

As a result, you will be able to write #include "MyLib/MyLib.h" and #include "MyOtherLib/MyLib.h" in any program linking against the libraries in the build-tree.

If you also want to differentiate the include directories between the build-tree and the install-tree have a look at target_include_directories documentation and the useful cmake-generator-expressions.

Body:
Say I have a project that looks like:

 Project (dir)
   -- CMakeLists.txt
   -- MyLib (dir)
     |-- CMakeLists.txt
     |-- MyLib.h
     |-- MyLib.cpp

   -- MyOtherLib (dir)
     |-- CMakeLists.txt
     |-- MyLib.h (note that this is exactly the same name as in MyLib above)
     |-- MyLib.cpp

If in MyLib/CMakeLists.txt I do this:

target_include_directories(MyLib PUBLIC
  $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}>

Then anything that target_link_libraries to MyLib will have the "correct" include path to do #include "MyLib.h". However, if another executable MyExecutable depends on both libraries using target_link_libraries(MyExecutable MyLib MyOtherLib) you'd like to be able to instead specify which one is intended with #include "MyLib/MyLib.h" or #include "MyOtherLib/MyLib.h". The only way I see to do that is to instead use:

target_include_directories(MyLib PUBLIC
  $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/..>

which kind of defeats one of the nice things about target_include_directories in that it really strongly enforces avoiding accidental header dependencies, because you literally can't include things that you aren't explicitly claiming to use.

Is there another way to get this #include "MyLib/MyLib.h" behavior?

Body:
You should reconsider your directory tree as follows:

Project (dir)
   -- CMakeLists.txt
   -- MyLib (dir)
     |-- CMakeLists.txt
     |-- src (dir)
         MyLib.cpp
     |-- include/MyLib (two dirs)
         MyLib.h

   -- MyOtherLib (dir)
     |-- CMakeLists.txt
     |-- src (dir)
         MyLib.cpp
     |-- include/MyOtherLib (two dirs)
         MyLib.h

In this way you avoid including the ../, i.e. Project, folder and everything therein, which is not a clean approach and may lead to other problem should you add other files/folders in the future.
Then, you can write in MyLib/CMakeLists.txt

target_include_directories(MyLib PUBLIC
    $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}>/include)

and in MyOtherLib/CMakeLists.txt

target_include_directories(MyOtherLib PUBLIC
    $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}>/include)

As a result, you will be able to write #include "MyLib/MyLib.h" and #include "MyOtherLib/MyLib.h" in any program linking against the libraries in the build-tree.

If you also want to differentiate the include directories between the build-tree and the install-tree have a look at target_include_directories documentation and the useful cmake-generator-expressions.


问:
Javascript month difference
How do I calculate difference in months in Javascript?

Please note there are similar questions such as:
What's the best way to calculate date difference in Javascript

But these are based around MS difference, when some months have different number of days than others!

Any easy way to calculate month difference between 2 dates?

Just to be clear, I need to know how many months the dates span, for example:

```<code>Jan 29th 2010, and Feb 1st 2010 = 2 months
Jan 1st 2010, and Jan 2nd 2010 = 1 month
Feb 14th 2010, Feb 1st 2011 = 13 months
Feb 1st 2010, March 30th 2011 = 14 months
</code>```

答:
[edit] Based on comment, I stand corrected. Using the accepted answer I'd use somethng like:

```<code>var  datefrom = new Date('2001/03/15')
    ,dateto = new Date('2011/07/21')
    ,nocando = datefrom<dateto ? null : 'datefrom > dateto!'
    ,diffM = nocando ||
             dateto.getMonth() - datefrom.getMonth()
              + (12 * (dateto.getFullYear() - datefrom.getFullYear()))
    ,diffY = nocando || Math.floor(diffM/12)
    ,diffD = dateto.getDate()-datefrom.getDate()
    ,diffYM = nocando ||
               (diffY>0 ? ' Year(s) ' : '')
               + diffM%12+' Month(s) '+(diffD>0? (diffD+' day(s)') : '') ;

 console.log(diffYM); //=> 10 Year(s) 4 Month(s) 6 day(s)
</code>```

Title: Javascript month difference

Body:
How do I calculate difference in months in Javascript?

Please note there are similar questions such as:
What's the best way to calculate date difference in Javascript

But these are based around MS difference, when some months have different number of days than others!

Any easy way to calculate month difference between 2 dates?

Just to be clear, I need to know how many months the dates span, for example:

Jan 29th 2010, and Feb 1st 2010 = 2 months
Jan 1st 2010, and Jan 2nd 2010 = 1 month
Feb 14th 2010, Feb 1st 2011 = 13 months
Feb 1st 2010, March 30th 2011 = 14 months

Body:
[edit] Based on comment, I stand corrected. Using the accepted answer I'd use somethng like:

var  datefrom = new Date('2001/03/15')
    ,dateto = new Date('2011/07/21')
    ,nocando = datefrom<dateto ? null : 'datefrom > dateto!'
    ,diffM = nocando ||
             dateto.getMonth() - datefrom.getMonth()
              + (12 * (dateto.getFullYear() - datefrom.getFullYear()))
    ,diffY = nocando || Math.floor(diffM/12)
    ,diffD = dateto.getDate()-datefrom.getDate()
    ,diffYM = nocando ||
               (diffY>0 ? ' Year(s) ' : '')
               + diffM%12+' Month(s) '+(diffD>0? (diffD+' day(s)') : '') ;

 console.log(diffYM); //=> 10 Year(s) 4 Month(s) 6 day(s)


答:
First, represent dates using ISO standard formats.  Second, when using LEFT JOIN, conditions on all but the first table go in the ON clause.  Otherwise, the NULL values in non-matching rows get filtered out.  Also, = IS NULL is not valid syntax.

I think you intend:

```<code>SELECT a.[Date], b.[Date], a.[Inv Name], b.[Inv Name], a.[amt]
FROM  [Invoice Table] a LEFT JOIN
      [Invoice Table] b
      ON a.[Inv Name] = b.[Inv Name] AND b.[Date] = '2017-03-22'
WHERE  --a.[customer_industry]<>b.[customer_industry] AND
      a.[Date] = '2017-03-23' AND
      b.[Date] IS NULL;
</code>```

However, I think this is much more simply written using LAG():

```<code>select t.*
from (select t.*, lag(date) over (partition by [Inv Name] order by date) as prev_date
      from [Invoice Table] t
     ) t
where date = '2017-03-23' and (prev_date is null or prev_date <> '2017-03-22')
</code>```

Title: Self Join table to identify new records by date

Body:
First, represent dates using ISO standard formats.  Second, when using LEFT JOIN, conditions on all but the first table go in the ON clause.  Otherwise, the NULL values in non-matching rows get filtered out.  Also, = IS NULL is not valid syntax.

I think you intend:

SELECT a.[Date], b.[Date], a.[Inv Name], b.[Inv Name], a.[amt]
FROM  [Invoice Table] a LEFT JOIN
      [Invoice Table] b
      ON a.[Inv Name] = b.[Inv Name] AND b.[Date] = '2017-03-22'
WHERE  --a.[customer_industry]<>b.[customer_industry] AND
      a.[Date] = '2017-03-23' AND
      b.[Date] IS NULL;

However, I think this is much more simply written using LAG():

select t.*
from (select t.*, lag(date) over (partition by [Inv Name] order by date) as prev_date
      from [Invoice Table] t
     ) t
where date = '2017-03-23' and (prev_date is null or prev_date <> '2017-03-22')


问:
custom directive dom is not updated on parent scope change
When I update parent scope variable from custom directive by calling a function from directive then directive dom is not updated.
In this example $scope.ascending is true, and sort() function do toggle its value. I am calling sort function from both parent view as well as from child(directive), but change is not reflected in directive template. run this code as is to see the issue

HTML

```<code><html ng-app="sortApp">
    <head>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular.min.js"></script>
        <script src="testApp.js"></script>
    </head>
    <body>
        <div ng-view>
            <div ng-controller="sortController">
                <span>Parent scope: sorting order: </span>"{{ascending ? 'a->z' : 'z->a'}}"
                <br /><br />
                <div><input type='button' value='toggal sort order from parent' ng-click='sort()' /></div><br/>
                <sorting-from-directive asc="ascending" sort-action="sort()"> </sorting-from-directive>
            </div>
        </div>
    </body>
</html>
</code>```

CODE

```<code>var app = angular.module('sortApp', []);

app.controller('sortController', function ($scope) {

    $scope.ascending = true;

    $scope.sort = function () {

        $scope.ascending = !$scope.ascending;
    }

});

app.directive('sortingFromDirective', function () {

    return {
        restrict: 'EA',
        scope: {
            asc: '=',
            sortAction: '&'
        },
        template: "<div><input type='button' value='toggal sort order from directive' ng-click='sortAction()'/> <span>Child scope: sorting order:</span><span ng-show={{asc}}>a->z</span> <span ng-hide={{asc}}>z->a</span></div>"
    };
});
</code>```

答:
You shouldn't be using {{}}(interpolation) inside ng-show/ng-hide

```<code><span ng-show='asc'>a->z</span>
<span ng-hide='asc'>z->a</span>
</code>```

Body:
When I update parent scope variable from custom directive by calling a function from directive then directive dom is not updated.
In this example $scope.ascending is true, and sort() function do toggle its value. I am calling sort function from both parent view as well as from child(directive), but change is not reflected in directive template. run this code as is to see the issue

HTML

                Parent scope: sorting order: "{{ascending ? 'a->z' : 'z->a'}}"

<input type='button' value='toggal sort order from parent' ng-click='sort()' />

                <sorting-from-directive asc="ascending" sort-action="sort()"> </sorting-from-directive>

CODE

var app = angular.module('sortApp', []);

app.controller('sortController', function ($scope) {

    $scope.ascending = true;

    $scope.sort = function () {

        $scope.ascending = !$scope.ascending;
    }

});

app.directive('sortingFromDirective', function () {

    return {
        restrict: 'EA',
        scope: {
            asc: '=',
            sortAction: '&'
        },
        template: "
<input type='button' value='toggal sort order from directive' ng-click='sortAction()'/> Child scope: sorting order:a->z z->a
"
    };
});

Body:
You shouldn't be using {{}}(interpolation) inside ng-show/ng-hide

<span ng-show='asc'>a->z</span>
<span ng-hide='asc'>z->a</span>


问:
Passing constant parameter to simulink s-function (mdlderivatives)
I have build a model in MATLAB and i am using SIMULINK to solve the differential equation.

```<code>function sys=mdlDerivatives(t,x,u)
% Constant block
n    = 10; % fixed switch exponent
k1   = u(2);% input rate constant (1/min)
k2   = u(3);% output rate constant (1/min)
Td   = 70; % time delay (min)
Alfa = 0.7;% ug per 100 ml
Beta = 1;% ug per 100 ml
f    = 250; % phase (min)

a=Alfa*cos((t-f)*2*pi()/1440) + Beta;
Sigmoid = a^n*u(4)/(a^n + u(4)^n);
dxdt(1) = k1*Sigmoid -k2*x(1);
sys = [dxdt];
</code>```

I want to send the value of Alfa from the base workspace.

```<code>tspan=[0:0.05:1400]';
x0=1.7;
PARAMETERS=simset('InitialState',x0,'Solver','ode15s','MaxStep',0.05,'OutputPoints','specified','RelTol',1E-6);
[tdata,y]=sim('cortisol_model_2',tspan,PARAMETERS);
</code>```

I tried using From Workspace in the simulink block but I am only able to insert a vector from that. So is there a better way to pass a constant parameter to the mdlfunction. I actually want to pass different values of alpha to check the sensitivity.

答:
You should be writing any new code using level-2 m-code S-functions.  Level-1 functionality only exists for backwards compatibility.

Nonetheless, to pass parameters into a level-1 S-function you do the following:

Within the Primary/main/first function

```<code>function [sys,x0,str,ts,simStateCompliance] = sfuntmpl(t,x,u,flag,p1,p2,p3)
...
switch flag,
...
  case 1,
    sys=mdlDerivatives(t,x,u,p1,p2,p3);

...
</code>```

And with mdlDerivatives

```<code>function sys=mdlDerivatives(t,x,u,p1,p2,p3)
...
% use p1, p2 and/or p3 here
...
</code>```

Body:
I have build a model in MATLAB and i am using SIMULINK to solve the differential equation.

function sys=mdlDerivatives(t,x,u)
% Constant block
n    = 10; % fixed switch exponent
k1   = u(2);% input rate constant (1/min)
k2   = u(3);% output rate constant (1/min)
Td   = 70; % time delay (min)
Alfa = 0.7;% ug per 100 ml
Beta = 1;% ug per 100 ml
f    = 250; % phase (min)

a=Alfa*cos((t-f)*2*pi()/1440) + Beta;
Sigmoid = a^n*u(4)/(a^n + u(4)^n);
dxdt(1) = k1*Sigmoid -k2*x(1);
sys = [dxdt];

I want to send the value of Alfa from the base workspace.

tspan=[0:0.05:1400]';
x0=1.7;
PARAMETERS=simset('InitialState',x0,'Solver','ode15s','MaxStep',0.05,'OutputPoints','specified','RelTol',1E-6);
[tdata,y]=sim('cortisol_model_2',tspan,PARAMETERS);

I tried using From Workspace in the simulink block but I am only able to insert a vector from that. So is there a better way to pass a constant parameter to the mdlfunction. I actually want to pass different values of alpha to check the sensitivity.

Body:
You should be writing any new code using level-2 m-code S-functions.  Level-1 functionality only exists for backwards compatibility.

Nonetheless, to pass parameters into a level-1 S-function you do the following:

Within the Primary/main/first function

function [sys,x0,str,ts,simStateCompliance] = sfuntmpl(t,x,u,flag,p1,p2,p3)
...
switch flag,
...
  case 1,
    sys=mdlDerivatives(t,x,u,p1,p2,p3);

...

And with mdlDerivatives

function sys=mdlDerivatives(t,x,u,p1,p2,p3)
...
% use p1, p2 and/or p3 here
...


问:
How to run Karma/Jasmine unit tests with JWPlayer
I am testing a method, which sets up JWPlayer using the following method

```<code>jwplayer(playerTag).setup({ [...]
</code>```

When running Karma I get an error about jwplayer being undefined.

答:
Hello maybe it's too late, but have you tried to set window.jwplayer as a mock function? </p>

```<code>window.jwplayer = function() {
        return {
            setup: jasmine.createSpy('jwplayer.setup')
        };
    };
</code>```

Body:
I am testing a method, which sets up JWPlayer using the following method

jwplayer(playerTag).setup({ [...]

When running Karma I get an error about jwplayer being undefined.

Body:
Hello maybe it's too late, but have you tried to set window.jwplayer as a mock function?

window.jwplayer = function() {
        return {
            setup: jasmine.createSpy('jwplayer.setup')
        };
    };


问:
Error creating Node.js Express App. Cannot find

Im trying to create a node.js project in WebStorm
Can you tell what am I missing here?

答:
Have you tried installing required dependencies globally?
It's usually done like this:

```<code>npm install [dependency_name] -g
</code>```

In your case it might be that express-generator is either not installed globally or not available in PATH.

Body:
Have you tried installing required dependencies globally?
It's usually done like this:

npm install [dependency_name] -g

In your case it might be that express-generator is either not installed globally or not available in PATH.


问:
Application that checks a website periodically
I want to make an application for personal use that checks a few items on a website every day(or every time someone runs the application) and tells me if the price has changed. What I mean is that, it should take the price tag from the source code of the website and save it then compare it to the earlier price tag. Doing this every day manually takes too much time honestly and I also want to improve my programming skills.

What should I learn and how should I go about making this application as simple as possible? You don't have to tell me everything, just point me in the right direction.

I have worked with Visual Studio(VB.Net) before and made some applications for my high school project. I also have some knowledge in C++ and HTML (enough to be able to understand the source code of a website).

Any help is appreciated. Thank you in advance!

答:
If you understand html you could use a web browser control and look at the html.
In the html you can find the element with the price in the page.

Since websites change often I do not recommend this method unless you
  own the site or maintain you program frequently.

This is how you can retrieve the html. You will need to find the right place to look for the data.

```<code>Private Sub WebBrowser1_DocumentCompleted(sender As Object, e As WebBrowserDocumentCompletedEventArgs) Handles WebBrowser1.DocumentCompleted
    MessageBox.Show(WebBrowser1.DocumentText)
End Sub
</code>```

Body:
If you understand html you could use a web browser control and look at the html.
In the html you can find the element with the price in the page.

Since websites change often I do not recommend this method unless you
  own the site or maintain you program frequently.

This is how you can retrieve the html. You will need to find the right place to look for the data.

Private Sub WebBrowser1_DocumentCompleted(sender As Object, e As WebBrowserDocumentCompletedEventArgs) Handles WebBrowser1.DocumentCompleted
    MessageBox.Show(WebBrowser1.DocumentText)
End Sub


问:
Why does the compiler invoke a templated copy constructor when assigning?
Consider the code below:

```<code>#include <iostream>

template<class T>
struct X
{
    X() = default;

    template<class U>
    X(const X<U>&)
    {
        std::cout << __PRETTY_FUNCTION__ << std::endl;
    }

/*
    template<class U>
    X& operator=(const X<U>&)
    {
        std::cout << __PRETTY_FUNCTION__ << std::endl;
        return *this;
    }
*/

};

int main()
{
    X<int> a;
    X<double> b;

    b = a;
}
</code>```

Live on Coliru

As you can see, the assignment operator is commented out. However, the line

```<code>b = a;
</code>```

compiles fine. I thought it should not compile, as a and b have different types, and the operator=(const X&) that is generated by default by the compiler will be instantiated by the underlying type, so it won't assign an X<int> to an X<double>.

To my surprise, the code compiles, and it seems that the templated copy constructor is being invoked. Why is this? Is it because the compiler tries first to cast the a to a b then invoke the default-generated B::operator=?

答:
The compiler is generating a call to X<double>(const X<int>&) to convert an X<int> into an X<double>. Then it's calling the generated assignment operator X<double>& X<double>::operator =(const X<double>&); to do the assignment.

If you wrote out all the steps explicitly it would be:

```<code>b.operator =(X<double>(a));
</code>```

Body:
Consider the code below:

#include <iostream>

template<class T>
struct X
{
    X() = default;

    template<class U>
    X(const X&)
    {
        std::cout << __PRETTY_FUNCTION__ << std::endl;
    }

/*
    template<class U>
    X& operator=(const X&)
    {
        std::cout << __PRETTY_FUNCTION__ << std::endl;
        return *this;
    }
*/

};

int main()
{
    X<int> a;
    X<double> b;

    b = a;
}

Live on Coliru

As you can see, the assignment operator is commented out. However, the line

b = a;

compiles fine. I thought it should not compile, as a and b have different types, and the operator=(const X&) that is generated by default by the compiler will be instantiated by the underlying type, so it won't assign an X<int> to an X<double>.

To my surprise, the code compiles, and it seems that the templated copy constructor is being invoked. Why is this? Is it because the compiler tries first to cast the a to a b then invoke the default-generated B::operator=?

Body:
The compiler is generating a call to X<double>(const X<int>&) to convert an X<int> into an X<double>. Then it's calling the generated assignment operator X<double>& X<double>::operator =(const X<double>&); to do the assignment.

If you wrote out all the steps explicitly it would be:

b.operator =(X<double>(a));


问:
Is there any benefit to using getters/setters inside a class for its own fields?
Usually, in my own projects I use getters and setters for any field access, and I followed to do the same on my job. Some time ago, the tech lead of our project asked me why I was doing that and why is this better than just using fields themselves (with an option of declaring them protected if they needed to be accessed by subclasses). I couldn't come up with a clear answer.

So, are there any reasons to using getters and setters inside a class for class' own fields, or is it better to use fields directly?

答:
This is part of the general question as to why you use getters and setters.  Many developers use them without though, as a matter of practice.  Personally, I only put in getters/setters if I need to.

I would suggest you do what is clearest/simplest to you.

In general, if I can easily add a getter/setter later should I need it, I won't add it.  If it would be difficult to add later (or you have an immediate use for them), I would include them.


问:
Equivalent to Array.scan |> Array.skip 1, but without creating intermediate array?
The Array.scan function returns an array of length n+1, where n was the length of its input array, and whose first item is the initial state passed to Array.scan. E.g.,

```<code>[|1;2;3;4|] |> Array.scan (+) 0  // Returns [|0;1;3;6;10|]
</code>```

However, I usually find that that isn't what I wanted: I wanted an array of length n, without the initial state being preserved in my output array. I could easily get this result by simply doing:

```<code>input |> Array.scan f initialState |> Array.skip 1
</code>```

But this will create an intermediate array which is immediately thrown away. Is there a good way to get this result without creating an intermediate array? I could easily implement that myself:

```<code>let scanWithoutInitial f initState input =
    let result = Array.zeroCreate (Array.length input)
    let mutable state = initState
    for i = 0 to (Array.length input - 1) do
        state <- f state input.[i]
        result.[i] <- state
    result
</code>```

However, this seems like a lot of work to reimplement something that I would think would be in the standard F# core library. Is there a function that I'm overlooking? Or am I the only one with this use case, and most people want the initial value as the first item of their Array.scan results?

答:
mapFold does exactly that:

```<code>Array.mapFold (fun acc x -> (acc + x, acc + x)) 0 [|1;2;3;4|] |> fst
</code>```

For more of a brainteaser, ref this post.

Body:
The Array.scan function returns an array of length n+1, where n was the length of its input array, and whose first item is the initial state passed to Array.scan. E.g.,

[|1;2;3;4|] |> Array.scan (+) 0  // Returns [|0;1;3;6;10|]

However, I usually find that that isn't what I wanted: I wanted an array of length n, without the initial state being preserved in my output array. I could easily get this result by simply doing:

input |> Array.scan f initialState |> Array.skip 1

But this will create an intermediate array which is immediately thrown away. Is there a good way to get this result without creating an intermediate array? I could easily implement that myself:

let scanWithoutInitial f initState input =
    let result = Array.zeroCreate (Array.length input)
    let mutable state = initState
    for i = 0 to (Array.length input - 1) do
        state <- f state input.[i]
        result.[i] <- state
    result

However, this seems like a lot of work to reimplement something that I would think would be in the standard F# core library. Is there a function that I'm overlooking? Or am I the only one with this use case, and most people want the initial value as the first item of their Array.scan results?

Body:
mapFold does exactly that:

Array.mapFold (fun acc x -> (acc + x, acc + x)) 0 [|1;2;3;4|] |> fst

For more of a brainteaser, ref this post.


问:
Python 3 - CSV File Issue (ValueError: not enough values to unpack)
I tried modifying this example code on python 3.x.

```<code>import csv

def cmp(a, b):
    return (a > b) - (a < b)

# write stocks data as comma-separated values
f = open('stocks.csv', 'w')
writer = csv.writer(f)
writer.writerows([
    ('GOOG', 'Google, Inc.', 505.24, 0.47, 0.09),
    ('YHOO', 'Yahoo!, Inc.', 27.38, 0.33, 1.22),
    ('CNET', 'CNET Networks, Inc.', 8.62, -0.13, -1.49)
])

f.close()

# read stocks data, print status messages
f = open('stocks.csv', 'r')
stocks = csv.reader(f)
status_labels = {-1: 'down', 0: 'unchanged', 1: 'up'}
for ticker, name, price, change, pct in stocks:
    status = status_labels[cmp(float(change), 0.0)]
    print('%s is %s (%s%%)' % (name, status, pct))

f.close()
</code>```

With suggestions from @glibdud, and @bernie, I have updated my code.
Am getting the below error:

ValueError: not enough values to unpack (expected 5, got 0)

What am I missing?

Note: Removed my question about double quotes in CSV file for string. Double quotes will be there if we have comma separated string, otherwise not.

答:
The Problem occurs during writing the file.
The problem is the newline handling of the csv module. See this and footnote 1

if you add print(*stocks, sep='\n') between line 19 ans 20 you will get following output:

```<code>['GOOG', 'Google, Inc.', '505.24', '0.47', '0.09']
[]
['YHOO', 'Yahoo!, Inc.', '27.38', '0.33', '1.22']
[]
['CNET', 'CNET Networks, Inc.', '8.62', '-0.13', '-1.49']
[]
</code>```

You see... an empty list can not have 5 values to unpack

@bernie already gave you the solution in his comment.

Change line 7 to:

```<code>f = open('stocks.csv', 'w', newline='')
                          ^^^^^^^^^^^^
</code>```

and you're fine.

Body:
I tried modifying this example code on python 3.x.

import csv

def cmp(a, b):
    return (a > b) - (a < b)

# write stocks data as comma-separated values
f = open('stocks.csv', 'w')
writer = csv.writer(f)
writer.writerows([
    ('GOOG', 'Google, Inc.', 505.24, 0.47, 0.09),
    ('YHOO', 'Yahoo!, Inc.', 27.38, 0.33, 1.22),
    ('CNET', 'CNET Networks, Inc.', 8.62, -0.13, -1.49)
])

f.close()

# read stocks data, print status messages
f = open('stocks.csv', 'r')
stocks = csv.reader(f)
status_labels = {-1: 'down', 0: 'unchanged', 1: 'up'}
for ticker, name, price, change, pct in stocks:
    status = status_labels[cmp(float(change), 0.0)]
    print('%s is %s (%s%%)' % (name, status, pct))

f.close()

With suggestions from @glibdud, and @bernie, I have updated my code.
Am getting the below error:

ValueError: not enough values to unpack (expected 5, got 0)

What am I missing?

Note: Removed my question about double quotes in CSV file for string. Double quotes will be there if we have comma separated string, otherwise not.

Body:
The Problem occurs during writing the file.
The problem is the newline handling of the csv module. See this and footnote 1

if you add print(*stocks, sep='\n') between line 19 ans 20 you will get following output:

['GOOG', 'Google, Inc.', '505.24', '0.47', '0.09']
[]
['YHOO', 'Yahoo!, Inc.', '27.38', '0.33', '1.22']
[]
['CNET', 'CNET Networks, Inc.', '8.62', '-0.13', '-1.49']
[]

You see... an empty list can not have 5 values to unpack

@bernie already gave you the solution in his comment.

Change line 7 to:

f = open('stocks.csv', 'w', newline='')
                          ^^^^^^^^^^^^

and you're fine.


问:
Django object filter not recognizing related name
Using Django 1.7

This console log demonstrates the problem.  The 'Positions' related field is not recognized.

```<code>    x = Person.objects.get(PersonSk=452)

    x.Positions
    <django.db.models.fields.related.RelatedManager object at 0x0000000005B4A358>

    x.Associations
    <django.db.models.fields.related.RelatedManager object at 0x0000000005AEDC18>

    Person.objects.filter(Associations__isnull=True)
    [lots of peeps]

    Person.objects.filter(Positions__isnull=True)
raise_field_error
    "Choices are: %s" % (name, ", ".join(available)))
FieldError: Cannot resolve keyword 'Positions' into field.
</code>```

Here are the model classes for Person, PersonAssociation, and Position.  Why does it work for PersonAssociation but not Position?

```<code>class Person(models.Model):
    class Meta:
        managed = False
        db_table = 'PERSON].[Person'
        ordering = ('LastName', 'FirstName')

    PersonSk = models.AutoField(primary_key=True, editable=False)
    FirstName = CharNullField('First Name', max_length=30, blank=True)
    LastName = CharNullField('Last Name', max_length=30, blank=True)
    Email = CharNullField(max_length=50, blank=True)
    PhoneWork = CharNullField('Work Phone', max_length=20, blank=True)
    PhoneMobile = CharNullField('Mobile Phone', max_length=20, blank=True)

class PersonAssociation(models.Model):
    class Meta:
        managed = False
        db_table ='CLIENT].[PersonAssociation'

    PersonAssociationSk = models.AutoField(primary_key=True, editable=False)
    Client = models.ForeignKey(Client, db_column='ClientCode', related_name='Associations')
    Person = models.ForeignKey(Person, db_column='PersonSk', related_name='Associations')

class Position(models.Model):
    class Meta:
        managed = False
        db_table = 'PERSON].[Position'

    PositionSk = models.AutoField(primary_key=True, editable=False)
    Person = models.ForeignKey(Person, db_column='PersonSk', related_name='Positions')
    ConsumerClient = models.ForeignKey(Client, db_column='ClientCode', related_name='Positions')
    ProviderClient = models.ForeignKey(Client, db_column='ProviderClientCode', related_name='ProviderPositions', blank=True, null=True)
    Role = models.ForeignKey(ContactRole, db_column='ContactRoleSk', related_name='Positions')
    Facility = models.ForeignKey(Facility, db_column='FacilitySk', blank=True, null=True)
    Notes = models.TextField(blank=True, null=True)
    StartDate = models.DateField()
    EndDate = models.DateField(blank=True, null=True)
</code>```

As far as I can tell, the related_name field is setup in the same way for both?  I also tried changing the related_name in Position to "Plops", and redid the test with the same result.

Here is another console log that I think better illustrates the problem.  In the Positions models, I have the Role field and Person field configured with the same related name.  So I tried this:

```<code>ContactRole.Positions
<django.db.models.fields.related.ForeignRelatedObjectsDescriptor object at 0x00000000060F5DA0>

Person.Positions
<django.db.models.fields.related.ForeignRelatedObjectsDescriptor object at 0x00000000060F5CC0>

ContactRole.objects.filter(Positions__isnull=True)
[ lots of roles ]

Person.objects.filter(Positions__isnull=True)
FieldError: Cannot resolve keyword 'Positions' into field.
</code>```

So it looks like its specifically the filter function that isn't working?

答:
Your issue here is that Positions isn't a field, it's a relation. If you want a list of employees with zero positions, you'll need to do an aggregation, and then a filter on that aggregation.

Something like this:

```<code>Person.objects.annotate(
    positions_count=Count('Positions')
).filter(positions_count=0)
</code>```

Body:
Using Django 1.7

This console log demonstrates the problem.  The 'Positions' related field is not recognized.

    x = Person.objects.get(PersonSk=452)

    x.Positions
    <django.db.models.fields.related.RelatedManager object at 0x0000000005B4A358>

    x.Associations
    <django.db.models.fields.related.RelatedManager object at 0x0000000005AEDC18>

    Person.objects.filter(Associations__isnull=True)
    [lots of peeps]

    Person.objects.filter(Positions__isnull=True)
raise_field_error
    "Choices are: %s" % (name, ", ".join(available)))
FieldError: Cannot resolve keyword 'Positions' into field.

Here are the model classes for Person, PersonAssociation, and Position.  Why does it work for PersonAssociation but not Position?

class Person(models.Model):
    class Meta:
        managed = False
        db_table = 'PERSON].[Person'
        ordering = ('LastName', 'FirstName')

    PersonSk = models.AutoField(primary_key=True, editable=False)
    FirstName = CharNullField('First Name', max_length=30, blank=True)
    LastName = CharNullField('Last Name', max_length=30, blank=True)
    Email = CharNullField(max_length=50, blank=True)
    PhoneWork = CharNullField('Work Phone', max_length=20, blank=True)
    PhoneMobile = CharNullField('Mobile Phone', max_length=20, blank=True)

class PersonAssociation(models.Model):
    class Meta:
        managed = False
        db_table ='CLIENT].[PersonAssociation'

    PersonAssociationSk = models.AutoField(primary_key=True, editable=False)
    Client = models.ForeignKey(Client, db_column='ClientCode', related_name='Associations')
    Person = models.ForeignKey(Person, db_column='PersonSk', related_name='Associations')

class Position(models.Model):
    class Meta:
        managed = False
        db_table = 'PERSON].[Position'

    PositionSk = models.AutoField(primary_key=True, editable=False)
    Person = models.ForeignKey(Person, db_column='PersonSk', related_name='Positions')
    ConsumerClient = models.ForeignKey(Client, db_column='ClientCode', related_name='Positions')
    ProviderClient = models.ForeignKey(Client, db_column='ProviderClientCode', related_name='ProviderPositions', blank=True, null=True)
    Role = models.ForeignKey(ContactRole, db_column='ContactRoleSk', related_name='Positions')
    Facility = models.ForeignKey(Facility, db_column='FacilitySk', blank=True, null=True)
    Notes = models.TextField(blank=True, null=True)
    StartDate = models.DateField()
    EndDate = models.DateField(blank=True, null=True)

As far as I can tell, the related_name field is setup in the same way for both?  I also tried changing the related_name in Position to "Plops", and redid the test with the same result.

Here is another console log that I think better illustrates the problem.  In the Positions models, I have the Role field and Person field configured with the same related name.  So I tried this:

ContactRole.Positions
<django.db.models.fields.related.ForeignRelatedObjectsDescriptor object at 0x00000000060F5DA0>

Person.Positions
<django.db.models.fields.related.ForeignRelatedObjectsDescriptor object at 0x00000000060F5CC0>

ContactRole.objects.filter(Positions__isnull=True)
[ lots of roles ]

Person.objects.filter(Positions__isnull=True)
FieldError: Cannot resolve keyword 'Positions' into field.

So it looks like its specifically the filter function that isn't working?

Body:
Your issue here is that Positions isn't a field, it's a relation. If you want a list of employees with zero positions, you'll need to do an aggregation, and then a filter on that aggregation.

Something like this:

Person.objects.annotate(
    positions_count=Count('Positions')
).filter(positions_count=0)


问:
drawBitmap low performance on SurfaceView game thread (android)
I am drawing set of images on SurfaceView canvas. doDraw is called by game loop thread after getting surfaceHolder. The issue is frames per second (FPS) is really low when number of images drawn on canvas is large. This is because of drawBitmap is slow.

Test Setup

clusters arraylist has 400 small images (cluster.Picture). Time difference is the measured parameter to run drawBitmap loop. To compare I replaced drawBitmap with drawRect and also commented out drawBitmap leaving the loop empty body.
Device used for testing
https://www.optus.com.au/shop/prepaidmobile/lg/leon

Test Result  (milliseconds)

drawBitmap 400 loop - Average: 25.5, MIN: 14 , MAX: 37

drawRect 400 loop   - Average: 8.6, MIN: 5 , MAX: 21

Nothing 400 loop    - Average: 1.3, MIN: 0 , MAX: 10

The time above only measures portion of logic. Total game loop would take close to 40 ms. This means FPS is really low. Even for 100 loop, it takes 18 ms just to draw bitmaps.

I tried setting getHolder().setFormat(PixelFormat.RGBA_8888), setFixedSize(screenSize.x , screenSize.y) and zorder as well as setting bitmap configurations to RGBA_8888. In addition I tried setting high priority using setPriority of game thread.

I am not sure what else I can do. How can I improve performance of my game loop and FPS.

```<code>    public List<PCluster> clusters = new ArrayList<PCluster>();

    public void doDraw(Canvas canvas) {

    try {
        if (canvas == null) {
            return;
        }
        super.draw(canvas);

        canvas.drawColor(backColor);
        if (waitTillLoad) {
            return;
        }

    } catch (Exception ex) {
    }
    final int savedState = canvas.save();
    try {

        minX = (int) (((viewWidth / mScaleFactor) - Gen.screenSizeWidth) / 2) * Utils.VIEW_SIZE;
        minY = (int) (((viewHeight / mScaleFactor) - Gen.screenSizeHeight) / 2) * Utils.VIEW_SIZE;

        if (mPosX > maxX) {
            mPosX = maxX;
        }
        if (mPosX < minX) {
            mPosX = minX;
        }
        if (mPosY > maxY) {
            mPosY = maxY;
        }
        if (mPosY < minY) {
            mPosY = minY;
        }

        canvas.scale(mScaleFactor, mScaleFactor);
        canvas.translate(mPosX, mPosY);

        long startTime = System.currentTimeMillis();
        if (!showBackground) {

            for (PCluster cluster : clusters) {
                if (cluster.isVisible) {
                    canvas.drawBitmap(cluster.Picture, cluster.BoardLocation.left,
                            cluster.BoardLocation.top, null);
                }
            }
            Log.d("myApp", "   " + (System.currentTimeMillis() - startTime));
        }

    } catch (Exception ex) {
    } finally {
        canvas.restoreToCount(savedState);
    }
}
</code>```

答:
I was able to improve performance some what using PorterDuff SRC_OVER paint object. This is probably because less calculations when transparent images are drawn on top of each other. Also make sure to add dithering and anti-aliasing to the paint.</p>

```<code>canvasPaint = new Paint();
canvasPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_OVER ));

canvas.drawBitmap(cluster.Picture, cluster.BoardLocation.left,
                            cluster.BoardLocation.top, canvasPaint );
</code>```

Body:
I am drawing set of images on SurfaceView canvas. doDraw is called by game loop thread after getting surfaceHolder. The issue is frames per second (FPS) is really low when number of images drawn on canvas is large. This is because of drawBitmap is slow.

Test Setup

clusters arraylist has 400 small images (cluster.Picture). Time difference is the measured parameter to run drawBitmap loop. To compare I replaced drawBitmap with drawRect and also commented out drawBitmap leaving the loop empty body.
Device used for testing
https://www.optus.com.au/shop/prepaidmobile/lg/leon

Test Result  (milliseconds)

drawBitmap 400 loop - Average: 25.5, MIN: 14 , MAX: 37

drawRect 400 loop   - Average: 8.6, MIN: 5 , MAX: 21

Nothing 400 loop    - Average: 1.3, MIN: 0 , MAX: 10

The time above only measures portion of logic. Total game loop would take close to 40 ms. This means FPS is really low. Even for 100 loop, it takes 18 ms just to draw bitmaps.

I tried setting getHolder().setFormat(PixelFormat.RGBA_8888), setFixedSize(screenSize.x , screenSize.y) and zorder as well as setting bitmap configurations to RGBA_8888. In addition I tried setting high priority using setPriority of game thread.

I am not sure what else I can do. How can I improve performance of my game loop and FPS.

    public List<PCluster> clusters = new ArrayList<PCluster>();

    public void doDraw(Canvas canvas) {

    try {
        if (canvas == null) {
            return;
        }
        super.draw(canvas);

        canvas.drawColor(backColor);
        if (waitTillLoad) {
            return;
        }

    } catch (Exception ex) {
    }
    final int savedState = canvas.save();
    try {

        minX = (int) (((viewWidth / mScaleFactor) - Gen.screenSizeWidth) / 2) * Utils.VIEW_SIZE;
        minY = (int) (((viewHeight / mScaleFactor) - Gen.screenSizeHeight) / 2) * Utils.VIEW_SIZE;

        if (mPosX > maxX) {
            mPosX = maxX;
        }
        if (mPosX < minX) {
            mPosX = minX;
        }
        if (mPosY > maxY) {
            mPosY = maxY;
        }
        if (mPosY < minY) {
            mPosY = minY;
        }

        canvas.scale(mScaleFactor, mScaleFactor);
        canvas.translate(mPosX, mPosY);

        long startTime = System.currentTimeMillis();
        if (!showBackground) {

            for (PCluster cluster : clusters) {
                if (cluster.isVisible) {
                    canvas.drawBitmap(cluster.Picture, cluster.BoardLocation.left,
                            cluster.BoardLocation.top, null);
                }
            }
            Log.d("myApp", "   " + (System.currentTimeMillis() - startTime));
        }

    } catch (Exception ex) {
    } finally {
        canvas.restoreToCount(savedState);
    }
}

Body:
I was able to improve performance some what using PorterDuff SRC_OVER paint object. This is probably because less calculations when transparent images are drawn on top of each other. Also make sure to add dithering and anti-aliasing to the paint.

canvasPaint = new Paint();
canvasPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_OVER ));

canvas.drawBitmap(cluster.Picture, cluster.BoardLocation.left,
                            cluster.BoardLocation.top, canvasPaint );


问:
OneLogin for Java: configure certificate and PK
How do I configure certificate and PK exactly ?

For security I probably don't want to keep my PK in my source code. So how do I specify a custom path ?

But in the meantime is this correct ?

```<code># Usually x509cert and privateKey of the SP are provided by files placed at
# the certs folder. But we can also provide them with the following parameters
onelogin.saml2.sp.x509cert = -----BEGIN CERTIFICATE-----
MIICQjCCAaugAwIBAgIEJC7VoDANBgkqhkiG9w0BAQsFADBUMQswCQYDVQQGEwJV
...
rYsMZmOthlq9nzyvTgYPWUozUX2PsUvrWDOehtulcfO9GbT7TqhSfs96RWoAJlpx
DVnF33gs
-----END CERTIFICATE-----

# Requires Format PKCS#8   BEGIN PRIVATE KEY
# If you have     PKCS#1   BEGIN RSA PRIVATE KEY  convert it by   openssl pkcs8 -topk8 -inform pem -nocrypt -in sp.rsa_key -outform pem -out sp.pem
onelogin.saml2.sp.privatekey = -----BEGIN PRIVATE KEY-----
MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAKUKJ+2aDsroFdbv
...ZKL4hvtee3nRwXyjjVdeXF9vZrbqSAkVdRt+RnqtqvvHTkpUWWoHWhNT8ijyLvst
+L8dfnvBv2S6hg==
-----END PRIVATE KEY-----
</code>```

Related to this: what is the difference between using a certificate vs using a certificate fingerprint ?

Thank you,

Simon

答:
Currently the java-saml only is able to read SP public cert/private key from the settings file. Support read them from files is something that we want to implement Issue 54 and Issue 55 but can't say to you when it gonna be ready.

Properties on settings MUST be in 1 unique line so your values are wrong.

fingerprint is an easier way to provide a way to validate the signatures of the SAMLResponse when it is sent using HTTP-POST binding (not valid on SAML Messages sent using HTTP-Redirect binding).

Body:
How do I configure certificate and PK exactly ?

For security I probably don't want to keep my PK in my source code. So how do I specify a custom path ?

But in the meantime is this correct ?

# Usually x509cert and privateKey of the SP are provided by files placed at
# the certs folder. But we can also provide them with the following parameters
onelogin.saml2.sp.x509cert = -----BEGIN CERTIFICATE-----
MIICQjCCAaugAwIBAgIEJC7VoDANBgkqhkiG9w0BAQsFADBUMQswCQYDVQQGEwJV
...
rYsMZmOthlq9nzyvTgYPWUozUX2PsUvrWDOehtulcfO9GbT7TqhSfs96RWoAJlpx
DVnF33gs
-----END CERTIFICATE-----

# Requires Format PKCS#8   BEGIN PRIVATE KEY
# If you have     PKCS#1   BEGIN RSA PRIVATE KEY  convert it by   openssl pkcs8 -topk8 -inform pem -nocrypt -in sp.rsa_key -outform pem -out sp.pem
onelogin.saml2.sp.privatekey = -----BEGIN PRIVATE KEY-----
MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAKUKJ+2aDsroFdbv
...ZKL4hvtee3nRwXyjjVdeXF9vZrbqSAkVdRt+RnqtqvvHTkpUWWoHWhNT8ijyLvst
+L8dfnvBv2S6hg==
-----END PRIVATE KEY-----

Related to this: what is the difference between using a certificate vs using a certificate fingerprint ?

Thank you,

Simon


问:
How to install third party libraries in Drupal 8 with Composer that are not on packagist?
What is the best way to install a third party library in Drupal 8 that is not on packagist?

For example I have the Color Field module, which can use the jQuery Simple Color Picker library to provide a better user experience.

The most obvious solution is to just add the library manually, but that's not really maintainable.

My second idea was to add the git repository to my composer.json, as shown below, but it doesn't work because the target repository doesn't have a composer.json file.

```<code>"repositories": [
    {
        "name": "jquery-simple-color",
        "type": "git",
        "url": "https://github.com/recurser/jquery-simple-color.git"
    }
],
"require": {
    "jquery-simple-color/": "1.2.1"
}
</code>```

Should I just fork the git repository and add a composer.json file there?

答:
You was on the right track, in your composer.json you can make your own "packages"
for example:

```<code>"repositories": [
  {
    "type": "package",
    "package": {
      "name": "jquery/simplecolor",
      "version": "1.2.1",
      "dist": {
        "url": "https://github.com/recurser/jquery-simple-color/archive/v1.2.1.zip",
        "type": "zip"
      },
      "type": "drupal-library"
    }
  }
]
</code>```

And then include it trough

```<code>  "jquery/simplecolor": "1.2.1,
</code>```

Body:
What is the best way to install a third party library in Drupal 8 that is not on packagist?

For example I have the Color Field module, which can use the jQuery Simple Color Picker library to provide a better user experience.

The most obvious solution is to just add the library manually, but that's not really maintainable.

My second idea was to add the git repository to my composer.json, as shown below, but it doesn't work because the target repository doesn't have a composer.json file.

"repositories": [
    {
        "name": "jquery-simple-color",
        "type": "git",
        "url": "https://github.com/recurser/jquery-simple-color.git"
    }
],
"require": {
    "jquery-simple-color/": "1.2.1"
}

Should I just fork the git repository and add a composer.json file there?

Body:
You was on the right track, in your composer.json you can make your own "packages"
for example:

"repositories": [
  {
    "type": "package",
    "package": {
      "name": "jquery/simplecolor",
      "version": "1.2.1",
      "dist": {
        "url": "https://github.com/recurser/jquery-simple-color/archive/v1.2.1.zip",
        "type": "zip"
      },
      "type": "drupal-library"
    }
  }
]

And then include it trough

  "jquery/simplecolor": "1.2.1,