问:
Undefined references when compiling project with libvpx
I've build libvpx.a and headers with MSYS (for MinGW). When I'm trying to compile an example a lot of undefined references to vpx members occurs:

```<code>g++ -m32 -static    -o dist/Debug/MinGW-Windows/test1 build/Debug/MinGW-Windows/main.o -L/D/Libraries/libvpx/ -lvpx
build/Debug/MinGW-Windows/main.o: In function `main':
D:\Projects\CPP_test\Test1/main.cpp:107: undefined reference to `die'
D:\Projects\CPP_test\Test1/main.cpp:109: undefined reference to `vpx_video_reader_open'
D:\Projects\CPP_test\Test1/main.cpp:111: undefined reference to `die'
D:\Projects\CPP_test\Test1/main.cpp:114: undefined reference to `die'
D:\Projects\CPP_test\Test1/main.cpp:116: undefined reference to `vpx_video_reader_get_info'
D:\Projects\CPP_test\Test1/main.cpp:118: undefined reference to `get_vpx_decoder_by_fourcc'
D:\Projects\CPP_test\Test1/main.cpp:120: undefined reference to `die'
D:\Projects\CPP_test\Test1/main.cpp:125: undefined reference to `die_codec'
D:\Projects\CPP_test\Test1/main.cpp:127: undefined reference to `vpx_video_reader_read_frame'
D:\Projects\CPP_test\Test1/main.cpp:132: undefined reference to `vpx_video_reader_get_frame'
D:\Projects\CPP_test\Test1/main.cpp:134: undefined reference to `die_codec'
D:\Projects\CPP_test\Test1/main.cpp:137: undefined reference to `vpx_img_write'
D:\Projects\CPP_test\Test1/main.cpp:144: undefined reference to `die_codec'
D:\Projects\CPP_test\Test1/main.cpp:149: undefined reference to `vpx_video_reader_close'
</code>```

All includes made, lib is linked...
So what am I doing wrong?

PS: Maybe it's not enough to link the libvpx.a file, and I also need the .c files that come with the sources (if so, I do not understand what for the .a lib file is needed)?

答:
It looks like you just copied and pasted blindly from the example.

The functions die_codec and vpx_video_* all come from tools_common.c (https://github.com/webmproject/libvpx/blob/master/tools_common.c) and video_reader.h (https://github.com/webmproject/libvpx/blob/master/video_reader.c), which I believe is not a core part of the libvpx sdk (see here: http://www.webmproject.org/docs/webm-sdk/files.html).

In order for your example to work, you will need to copy-paste those files (both the .c and .h files) as well and include them in your main.cc file.

Body:
I've build libvpx.a and headers with MSYS (for MinGW). When I'm trying to compile an example a lot of undefined references to vpx members occurs:

g++ -m32 -static    -o dist/Debug/MinGW-Windows/test1 build/Debug/MinGW-Windows/main.o -L/D/Libraries/libvpx/ -lvpx
build/Debug/MinGW-Windows/main.o: In function `main':
D:\Projects\CPP_test\Test1/main.cpp:107: undefined reference to `die'
D:\Projects\CPP_test\Test1/main.cpp:109: undefined reference to `vpx_video_reader_open'
D:\Projects\CPP_test\Test1/main.cpp:111: undefined reference to `die'
D:\Projects\CPP_test\Test1/main.cpp:114: undefined reference to `die'
D:\Projects\CPP_test\Test1/main.cpp:116: undefined reference to `vpx_video_reader_get_info'
D:\Projects\CPP_test\Test1/main.cpp:118: undefined reference to `get_vpx_decoder_by_fourcc'
D:\Projects\CPP_test\Test1/main.cpp:120: undefined reference to `die'
D:\Projects\CPP_test\Test1/main.cpp:125: undefined reference to `die_codec'
D:\Projects\CPP_test\Test1/main.cpp:127: undefined reference to `vpx_video_reader_read_frame'
D:\Projects\CPP_test\Test1/main.cpp:132: undefined reference to `vpx_video_reader_get_frame'
D:\Projects\CPP_test\Test1/main.cpp:134: undefined reference to `die_codec'
D:\Projects\CPP_test\Test1/main.cpp:137: undefined reference to `vpx_img_write'
D:\Projects\CPP_test\Test1/main.cpp:144: undefined reference to `die_codec'
D:\Projects\CPP_test\Test1/main.cpp:149: undefined reference to `vpx_video_reader_close'

All includes made, lib is linked...
So what am I doing wrong?

PS: Maybe it's not enough to link the libvpx.a file, and I also need the .c files that come with the sources (if so, I do not understand what for the .a lib file is needed)?


来源: stackexchange

问:
PHP Code: usage of this keyword
```<code>public function __construct($template = '', array $data = array())
{
    if ($template !== '') {
        $this->setTemplate($template);
    }
    if (!empty($data)) {
        foreach ($data as $name => $value) {
            $this->$name = $value;
        }
    }
}
</code>```

Got this from the devshed composite view tutorial (http://www.devshed.com/c/a/PHP/PHP-Composite-View-Design-Pattern-Introducing-the-Key-Concepts/1/). Anyway, I'm a bit confuse on, $this->$name = $value; statement.

I usually use $this for class's properties and/or when invoking class's methods within the said class. Plus the statement have two $'s. Which is weird! So is $this->$name = $value referring to the $name defined in the foreach loop? If so can someone explain this usage or logic behind this?

Thank you in advance.

答:
The $name in

```<code>$this->$name = $value
</code>```

Sets the variable defined as $name to $value

E.g. if $name = 'user', then this is the equivalent to

```<code>$this->user = value;
</code>```

This type of syntax is often used (as demonstrated above) in foreach loops to set object values.

Note: Each time $this->variable_name is called, if 'variable_name' is not already defined as a property of the object, the magic __set function is called, with 'variable_name' passed as the argument.

See http://php.net/manual/en/language.oop5.overloading.php

ContentLicense: CC BY-SA 2.5

Title: PHP Code: usage of this keyword

Body:
public function __construct($template = '', array $data = array())
{
    if ($template !== '') {
        $this->setTemplate($template);
    }
    if (!empty($data)) {
        foreach ($data as $name => $value) {
            $this->$name = $value;
        }
    }
}

Got this from the devshed composite view tutorial (http://www.devshed.com/c/a/PHP/PHP-Composite-View-Design-Pattern-Introducing-the-Key-Concepts/1/). Anyway, I'm a bit confuse on, $this->$name = $value; statement.

I usually use $this for class's properties and/or when invoking class's methods within the said class. Plus the statement have two $'s. Which is weird! So is $this->$name = $value referring to the $name defined in the foreach loop? If so can someone explain this usage or logic behind this?

Thank you in advance.

Body:
The $name in

$this->$name = $value

Sets the variable defined as $name to $value

E.g. if $name = 'user', then this is the equivalent to

$this->user = value;

This type of syntax is often used (as demonstrated above) in foreach loops to set object values.

Note: Each time $this->variable_name is called, if 'variable_name' is not already defined as a property of the object, the magic __set function is called, with 'variable_name' passed as the argument.

See http://php.net/manual/en/language.oop5.overloading.php


问:
Galois field algorithm from C to Matlab
I'm transcribing a C code for Matlab from a multiplication by 2 in the Gallois field, the problem is that my matlab code is not displaying the same value as the C code. Apparently everything is ok, I commented the code in matlab to identify the adaptations of the C code, below the codes.

C:

```<code>#include <stdio.h>
#include <stdlib.h>

int main()
{
  unsigned char value = 0xaa;
  signed char temp;
  // cast to signed value
  temp = (signed char) value;
  printf("\n%d",temp);
  // if MSB is 1, then this will signed extend and fill the temp variable with 1's
  temp = temp >> 7;
  printf("\n%d",temp);
  // AND with the reduction variable
  temp = temp & 0x1b;
  printf("\n%d",temp);
  // finally shift and reduce the value
  printf("\n%d",((value << 1)^temp));
}
</code>```

Output:

```<code>-86
-1
27
335
</code>```

MatLab:

```<code>hex = uint8(hex2dec('1B'));                     % define 0x1b
temp = uint8(hex2dec('AA'));                    % temp = (signed char) value;
disp(temp);
value = uint8(hex2dec('AA'));                   % unsigned char value = 0xaa
temp = bitsra(temp,7);                          % temp = temp >> 7;
disp(temp);
temp = bitand(temp,hex);                        % temp = temp and 0x1b
disp(temp);
galois_value =  bitxor(bitsll(value,1),temp);   % ((value << 1)^temp)
disp(galois_value);                             % printf ("\n%u",...)
</code>```

Output:

```<code> 170

    1

    1

   85
</code>```

The C code works correctly, I'm printing %d in the C code to show the integer value of the varible because the cast in the beggining of the code.

Someone knows what is happening

答:
Try this:</p>

```<code>hex = uint8(hex2dec('1B'));

temp = typecast(uint8(hex2dec('AA')), 'int8');
disp(temp);

temp = bitshift(temp,-7);
disp(temp);

temp = bitand(typecast(temp,'uint8'),hex);
disp(temp);

galois_value =  bitxor(bitshift(uint16(hex2dec('AA')),1),uint16(temp));
disp(galois_value);
</code>```

ContentLicense: CC BY-SA 3.0

Title: Galois field algorithm from C to Matlab

Body:
I'm transcribing a C code for Matlab from a multiplication by 2 in the Gallois field, the problem is that my matlab code is not displaying the same value as the C code. Apparently everything is ok, I commented the code in matlab to identify the adaptations of the C code, below the codes.

C:

#include <stdio.h>
#include <stdlib.h>

int main()
{
  unsigned char value = 0xaa;
  signed char temp;
  // cast to signed value
  temp = (signed char) value;
  printf("\n%d",temp);
  // if MSB is 1, then this will signed extend and fill the temp variable with 1's
  temp = temp >> 7;
  printf("\n%d",temp);
  // AND with the reduction variable
  temp = temp & 0x1b;
  printf("\n%d",temp);
  // finally shift and reduce the value
  printf("\n%d",((value << 1)^temp));
}

Output:

-86
-1
27
335

MatLab:

hex = uint8(hex2dec('1B'));                     % define 0x1b
temp = uint8(hex2dec('AA'));                    % temp = (signed char) value;
disp(temp);
value = uint8(hex2dec('AA'));                   % unsigned char value = 0xaa
temp = bitsra(temp,7);                          % temp = temp >> 7;
disp(temp);
temp = bitand(temp,hex);                        % temp = temp and 0x1b
disp(temp);
galois_value =  bitxor(bitsll(value,1),temp);   % ((value << 1)^temp)
disp(galois_value);                             % printf ("\n%u",...)

Output:

 170

    1

    1

   85

The C code works correctly, I'm printing %d in the C code to show the integer value of the varible because the cast in the beggining of the code.

Someone knows what is happening

Body:
Try this:

hex = uint8(hex2dec('1B'));

temp = typecast(uint8(hex2dec('AA')), 'int8');
disp(temp);

temp = bitshift(temp,-7);
disp(temp);

temp = bitand(typecast(temp,'uint8'),hex);
disp(temp);

galois_value =  bitxor(bitshift(uint16(hex2dec('AA')),1),uint16(temp));
disp(galois_value);


问:
In SqlTransaction.BeginTransaction() if returing Ident_current before commit(), what value should return
I am using SqlTransaction.BeginTranaction and Commit methods. I am calling a stored procedure after BeginTransaction and before Commit.

And the stored procedure returns Ident_Current, should it return the last inserted value in that table or 0?

Thanks,
Bhupesh

答:
Warning: Do NOT ever (unless you have a very specific and targeted reason to) use Ident_Current() - use Scope_Identity(). Ident_Current() will return the last Identity value inserted by ANY Session, not just yours.

Scope_Identity() will contain the value you want.

https://learn.microsoft.com/en-us/sql/t-sql/functions/scope-identity-transact-sql

Returns the last identity value inserted into an identity column in the same scope. A scope is a module: a stored procedure, trigger, function, or batch. Therefore, two statements are in the same scope if they are in the same stored procedure, function, or batch.


问:
Remove quotes between letters
In golang, how can I remove quotes between two letters, like that:

```<code>import (
    "testing"
)

func TestRemoveQuotes(t *testing.T) {
    var a = "bus\"zipcode"
    var mockResult = "bus zipcode"
    a = RemoveQuotes(a)

    if a != mockResult {
        t.Error("Error or TestRemoveQuotes: ", a)
    }
}
</code>```

Function:

```<code>import (
    "fmt"
    "strings"
)

func RemoveQuotes(s string) string {
    s = strings.Replace(s, "\"", "", -1) //here I removed all quotes. I'd like to remove only quotes between letters

    fmt.Println(s)

    return s
}
</code>```

For example:

"bus"zipcode" = "bus zipcode"

答:
In your example you define a string variable so the outer quotes are not part of the actual string. If you would do fmt.Println("bus\"zipcode") the output on the screen would be bus"zipcode. If your goal is to replace quotes in a string with a space then you need to replace the quote not with an empty string as you do, but rather with a space - s = strings.Replace(s, "\"", " ", -1). Though if you want to remove the quotes entirely you can do something like this:

```<code>package main

import (
    "fmt"
    "strings"
)

func RemoveQuotes(s string) string {
    result := ""
    arr := strings.Split(s, ",")
    for i:=0;i<len(arr);i++ {
       sub := strings.Replace(arr[i], "\"", "", -1)
       result = fmt.Sprintf("%s,\"%s\"", result, sub)
    }

    return result[1:]
}

func main() {
    a:= "\"test1\",\"test2\",\"tes\"t3\""
    fmt.Println(RemoveQuotes(a))
}
</code>```

Note however that this is not very efficient, but I assume it's more about learning how to do it in this case.

Title: Remove quotes between letters

Body:
In golang, how can I remove quotes between two letters, like that:

import (
    "testing"
)

func TestRemoveQuotes(t *testing.T) {
    var a = "bus\"zipcode"
    var mockResult = "bus zipcode"
    a = RemoveQuotes(a)

    if a != mockResult {
        t.Error("Error or TestRemoveQuotes: ", a)
    }
}

Function:

import (
    "fmt"
    "strings"
)

func RemoveQuotes(s string) string {
    s = strings.Replace(s, "\"", "", -1) //here I removed all quotes. I'd like to remove only quotes between letters

    fmt.Println(s)

    return s
}

For example:

"bus"zipcode" = "bus zipcode"

Body:
In your example you define a string variable so the outer quotes are not part of the actual string. If you would do fmt.Println("bus\"zipcode") the output on the screen would be bus"zipcode. If your goal is to replace quotes in a string with a space then you need to replace the quote not with an empty string as you do, but rather with a space - s = strings.Replace(s, "\"", " ", -1). Though if you want to remove the quotes entirely you can do something like this:

