问:
How to properly center the text?
I'm trying to center the text in the middle of JQM page, vertically and horizontally. Using 1.4.5, default theme.

In my .css I have:

```<code>.splashDiv {
    position: absolute;
    top: 50%;
    height: 50%;
    width: 100%;
    text-align: center;
    padding:0;
}
</code>```

HTML

```<code><div class="splashDiv" data-role="page">
    Please wait...
</div>
</code>```

The result is:

The text is vertically centered only if I remove top: 0 directive in developer tools(although not perfectly centered).

My question is what is the proper way according to JQM architecture to have what I want? I am not looking for quick/dirty workaround, unless there is no other way.

UPDATE

答:
Please Try it.
Your HTML

```<code><div data-role="page" id="page1">
    <div id="cont" role="main" class="ui-content">
      <div class="splashDiv" >
        <span>Please wait...</span>
      </div>
   </div>
</div>
</code>```

Your CSS

```<code>.splashDiv {
    position: absolute;
    top: 50%;
    left: 50%;
    height: 50%;
    width: 100%;
    text-align: center;
    padding:0;
    overflow: hidden;
    transform: translate(-50%, -50%)
}
.splashDiv span {
    margin: 0;
    background: yellow;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%)
}
</code>```

DEMO

Title: How to properly center the text?

Body:
I'm trying to center the text in the middle of JQM page, vertically and horizontally. Using 1.4.5, default theme.

In my .css I have:

.splashDiv {
    position: absolute;
    top: 50%;
    height: 50%;
    width: 100%;
    text-align: center;
    padding:0;
}

HTML

    Please wait...

The result is:

The text is vertically centered only if I remove top: 0 directive in developer tools(although not perfectly centered).

My question is what is the proper way according to JQM architecture to have what I want? I am not looking for quick/dirty workaround, unless there is no other way.

UPDATE

Body:
Please Try it.
Your HTML

<div data-role="page" id="page1">
    <div id="cont" role="main" class="ui-content">
      <div class="splashDiv" >
        <span>Please wait...</span>
      </div>
   </div>
</div>

Your CSS

.splashDiv {
    position: absolute;
    top: 50%;
    left: 50%;
    height: 50%;
    width: 100%;
    text-align: center;
    padding:0;
    overflow: hidden;
    transform: translate(-50%, -50%)
}
.splashDiv span {
    margin: 0;
    background: yellow;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%)
}

DEMO


来源: stackexchange

问:
Dynamically create a tuple with all the same type and a known number of elements
I am looking to dynamically create tuples of a given size that have all the same type.

So if I wanted a tuple of strings of size three I would get Tuple<string, string, string>

I have tried both to pass strings into the angle brackets for Tuple like this:

```<code>string foo = "string, string, string";
Tuple<foo> testTuple = Tuple<foo>(~parameters~);
</code>```

and to pass an array of types into the angle brackets like this:

```<code>List<Type> types = new List<Type>() {"".GetType(), "".GetType(), "".GetType()};
Tuple<types> testTuple = Tuple<foo>(~parameters~);
</code>```

Neither one of these worked. Does anyone know how to make the described dynamic tuples?

(The reason I want to do this is to use tuples inside of a dictionary like

```<code>Dictionary<Tuple<# strings>, int> testDictionary = new Dictionary<Tuple<x # strings>, int>();
</code>```

Using tuples here is more useful than HashSets because the comparison in tuples is by components instead of by reference so that if I have

```<code>Tuple<string, string> testTuple1 = new Tuple<string, string>("yes", "no");
Tuple<string, string> testTuple2 = new Tuple<string, string>("yes", "no");
Dictionary<Tuple<string, string>, string> testDictionary = new Dictionary<Tuple<string, string>, string>() {
    {testTuple1, "maybe"}
};
Console.WriteLine(testDict[testTuple2]);
</code>```

it writes "maybe". If you run this same test with HashSets, it throws an error. If there is a better way to accomplish this same thing, that would also be useful.)

答:
"Does anyone know how to make the described dynamic tuples?"

You can just use Tuple.Create(). For a 3-tuple:

```<code>var tupleOfStrings = Tuple.Create("string1", "string2", "string3");
var tupleOfInts = Tuple.Create(1, 2, 3);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am looking to dynamically create tuples of a given size that have all the same type.

So if I wanted a tuple of strings of size three I would get Tuple<string, string, string>

I have tried both to pass strings into the angle brackets for Tuple like this:

string foo = "string, string, string";
Tuple<foo> testTuple = Tuple<foo>(~parameters~);

and to pass an array of types into the angle brackets like this:

List<Type> types = new List<Type>() {"".GetType(), "".GetType(), "".GetType()};
Tuple<types> testTuple = Tuple<foo>(~parameters~);

Neither one of these worked. Does anyone know how to make the described dynamic tuples?

(The reason I want to do this is to use tuples inside of a dictionary like

Dictionary<Tuple<# strings>, int> testDictionary = new Dictionary<Tuple<x # strings>, int>();

Using tuples here is more useful than HashSets because the comparison in tuples is by components instead of by reference so that if I have

Tuple<string, string> testTuple1 = new Tuple<string, string>("yes", "no");
Tuple<string, string> testTuple2 = new Tuple<string, string>("yes", "no");
Dictionary<Tuple<string, string>, string> testDictionary = new Dictionary<Tuple<string, string>, string>() {
    {testTuple1, "maybe"}
};
Console.WriteLine(testDict[testTuple2]);

it writes "maybe". If you run this same test with HashSets, it throws an error. If there is a better way to accomplish this same thing, that would also be useful.)

Body:
"Does anyone know how to make the described dynamic tuples?"

You can just use Tuple.Create(). For a 3-tuple:

var tupleOfStrings = Tuple.Create("string1", "string2", "string3");
var tupleOfInts = Tuple.Create(1, 2, 3);


问:
Scala HTTPS post including JSON input and output along with authentication
I cannot find a single example of Scala HTTPS post including JSON input and output along with authentication.  I can't even find such an example in Java.  I can do this easily in Python:

```<code>def main(user_name, password):
    headers = {'Content-Type': 'application/json', 'Accept': 'application/json'}

    eta_data = """{
      "contact": {
        "longitude": "-151.7200",
        "latitude": "-16.4400",
        "timestamp": "2016-04-22 15:14:55",
        "speedKnots": "15.4"
      },
      "destination": {
        "longitude": "-149.869722",
        "latitude": "-17.491667"
      }
    }"""

    r = requests.post('https://www4.demo.exactearth.com/eta', data=eta_data, auth=(user_name, password), headers=headers)
    print()
    print("eta:")
    print(r.text)
    print(r.json())
</code>```

I'm not asking anyone to translate this to Scala for me, but how hard can this be?  Can someone please point me to an up-to-date Scala book that covers this?  Scala HTTPS post AND JSON input AND JSON output AND simple username/password authentication

答:
I actually tried to solve this task after I read your question. I've found most of the libraries are pretty complicated and use Akka in their dependencies.
I wrote that kind of call use couple of libraries and liked Play-WS more than others. Initialization a bit long (as it also using Akka) but actual usage is nice and tidy.

Down below is the code I've ended up with. Actual call is in call function

```<code>import akka.actor.ActorSystem
import akka.stream.ActorMaterializer
import play.api.libs.ws._
import play.api.libs.ws.ahc._

import scala.concurrent.Future
import scala.concurrent.ExecutionContext.Implicits._

object PlayWs extends App{

  val eta_data = """{
      "contact": {
        "longitude": "-151.7200",
        "latitude": "-16.4400",
        "timestamp": "2016-04-22 15:14:55",
        "speedKnots": "15.4"
      },
      "destination": {
        "longitude": "-149.869722",
        "latitude": "-17.491667"
      }
    }"""

  def call(wsClient: StandaloneWSClient): Future[Unit] = {

    wsClient.url("http://requestb.in/ozxfttoz")
      .withAuth("username", "password", WSAuthScheme.BASIC)
      .withHeaders("Content-Type" -> "application/json", "Accept" -> "application/json")
      .post(eta_data).map { response ⇒
        val statusText: String = response.statusText
        println("Response:")
        println(s"${response.status} $statusText")
        println(s"${response.body}")
      }
  }
  // Create Akka system for thread and streaming management
  implicit val system = ActorSystem()
  system.registerOnTermination {
    System.exit(0)
  }
  implicit val materializer = ActorMaterializer()

  val wsClient = StandaloneAhcWSClient()

  call(wsClient)
    .andThen { case _ => wsClient.close() }
    .andThen { case _ => system.terminate() }

}
</code>```

I've used standalone version and added it to project as

```<code>libraryDependencies += "com.typesafe.play" %% "play-ahc-ws-standalone" % "1.0.0-M6"
</code>```

Body:
I cannot find a single example of Scala HTTPS post including JSON input and output along with authentication.  I can't even find such an example in Java.  I can do this easily in Python:

def main(user_name, password):
    headers = {'Content-Type': 'application/json', 'Accept': 'application/json'}

    eta_data = """{
      "contact": {
        "longitude": "-151.7200",
        "latitude": "-16.4400",
        "timestamp": "2016-04-22 15:14:55",
        "speedKnots": "15.4"
      },
      "destination": {
        "longitude": "-149.869722",
        "latitude": "-17.491667"
      }
    }"""

    r = requests.post('https://www4.demo.exactearth.com/eta', data=eta_data, auth=(user_name, password), headers=headers)
    print()
    print("eta:")
    print(r.text)
    print(r.json())

I'm not asking anyone to translate this to Scala for me, but how hard can this be?  Can someone please point me to an up-to-date Scala book that covers this?  Scala HTTPS post AND JSON input AND JSON output AND simple username/password authentication

Body:
I actually tried to solve this task after I read your question. I've found most of the libraries are pretty complicated and use Akka in their dependencies.
I wrote that kind of call use couple of libraries and liked Play-WS more than others. Initialization a bit long (as it also using Akka) but actual usage is nice and tidy.

Down below is the code I've ended up with. Actual call is in call function

import akka.actor.ActorSystem
import akka.stream.ActorMaterializer
import play.api.libs.ws._
import play.api.libs.ws.ahc._

import scala.concurrent.Future
import scala.concurrent.ExecutionContext.Implicits._

object PlayWs extends App{

  val eta_data = """{
      "contact": {
        "longitude": "-151.7200",
        "latitude": "-16.4400",
        "timestamp": "2016-04-22 15:14:55",
        "speedKnots": "15.4"
      },
      "destination": {
        "longitude": "-149.869722",
        "latitude": "-17.491667"
      }
    }"""

  def call(wsClient: StandaloneWSClient): Future[Unit] = {

    wsClient.url("http://requestb.in/ozxfttoz")
      .withAuth("username", "password", WSAuthScheme.BASIC)
      .withHeaders("Content-Type" -> "application/json", "Accept" -> "application/json")
      .post(eta_data).map { response ⇒
        val statusText: String = response.statusText
        println("Response:")
        println(s"${response.status} $statusText")
        println(s"${response.body}")
      }
  }
  // Create Akka system for thread and streaming management
  implicit val system = ActorSystem()
  system.registerOnTermination {
    System.exit(0)
  }
  implicit val materializer = ActorMaterializer()

  val wsClient = StandaloneAhcWSClient()

  call(wsClient)
    .andThen { case _ => wsClient.close() }
    .andThen { case _ => system.terminate() }

}

I've used standalone version and added it to project as

libraryDependencies += "com.typesafe.play" %% "play-ahc-ws-standalone" % "1.0.0-M6"


问:
SQL Server Convert case for letter that comes after - (hyphen)
I need to convert case for letter that comes after hyphen (-) in all values of a column

like

```<code>Aaa - aaa
Bbbdd - bbbdd
Ccc123 - ccc123
</code>```

to

```<code>Aaa - Aaa
Bbbdd - Bbbdd
Ccc123 - Ccc123
</code>```

Please help!

答:
Well if the format doesn't change here's an easy way. It works for n - n characters

```<code>declare @char varchar(64) = 'Aaa - aaa'

select
    @char
    ,substring(@char,1,CHARINDEX('-',@char,1)) + ' ' + upper(substring(@char,CHARINDEX('-',@char,1) + 2,1)) + substring(@char,CHARINDEX('-',@char,1)+3,len(@char))
