问:
$_GET Parameter already exist, replace parameter
I have a question im busy with a filter inside of wordpress. Now i have problem i try to explain.

If a visitor select a "single merk" url gonna be ?merk=Brand1 and than option 2 is select "Soort" than the url is gonna be "?merk=Brand1&soort=Soort1" that works.

But if you have select both, than want to change only ?merk=Brand2 than the url is "?merk=Brand2&soort=Soort1&merk=brand1" how can i make it if you switch between the "merk" that "Brand1" replaced to "Brand2".

Here is the code:

```<code>            foreach ( $allemerken as $merksingle ) { ?>
                <?php if(isset($_GET['merk']) && $_GET['merk'] == $merksingle->slug){?>
                <a href="<?php echo $current_url; ?>" class="filter_merklink active"><i class="fa fa-times" aria-hidden="true"></i> <?php echo $merksingle->name; ?></a>
                <?php }else{ ?>
                <a href="<?php echo $current_url; ?>?merk=<?php echo $merksingle->slug;?><?php if(isset($_GET['soort']) && $_GET['soort'] != ''){ echo '&'.$_SERVER['QUERY_STRING'];} ?>" class="filter_merklink"><?php echo $merksingle->name; ?></a>
                <?php }?>
            <?php }?>
            <p class="mt-30"><strong>Soort:</strong></p>
            <?php
            $soorten = get_terms('warmtepompcategorie');
//            echo '```'.print_r($allemerken,true).'```';
            foreach ( $soorten as $soort ) { ?>
                <?php if(isset($_GET['soort']) && $_GET['soort'] == $soort->slug){?>
                " class="filter_merklink active"><i class="fa fa-times" aria-hidden="true"></i> <?php echo $soort->name; ?>
                <?php }else{ ?>
                ?soort=<?php echo $soort->slug;?><?php if(isset($_GET['merk']) && $_GET['merk'] != ''){ echo '&'.$_SERVER['QUERY_STRING'];} ?>" class="filter_merklink"><?php echo $soort->name; ?>
                <?php }?>
            <?php }?>
</code>```

Ps. sorry for my bad English, but hope someone can help me out!

答:
To prevent the values from duplicating I would operate on a $_GET array, or its copy for adding or removing the parameters like:

```<code>$_GET['soort'] = 'new value'; // adding, modifying value
unset($_GET['soort']); // removing value
</code>```

and then using http_build_query() for building the URL-encoded query string like this:

```<code>$query = http_build_query(array('aParam' => $data));
</code>```

Body:
I have a question im busy with a filter inside of wordpress. Now i have problem i try to explain.

If a visitor select a "single merk" url gonna be ?merk=Brand1 and than option 2 is select "Soort" than the url is gonna be "?merk=Brand1&soort=Soort1" that works.

But if you have select both, than want to change only ?merk=Brand2 than the url is "?merk=Brand2&soort=Soort1&merk=brand1" how can i make it if you switch between the "merk" that "Brand1" replaced to "Brand2".

Here is the code:

            foreach ( $allemerken as $merksingle ) { ?>
                <?php if(isset($_GET['merk']) && $_GET['merk'] == $merksingle->slug){?>
                <a href="<?php echo $current_url; ?>" class="filter_merklink active"> <?php echo $merksingle->name; ?>
                <?php }else{ ?>
                <a href="<?php echo $current_url; ?>?merk=<?php echo $merksingle->slug;?><?php if(isset($_GET['soort']) && $_GET['soort'] != ''){ echo '&'.$_SERVER['QUERY_STRING'];} ?>" class="filter_merklink"><?php echo $merksingle->name; ?>
                <?php }?>
            <?php }?>

Soort:

            <?php
            $soorten = get_terms('warmtepompcategorie');
//            echo '
'.print_r($allemerken,true).'
';
            foreach ( $soorten as $soort ) { ?>
                <?php if(isset($_GET['soort']) && $_GET['soort'] == $soort->slug){?>
                <a href="<?php echo $current_url; ?>" class="filter_merklink active"> <?php echo $soort->name; ?>
                <?php }else{ ?>
                <a href="<?php echo $current_url; ?>?soort=<?php echo $soort->slug;?><?php if(isset($_GET['merk']) && $_GET['merk'] != ''){ echo '&'.$_SERVER['QUERY_STRING'];} ?>" class="filter_merklink"><?php echo $soort->name; ?>
                <?php }?>
            <?php }?>

Ps. sorry for my bad English, but hope someone can help me out!

Body:
To prevent the values from duplicating I would operate on a $_GET array, or its copy for adding or removing the parameters like:

$_GET['soort'] = 'new value'; // adding, modifying value
unset($_GET['soort']); // removing value

and then using http_build_query() for building the URL-encoded query string like this:

$query = http_build_query(array('aParam' => $data));


来源: stackexchange

问:
VueJS: Redirecting between two pages
I use Firebase with VueJS (and VueRouter).

I have a problem with redirecting. I want to redirect between two pages. The first page is used for authentication and the second one for content that should only be visible to logged-in users.

My state holds the firebase user key (which will be populated through a mutation, that calls firebase):

```<code>state: {
  user: { key: null }
}
</code>```

The authentication page these lines:

```<code>beforeCreate() {
  if (this.$store.state.user.key !== null) {
    this.$router.replace('/')
  }
}
</code>```

And the secret page these:

```<code>beforeCreate() {
  if (this.$store.state.user.key === null) {
    this.$router.replace('/new')
  }
}
</code>```

But: the redirect from the authentication page to the secret page doesn't take place.

My Vue-dev-tools show that the user-key is set.

What could be the solution to this problem?

EDIT:

This is the mutation that calls Firebase and sets the user-key:

```<code>updateSession(state) {
  auth.onAuthStateChanged((user) => {
    if (user) {
      state.user.key = user.uid
    }
  })
}
</code>```

Here is the action:

```<code>UPDATE_SESSION({ commit }) {
  commit('updateSession')
}
</code>```

I call the action in my root component (App.vue):

```<code>beforeCreate() {
  this.$store.dispatch('UPDATE_SESSION')
}
</code>```

EDIT 2:

Now my routes array:

```<code>routes: [
  { path: '/', component: Secret },
  { path: '/new', component: Authentication }
]
</code>```

答:
Take a look at the Per-Route Guards section of the docs: https://router.vuejs.org/en/advanced/navigation-guards.html

You might want to try something like the below. By putting the beforeEnter guard on the route, you are telling Vue to do that first. The next argument tells VueRouter what to do next, and can redirect if needed or continue on to the original route.

```<code> beforeEnter(to, from, next) {
  if (this.$store.state.user.key === null) {
    next('/new')
  }
}
</code>```

EDIT

You may also want to try using push instead of replace

ContentLicense: CC BY-SA 3.0

Title: VueJS: Redirecting between two pages

Body:
I use Firebase with VueJS (and VueRouter).

I have a problem with redirecting. I want to redirect between two pages. The first page is used for authentication and the second one for content that should only be visible to logged-in users.

My state holds the firebase user key (which will be populated through a mutation, that calls firebase):

state: {
  user: { key: null }
}

The authentication page these lines:

beforeCreate() {
  if (this.$store.state.user.key !== null) {
    this.$router.replace('/')
  }
}

And the secret page these:

beforeCreate() {
  if (this.$store.state.user.key === null) {
    this.$router.replace('/new')
  }
}

But: the redirect from the authentication page to the secret page doesn't take place.

My Vue-dev-tools show that the user-key is set.

What could be the solution to this problem?

EDIT:

This is the mutation that calls Firebase and sets the user-key:

updateSession(state) {
  auth.onAuthStateChanged((user) => {
    if (user) {
      state.user.key = user.uid
    }
  })
}

Here is the action:

UPDATE_SESSION({ commit }) {
  commit('updateSession')
}

I call the action in my root component (App.vue):

beforeCreate() {
  this.$store.dispatch('UPDATE_SESSION')
}

EDIT 2:

Now my routes array:

routes: [
  { path: '/', component: Secret },
  { path: '/new', component: Authentication }
]

Body:
Take a look at the Per-Route Guards section of the docs: https://router.vuejs.org/en/advanced/navigation-guards.html

You might want to try something like the below. By putting the beforeEnter guard on the route, you are telling Vue to do that first. The next argument tells VueRouter what to do next, and can redirect if needed or continue on to the original route.

 beforeEnter(to, from, next) {
  if (this.$store.state.user.key === null) {
    next('/new')
  }
}

EDIT

You may also want to try using push instead of replace


问:
LINQ to XML how compare children with repeater items
I've got a print button that gives XML data to filling an adobe lifecycle template. I'm trying to compare ROWID in XML with a repeater rowid to make it print the information about the row the button was clicked on.

```<code>Int32 rownum = Convert.ToInt32(e.CommandArgument.ToString());
string xmlROWID = Xmld.Descendants("ROWID").First().Value;
</code>```

Here are 2 of the children in the XML:

```<code><VKRSADL>
    <CUSTOMER_SADLS>
      <TABLEVALUE>
        <ROW>
          <ROWID>0</ROWID>
          <ID>Съкредитополучател</ID>
          <TYPE>48</TYPE>
          <TYPEID>1</TYPEID>
          <TYPECODE>1</TYPECODE>
          <CRSCODE>777</CRSCODE>
          <EGN />
          <NAME />
          <XML>
            <SADL0>
              <OwnerCrsCode />
              <TABLEVALUE />
            </SADL0>
          </XML>
          <XMLCHECK />
        </ROW>
        <ROW>
          <ROWID>1</ROWID>
          <ID>Съкредитополучател</ID>
          <TYPE>48</TYPE>
          <TYPEID>2</TYPEID>
          <TYPECODE>1</TYPECODE>
          <CRSCODE>123123</CRSCODE>
          <EGN />
          <NAME />
          <XML>
            <SADL1>
              <OwnerCrsCode />
              <TABLEVALUE />
            </SADL1>
          </XML>
          <XMLCHECK />
        </ROW>
      </TABLEVALUE>
    </CUSTOMER_SADLS>
  </VKRSADL>
</code>```

Comparing it to the First() gives me only the first ROWID, and there can be multiple. How can I compare the repeater rowid it to each of the ROWID's I've got saved?

I've tried this:

```<code>foreach (var child in Xmld.Root.Element("REQUEST").Element("VKRSADL").Element("CUSTOMER_SADLS").Element("TABLEVALUE").Elements("ROW").Elements()) {
    //DO SOMETHING
}
</code>```

but I get an error:
An exception of type 'System.NullReferenceException' occurred in App_Web_f2rvuyke.dll but was not handled in user code

Additional information: Object reference not set to an instance of an object.

答:
As I understand from your question, you want to iterate through ROW element to get all elements which their ROWID is equal to a certain value.

You can use below code to get all ROW elements, then you can do what ever you want with each ROW, in my example below I print ROWID to console window:

```<code>string xml = "<VKRSADL><CUSTOMER_SADLS><TABLEVALUE><ROW><ROWID>0</ROWID><ID>Съкредитополучател</ID><TYPE>48</TYPE><TYPEID>1</TYPEID><TYPECODE>1</TYPECODE><CRSCODE>777</CRSCODE><EGN /><NAME /><XML><SADL0><OwnerCrsCode /><TABLEVALUE /></SADL0></XML><XMLCHECK /></ROW><ROW><ROWID>1</ROWID><ID>Съкредитополучател</ID><TYPE>48</TYPE><TYPEID>2</TYPEID><TYPECODE>1</TYPECODE><CRSCODE>123123</CRSCODE><EGN /><NAME /><XML><SADL1><OwnerCrsCode /><TABLEVALUE /></SADL1></XML><XMLCHECK /></ROW></TABLEVALUE></CUSTOMER_SADLS></VKRSADL>";
XDocument xDoc = XDocument.Parse(xml);

foreach (var child in xDoc.Element("VKRSADL").Element("CUSTOMER_SADLS").Element("TABLEVALUE").Elements().Where(e => e.Name == "ROW"))
{
    Console.WriteLine(child.Element("ROWID").Value);
}
</code>```