package main

import (
    "fmt"
    "strings"
)

func RemoveQuotes(s string) string {
    result := ""
    arr := strings.Split(s, ",")
    for i:=0;i<len(arr);i++ {
       sub := strings.Replace(arr[i], "\"", "", -1)
       result = fmt.Sprintf("%s,\"%s\"", result, sub)
    }

    return result[1:]
}

func main() {
    a:= "\"test1\",\"test2\",\"tes\"t3\""
    fmt.Println(RemoveQuotes(a))
}

Note however that this is not very efficient, but I assume it's more about learning how to do it in this case.


问:
Regional Opsworks stack can't be found by Cloudformation
I have a Cloudformation template that modifies an Opsworks stack by adding few resources.

The Opsworks stack is deployed in the region eu-west-1 which is the API endpoint region as well and it shows on the side of the name of the stack: Regional.

When I run the Cloudformation template ( I give the stack ID as a parameter) I get this error:

Unable to find stack with ID xxxxxxx

I guess Cloudformation can only see the opsworks resources which are in us-east-1 region?

I tried changing the region of Cloudformation and deploy the template but the stack is still unfound.

How can I let Cloudformation search for the stack in all regions?

Should I clone the opsworks stack and change the endpoint to us-east-1 region?

What would be the best solution?

Template

```<code>{
  "AWSTemplateFormatVersion": "2010-09-09",
  "Description": "Add a  layer to an existing stack",
  "Mappings": {
    "Region2Principal": {
      "eu-west-1": {
        "EC2Principal": "ec2.amazonaws.com",
        "OpsWorksPrincipal": "opsworks.amazonaws.com"
      }
    },
  },
  "Parameters": {
    "Environment" : {
      "Description": "The Environnement variable ",
      "Type": "String",
      "Default": "dev",
      "AllowedValues" : ["test", "prod"]
    },
    "InstanceType": {
      "Type": "String",
      "Default": "m4.large",
      "AllowedValues" : ["t2.micro", "m1.small", "m1.large","m4.large","m4.xlarge","m4.2xlarge","m4.4xlarge","m4.10xlarge","m4.16xlarge","c4.large" , "c4.xlarge" ,"c4.2xlarge" , "c4.4xlarge","c4.8xlarge" , "c3.large" , "c3.xlarge", "c3.2xlarge", "c3.4xlarge" ,"c3.8xlarge"],
      "ConstraintDescription": "must be a valid EC2 instance type"
    },
    "StackID": {
      "Type": "String",
      "Description": "ID of the existing opsworks stack to edit"
    },
    "vpcId": {
      "Description": "VPC id of corresponding to the Environment",
      "Type": "String"
    },
    "subnetIds" :{
      "Description": "list of sunbnets in the chosen VPC",
      "Type": "List<AWS::EC2::Subnet::Id>"
    },
    "ScriptSG":{
      "Description": "script security group",
      "Type" : "String"
    },
    "SG": {
      "Description": " layer security group",
      "Type": "String"
    }
  },
  "Resources":{
    "Layer": {
      "Type": "AWS::OpsWorks::Layer",
      "Properties": {
        "AutoAssignElasticIps" : false,
        "AutoAssignPublicIps" : true
      }
    },
    "SInstance1": {
      "Type": "AWS::OpsWorks::Instance",
      "Properties": {
        "Hostname": "S1",
        "AutoScalingType": "timer",
        "TimeBasedAutoScaling" : {
          "Friday"  : { "0" : "on",  "6" : "on", "12" : "on", "18" : "on" },
          "Monday"  : { "0" : "on",  "6" : "on", "12" : "on", "18" : "on" }
        },
        "RootDeviceType": "ebs",
        "StackId": {"Ref": "StackID"},
        "LayerIds": [{"Ref": "Layer"}],
        "InstanceType": {"Ref" : "InstanceType"}
      }
    },
    "Instance2": {
      "Type": "AWS::OpsWorks::Instance",
      "Properties": {
        "Hostname": "S2",
        "AutoScalingType": "timer",
        "TimeBasedAutoScaling" : {
          "Saturday": { "0" : "on",  "6" : "on", "12" : "on", "18" : "on" },
          "Sunday" :  { "0" : "on",  "6" : "on", "12" : "on", "18" : "on" },
          "Thursday": { "0" : "on",  "6" : "on", "12" : "on", "18" : "on" },
          "Tuesday" : { "0" : "on",  "6" : "on", "12" : "on", "18" : "on" },
          "Wednesday":{ "0" : "on",  "6" : "on", "12" : "on", "18" : "on" }
        },
        "RootDeviceType": "ebs",
        "StackId": {"Ref": "StackID"},
        "LayerIds": [{"Ref": "Layer"}],
        "InstanceType": {"Ref" : "InstanceType"}
      }
    },
    "ELB": {
      "Type": "AWS::ElasticLoadBalancing::LoadBalancer",
      "Properties": {
        "ConnectionDrainingPolicy" : {
          "Enabled" : true,
          "Timeout" : 300
        },
        "ConnectionSettings" : {
          "IdleTimeout" : 60
        },
        "CrossZone" : true,
        "HealthCheck" : {
          "HealthyThreshold" : "3",
          "Interval" : "30",
          "Target" : "HTTP:80/ping",
          "Timeout" : "5",
          "UnhealthyThreshold" : "2"
        },
        "LoadBalancerName": "loadBalancer",
        "Listeners" : [{
          "InstancePort" : "80",
          "InstanceProtocol" : "HTTP",
          "LoadBalancerPort" : "80",
          "Protocol" : "HTTP"
        }],
        "Scheme" : "internal",
        "SecurityGroups" : [{ "Ref" : "ELBSecurityGroup" }],
        "Subnets" :  { "Ref" : "subnetIds"}
      }
    },
    "ELBAttach":{
      "Type": "AWS::OpsWorks::ElasticLoadBalancerAttachment",
      "Properties": {
        "ElasticLoadBalancerName" : {"Ref" : "ELB"},
        "LayerId" : {"Ref" : "Layer" }
      }
    }
  },
}
</code>```

答:
It looks like you will need to move them to the same region.

Resources can be managed only in the region in which they are created. Resources that are created in one regional endpoint are not available, nor can they be cloned to, another regional endpoint.

http://docs.aws.amazon.com/general/latest/gr/rande.html#opsworks_region

https://aws.amazon.com/about-aws/whats-new/2016/08/aws-opsworks-adds-nine-regional-endpoints-and-asia-pacific-seoul-region-support/

Layer is missing the stackID parameter.

```<code>{
"Type": "AWS::OpsWorks::Layer",
"Properties": {
 "Attributes" : { String:String },
 "AutoAssignElasticIps" : Boolean,
 "AutoAssignPublicIps" : Boolean,
 "CustomInstanceProfileArn" : String,
 "CustomJson" : JSON object,
 "CustomRecipes" : Recipes,
 "CustomSecurityGroupIds" :  [ String, ... ],
 "EnableAutoHealing" : Boolean,
 "InstallUpdatesOnBoot" : Boolean,
 "LifecycleEventConfiguration" :                 LifeCycleEventConfiguration,
"LoadBasedAutoScaling" : LoadBasedAutoScaling,
"Name" : String,
"Packages" : [ String, ... ],
"Shortname" : String,
"StackId" : String,
"Type" : String,
"VolumeConfigurations" : [ VolumeConfiguration, ... ]
 }
  }
</code>```

http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-opsworks-layer.html

Body:
I have a Cloudformation template that modifies an Opsworks stack by adding few resources.

The Opsworks stack is deployed in the region eu-west-1 which is the API endpoint region as well and it shows on the side of the name of the stack: Regional.

When I run the Cloudformation template ( I give the stack ID as a parameter) I get this error:

Unable to find stack with ID xxxxxxx

I guess Cloudformation can only see the opsworks resources which are in us-east-1 region?

I tried changing the region of Cloudformation and deploy the template but the stack is still unfound.

How can I let Cloudformation search for the stack in all regions?

Should I clone the opsworks stack and change the endpoint to us-east-1 region?

What would be the best solution?

Template