</code>```

Otherwise you need a UDF

Body:
I need to convert case for letter that comes after hyphen (-) in all values of a column

like

Aaa - aaa
Bbbdd - bbbdd
Ccc123 - ccc123

to

Aaa - Aaa
Bbbdd - Bbbdd
Ccc123 - Ccc123

Please help!

Body:
Well if the format doesn't change here's an easy way. It works for n - n characters

declare @char varchar(64) = 'Aaa - aaa'

select
    @char
    ,substring(@char,1,CHARINDEX('-',@char,1)) + ' ' + upper(substring(@char,CHARINDEX('-',@char,1) + 2,1)) + substring(@char,CHARINDEX('-',@char,1)+3,len(@char))

Otherwise you need a UDF


问:
Pyspark Specify Default Value for Column
I'm using Spark 1.6.1 and Python 2.7

I'm trying to figure out how I can specify a default value for a newly added column to a dataframe. Take this scenario where I have a dataframe named df1 that contains

```<code>+-------+----+
|user_id| age|
+-------+----+
|  10000|  45|
|  10013|  40|
|  10021|Null|
|  10025|  50|
|  10051|  31|
+-------+----+
</code>```

Now I want to add a new column called age2 that just has a simple function age + 1

```<code>>>> df1 = df1.withColumn("age2", df1["age"]+1)

+-------+----+----+
|user_id| age|age2|
+-------+----+----+
|  10000|  45|  46|
|  10013|  40|  41|
|  10021|Null|Null|
|  10025|  50|  51|
|  10051|  31|  32|
+-------+----+----+
</code>```

Is there a way I can specify a default value for age2 so that instead of returning a null for age2 when there is a null in age, I can return something like 1 so that I get

```<code>+-------+----+----+
|user_id| age|age2|
+-------+----+----+
|  10000|  45|  46|
|  10013|  40|  41|
|  10021|Null|   1|
|  10025|  50|  51|
|  10051|  31|  32|
+-------+----+----+
</code>```

I know that I can use a UDF to do this, but I want to know if there is a built in way to do it instead.

答:
I would suggest you to use fillna function. Create a new column as you are doing it currently. Next fill the null values with the fillna function

```<code>>>> df1 = df1.withColumn("age2", df1["age"]+1)
>>> df1 = df1.na.fill({'age2': 1})
</code>```

Body:
I'm using Spark 1.6.1 and Python 2.7

I'm trying to figure out how I can specify a default value for a newly added column to a dataframe. Take this scenario where I have a dataframe named df1 that contains

+-------+----+
|user_id| age|
+-------+----+
|  10000|  45|
|  10013|  40|
|  10021|Null|
|  10025|  50|
|  10051|  31|
+-------+----+

Now I want to add a new column called age2 that just has a simple function age + 1

>>> df1 = df1.withColumn("age2", df1["age"]+1)

+-------+----+----+
|user_id| age|age2|
+-------+----+----+
|  10000|  45|  46|
|  10013|  40|  41|
|  10021|Null|Null|
|  10025|  50|  51|
|  10051|  31|  32|
+-------+----+----+

Is there a way I can specify a default value for age2 so that instead of returning a null for age2 when there is a null in age, I can return something like 1 so that I get

+-------+----+----+
|user_id| age|age2|
+-------+----+----+
|  10000|  45|  46|
|  10013|  40|  41|
|  10021|Null|   1|
|  10025|  50|  51|
|  10051|  31|  32|
+-------+----+----+

I know that I can use a UDF to do this, but I want to know if there is a built in way to do it instead.

Body:
I would suggest you to use fillna function. Create a new column as you are doing it currently. Next fill the null values with the fillna function

>>> df1 = df1.withColumn("age2", df1["age"]+1)
>>> df1 = df1.na.fill({'age2': 1})


问:
Combining tweens in ScrollMagic
I'm creating two SVG animations using Scrollmagic, using two scripts, but the code is redundant and repeating. Is there a way to make it cleaner / more efficient, combining everything in a single script? Thank you. The code I am using is something like this:</p>

```<code><script>
// START of animation 1

function pathPrepare ($el) {
    var lineLength = $el[0].getTotalLength();
    $el.css("stroke-dasharray", lineLength);
    $el.css("stroke-dashoffset", lineLength);
    }

var $animation1 = $("path#animation1");
pathPrepare($animation1);
var tween = new TimelineMax()
.add(TweenMax.to($animation1, 3, {strokeDashoffset: 0, ease:Linear.easeNone}))

var scene = new ScrollMagic.Scene({triggerElement: "#animationonediv", duration: 300, tweenChanges: true})
.setTween(tween)
.addTo(controller);

</script>

<script>
// START of animation 2, which is in essence a copy of the previous code

function pathPrepare ($el) {
    var lineLength = $el[0].getTotalLength();
    $el.css("stroke-dasharray", lineLength);
    $el.css("stroke-dashoffset", lineLength);
    }

var $animation1 = $("path#animation2");
pathPrepare($animation2);
var tween = new TimelineMax()
.add(TweenMax.to($animation2, 3, {strokeDashoffset: 0, ease:Linear.easeNone}))

var scene = new ScrollMagic.Scene({triggerElement: "#animationtwodiv", duration: 300, tweenChanges: true})
.setTween(tween)
.addTo(controller);

</script>
</code>```

答:
You could essentially do something like this so variables and functions aren't duplicated:</p>

```<code><script>
    // START of animation 1
    function pathPrepare ($el) {
        var lineLength = $el[0].getTotalLength();
        $el.css("stroke-dasharray", lineLength);
        $el.css("stroke-dashoffset", lineLength);
        }

    var $animation1 = $("path#animation1");
    pathPrepare($animation1);
    var tween = new TimelineMax()
    .add(TweenMax.to($animation1, 3, {strokeDashoffset: 0, ease:Linear.easeNone}))

    var scene = new ScrollMagic.Scene({triggerElement: "#animationonediv", duration: 300, tweenChanges: true})
    .setTween(tween)
    .addTo(controller);

    var $animation2 = $("path#animation2");
    pathPrepare($animation2);
    var tween2 = new TimelineMax()
    .add(TweenMax.to($animation2, 3, {strokeDashoffset: 0, ease:Linear.easeNone}))

    var scene2 = new ScrollMagic.Scene({triggerElement: "#animationtwodiv", duration: 300, tweenChanges: true})
    .setTween(tween2)
    .addTo(controller);
</script>
</code>```

Title: Combining tweens in ScrollMagic

Body:
You could essentially do something like this so variables and functions aren't duplicated:

<script>
    // START of animation 1
    function pathPrepare ($el) {
        var lineLength = $el[0].getTotalLength();
        $el.css("stroke-dasharray", lineLength);
        $el.css("stroke-dashoffset", lineLength);
        }

    var $animation1 = $("path#animation1");
    pathPrepare($animation1);
    var tween = new TimelineMax()
    .add(TweenMax.to($animation1, 3, {strokeDashoffset: 0, ease:Linear.easeNone}))

    var scene = new ScrollMagic.Scene({triggerElement: "#animationonediv", duration: 300, tweenChanges: true})
    .setTween(tween)
    .addTo(controller);

    var $animation2 = $("path#animation2");
    pathPrepare($animation2);
    var tween2 = new TimelineMax()
    .add(TweenMax.to($animation2, 3, {strokeDashoffset: 0, ease:Linear.easeNone}))

    var scene2 = new ScrollMagic.Scene({triggerElement: "#animationtwodiv", duration: 300, tweenChanges: true})
    .setTween(tween2)
    .addTo(controller);
</script>


问:
What does TestFlight do to my iOS executable?
I hash my iOS executable at launch to verify its integrity, and have had no problems doing so until TestFlight -- which appears to modify the executable as well as install it in some funky (undocumented?) way.

Even more concerning is I get multiple hash values, which appear to vary by device or iOS version or carrier or something.  I don't own enough devices to be certain.  But none of the hashes match the one I compute prior to uploading to TestFlight.

So I have two questions: (1) What is TestFlight doing to my executable, and is the process documented somewhere?  And (2) Does the final app store release pull the same shennanigan, or something similar, or does it leave my executable unmodified from when I uploaded it?

答: In addition to d4rk's answer, if you're using Swift, Apple compiles in appropriate bits to optimize your app for each device.</p>


问:
Coding a Javascript Queue
In this problem, I have been asked to write a function nextInLine which takes an array (arr) and a number (item) as arguments. Add the number to the end of the array, then remove the first element of array. The nextInLine function should then return the element that was removed.

Here is the snippet:

```<code>function nextInLine(arr, item) {
  // Your code here

  return item;  // Change this line
}

// Test Setup
var testArr = [1,2,3,4,5];

// Display Code
console.log("Before: " + JSON.stringify(testArr));
console.log(nextInLine(testArr, 6)); // Modify this line to test
console.log("After: " + JSON.stringify(testArr));
</code>```

How to make this code work? Thanks in advance!

答:
Use .shift() to remove and return the first element of an array, and push() to add a new element to the end of the array. In order to make

```<code>nextInLine([], 1)
</code>```

return 1 you need to do the push() before shift()

function nextInLine(arr, item) {
  arr.push(item);
  return arr.shift();
}

// Test Setup
var testArr = [1,2,3,4,5];

// Display Code
console.log("Before: " + JSON.stringify(testArr));
console.log(nextInLine(testArr, 6)); // Modify this line to test
console.log("After: " + JSON.stringify(testArr));

console.log(nextInLine([], 1));```

Title: Coding a Javascript Queue

Body:
In this problem, I have been asked to write a function nextInLine which takes an array (arr) and a number (item) as arguments. Add the number to the end of the array, then remove the first element of array. The nextInLine function should then return the element that was removed.

Here is the snippet:

function nextInLine(arr, item) {
  // Your code here

  return item;  // Change this line
}

// Test Setup
var testArr = [1,2,3,4,5];

// Display Code
console.log("Before: " + JSON.stringify(testArr));
console.log(nextInLine(testArr, 6)); // Modify this line to test
console.log("After: " + JSON.stringify(testArr));

How to make this code work? Thanks in advance!

Body:
Use .shift() to remove and return the first element of an array, and push() to add a new element to the end of the array. In order to make

nextInLine([], 1)

return 1 you need to do the push() before shift()

function nextInLine(arr, item) {
  arr.push(item);
  return arr.shift();
}

// Test Setup
var testArr = [1,2,3,4,5];

// Display Code
console.log("Before: " + JSON.stringify(testArr));
console.log(nextInLine(testArr, 6)); // Modify this line to test
console.log("After: " + JSON.stringify(testArr));

console.log(nextInLine([], 1));


问:
Python Pandas mark all but one specific duplicate row
I have a Pandas dataframe that has already been reduced to duplicates only and sorted.
Duplicates are identified by column "HASH" and then sorted by "HASH" and "SIZE"

```<code>df_out['is_duplicated'] = df.duplicated(['HASH'], keep=False) #keep=False: mark all duplicates as true
df_out = df_out.ix[(df_out['is_duplicated'] == True)] #Keep only duplicate records
df_out = df_out.sort_values(['HASH', 'SIZE'], ascending=[True, False]) #Sort by "HASH", then by "SIZE"
</code>```

Result:

```<code>HASH  SIZE  is_duplicated
1      5     TRUE
1      3     TRUE
1      2     TRUE
9      7     TRUE
9      5     TRUE
</code>```

I would like to add 2 more columns.
First column would identify rows of data with the same "HASH" by an ID.
First set of rows with the same "HASH" would be 1, next set would be 2, etc...

Second column would mark the a single row in each group that has the largest "SIZE"

```<code>HASH  SIZE ID   KEEP
1      5   1    TRUE
1      3   1    FALSE
1      2   1    FALSE
9      7   2    TRUE
9      5   2    FALSE
</code>```

答:
Perhaps use dicts and list comprehension:</p>

```<code>import pandas as pd
df = pd.DataFrame([[1,1,1,9,9],[5,3,2,7,5]]).T
df.columns = ['HASH','SIZE']

hash_dict = dict(zip(df.HASH.unique(),range(1,df.HASH.nunique()+1)))
df['ID'] = [hash_dict[k] for k in df.HASH]

max_dict = dict(df.groupby('HASH')['SIZE'].max())
df['KEEP'] = [True if b==max_dict[a] else False for a,b in zip(df.HASH,df.SIZE)]
</code>```

Body:
I have a Pandas dataframe that has already been reduced to duplicates only and sorted.
Duplicates are identified by column "HASH" and then sorted by "HASH" and "SIZE"

df_out['is_duplicated'] = df.duplicated(['HASH'], keep=False) #keep=False: mark all duplicates as true
df_out = df_out.ix[(df_out['is_duplicated'] == True)] #Keep only duplicate records
df_out = df_out.sort_values(['HASH', 'SIZE'], ascending=[True, False]) #Sort by "HASH", then by "SIZE"

Result:

HASH  SIZE  is_duplicated
1      5     TRUE
1      3     TRUE
1      2     TRUE
9      7     TRUE
9      5     TRUE

I would like to add 2 more columns.
First column would identify rows of data with the same "HASH" by an ID.
First set of rows with the same "HASH" would be 1, next set would be 2, etc...

Second column would mark the a single row in each group that has the largest "SIZE"