Note: Above example assume that the XML schema will not be changed, and if it changed then an exception could be occurred.

Body:
I've got a print button that gives XML data to filling an adobe lifecycle template. I'm trying to compare ROWID in XML with a repeater rowid to make it print the information about the row the button was clicked on.

Int32 rownum = Convert.ToInt32(e.CommandArgument.ToString());
string xmlROWID = Xmld.Descendants("ROWID").First().Value;

Here are 2 of the children in the XML:

<VKRSADL>
    <CUSTOMER_SADLS>
      <TABLEVALUE>
        <ROW>
          <ROWID>0</ROWID>
          <ID>Съкредитополучател</ID>
          <TYPE>48</TYPE>
          <TYPEID>1</TYPEID>
          <TYPECODE>1</TYPECODE>
          <CRSCODE>777</CRSCODE>
          <EGN />
          <NAME />
          <XML>
            <SADL0>
              <OwnerCrsCode />
              <TABLEVALUE />
            </SADL0>
          </XML>
          <XMLCHECK />
        </ROW>
        <ROW>
          <ROWID>1</ROWID>
          <ID>Съкредитополучател</ID>
          <TYPE>48</TYPE>
          <TYPEID>2</TYPEID>
          <TYPECODE>1</TYPECODE>
          <CRSCODE>123123</CRSCODE>
          <EGN />
          <NAME />
          <XML>
            <SADL1>
              <OwnerCrsCode />
              <TABLEVALUE />
            </SADL1>
          </XML>
          <XMLCHECK />
        </ROW>
      </TABLEVALUE>
    </CUSTOMER_SADLS>
  </VKRSADL>

Comparing it to the First() gives me only the first ROWID, and there can be multiple. How can I compare the repeater rowid it to each of the ROWID's I've got saved?

I've tried this:

foreach (var child in Xmld.Root.Element("REQUEST").Element("VKRSADL").Element("CUSTOMER_SADLS").Element("TABLEVALUE").Elements("ROW").Elements()) {
    //DO SOMETHING
}

but I get an error:
An exception of type 'System.NullReferenceException' occurred in App_Web_f2rvuyke.dll but was not handled in user code

Additional information: Object reference not set to an instance of an object.

Body:
As I understand from your question, you want to iterate through ROW element to get all elements which their ROWID is equal to a certain value.

You can use below code to get all ROW elements, then you can do what ever you want with each ROW, in my example below I print ROWID to console window:

string xml = "<VKRSADL><CUSTOMER_SADLS><TABLEVALUE><ROW><ROWID>0</ROWID><ID>Съкредитополучател</ID><TYPE>48</TYPE><TYPEID>1</TYPEID><TYPECODE>1</TYPECODE><CRSCODE>777</CRSCODE><EGN /><NAME /><XML><SADL0><OwnerCrsCode /><TABLEVALUE /></SADL0></XML><XMLCHECK /></ROW><ROW><ROWID>1</ROWID><ID>Съкредитополучател</ID><TYPE>48</TYPE><TYPEID>2</TYPEID><TYPECODE>1</TYPECODE><CRSCODE>123123</CRSCODE><EGN /><NAME /><XML><SADL1><OwnerCrsCode /><TABLEVALUE /></SADL1></XML><XMLCHECK /></ROW></TABLEVALUE></CUSTOMER_SADLS></VKRSADL>";
XDocument xDoc = XDocument.Parse(xml);

foreach (var child in xDoc.Element("VKRSADL").Element("CUSTOMER_SADLS").Element("TABLEVALUE").Elements().Where(e => e.Name == "ROW"))
{
    Console.WriteLine(child.Element("ROWID").Value);
}

Note: Above example assume that the XML schema will not be changed, and if it changed then an exception could be occurred.


问:
How to programmatically scroll a SurfaceScatterView
The SurfaceScatterView is an ItemControl,
I want to scroll it into a position that I choose,
Can any one help ,
Thanks</p>

答:
Problem resolved ,
ScrollToHorizontalOffset(double d)
ScrollToVerticalOffset(double d)</p>

ContentLicense: CC BY-SA 2.5


问:
Understanding how to do JUnit testing with Mockito doReturn/when for the methods with return type void
Suppose, I have a test class with two methods as follows:

```<code>public class TestClass {
   @Mock
   TestClass testObject;

   @Test
   public void method1() {
      doReturn("str").when(testObject).method2();

      String s1 = testObject.method2(); // This line gives compilation
      //error. Type mismatch cannot convert from void to string
   }

   @Test
   public void method2() {
   }
</code>```

I am basically trying to mock method2 which is a dependency in method1.

But as you can see, the method2 return type is void. So, I am using doReturn to mock it.

As far as my understanding goes, although the method2 's return type is void, after I mock it, the mocked version of method2 should return String type.

But, as I have commented in method1, it is giving type mismatch.

答:
I think you're using the wrong method. doReturn allows you to "inject" the result of the execution. If you want to "falsify" the whole method execution you should consider using doAnswer:

```<code>doAnswer(new Answer<Void>() {
    public Void answer(InvocationOnMock invocation) {
      // whatever you want to execute here...
      // Simply return null
      return null;
    }
}).when(testObject).method2();
</code>```

Body:
Suppose, I have a test class with two methods as follows:

public class TestClass {
   @Mock
   TestClass testObject;

   @Test
   public void method1() {
      doReturn("str").when(testObject).method2();

      String s1 = testObject.method2(); // This line gives compilation
      //error. Type mismatch cannot convert from void to string
   }