{
  "AWSTemplateFormatVersion": "2010-09-09",
  "Description": "Add a  layer to an existing stack",
  "Mappings": {
    "Region2Principal": {
      "eu-west-1": {
        "EC2Principal": "ec2.amazonaws.com",
        "OpsWorksPrincipal": "opsworks.amazonaws.com"
      }
    },
  },
  "Parameters": {
    "Environment" : {
      "Description": "The Environnement variable ",
      "Type": "String",
      "Default": "dev",
      "AllowedValues" : ["test", "prod"]
    },
    "InstanceType": {
      "Type": "String",
      "Default": "m4.large",
      "AllowedValues" : ["t2.micro", "m1.small", "m1.large","m4.large","m4.xlarge","m4.2xlarge","m4.4xlarge","m4.10xlarge","m4.16xlarge","c4.large" , "c4.xlarge" ,"c4.2xlarge" , "c4.4xlarge","c4.8xlarge" , "c3.large" , "c3.xlarge", "c3.2xlarge", "c3.4xlarge" ,"c3.8xlarge"],
      "ConstraintDescription": "must be a valid EC2 instance type"
    },
    "StackID": {
      "Type": "String",
      "Description": "ID of the existing opsworks stack to edit"
    },
    "vpcId": {
      "Description": "VPC id of corresponding to the Environment",
      "Type": "String"
    },
    "subnetIds" :{
      "Description": "list of sunbnets in the chosen VPC",
      "Type": "List<AWS::EC2::Subnet::Id>"
    },
    "ScriptSG":{
      "Description": "script security group",
      "Type" : "String"
    },
    "SG": {
      "Description": " layer security group",
      "Type": "String"
    }
  },
  "Resources":{
    "Layer": {
      "Type": "AWS::OpsWorks::Layer",
      "Properties": {
        "AutoAssignElasticIps" : false,
        "AutoAssignPublicIps" : true
      }
    },
    "SInstance1": {
      "Type": "AWS::OpsWorks::Instance",
      "Properties": {
        "Hostname": "S1",
        "AutoScalingType": "timer",
        "TimeBasedAutoScaling" : {
          "Friday"  : { "0" : "on",  "6" : "on", "12" : "on", "18" : "on" },
          "Monday"  : { "0" : "on",  "6" : "on", "12" : "on", "18" : "on" }
        },
        "RootDeviceType": "ebs",
        "StackId": {"Ref": "StackID"},
        "LayerIds": [{"Ref": "Layer"}],
        "InstanceType": {"Ref" : "InstanceType"}
      }
    },
    "Instance2": {
      "Type": "AWS::OpsWorks::Instance",
      "Properties": {
        "Hostname": "S2",
        "AutoScalingType": "timer",
        "TimeBasedAutoScaling" : {
          "Saturday": { "0" : "on",  "6" : "on", "12" : "on", "18" : "on" },
          "Sunday" :  { "0" : "on",  "6" : "on", "12" : "on", "18" : "on" },
          "Thursday": { "0" : "on",  "6" : "on", "12" : "on", "18" : "on" },
          "Tuesday" : { "0" : "on",  "6" : "on", "12" : "on", "18" : "on" },
          "Wednesday":{ "0" : "on",  "6" : "on", "12" : "on", "18" : "on" }
        },
        "RootDeviceType": "ebs",
        "StackId": {"Ref": "StackID"},
        "LayerIds": [{"Ref": "Layer"}],
        "InstanceType": {"Ref" : "InstanceType"}
      }
    },
    "ELB": {
      "Type": "AWS::ElasticLoadBalancing::LoadBalancer",
      "Properties": {
        "ConnectionDrainingPolicy" : {
          "Enabled" : true,
          "Timeout" : 300
        },
        "ConnectionSettings" : {
          "IdleTimeout" : 60
        },
        "CrossZone" : true,
        "HealthCheck" : {
          "HealthyThreshold" : "3",
          "Interval" : "30",
          "Target" : "HTTP:80/ping",
          "Timeout" : "5",
          "UnhealthyThreshold" : "2"
        },
        "LoadBalancerName": "loadBalancer",
        "Listeners" : [{
          "InstancePort" : "80",
          "InstanceProtocol" : "HTTP",
          "LoadBalancerPort" : "80",
          "Protocol" : "HTTP"
        }],
        "Scheme" : "internal",
        "SecurityGroups" : [{ "Ref" : "ELBSecurityGroup" }],
        "Subnets" :  { "Ref" : "subnetIds"}
      }
    },
    "ELBAttach":{
      "Type": "AWS::OpsWorks::ElasticLoadBalancerAttachment",
      "Properties": {
        "ElasticLoadBalancerName" : {"Ref" : "ELB"},
        "LayerId" : {"Ref" : "Layer" }
      }
    }
  },
}

Body:
It looks like you will need to move them to the same region.

Resources can be managed only in the region in which they are created. Resources that are created in one regional endpoint are not available, nor can they be cloned to, another regional endpoint.

http://docs.aws.amazon.com/general/latest/gr/rande.html#opsworks_region

https://aws.amazon.com/about-aws/whats-new/2016/08/aws-opsworks-adds-nine-regional-endpoints-and-asia-pacific-seoul-region-support/

Layer is missing the stackID parameter.

{
"Type": "AWS::OpsWorks::Layer",
"Properties": {
 "Attributes" : { String:String },
 "AutoAssignElasticIps" : Boolean,
 "AutoAssignPublicIps" : Boolean,
 "CustomInstanceProfileArn" : String,
 "CustomJson" : JSON object,
 "CustomRecipes" : Recipes,
 "CustomSecurityGroupIds" :  [ String, ... ],
 "EnableAutoHealing" : Boolean,
 "InstallUpdatesOnBoot" : Boolean,
 "LifecycleEventConfiguration" :                 LifeCycleEventConfiguration,
"LoadBasedAutoScaling" : LoadBasedAutoScaling,
"Name" : String,
"Packages" : [ String, ... ],
"Shortname" : String,
"StackId" : String,
"Type" : String,
"VolumeConfigurations" : [ VolumeConfiguration, ... ]
 }
  }

http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-opsworks-layer.html


问:
Powershell GCI Recursive Depth Stops Working When Adding Include Parameter
I have what I'm assuming to be a simple question. I have a large block of code that I have written. In short, it downloads a dynamic list of file names and extensions, imports a csv with the roots of every one of our shares, and compares the files to find matches.

```<code>$Directory = Get-ChildItem -Path $path -Recurse -Depth 2 -Include $ExtList -Force
</code>```

Super simple, right? Except the depth parameter isn't working. It recursively searches through every single level. If I do this:

```<code>$Directory = Get-ChildItem -Path $path -Depth 2  -Force
</code>```

The Depth parameter works perfectly and it only searches through the two levels. If I don't include recurse or depth, it works as expected by searching only the top level. The only difference is that I'm removing the -Include parameter.

$Path is a variable like \server\root\
$ExtList is an array of filenames

Again, they both work individually, but not together.

I need to have both the depth and include parameters in here. Does anybody know what I am doing wrong, or if it's a glitch?

Edit ---------------------------

Doing "Where-Object" I tried this:

```<code>$Directory = Get-ChildItem -Path $path -Recurse -Depth 2 -Force | Where-Object {$_.Extension -like $ExtList}
</code>```

And... nothing happens. For testing, this script takes about 10 minutes to successfully run on a good day, it finished in less than 1 second. (715ms to be exact)
When I go into debugging, it's like there is nothing being piped into the where-object.

EDIT------

The $ExtList setup looks like this:

```<code>@((Invoke-WebRequest -Uri "https://fsrm.experiant.ca/api/v1/get").content | convertfrom-json | % {$_.filters})
</code>```

That will get you the exact list and format that I'm using.

$Path pulls from a csv file that looks like this:

This CSV has over 3000 different shares in it. I know it's weird, yes I have to do it this way for our infrastructure.

答: After switching  to run on a Windows Server 2012 R2 box, the depth parameter works with include. It seems to have been a bug with the version that I was on. </p>

Body:
I have what I'm assuming to be a simple question. I have a large block of code that I have written. In short, it downloads a dynamic list of file names and extensions, imports a csv with the roots of every one of our shares, and compares the files to find matches.

$Directory = Get-ChildItem -Path $path -Recurse -Depth 2 -Include $ExtList -Force

Super simple, right? Except the depth parameter isn't working. It recursively searches through every single level. If I do this:

$Directory = Get-ChildItem -Path $path -Depth 2  -Force

The Depth parameter works perfectly and it only searches through the two levels. If I don't include recurse or depth, it works as expected by searching only the top level. The only difference is that I'm removing the -Include parameter.

$Path is a variable like \server\root\
$ExtList is an array of filenames

Again, they both work individually, but not together.

I need to have both the depth and include parameters in here. Does anybody know what I am doing wrong, or if it's a glitch?

Edit ---------------------------

Doing "Where-Object" I tried this:

$Directory = Get-ChildItem -Path $path -Recurse -Depth 2 -Force | Where-Object {$_.Extension -like $ExtList}

And... nothing happens. For testing, this script takes about 10 minutes to successfully run on a good day, it finished in less than 1 second. (715ms to be exact)
When I go into debugging, it's like there is nothing being piped into the where-object.

EDIT------

The $ExtList setup looks like this:

@((Invoke-WebRequest -Uri "https://fsrm.experiant.ca/api/v1/get").content | convertfrom-json | % {$_.filters})

That will get you the exact list and format that I'm using.

$Path pulls from a csv file that looks like this:

This CSV has over 3000 different shares in it. I know it's weird, yes I have to do it this way for our infrastructure.


问:
The Concept of 'Hold space' and 'Pattern space' in sed
I'm confused by the two concepts in sed: hold space and pattern space. Can someone help explain them?

Here's a snippet of the manual:

```<code>h H    Copy/append pattern space to hold space.
g G    Copy/append hold space to pattern space.

n N    Read/append the next line of input into the pattern space.
</code>```

These six commands really confuse me.

答:
Although @January's answer and the example are nice, the explanation was not enough for me. I had to search and learn a lot until I managed to understand how exactly sed -n '1!G;h;$p' works. So I'd like to elaborate on the command for someone like me.

First of all, let's see what the command does.

```<code>$ echo {a..d} | tr ' ' '\n' # Prints from 'a' to 'd' in each line
a
b
c
d
$ echo {a..d} | tr ' ' '\n' | sed -n '1!G;h;$p'
d
c
b
a
</code>```

It reverses the input like tac command does.

sed reads line-by-line, so let's see what happens on the patten space and the hold space at each line. As h command copies the contents of the pattern space to the hold space, both spaces have the same text.

```<code>Read line    Pattern Space / Hold Space    Command executed
-----------------------------------------------------------
a            a$                            h
b            b\na$                         1!G;h
c            c\nb\na$                      1!G;h
d            d\nc\nb\na$                   1!G;h;$p
</code>```

At the last line, $p prints d\nc\nb\na$ which is formatted to

```<code>d
c
b
a
</code>```

If you want to see the pattern space for each line, you can add an l command.

```<code>$ echo {a..d} | tr ' ' '\n' | sed -n '1!G;h;l;$p'
a$
b\na$
c\nb\na$
d\nc\nb\na$
d
c
b
a
</code>```

I found it very helpful to watch this video tutorial Understanding how sed works, as the guy shows how each space will be used step by step. The hold spaced is referred in the 4th tutorial, but I recommend watching all the videos if you are not familiar with sed.

Also GNU sed document and Bruce Barnett's Sed tutorial are very good references.

Body:
I'm confused by the two concepts in sed: hold space and pattern space. Can someone help explain them?

Here's a snippet of the manual:

h H    Copy/append pattern space to hold space.
g G    Copy/append hold space to pattern space.