HASH  SIZE ID   KEEP
1      5   1    TRUE
1      3   1    FALSE
1      2   1    FALSE
9      7   2    TRUE
9      5   2    FALSE

Body:
Perhaps use dicts and list comprehension:

import pandas as pd
df = pd.DataFrame([[1,1,1,9,9],[5,3,2,7,5]]).T
df.columns = ['HASH','SIZE']

hash_dict = dict(zip(df.HASH.unique(),range(1,df.HASH.nunique()+1)))
df['ID'] = [hash_dict[k] for k in df.HASH]

max_dict = dict(df.groupby('HASH')['SIZE'].max())
df['KEEP'] = [True if b==max_dict[a] else False for a,b in zip(df.HASH,df.SIZE)]


问:
Updating A Program's Directory
I have a program that uses forms.  The forms are pointing to files in c:\filepath1 as set forth in main.prg (set defa, set path).   I make a test copy of the files, change the path in main.prg, the forms are still referencing the files in the old path.  I don't want to have to recreate all the data environments in all the forms.  How can I avoid doing so?  Any help on this would be kindly appreciated.

Missy.

答: I ended up renaming the default path then going through all the screens in the program then recompiling.  Thank you for your help.  I did understand it and is probably another good solution.</p>

Title: Updating A Program's Directory


问:
Timing Format in Flex "24-hour clock" and "12-hour clock"
Kindly guide me.

Timing Format in Flex "24-hour clock" and "12-hour clock"

if "24-hour clock" Button is selected, the control should convert times to 24 hour
clock time.  For example, if 3:45 p.m. is entered, it should be converted to
15:45.

if "12-hour clock" Button is selected, the control should convert times to 12 hour
clock time.  For example, if 15:45 p.m. is entered, it should be converted to
3:45.

Thanks in Advance

Amit pathak

答:
```<code>list($hh,$mm,$ss) = explode(":",$time);
if($hh>12)
{
  $hh = $hh-12;
  $ampm = 'pm';
}
else
{
  $ampm = 'am';
}
$newcall_time = $hh.":".$mm.$ampm;
</code>```

ContentLicense: CC BY-SA 2.5


问:
Optimize a algorithm that find a specific Fibonacci number

Given an number A, I want to find the Ath Fibonacci number
  that is multiple of 3 or if the number representation has at least a 3
  on it.

Example:

Fibonacci > 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, ...

Input: 1, Output: 3;

3 is the first Fibonacci number that is multiple of 3 or has an 3 on
  it.

Input: 3, Output: 21;

21 is the third Fibonacci number that is multiple of 3 or has an 3 on
  it.

Edit: Variable type changed to unsigned long long int and ajust on Fibonacci generator. Thanks @rcgldr and @Jarod42 for the help!

My code:

```<code>#include<bits/stdc++.h>

using namespace std;

int tem(unsigned long long int i){

    while(i != 0){
        if(i%10 == 3){
            return true;
        }
        i = i/10;
    }
    return false;
}

int main(){

    int a, count = 0;
    unsigned long long int f1 = 1, f2 = 1;

    while(scanf("%d", &a) != EOF){
        for(unsigned long long int i = 2; i > 0; i++){
            i = f1 + f2;
            f1 = f2;
            f2 = i;
                if((i%3 == 0) || tem(i)){
                    count++;
                    if(count == a){
                        cout << i << endl;
                        break;
                    }
                }

        }
    }
}
</code>```

When A > 20, it starts to slow down. Makes sense because it tends to be exponecial. My code is not very efficient, but I didn't find an better logic to use.

I looked into these links, but didn't find an conclusion:

1 - Recursive Fibonacci

2 - Fibonacci Optimization

Any ideas? Thanks for the help!

答:
You can speed up the Fibonacci part using this sequence

```<code>uint64_t f0 = 0;    // fib( 0)
uint64_t f1 = 1;    // fib(-1)
int n = ... ;       // generate fib(n)
    for(int i = 0; i < n; i++){
        std::swap(f0,f1);
        f0 += f1;
    }
</code>```

Note Fib(93) is the maximum Fibonacci number that fits in a 64 bit unsigned integer, it also has a 3 in it. Fib(92) is the maximum Fibonacci number that is a multiple of 3.

I used this example code to find all of the values (a ranges from 0 to 62), it seems to run fairly fast, so I'm not sure what the issue is. Is optimization enabled?

```<code>#include <iostream>
#include <iomanip>

typedef unsigned long long uint64_t;

int tem(uint64_t i){
    while(i != 0){
        if(i%10 == 3)
            return true;
        i = i/10;
    }
    return false;
}

int main(){
    int a = 0, n;
    uint64_t f0 = 1, f1 = -1;  // fib(-1), fib(-2)

    for(n = 0; n <= 93; n++){
        std::swap(f0, f1);     // f0 = next fib
        f0 += f1;
        if((n&3) == 0 || tem(f0)){
            std::cout << std::setw( 2) << a << " "
                      << std::setw( 2) << n << " "
                      << std::setw(20) << f0 << std::endl;
            a++;
        }
    }
    return 0;
}
</code>```

Depending on the compiler, i%10 and i/10 may use a multiply by "magic number" and shift to replace divide by a constant. Code generated by Visual Studio 2015 for tem(), which is fairly "clever":

```<code>tem     proc                                ;rcx = input
        test    rcx,rcx                     ; return false if rcx == 0
        je      SHORT tem1
        mov     r8, 0cccccccccccccccdh      ;magic number for divide by 10
tem0:   mov     rax, r8                     ;rax = magic number
        mul     rcx                         ;rdx = quotient << 3
        shr     rdx, 3                      ;rdx = quotient
        lea     rax, QWORD PTR [rdx+rdx*4]  ;rax = quotient*5
        add     rax, rax                    ;rax = quotient*10
        sub     rcx, rax                    ;rcx -= quotient * 10 == rcx % 10
        cmp     rcx, 3                      ;br if rcx % 10 == 3
        je      SHORT tem2
        mov     rcx, rdx                    ;rcx = quotient  (rcx /= 10)
        test    rdx, rdx                    ;loop if quotient != 0
        jne     SHORT tem0
tem1:   xor     eax, eax                    ;return false
        ret     0

tem2:   mov     eax, 1                      ;return true
        ret     0

tem     endp
</code>```

Body:
Given an number A, I want to find the Ath Fibonacci number
  that is multiple of 3 or if the number representation has at least a 3
  on it.

Example:

Fibonacci > 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, ...

Input: 1, Output: 3;

3 is the first Fibonacci number that is multiple of 3 or has an 3 on
  it.

Input: 3, Output: 21;

21 is the third Fibonacci number that is multiple of 3 or has an 3 on
  it.

Edit: Variable type changed to unsigned long long int and ajust on Fibonacci generator. Thanks @rcgldr and @Jarod42 for the help!

My code:

#include<bits/stdc++.h>

using namespace std;

int tem(unsigned long long int i){

    while(i != 0){
        if(i%10 == 3){
            return true;
        }
        i = i/10;
    }
    return false;
}

int main(){

    int a, count = 0;
    unsigned long long int f1 = 1, f2 = 1;

    while(scanf("%d", &a) != EOF){
        for(unsigned long long int i = 2; i > 0; i++){
            i = f1 + f2;
            f1 = f2;
            f2 = i;
                if((i%3 == 0) || tem(i)){
                    count++;
                    if(count == a){
                        cout << i << endl;
                        break;
                    }
                }

        }
    }
}

When A > 20, it starts to slow down. Makes sense because it tends to be exponecial. My code is not very efficient, but I didn't find an better logic to use.

I looked into these links, but didn't find an conclusion:

1 - Recursive Fibonacci

2 - Fibonacci Optimization

Any ideas? Thanks for the help!

Body:
You can speed up the Fibonacci part using this sequence

uint64_t f0 = 0;    // fib( 0)
uint64_t f1 = 1;    // fib(-1)
int n = ... ;       // generate fib(n)
    for(int i = 0; i < n; i++){
        std::swap(f0,f1);
        f0 += f1;
    }

Note Fib(93) is the maximum Fibonacci number that fits in a 64 bit unsigned integer, it also has a 3 in it. Fib(92) is the maximum Fibonacci number that is a multiple of 3.

I used this example code to find all of the values (a ranges from 0 to 62), it seems to run fairly fast, so I'm not sure what the issue is. Is optimization enabled?

#include <iostream>
#include <iomanip>

typedef unsigned long long uint64_t;

int tem(uint64_t i){
    while(i != 0){
        if(i%10 == 3)
            return true;
        i = i/10;
    }
    return false;
}

int main(){
    int a = 0, n;
    uint64_t f0 = 1, f1 = -1;  // fib(-1), fib(-2)

    for(n = 0; n <= 93; n++){
        std::swap(f0, f1);     // f0 = next fib
        f0 += f1;
        if((n&3) == 0 || tem(f0)){
            std::cout << std::setw( 2) << a << " "
                      << std::setw( 2) << n << " "
                      << std::setw(20) << f0 << std::endl;
            a++;
        }
    }
    return 0;
}

Depending on the compiler, i%10 and i/10 may use a multiply by "magic number" and shift to replace divide by a constant. Code generated by Visual Studio 2015 for tem(), which is fairly "clever":

tem     proc                                ;rcx = input
        test    rcx,rcx                     ; return false if rcx == 0
        je      SHORT tem1
        mov     r8, 0cccccccccccccccdh      ;magic number for divide by 10
tem0:   mov     rax, r8                     ;rax = magic number
        mul     rcx                         ;rdx = quotient << 3
        shr     rdx, 3                      ;rdx = quotient
        lea     rax, QWORD PTR [rdx+rdx*4]  ;rax = quotient*5
        add     rax, rax                    ;rax = quotient*10
        sub     rcx, rax                    ;rcx -= quotient * 10 == rcx % 10
        cmp     rcx, 3                      ;br if rcx % 10 == 3
        je      SHORT tem2
        mov     rcx, rdx                    ;rcx = quotient  (rcx /= 10)
        test    rdx, rdx                    ;loop if quotient != 0
        jne     SHORT tem0
tem1:   xor     eax, eax                    ;return false
        ret     0

tem2:   mov     eax, 1                      ;return true
        ret     0

tem     endp


问:
Can't Move a dynamically created nested div from one div to another div
I have created some dynamic div based on an input inside a parent div.

Now what I want to do is that if I click one of those created divs, it should move to other parent div and vice versa.

My code:

```<code>/*Html code*/

<input type="text" id="txtName" />
<input type="button" value="ok" id="btnSave" />
<div id="firstDiv">
<div id="1" class="a">Value</div>(Working over statically created div  )
</div>
<br>
--------------
--------------
-------------
<br>
<div id="SecondDiv">
<div id="4" class="b">
</div>
</div>
</code>```

And JavaScript code:

```<code>  $(document).ready(function() {
  $('#btnSave').click(function() {
  addDiv($('#txtName').val());
  $('#txtName').val('');
  });
  $("div.a").on("click", function() {
  var $this = $(this);
 if ($this.hasClass("a")) {
    $this.removeClass("a").addClass("b").prependTo("#firstDiv");
 } else {
    $this.removeClass("b").addClass("a").prependTo("#SecondDiv");
 }
 });

});

function addDiv(name) {
var container = $('#firstDiv ');
$('<div />', {class:'a',text:name }).appendTo(container).after("<br/>");
}
</code>```

But the code is only working over already created div. I tested this, but it is not working for dynamically created div.

All I want is that I can create child div dynamically and move it to another div when clicked.

A Sample Fiddle is also added

答:
Try:

$(document).ready(function() {
        $('#btnSave').click(function() {
            addDiv($('#txtName').val());
            $('#txtName').val('');
        });
         allowToggleDivLocation("div.a");
    });

    function allowToggleDivLocation(a){
        $(a).on("click", function() {
            var $this = $(this);
            if ($this.hasClass("a")) {
                $this.removeClass("a").addClass("b").prependTo("#firstDiv");
            } else {
                $this.removeClass("b").addClass("a").prependTo("#SecondDiv");
            }
        });
    }

    function addDiv(name) {
        var container = $('#firstDiv '),
            c = $('
', {class:'a',text:name });
        allowToggleDivLocation(c);
        c.appendTo(container).after("
");
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="txtName" />
<input type="button" value="ok" id="btnSave" />
<div id="firstDiv">
<div id="1" class="a">Value</div>(Working over statically created div  )
</div>
<br>
--------------
--------------
-------------
<br>
<div id="SecondDiv">
<div id="4" class="b">
</div>
</div></code>```

Didn't get to test it, but it should work.

$(document).ready(function() {
        $('#btnSave').click(function() {
            addDiv($('#txtName').val());
            $('#txtName').val('');
        });
         allowToggleDivLocation("div.a");
    });

    function allowToggleDivLocation(a){
        $(a).on("click", function() {
            var $this = $(this);
            if ($this.hasClass("a")) {
                $this.removeClass("a").addClass("b").prependTo("#firstDiv");
            } else {
                $this.removeClass("b").addClass("a").prependTo("#SecondDiv");
            }
        });
    }

    function addDiv(name) {
        var container = $('#firstDiv '),
            c = $('
', {class:'a',text:name });
        allowToggleDivLocation(c);
        c.appendTo(container).after("
");
    }```
</div>
</div>
</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="text" id="txtName" />
<input type="button" value="ok" id="btnSave" />
<div id="firstDiv">
<div id="1" class="a">Value</div>(Working over statically created div  )
</div>
<br>
--------------
--------------
-------------
<br>
<div id="SecondDiv">
<div id="4" class="b">
</div>
</div></code>```

Body:
I have created some dynamic div based on an input inside a parent div.

Now what I want to do is that if I click one of those created divs, it should move to other parent div and vice versa.

My code:

/*Html code*/

<input type="text" id="txtName" />
<input type="button" value="ok" id="btnSave" />

Value
(Working over statically created div  )

--------------
--------------
-------------

And JavaScript code:

  $(document).ready(function() {
  $('#btnSave').click(function() {
  addDiv($('#txtName').val());
  $('#txtName').val('');
  });
  $("div.a").on("click", function() {
  var $this = $(this);
 if ($this.hasClass("a")) {
    $this.removeClass("a").addClass("b").prependTo("#firstDiv");
 } else {
    $this.removeClass("b").addClass("a").prependTo("#SecondDiv");
 }
 });

});

function addDiv(name) {
var container = $('#firstDiv ');
$('
', {class:'a',text:name }).appendTo(container).after("
");
}

But the code is only working over already created div. I tested this, but it is not working for dynamically created div.

All I want is that I can create child div dynamically and move it to another div when clicked.

A Sample Fiddle is also added

Body:
Try:

$(document).ready(function() {
        $('#btnSave').click(function() {
            addDiv($('#txtName').val());
            $('#txtName').val('');
        });
         allowToggleDivLocation("div.a");
    });

    function allowToggleDivLocation(a){
        $(a).on("click", function() {
            var $this = $(this);
            if ($this.hasClass("a")) {
                $this.removeClass("a").addClass("b").prependTo("#firstDiv");
            } else {
                $this.removeClass("b").addClass("a").prependTo("#SecondDiv");
            }
        });
    }

    function addDiv(name) {
        var container = $('#firstDiv '),
            c = $('<div />', {class:'a',text:name });
        allowToggleDivLocation(c);
        c.appendTo(container).after("<br/>");
    }

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="txtName" />
<input type="button" value="ok" id="btnSave" />
<div id="firstDiv">
<div id="1" class="a">Value</div>(Working over statically created div  )
</div>
<br>
--------------
--------------
-------------
<br>
<div id="SecondDiv">
<div id="4" class="b">
</div>
</div>

Didn't get to test it, but it should work.

$(document).ready(function() {
        $('#btnSave').click(function() {
            addDiv($('#txtName').val());
            $('#txtName').val('');
        });
         allowToggleDivLocation("div.a");
    });

    function allowToggleDivLocation(a){
        $(a).on("click", function() {
            var $this = $(this);
            if ($this.hasClass("a")) {
                $this.removeClass("a").addClass("b").prependTo("#firstDiv");
            } else {
                $this.removeClass("b").addClass("a").prependTo("#SecondDiv");
            }
        });
    }

    function addDiv(name) {
        var container = $('#firstDiv '),
            c = $('<div />', {class:'a',text:name });
        allowToggleDivLocation(c);
        c.appendTo(container).after("<br/>");
    }

<input type="text" id="txtName" />
<input type="button" value="ok" id="btnSave" />
<div id="firstDiv">
<div id="1" class="a">Value</div>(Working over statically created div  )
</div>
<br>
--------------
--------------
-------------
<br>
<div id="SecondDiv">
<div id="4" class="b">
</div>
</div>


问:
scala reflection
I want to create a hashmap to store parameters names and their values. The parameters however are with different types. I could use HashMap[String, Any], but I wouldn't know which types they are later on.  Is there anyway I can recovery the type information? Or is there any better way to store  pair?</p>

答: See this, which implements exactly what you ask for.</p>

Title: scala reflection


问:
scrapyd deploy shows 0 spiders by scrapyd-client
I found that my problem is very similar to scrapyd deploy shows 0 spiders. I also tried the accepted answer several times, but it doesn't work for me, so I come for some help.

The project directory is timediff_crawler, and tree view of the directory is:

```<code>timediff_crawler/
├── scrapy.cfg
├── scrapyd-deploy
├── timediff_crawler
│   ├── __init__.py
│   ├── items.py
│   ├── pipelines.py
│   ├── settings.py
│   ├── spiders
│   │   ├── __init__.py
│   │   ├── prod
│   │   │   ├── __init__.py
│   │   │   ├── job
│   │   │   │   ├── __init__.py
│   │   │   │   ├── zhuopin.py
│   │   │   ├── rent
│   │   │   │   ├── australia_rent.py
│   │   │   │   ├── canada_rent.py
│   │   │   │   ├── germany_rent.py
│   │   │   │   ├── __init__.py
│   │   │   │   ├── korea_rent.py
│   │   │   │   ├── singapore_rent.py
...
</code>```

1.1 start scrapyd, it's ok

```<code>(crawl_env)web@ha-2:/opt/crawler$ scrapyd
2015-11-11 15:00:37+0800 [-] Log opened.
2015-11-11 15:00:37+0800 [-] twistd 15.4.0 (/opt/crawler/crawl_env/bin/python 2.7.6) starting up.
2015-11-11 15:00:37+0800 [-] reactor class: twisted.internet.epollreactor.EPollReactor.
2015-11-11 15:00:37+0800 [-] Site starting on 6800
...
</code>```

1.2 edit scrapy.cfg

```<code>[settings]
default = timediff_crawler.settings

[deploy:ha2-crawl]
url = http://localhost:6800/
project = timediff_crawler
</code>```

1.3 deploy the project

```<code>(crawl_env)web@ha-2:/opt/crawler/timediff_crawler$ ./scrapyd-deploy -l
ha2-crawl            http://localhost:6800/

(crawl_env)web@ha-2:/opt/crawler/timediff_crawler$ ./scrapyd-deploy ha2-crawl -p timediff_crawler
Packing version 1447229952
Deploying to project "timediff_crawler" in http://localhost:6800/addversion.json
Server response (200):
{"status": "ok", "project": "timediff_crawler", "version": "1447229952", "spiders": 0, "node_name": "ha-2"}
</code>```

1.4 the problem

The response shows that the number of spiders is 0, actually I have about 10 spiders.

I followed the advice in this post scrapyd deploy shows 0 spiders, delete all projects, versions, directories(include build/ eggs/ project.egg-info setup.py) and try to deploy again, but it doesn't work, the number of spiders is always 0.

I validate the egg file, the output shows it seems ok:

```<code>(crawl_env)web@ha-2:/opt/crawler/timediff_crawler/eggs/timediff_crawler$ unzip -t 1447229952.egg
Archive:  1447229952.egg

testing: timediff_crawler/pipelines.py   OK
testing: timediff_crawler/__init__.py   OK
testing: timediff_crawler/items.py   OK
testing: timediff_crawler/spiders/prod/job/zhuopin.py   OK
testing: timediff_crawler/spiders/prod/rent/singapore_rent.py   OK
testing: timediff_crawler/spiders/prod/rent/australia_rent.py   OK
...
</code>```

So I don't know what's going wrong, please help and thanks in advance!

答:
Development environment is different than production. Scrapyd can not find other classes. Try to move related classes or modules under spider folder. Then give correct references again.

For defining a problematic reference you can try to comment out the references one by one and try scrapy-deploy

├── Myapp

│   └── spider

│       ├── bbc_spider.py

│── Model.py

At the development environment this works but after deploy by scrapyd it may not. Because   bbc_spider.py can not reach to model.py  .
If you will, move the model.py under to spider folder. I solved problem like that.

Body:
I found that my problem is very similar to scrapyd deploy shows 0 spiders. I also tried the accepted answer several times, but it doesn't work for me, so I come for some help.

The project directory is timediff_crawler, and tree view of the directory is:

timediff_crawler/
├── scrapy.cfg
├── scrapyd-deploy
├── timediff_crawler
│   ├── __init__.py
│   ├── items.py
│   ├── pipelines.py
│   ├── settings.py
│   ├── spiders
│   │   ├── __init__.py
│   │   ├── prod
│   │   │   ├── __init__.py
│   │   │   ├── job
│   │   │   │   ├── __init__.py
│   │   │   │   ├── zhuopin.py
│   │   │   ├── rent
│   │   │   │   ├── australia_rent.py
│   │   │   │   ├── canada_rent.py
│   │   │   │   ├── germany_rent.py
│   │   │   │   ├── __init__.py
│   │   │   │   ├── korea_rent.py
│   │   │   │   ├── singapore_rent.py
...

1.1 start scrapyd, it's ok

(crawl_env)web@ha-2:/opt/crawler$ scrapyd
2015-11-11 15:00:37+0800 [-] Log opened.
2015-11-11 15:00:37+0800 [-] twistd 15.4.0 (/opt/crawler/crawl_env/bin/python 2.7.6) starting up.
2015-11-11 15:00:37+0800 [-] reactor class: twisted.internet.epollreactor.EPollReactor.
2015-11-11 15:00:37+0800 [-] Site starting on 6800
...

1.2 edit scrapy.cfg

[settings]
default = timediff_crawler.settings

[deploy:ha2-crawl]
url = http://localhost:6800/
project = timediff_crawler

1.3 deploy the project

(crawl_env)web@ha-2:/opt/crawler/timediff_crawler$ ./scrapyd-deploy -l
ha2-crawl            http://localhost:6800/

(crawl_env)web@ha-2:/opt/crawler/timediff_crawler$ ./scrapyd-deploy ha2-crawl -p timediff_crawler
Packing version 1447229952
Deploying to project "timediff_crawler" in http://localhost:6800/addversion.json
Server response (200):
{"status": "ok", "project": "timediff_crawler", "version": "1447229952", "spiders": 0, "node_name": "ha-2"}

1.4 the problem

The response shows that the number of spiders is 0, actually I have about 10 spiders.

I followed the advice in this post scrapyd deploy shows 0 spiders, delete all projects, versions, directories(include build/ eggs/ project.egg-info setup.py) and try to deploy again, but it doesn't work, the number of spiders is always 0.

I validate the egg file, the output shows it seems ok:

(crawl_env)web@ha-2:/opt/crawler/timediff_crawler/eggs/timediff_crawler$ unzip -t 1447229952.egg
Archive:  1447229952.egg

testing: timediff_crawler/pipelines.py   OK
testing: timediff_crawler/__init__.py   OK
testing: timediff_crawler/items.py   OK
testing: timediff_crawler/spiders/prod/job/zhuopin.py   OK
testing: timediff_crawler/spiders/prod/rent/singapore_rent.py   OK
testing: timediff_crawler/spiders/prod/rent/australia_rent.py   OK
...

So I don't know what's going wrong, please help and thanks in advance!


问:
Is there a Stream Wrapping component that edits streams? C#
I would like to replace some text in a NetworkStream. Ideally by using a Regex to find what I want to replace. The consuming part takes a Stream and I would not like to modify it.

I image something like this?

```<code>Stream outputStream = new StreamChanger(inputStream, "apple", "banana");
</code>```

Is there an existing component or pattern which can do this?

答:
You will probably need to roll your own...some pseudocode:

var changedString = inputStream.read();
changedString = changedString.replace("apple", "banana");

Stream outputStream = new StreamWriter(path);
outputStream.Write(changedString);

Body:
I would like to replace some text in a NetworkStream. Ideally by using a Regex to find what I want to replace. The consuming part takes a Stream and I would not like to modify it.

I image something like this?

Stream outputStream = new StreamChanger(inputStream, "apple", "banana");

Is there an existing component or pattern which can do this?


问:
How to find .tpl file of navbar
I am struggling to find the file of my prestashop page navigation bar.

Code snippet example

I need to delete the title tag and after two hours of searching i failed. anybody have any ideas ?

EDIT

To clarify it: I need to remove the span title appearing after hovering category on my side navigation block on homepage. Picture:
Side nav block

答:
Please find the root/themes/your_current_themes folder.

or

Please find the root/modules/ folder. May be you can find this.

You can use any search tools: such as grepwin or any others.

Title: How to find .tpl file of navbar


问:
Spring MVC @Controller to intercept own requests
Imagine we have a controller like this:

```<code>@RestController
@RequestMapping("/{parameter}")
public class MyController {

    @ExceptionHandler(SomeException.class)
    public Object handleSomeException() { /* handle */ }

    @RequestMapping("/something")
    public Object handleSomething(@PathVariable("parameter") String parameter) {
        /* handle */
    }

    @RequestMapping("/somethingElse")
    public Object handleSomethingElse(@PathVariable("parameter") String parameter) {
        /* handle */
    }
}
</code>```

The question is, how to implement some common pre-\post-handling for this particular controller in similar way as @ExceptionHandler is working? E.g. I want to have a method in controller which receives request prior to handler methods, but only requests for this particular controller.

I'm aware of RequestBodyAdvice and ResponseBodyAdvice interfaces, but want something local to controller.

As a usage example - I want to do some validation for common parameter variable before each handler.

答:
As you want to handle the path variable in a common way, think about introducing a model object. With this you can validate the attribute (java bean validation) and also mix path variables and query parameters (a very simple example here, you can even create custom validations):

```<code>@Data
class SomeModel {
  @NotEmpty
  private String parameter;
}
</code>```

In the controller you simply have to add the model as a parameter:

```<code>@RequestMapping("/something")
public Object handleSomething(@Valid SomeModel model) {
  /* handle using model.getParameter() */
}
</code>```

Body:
Imagine we have a controller like this:

@RestController
@RequestMapping("/{parameter}")
public class MyController {

    @ExceptionHandler(SomeException.class)
    public Object handleSomeException() { /* handle */ }

    @RequestMapping("/something")
    public Object handleSomething(@PathVariable("parameter") String parameter) {
        /* handle */
    }

    @RequestMapping("/somethingElse")
    public Object handleSomethingElse(@PathVariable("parameter") String parameter) {
        /* handle */
    }
}

The question is, how to implement some common pre-\post-handling for this particular controller in similar way as @ExceptionHandler is working? E.g. I want to have a method in controller which receives request prior to handler methods, but only requests for this particular controller.

I'm aware of RequestBodyAdvice and ResponseBodyAdvice interfaces, but want something local to controller.

As a usage example - I want to do some validation for common parameter variable before each handler.

Body:
As you want to handle the path variable in a common way, think about introducing a model object. With this you can validate the attribute (java bean validation) and also mix path variables and query parameters (a very simple example here, you can even create custom validations):

@Data
class SomeModel {
  @NotEmpty
  private String parameter;
}

In the controller you simply have to add the model as a parameter:

@RequestMapping("/something")
public Object handleSomething(@Valid SomeModel model) {
  /* handle using model.getParameter() */
}


问:
Android SDK missing in Intellij Idea Community After installation
I am not able to resolve the error of Android SDK missing in Intellij-idea i tried as instructions mentioned in the image also i searched it on google and also tried some methods of stack overflow but it's still not resolved so please if anyone know then suggest the solution for it...enter image description here

答:
This post (How do I set up IntelliJ IDEA for Android applications?) helped me, but had to download Android Studio and install the tools through the wizard when first launching the program.

Then I started IntelliJ and created a new project (not Android) and went to File>Project Structure and added a new Android SDK under SDKs. You have to choose the path to the SDK int the finder. To do this make sure Library is visible (see here: http://www.macworld.com/article/2057221/how-to-view-the-library-folder-in-mavericks.html) and go to Libraries>Android and choose to open SDK. After that I no longer had the problem of not finding the SDK when creating a New Android Project.


问:
Multidimensional Arrays Nested to Unlimited Depth
I have a multidimensional array nested to an unknown/unlimited depth.
I'd like to be able to loop through every element.
I don't want to use, foreach(){foreach(){foreach(){}}} as I don't know the depth.

I'm eventually looking for all nested arrays called "xyz".  Has anyone got any suggestions?

答:
Using the comments above, I've found the answer:

```<code>function findXyz($array){
    foreach($array as $foo=>$bar){
      if (is_array($bar)){
         if ($bar["xyz"]){
             echo "<br />The array of xyz has now been found";
             print_r($bar['xyz']);
         }else{
            findXyz($bar);
         }
      }
    }
}
findXyz($myarray);
</code>```

This loops through all nested arrays and looks for any element who has a sub-array of xyz, as per my original request. array_walk_array and RecursiveIteratorIterator were unable to achieve this.

Body:
Using the comments above, I've found the answer:

function findXyz($array){
    foreach($array as $foo=>$bar){
      if (is_array($bar)){
         if ($bar["xyz"]){
             echo "<br />The array of xyz has now been found";
             print_r($bar['xyz']);
         }else{
            findXyz($bar);
         }
      }
    }
}
findXyz($myarray);

This loops through all nested arrays and looks for any element who has a sub-array of xyz, as per my original request. array_walk_array and RecursiveIteratorIterator were unable to achieve this.


问:
How do I find the parameters/schema for a DSC Resource? Using my configuration says one is undefined
I'm writing a DSC Pull Server script to generate a MOF file. The xDSCWebService resource requires a boolean for the value UseSecurityBestPractices which I have defined. However, running the script then generates an error: "Undefined Property UseSecurityBestPractices".

As you can probably tell, I'm fairly new to the Powershell world and especially to DSC.

Link to picture of error message

Any ideas?

```<code>Configuration NewPullServer
{
$ComputerName = 'localhost'
Import-DscResource -ModuleName PSDesiredStateConfiguration
Import-DscResource -Name xDSCWebService

Node $ComputerName
{
    WindowsFeature DSCServiceFeature
    {
        Ensure = "Present"
        Name = "DSC-Service"
    }

    xDscWebService PSDSCPullServer
    {
        Ensure = "Present"
        UseSecurityBestPractices = $True
        EndpointName = "PSDSCPullServer"
        Port = 8080
        PhysicalPath = "$env:SystemDrive\inetpub\wwwroot\PSDSCPullServer"
        CertificateThumbprint = "AllowUnencryptedTraffic"
        ModulePath = "$env:PROGRAMFILES\WindowsPowershell\DscService\Modules"
        ConfigurationPath = "$env:PROGRAMFILES\WindowsPowershell\DscService\Configuration"
        State = "Started"
        DependsOn = "[WindowsFeature]DSCServiceFeature"
    }

    xDscWebService PSDSCComplianceServer
    {
        Ensure = "Present"
        EndpointName = "PSDSCComplianceServer"
        Port = 9080
        PhysicalPath = "$env:SystemDrive\inetpub\wwwroot\PSDSCComplianceServer"
        CertificateThumbprint = "AllowUnencryptedTraffic"
        State = "Started"
        UseSecurityBestPractices = $True
        DependsOn = ("[WindowsFeature]DSCServiceFeature","[xDSCWebService]PSDSCPullServer")
    }
}
}

NewPullServer
Start-DscConfiguration ./NewPullServer -Wait -verbose
</code>```

答:
The UseSecurityBestPractices parameter is not available on your resource.

The MSFT_xDSCWebService is available in xPSDesiredStateConfiguration from https://gallery.technet.microsoft.com/xPSDesiredStateConfiguratio-417dc71d.

Downloading and opening the zip, you'll find the definition of the resource in xPSDesiredStateConfiguration_3.0.3.4.zip\xPSDesiredStateConfiguration\DSCResources\MSFT_xDSCWebService, and its parameter schema in MSFT_xDSCWebService.Schema.mof.

The available parameters are:

```<code>[ClassVersion("1.0.0"), FriendlyName("xDSCWebService")]
class MSFT_xDSCWebService : OMI_BaseResource
{
  [Key] string EndpointName;
  [required] string CertificateThumbPrint;
  [write] uint32 Port;
  [write] string PhysicalPath;
  [write,ValueMap{"Present", "Absent"},Values{"Present", "Absent"}] string Ensure;
  [write,ValueMap{"Started","Stopped"},Values{"Started", "Stopped"}] string State;
  [write] string ModulePath;
  [write] string ConfigurationPath;
  [write] boolean IsComplianceServer;
  [read] string DSCServerUrl;
};
</code>```

Body:
I'm writing a DSC Pull Server script to generate a MOF file. The xDSCWebService resource requires a boolean for the value UseSecurityBestPractices which I have defined. However, running the script then generates an error: "Undefined Property UseSecurityBestPractices".

As you can probably tell, I'm fairly new to the Powershell world and especially to DSC.

Link to picture of error message

Any ideas?

Configuration NewPullServer
{
$ComputerName = 'localhost'
Import-DscResource -ModuleName PSDesiredStateConfiguration
Import-DscResource -Name xDSCWebService

Node $ComputerName
{
    WindowsFeature DSCServiceFeature
    {
        Ensure = "Present"
        Name = "DSC-Service"
    }

    xDscWebService PSDSCPullServer
    {
        Ensure = "Present"
        UseSecurityBestPractices = $True
        EndpointName = "PSDSCPullServer"
        Port = 8080
        PhysicalPath = "$env:SystemDrive\inetpub\wwwroot\PSDSCPullServer"
        CertificateThumbprint = "AllowUnencryptedTraffic"
        ModulePath = "$env:PROGRAMFILES\WindowsPowershell\DscService\Modules"
        ConfigurationPath = "$env:PROGRAMFILES\WindowsPowershell\DscService\Configuration"
        State = "Started"
        DependsOn = "[WindowsFeature]DSCServiceFeature"
    }

    xDscWebService PSDSCComplianceServer
    {
        Ensure = "Present"
        EndpointName = "PSDSCComplianceServer"
        Port = 9080
        PhysicalPath = "$env:SystemDrive\inetpub\wwwroot\PSDSCComplianceServer"
        CertificateThumbprint = "AllowUnencryptedTraffic"
        State = "Started"
        UseSecurityBestPractices = $True
        DependsOn = ("[WindowsFeature]DSCServiceFeature","[xDSCWebService]PSDSCPullServer")
    }
}
}

NewPullServer
Start-DscConfiguration ./NewPullServer -Wait -verbose

Body:
The UseSecurityBestPractices parameter is not available on your resource.

The MSFT_xDSCWebService is available in xPSDesiredStateConfiguration from https://gallery.technet.microsoft.com/xPSDesiredStateConfiguratio-417dc71d.

Downloading and opening the zip, you'll find the definition of the resource in xPSDesiredStateConfiguration_3.0.3.4.zip\xPSDesiredStateConfiguration\DSCResources\MSFT_xDSCWebService, and its parameter schema in MSFT_xDSCWebService.Schema.mof.

The available parameters are:

[ClassVersion("1.0.0"), FriendlyName("xDSCWebService")]
class MSFT_xDSCWebService : OMI_BaseResource
{
  [Key] string EndpointName;
  [required] string CertificateThumbPrint;
  [write] uint32 Port;
  [write] string PhysicalPath;
  [write,ValueMap{"Present", "Absent"},Values{"Present", "Absent"}] string Ensure;
  [write,ValueMap{"Started","Stopped"},Values{"Started", "Stopped"}] string State;
  [write] string ModulePath;
  [write] string ConfigurationPath;
  [write] boolean IsComplianceServer;
  [read] string DSCServerUrl;
};


问:
Logging exceptions in asp.net core / kestrel
The docs show how to set a page for when an exception occurs: https://learn.microsoft.com/en-us/aspnet/core/fundamentals/error-handling

But how do I record the details of the exception in a log file on my server?

Does kestrel log exceptions and errors anywhere by default or do I have to do this manually?

Are there any examples or documentation available?

答:
Yes, ASP.NET core has the built-in logging, but it does not provide the ability to log to file directly. Instead, you need to use 3-rd party libraries.
 The good news is that all three most common logging libraries are available already for .NET Core as nuget packages: NLog, Serilog and log4net.

This article has a good overview over them and provides how-to-use examples: ASP.NET Core Logging Tutorial – What Still Works and What Changed?.

Then I suggest looking into samples in aspnet/Diagnostics repo. It shows how to custom or built-in error Middleware, ExceptionHandler.


问:
change loss function during training
Suppose my loss function is of the following form:

loss = a*loss_1 + (1-a)*loss_2

Suppose also I am training for 100 steps.  How can I dynamically change the loss function in tensorflow so that I gradually change "a" from 1 to 0 during the 100 steps of training?

To be precise, I want my loss to be
 loss = 1*loss_1+0*loss_2 = loss_1
at the beginning of training (at step 1)

and

loss = 0*loss_1+1*loss_2 = loss_2 at the end (step 100)

with some kind of gradual (doesn't have to be continuous) decrease in between.

答: Assuming that the value of a does not depend on the computation done at the current step, create a placeholder for a then pass the value you want using the feed dictionary.

Title: change loss function during training


问:
Very slow Apache on Windows 7
The simplest script:

```<code><?php echo 'hello';
</code>```

Takes about 3 seconds to execute. There seems to be a big time interval Apache waits until it serves a web page.

I tried turning off antivirus, disabling ipv6 and more but Apache is still very slow. What should I do?

EDIT:

Additional information:

Apache 2.2

PHP 5.2

It's only dynamic PHP files. Static files (html) are served instantly

It has nothing to do with system specs, it's new PC

There are few PHP notices in Apache error log:

```<code>[Thu Jul 01 08:37:21 2010] [error] [client 127.0.0.1] PHP Notice:  Undefined variable: ref in D:\\data\\o\\WebProjects\\elearning\\application\\modules\\clientarea\\controllers\\ViewController.php on line 578, referer: http://elearning/clientarea/view/course/teid/1/cid/1
</code>```

答: The only thing helped me is un-ticking box 'register this connection's addresses in dns' in ipv4 parameters of the network adapter, button under DNS settings -> lower two checkboxes. </p>

Title: Very slow Apache on Windows 7

Body:
The simplest script:

<?php echo 'hello';

Takes about 3 seconds to execute. There seems to be a big time interval Apache waits until it serves a web page.

I tried turning off antivirus, disabling ipv6 and more but Apache is still very slow. What should I do?

EDIT:

Additional information:

Apache 2.2

PHP 5.2

It's only dynamic PHP files. Static files (html) are served instantly

It has nothing to do with system specs, it's new PC

There are few PHP notices in Apache error log:

[Thu Jul 01 08:37:21 2010] [error] [client 127.0.0.1] PHP Notice:  Undefined variable: ref in D:\\data\\o\\WebProjects\\elearning\\application\\modules\\clientarea\\controllers\\ViewController.php on line 578, referer: http://elearning/clientarea/view/course/teid/1/cid/1


问:
Match set of x,y points to another set that is scaled, rotated, translated, and with missing elements
(Why am I doing this? See explanation below)

Consider two sets of points, A and B as shown below

It might not look like it, but set A is "hidden" within set B. It can not be easily seen because points in B are scaled, rotated, and translated in (x, y) with respect to A. Even worse, some points that are present in A are missing in B, and B contains many points that are not in A.

I need to find the appropriate scaling, rotation, and translation that must be applied to the B set in order to match it with set A. In the case shown above, the correct values are:

```<code>scale = 0.14, rot_angle = 0.0, x_transl = 35.0, y_transl = 2.0
</code>```

which produces the (good enough) match

(in red, only the matched B points are shown; these are located in the sector 1000<x<2000, y~2000 in the first figure to the right). Given the many degrees of freedom (DoF: scaling + rotation + 2D translation) I am aware of the possibility of a miss-match, but the coordinates of the points are not random (although they may look like it) so the probability of this happening is very small.

The code I wrote (see below) uses brute force to loop through all possible DoF values taken from pre-defined ranges for each one. The core of the code is based on minimizing the distance of each point in A to any point in B

The code works (it actually generated the solution mentioned above), but since the number of solutions (i.e., the combinations of accepted values for each DoF) scales with larger ranges, it can become unacceptably slow pretty quick (also it eats up all the RAM in my system)

How can I improve the performance of the code? I'm open to any solution including numpy and/or scipy. Perhaps something like Basing-Hopping to search for the best match (or a relatively close one) instead of the brute force method I currently employ?

```<code>import numpy as np
from scipy.spatial import distance
import math

def scalePoints(B_center, delta_x, delta_y, scale):
    """
    Scales xy points.

    http://codereview.stackexchange.com/q/159183/35351
    """
    x_scale = B_center[0] - scale * delta_x
    y_scale = B_center[1] - scale * delta_y

    return x_scale, y_scale

def rotatePoints(center, x, y, angle):
    """
    Rotates points in 'xy' around 'center'. Angle is in degrees.
    Rotation is counter-clockwise

    http://stackoverflow.com/a/20024348/1391441
    """
    angle = math.radians(angle)
    xy_rot = x - center[0], y - center[1]
    xy_rot = (xy_rot[0] * math.cos(angle) - xy_rot[1] * math.sin(angle),
              xy_rot[0] * math.sin(angle) + xy_rot[1] * math.cos(angle))
    xy_rot = xy_rot[0] + center[0], xy_rot[1] + center[1]

    return xy_rot

def distancePoints(set_A, x_transl, y_transl):
    """
    Find the sum of the minimum distance of points in set_A to points in set_B.
    """
    d = distance.cdist(set_A, zip(*[x_transl, y_transl]), 'euclidean')
    # Sum of all minimal distances.
    d_sum = np.sum(np.min(d, axis=1))

    return d_sum

def match_frames(
        set_A, B_center, delta_x, delta_y, tol, sc_min, sc_max, sc_step,
        ang_min, ang_max, ang_step, xmin, xmax, xstep, ymin, ymax, ystep):
    """
    Process all possible solutions in the defined ranges.
    """
    N = len(set_A)
    # Ranges
    sc_range = np.arange(sc_min, sc_max, sc_step)
    ang_range = np.arange(ang_min, ang_max, ang_step)
    x_range = np.arange(xmin, xmax, xstep)
    y_range = np.arange(ymin, ymax, ystep)
    print("Total solutions: {:.2e}".format(
          np.prod([len(_) for _ in [sc_range, ang_range, x_range, y_range]])))

    d_sum, params_all = [], []
    for scale in sc_range:
        # Scaled points.
        x_scale, y_scale = scalePoints(B_center, delta_x, delta_y, scale)
        for ang in ang_range:
            # Rotated points.
            xy_rot = rotatePoints(B_center, x_scale, y_scale, ang)
            # x translation
            for x_tr in x_range:
                x_transl = xy_rot[0] + x_tr
                # y translation
                for y_tr in y_range:
                    y_transl = xy_rot[1] + y_tr

                    # Find minimum distance sum.
                    d_sum.append(distancePoints(set_A, x_transl, y_transl))

                    # Store solutions.
                    params_all.append([scale, ang, x_tr, y_tr])

                    # Condition to break out if given tolerance for match
                    # is achieved.
                    if d_sum[-1] <= tol * N:
                        print("Match found:", scale, ang, x_tr, y_tr)
                        i_min = d_sum.index(min(d_sum))
                        return i_min, params_all

        # Print best solution found so far.
        i_min = d_sum.index(min(d_sum))
        print("d_sum_min = {:.2f}".format(d_sum[i_min]))

    return i_min, params_all

# Data.
set_A = [[2015.81, 1981.665], [1967.31, 1960.865], [1962.91, 1951.365],
         [1964.91, 1994.565], [1894.41, 1957.065]]
set_B = [
    [2689.28, 3507.04, 2895.67, 1051.3, 1929.49, 1035.97, 752.44, 130.62,
     620.06, 2769.06, 1580.77, 281.76, 224.54, 3848.3],
    [2061.19, 3700.27, 2131.2, 1837.3, 2017.52, 80.96, 3524.61, 3821.22,
     3711.53, 1812.12, 1868.33, 3865.77, 3273.77, 2100.71]]

# This is necessary to apply the scaling.
x, y = np.asarray(set_B)
# Center of B points, defined as the center of the minimal rectangle that
# contains all points.
B_center = [(min(x) + max(x)) * .5, (min(y) + max(y)) * .5]
# Difference between the center coordinates and the xy points.
delta_x, delta_y = B_center[0] - x, B_center[1] - y

# Tolerance in pixels for match.
tol = 1.
# Ranges for each DoF.
sc_min, sc_max, sc_step = .01, .2, .01
ang_min, ang_max, ang_step = -30., 30., 1.
xmin, xmax, xstep = -150., 150., 1.
ymin, ymax, ystep = -150., 150., 1.

# Find proper scaling + rotation + translation for set_B.
i_min, params_all = match_frames(
    set_A, B_center, delta_x, delta_y, tol, sc_min, sc_max, sc_step,
    ang_min, ang_max, ang_step, xmin, xmax, xstep, ymin, ymax, ystep)

# Best match found
print(params_all[i_min])
</code>```

Why am I doing this?

When an astronomer observes a star field, it also needs to observe what is called a "standard field of stars". This is needed to be able to transform the "instrumental magnitudes" (a logarithmic measure of the brightness) of the observed stars to a common universal scale, since these magnitudes depend on the optical system used (telescope + CCD array). In the example shown here, the standard field can be seen below to the left, and the observed one to the right.

Notice that the points in the set A (used above) are the marked stars in the standard field, and the set B are those stars detected in the observed field (marked in red above)

The process of identifying those stars in the observed field that correspond to the stars marked in the standard field is done by-eye, even  today. This is due to the complexity of the task.

In the observed image above, there's quite a bit of scaling, but no rotation and little translation. This constitutes a rather favorable scenario; it could be much worse. I'm trying to develop a simple algorithm to avoid having to manually identify stars in the observed field as stars in the standard field, one by one.

Solution proposed by litepresence

This is a script I made following the answer by litepresence.

```<code>import itertools
import numpy as np
import matplotlib.pyplot as plt

def getTriangles(set_X, X_combs):
    """
    Inefficient way of obtaining the lengths of each triangle's side.
    Normalized so that the minimum length is 1.
    """
    triang = []
    for p0, p1, p2 in X_combs:
        d1 = np.sqrt((set_X[p0][0] - set_X[p1][0]) ** 2 +
                     (set_X[p0][1] - set_X[p1][1]) ** 2)
        d2 = np.sqrt((set_X[p0][0] - set_X[p2][0]) ** 2 +
                     (set_X[p0][1] - set_X[p2][1]) ** 2)
        d3 = np.sqrt((set_X[p1][0] - set_X[p2][0]) ** 2 +
                     (set_X[p1][1] - set_X[p2][1]) ** 2)
        d_min = min(d1, d2, d3)
        d_unsort = [d1 / d_min, d2 / d_min, d3 / d_min]
        triang.append(sorted(d_unsort))

    return triang

def sumTriangles(A_triang, B_triang):
    """
    For each normalized triangle in A, compare with each normalized triangle
    in B. find the differences between their sides, sum their absolute values,
    and select the two triangles with the smallest sum of absolute differences.
    """
    tr_sum, tr_idx = [], []
    for i, A_tr in enumerate(A_triang):
        for j, B_tr in enumerate(B_triang):
            # Absolute value of lengths differences.
            tr_diff = abs(np.array(A_tr) - np.array(B_tr))
            # Sum the differences
            tr_sum.append(sum(tr_diff))
            tr_idx.append([i, j])

    # Index of the triangles in A and B with the smallest sum of absolute
    # length differences.
    tr_idx_min = tr_idx[tr_sum.index(min(tr_sum))]
    A_idx, B_idx = tr_idx_min[0], tr_idx_min[1]
    print("Smallest difference: {}".format(min(tr_sum)))

    return A_idx, B_idx

# Data.
set_A = [[2015.81, 1981.665], [1967.31, 1960.865], [1962.91, 1951.365],
         [1964.91, 1994.565], [1894.41, 1957.065]]
set_B = [
    [2689.28, 3507.04, 2895.67, 1051.3, 1929.49, 1035.97, 752.44, 130.62,
     620.06, 2769.06, 1580.77, 281.76, 224.54, 3848.3],
    [2061.19, 3700.27, 2131.2, 1837.3, 2017.52, 80.96, 3524.61, 3821.22,
     3711.53, 1812.12, 1868.33, 3865.77, 3273.77, 2100.71]]
set_B = zip(*set_B)

# All possible triangles.
A_combs = list(itertools.combinations(range(len(set_A)), 3))
B_combs = list(itertools.combinations(range(len(set_B)), 3))

# Obtain normalized triangles.
A_triang, B_triang = getTriangles(set_A, A_combs), getTriangles(set_B, B_combs)

# Index of the A and B triangles with the smallest difference.
A_idx, B_idx = sumTriangles(A_triang, B_triang)

# Indexes of points in A and B of the best match triangles.
A_idx_pts, B_idx_pts = A_combs[A_idx], B_combs[B_idx]
print 'triangle A %s matches triangle B %s' % (A_idx_pts, B_idx_pts)

# Matched points in A and B.
print "A:", [set_A[_] for _ in A_idx_pts]
print "B:", [set_B[_] for _ in B_idx_pts]

# Plot
A_pts = zip(*[set_A[_] for _ in A_idx_pts])
B_pts = zip(*[set_B[_] for _ in B_idx_pts])
plt.scatter(*A_pts, s=10, c='k')
plt.scatter(*B_pts, s=10, c='r')
plt.show()
</code>```

The method is almost instantaneous and produces the correct match:

```<code>Smallest difference: 0.0314154749597
triangle A (0, 1, 4) matches triangle B (3, 4, 10)
A: [[2015.81, 1981.665], [1967.31, 1960.865], [1894.41, 1957.065]]
B: [(1051.3, 1837.3), (1929.49, 2017.52), (1580.77, 1868.33)]
</code>```

答:
1) I would approach this problem by labeling all points and finding all possible combinations of 3 points from each set.

```<code># normalize B data to same format as A
set_Bx, set_By = (set_B)
set_B = []
for i in range(len(set_Bx)):
    set_B.append([set_Bx[i],set_By[i]])
'''
set_B = [[2689.28, 2061.19], [3507.04, 3700.27], [2895.67, 2131.2],
[1051.3, 1837.3], [1929.49, 2017.52], [1035.97, 80.96], [752.44,
3524.61], [130.62, 3821.22], [620.06, 3711.53], [2769.06, 1812.12],
[1580.77, 1868.33], [281.76, 3865.77], [224.54, 3273.77], [3848.3,
2100.71]]
'''

list(itertools.combinations(range(len(set_A)), 3))
list(itertools.combinations(range(len(set_B)), 3))
</code>```

How to generate all permutations of a list in Python

2) For each 3 point group, calculate the sides of the respective triangle; repeating the process for group A and group B.

```<code>dist = sqrt( (x2 - x1)**2 + (y2 - y1)**2 )
</code>```

How do I find the distance between two points?

3) Then reduce the ratio of sides for each such that each triangle's smallest side was then equal to 1; the other sides reduced in respective ratio.

In two similar triangles:

The perimeters of the two triangles are in the same ratio as the
  sides. The corresponding sides, medians and altitudes will all be in
  this same ratio.

http://www.mathopenref.com/similartrianglesparts.html

4) Finally for each a triangle from group A, compare to each triangle from group B, with element-wise subtraction.  Then sum the resulting elements and find the triangles from A and B with the smallest sum.

```<code>list(numpy.array(list1)-numpy.array(list2))
</code>```

Subtracting 2 lists in Python

5) Given matched triangles; finding the appropriate scaling, translation, and rotation should be relatively trivial in terms of CPU/RAM.

ETA1: rough draft script

ETA2: patched error discussed in comments: with sum(abs()) instead of abs(sum()).  Now it works, fast too!

```<code>'''
known correct solution

A = [[1894.41, 1957.065],[1967.31, 1960.865],[2015.81, 1981.665]]
B = [[1051.3, 1837.3],[1580.77, 1868.33],[1929.49, 2017.52]]

'''
import numpy as np
import itertools
import math
import operator

set_A = [[2015.81, 1981.665], [1967.31, 1960.865], [1962.91, 1951.365],
        [1964.91, 1994.565], [1894.41, 1957.065]]
set_B = [[2689.28, 3507.04, 2895.67, 1051.3, 1929.49, 1035.97, 752.44, 130.62,
        620.06, 2769.06, 1580.77, 281.76, 224.54, 3848.3],
        [2061.19, 3700.27, 2131.2, 1837.3, 2017.52, 80.96, 3524.61, 3821.22,
        3711.53, 1812.12, 1868.33, 3865.77, 3273.77, 2100.71]]

# normalize set B data to set A format
set_Bx, set_By = (set_B)
set_B = []
for i in range(len(set_Bx)):
    set_B.append([set_Bx[i],set_By[i]])

'''
set_B = [[2689.28, 2061.19], [3507.04, 3700.27], [2895.67, 2131.2],
[1051.3, 1837.3], [1929.49, 2017.52], [1035.97, 80.96], [752.44, 3524.61],
[130.62, 3821.22], [620.06, 3711.53], [2769.06, 1812.12], [1580.77, 1868.33],
[281.76, 3865.77], [224.54, 3273.77], [3848.3, 2100.71]]
'''

print set_A
print set_B
print len(set_A)
print len(set_B)

set_A_tri = list(itertools.combinations(range(len(set_A)), 3))
set_B_tri = list(itertools.combinations(range(len(set_B)), 3))

print set_A_tri
print set_B_tri
print len(set_A_tri)
print len(set_B_tri)

'''
set_A = [[2015.81, 1981.665], [1967.31, 1960.865], [1962.91, 1951.365],
[1964.91, 1994.565], [1894.41, 1957.065]]

set_A_tri = [(0, 1, 2), (0, 1, 3), (0, 1, 4), (0, 2, 3), (0, 2, 4), (0, 3, 4),
(1, 2, 3), (1, 2, 4), (1, 3, 4), (2, 3, 4)]
'''

def distance(x1,y1,x2,y2):
    return math.sqrt((x2 - x1)**2 + (y2 - y1)**2 )

def tri_sides(set_x, set_x_tri):

    triangles = []
    for i in range(len(set_x_tri)):

        point1 = set_x_tri[i][0]
        point2 = set_x_tri[i][1]
        point3 = set_x_tri[i][2]

        point1x, point1y = set_x[point1][0], set_x[point1][1]
        point2x, point2y = set_x[point2][0], set_x[point2][1]
        point3x, point3y = set_x[point3][0], set_x[point3][1]

        len1 = distance(point1x,point1y,point2x,point2y)
        len2 = distance(point1x,point1y,point3x,point3y)
        len3 = distance(point2x,point2y,point3x,point3y)

        min_side = min(len1,len2,len3)
        len1/=min_side
        len2/=min_side
        len3/=min_side
        t=[len1,len2,len3]
        t.sort()
        triangles.append(t)

    return triangles

A_triangles = tri_sides(set_A, set_A_tri)
B_triangles = tri_sides(set_B, set_B_tri)

print A_triangles
'''
[[1.0, 5.0405616860744304, 5.822935502560814],
[1.0, 1.5542012854321234, 1.5619803879976761],
[1.0, 1.3832883678507584, 2.347214708755337],
[1.0, 1.2141910838179129, 1.4096730529373076],
[1.0, 1.1275138587537166, 2.0318412465223665],
[1.0, 1.5207417600732074, 2.3589630093994876],
[1.0, 3.2270326342163584, 4.13069930678442],
[1.0, 6.565440477766354, 6.972550347780966],
[1.0, 2.1606693015281997, 2.3635387983160885],
[1.0, 1.589425903498476, 1.846471085870448]]
'''
print B_triangles

def list_subtract(list1,list2):

    return np.absolute(np.array(list1)-np.array(list2))

sums = []
threshold = 1
for i in range(len(A_triangles)):
    for j in range(len(B_triangles)):
        k = sum(list_subtract(A_triangles[i], B_triangles[j]))
        if k < threshold:
            sums.append([i,j,k])
# sort by smallest sum
sums = sorted(sums, key=operator.itemgetter(2))

print sums
print 'winner %s' % sums[0]
print sums[0][0]
print sums[0][1]
match_A = set_A_tri[sums[0][0]]
match_B = set_B_tri[sums[0][1]]
print 'triangle A %s matches triangle B %s' % (match_A, match_B)

match_A_pts = []
match_B_pts = []
for i in range(3):
    match_A_pts.append(set_A[match_A[i]])
    match_B_pts.append(set_B[match_B[i]])

print 'triangle A has points %s' % match_A_pts
print 'triangle B has points %s' % match_B_pts

'''
winner [2, 204, 0.031415474959738399]
2
204
triangle A (0, 1, 4) matches triangle B (3, 4, 10)
triangle A has points [[2015.81, 1981.665], [1967.31, 1960.865], [1894.41, 1957.065]]
triangle B has points [[1051.3, 1837.3], [1929.49, 2017.52], [1580.77, 1868.33]]
'''
</code>```

Body:
(Why am I doing this? See explanation below)

Consider two sets of points, A and B as shown below

It might not look like it, but set A is "hidden" within set B. It can not be easily seen because points in B are scaled, rotated, and translated in (x, y) with respect to A. Even worse, some points that are present in A are missing in B, and B contains many points that are not in A.

I need to find the appropriate scaling, rotation, and translation that must be applied to the B set in order to match it with set A. In the case shown above, the correct values are:

scale = 0.14, rot_angle = 0.0, x_transl = 35.0, y_transl = 2.0

which produces the (good enough) match

(in red, only the matched B points are shown; these are located in the sector 1000<x<2000, y~2000 in the first figure to the right). Given the many degrees of freedom (DoF: scaling + rotation + 2D translation) I am aware of the possibility of a miss-match, but the coordinates of the points are not random (although they may look like it) so the probability of this happening is very small.

The code I wrote (see below) uses brute force to loop through all possible DoF values taken from pre-defined ranges for each one. The core of the code is based on minimizing the distance of each point in A to any point in B

The code works (it actually generated the solution mentioned above), but since the number of solutions (i.e., the combinations of accepted values for each DoF) scales with larger ranges, it can become unacceptably slow pretty quick (also it eats up all the RAM in my system)

How can I improve the performance of the code? I'm open to any solution including numpy and/or scipy. Perhaps something like Basing-Hopping to search for the best match (or a relatively close one) instead of the brute force method I currently employ?

import numpy as np
from scipy.spatial import distance
import math

def scalePoints(B_center, delta_x, delta_y, scale):
    """
    Scales xy points.

    http://codereview.stackexchange.com/q/159183/35351
    """
    x_scale = B_center[0] - scale * delta_x
    y_scale = B_center[1] - scale * delta_y

    return x_scale, y_scale

def rotatePoints(center, x, y, angle):
    """
    Rotates points in 'xy' around 'center'. Angle is in degrees.
    Rotation is counter-clockwise

    http://stackoverflow.com/a/20024348/1391441
    """
    angle = math.radians(angle)
    xy_rot = x - center[0], y - center[1]
    xy_rot = (xy_rot[0] * math.cos(angle) - xy_rot[1] * math.sin(angle),
              xy_rot[0] * math.sin(angle) + xy_rot[1] * math.cos(angle))
    xy_rot = xy_rot[0] + center[0], xy_rot[1] + center[1]

    return xy_rot

def distancePoints(set_A, x_transl, y_transl):
    """
    Find the sum of the minimum distance of points in set_A to points in set_B.
    """
    d = distance.cdist(set_A, zip(*[x_transl, y_transl]), 'euclidean')
    # Sum of all minimal distances.
    d_sum = np.sum(np.min(d, axis=1))

    return d_sum

def match_frames(
        set_A, B_center, delta_x, delta_y, tol, sc_min, sc_max, sc_step,
        ang_min, ang_max, ang_step, xmin, xmax, xstep, ymin, ymax, ystep):
    """
    Process all possible solutions in the defined ranges.
    """
    N = len(set_A)
    # Ranges
    sc_range = np.arange(sc_min, sc_max, sc_step)
    ang_range = np.arange(ang_min, ang_max, ang_step)
    x_range = np.arange(xmin, xmax, xstep)
    y_range = np.arange(ymin, ymax, ystep)
    print("Total solutions: {:.2e}".format(
          np.prod([len(_) for _ in [sc_range, ang_range, x_range, y_range]])))

    d_sum, params_all = [], []
    for scale in sc_range:
        # Scaled points.
        x_scale, y_scale = scalePoints(B_center, delta_x, delta_y, scale)
        for ang in ang_range:
            # Rotated points.
            xy_rot = rotatePoints(B_center, x_scale, y_scale, ang)
            # x translation
            for x_tr in x_range:
                x_transl = xy_rot[0] + x_tr
                # y translation
                for y_tr in y_range:
                    y_transl = xy_rot[1] + y_tr

                    # Find minimum distance sum.
                    d_sum.append(distancePoints(set_A, x_transl, y_transl))

                    # Store solutions.
                    params_all.append([scale, ang, x_tr, y_tr])

                    # Condition to break out if given tolerance for match
                    # is achieved.
                    if d_sum[-1] <= tol * N:
                        print("Match found:", scale, ang, x_tr, y_tr)
                        i_min = d_sum.index(min(d_sum))
                        return i_min, params_all

        # Print best solution found so far.
        i_min = d_sum.index(min(d_sum))
        print("d_sum_min = {:.2f}".format(d_sum[i_min]))

    return i_min, params_all

# Data.
set_A = [[2015.81, 1981.665], [1967.31, 1960.865], [1962.91, 1951.365],
         [1964.91, 1994.565], [1894.41, 1957.065]]
set_B = [
    [2689.28, 3507.04, 2895.67, 1051.3, 1929.49, 1035.97, 752.44, 130.62,
     620.06, 2769.06, 1580.77, 281.76, 224.54, 3848.3],
    [2061.19, 3700.27, 2131.2, 1837.3, 2017.52, 80.96, 3524.61, 3821.22,
     3711.53, 1812.12, 1868.33, 3865.77, 3273.77, 2100.71]]

# This is necessary to apply the scaling.
x, y = np.asarray(set_B)
# Center of B points, defined as the center of the minimal rectangle that
# contains all points.
B_center = [(min(x) + max(x)) * .5, (min(y) + max(y)) * .5]
# Difference between the center coordinates and the xy points.
delta_x, delta_y = B_center[0] - x, B_center[1] - y

# Tolerance in pixels for match.
tol = 1.
# Ranges for each DoF.
sc_min, sc_max, sc_step = .01, .2, .01
ang_min, ang_max, ang_step = -30., 30., 1.
xmin, xmax, xstep = -150., 150., 1.
ymin, ymax, ystep = -150., 150., 1.

# Find proper scaling + rotation + translation for set_B.
i_min, params_all = match_frames(
    set_A, B_center, delta_x, delta_y, tol, sc_min, sc_max, sc_step,
    ang_min, ang_max, ang_step, xmin, xmax, xstep, ymin, ymax, ystep)

# Best match found
print(params_all[i_min])

Why am I doing this?

When an astronomer observes a star field, it also needs to observe what is called a "standard field of stars". This is needed to be able to transform the "instrumental magnitudes" (a logarithmic measure of the brightness) of the observed stars to a common universal scale, since these magnitudes depend on the optical system used (telescope + CCD array). In the example shown here, the standard field can be seen below to the left, and the observed one to the right.

Notice that the points in the set A (used above) are the marked stars in the standard field, and the set B are those stars detected in the observed field (marked in red above)

The process of identifying those stars in the observed field that correspond to the stars marked in the standard field is done by-eye, even  today. This is due to the complexity of the task.

In the observed image above, there's quite a bit of scaling, but no rotation and little translation. This constitutes a rather favorable scenario; it could be much worse. I'm trying to develop a simple algorithm to avoid having to manually identify stars in the observed field as stars in the standard field, one by one.

Solution proposed by litepresence

This is a script I made following the answer by litepresence.

import itertools
import numpy as np
import matplotlib.pyplot as plt

def getTriangles(set_X, X_combs):
    """
    Inefficient way of obtaining the lengths of each triangle's side.
    Normalized so that the minimum length is 1.
    """
    triang = []
    for p0, p1, p2 in X_combs:
        d1 = np.sqrt((set_X[p0][0] - set_X[p1][0]) ** 2 +
                     (set_X[p0][1] - set_X[p1][1]) ** 2)
        d2 = np.sqrt((set_X[p0][0] - set_X[p2][0]) ** 2 +
                     (set_X[p0][1] - set_X[p2][1]) ** 2)
        d3 = np.sqrt((set_X[p1][0] - set_X[p2][0]) ** 2 +
                     (set_X[p1][1] - set_X[p2][1]) ** 2)
        d_min = min(d1, d2, d3)
        d_unsort = [d1 / d_min, d2 / d_min, d3 / d_min]
        triang.append(sorted(d_unsort))

    return triang

def sumTriangles(A_triang, B_triang):
    """
    For each normalized triangle in A, compare with each normalized triangle
    in B. find the differences between their sides, sum their absolute values,
    and select the two triangles with the smallest sum of absolute differences.
    """
    tr_sum, tr_idx = [], []
    for i, A_tr in enumerate(A_triang):
        for j, B_tr in enumerate(B_triang):
            # Absolute value of lengths differences.
            tr_diff = abs(np.array(A_tr) - np.array(B_tr))
            # Sum the differences
            tr_sum.append(sum(tr_diff))
            tr_idx.append([i, j])

    # Index of the triangles in A and B with the smallest sum of absolute
    # length differences.
    tr_idx_min = tr_idx[tr_sum.index(min(tr_sum))]
    A_idx, B_idx = tr_idx_min[0], tr_idx_min[1]
    print("Smallest difference: {}".format(min(tr_sum)))

    return A_idx, B_idx

# Data.
set_A = [[2015.81, 1981.665], [1967.31, 1960.865], [1962.91, 1951.365],
         [1964.91, 1994.565], [1894.41, 1957.065]]
set_B = [
    [2689.28, 3507.04, 2895.67, 1051.3, 1929.49, 1035.97, 752.44, 130.62,
     620.06, 2769.06, 1580.77, 281.76, 224.54, 3848.3],
    [2061.19, 3700.27, 2131.2, 1837.3, 2017.52, 80.96, 3524.61, 3821.22,
     3711.53, 1812.12, 1868.33, 3865.77, 3273.77, 2100.71]]
set_B = zip(*set_B)

# All possible triangles.
A_combs = list(itertools.combinations(range(len(set_A)), 3))
B_combs = list(itertools.combinations(range(len(set_B)), 3))

# Obtain normalized triangles.
A_triang, B_triang = getTriangles(set_A, A_combs), getTriangles(set_B, B_combs)

# Index of the A and B triangles with the smallest difference.
A_idx, B_idx = sumTriangles(A_triang, B_triang)

# Indexes of points in A and B of the best match triangles.
A_idx_pts, B_idx_pts = A_combs[A_idx], B_combs[B_idx]
print 'triangle A %s matches triangle B %s' % (A_idx_pts, B_idx_pts)

# Matched points in A and B.
print "A:", [set_A[_] for _ in A_idx_pts]
print "B:", [set_B[_] for _ in B_idx_pts]

# Plot
A_pts = zip(*[set_A[_] for _ in A_idx_pts])
B_pts = zip(*[set_B[_] for _ in B_idx_pts])
plt.scatter(*A_pts, s=10, c='k')
plt.scatter(*B_pts, s=10, c='r')
plt.show()

The method is almost instantaneous and produces the correct match:

Smallest difference: 0.0314154749597
triangle A (0, 1, 4) matches triangle B (3, 4, 10)
A: [[2015.81, 1981.665], [1967.31, 1960.865], [1894.41, 1957.065]]
B: [(1051.3, 1837.3), (1929.49, 2017.52), (1580.77, 1868.33)]

Body:
1) I would approach this problem by labeling all points and finding all possible combinations of 3 points from each set.

# normalize B data to same format as A
set_Bx, set_By = (set_B)
set_B = []
for i in range(len(set_Bx)):
    set_B.append([set_Bx[i],set_By[i]])
'''
set_B = [[2689.28, 2061.19], [3507.04, 3700.27], [2895.67, 2131.2],
[1051.3, 1837.3], [1929.49, 2017.52], [1035.97, 80.96], [752.44,
3524.61], [130.62, 3821.22], [620.06, 3711.53], [2769.06, 1812.12],
[1580.77, 1868.33], [281.76, 3865.77], [224.54, 3273.77], [3848.3,
2100.71]]
'''

list(itertools.combinations(range(len(set_A)), 3))
list(itertools.combinations(range(len(set_B)), 3))

How to generate all permutations of a list in Python

2) For each 3 point group, calculate the sides of the respective triangle; repeating the process for group A and group B.

dist = sqrt( (x2 - x1)**2 + (y2 - y1)**2 )

How do I find the distance between two points?

3) Then reduce the ratio of sides for each such that each triangle's smallest side was then equal to 1; the other sides reduced in respective ratio.

In two similar triangles:

The perimeters of the two triangles are in the same ratio as the
  sides. The corresponding sides, medians and altitudes will all be in
  this same ratio.

http://www.mathopenref.com/similartrianglesparts.html

4) Finally for each a triangle from group A, compare to each triangle from group B, with element-wise subtraction.  Then sum the resulting elements and find the triangles from A and B with the smallest sum.

list(numpy.array(list1)-numpy.array(list2))

Subtracting 2 lists in Python

5) Given matched triangles; finding the appropriate scaling, translation, and rotation should be relatively trivial in terms of CPU/RAM.

ETA1: rough draft script

ETA2: patched error discussed in comments: with sum(abs()) instead of abs(sum()).  Now it works, fast too!

'''
known correct solution

A = [[1894.41, 1957.065],[1967.31, 1960.865],[2015.81, 1981.665]]
B = [[1051.3, 1837.3],[1580.77, 1868.33],[1929.49, 2017.52]]

'''
import numpy as np
import itertools
import math
import operator

set_A = [[2015.81, 1981.665], [1967.31, 1960.865], [1962.91, 1951.365],
        [1964.91, 1994.565], [1894.41, 1957.065]]
set_B = [[2689.28, 3507.04, 2895.67, 1051.3, 1929.49, 1035.97, 752.44, 130.62,
        620.06, 2769.06, 1580.77, 281.76, 224.54, 3848.3],
        [2061.19, 3700.27, 2131.2, 1837.3, 2017.52, 80.96, 3524.61, 3821.22,
        3711.53, 1812.12, 1868.33, 3865.77, 3273.77, 2100.71]]

# normalize set B data to set A format
set_Bx, set_By = (set_B)
set_B = []
for i in range(len(set_Bx)):
    set_B.append([set_Bx[i],set_By[i]])

'''
set_B = [[2689.28, 2061.19], [3507.04, 3700.27], [2895.67, 2131.2],
[1051.3, 1837.3], [1929.49, 2017.52], [1035.97, 80.96], [752.44, 3524.61],
[130.62, 3821.22], [620.06, 3711.53], [2769.06, 1812.12], [1580.77, 1868.33],
[281.76, 3865.77], [224.54, 3273.77], [3848.3, 2100.71]]
'''

print set_A
print set_B
print len(set_A)
print len(set_B)

set_A_tri = list(itertools.combinations(range(len(set_A)), 3))
set_B_tri = list(itertools.combinations(range(len(set_B)), 3))

print set_A_tri
print set_B_tri
print len(set_A_tri)
print len(set_B_tri)

'''
set_A = [[2015.81, 1981.665], [1967.31, 1960.865], [1962.91, 1951.365],
[1964.91, 1994.565], [1894.41, 1957.065]]

set_A_tri = [(0, 1, 2), (0, 1, 3), (0, 1, 4), (0, 2, 3), (0, 2, 4), (0, 3, 4),
(1, 2, 3), (1, 2, 4), (1, 3, 4), (2, 3, 4)]
'''

def distance(x1,y1,x2,y2):
    return math.sqrt((x2 - x1)**2 + (y2 - y1)**2 )

def tri_sides(set_x, set_x_tri):

    triangles = []
    for i in range(len(set_x_tri)):

        point1 = set_x_tri[i][0]
        point2 = set_x_tri[i][1]
        point3 = set_x_tri[i][2]

        point1x, point1y = set_x[point1][0], set_x[point1][1]
        point2x, point2y = set_x[point2][0], set_x[point2][1]
        point3x, point3y = set_x[point3][0], set_x[point3][1]

        len1 = distance(point1x,point1y,point2x,point2y)
        len2 = distance(point1x,point1y,point3x,point3y)
        len3 = distance(point2x,point2y,point3x,point3y)

        min_side = min(len1,len2,len3)
        len1/=min_side
        len2/=min_side
        len3/=min_side
        t=[len1,len2,len3]
        t.sort()
        triangles.append(t)

    return triangles

A_triangles = tri_sides(set_A, set_A_tri)
B_triangles = tri_sides(set_B, set_B_tri)

print A_triangles
'''
[[1.0, 5.0405616860744304, 5.822935502560814],
[1.0, 1.5542012854321234, 1.5619803879976761],
[1.0, 1.3832883678507584, 2.347214708755337],
[1.0, 1.2141910838179129, 1.4096730529373076],
[1.0, 1.1275138587537166, 2.0318412465223665],
[1.0, 1.5207417600732074, 2.3589630093994876],
[1.0, 3.2270326342163584, 4.13069930678442],
[1.0, 6.565440477766354, 6.972550347780966],
[1.0, 2.1606693015281997, 2.3635387983160885],
[1.0, 1.589425903498476, 1.846471085870448]]
'''
print B_triangles

def list_subtract(list1,list2):

    return np.absolute(np.array(list1)-np.array(list2))

sums = []
threshold = 1
for i in range(len(A_triangles)):
    for j in range(len(B_triangles)):
        k = sum(list_subtract(A_triangles[i], B_triangles[j]))
        if k < threshold:
            sums.append([i,j,k])
# sort by smallest sum
sums = sorted(sums, key=operator.itemgetter(2))

print sums
print 'winner %s' % sums[0]
print sums[0][0]
print sums[0][1]
match_A = set_A_tri[sums[0][0]]
match_B = set_B_tri[sums[0][1]]
print 'triangle A %s matches triangle B %s' % (match_A, match_B)

match_A_pts = []
match_B_pts = []
for i in range(3):
    match_A_pts.append(set_A[match_A[i]])
    match_B_pts.append(set_B[match_B[i]])

print 'triangle A has points %s' % match_A_pts
print 'triangle B has points %s' % match_B_pts

'''
winner [2, 204, 0.031415474959738399]
2
204
triangle A (0, 1, 4) matches triangle B (3, 4, 10)
triangle A has points [[2015.81, 1981.665], [1967.31, 1960.865], [1894.41, 1957.065]]
triangle B has points [[1051.3, 1837.3], [1929.49, 2017.52], [1580.77, 1868.33]]
'''