   @Test
   public void method2() {
   }

I am basically trying to mock method2 which is a dependency in method1.

But as you can see, the method2 return type is void. So, I am using doReturn to mock it.

As far as my understanding goes, although the method2 's return type is void, after I mock it, the mocked version of method2 should return String type.

But, as I have commented in method1, it is giving type mismatch.

Body:
I think you're using the wrong method. doReturn allows you to "inject" the result of the execution. If you want to "falsify" the whole method execution you should consider using doAnswer:

doAnswer(new Answer<Void>() {
    public Void answer(InvocationOnMock invocation) {
      // whatever you want to execute here...
      // Simply return null
      return null;
    }
}).when(testObject).method2();


问:
Opensource Java ASN.1 decoder that work with automatic tags
I'm new to working with ASN.1 encoded streams and I'm having a hard time finding a free class compiler and decoder, preferably for Java.

I have an encoded hex string:

```<code>String test("30820274800200a2810105820410300c3d830401bb0afc84...
</code>```

Here is an example of the notation:

```<code>SEMI DEFINITIONS AUTOMATIC TAGS ::= BEGIN

IntersectionSituationData ::= SEQUENCE {
    dialogID        SemiDialogID,                   -- 0xA2
    seqID           SemiSequenceID,                 -- 0x05 Data
    groupID         GroupID,
    -- Some more members
}

SemiDialogID ::= ENUMERATED {
   intersectionSitDataDep       (162),  -- 0xA2
   -- additional DialogIDs
}
SemiSequenceID ::= ENUMERATED {
    data                (5),    -- Data
    -- additional SeqIDs
}
</code>```

I started using JAC: https://sourceforge.net/projects/jac-asn1/
But it doesn't support Automatic tags.

I next tried jASN1: https://www.openmuc.org/asn1/
It doesn't say if it supports automatic tags or not. It seems to compile the Notation without complaining, but I can't get it to decode correctly and it looks like the tagging if wrong.

If we take the start of the encoded string: 30 82 02 74 80 02 00 a2...
This is my understanding:

```<code>30 = Sequence
82 = Length encoded in 2 octets
02 74 = Length = 2x256 + 7x16 +4 == 638 bytes, correct
80 ?? is this a result of automatic encoding? x80= 128= 8th bit set = context-specific class, number 0?
02 = length of value is 2 octets
00 a2 is value == xA2 as expected from SemiDialogID
</code>```

But if I encode a test of "IntersectionSituationData" I get the following: 30 81 8a 0a 02 00 a2
i.e. the type is 'x0a' == 10 which is ASN.1 Universal ENUMERATED. That makes sense form looking at he notification but I am guessing Automatic tags is being ignored by jASN1. When I look at the generated Java classes we see SemiDialogID extends BerEnum, which uses universal clas identifier:

```<code>// SemiDialogID.java
public class SemiDialogID extends BerEnum {
   ...
}

//BerEnum.java
public class BerEnum extends BerInteger {

   public final static BerIdentifier identifier = new BerIdentifier(BerIdentifier.UNIVERSAL_CLASS,
        BerIdentifier.PRIMITIVE, BerIdentifier.ENUMERATED_TAG);
</code>```

Is there something I need to do to get jASN1 to work with automatic tags or do I need a different library? IF the latter, what do people recommend? Ideally I am looking for an open source java solution  that is easy to use.  I guess I could make do with a C solution and use JNI to get it to work.

答: Since version 1.6.0 jASN1 supports automatic tagging.</p>

Body:
I'm new to working with ASN.1 encoded streams and I'm having a hard time finding a free class compiler and decoder, preferably for Java.

I have an encoded hex string:

String test("30820274800200a2810105820410300c3d830401bb0afc84...

Here is an example of the notation:

SEMI DEFINITIONS AUTOMATIC TAGS ::= BEGIN

IntersectionSituationData ::= SEQUENCE {
    dialogID        SemiDialogID,                   -- 0xA2
    seqID           SemiSequenceID,                 -- 0x05 Data
    groupID         GroupID,
    -- Some more members
}

SemiDialogID ::= ENUMERATED {
   intersectionSitDataDep       (162),  -- 0xA2
   -- additional DialogIDs
}
SemiSequenceID ::= ENUMERATED {
    data                (5),    -- Data
    -- additional SeqIDs
}

I started using JAC: https://sourceforge.net/projects/jac-asn1/
But it doesn't support Automatic tags.

I next tried jASN1: https://www.openmuc.org/asn1/
It doesn't say if it supports automatic tags or not. It seems to compile the Notation without complaining, but I can't get it to decode correctly and it looks like the tagging if wrong.

If we take the start of the encoded string: 30 82 02 74 80 02 00 a2...
This is my understanding:

30 = Sequence
82 = Length encoded in 2 octets
02 74 = Length = 2x256 + 7x16 +4 == 638 bytes, correct
80 ?? is this a result of automatic encoding? x80= 128= 8th bit set = context-specific class, number 0?
02 = length of value is 2 octets
00 a2 is value == xA2 as expected from SemiDialogID

But if I encode a test of "IntersectionSituationData" I get the following: 30 81 8a 0a 02 00 a2
i.e. the type is 'x0a' == 10 which is ASN.1 Universal ENUMERATED. That makes sense form looking at he notification but I am guessing Automatic tags is being ignored by jASN1. When I look at the generated Java classes we see SemiDialogID extends BerEnum, which uses universal clas identifier:

// SemiDialogID.java
public class SemiDialogID extends BerEnum {
   ...
}

//BerEnum.java
public class BerEnum extends BerInteger {

   public final static BerIdentifier identifier = new BerIdentifier(BerIdentifier.UNIVERSAL_CLASS,
        BerIdentifier.PRIMITIVE, BerIdentifier.ENUMERATED_TAG);

Is there something I need to do to get jASN1 to work with automatic tags or do I need a different library? IF the latter, what do people recommend? Ideally I am looking for an open source java solution  that is easy to use.  I guess I could make do with a C solution and use JNI to get it to work.


问:
Ambiguity with pattern matching records
I learned from this question that it's possible to use pattern matching with records. However, I've noticed that I'm having trouble trying to match different types of records.

My goal in this example is to be able to distinguish between different records. I'm given a record that I'm not entirely sure which type it is, and I'm trying to figure it out using pattern matching.

Here's a simplified example:

```<code>module IceCream = struct
  type t = {
    temperature: float;
    toppings: string list;
  }
end

module Candy = struct
  type t = {
    flavour: string;
    colour: string;
    volume: int;
  }
end

(* Could be Candy or IceCream *)
let example =
  { Candy.
    flavour = "mint";
    colour = "green";
    volume = 10 }

let printFavoriteTreat treat = match treat with
  | { Candy.
      flavour = "mint";
      colour;
      volume } -> "It's Candy"
  | { IceCream.
      temperature;
      toppings } -> "It's IceCream"

let () = printFavoriteTreat example
</code>```

When I try to build this file, I get:

```<code>Error: The field IceCream.temperature belongs to the record type IceCream.t
       but a field was expected belonging to the record type Candy.t
</code>```

Is doing something like this possible?

答:
You are trying to match against to different types without using variant types.

The module syntax you are using cannot help,  as module just structure the code. You could have defined the following types :

```<code>type a = {
     temperature: float;
     toppings: string list;
  }

type b =  {
    flavour: string;
    colour: string;
    volume: int;
  }
</code>```

But the results would be the same.

The way to disambiguate is to use variant types (or union type which is not described in the example below) :

```<code>let printFavoriteTreat treat = match treat with
  | `A{ Candy.
      flavour = "mint";
      colour;
      volume } -> "It's Candy"
  | `B { IceCream.
      temperature;
      toppings } -> "It's IceCream"
;;
</code>```

And

```<code>let () = printFavoriteTreat (`A example)
</code>```

Title: Ambiguity with pattern matching records

Body:
I learned from this question that it's possible to use pattern matching with records. However, I've noticed that I'm having trouble trying to match different types of records.

My goal in this example is to be able to distinguish between different records. I'm given a record that I'm not entirely sure which type it is, and I'm trying to figure it out using pattern matching.

Here's a simplified example:

module IceCream = struct
  type t = {
    temperature: float;
    toppings: string list;
  }
end

module Candy = struct
  type t = {
    flavour: string;
    colour: string;
    volume: int;
  }
end

(* Could be Candy or IceCream *)
let example =
  { Candy.
    flavour = "mint";
    colour = "green";
    volume = 10 }

let printFavoriteTreat treat = match treat with
  | { Candy.
      flavour = "mint";
      colour;
      volume } -> "It's Candy"
  | { IceCream.
      temperature;
      toppings } -> "It's IceCream"

let () = printFavoriteTreat example

When I try to build this file, I get:

Error: The field IceCream.temperature belongs to the record type IceCream.t
       but a field was expected belonging to the record type Candy.t

Is doing something like this possible?

Body:
You are trying to match against to different types without using variant types.

The module syntax you are using cannot help,  as module just structure the code. You could have defined the following types :

type a = {
     temperature: float;
     toppings: string list;
  }

type b =  {
    flavour: string;
    colour: string;
    volume: int;
  }

But the results would be the same.

The way to disambiguate is to use variant types (or union type which is not described in the example below) :

let printFavoriteTreat treat = match treat with
  | `A{ Candy.
      flavour = "mint";
      colour;
      volume } -> "It's Candy"
  | `B { IceCream.
      temperature;
      toppings } -> "It's IceCream"
;;

And

let () = printFavoriteTreat (`A example)


问:
angularJs shift table item index to up or down
I have a table where I would like to change the order or rows by moving an item Up or Down. The element select here(T17180054) with index 3 should move up and have a new index of 2 and keep the selection preferably.

This is my HTML:

```<code><table st-safe-src="flow3.dataSet" st-table="flow3.displayed" class="table table-striped">
    <thead>
        <tr>
            <th st-sort="method">Method</th>
            <th st-sort="sample">Sample</th>
            <th st-sort="parameters">Parameters</th>
        </tr>
    </thead>
    <tbody ui-sortable ng-model="flow3.displayed">
        <tr ng-repeat="row in flow3.displayed track by $index" style="cursor: move;"
            ng-click="row.selected = !row.selected; flow3.selectRow($event, row, index)"
            ng-class="{success: row.selected}">>
            <td>{{row.method.name}}</td>
            <td>{{row.sample}}</td>
            <td>
                <span ng-repeat="parameter in row.parameters">
                    {{parameter.methodInputParameter.name}} : {{parameter.value}}<br/></span>
            </td>
            <td>
                <button type="button" ng-click="flow3.removeItem(row)"
                    class="btn btn-danger btn-sm btn-round pull-right"
                    ng-disabled="flow3.confirmDisabled">
                        <i class="glyphicon glyphicon-trash"></i>
                </button>
            </td>
        </tr>
    </tbody>
</table>
</code>```

This is my two Up and Down buttons

```<code><div class="row">
    <div class="col-xs-6">
        <div class="btn btn-info btn-lg btn-full-width">
            <span class="glyphicon glyphicon-menu-up" ng-click="flow3.moveItemUp();"></span> Up
        </div>
    </div>
    <div class="col-xs-6">
        <div class="btn btn-info btn-lg btn-full-width">
            <span class="glyphicon glyphicon-menu-down" ng-click="flow3.moveItemDown();"></span> Down
        </div>
    </div>
</div>
</code>```

This is my JS :
I have tried to use the splice method by I had wrong results each time.
Is there a better alternative?

```<code>flow3.moveItemDown = function moveItemDown() {
    var index = flow3.dataSet.indexOf(flow3.selectedItem);

    if(index == 0) {
        return;
    } else {
        flow3.dataSet.splice(?, ?, ? , ?)
    }
}
</code>```

答:
You can use splice, but you would need to use it twice: once to remove the item from the old position, and once to re-add the item to the new position:

```<code>flow3.moveItemDown = function moveItemDown() {
    var index = flow3.dataSet.indexOf(flow3.selectedItem);

    if(index <= 0) {
        // The item cannot be moved up if it's already the first in the array;
        // and account for -1, index not found
        return;
    } else {
        // Remove value to replace
        var removed = flow3.dataSet.splice(index, 1);
        // Re-add removed value to the previous index
        flow3.dataSet.splice(index - 1, 0, removed[0]);
    }
}
</code>```

If you try to do both using the same splice the added items will be added at the start index of the splice, resulting in the item being re-added at its original index.

more about array.splice

Also, dont forget to account for the array length when moving items down, you cannot move the last item down anymore ;)

Body:
I have a table where I would like to change the order or rows by moving an item Up or Down. The element select here(T17180054) with index 3 should move up and have a new index of 2 and keep the selection preferably.

This is my HTML:

            Method
            Sample
            Parameters

>
            {{row.method.name}}
            {{row.sample}}

                    {{parameter.methodInputParameter.name}} : {{parameter.value}}

                <button type="button" ng-click="flow3.removeItem(row)"
                    class="btn btn-danger btn-sm btn-round pull-right"
                    ng-disabled="flow3.confirmDisabled">

                </button>

This is my two Up and Down buttons

             Up

             Down

This is my JS :
I have tried to use the splice method by I had wrong results each time.
Is there a better alternative?

flow3.moveItemDown = function moveItemDown() {
    var index = flow3.dataSet.indexOf(flow3.selectedItem);

    if(index == 0) {
        return;
    } else {
        flow3.dataSet.splice(?, ?, ? , ?)
    }
}

Body:
You can use splice, but you would need to use it twice: once to remove the item from the old position, and once to re-add the item to the new position:

flow3.moveItemDown = function moveItemDown() {
    var index = flow3.dataSet.indexOf(flow3.selectedItem);

    if(index <= 0) {
        // The item cannot be moved up if it's already the first in the array;
        // and account for -1, index not found
        return;
    } else {
        // Remove value to replace
        var removed = flow3.dataSet.splice(index, 1);
        // Re-add removed value to the previous index
        flow3.dataSet.splice(index - 1, 0, removed[0]);
    }
}

If you try to do both using the same splice the added items will be added at the start index of the splice, resulting in the item being re-added at its original index.

more about array.splice

Also, dont forget to account for the array length when moving items down, you cannot move the last item down anymore ;)


问:
To check whether the string value has numeric value or not in C#
I am having an string like this

string str = "dfdsfdsf8fdfdfd9dfdfd4"

I need to check whether the string contains number by looping through the array.

答:
Combining parts of Kamals answer and Tristars answers give...

```<code>str.Any(char.IsNumber)
</code>```

which I think is the most succinct and readable way, instead of a regex

OwnerDisplayName: balaweblog

LastEditorDisplayName: balaweblog

Body:
Combining parts of Kamals answer and Tristars answers give...

str.Any(char.IsNumber)

which I think is the most succinct and readable way, instead of a regex


问:
Exception/MessageBox in Calibur.Micro
I start learning Caliburn.Micro and I am little confuse of handling with exception/messange box in view model class.

I found some blogs about, for example:

http://frankmao.com/2010/11/18/handling-messagebox-in-caliburn-micro/

For example some method in view model class which can produce exception.

```<code>    public void MethodWichCanProduceEx(string arg1, string arg2 )
    {
        if(arg1==null)
            throw new ArgumentNullException("arg1 is null");
        if (arg2 == null)
            throw new ArgumentNullException("arg2 is null");

        try
        {

        }
        catch (Exception exception)
        {

            throw exception;
            //? show message box MessageBox.Shox(exception.Message)
        }
    }
</code>```

What is correct handling and showing these exception in view ? It exist any kind of pattern for caliburn.micro?

It possible trace exception as in .NET in text, xml file ?

For example I would like trace exception in xml, text file and in view show only message.box or something message.

Thank for advance, maybe is my question little stupid, sorry  I am only learning calibur.micro.

答:
You'll want to always work against abstractions in your view models, in the case of message boxes, you don't want to have to wait for user input when you come to unit test your view models.

The Frank Mao code you linked to uses a delegate to abstract the implementation of the message box from the view model, but I would use an interface here.  You can think of a delegate as an interface with a single method, but the advantage of using an interface in this context is that you can have different methods depending on the type of message you wish to show.  For example, you could have a ShowMessageError, ShowMessageWarning, ShowMessageInfo etc.

So, define a contract for your message box:

```<code>public interface IMessageBox
{
  void ShowException(Exception exc);
}
</code>```

Inject the message box dependency into your view model, e.g. via the constructor

```<code>public class MyViewModel
{
  private readonly IMessageBox messageBox;

  public MyViewModel(IMessageBox messageBox)
  {
    this.messageBox = messageBox;
  }

  public void MethodThatCanThrowException()
  {
    try {}
    catch(Exception exc)
    {
      // log the exception here
      ...
      // show message box
      this.messageBox.ShowException(exc);
    }
  }
}
</code>```

You can then implement the message box anyway you wish, either using the windows system message box, or nicer still use your own view/viewmodel to display the message, perhaps using the Caliburn.Micro WindowManager.ShowDialog().

An implementation that uses the windows system message box may look like:

```<code>public class StandardMessageBox : IMessageBox
{
  public void ShowException(Exception exception)
  {
    MessageBox.Show(exception.ToString(), "Error Occurred");
  }
}
</code>```

In production code, you can register StandardMessageBox against the IMessageBox interface in your IoC container.

In unit test land, you can mock out IMessageBox and have it do nothing, or in the case of methods with a result from the message box, always return a value you wish.