n N    Read/append the next line of input into the pattern space.

These six commands really confuse me.

Body:
Although @January's answer and the example are nice, the explanation was not enough for me. I had to search and learn a lot until I managed to understand how exactly sed -n '1!G;h;$p' works. So I'd like to elaborate on the command for someone like me.

First of all, let's see what the command does.

$ echo {a..d} | tr ' ' '\n' # Prints from 'a' to 'd' in each line
a
b
c
d
$ echo {a..d} | tr ' ' '\n' | sed -n '1!G;h;$p'
d
c
b
a

It reverses the input like tac command does.

sed reads line-by-line, so let's see what happens on the patten space and the hold space at each line. As h command copies the contents of the pattern space to the hold space, both spaces have the same text.

Read line    Pattern Space / Hold Space    Command executed
-----------------------------------------------------------
a            a$                            h
b            b\na$                         1!G;h
c            c\nb\na$                      1!G;h
d            d\nc\nb\na$                   1!G;h;$p

At the last line, $p prints d\nc\nb\na$ which is formatted to

d
c
b
a

If you want to see the pattern space for each line, you can add an l command.

$ echo {a..d} | tr ' ' '\n' | sed -n '1!G;h;l;$p'
a$
b\na$
c\nb\na$
d\nc\nb\na$
d
c
b
a

I found it very helpful to watch this video tutorial Understanding how sed works, as the guy shows how each space will be used step by step. The hold spaced is referred in the 4th tutorial, but I recommend watching all the videos if you are not familiar with sed.

Also GNU sed document and Bruce Barnett's Sed tutorial are very good references.


问:
Using geofire,mapbox show multiple positions in realtime on Android
I'm using Mapbox fired with Geofire / Geoquery to get my current user positions. I want to put markers on a Mapbox map to show my users (in real time). I use:

```<code>// object or in the same activity which contains the mapview.
Mapbox.getInstance(this, getString(R.string.access_token));

mapView = (MapView) findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(new OnMapReadyCallback() {
    @Override
    public void onMapReady(final MapboxMap mapboxMap) {
        map = mapboxMap;

        GeoQuery geoQuery = geoFire.queryAtLocation(new GeoLocation(latitude, longitude), 100);

        geoQuery.addGeoQueryEventListener(new GeoQueryEventListener() {
            @Override
            public void onKeyEntered(String key, GeoLocation location) {
                Log.d("test","Key "+key+" entered the search area at ["+location.latitude+","+location.longitude+"]");
                mapboxMap.addMarker(new MarkerOptions().position(new LatLng(location.latitude, location.longitude)));
            }

            @Override
            public void onKeyExited(String key) {
                Log.d("test","Key %s is no longer in the search area"+key);
            }

            @Override
            public void onKeyMoved(String key, GeoLocation location) {
                Log.d("test", "Key %s moved within the search area to [%f,%f]" + key + location.latitude + location.longitude);
            }

            @Override
            public void onGeoQueryReady() {
                Log.d("test","All initial data has been loaded and events have been fired!");
            }

            @Override
            public void onGeoQueryError(DatabaseError error) {
                Log.d("test","There was an error with this query: " + error);
            }
        });

    }
});
</code>```

This is working, but only for the first time when I start my activity, now I'm using the SFVehicles example to create live queries:

```<code>private GeoFire geoFire;
private GeoQuery geoQuery;
private MapView mapView;
private MapboxMap map;
private Map<String,Marker> markers;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_rallye_main);

    // setup map and camera position
    SupportMapFragment mapFragment = (SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.map);

    this.map = mapFragment.getMap();

    LatLng latLngCenter = new LatLng(INITIAL_CENTER.latitude, INITIAL_CENTER.longitude);
    this.map.moveCamera(CameraUpdateFactory.newLatLngZoom(latLngCenter, INITIAL_ZOOM_LEVEL));
    this.map.setOnCameraChangeListener(this);

    FirebaseOptions options = new FirebaseOptions.Builder().setApplicationId("geofire").build();
    FirebaseApp app = FirebaseApp.initializeApp(this, options);

    // setup GeoFire
    this.geoFire = new GeoFire(FirebaseDatabase.getInstance(app).getReferenceFromUrl(GEO_FIRE_REF));
    // radius in km gibt alle positionen der Teilnehmer im radius von x km aus
    this.geoQuery = this.geoFire.queryAtLocation(INITIAL_CENTER, 50);

    // setup markers
    this.markers = new HashMap<String, Marker>();

}

@Override
protected void onStop() {
    super.onStop();
    // remove all event listeners to stop updating in the background
    this.geoQuery.removeAllListeners();
    for (Marker marker: this.markers.values()) {
        marker.remove();
    }
    this.markers.clear();
}

@Override
protected void onStart() {
    super.onStart();
    // add an event listener to start updating locations again
    this.geoQuery.addGeoQueryEventListener(this);
}

@Override
public void onKeyEntered(String key, GeoLocation location) {
    // Add a new marker to the map
    Marker marker = this.map.addMarker(new MarkerOptions().position(new LatLng(location.latitude, location.longitude)));
    this.markers.put(key, marker);
}

@Override
public void onKeyExited(String key) {
    // Remove any old marker
    Marker marker = this.markers.get(key);
    if (marker != null) {
        marker.remove();
        this.markers.remove(key);
    }
}

@Override
public void onKeyMoved(String key, GeoLocation location) {
    // Move the marker
    Marker marker = this.markers.get(key);
    if (marker != null) {
        this.animateMarkerTo(marker, location.latitude, location.longitude);
    }
}

@Override
public void onGeoQueryReady() {
}

@Override
public void onGeoQueryError(DatabaseError error) {
    new AlertDialog.Builder(this)
            .setTitle("Error")
            .setMessage("There was an unexpected error querying GeoFire: " + error.getMessage())
            .setPositiveButton(android.R.string.ok, null)
            .setIcon(android.R.drawable.ic_dialog_alert)
            .show();
}

// Animation handler for old APIs without animation support
private void animateMarkerTo(final Marker marker, final double lat, final double lng) {
    final Handler handler = new Handler();
    final long start = SystemClock.uptimeMillis();
    final long DURATION_MS = 3000;
    final Interpolator interpolator = new AccelerateDecelerateInterpolator();
    final LatLng startPosition = marker.getPosition();
    handler.post(new Runnable() {
        @Override
        public void run() {
            float elapsed = SystemClock.uptimeMillis() - start;
            float t = elapsed/DURATION_MS;
            float v = interpolator.getInterpolation(t);

            //double currentLat = (lat - startPosition.latitude) * v + startPosition.latitude;
            //double currentLng = (lng - startPosition.longitude) * v + startPosition.longitude;
            double currentLat = (lat - startPosition.getLatitude()) * v + startPosition.getLatitude();
            double currentLng = (lng - startPosition.getLongitude()) * v + startPosition.getLongitude();
            marker.setPosition(new LatLng(currentLat, currentLng));

            // if animation is not finished yet, repeat
            if (t < 1) {
                handler.postDelayed(this, 16);
            }
        }
    });
}

private double zoomLevelToRadius(double zoomLevel) {
    // Approximation to fit circle into view
    return 16384000/Math.pow(2, zoomLevel);
}

@Override
public void onCameraChange(CameraPosition cameraPosition) {
    // Update the search criteria for this geoQuery and the circle on the map
    LatLng center = cameraPosition.target;
    double radius = zoomLevelToRadius(cameraPosition.zoom);
    this.geoQuery.setCenter(new GeoLocation(center.getLatitude(), center.getLongitude()));
    // radius in km
    this.geoQuery.setRadius(radius/1000);
}
</code>```

The example code using Google map but I have to use Mapbox to provide offline maps and I get errors on this line:

```<code>SupportMapFragment mapFragment = (SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.map);

this.map = mapFragment.getMap();
</code>```

Specifically:

```<code>Cannot resolve Method getMap()
</code>```

I have already tried something like:

```<code>mapFragment.getMapAsync(new OnMapReadyCallback() {
    @Override
    public void onMapReady(MapboxMap mapboxMap) {

        // Customize map with markers, polylines, etc.

    }
});
</code>```

But nothing, I get this error:

```<code>FATAL EXCEPTION: main Process: com.test.bla, PID: 30149
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.test.bla/com.test.bla.rallye.rallye_main}: android.view.InflateException: Binary XML file line >#2: Error inflating class fragment
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2689)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2754)
at android.app.ActivityThread.access$900(ActivityThread.java:177)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1448)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:5938)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1400)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1195)
Caused by: android.view.InflateException: Binary XML file line #2: Error inflating class fragment
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:770)
at android.view.LayoutInflater.inflate(LayoutInflater.java:483)
at android.view.LayoutInflater.inflate(LayoutInflater.java:415)
at android.view.LayoutInflater.inflate(LayoutInflater.java:366)
at android.transition.Scene.enter(Scene.java:175)
at com.android.internal.policy.impl.PhoneWindow.transitionTo(PhoneWindow.java:483)
at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:426)
at android.app.Activity.setContentView(Activity.java:2267).....
</code>```

I can't convert this example from Google mapx to Mapbox

Layout

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:mapbox="http://schemas.android.com/apk/res-auto"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">

    <com.mapbox.mapboxsdk.maps.MapView
        android:id="@+id/mapView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        mapbox:mapbox_cameraTargetLat="52.00000"
        mapbox:mapbox_cameraTargetLng="8.00000"
        mapbox:mapbox_styleUrl="@string/mapbox_style_mapbox_streets"
        mapbox:mapbox_cameraZoom="12"/>

</RelativeLayout>
</code>```

or my second try:

```<code><?xml version="1.0" encoding="utf-8"?>
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/map"
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>
</code>```

答: It looks like something in your layout xml is incorrect. Are you trying to inflate a google map or a mapbox map? Please include the layout XML.</p>

Body:
I'm using Mapbox fired with Geofire / Geoquery to get my current user positions. I want to put markers on a Mapbox map to show my users (in real time). I use:

// object or in the same activity which contains the mapview.
Mapbox.getInstance(this, getString(R.string.access_token));

mapView = (MapView) findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(new OnMapReadyCallback() {
    @Override
    public void onMapReady(final MapboxMap mapboxMap) {
        map = mapboxMap;

        GeoQuery geoQuery = geoFire.queryAtLocation(new GeoLocation(latitude, longitude), 100);

        geoQuery.addGeoQueryEventListener(new GeoQueryEventListener() {
            @Override
            public void onKeyEntered(String key, GeoLocation location) {
                Log.d("test","Key "+key+" entered the search area at ["+location.latitude+","+location.longitude+"]");
                mapboxMap.addMarker(new MarkerOptions().position(new LatLng(location.latitude, location.longitude)));
            }

            @Override
            public void onKeyExited(String key) {
                Log.d("test","Key %s is no longer in the search area"+key);
            }

            @Override
            public void onKeyMoved(String key, GeoLocation location) {
                Log.d("test", "Key %s moved within the search area to [%f,%f]" + key + location.latitude + location.longitude);
            }

            @Override
            public void onGeoQueryReady() {
                Log.d("test","All initial data has been loaded and events have been fired!");
            }

            @Override
            public void onGeoQueryError(DatabaseError error) {
                Log.d("test","There was an error with this query: " + error);
            }
        });

    }
});

This is working, but only for the first time when I start my activity, now I'm using the SFVehicles example to create live queries:

private GeoFire geoFire;
private GeoQuery geoQuery;
private MapView mapView;
private MapboxMap map;
private Map<String,Marker> markers;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_rallye_main);

    // setup map and camera position
    SupportMapFragment mapFragment = (SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.map);

    this.map = mapFragment.getMap();

    LatLng latLngCenter = new LatLng(INITIAL_CENTER.latitude, INITIAL_CENTER.longitude);
    this.map.moveCamera(CameraUpdateFactory.newLatLngZoom(latLngCenter, INITIAL_ZOOM_LEVEL));
    this.map.setOnCameraChangeListener(this);

    FirebaseOptions options = new FirebaseOptions.Builder().setApplicationId("geofire").build();
    FirebaseApp app = FirebaseApp.initializeApp(this, options);

    // setup GeoFire
    this.geoFire = new GeoFire(FirebaseDatabase.getInstance(app).getReferenceFromUrl(GEO_FIRE_REF));
    // radius in km gibt alle positionen der Teilnehmer im radius von x km aus
    this.geoQuery = this.geoFire.queryAtLocation(INITIAL_CENTER, 50);

    // setup markers
    this.markers = new HashMap<String, Marker>();

}

@Override
protected void onStop() {
    super.onStop();
    // remove all event listeners to stop updating in the background
    this.geoQuery.removeAllListeners();
    for (Marker marker: this.markers.values()) {
        marker.remove();
    }
    this.markers.clear();
}

@Override
protected void onStart() {
    super.onStart();
    // add an event listener to start updating locations again
    this.geoQuery.addGeoQueryEventListener(this);
}

@Override
public void onKeyEntered(String key, GeoLocation location) {
    // Add a new marker to the map
    Marker marker = this.map.addMarker(new MarkerOptions().position(new LatLng(location.latitude, location.longitude)));
    this.markers.put(key, marker);
}

@Override
public void onKeyExited(String key) {
    // Remove any old marker
    Marker marker = this.markers.get(key);
    if (marker != null) {
        marker.remove();
        this.markers.remove(key);
    }
}

@Override
public void onKeyMoved(String key, GeoLocation location) {
    // Move the marker
    Marker marker = this.markers.get(key);
    if (marker != null) {
        this.animateMarkerTo(marker, location.latitude, location.longitude);
    }
}

@Override
public void onGeoQueryReady() {
}

@Override
public void onGeoQueryError(DatabaseError error) {
    new AlertDialog.Builder(this)
            .setTitle("Error")
            .setMessage("There was an unexpected error querying GeoFire: " + error.getMessage())
            .setPositiveButton(android.R.string.ok, null)
            .setIcon(android.R.drawable.ic_dialog_alert)
            .show();
}

// Animation handler for old APIs without animation support
private void animateMarkerTo(final Marker marker, final double lat, final double lng) {
    final Handler handler = new Handler();
    final long start = SystemClock.uptimeMillis();
    final long DURATION_MS = 3000;
    final Interpolator interpolator = new AccelerateDecelerateInterpolator();
    final LatLng startPosition = marker.getPosition();
    handler.post(new Runnable() {
        @Override
        public void run() {
            float elapsed = SystemClock.uptimeMillis() - start;
            float t = elapsed/DURATION_MS;
            float v = interpolator.getInterpolation(t);

            //double currentLat = (lat - startPosition.latitude) * v + startPosition.latitude;
            //double currentLng = (lng - startPosition.longitude) * v + startPosition.longitude;
            double currentLat = (lat - startPosition.getLatitude()) * v + startPosition.getLatitude();
            double currentLng = (lng - startPosition.getLongitude()) * v + startPosition.getLongitude();
            marker.setPosition(new LatLng(currentLat, currentLng));

            // if animation is not finished yet, repeat
            if (t < 1) {
                handler.postDelayed(this, 16);
            }
        }
    });
}

private double zoomLevelToRadius(double zoomLevel) {
    // Approximation to fit circle into view
    return 16384000/Math.pow(2, zoomLevel);
}

@Override
public void onCameraChange(CameraPosition cameraPosition) {
    // Update the search criteria for this geoQuery and the circle on the map
    LatLng center = cameraPosition.target;
    double radius = zoomLevelToRadius(cameraPosition.zoom);
    this.geoQuery.setCenter(new GeoLocation(center.getLatitude(), center.getLongitude()));
    // radius in km
    this.geoQuery.setRadius(radius/1000);
}

The example code using Google map but I have to use Mapbox to provide offline maps and I get errors on this line:

SupportMapFragment mapFragment = (SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.map);

this.map = mapFragment.getMap();

Specifically:

Cannot resolve Method getMap()

I have already tried something like:

mapFragment.getMapAsync(new OnMapReadyCallback() {
    @Override
    public void onMapReady(MapboxMap mapboxMap) {

        // Customize map with markers, polylines, etc.

    }
});

But nothing, I get this error:

FATAL EXCEPTION: main Process: com.test.bla, PID: 30149
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.test.bla/com.test.bla.rallye.rallye_main}: android.view.InflateException: Binary XML file line >#2: Error inflating class fragment
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2689)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2754)
at android.app.ActivityThread.access$900(ActivityThread.java:177)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1448)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:5938)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1400)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1195)
Caused by: android.view.InflateException: Binary XML file line #2: Error inflating class fragment
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:770)
at android.view.LayoutInflater.inflate(LayoutInflater.java:483)
at android.view.LayoutInflater.inflate(LayoutInflater.java:415)
at android.view.LayoutInflater.inflate(LayoutInflater.java:366)
at android.transition.Scene.enter(Scene.java:175)
at com.android.internal.policy.impl.PhoneWindow.transitionTo(PhoneWindow.java:483)
at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:426)
at android.app.Activity.setContentView(Activity.java:2267).....

I can't convert this example from Google mapx to Mapbox

Layout

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:mapbox="http://schemas.android.com/apk/res-auto"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">

    <com.mapbox.mapboxsdk.maps.MapView
        android:id="@+id/mapView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        mapbox:mapbox_cameraTargetLat="52.00000"
        mapbox:mapbox_cameraTargetLng="8.00000"
        mapbox:mapbox_styleUrl="@string/mapbox_style_mapbox_streets"
        mapbox:mapbox_cameraZoom="12"/>

</RelativeLayout>

or my second try:

<?xml version="1.0" encoding="utf-8"?>
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/map"
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>


问:
Pre-populate modal textarea with text
Currently a button opens a modal that includes a text box. I need have that text box pre-populated, so I have attempted to mess around with the modal with no luck.

I have tried the following and nothing appears to happen.

function testFunc(){
    $('#contactUsDlg').modal('show');
    $('#contactUsDlg').on('shown.bs.modal', function {
       $('#message-text').text("test");
    });
}```
<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>
<button type="button" name="btn-ask" id="nonconform-btn" data-form-action-url="${newMessageUrl}"
                                data-pns="<%=OrderStatusPortletConstants.MESSAGE_CENTER_PORTLET_NAMESPACE %>"
                                data-use-ajax="true"
                                class="btn btn-submit btn-ask contact-us-dlg"
                                data-hidden-fields="message-order-id,message-source-url"
                                data-message-order-id="${selectedOrder.id}" data-message-source-url="${sourceUrl}" >
                                Contact Us
</button></code>```

答:
If you haven't already, you should look into using jQuery UI. Here you can use something like the following:</p>

```<code><script src='jquery-3.2.1.min.js'></script>
<script src='jquery-ui-1.12.1.custom/jquery-ui.js'></script>
<link href='jquery-ui-1.12.1.custom/jquery-ui.css' rel='stylesheet' type='text/css'></link>
<link href='jquery-ui-1.12.1.custom/jquery-ui.theme.css' rel='stylesheet' type='text/css'></link>

<input id='mybutton' type='button' value='click me' />
<div id='result'>
    <p id='firstp'></p>
    <p id='secondp'></p>
</div>

<script>
$(function() {
    $('#result').dialog({
        open: function(event, ui) {
            $('#resultp').html('[this is my text]');
        }
    });
});
$('#mybutton').on('click', function(evt) {
    $('#secondp').html('[this is my second text]');
});
</script>
</code>```

Title: Pre-populate modal textarea with text

Body:
Currently a button opens a modal that includes a text box. I need have that text box pre-populated, so I have attempted to mess around with the modal with no luck.

I have tried the following and nothing appears to happen.

function testFunc(){
    $('#contactUsDlg').modal('show');
    $('#contactUsDlg').on('shown.bs.modal', function {
       $('#message-text').text("test");
    });
}

<button type="button" name="btn-ask" id="nonconform-btn" data-form-action-url="${newMessageUrl}"
                                data-pns="<%=OrderStatusPortletConstants.MESSAGE_CENTER_PORTLET_NAMESPACE %>"
                                data-use-ajax="true"
                                class="btn btn-submit btn-ask contact-us-dlg"
                                data-hidden-fields="message-order-id,message-source-url"
                                data-message-order-id="${selectedOrder.id}" data-message-source-url="${sourceUrl}" >
                                Contact Us
</button>

Body:
If you haven't already, you should look into using jQuery UI. Here you can use something like the following:

<script src='jquery-3.2.1.min.js'></script>
<script src='jquery-ui-1.12.1.custom/jquery-ui.js'></script>
<link href='jquery-ui-1.12.1.custom/jquery-ui.css' rel='stylesheet' type='text/css'></link>
<link href='jquery-ui-1.12.1.custom/jquery-ui.theme.css' rel='stylesheet' type='text/css'></link>

<input id='mybutton' type='button' value='click me' />
<div id='result'>
    <p id='firstp'></p>
    <p id='secondp'></p>
</div>

<script>
$(function() {
    $('#result').dialog({
        open: function(event, ui) {
            $('#resultp').html('[this is my text]');
        }
    });
});
$('#mybutton').on('click', function(evt) {
    $('#secondp').html('[this is my second text]');
});
</script>


问:
iTextSharp - Text overlapping image
I'm using iTextSharpText to build a PDF.

I was asked to add some dynamic text over an image.
I've already tried some examples that I found on this forum and other websites, but I can't seem to get this right, and it's really driving me nuts.

I followed this thread (iTextSharp Adding Text plus Barcode in a single cell?), and tried both answers.

First I tried:

```<code>            var img_operacao = Image.GetInstance(String.Format("{0}{1}", Settings.Default.SiteRootURL, "/PublishingImages/PDF_operacao.png"));
            img_operacao.ScaleToFit(150, 41);

            img_operacao.Alignment = Image.UNDERLYING;

            var ph0 = new Phrase(title0, pageHeader);
            var cell = new PdfPCell();

            cell.AddElement(ph0);
            cell.AddElement(new Phrase(new Chunk(img_operacao, 0, 0)));
            table.AddCell(cell);
</code>```

And I got this:
http://imageshack.us/photo/my-images/515/25265113.png/

My second attempt:

```<code>            var img_operacao = Image.GetInstance(String.Format("{0}{1}", Settings.Default.SiteRootURL, "/PublishingImages/PDF_operacao.png"));
            img_operacao.ScaleToFit(150, 41);

            img_operacao.Alignment = Image.UNDERLYING;

            var cell = new PdfPCell
                       {
                           Border = Rectangle.NO_BORDER,
                           PaddingTop = 0,
                           PaddingBottom = 0,
                           HorizontalAlignment = Element.ALIGN_CENTER,
                           VerticalAlignment = Element.ALIGN_MIDDLE
                       };

            var ph0 = new Phrase();
            ph0.Add(new Chunk(title0, pageHeader));
            ph0.Add(new Chunk(img_operacao, 0, 0, true));

            cell.AddElement(ph0);
            table.AddCell(cell);