For logging the exception, I would look at a logging framework such as log4net (http://logging.apache.org/log4net/index.html) or NLog (http://nlog-project.org/)

Title: Exception/MessageBox in Calibur.Micro

Body:
I start learning Caliburn.Micro and I am little confuse of handling with exception/messange box in view model class.

I found some blogs about, for example:

http://frankmao.com/2010/11/18/handling-messagebox-in-caliburn-micro/

For example some method in view model class which can produce exception.

    public void MethodWichCanProduceEx(string arg1, string arg2 )
    {
        if(arg1==null)
            throw new ArgumentNullException("arg1 is null");
        if (arg2 == null)
            throw new ArgumentNullException("arg2 is null");

        try
        {

        }
        catch (Exception exception)
        {

            throw exception;
            //? show message box MessageBox.Shox(exception.Message)
        }
    }

What is correct handling and showing these exception in view ? It exist any kind of pattern for caliburn.micro?

It possible trace exception as in .NET in text, xml file ?

For example I would like trace exception in xml, text file and in view show only message.box or something message.

Thank for advance, maybe is my question little stupid, sorry  I am only learning calibur.micro.

Body:
You'll want to always work against abstractions in your view models, in the case of message boxes, you don't want to have to wait for user input when you come to unit test your view models.

The Frank Mao code you linked to uses a delegate to abstract the implementation of the message box from the view model, but I would use an interface here.  You can think of a delegate as an interface with a single method, but the advantage of using an interface in this context is that you can have different methods depending on the type of message you wish to show.  For example, you could have a ShowMessageError, ShowMessageWarning, ShowMessageInfo etc.

So, define a contract for your message box:

public interface IMessageBox
{
  void ShowException(Exception exc);
}

Inject the message box dependency into your view model, e.g. via the constructor

public class MyViewModel
{
  private readonly IMessageBox messageBox;

  public MyViewModel(IMessageBox messageBox)
  {
    this.messageBox = messageBox;
  }

  public void MethodThatCanThrowException()
  {
    try {}
    catch(Exception exc)
    {
      // log the exception here
      ...
      // show message box
      this.messageBox.ShowException(exc);
    }
  }
}

You can then implement the message box anyway you wish, either using the windows system message box, or nicer still use your own view/viewmodel to display the message, perhaps using the Caliburn.Micro WindowManager.ShowDialog().

An implementation that uses the windows system message box may look like:

public class StandardMessageBox : IMessageBox
{
  public void ShowException(Exception exception)
  {
    MessageBox.Show(exception.ToString(), "Error Occurred");
  }
}

In production code, you can register StandardMessageBox against the IMessageBox interface in your IoC container.

In unit test land, you can mock out IMessageBox and have it do nothing, or in the case of methods with a result from the message box, always return a value you wish.

For logging the exception, I would look at a logging framework such as log4net (http://logging.apache.org/log4net/index.html) or NLog (http://nlog-project.org/)


问:
Set default value to number column in Mysql
Trying to set default value of 10 digits to number column, type is INT. Gives error saying

1067 Invalid default value for number.

Also have set the lenght to 25.

答:
If want to set any random 10 digit number then, assign the type as bigint.
If the the random 10 digit is in range between -2147483648 to 2147483647 then type int is will do .

The datatype INT uses 4 bytes (from -2147483648 to 2147483647 or unsigned from 0 to 4294967295),
the datatype BIGINT uses 8 bytes (from -9223372036854775808 to 9223372036854775807 or unsigned from 0 to 18446744073709551615).


问:
How to set an interface{} parameter by reference?
I have a function that has a parameter with the type interface{}. This parameter represents my template data. So on each page it stores different data types (mostly structs). I want to append some data to this parameter's data, but it's an interface{} type and I can't do it.

This is what I tried:

```<code>func LoadTemplate(templateData interface) {
  appendCustomData(&templateData)
  ... //other functionality that is not relevant
}

func appendCustomData(dst interface{}) {
    // ValueOf to enter reflect-land
    dstPtrValue := reflect.ValueOf(dst)
    // need the type to create a value
    dstPtrType := dstPtrValue.Type()
    // *T -> T, crashes if not a ptr
    dstType := dstPtrType.Elem()
    // the *dst in *dst = zero
    dstValue := reflect.Indirect(dstPtrValue)
    // the zero in *dst = zero
    zeroValue := reflect.Zero(dstType)
    // the = in *dst = 0

    v := reflect.ValueOf(dst).Elem().Elem().FieldByName("HeaderCSS")
    if v.IsValid() {
        v = reflect.ValueOf("new header css value")
    }

    reflect.ValueOf(dst).Elem().Elem().FieldByName("HeaderCSS").Set(reflect.ValueOf(v))

    //dstValue.Set(zeroValue)
    fmt.Println("new dstValue: ", dstValue)
}
</code>```

I can successfully get the "HeaderCSS" value. But I can't replace it with another value. What am I doing wrong?

My templateData looks like this:

I have a generic struct:

```<code>type TemplateData struct {
    FooterJS template.HTML
    HeaderJS template.HTML
    HeaderCSS template.HTML
    //and some more
}
</code>```

and I have another struct, such as:

```<code>type pageStruct struct {
    TemplateData //extends the previous struct
    Form template.HTML
    // and some other maps/string
}
</code>```

I send this second struct as templateData argument.

Right now I get this error:

"reflect.Value.Set using unaddressable value" at the line: reflect.ValueOf(dst).Elem().Elem().FieldByName("HeaderCSS").Set(reflect.ValueOf(v))

The code from above is inspired from this answer: https://stackoverflow.com/a/26824071/1564840

I want to be able to append/edit values from this interface. Any idea how can I do it? Thanks.

答:
Don't pass a pointer to interface. Instead the interface{} value should contain the pointer. And simply just hand over this interface{} value:

```<code>func LoadTemplate(templateData interface) {
  appendCustomData(templateData)
  ... //other functionality that is not relevant
}
</code>```

Even if you can't use a more concrete type than interface{} (because you must allow multiple types), you can still use type assertion, it will be "super" easy:

```<code>func appendCustomData(d interface{}) {
    if ps, ok := d.(*pageStruct); ok {
        ps.TemplateData.HeaderCSS += "+new"
    }

}
</code>```

Try this one on the Go Playground.

If you must or want to use reflection, this is how appendCustomData() can be implemented:

```<code>type Data struct {
    Name  string
    Age   int
    Marks []int
}

func appendCustomData(d interface{}) {
    v := reflect.ValueOf(d).Elem()

    if f := v.FieldByName("Name"); f.IsValid() {
        f.SetString(f.Interface().(string) + "2")
    }

    if f := v.FieldByName("Age"); f.IsValid() {
        f.SetInt(f.Int() + 2)
    }

    if f := v.FieldByName("Marks"); f.IsValid() {
        f.Set(reflect.ValueOf(append(f.Interface().([]int), 2)))
    }

    if f := v.FieldByName("Invalid"); f.IsValid() {
        f.Set(reflect.ValueOf(append(f.Interface().([]int), 2)))
    }
}
</code>```

Testing it:

```<code>d := &Data{
    Name:  "Bob",
    Age:   22,
    Marks: []int{5, 4, 3},
}
fmt.Printf("%+v\n", d)
appendCustomData(d)
fmt.Printf("%+v\n", d)
</code>```

Output (try it on the Go Playground):

```<code>&{Name:Bob Age:22 Marks:[5 4 3]}
&{Name:Bob2 Age:24 Marks:[5 4 3 2]}
</code>```

Update:

To answer your edited question: there is no difference when the value passed is a struct that embeds another struct. But the value wrapped in the interface{} still must be a pointer.

Example appendCustomData() that appends content to pageStruct.TemplateData.HeaderCSS:

```<code>func appendCustomData(d interface{}) {
    v := reflect.ValueOf(d).Elem()

    if f := v.FieldByName("TemplateData"); f.IsValid() {
        if f = f.FieldByName("HeaderCSS"); f.IsValid() {
            f.Set(reflect.ValueOf(f.Interface().(template.HTML) + "+new"))
        }
    }
}
</code>```

Testing it:

```<code>ps := &pageStruct{
    TemplateData: TemplateData{
        HeaderCSS: template.HTML("old"),
    },
}
fmt.Printf("%+v\n", ps)
appendCustomData(ps)
fmt.Printf("%+v\n", ps)
</code>```

Output (try it on the Go Playground):

```<code>&{TemplateData:{FooterJS: HeaderJS: HeaderCSS:old} Form:}
&{TemplateData:{FooterJS: HeaderJS: HeaderCSS:old+new} Form:}
</code>```

Body:
I have a function that has a parameter with the type interface{}. This parameter represents my template data. So on each page it stores different data types (mostly structs). I want to append some data to this parameter's data, but it's an interface{} type and I can't do it.

This is what I tried:

func LoadTemplate(templateData interface) {
  appendCustomData(&templateData)
  ... //other functionality that is not relevant
}

func appendCustomData(dst interface{}) {
    // ValueOf to enter reflect-land
    dstPtrValue := reflect.ValueOf(dst)
    // need the type to create a value
    dstPtrType := dstPtrValue.Type()
    // *T -> T, crashes if not a ptr
    dstType := dstPtrType.Elem()
    // the *dst in *dst = zero
    dstValue := reflect.Indirect(dstPtrValue)
    // the zero in *dst = zero
    zeroValue := reflect.Zero(dstType)
    // the = in *dst = 0

    v := reflect.ValueOf(dst).Elem().Elem().FieldByName("HeaderCSS")
    if v.IsValid() {
        v = reflect.ValueOf("new header css value")
    }

    reflect.ValueOf(dst).Elem().Elem().FieldByName("HeaderCSS").Set(reflect.ValueOf(v))

    //dstValue.Set(zeroValue)
    fmt.Println("new dstValue: ", dstValue)
}

I can successfully get the "HeaderCSS" value. But I can't replace it with another value. What am I doing wrong?

My templateData looks like this:

I have a generic struct:

type TemplateData struct {
    FooterJS template.HTML
    HeaderJS template.HTML
    HeaderCSS template.HTML
    //and some more
}

and I have another struct, such as:

type pageStruct struct {
    TemplateData //extends the previous struct
    Form template.HTML
    // and some other maps/string
}

I send this second struct as templateData argument.

Right now I get this error:

"reflect.Value.Set using unaddressable value" at the line: reflect.ValueOf(dst).Elem().Elem().FieldByName("HeaderCSS").Set(reflect.ValueOf(v))

The code from above is inspired from this answer: https://stackoverflow.com/a/26824071/1564840

I want to be able to append/edit values from this interface. Any idea how can I do it? Thanks.

Body:
Don't pass a pointer to interface. Instead the interface{} value should contain the pointer. And simply just hand over this interface{} value:

func LoadTemplate(templateData interface) {
  appendCustomData(templateData)
  ... //other functionality that is not relevant
}

Even if you can't use a more concrete type than interface{} (because you must allow multiple types), you can still use type assertion, it will be "super" easy:

func appendCustomData(d interface{}) {
    if ps, ok := d.(*pageStruct); ok {
        ps.TemplateData.HeaderCSS += "+new"
    }

}

Try this one on the Go Playground.

If you must or want to use reflection, this is how appendCustomData() can be implemented:

type Data struct {
    Name  string
    Age   int
    Marks []int
}

func appendCustomData(d interface{}) {
    v := reflect.ValueOf(d).Elem()

    if f := v.FieldByName("Name"); f.IsValid() {
        f.SetString(f.Interface().(string) + "2")
    }

    if f := v.FieldByName("Age"); f.IsValid() {
        f.SetInt(f.Int() + 2)
    }

    if f := v.FieldByName("Marks"); f.IsValid() {
        f.Set(reflect.ValueOf(append(f.Interface().([]int), 2)))
    }

    if f := v.FieldByName("Invalid"); f.IsValid() {
        f.Set(reflect.ValueOf(append(f.Interface().([]int), 2)))
    }
}

Testing it:

d := &Data{
    Name:  "Bob",
    Age:   22,
    Marks: []int{5, 4, 3},
}
fmt.Printf("%+v\n", d)
appendCustomData(d)
fmt.Printf("%+v\n", d)

Output (try it on the Go Playground):

&{Name:Bob Age:22 Marks:[5 4 3]}
&{Name:Bob2 Age:24 Marks:[5 4 3 2]}

Update:

To answer your edited question: there is no difference when the value passed is a struct that embeds another struct. But the value wrapped in the interface{} still must be a pointer.

Example appendCustomData() that appends content to pageStruct.TemplateData.HeaderCSS:

func appendCustomData(d interface{}) {
    v := reflect.ValueOf(d).Elem()

    if f := v.FieldByName("TemplateData"); f.IsValid() {
        if f = f.FieldByName("HeaderCSS"); f.IsValid() {
            f.Set(reflect.ValueOf(f.Interface().(template.HTML) + "+new"))
        }
    }
}

Testing it:

ps := &pageStruct{
    TemplateData: TemplateData{
        HeaderCSS: template.HTML("old"),
    },
}
fmt.Printf("%+v\n", ps)
appendCustomData(ps)
fmt.Printf("%+v\n", ps)

Output (try it on the Go Playground):

&{TemplateData:{FooterJS: HeaderJS: HeaderCSS:old} Form:}
&{TemplateData:{FooterJS: HeaderJS: HeaderCSS:old+new} Form:}


问:
Exporting plaintext for excel with sympy
Most of my schoolwork for numerical analysis is done in excel, so I use excel functions extensively. However, I would like to start incorporating sympy into my workflow.

My question is is there a way to print functions from sympy to make them copy-paste-able to excel? What I end up doing when I get my output in sympy is reformatting it for excel i.e., regroup some terms so they are clearer to excel, and more often, change ** to ^.

I am aware that I can simply use mathematica for this, which prints my output to plaintext (where exponents are by default expressed with ^), but I am wondering if I can do the same with sympy.

答:
If mathematica style output is sufficient then the following should do:

```<code>import sympy
from sympy.printing import mathematica_code

x = sympy.symbols('x')
sympy.printing.mathematica_code(sympy.integrate(x**2,x))
</code>```

Documentation here.

There are lots of other printing options which might work even better than mathematica style output.

Body:
If mathematica style output is sufficient then the following should do:

import sympy
from sympy.printing import mathematica_code

x = sympy.symbols('x')
sympy.printing.mathematica_code(sympy.integrate(x**2,x))

Documentation here.

There are lots of other printing options which might work even better than mathematica style output.


问:
How to set the Toolbar collapseIcon color programmatically
I want to change the color of the back button in the toolbar when a search is displayed (the circled white arrow).

I managed to change the color of all other elements and I am stuck with the back arrow color.

I can set the collapseIcon (back arrow drawable) from xml:

```<code><android.support.v7.widget.Toolbar
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="?attr/actionBarSize"
    android:background="?attr/colorPrimary"
    app:layout_scrollFlags="enterAlways"
    app:popupTheme="@style/AppTheme.PopupOverlay"
    app:collapseIcon=I_WANT_TO_SET_THIS_PROGRAMMATICALLY>
</code>```

I set app:collapseIcon to whatever drawable I want and that works, however, I need to set it dynamically.

None of the suggestions I found here work for me.

not this:

```<code>final Drawable upArrow = ContextCompat.getDrawable(this, R.drawable. abc_ic_ab_back_material);
upArrow.setColorFilter(myColor, PorterDuff.Mode.SRC_ATOP);
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeAsUpIndicator(upArrow);
</code>```

or this:

```<code>appBar.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
    @Override
    public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
        Drawable d = ContextCompat.getDrawable(MyActivity.this, R.drawable.ic_back_white);
        d.setColorFilter(myColor, PorterDuff.Mode.SRC_ATOP);
        toolbar.setNavigationIcon(d);

//        Drawable d = ContextCompat.getDrawable(MyActivity.this, R.drawable.ic_back_white);
//        d.setColorFilter(myColor, PorterDuff.Mode.SRC_ATOP);
//        getSupportActionBar().setHomeAsUpIndicator(d);
            }
        });
</code>```

Neither anything else I found.

Can anyone please help?

Thank you

答:
Finally got it...

This is what worked for me:

```<code>final Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
AppBarLayout appBar = (AppBarLayout) findViewById(R.id.appbar);
appBar.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
    @Override
    public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
        for (int i = 0; i < toolbar.getChildCount(); i++) {
            View view = toolbar.getChildAt(i);
            if (view instanceof ImageButton) {
                ImageButton btn = (ImageButton) view;
                Drawable drawable = btn.getDrawable();
                drawable.setColorFilter(new_button_color, PorterDuff.Mode.SRC_ATOP);
                btn.setImageDrawable(drawable);
            }
        }
    }
});
</code>```

Body:
I want to change the color of the back button in the toolbar when a search is displayed (the circled white arrow).

I managed to change the color of all other elements and I am stuck with the back arrow color.

I can set the collapseIcon (back arrow drawable) from xml:

<android.support.v7.widget.Toolbar
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="?attr/actionBarSize"
    android:background="?attr/colorPrimary"
    app:layout_scrollFlags="enterAlways"
    app:popupTheme="@style/AppTheme.PopupOverlay"
    app:collapseIcon=I_WANT_TO_SET_THIS_PROGRAMMATICALLY>

I set app:collapseIcon to whatever drawable I want and that works, however, I need to set it dynamically.

None of the suggestions I found here work for me.

not this:

final Drawable upArrow = ContextCompat.getDrawable(this, R.drawable. abc_ic_ab_back_material);
upArrow.setColorFilter(myColor, PorterDuff.Mode.SRC_ATOP);
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeAsUpIndicator(upArrow);

or this:

appBar.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
    @Override
    public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
        Drawable d = ContextCompat.getDrawable(MyActivity.this, R.drawable.ic_back_white);
        d.setColorFilter(myColor, PorterDuff.Mode.SRC_ATOP);
        toolbar.setNavigationIcon(d);

//        Drawable d = ContextCompat.getDrawable(MyActivity.this, R.drawable.ic_back_white);
//        d.setColorFilter(myColor, PorterDuff.Mode.SRC_ATOP);
//        getSupportActionBar().setHomeAsUpIndicator(d);
            }
        });