</code>```

And I got:
http://imageshack.us/photo/my-images/688/89424619.png/

I've tried several other variations with chunks, paragraphs, etc, but I can't get the text over the image!!!

If there is someone that can help me, I would really appreciate it.
I'm stuck right now...

Thanks a lot

Paula

答: I stumbled across a solution while trying to resolve this issue for my own needs.  I created a Table object and defined multiple columns.  The first column was set to a minimum width, and the rest the appropriate widths to position text being positioned on the form.   I am producing an image about 1"x7".  The image was added to the cell in the first column of a table row.  It's dimensions as set by SetAbsoluteHeight and SetAbsoluteWidth far exceeded the size of the column, so the image kind of bled into/under the remaining columns of the row.  For the text being overlaid onto the image, column widths, adding Chunk.Newlines, and paragraph SetLeading (to effect line spacing) were used to adjust text positioning.</p>

Title: iTextSharp - Text overlapping image

Body:
I'm using iTextSharpText to build a PDF.

I was asked to add some dynamic text over an image.
I've already tried some examples that I found on this forum and other websites, but I can't seem to get this right, and it's really driving me nuts.

I followed this thread (iTextSharp Adding Text plus Barcode in a single cell?), and tried both answers.

First I tried:

            var img_operacao = Image.GetInstance(String.Format("{0}{1}", Settings.Default.SiteRootURL, "/PublishingImages/PDF_operacao.png"));
            img_operacao.ScaleToFit(150, 41);

            img_operacao.Alignment = Image.UNDERLYING;

            var ph0 = new Phrase(title0, pageHeader);
            var cell = new PdfPCell();

            cell.AddElement(ph0);
            cell.AddElement(new Phrase(new Chunk(img_operacao, 0, 0)));
            table.AddCell(cell);

And I got this:
http://imageshack.us/photo/my-images/515/25265113.png/

My second attempt:

            var img_operacao = Image.GetInstance(String.Format("{0}{1}", Settings.Default.SiteRootURL, "/PublishingImages/PDF_operacao.png"));
            img_operacao.ScaleToFit(150, 41);

            img_operacao.Alignment = Image.UNDERLYING;

            var cell = new PdfPCell
                       {
                           Border = Rectangle.NO_BORDER,
                           PaddingTop = 0,
                           PaddingBottom = 0,
                           HorizontalAlignment = Element.ALIGN_CENTER,
                           VerticalAlignment = Element.ALIGN_MIDDLE
                       };

            var ph0 = new Phrase();
            ph0.Add(new Chunk(title0, pageHeader));
            ph0.Add(new Chunk(img_operacao, 0, 0, true));

            cell.AddElement(ph0);
            table.AddCell(cell);

And I got:
http://imageshack.us/photo/my-images/688/89424619.png/

I've tried several other variations with chunks, paragraphs, etc, but I can't get the text over the image!!!

If there is someone that can help me, I would really appreciate it.
I'm stuck right now...

Thanks a lot

Paula


问:
ES Lint error for jQuery anonymous function
The code I have is as follows:

```<code>$('.panel').each( function() {
    $(this).css('height', 'auto');
    $(this).find('.portlet-panel-item').css('height', 'auto');
});
</code>```

I am getting the following error: 37:26  warning  Missing function expression name  func-names.

I can't use the ES6 arrow functions because of the way this is being handled in the two use cases.

How can I fix this issue without having to put named functions for each?

答:
You should either use a named function or disable the rule.

From AirBnB JavaScript style guide:

Don’t forget to name the expression - anonymous functions can make it harder to locate the problem in an Error's call stack.

You can set this rule to check "always", "as-needed", or "never" by using a comment, so in your case:
/*eslint func-names: ["error", "never"]*/

Body:
The code I have is as follows:

$('.panel').each( function() {
    $(this).css('height', 'auto');
    $(this).find('.portlet-panel-item').css('height', 'auto');
});

I am getting the following error: 37:26  warning  Missing function expression name  func-names.

I can't use the ES6 arrow functions because of the way this is being handled in the two use cases.

How can I fix this issue without having to put named functions for each?


问:
issue with rotation and uilabels with size set using NSString's sizeWithFont
I have a few UILabels in my view with their height set using sizeWithFont:.

I set the autoreszingMask to flexible width and height, however on rotate the width changes (am assuming because self.view's width changes and its set with a width relative to self.view) but the height of it doesn't change to fit the content again. This results in a large white space at the top and bottom.

Just wondering how I would go about re-sizing the UILabel on rotation? Is there any automatic way of doing this, or is there a way of getting all UILabels and re-doing sizeWithFont when the device is rotated?

The UILabels are subviews of UIView heirarchies used as headers for sections in my UITableView.

Thanks
Tom

答:
The problem was having a flexible left and right margin on a slightly offset uilabel.

If the label isn't centered then you need to choose left or right and set the flexible margin for one of those.


问:
Deleting Visualization from Kibana
I just added a large JSON object in the Visualization x-axis filters tab which sent me to this page

http://localhost:5601/app/kibana#/error/url-overflow?_g=()

Kibana limits URLs in your browser to 25000 characters for your safety.

Kibana is shutting me out. How can I delete this visualization?

答:
Solved this if anyone else has this problem. Kibana UI is saving the previous request somewhere (tried clearing everything) ended up going to each of the following links to reset the 'saved url'..

http://localhost:5601/app/kibana#/dashboard

http://localhost:5601/app/kibana#/timelion

http://localhost:5601/app/kibana#/visualize/new

Title: Deleting Visualization from Kibana


问:
How do I keep the divs side by side in the container?
I want to create container that has two elements with colors given in the picture.  The two are different divs and must stay side by side.  How do I do it?

Here is my code:

  <title>Testing</title>

```

答:
```<code>How about this:

<div class="container">
   <div class="sidenav">
      test
   </div>
   <div class="bgrnd">
      test
   </div>
</div>

CSS:

.container {
    width: 50%;
    height: 50%;
}
.sidenav {
    width: 25%;
    height: 100%;
    background-color: black;
    color: #fff;
    float: left;
}
.bgrnd {
    width: 75%;
    height: 100%;
    background-color: blue;
    color: #fff;
    float: right;
}
</code>```


问:
Cannot get MEAN app deployed to Heroku because of “ No default language could be detected for this app.”
I am trying to deploy a MEAN app to Heroku, but cannot push due to the following error:

```<code> !     No default language could be detected for this app.
        HINT: This occurs when Heroku cannot detect the buildpack to use for this application automatically.
        See https://devcenter.heroku.com/articles/buildpacks
!     Push failed
</code>```

I tried setting a node.js buildpack with their latest node buildpack release, but just received another error:

```<code>failed to detect buildpack
</code>```

This is my first deployment to Heroku, so I'm brand new at this.

Here are my package.jsons:

 Server

```<code>{
  "version": "0.0.0",
  "private": true,
  "scripts": {
    "start": "node ./bin/www"
  },
  "dependencies": {
    "bcrypt": "^1.0.2",
    "body-parser": "^1.16.1",
    "cookie-parser": "^1.4.3",
    "cors": "^2.8.2",
    "debug": "^2.6.3",
    "ejs": "~2.5.5",
    "express": "^4.14.1",
    "jsonwebtoken": "^7.3.0",
    "mongoose": "^4.9.2",
    "morgan": "^1.7.0",
    "multer": "^1.3.0",
    "passport": "^0.3.2",
    "passport-jwt": "^2.2.1",
    "request": "^2.81.0",
    "request-promise": "^4.2.0",
    "serve-favicon": "^2.3.2"
  }
}
</code>```

 Client

```<code>{
  "version": "0.0.0",
  "license": "MIT",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
  },
  "private": true,
  "dependencies": {
    "@angular/common": "^2.4.0",
    "@angular/compiler": "^2.4.0",
    "@angular/core": "^2.4.0",
    "@angular/forms": "^2.4.0",
    "@angular/http": "^2.4.0",
    "@angular/platform-browser": "^2.4.0",
    "@angular/platform-browser-dynamic": "^2.4.0",
    "@angular/router": "^3.4.0",
    "@types/googlemaps": "^3.26.8",
    "@types/jquery": "^2.0.43",
    "@types/lodash": "^4.14.62",
    "@types/underscore": "^1.8.0",
    "amcharts3-angular2": "github:amcharts/amcharts3-angular2",
    "angular2-google-maps": "^0.17.0",
    "core-js": "^2.4.1",
    "dotenv": "^4.0.0",
    "jquery": "^3.2.1",
    "lodash": "^4.17.4",
    "ng2-google-charts": "^2.1.0",
    "rxjs": "^5.1.0",
    "tslint": "^4.4.2",
    "typescript": "^2.0.10",
    "underscore": "^1.8.3",
    "zone.js": "^0.7.6"
  },
  "devDependencies": {
    "@angular/cli": "1.0.0-rc.0",
    "@angular/compiler-cli": "^2.4.0",
    "@types/jasmine": "2.5.38",
    "@types/node": "~6.0.60",
    "codelyzer": "~2.0.0",
    "jasmine-core": "~2.5.2",
    "jasmine-spec-reporter": "~3.2.0",
    "karma": "~1.4.1",
    "karma-chrome-launcher": "~2.0.0",
    "karma-cli": "~1.0.1",
    "karma-jasmine": "~1.1.0",
    "karma-jasmine-html-reporter": "^0.2.2",
    "karma-coverage-istanbul-reporter": "^0.2.0",
    "protractor": "~5.1.0",
    "ts-node": "~2.0.0",
    "tslint": "~4.4.2",
    "typescript": "~2.0.0"
  }
}
</code>```

Why is Heroku not detecting Node?

答: I have two package.jsons, one for client and one for server.  I needed to put my server dependencies into the root folder (they were each nested in client and server folders, respectively).  Moving it into root made it detectable by heroku.  Of course, now I have a new error.  :)</p>

Body:
I am trying to deploy a MEAN app to Heroku, but cannot push due to the following error:

 !     No default language could be detected for this app.
        HINT: This occurs when Heroku cannot detect the buildpack to use for this application automatically.
        See https://devcenter.heroku.com/articles/buildpacks
!     Push failed

I tried setting a node.js buildpack with their latest node buildpack release, but just received another error:

failed to detect buildpack

This is my first deployment to Heroku, so I'm brand new at this.

Here are my package.jsons:

 Server

{
  "version": "0.0.0",
  "private": true,
  "scripts": {
    "start": "node ./bin/www"
  },
  "dependencies": {
    "bcrypt": "^1.0.2",
    "body-parser": "^1.16.1",
    "cookie-parser": "^1.4.3",
    "cors": "^2.8.2",
    "debug": "^2.6.3",
    "ejs": "~2.5.5",
    "express": "^4.14.1",
    "jsonwebtoken": "^7.3.0",
    "mongoose": "^4.9.2",
    "morgan": "^1.7.0",
    "multer": "^1.3.0",
    "passport": "^0.3.2",
    "passport-jwt": "^2.2.1",
    "request": "^2.81.0",
    "request-promise": "^4.2.0",
    "serve-favicon": "^2.3.2"
  }
}

 Client

{
  "version": "0.0.0",
  "license": "MIT",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
  },
  "private": true,
  "dependencies": {
    "@angular/common": "^2.4.0",
    "@angular/compiler": "^2.4.0",
    "@angular/core": "^2.4.0",
    "@angular/forms": "^2.4.0",
    "@angular/http": "^2.4.0",
    "@angular/platform-browser": "^2.4.0",
    "@angular/platform-browser-dynamic": "^2.4.0",
    "@angular/router": "^3.4.0",
    "@types/googlemaps": "^3.26.8",
    "@types/jquery": "^2.0.43",
    "@types/lodash": "^4.14.62",
    "@types/underscore": "^1.8.0",
    "amcharts3-angular2": "github:amcharts/amcharts3-angular2",
    "angular2-google-maps": "^0.17.0",
    "core-js": "^2.4.1",
    "dotenv": "^4.0.0",
    "jquery": "^3.2.1",
    "lodash": "^4.17.4",
    "ng2-google-charts": "^2.1.0",
    "rxjs": "^5.1.0",
    "tslint": "^4.4.2",
    "typescript": "^2.0.10",
    "underscore": "^1.8.3",
    "zone.js": "^0.7.6"
  },
  "devDependencies": {
    "@angular/cli": "1.0.0-rc.0",
    "@angular/compiler-cli": "^2.4.0",
    "@types/jasmine": "2.5.38",
    "@types/node": "~6.0.60",
    "codelyzer": "~2.0.0",
    "jasmine-core": "~2.5.2",
    "jasmine-spec-reporter": "~3.2.0",
    "karma": "~1.4.1",
    "karma-chrome-launcher": "~2.0.0",
    "karma-cli": "~1.0.1",
    "karma-jasmine": "~1.1.0",
    "karma-jasmine-html-reporter": "^0.2.2",
    "karma-coverage-istanbul-reporter": "^0.2.0",
    "protractor": "~5.1.0",
    "ts-node": "~2.0.0",
    "tslint": "~4.4.2",
    "typescript": "~2.0.0"
  }
}

Why is Heroku not detecting Node?


问:
How to see real call stack in WinDbg when we break with CTRL + Break
When we have a regular breakpoint, the debugger breaks there and we see the call stack. But what if we break the execution using CTRL + Break? I would expect the currently running thread to break whererbrt it was but what I see typically is the following:

```<code> # ChildEBP RetAddr
00 02b7fdc4 7762f216 ntdll!DbgBreakPoint
01 02b7fdf4 76c0336a ntdll!DbgUiRemoteBreakin+0x3c
02 02b7fe00 775c9902 kernel32!BaseThreadInitThunk+0xe
03 02b7fe40 775c98d5 ntdll!__RtlUserThreadStart+0x70
04 02b7fe58 00000000 ntdll!_RtlUserThreadStart+0x1b
*** WARNING: Unable to verify checksum for ThreadDemo.exe
</code>```

But how do I get to the actual code of current thread that got interrupted?

I am running a long loop as below which takes sometime and I expect it to break there.

```<code>void Bank::Deposit(void* param)
{
    Bank * bank = (Bank *)param;

    char *who = (char*) bank->bankName;

    int i;
    printf("%s: begin deposite\n", who);
    for (i = 0; i < 1000000000; i++) {
        bank->balance = bank->balance + 1;
    }
    printf("%s: done\n", who);

    return;
}
</code>```

In this case when it breaks, one of the other thread does break in this function but this is a simple demo. How can I know in real windows application where did the application really stopped (and what was it doing) when I have many threads?

答:
When you press Ctrl+C or Ctrl+Break, that keyboard event is processed by the debugger. This implies that at least one thread of the debugger is running at that time and not yours. Figuring out which thread was running before is not so easy.

The debugger will inject a new thread into your application with an int 3 instruction on the call stack. This thread is not running immediately, it first has to be scheduled by the operating system to run. This requires a context switch.

When the int 3 is reached, all threads in the process get suspended and the debugger is notified about the exception. So, between you press a key and when the threads actually stop, a time between ~15 ms and ~30 ms passes by.

However, this is nothing to worry about. Given an average human reaction time of 25 ms, millions of CPU instructions are between an observation which makes you want to stop the threads and the actual stop.

As already mentioned by Sean Cline in the comments and in the answer of Mike Vine, the other threads are stil there. You can list them with ~, show the call stacks of them using ~*k or switch to a particular thread with ~<thread>s.

Body:
When we have a regular breakpoint, the debugger breaks there and we see the call stack. But what if we break the execution using CTRL + Break? I would expect the currently running thread to break whererbrt it was but what I see typically is the following:

 # ChildEBP RetAddr
00 02b7fdc4 7762f216 ntdll!DbgBreakPoint
01 02b7fdf4 76c0336a ntdll!DbgUiRemoteBreakin+0x3c
02 02b7fe00 775c9902 kernel32!BaseThreadInitThunk+0xe
03 02b7fe40 775c98d5 ntdll!__RtlUserThreadStart+0x70
04 02b7fe58 00000000 ntdll!_RtlUserThreadStart+0x1b
*** WARNING: Unable to verify checksum for ThreadDemo.exe

But how do I get to the actual code of current thread that got interrupted?

I am running a long loop as below which takes sometime and I expect it to break there.

void Bank::Deposit(void* param)
{
    Bank * bank = (Bank *)param;

    char *who = (char*) bank->bankName;

    int i;
    printf("%s: begin deposite\n", who);
    for (i = 0; i < 1000000000; i++) {
        bank->balance = bank->balance + 1;
    }
    printf("%s: done\n", who);

    return;
}

In this case when it breaks, one of the other thread does break in this function but this is a simple demo. How can I know in real windows application where did the application really stopped (and what was it doing) when I have many threads?


问:
Java 8: How to create DateTimeFormatter with milli, micro or nano seconds?
I need to create the formatter for parsing timestamps with optional milli, micro or nano fractions of second.

For example, for my needs I see the following opportunity:

```<code>DateTimeFormatter formatter = new DateTimeFormatterBuilder()
                                   .append(DateTimeFormatter.BASIC_ISO_DATE)
                                   .appendLiteral('-')
                                   .append(DateTimeFormatter.ISO_LOCAL_TIME)
                                   .appendOffset("+HH:mm", "Z")
                                   .toFormatter();
</code>```

Or it is also possible to use appendFraction(field, minWidth, maxWidth, decimalPoint).

However in these cases will it be possible to parse timestamps with any number of decimals (up to 9 or maxWidth). How to achieve that we can parse (optionally) only 3, 6 or 9 numbers after the comma?

It should be possible to parse the following time parts:

HH:mm:ss.SSS

HH:mm:ss.SSSSSS

HH:mm:ss.SSSSSSSSS

But impossible to parse: HH:mm:ss.SSSS.

答:
DateTimeFormatter only supports width ranges, so this wouldn't be possible with a single instance. You could make 3 separate formatters using .appendFraction(NANO_OF_SECOND, #, #, true) where # is 3, 6, or 9. Then try them in sequence, ignoring any DateTimeParseException until the last one:

```<code>private static TemporalAccessor parse(String text) {
    try {
        return formatter3.parse(text);
    } catch (DateTimeParseException e) {
        // ignore
    }
    try {
        return formatter6.parse(text);
    } catch (DateTimeParseException e) {
        // ignore
    }
    return formatter9.parse(text); // let this one throw
}
</code>```

Another option would be checking the input with a regular expression first, something like text.matches("[^.]+(.+\\.(\\d{3}|\\d{6}|\\d{9})\\b.*)?").

Body:
I need to create the formatter for parsing timestamps with optional milli, micro or nano fractions of second.

For example, for my needs I see the following opportunity:

DateTimeFormatter formatter = new DateTimeFormatterBuilder()
                                   .append(DateTimeFormatter.BASIC_ISO_DATE)
                                   .appendLiteral('-')
                                   .append(DateTimeFormatter.ISO_LOCAL_TIME)
                                   .appendOffset("+HH:mm", "Z")
                                   .toFormatter();

Or it is also possible to use appendFraction(field, minWidth, maxWidth, decimalPoint).

However in these cases will it be possible to parse timestamps with any number of decimals (up to 9 or maxWidth). How to achieve that we can parse (optionally) only 3, 6 or 9 numbers after the comma?

It should be possible to parse the following time parts:

HH:mm:ss.SSS

HH:mm:ss.SSSSSS

HH:mm:ss.SSSSSSSSS

But impossible to parse: HH:mm:ss.SSSS.

Body:
DateTimeFormatter only supports width ranges, so this wouldn't be possible with a single instance. You could make 3 separate formatters using .appendFraction(NANO_OF_SECOND, #, #, true) where # is 3, 6, or 9. Then try them in sequence, ignoring any DateTimeParseException until the last one:

private static TemporalAccessor parse(String text) {
    try {
        return formatter3.parse(text);
    } catch (DateTimeParseException e) {
        // ignore
    }
    try {
        return formatter6.parse(text);
    } catch (DateTimeParseException e) {
        // ignore
    }
    return formatter9.parse(text); // let this one throw
}

Another option would be checking the input with a regular expression first, something like text.matches("[^.]+(.+\\.(\\d{3}|\\d{6}|\\d{9})\\b.*)?").


问:
Architetural Considerations for VueJS project: Implementing Vuex
Our front-end team is presently working on a Reporting application with the following features:

Dashboards

Portfolio Analysis Tool (search form that returns grid-based results)

Automated Reports page

We've decided to architect the above using VueJS with the Webpack boilerplate (via Vue-Cli) and are trying to design to have common components:

A report component

Has title, description, type (grid, visualization, etc.) and some setting parameters

A report list component

Has a title and an array of report components as its properties

A dashboard that has an array of report list components arranged in a grid

Some requirements

A dashboard component can have 4 or more report list components, each with multiple reports that can be selected for view by the user from a report list select menu. Each report component can have one or more setting parameters that the user can manipulate and submit to re-render the report. A report can be a grid (ag-grid in our case) or a visualization-based report. Lastly, there is also authentication via Auth0.

Questions

Does it make sense to use Vuex to manage state for all our components and related interactions?

Does it sound like the application is a good use-case for Vuex?

If so, why? Is it better than using component to component communication via the built in Vue mechanisms (for parent-child, sibling-sibling components)?

Thank you in advance for helping us make a decision.

答:
Vuex is useful when you have multiple components that need the same state. In your case, you're displaying reports in lots of different places and formats. This is a great use case for Vuex in my opinion.

Now, i don't know if your team is familiar with Vue, but passing data via props is a PITA. Especially if the components that need the data are spread far away in the component hierarchy, and deeply nested, which they usually are. Anyone who's been thru the gauntlet of passing props and emitting events up multiple levels will tell you that.

With Vuex, it's a single function call to get your data, from ANYWHERE in the component hierachy. It's a breath of fresh air.


问:
modify plist inside list?
I have a list of plists such as

```<code>'((:atom Toddler :visited nil :on-clauses (0 1))
  (:atom Child   :visited nil :on-clauses 1))
</code>```

how should I change the :onclauses property on a given :atom? I'd like to update this property, e.g. making the second plist (:atom Child :visited nil :on-clauses (1 2)) (only adding new values, never deleting the old ones).

the best I could do was to create a new list from scratch using

```<code>(remove-if-not #'(lambda(record)
                   (equal (getf record :atom) atom))
               *ATOMS*)
</code>```

to get the initial value, updating it, then using its analogue to get a list without this value, and append both together, but this is probably terribly inneficient (I know premature optimatization is bad, but I'm learning LISP and want to know how to do things properly!)

答:
Use POSITION to find the plist with the specific :atom, and then REMF to remove the property from that plist.

```<code>(defun update-on-clauses (atom new-on-clause)
  (let ((pos (position atom *atoms*
                       :key #'(lambda (record) (getf record :atom)))))
    (when pos
      (setf (getf (nth pos *atoms*) :on-clauses) new-on-clause))))
</code>```

It might be simpler to make *ATOMS* an alist that maps atoms to property lists.

Title: modify plist inside list?

Body:
I have a list of plists such as

'((:atom Toddler :visited nil :on-clauses (0 1))
  (:atom Child   :visited nil :on-clauses 1))