Neither anything else I found.

Can anyone please help?

Thank you

Body:
Finally got it...

This is what worked for me:

final Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
AppBarLayout appBar = (AppBarLayout) findViewById(R.id.appbar);
appBar.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
    @Override
    public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
        for (int i = 0; i < toolbar.getChildCount(); i++) {
            View view = toolbar.getChildAt(i);
            if (view instanceof ImageButton) {
                ImageButton btn = (ImageButton) view;
                Drawable drawable = btn.getDrawable();
                drawable.setColorFilter(new_button_color, PorterDuff.Mode.SRC_ATOP);
                btn.setImageDrawable(drawable);
            }
        }
    }
});


问:
Matplotlib automatically scale vertical height of subplots for shared x-axis figure
I want to automatically scale the vertical height of subplots for shared x-axis figures based on their data span! I want to compare the relative intensity of the displayed data. If i use the sharey=True kwarg for the subbplots the data is displayed in a way that the relative intensity is  recognizable:

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

    SIZE = (12, 8) #desired overall figure size

    # Simple data to display in various forms
    x = np.linspace(0, 2 * np.pi, 400)

    y = np.sin(x ** 2)
    y2 = 2*(np.sin(x ** 2))
    y3 = 3*(np.sin(x ** 2))

    fig, ax = plt.subplots(3,ncols=1, sharex=True, sharey=True)
    fig.set_size_inches(SIZE[1], SIZE[0])
    fig.subplots_adjust(hspace=0.001)

    ax[0].plot(x, y)
    ax[1].plot(x, y2)
    ax[2].plot(x, y3)
    plt.show()
</code>```

All subplots have the same height now and the data span in the y-Axis is recognizable as the data is displayed with the correct relative proportion.
What i would like to achieve is that the scales of each plot end where the data ends. Essentially eliminating the not used white space. The size of the subplot would than represent the relative height ratios of the data. They should still have the same scaling on the Y axis in order for the viewer to estimate the relative data height ( which cold be a countrate for example).

I found the following links to  similar problems but none really helped me to solve my issue:

Link1 Link2

答:
Here an example that determines the ratio for you and creates the subplots accordingly:

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

SIZE = (12, 8) #desired overall figure size

# Simple data to display in various forms
x = np.linspace(0, 2 * np.pi, 400)

# the maximum multiplier for the function
N = 3

# the y-ranges:
ys = [i * np.sin(x**2) for i in range(1,N+1)]

# the maximum extent of the plot in y-direction (cast as int)
hs = [int(np.ceil(np.max(np.abs(y)))) for y in ys]

# determining the size of the GridSpec:
gs_size = np.sum(hs)
gs = gridspec.GridSpec(gs_size,1)

# the figure
fig = plt.figure(figsize = SIZE)

# creating the subplots
base = 0
ax = []
for y,h in zip(ys,hs):
    ax.append(fig.add_subplot(gs[base:h+base,:]))
    base += h
    ax[-1].plot(x,y)

##fig, ax = plt.subplots(3,ncols=1, sharex=True, sharey=True)
##fig.set_size_inches(SIZE[1], SIZE[0])
fig.subplots_adjust(hspace=0.001)

##ax[0].plot(x, ys[0])
##ax[1].plot(x, ys[1])
##ax[2].plot(x, ys[2])
plt.show()
</code>```

The code determines the maximum y-extend for each set of data, casts it into an integer and then divides the figure into subplots using the sum of these extends as scale for the GridSpec.

The resulting figure looks like this:

Tested on Python 3.5

EDIT:

If the maximum and minimum extents of your data are not comparable, it may be better to change the way hs is calculated into

```<code>hs = [int(np.ceil(np.max(y))) - int(np.floor(np.min(y))) for y in ys]
</code>```

Body:
I want to automatically scale the vertical height of subplots for shared x-axis figures based on their data span! I want to compare the relative intensity of the displayed data. If i use the sharey=True kwarg for the subbplots the data is displayed in a way that the relative intensity is  recognizable:

    import matplotlib.pyplot as plt
    from matplotlib import gridspec
    import numpy as np

    SIZE = (12, 8) #desired overall figure size

    # Simple data to display in various forms
    x = np.linspace(0, 2 * np.pi, 400)

    y = np.sin(x ** 2)
    y2 = 2*(np.sin(x ** 2))
    y3 = 3*(np.sin(x ** 2))

    fig, ax = plt.subplots(3,ncols=1, sharex=True, sharey=True)
    fig.set_size_inches(SIZE[1], SIZE[0])
    fig.subplots_adjust(hspace=0.001)

    ax[0].plot(x, y)
    ax[1].plot(x, y2)
    ax[2].plot(x, y3)
    plt.show()

All subplots have the same height now and the data span in the y-Axis is recognizable as the data is displayed with the correct relative proportion.
What i would like to achieve is that the scales of each plot end where the data ends. Essentially eliminating the not used white space. The size of the subplot would than represent the relative height ratios of the data. They should still have the same scaling on the Y axis in order for the viewer to estimate the relative data height ( which cold be a countrate for example).

I found the following links to  similar problems but none really helped me to solve my issue:

Link1 Link2

Body:
Here an example that determines the ratio for you and creates the subplots accordingly:

import matplotlib.pyplot as plt
from matplotlib import gridspec
import numpy as np

SIZE = (12, 8) #desired overall figure size

# Simple data to display in various forms
x = np.linspace(0, 2 * np.pi, 400)

# the maximum multiplier for the function
N = 3

# the y-ranges:
ys = [i * np.sin(x**2) for i in range(1,N+1)]

# the maximum extent of the plot in y-direction (cast as int)
hs = [int(np.ceil(np.max(np.abs(y)))) for y in ys]

# determining the size of the GridSpec:
gs_size = np.sum(hs)
gs = gridspec.GridSpec(gs_size,1)

# the figure
fig = plt.figure(figsize = SIZE)

# creating the subplots
base = 0
ax = []
for y,h in zip(ys,hs):
    ax.append(fig.add_subplot(gs[base:h+base,:]))
    base += h
    ax[-1].plot(x,y)

##fig, ax = plt.subplots(3,ncols=1, sharex=True, sharey=True)
##fig.set_size_inches(SIZE[1], SIZE[0])
fig.subplots_adjust(hspace=0.001)

##ax[0].plot(x, ys[0])
##ax[1].plot(x, ys[1])
##ax[2].plot(x, ys[2])
plt.show()

The code determines the maximum y-extend for each set of data, casts it into an integer and then divides the figure into subplots using the sum of these extends as scale for the GridSpec.

The resulting figure looks like this:

Tested on Python 3.5

EDIT:

If the maximum and minimum extents of your data are not comparable, it may be better to change the way hs is calculated into

hs = [int(np.ceil(np.max(y))) - int(np.floor(np.min(y))) for y in ys]


问:
Calculate total CPU usage
What is best algorithm for calculating total CPU usage at a particular time during execution of a process.

I am working windows platform in C++.

答:
Use WMI to get "PercentProcessorTime"; beware that this will probably have its own performance penalty.

If you are looking to throttle your application, a better way it to have your own internal performance metric specific to your application and throttle based on that (e.g. screen refresh rate, etc.)

Title: Calculate total CPU usage

LastEditorDisplayName: Martin

OwnerDisplayName: Nick


问:
How to debug kuberenetes system pod elections on masters?
I'm trying to make SSL work with kubernetes, but am stuck with leader election problem. So I think I should be seeing scheduler and controller system pods somewhere, while all I have is this:

kubectl get po --namespace=kube-system
NAME                             READY     STATUS    RESTARTS   AGE
kube-apiserver-10.255.12.200     1/1       Running   0          18h
kube-apiserver-10.255.16.111     1/1       Running   0          20h
kube-apiserver-10.255.17.12      1/1       Running   0          20h
scheduler-master-10.255.12.200   2/2       Running   0          20h
scheduler-master-10.255.16.111   2/2       Running   0          20h
scheduler-master-10.255.17.12    2/2       Running   0          20h

as for comparison, on my other clusters, I can see more pods:

kubectl get po --namespace=kube-system
NAME                                    READY     STATUS    RESTARTS   AGE
kube-apiserver-10.255.0.248             1/1       Running   1          30d
kube-apiserver-10.255.1.112             1/1       Running   1          30d
kube-apiserver-10.255.1.216             1/1       Running   1          30d
kube-controller-manager-10.255.1.216    1/1       Running   3          30d
kube-scheduler-10.255.1.216             1/1       Running   1          30d
scheduler-master-10.255.0.248           2/2       Running   2          30d
scheduler-master-10.255.1.112           2/2       Running   2          30d
scheduler-master-10.255.1.216           2/2       Running   2          30d

Does anybody knows how to debug this ? Pod logs doesn't show much, and my pods are stuck in pending state.

答: As mentioned by Javier Salmeron check the manifest folder. If they do exist there then check the log output of kubelet. If the missing pods try to start yout could also check the logs with "docker logs"</p>


问:
c# / XAML - ListView grouping: Changing the (background) color of the first header only
In my WPF Application, I have this ListView:

```<code><ListView.GroupStyle>
  <GroupStyle>
    <GroupStyle.ContainerStyle>
      <Style TargetType="{x:Type GroupItem}">
        <Setter Property="Template">
          <Setter.Value>
            <ControlTemplate>
              <Expander IsExpanded="True">
                <Expander.Header>
                  <StackPanel Orientation="Horizontal">
                    <TextBlock Text="{Binding Name}" FontWeight="Bold"
                               Foreground="Gray" FontSize="22"
                               VerticalAlignment="Bottom"/>
                    <TextBlock Text="{Binding ItemCount}" FontSize="22"
                               Foreground="Green" FontWeight="Bold"
                               FontStyle="Italic" Margin="10,0,0,0"
                               VerticalAlignment="Bottom" />
                    <TextBlock Text=" Ergebnis(se)" FontSize="22"
                               Foreground="Silver" FontStyle="Italic"
                               VerticalAlignment="Bottom"/>
                  </StackPanel>
                </Expander.Header>
                <ItemsPresenter/>
              </Expander>
            </ControlTemplate>
          </Setter.Value>
        </Setter>
      </Style>
    </GroupStyle.ContainerStyle>
  </GroupStyle>
</ListView.GroupStyle>
</code>```