how should I change the :onclauses property on a given :atom? I'd like to update this property, e.g. making the second plist (:atom Child :visited nil :on-clauses (1 2)) (only adding new values, never deleting the old ones).

the best I could do was to create a new list from scratch using

(remove-if-not #'(lambda(record)
                   (equal (getf record :atom) atom))
               *ATOMS*)

to get the initial value, updating it, then using its analogue to get a list without this value, and append both together, but this is probably terribly inneficient (I know premature optimatization is bad, but I'm learning LISP and want to know how to do things properly!)

Body:
Use POSITION to find the plist with the specific :atom, and then REMF to remove the property from that plist.

(defun update-on-clauses (atom new-on-clause)
  (let ((pos (position atom *atoms*
                       :key #'(lambda (record) (getf record :atom)))))
    (when pos
      (setf (getf (nth pos *atoms*) :on-clauses) new-on-clause))))

It might be simpler to make *ATOMS* an alist that maps atoms to property lists.


问:
Maximum path sum In a triangle with prime number check
I was given this algorithm task:

You will have a triangle input below and you need to find the maximum sum of the numbers according to given rules below;

You will start from the top and move downwards to an adjacent number as in below.

You are only allowed to walk downwards and diagonally.

You can only walk over NON PRIME NUMBERS.

```<code>     1
    8 4
  2  6  9
 8  5  9  3
</code>```

As you can see this has several paths that fits the rule of NOT PRIME NUMBERS; 1>8>6>9, 1>4>6>9, 1>4>9>9
1 + 8 + 6 + 9 = 24.  As you see 1, 8, 6, 9 are all NOT PRIME NUMBERS and walking over these yields the maximum sum.

According to above rules what is the maximum sum of below input? It means please take this pyramid as an input (as file or constants directly inside the code) for your implementation and solve by using it.

```<code>                                  215
                               193 124
                             117 237 442
                           218 935 347 235
                         320 804 522 417 345
                       229 601 723 835 133 124
                     248 202 277 433 207 263 257
                   359 464 504 528 516 716 871 182
                 461 441 426 656 863 560 380 171 923
               381 348 573 533 447 632 387 176 975 449
             223 711 445 645 245 543 931 532 937 541 444
           330 131 333 928 377 733 017 778 839 168 197 197
        131 171 522 137 217 224 291 413 528 520 227 229 928
      223 626 034 683 839 053 627 310 713 999 629 817 410 121
    924 622 911 233 325 139 721 218 253 223 107 233 230 124 233
</code>```

Note that, each node has only two children here (except the most bottom ones). As an example, you can walk from 215 to 124 (because 193 is a prime) then from 124 to either 237 or 442. From 124 you cannot go to 117 because it’s not a direct child of 124.

I know there are different approaches of solving this problem which can be

Brute Force method

Dynamic Programming method

I used Dynamic Programming method approach due to its efficiency:

```<code>using System;

class Program
{
    static void Main(string[] args)
    {

        //get input
        var input = GetInput();

        string[] arrayOfRowsByNewlines = input.Split('\n');

        var tableHolder = FlattenTheTriangleIntoTable(arrayOfRowsByNewlines);

        var result = WalkThroughTheNode(arrayOfRowsByNewlines, tableHolder);

        Console.WriteLine($"The Maximum Total Sum Of Non-Prime Numbers From Top To Bottom Is:  {result[0,0]}");

        Console.ReadKey();
    }

    private static string GetInput()
    {

            const string input = @"   215
                                   193 124
                                  117 237 442
                                218 935 347 235
                              320 804 522 417 345
                            229 601 723 835 133 124
                          248 202 277 433 207 263 257
                        359 464 504 528 516 716 871 182
                      461 441 426 656 863 560 380 171 923
                     381 348 573 533 447 632 387 176 975 449
                   223 711 445 645 245 543 931 532 937 541 444
                 330 131 333 928 377 733 017 778 839 168 197 197
                131 171 522 137 217 224 291 413 528 520 227 229 928
              223 626 034 683 839 053 627 310 713 999 629 817 410 121
            924 622 911 233 325 139 721 218 253 223 107 233 230 124 233";
        return input;
    }

    private static int[,] WalkThroughTheNode(string[] arrayOfRowsByNewlines, int[,] tableHolder)
    {
        // walking through the non-prime node
        for (int i = arrayOfRowsByNewlines.Length - 2; i >= 0; i--)
        {
            for (int j = 0; j < arrayOfRowsByNewlines.Length; j++)
            {
                //only sum through the non-prime node
                if ((!IsPrime(tableHolder[i, j])))
                {
                    tableHolder[i, j] = Math.Max(tableHolder[i, j] + tableHolder[i + 1, j],
                        tableHolder[i, j] + tableHolder[i + 1, j + 1]);
                }
            }
        }
        return tableHolder;
    }

    private static int[,] FlattenTheTriangleIntoTable(string[] arrayOfRowsByNewlines)
    {
        int[,] tableHolder = new int[arrayOfRowsByNewlines.Length, arrayOfRowsByNewlines.Length + 1];

        for (int row = 0; row < arrayOfRowsByNewlines.Length; row++)
        {
            var eachCharactersInRow = arrayOfRowsByNewlines[row].Trim().Split(' ');

            for (int column = 0; column < eachCharactersInRow.Length; column++)
            {
                int number;
                int.TryParse(eachCharactersInRow[column], out number);
                tableHolder[row, column] = number;
            }
        }
        return tableHolder;
    }

    public static bool IsPrime(int number)
    {
        // Test whether the parameter is a prime number.
        if ((number & 1) == 0)
        {
            if (number == 2)
            {
                return true;
            }
            return false;
        }

        for (int i = 3; (i * i) <= number; i += 2)
        {
            if ((number % i) == 0)
            {
                return false;
            }
        }
        return number != 1;
    }

}
</code>```

Can somebody help me go through the code and see if there is a better way of solving it.

答:
Your method seems pretty reasonable for this specific problem. This problem is a simplified version of a more general problem; you might consider solving the more general problem.

Construct a directed graph where the nodes are the elements of the triangle and the directed edges go from a node to the nodes that can be reached.

Create a start node, with an edge going to the top of the triangle, and a stop node, with edges going from every bottom node to it.

Remove all edges that go to a node that is a prime number.

The weight of an edge is the negative value of the node it points to; the stop node is of value zero.

Now you have a weighted directed acyclic graph. Use the standard minimum-path finding algorithm to find the least cost path from start to stop nodes.

The least cost is the negative of the value you are looking for.

This technique works for any weighted directed acyclic graph, not just ones in the triangle shape.

Body:
I was given this algorithm task:

You will have a triangle input below and you need to find the maximum sum of the numbers according to given rules below;

You will start from the top and move downwards to an adjacent number as in below.

You are only allowed to walk downwards and diagonally.

You can only walk over NON PRIME NUMBERS.

     1
    8 4
  2  6  9
 8  5  9  3

As you can see this has several paths that fits the rule of NOT PRIME NUMBERS; 1>8>6>9, 1>4>6>9, 1>4>9>9
1 + 8 + 6 + 9 = 24.  As you see 1, 8, 6, 9 are all NOT PRIME NUMBERS and walking over these yields the maximum sum.

According to above rules what is the maximum sum of below input? It means please take this pyramid as an input (as file or constants directly inside the code) for your implementation and solve by using it.

                                  215
                               193 124
                             117 237 442
                           218 935 347 235
                         320 804 522 417 345
                       229 601 723 835 133 124
                     248 202 277 433 207 263 257
                   359 464 504 528 516 716 871 182
                 461 441 426 656 863 560 380 171 923
               381 348 573 533 447 632 387 176 975 449
             223 711 445 645 245 543 931 532 937 541 444
           330 131 333 928 377 733 017 778 839 168 197 197
        131 171 522 137 217 224 291 413 528 520 227 229 928
      223 626 034 683 839 053 627 310 713 999 629 817 410 121
    924 622 911 233 325 139 721 218 253 223 107 233 230 124 233

Note that, each node has only two children here (except the most bottom ones). As an example, you can walk from 215 to 124 (because 193 is a prime) then from 124 to either 237 or 442. From 124 you cannot go to 117 because it’s not a direct child of 124.

I know there are different approaches of solving this problem which can be

Brute Force method

Dynamic Programming method

I used Dynamic Programming method approach due to its efficiency:

using System;

class Program
{
    static void Main(string[] args)
    {

        //get input
        var input = GetInput();

        string[] arrayOfRowsByNewlines = input.Split('\n');

        var tableHolder = FlattenTheTriangleIntoTable(arrayOfRowsByNewlines);

        var result = WalkThroughTheNode(arrayOfRowsByNewlines, tableHolder);

        Console.WriteLine($"The Maximum Total Sum Of Non-Prime Numbers From Top To Bottom Is:  {result[0,0]}");

        Console.ReadKey();
    }

    private static string GetInput()
    {

            const string input = @"   215
                                   193 124
                                  117 237 442
                                218 935 347 235
                              320 804 522 417 345
                            229 601 723 835 133 124
                          248 202 277 433 207 263 257
                        359 464 504 528 516 716 871 182
                      461 441 426 656 863 560 380 171 923
                     381 348 573 533 447 632 387 176 975 449
                   223 711 445 645 245 543 931 532 937 541 444
                 330 131 333 928 377 733 017 778 839 168 197 197
                131 171 522 137 217 224 291 413 528 520 227 229 928
              223 626 034 683 839 053 627 310 713 999 629 817 410 121
            924 622 911 233 325 139 721 218 253 223 107 233 230 124 233";
        return input;
    }

    private static int[,] WalkThroughTheNode(string[] arrayOfRowsByNewlines, int[,] tableHolder)
    {
        // walking through the non-prime node
        for (int i = arrayOfRowsByNewlines.Length - 2; i >= 0; i--)
        {
            for (int j = 0; j < arrayOfRowsByNewlines.Length; j++)
            {
                //only sum through the non-prime node
                if ((!IsPrime(tableHolder[i, j])))
                {
                    tableHolder[i, j] = Math.Max(tableHolder[i, j] + tableHolder[i + 1, j],
                        tableHolder[i, j] + tableHolder[i + 1, j + 1]);
                }
            }
        }
        return tableHolder;
    }

    private static int[,] FlattenTheTriangleIntoTable(string[] arrayOfRowsByNewlines)
    {
        int[,] tableHolder = new int[arrayOfRowsByNewlines.Length, arrayOfRowsByNewlines.Length + 1];

        for (int row = 0; row < arrayOfRowsByNewlines.Length; row++)
        {
            var eachCharactersInRow = arrayOfRowsByNewlines[row].Trim().Split(' ');

            for (int column = 0; column < eachCharactersInRow.Length; column++)
            {
                int number;
                int.TryParse(eachCharactersInRow[column], out number);
                tableHolder[row, column] = number;
            }
        }
        return tableHolder;
    }

    public static bool IsPrime(int number)
    {
        // Test whether the parameter is a prime number.
        if ((number & 1) == 0)
        {
            if (number == 2)
            {
                return true;
            }
            return false;
        }

        for (int i = 3; (i * i) <= number; i += 2)
        {
            if ((number % i) == 0)
            {
                return false;
            }
        }
        return number != 1;
    }

}

Can somebody help me go through the code and see if there is a better way of solving it.