Now I want the first - and only the first - Header to appear in a different color (than the rest of the Headers - Font Color or Background Color, I don't care) for it to be marked.
I can't for the hell of it come up with an idea on how to do it.

答:
Converter in WPF is very costly as it will execute for each ListViewItem. Since the requirement is to apply style always for the first item, VisualTreeHelper will be best fit for the solution.

```<code>var expander = GetElement<Expander>(myListView);
// Do expander style changes
</code>```

Below is a generic method to get the element from the Visual Tree.

```<code>public T GetElement<T>(Visual element)
{
        T foundElement = default(T);
        if (element == null) return foundElement;
        if (element.GetType() == typeof(T)) return (T)Convert.ChangeType(element, typeof(T));

        for (int i = 0; i < VisualTreeHelper.GetChildrenCount(element); i++)
        {
            Visual visual = VisualTreeHelper.GetChild(element, i) as Visual;
            foundElement = GetElement<T>(visual);
            if (foundElement != null) break;
        }
        return foundElement;
    }
</code>```

Body:
In my WPF Application, I have this ListView:

<ListView.GroupStyle>
  <GroupStyle>
    <GroupStyle.ContainerStyle>

    </GroupStyle.ContainerStyle>
  </GroupStyle>
</ListView.GroupStyle>

Now I want the first - and only the first - Header to appear in a different color (than the rest of the Headers - Font Color or Background Color, I don't care) for it to be marked.
I can't for the hell of it come up with an idea on how to do it.

Body:
Converter in WPF is very costly as it will execute for each ListViewItem. Since the requirement is to apply style always for the first item, VisualTreeHelper will be best fit for the solution.

var expander = GetElement<Expander>(myListView);
// Do expander style changes

Below is a generic method to get the element from the Visual Tree.

public T GetElement<T>(Visual element)
{
        T foundElement = default(T);
        if (element == null) return foundElement;
        if (element.GetType() == typeof(T)) return (T)Convert.ChangeType(element, typeof(T));

        for (int i = 0; i < VisualTreeHelper.GetChildrenCount(element); i++)
        {
            Visual visual = VisualTreeHelper.GetChild(element, i) as Visual;
            foundElement = GetElement<T>(visual);
            if (foundElement != null) break;
        }
        return foundElement;
    }


问:
Incorrect Character spacing When calling GraphicsPath.AddString In Windows 8 or newer
I've noticed on Windows 8.1 and newer operating systems that the spacing between glyphs is incorrect when drawing text using GraphicsPath.AddString().

The issue is extra obvious on fonts like Script MT Bold and other script fonts. You can see that the line between the characters doesn't properly connect to each other.

I've tried calling AddString() with different StringFormat configurations with no success. I see this behaviour both when using a PrivateFontCollection and normal fonts.

For our use case it is absolutely essential that we keep using a GraphicsPath object.

TextRender.DrawText and WPF behaves correctly.

I suspect this is a bug in GDI+.

I'm looking for a workaround or a way to make GraphicsPath.AddString() start behaving correctly.

We are also using PrivateFontCollection.

答:
If using WPF is an option you can generate Geometry using FormattedText and then add the Geometry figure by figure to a GraphicsPath object.

to use WPF in a WinForms application you will need a reference to

PresentationFramework

WindowsBase

PresentationCore

these methods might get you started.

```<code>    public static readonly int FORMATTED_TEXT_MAX_SIZE = 3579139;

    private static void addStringUsingFormattedText(GraphicsPath targetPath, string text, System.Drawing.FontFamily fontFamily, int fontStyle, float fontSize, System.Drawing.RectangleF layoutRect, System.Drawing.StringFormat stringFormat)
    {
        if (string.IsNullOrEmpty(text))
            return;
        var typeFaceToUse = createTypeFace((System.Drawing.FontStyle)fontStyle, fontFamily.Name);
        var ft = createFormattedText(text, fontSize, layoutRect.Width, layoutRect.Height, typeFaceToUse, stringFormat);
        var geometry = ft.BuildGeometry(new System.Windows.Point(layoutRect.X, layoutRect.Y));
        targetPath.StartFigure();
        foreach (PathFigure pf in geometry.GetFlattenedPathGeometry().Figures)
        {
            foreach (PolyLineSegment polySegment in pf.Segments)
                targetPath.AddPolygon(polySegment.Points.Select(point => new System.Drawing.PointF((float)point.X, (float)point.Y)).ToArray());
        }
        targetPath.CloseFigure();
    }

    private static FormattedText createFormattedText(string text, float fontSize, float width, float height, Typeface typeFaceToUse, System.Drawing.StringFormat stringFormat)
    {
        var ft = new FormattedText(text, System.Globalization.CultureInfo.CurrentCulture, System.Windows.FlowDirection.LeftToRight
            , typeFaceToUse, fontSize, Brushes.Black);
        if (width > 0)
            ft.MaxTextWidth = Math.Min(FORMATTED_TEXT_MAX_SIZE, width);
        if (height > 0)
            ft.MaxTextHeight = Math.Min(FORMATTED_TEXT_MAX_SIZE, height);
        ft.Trimming = TextTrimming.None;

        switch (stringFormat.Alignment)
        {
            case System.Drawing.StringAlignment.Center:
                ft.TextAlignment = TextAlignment.Center;
                break;
            case System.Drawing.StringAlignment.Far:
                ft.TextAlignment = ft.FlowDirection == FlowDirection.LeftToRight ? TextAlignment.Right : TextAlignment.Left;
                break;
            case System.Drawing.StringAlignment.Near:
                ft.TextAlignment = ft.FlowDirection == FlowDirection.LeftToRight ? TextAlignment.Left : TextAlignment.Right;
                break;
        }

        return ft;
    }
</code>```

We noticed that if we have an alignment set on our StringFormat it behaves slightly differently. You might need to adjust your logic for that.

In our case we were also using Graphics.MeasureString() to anticipate the width of the string. These following methods should work:

```<code>    private static System.Drawing.SizeF measureStringUsingFormattedText(string text, System.Drawing.Font measureFont, System.Drawing.RectangleF layoutRect, System.Drawing.StringFormat stringFormat)
    {
        if (string.IsNullOrEmpty(text))
            return new System.Drawing.SizeF(0, 0);
        var typeFaceToUse = createTypeFace(measureFont.Style, measureFont.Name);
        var ft = createFormattedText(text, measureFont.Size, layoutRect.Width, layoutRect.Height, typeFaceToUse, stringFormat);
        bool includeTrailingSpaces = System.Drawing.StringFormatFlags.MeasureTrailingSpaces == (stringFormat.FormatFlags & System.Drawing.StringFormatFlags.MeasureTrailingSpaces);
        var rectangleToReturn = new System.Drawing.SizeF((float)(includeTrailingSpaces ? ft.WidthIncludingTrailingWhitespace : ft.Width), (float)ft.Height);
        return rectangleToReturn;
    }

    private static System.Drawing.SizeF measureStringUsingFormattedText(string text, System.Drawing.Font measureFont, System.Drawing.SizeF layoutArea, System.Drawing.StringFormat stringFormat, out int linesFilled)
    {
        if (string.IsNullOrEmpty(text))
        {
            linesFilled = 0;
            return new System.Drawing.SizeF(0, 0);
        }

        var typeFaceToUse = createTypeFace(measureFont.Style, measureFont.Name);
        var ft = createFormattedText(text, measureFont.Size, layoutArea.Width, layoutArea.Height, typeFaceToUse, stringFormat);
        bool includeTrailingSpaces = System.Drawing.StringFormatFlags.MeasureTrailingSpaces == (stringFormat.FormatFlags & System.Drawing.StringFormatFlags.MeasureTrailingSpaces);
        var rectangleToReturn = new System.Drawing.SizeF((float)(includeTrailingSpaces ? ft.WidthIncludingTrailingWhitespace : ft.Width), (float)ft.Height);
        linesFilled = (int)Math.Floor(ft.Height / ft.Baseline);
        return rectangleToReturn;
    }
</code>```

For us the complicated part is how to get the TypeFace object. You can not convert a System.Drawing.FontFamily to a System.Windows.Media.TypeFace object. As long as you do not need a PrivateFontCollection this is no problem.

```<code>    private static Typeface createTypeFace(System.Drawing.FontStyle fontStyle, string familyName)
    {
        var fwToUse = System.Drawing.FontStyle.Bold == (fontStyle & System.Drawing.FontStyle.Bold) ? FontWeights.Bold : FontWeights.Normal;
        var fsToUse = System.Drawing.FontStyle.Italic == (fontStyle & System.Drawing.FontStyle.Italic) ? FontStyles.Italic : FontStyles.Normal;
        // Create and return a System.Windows.Media.TypeFace object...
        // if you previously used PrivateFontCollection you might need to load the font from a file.
    }
</code>```

I haven't done proper performance tests on this. I got the feeling this was slightly slower then just using GDI+.

Body:
If using WPF is an option you can generate Geometry using FormattedText and then add the Geometry figure by figure to a GraphicsPath object.

to use WPF in a WinForms application you will need a reference to

PresentationFramework

WindowsBase

PresentationCore

these methods might get you started.

    public static readonly int FORMATTED_TEXT_MAX_SIZE = 3579139;

    private static void addStringUsingFormattedText(GraphicsPath targetPath, string text, System.Drawing.FontFamily fontFamily, int fontStyle, float fontSize, System.Drawing.RectangleF layoutRect, System.Drawing.StringFormat stringFormat)
    {
        if (string.IsNullOrEmpty(text))
            return;
        var typeFaceToUse = createTypeFace((System.Drawing.FontStyle)fontStyle, fontFamily.Name);
        var ft = createFormattedText(text, fontSize, layoutRect.Width, layoutRect.Height, typeFaceToUse, stringFormat);
        var geometry = ft.BuildGeometry(new System.Windows.Point(layoutRect.X, layoutRect.Y));
        targetPath.StartFigure();
        foreach (PathFigure pf in geometry.GetFlattenedPathGeometry().Figures)
        {
            foreach (PolyLineSegment polySegment in pf.Segments)
                targetPath.AddPolygon(polySegment.Points.Select(point => new System.Drawing.PointF((float)point.X, (float)point.Y)).ToArray());
        }
        targetPath.CloseFigure();
    }

    private static FormattedText createFormattedText(string text, float fontSize, float width, float height, Typeface typeFaceToUse, System.Drawing.StringFormat stringFormat)
    {
        var ft = new FormattedText(text, System.Globalization.CultureInfo.CurrentCulture, System.Windows.FlowDirection.LeftToRight
            , typeFaceToUse, fontSize, Brushes.Black);
        if (width > 0)
            ft.MaxTextWidth = Math.Min(FORMATTED_TEXT_MAX_SIZE, width);
        if (height > 0)
            ft.MaxTextHeight = Math.Min(FORMATTED_TEXT_MAX_SIZE, height);
        ft.Trimming = TextTrimming.None;

        switch (stringFormat.Alignment)
        {
            case System.Drawing.StringAlignment.Center:
                ft.TextAlignment = TextAlignment.Center;
                break;
            case System.Drawing.StringAlignment.Far:
                ft.TextAlignment = ft.FlowDirection == FlowDirection.LeftToRight ? TextAlignment.Right : TextAlignment.Left;
                break;
            case System.Drawing.StringAlignment.Near:
                ft.TextAlignment = ft.FlowDirection == FlowDirection.LeftToRight ? TextAlignment.Left : TextAlignment.Right;
                break;
        }

        return ft;
    }

We noticed that if we have an alignment set on our StringFormat it behaves slightly differently. You might need to adjust your logic for that.

In our case we were also using Graphics.MeasureString() to anticipate the width of the string. These following methods should work:

    private static System.Drawing.SizeF measureStringUsingFormattedText(string text, System.Drawing.Font measureFont, System.Drawing.RectangleF layoutRect, System.Drawing.StringFormat stringFormat)
    {
        if (string.IsNullOrEmpty(text))
            return new System.Drawing.SizeF(0, 0);
        var typeFaceToUse = createTypeFace(measureFont.Style, measureFont.Name);
        var ft = createFormattedText(text, measureFont.Size, layoutRect.Width, layoutRect.Height, typeFaceToUse, stringFormat);
        bool includeTrailingSpaces = System.Drawing.StringFormatFlags.MeasureTrailingSpaces == (stringFormat.FormatFlags & System.Drawing.StringFormatFlags.MeasureTrailingSpaces);
        var rectangleToReturn = new System.Drawing.SizeF((float)(includeTrailingSpaces ? ft.WidthIncludingTrailingWhitespace : ft.Width), (float)ft.Height);
        return rectangleToReturn;
    }

    private static System.Drawing.SizeF measureStringUsingFormattedText(string text, System.Drawing.Font measureFont, System.Drawing.SizeF layoutArea, System.Drawing.StringFormat stringFormat, out int linesFilled)
    {
        if (string.IsNullOrEmpty(text))
        {
            linesFilled = 0;
            return new System.Drawing.SizeF(0, 0);
        }

        var typeFaceToUse = createTypeFace(measureFont.Style, measureFont.Name);
        var ft = createFormattedText(text, measureFont.Size, layoutArea.Width, layoutArea.Height, typeFaceToUse, stringFormat);
        bool includeTrailingSpaces = System.Drawing.StringFormatFlags.MeasureTrailingSpaces == (stringFormat.FormatFlags & System.Drawing.StringFormatFlags.MeasureTrailingSpaces);
        var rectangleToReturn = new System.Drawing.SizeF((float)(includeTrailingSpaces ? ft.WidthIncludingTrailingWhitespace : ft.Width), (float)ft.Height);
        linesFilled = (int)Math.Floor(ft.Height / ft.Baseline);
        return rectangleToReturn;
    }

For us the complicated part is how to get the TypeFace object. You can not convert a System.Drawing.FontFamily to a System.Windows.Media.TypeFace object. As long as you do not need a PrivateFontCollection this is no problem.

    private static Typeface createTypeFace(System.Drawing.FontStyle fontStyle, string familyName)
    {
        var fwToUse = System.Drawing.FontStyle.Bold == (fontStyle & System.Drawing.FontStyle.Bold) ? FontWeights.Bold : FontWeights.Normal;
        var fsToUse = System.Drawing.FontStyle.Italic == (fontStyle & System.Drawing.FontStyle.Italic) ? FontStyles.Italic : FontStyles.Normal;
        // Create and return a System.Windows.Media.TypeFace object...
        // if you previously used PrivateFontCollection you might need to load the font from a file.
    }

I haven't done proper performance tests on this. I got the feeling this was slightly slower then just using GDI+.


问:
How to make button's "pushed" effect?
I have 3 buttons that represents 3 states. I'd like when I push some of them that button stays in visual "push" state and other 2 are in normal non-pushed state.

Here's the code I use:

if (itemType === 'default') {
  document.getElementById("defaultMode").classList.remove('non-pushed');
  document.getElementById("defaultMode").classList.add('pushed');
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.pushed {
  border-style: inset;
}

.non-pushed {
  border-style: solid;
}</code>```

<button id="defaultMode" class="non-pushed" onclick="setMode('link', 'default');">Default</button>
<button id="orthoMode" onclick="setMode('link', 'ortho');">Ortho</button>
<button id="cornerMode" onclick="setMode('link', 'corner');">Corner</button>```

But, it's not working.

答:
You don't need JS!

Here's a CSS-only way:

 ```
<pre class="snippet-code-css lang-css prettyprint-override"><code>input.toggle {
  position:absolute;
  left:-20em;
}

input.toggle + label {
  border:1px solid black;
  background:lightgrey;
  display:inline-block;
  margin:5px;
  padding:5px;
  border-radius:5px;
  box-shadow:2px 2px 2px grey;
  user-select: none;
}

input.toggle:checked + label {
  background:grey;
  box-shadow:none;
}

input.toggle:focus + label {
  box-shadow:0px 0px 0px 2px dodgerblue;
}</code>```

<input type="radio" class="toggle" name="mode" value="default" id="default" checked>
Default

<input type="radio" class="toggle" name="mode" value="ortho" id="ortho">
Ortho

<input type="radio" class="toggle" name="mode" value="corner" id="corner">
Corner```
</div>
</div>
</p>

<p>If you need to know what mode has been selected:</p>

```let mode = document.querySelector('input[name=mode]:checked').value
console.log('Selected mode: ', mode)
```

Title: How to make button's "pushed" effect?

Body:
I have 3 buttons that represents 3 states. I'd like when I push some of them that button stays in visual "push" state and other 2 are in normal non-pushed state.

Here's the code I use:

if (itemType === 'default') {
  document.getElementById("defaultMode").classList.remove('non-pushed');
  document.getElementById("defaultMode").classList.add('pushed');
}

.pushed {
  border-style: inset;
}

.non-pushed {
  border-style: solid;
}

<button id="defaultMode" class="non-pushed" onclick="setMode('link', 'default');">Default</button>
<button id="orthoMode" onclick="setMode('link', 'ortho');">Ortho</button>
<button id="cornerMode" onclick="setMode('link', 'corner');">Corner</button>

But, it's not working.

Body:
You don't need JS!

Here's a CSS-only way:

input.toggle {
  position:absolute;
  left:-20em;
}

input.toggle + label {
  border:1px solid black;
  background:lightgrey;
  display:inline-block;
  margin:5px;
  padding:5px;
  border-radius:5px;
  box-shadow:2px 2px 2px grey;
  user-select: none;
}

input.toggle:checked + label {
  background:grey;
  box-shadow:none;
}

input.toggle:focus + label {
  box-shadow:0px 0px 0px 2px dodgerblue;
}

<input type="radio" class="toggle" name="mode" value="default" id="default" checked>
<label for="default">Default</label>

<input type="radio" class="toggle" name="mode" value="ortho" id="ortho">
<label for="ortho">Ortho</label>

<input type="radio" class="toggle" name="mode" value="corner" id="corner">
<label for="corner">Corner</label>

If you need to know what mode has been selected:

let mode = document.querySelector('input[name=mode]:checked').value
console.log('Selected mode: ', mode)


问:
How to get parent link of fancybox?
How to get parent window URL inside a child window of fancy box</p>

答:
If you're referring to accessing the containing document's URL from an iframe, try:</p>

```<code>window.top.location.href
</code>```

Title: How to get parent link of fancybox?

Body:
If you're referring to accessing the containing document's URL from an iframe, try:

window.top.location.href


问:
R purrr function: Sensitivity with multiple parameters
I have been working on this problem and can't seem to figure it out.

I have a dataset show below in which I want to run a cashflow sensitivity to price.  The dataset will have appended rows, but the problem I am running into is using the different prices with the unique labor cost and matching them to their unique stations.

```<code>a <- data.frame(Name = "station1", units_sold = seq(2000, 3000, by = 2))
b <- data.frame(Name = "station2", units_sold = seq(1000, 2000, by = 2))

monthly_sales <- rbind(a, b)

price_1 <- c(2,3,4,5,6) #price for station_1
price_2 <- c(3,4,5,6,7) #price for station_2

labor1 <- c(1000) #labor for station_1
labor2 <- c(2000) #labor for station_2
</code>```

I am using the code below and I am not able to apply price_1 and labor_1 to station_1, and then price_2 and labor_2 to station_2 for my sensitivity.

How do I setup my cf_model function or the map function to match the unique labor and price parameters?

Any help would be greatly appreciated!

```<code>cf_model <- function(x)
{
  data.frame(Scenario = (monthly_sales$units_sold * price_1[x]))
}
sensitivity_model <- data.frame(map(1:5, cf_model))
</code>```

答:
It is hard to figure out what you want to do exactly.
Do you want to find out what net revenue you will have if you have different assumptions about items sold, price per item and (total) labor costs?

If this is so I think the quickest way would look like e.g.

```<code>    scenario_station_1 <- data.frame(a$units_sold %*% t(price_1) - labor1)
    names(scenario_station_1)<-as.character(price_1)
</code>```

Body:
I have been working on this problem and can't seem to figure it out.

I have a dataset show below in which I want to run a cashflow sensitivity to price.  The dataset will have appended rows, but the problem I am running into is using the different prices with the unique labor cost and matching them to their unique stations.

a <- data.frame(Name = "station1", units_sold = seq(2000, 3000, by = 2))
b <- data.frame(Name = "station2", units_sold = seq(1000, 2000, by = 2))

monthly_sales <- rbind(a, b)

price_1 <- c(2,3,4,5,6) #price for station_1
price_2 <- c(3,4,5,6,7) #price for station_2

labor1 <- c(1000) #labor for station_1
labor2 <- c(2000) #labor for station_2

I am using the code below and I am not able to apply price_1 and labor_1 to station_1, and then price_2 and labor_2 to station_2 for my sensitivity.

How do I setup my cf_model function or the map function to match the unique labor and price parameters?

Any help would be greatly appreciated!

cf_model <- function(x)
{
  data.frame(Scenario = (monthly_sales$units_sold * price_1[x]))
}
sensitivity_model <- data.frame(map(1:5, cf_model))

Body:
It is hard to figure out what you want to do exactly.
Do you want to find out what net revenue you will have if you have different assumptions about items sold, price per item and (total) labor costs?

If this is so I think the quickest way would look like e.g.

    scenario_station_1 <- data.frame(a$units_sold %*% t(price_1) - labor1)
    names(scenario_station_1)<-as.character(price_1)


问:
Angular and NodeJS GET request url with params returns only response object no component HTML
I have a URL like for example 'localhost:3000/verify/a5d5sd', that I have sent to a user's email, upon clicking this link, I am using the param (a5d5sd) in the link for checking some stuff in the server and database(MongoDB) and returning a response with an object, now when the link is clicked or opened on a new tab, I only see the response from the server but not with the HTML from my Angular 2 component.

In my Angular 2 route config module, I did config a route like

```<code>  {
    path: 'verify/:id',
    component: MyComponent
  },
</code>```

And on ngOnInit of this component, I am calling a service method that makes a GET http request with a URL like verify/:id the param(:id) I get it using the ActivatedRoute from the @angular/router so that I can make the request.

To handle this I was advised to have the following code for my express to use:

```<code>app.use(express.static(path.join(__dirname, 'client/dist')));

app.get('*', function(req, res) {
  res.sendFile(__dirname + '/client/dist/index.html');
})
</code>```

Have even tried with:

```<code>app.all('*', function(req, res) {
  res.sendFile(__dirname + '/client/dist/index.html');
})
</code>```

This code works for direct navigation(pasting URLon the search bar) and refreshes for only POST and PUT requests but not working with GET requestS that expects a response from the server side, when I directly visit a URL or refresh the page, the DOM is written with the server response but with not HTML, any assistance will be appreciated.

答:
After define all routes, add the route for the index.html file

```<code>// Set your routes here
app.use('/api', api);

// Catch all other routes and return the index file
app.get('*', function(req, res) {
  res.sendFile(path.join(__dirname, 'path/to/index.html')); //path from the root dir
});
</code>```

This was work for me.
Thanks

Body:
I have a URL like for example 'localhost:3000/verify/a5d5sd', that I have sent to a user's email, upon clicking this link, I am using the param (a5d5sd) in the link for checking some stuff in the server and database(MongoDB) and returning a response with an object, now when the link is clicked or opened on a new tab, I only see the response from the server but not with the HTML from my Angular 2 component.

In my Angular 2 route config module, I did config a route like

  {
    path: 'verify/:id',
    component: MyComponent
  },

And on ngOnInit of this component, I am calling a service method that makes a GET http request with a URL like verify/:id the param(:id) I get it using the ActivatedRoute from the @angular/router so that I can make the request.

To handle this I was advised to have the following code for my express to use:

app.use(express.static(path.join(__dirname, 'client/dist')));

app.get('*', function(req, res) {
  res.sendFile(__dirname + '/client/dist/index.html');
})

Have even tried with:

app.all('*', function(req, res) {
  res.sendFile(__dirname + '/client/dist/index.html');
})

This code works for direct navigation(pasting URLon the search bar) and refreshes for only POST and PUT requests but not working with GET requestS that expects a response from the server side, when I directly visit a URL or refresh the page, the DOM is written with the server response but with not HTML, any assistance will be appreciated.

Body:
After define all routes, add the route for the index.html file

// Set your routes here
app.use('/api', api);

// Catch all other routes and return the index file
app.get('*', function(req, res) {
  res.sendFile(path.join(__dirname, 'path/to/index.html')); //path from the root dir
});

This was work for me.
Thanks


问:
could not load file or assembly 'microsoft.sqlserver.management.sdk.sfc version=11.0.0.0
I am using Database first approach of Entity framework. When I create new connection in "ADO.NET Entity Data Model" then after adding server name and database name, then it shows me this error -

```<code>Could not load file or assembly
'Microsoft.SqlServer.Management.Sdkc.Sfc, Version=11.0.0.0,
Culture=neutral, PublicKey Toekn = 89845dcd8080cc91' or one of its
dependencies. The system cannot find the file specified.
</code>```

Found many links on Google and tried but it doesn't solve my issue.

Could not load file or assembly Microsoft.SqlServer.management.sdk.sfc version 11.0.0.0

Tried this

SharedManagementObjects.msi (64 Bit) (Install proper and restart VS and same error occurs again)
PowerShellTools.msi

Visual Studio 2012, SQL Server 2008 R2, 64 Bit Operating System

答:
Note: x86 or x64 depending on OS Structure

Step 1: Visit the below url and then click on Download option. http://www.microsoft.com/en-us/download/details.aspx?id=35580

Step 2: select the file name:ENU\ x64 \SQLSysClrTypes.msi and then click on Next. This will shown an option to run this msi file. Please run this msi file and finish the installation.

Step 3: Again visit the above link and click on Download option. this time you need to select the file name:ENU\ x64 \SharedManagementObjects.msi and then click on Next. This will shown an option to run this msi file. Please run this msi file and finish the installation.

Step 4: Once above 2 files are downloaded and installed. Close the Visual Studio and reopen it. Now you should be able to create the database through server explorer without any errors.

Body:
I am using Database first approach of Entity framework. When I create new connection in "ADO.NET Entity Data Model" then after adding server name and database name, then it shows me this error -

Could not load file or assembly
'Microsoft.SqlServer.Management.Sdkc.Sfc, Version=11.0.0.0,
Culture=neutral, PublicKey Toekn = 89845dcd8080cc91' or one of its
dependencies. The system cannot find the file specified.

Found many links on Google and tried but it doesn't solve my issue.

Could not load file or assembly Microsoft.SqlServer.management.sdk.sfc version 11.0.0.0

Tried this

SharedManagementObjects.msi (64 Bit) (Install proper and restart VS and same error occurs again)
PowerShellTools.msi

Visual Studio 2012, SQL Server 2008 R2, 64 Bit Operating System


问:
HTML table cell issue
I am brand new to front end HTML and trying to construct a table identical to the below example whereby I have cell numbering identical to this.

My code as it stands when rendered looks like this.

I am struggling to figure out how I achieve the cell numbering. I have done a few things but it looks out of sorts.  Is this done via colspan.

```<code><table border="1">
          <tr>
            <td>Bruce Springsteen Born To Run</td>
            <td><img src="images/borntorun.jpg" alt="bruce springsteen"></td>
          </tr>
          <tr>
            <td>Thunder Road</td>
            <td>4.47</td>
          </tr>
          <tr>
            <td>10th Avenue Freeze Out</td>
            <td>3.10</td>
          </tr>
          <tr>
            <td>Night</td>
            <td>3.00</td>
          </tr>
            <td>Backstreets</td>
            <td>6.29</td>
          </tr>
          <tr>
            <td>Born To Run</td>
            <td>4.29</td>
          </tr>
          <tr>
            <td>She's the one</td>
            <td>4.29</td>
          </tr>
          <tr>
            <td>Meeting Across The River</td>
            <td>3.15</td>
          </tr>
          <tr>
            <td>Jungleland</td>
            <td>9.33</td>
        </table>
</code>```

答:
You can use colspan to do it.

    Bruce Springsteen Born To Run

    1
    Thunder Road
    4.47

    2
    10th Avenue Freeze Out
    3.10

```

Title: HTML table cell issue

Body:
I am brand new to front end HTML and trying to construct a table identical to the below example whereby I have cell numbering identical to this.

My code as it stands when rendered looks like this.

I am struggling to figure out how I achieve the cell numbering. I have done a few things but it looks out of sorts.  Is this done via colspan.

            Bruce Springsteen Born To Run

            Thunder Road
            4.47

            10th Avenue Freeze Out
            3.10

            Night
            3.00

            Backstreets
            6.29

            Born To Run
            4.29

            She's the one
            4.29

            Meeting Across The River
            3.15

            Jungleland
            9.33

Body:
You can use colspan to do it.

<table border="1" width="100%">
  <tr>
    <td colspan="2">Bruce Springsteen Born To Run</td>
    <td><img src="http://www.trait-tech.com/uploads/T-TOOL-9406__Acrylic-Mirror-Effect-3d-Wall-Decals-Flower-Shaped-Mirrors-Stickers-Pack-of-5-Set-for-Halloween-Chirstmas-Valentine-.jpg" alt="bruce springsteen"></td>
  </tr>
  <tr>
    <td>1</td>
    <td>Thunder Road</td>
    <td>4.47</td>
  </tr>
  <tr>
    <td>2</td>
    <td>10th Avenue Freeze Out</td>
    <td>3.10</td>
  </tr>
  <!--Other rows here-->
</table>