问:
@Watch decorator not activating
I've got a simple Test component, the template looks like this:

```<code><template>
  <div>
    <input type="text" v-model="name" class="form-control">
    <h5>{{ message }}</h5>
  </div>
</template>
<script src="./test.ts" lang="ts"></script>
</code>```

and the component TypeScript looks like this:

```<code>declare var Vue: typeof Function;
declare var VueClassComponent: any;

import { Component, Inject, Model, Prop, Watch } from "vue-property-decorator";

@VueClassComponent.default({
  template: require("./test.vue"),
  style: require("./test.sass"),
  props: {
    name: String,
    num: Number
  }
})
export default class TestComponent extends Vue {
  name: string;
  num: number;
  message: string = "";

  @Watch("name")
  protected onNameChanged(newName: string, oldName: string): any {
    console.log("setting " + oldName + " to " + newName);
  }

  mounted(this: any): void {
    console.log("mounted called");
    this.message = "Hello " + this.name + " " + this.num;
  }
}
</code>```

When I type in the input box, the @Watch("name") handler never fires, however I do get these errors in the console:

```<code>[Vue warn]: Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-renders. Instead, use a data or computed property based on the prop's value. Prop being mutated: "name"
</code>```

Once for every character entered in the input box. I have no idea where the name is being set, because I have not set it anywhere. Although that is my goal (to update name) I've been reading you can't just change the value directly, you need to set @Watch handlers, and then somewhere else set them (I still don't understand exactly how but can't even get that for right now.

答:
Based on our discussion, the root of the problem here was declaring name as a property. The intention was that name was an internal value that would simply be used to derive message. That being the case, a watch is unnecessary and a computed does the trick.

```<code>declare var Vue: typeof Function;
declare var VueClassComponent: any;

import { Component, Inject, Model, Prop, Watch } from "vue-property-decorator";

@VueClassComponent.default({
  template: require("./test.vue"),
  style: require("./test.sass"),
  props: {
    num: Number
  }
})
export default class TestComponent extends Vue {
  name: string;
  num: number;

  get message(){
      return "Hello " + this.name + " " + this.num;
  }
}
</code>```

Title: @Watch decorator not activating

Body:
I've got a simple Test component, the template looks like this:

<template>

    <input type="text" v-model="name" class="form-control">

{{ message }}

</template>

and the component TypeScript looks like this:

declare var Vue: typeof Function;
declare var VueClassComponent: any;

import { Component, Inject, Model, Prop, Watch } from "vue-property-decorator";

@VueClassComponent.default({
  template: require("./test.vue"),
  style: require("./test.sass"),
  props: {
    name: String,
    num: Number
  }
})
export default class TestComponent extends Vue {
  name: string;
  num: number;
  message: string = "";

  @Watch("name")
  protected onNameChanged(newName: string, oldName: string): any {
    console.log("setting " + oldName + " to " + newName);
  }

  mounted(this: any): void {
    console.log("mounted called");
    this.message = "Hello " + this.name + " " + this.num;
  }
}

When I type in the input box, the @Watch("name") handler never fires, however I do get these errors in the console:

[Vue warn]: Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-renders. Instead, use a data or computed property based on the prop's value. Prop being mutated: "name"

Once for every character entered in the input box. I have no idea where the name is being set, because I have not set it anywhere. Although that is my goal (to update name) I've been reading you can't just change the value directly, you need to set @Watch handlers, and then somewhere else set them (I still don't understand exactly how but can't even get that for right now.

Body:
Based on our discussion, the root of the problem here was declaring name as a property. The intention was that name was an internal value that would simply be used to derive message. That being the case, a watch is unnecessary and a computed does the trick.

declare var Vue: typeof Function;
declare var VueClassComponent: any;

import { Component, Inject, Model, Prop, Watch } from "vue-property-decorator";

@VueClassComponent.default({
  template: require("./test.vue"),
  style: require("./test.sass"),
  props: {
    num: Number
  }
})
export default class TestComponent extends Vue {
  name: string;
  num: number;

  get message(){
      return "Hello " + this.name + " " + this.num;
  }
}


来源: stackexchange

问:
UDF to return formatted number
Sometimes I like to display numbers along with text in the same cell. To do this, I custom format the cell to something like 0.00" test", e.g. a cell A1 with formula =PI(), but formatted with custom format 0.00" test" would return a displayed result of 3.14 test.

Crucially, the value of the cell is unchanged by the formatting - you can still do =A1 * 3 in another cell and get the result - since the value of A1 is still Pi, only it's display has changed.

For a UDF that returns a numerical value (in my case, Long, but it could be any number), is there a way of returning a cell such that it is displayed 1 way, but it's actual value (.Value2 in VBA I believe) is a number, not text.

I've tried Format( in VBA, but it returns a text string. I would just format my cell how I want it manually, but as you can see from the below code, the formatting is dependent on intermediate results (I'm trying to return the value formatted with the time the calculation took).

```<code>UDF_RESULT = Format(valueResult.Length, IIf(tElapsed < timeout, "0" & " """ & Round(tElapsed, 2) & "s""", "0"))
</code>```

This would be easy to do with a Macro, but within a UDF it's harder. I could declare all of the intermediate values at a module level, then a Worksheet_Calculate() macro can access those values and apply the custom formatting, but a UDF-wrapped approach would be much better.

答:
No.

You're confusing a cell's value with its number format. A UDF can compute a value, and the cell is free to format that value as needed.

So if a UDF returns a number, the cell's value is the result of that function - a number.

Just format the cell as needed. A function doesn't format anything.

ContentLicense: CC BY-SA 3.0

Title: UDF to return formatted number

Body:
Sometimes I like to display numbers along with text in the same cell. To do this, I custom format the cell to something like 0.00" test", e.g. a cell A1 with formula =PI(), but formatted with custom format 0.00" test" would return a displayed result of 3.14 test.

Crucially, the value of the cell is unchanged by the formatting - you can still do =A1 * 3 in another cell and get the result - since the value of A1 is still Pi, only it's display has changed.

For a UDF that returns a numerical value (in my case, Long, but it could be any number), is there a way of returning a cell such that it is displayed 1 way, but it's actual value (.Value2 in VBA I believe) is a number, not text.

I've tried Format( in VBA, but it returns a text string. I would just format my cell how I want it manually, but as you can see from the below code, the formatting is dependent on intermediate results (I'm trying to return the value formatted with the time the calculation took).

UDF_RESULT = Format(valueResult.Length, IIf(tElapsed < timeout, "0" & " """ & Round(tElapsed, 2) & "s""", "0"))

This would be easy to do with a Macro, but within a UDF it's harder. I could declare all of the intermediate values at a module level, then a Worksheet_Calculate() macro can access those values and apply the custom formatting, but a UDF-wrapped approach would be much better.


问:
Java - throws not working for a subtype of an exception that is handled
Take this as example:

```<code>public class TestClass {

    public static void test() throws SSLHandshakeException {
        throw new SSLHandshakeException("I'm a SSL Exception");
    }

    public static void main(String[] args) throws SSLHandshakeException {
        try {
            test ();
        } catch (IOException ioe) {
            System.out.println("I`m handling IO exception");
        }
    }
}
</code>```

So, I have my test method in which I'm just throwing an SSLHandshakeException which is a subtype of IOException.

The output for this is "I`m handling IO exception".

Why does this happen? I expected that my method will throw the SSLHandshakeException. Is there a rule that catch is more important than throws?

I just want to avoid using

```<code>try {
   test ();
} catch (SSLHandshakeException se) {
   throw se;
} catch (IOException ioe) {
   System.out.println("I`m handling IO exception");
}
</code>```

Because I consider it less readable

答:
Is there a rule that catch is more important than throws?

They are two completely different things. The throws keyword is part of the method signature and is saying 'This method can throw this exception, so every caller should handle that explicitly.'

Wether or not the method actually throws that exception is irrelevant here.

As for the catch statement. SSLHandshakeException is an IOException, and so it is caught as expected.

To get the behaviour you intent you can write:

```<code>    try {
        test ();
    } catch (SSLHandshakeException sslExc) {
        throw sslExc;
    } catch (IOException ioe) {
        System.out.println("I`m handling IO exception that is not an SSLHandshakeException");
    }
</code>```

Edit: You say you find this less readable. But honestly this is just the best way. If it would behave the way you proposed than you would never be able to catch an SSLHandshakeException in a method that might also throw it? What if you want to catch it in certain conditions but throw it in others? It would just be too limiting and unintuitive.

An alternative is like so; but in my opinion this is even less readable:

```<code>    try {
        test ();
    } catch (IOException ioe) {
        if(ioe instanceof SSLHandshakeException)
            throw ioe;
        System.out.println("I`m handling IO exception that is not an SSLHandshakeException");
    }
</code>```

Body:
Take this as example:

public class TestClass {

    public static void test() throws SSLHandshakeException {
        throw new SSLHandshakeException("I'm a SSL Exception");
    }

    public static void main(String[] args) throws SSLHandshakeException {
        try {
            test ();
        } catch (IOException ioe) {
            System.out.println("I`m handling IO exception");
        }
    }
}

So, I have my test method in which I'm just throwing an SSLHandshakeException which is a subtype of IOException.

The output for this is "I`m handling IO exception".

Why does this happen? I expected that my method will throw the SSLHandshakeException. Is there a rule that catch is more important than throws?

I just want to avoid using

try {
   test ();
} catch (SSLHandshakeException se) {
   throw se;
} catch (IOException ioe) {
   System.out.println("I`m handling IO exception");
}

Because I consider it less readable

Body:
Is there a rule that catch is more important than throws?

They are two completely different things. The throws keyword is part of the method signature and is saying 'This method can throw this exception, so every caller should handle that explicitly.'

Wether or not the method actually throws that exception is irrelevant here.

As for the catch statement. SSLHandshakeException is an IOException, and so it is caught as expected.

To get the behaviour you intent you can write:

    try {
        test ();
    } catch (SSLHandshakeException sslExc) {
        throw sslExc;
    } catch (IOException ioe) {
        System.out.println("I`m handling IO exception that is not an SSLHandshakeException");
    }

Edit: You say you find this less readable. But honestly this is just the best way. If it would behave the way you proposed than you would never be able to catch an SSLHandshakeException in a method that might also throw it? What if you want to catch it in certain conditions but throw it in others? It would just be too limiting and unintuitive.

An alternative is like so; but in my opinion this is even less readable:

    try {
        test ();
    } catch (IOException ioe) {
        if(ioe instanceof SSLHandshakeException)
            throw ioe;
        System.out.println("I`m handling IO exception that is not an SSLHandshakeException");
    }


问:
How can I do a "FOR JSON" with 2 joins
I can't get this to work properly. I have 4 tables: Products, Suppliers, X_Product_Suppliers and Comments. I want to query them all and put them into JSON using the following query:

```<code>WITH Products (Id, Name, Price) As (
    SELECT 1, 'First Product', 10
), Suppliers (Id, Name) As (
    SELECT 1, 'Factory1' UNION ALL
    SELECT 2, 'Factory2'
), Comments (Id, [Text], ProductId) As (
    SELECT 1, 'Good Product', 1 UNION ALL
    SELECT 2, 'Fantastic!'  , 1
), X_Product_Supplier (ProductId, SupplierId) As (
    SELECT 1, 1 UNION ALL
    SELECT 1, 2
)
SELECT Products.*, Suppliers.*, Comments.* FROM Products
LEFT OUTER JOIN X_Product_Supplier ON X_Product_Supplier.ProductId = Products.Id
LEFT OUTER JOIN Suppliers ON X_Product_Supplier.SupplierId = Suppliers.Id
LEFT OUTER JOIN Comments ON Comments.ProductId = Products.Id
FOR JSON AUTO
</code>```

For some reason sql-server will nest the comments under the supplier instead of under the product:

```<code>   {
      "Id":1,
      "Name":"First Product",
      "Price":"10",
      "Suppliers":[
         {
            "Id":1,
            "Name":"Factory1",
            "Comments":[  //THIS SHOULD BE UNDER PRODUCT, NOT SUPPLIER
               {
                  "Id":1,
                  "Text":"Good Product",
                  "ProductId":1
               },
               {
                  "Id":2,
                  "Text":"Fantastic!",
                  "ProductId":1
               }
            ]
         },
         {
            "Id":2,
            "Name":"Factory2",
            "Comments":[  //THIS IS NOW DUPLICATE
               {
                  "Id":1,
                  "Text":"Good Product",
                  "ProductId":1
               },
               {
                  "Id":2,
                  "Text":"Fantastic!",
                  "ProductId":1
               }
            ]
         }
      ]
   }
</code>```

What I actually want is this:

```<code>   {
      "Id":1,
      "Name":"First Product",
      "Price":"10",
      "Suppliers":[
         {
            "Id":1,
            "Name":"Factory1"
         },
         {
            "Id":2,
            "Name":"Factory2"
         }
      ],
      "Comments":[
               {
                  "Id":1,
                  "Text":"Good Product",
                  "ProductId":1
               },
               {
                  "Id":2,
                  "Text":"Fantastic!",
                  "ProductId":1
               }
            ]
   }
</code>```

How do I do this?

答:
SQL Server will convert result table into JSON with columns going in the same order as they appear in SELECT statement. It would not make any assumptions of column grouping. To help it Suppliers and Comments can be pre-arranged into JSON objects for each Product:

```<code>WITH Products (Id, Name, Price) As (
    SELECT 1, 'First Product', 10
), Suppliers (Id, Name) As (
    SELECT 1, 'Factory1' UNION ALL
    SELECT 2, 'Factory2'
), Comments (Id, [Text], ProductId) As (
    SELECT 1, 'Good Product', 1 UNION ALL
    SELECT 2, 'Fantastic!'  , 1
), X_Product_Supplier (ProductId, SupplierId) As (
    SELECT 1, 1 UNION ALL
    SELECT 1, 2
)
SELECT Products.*,
    (SELECT Suppliers.*
     FROM Suppliers
     INNER JOIN X_Product_Supplier ON X_Product_Supplier.SupplierId = Suppliers.Id
     WHERE X_Product_Supplier.ProductId = Products.Id
     FOR JSON AUTO, TYPE) As Suppliers,
    (SELECT Comments.*
     FROM Comments
     WHERE Comments.ProductId = Products.Id
     FOR JSON AUTO, TYPE) As Comments
FROM Products
FOR JSON AUTO
</code>```

Tested on XML as I do not have access to SQL Server 2016 at the moment.
Please let me know if this does not work.

Title: How can I do a "FOR JSON" with 2 joins

Body:
I can't get this to work properly. I have 4 tables: Products, Suppliers, X_Product_Suppliers and Comments. I want to query them all and put them into JSON using the following query:

WITH Products (Id, Name, Price) As (
    SELECT 1, 'First Product', 10
), Suppliers (Id, Name) As (
    SELECT 1, 'Factory1' UNION ALL
    SELECT 2, 'Factory2'
), Comments (Id, [Text], ProductId) As (
    SELECT 1, 'Good Product', 1 UNION ALL
    SELECT 2, 'Fantastic!'  , 1
), X_Product_Supplier (ProductId, SupplierId) As (
    SELECT 1, 1 UNION ALL
    SELECT 1, 2
)
SELECT Products.*, Suppliers.*, Comments.* FROM Products
LEFT OUTER JOIN X_Product_Supplier ON X_Product_Supplier.ProductId = Products.Id
LEFT OUTER JOIN Suppliers ON X_Product_Supplier.SupplierId = Suppliers.Id
LEFT OUTER JOIN Comments ON Comments.ProductId = Products.Id
FOR JSON AUTO

For some reason sql-server will nest the comments under the supplier instead of under the product:

   {
      "Id":1,
      "Name":"First Product",
      "Price":"10",
      "Suppliers":[
         {
            "Id":1,
            "Name":"Factory1",
            "Comments":[  //THIS SHOULD BE UNDER PRODUCT, NOT SUPPLIER
               {
                  "Id":1,
                  "Text":"Good Product",
                  "ProductId":1
               },
               {
                  "Id":2,
                  "Text":"Fantastic!",
                  "ProductId":1
               }
            ]
         },
         {
            "Id":2,
            "Name":"Factory2",
            "Comments":[  //THIS IS NOW DUPLICATE
               {
                  "Id":1,
                  "Text":"Good Product",
                  "ProductId":1
               },
               {
                  "Id":2,
                  "Text":"Fantastic!",
                  "ProductId":1
               }
            ]
         }
      ]
   }

What I actually want is this:

   {
      "Id":1,
      "Name":"First Product",
      "Price":"10",
      "Suppliers":[
         {
            "Id":1,
            "Name":"Factory1"
         },
         {
            "Id":2,
            "Name":"Factory2"
         }
      ],
      "Comments":[
               {
                  "Id":1,
                  "Text":"Good Product",
                  "ProductId":1
               },
               {
                  "Id":2,
                  "Text":"Fantastic!",
                  "ProductId":1
               }
            ]
   }

How do I do this?

Body:
SQL Server will convert result table into JSON with columns going in the same order as they appear in SELECT statement. It would not make any assumptions of column grouping. To help it Suppliers and Comments can be pre-arranged into JSON objects for each Product:

WITH Products (Id, Name, Price) As (
    SELECT 1, 'First Product', 10
), Suppliers (Id, Name) As (
    SELECT 1, 'Factory1' UNION ALL
    SELECT 2, 'Factory2'
), Comments (Id, [Text], ProductId) As (
    SELECT 1, 'Good Product', 1 UNION ALL
    SELECT 2, 'Fantastic!'  , 1
), X_Product_Supplier (ProductId, SupplierId) As (
    SELECT 1, 1 UNION ALL
    SELECT 1, 2
)
SELECT Products.*,
    (SELECT Suppliers.*
     FROM Suppliers
     INNER JOIN X_Product_Supplier ON X_Product_Supplier.SupplierId = Suppliers.Id
     WHERE X_Product_Supplier.ProductId = Products.Id
     FOR JSON AUTO, TYPE) As Suppliers,
    (SELECT Comments.*
     FROM Comments
     WHERE Comments.ProductId = Products.Id
     FOR JSON AUTO, TYPE) As Comments
FROM Products
FOR JSON AUTO

Tested on XML as I do not have access to SQL Server 2016 at the moment.
Please let me know if this does not work.


问:
Can't break MySQL table dump into new lines corresponding to table rows
I have a query that dumps a table's data into a text file for reporting purposes. The only problem is that it's not breaking the text file into lines corresponding to the field set in the table. I just get a continuous sequence of data and have to go to the start of what SHOULD be each row, and hit RETURN.

My code is

```<code>$fh = fopen('dump.txt', 'w');

while ($row = mysql_fetch_array($result))
     {
        $last = end($row);
        $num = mysql_num_fields($result) ;
           for($i = 1; $i < $num; $i++)
             {
               fwrite($fh, $row[$i]);
               if ($row[$i] != $last)
               fwrite($fh);
             }
        fwrite($fh, "\n");
     }
    fclose($fh);
</code>```

答:
```<code>$fh = fopen('dump.txt', 'w');
$exampleData = array(array(1,2,3),array('a','b','c'),array('x','y','z'));
while ($row = array_shift($exampleData))
{
  fwrite($fh, implode(' ',$row).PHP_EOL);
}
fclose($fh);
</code>```

will become

```<code>1 2 3
a b c
x y z
</code>```

if that not working for you, then there is some other bug to find.

Maybe use \r\n instead of just \n if you have still problems with line-breaks. PHP_EOL holds \n (linux) or \r\n (win).

Body:
I have a query that dumps a table's data into a text file for reporting purposes. The only problem is that it's not breaking the text file into lines corresponding to the field set in the table. I just get a continuous sequence of data and have to go to the start of what SHOULD be each row, and hit RETURN.

My code is

$fh = fopen('dump.txt', 'w');

while ($row = mysql_fetch_array($result))
     {
        $last = end($row);
        $num = mysql_num_fields($result) ;
           for($i = 1; $i < $num; $i++)
             {
               fwrite($fh, $row[$i]);
               if ($row[$i] != $last)
               fwrite($fh);
             }
        fwrite($fh, "\n");
     }
    fclose($fh);

Body:
$fh = fopen('dump.txt', 'w');
$exampleData = array(array(1,2,3),array('a','b','c'),array('x','y','z'));
while ($row = array_shift($exampleData))
{
  fwrite($fh, implode(' ',$row).PHP_EOL);
}
fclose($fh);

will become

1 2 3
a b c
x y z

if that not working for you, then there is some other bug to find.

Maybe use \r\n instead of just \n if you have still problems with line-breaks. PHP_EOL holds \n (linux) or \r\n (win).


问:
Assert specific constructor called by child class
I am trying to write a test to verify that child classes call a specific base class' constructor. Effectively, IDs for my entities are generated when the object is instantiated by the server. I am using NHibernate as my ORM, and so I need a 0-parameter constructor. I would prefer that this constructor not generate a Guid everytime that NHibernate hydrates an entity, so I created a second constructor for my base entity with a Guid as a paramter.

It looks something like this

```<code>public abstract class EntityBase {
    public Guid ID {get; protected set;}

    protected EntityBase() { }

    public EntityBase(Guid id) { ID = id }

    public static Guid NewID => GenerateGuid();
}

public class Entity : EntityBase {
    public int X {get; set;}

    protected Entity() { }

    public Entity(int x) : base(NewID) { X = x; }
}
</code>```

This test I want to write should assert that all constructors (except the 0-parameter constructor) of all concrete child classes of EntityBase call the correct base constructor:

public EntityBase(Guid id) { ID = id }

Currently, my code loops through constructors on all concrete classes assignable from EntityBase, but I don't know how to make the final check. Research into solutions suggested attempting to read IL using reflection. I considered trying to check if 'NewID' had been called, but was unable to find any accomplish that either.

Is there a way to achieve this, or is my solution to the NHibernate problem the real issue?

答:
OK, so this took me a while but I like a challenge.

A caveat before we start: some of the OperandType values are not listed on MSDN in terms of byte size, so I can't be sure that this is parsing everything properly.

You pass in the derived and base constructors, and then it works out if that constructor has been called or not.

```<code>public bool IsCalled(ConstructorInfo derivedConstructor, ConstructorInfo baseConstructor)
{
    var body = derivedConstructor.GetMethodBody();
    var expectedConstructorToken = baseConstructor.MetadataToken;
    byte[] il = body.GetILAsByteArray();

    var codes = new Dictionary<short, OpCode>();
    var fields = typeof(OpCodes).GetFields(System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public);
    foreach (var field in fields)
    {
        var value = field.GetValue(null);
        if (!(value is OpCode)) { continue; }
        var opCode = (OpCode)value;
        codes.Add(opCode.Value, opCode);
    }

    var operandSizes = new Dictionary<OperandType, int>();
    // https://msdn.microsoft.com/en-us/library/system.reflection.emit.operandtype(v=vs.110).aspx
    operandSizes.Add(OperandType.InlineBrTarget, 4);
    operandSizes.Add(OperandType.InlineField, 4);
    operandSizes.Add(OperandType.InlineI, 4);
    operandSizes.Add(OperandType.InlineI8, 8);
    operandSizes.Add(OperandType.InlineMethod, 4);
    operandSizes.Add(OperandType.InlineNone, 0);
    operandSizes.Add(OperandType.InlineR, 8);
    operandSizes.Add(OperandType.InlineSig, 4);
    operandSizes.Add(OperandType.InlineString, 4);
    operandSizes.Add(OperandType.InlineSwitch, 4);
    operandSizes.Add(OperandType.InlineType, 32);
    operandSizes.Add(OperandType.InlineVar, 2);
    operandSizes.Add(OperandType.ShortInlineBrTarget, 1);
    operandSizes.Add(OperandType.ShortInlineI, 1);
    operandSizes.Add(OperandType.ShortInlineR, 4);
    operandSizes.Add(OperandType.ShortInlineVar, 1);

    var i = 0;
    while(i < il.Length) {
        OpCode operation = OpCodes.Nop;
        if (il[i] == 0xfe)
        {
            operation = codes[BitConverter.ToInt16(il, i)];
        }
        else
        {
            operation = codes[(short)il[i]];
        }
        i += operation.Size;

        if (operation.OperandType == OperandType.InlineMethod)
        {
            var token = BitConverter.ToInt32(il, i);
            if (token == expectedConstructorToken) { return true; }
        }

        i += operandSizes[operation.OperandType];
    }
    return false;
}
</code>```

Usage:

```<code>var derivedConstructor = typeof(Derived).GetConstructor(new Type[] { typeof(int) });
var baseConstructor = typeof(Base).GetConstructor(new Type[] { typeof(int) });
bool isCalled = IsCalled(derivedConstructor, baseConstructor);
</code>```

Body:
I am trying to write a test to verify that child classes call a specific base class' constructor. Effectively, IDs for my entities are generated when the object is instantiated by the server. I am using NHibernate as my ORM, and so I need a 0-parameter constructor. I would prefer that this constructor not generate a Guid everytime that NHibernate hydrates an entity, so I created a second constructor for my base entity with a Guid as a paramter.

It looks something like this

public abstract class EntityBase {
    public Guid ID {get; protected set;}

    protected EntityBase() { }

    public EntityBase(Guid id) { ID = id }

    public static Guid NewID => GenerateGuid();
}

public class Entity : EntityBase {
    public int X {get; set;}

    protected Entity() { }

    public Entity(int x) : base(NewID) { X = x; }
}

This test I want to write should assert that all constructors (except the 0-parameter constructor) of all concrete child classes of EntityBase call the correct base constructor:

public EntityBase(Guid id) { ID = id }

Currently, my code loops through constructors on all concrete classes assignable from EntityBase, but I don't know how to make the final check. Research into solutions suggested attempting to read IL using reflection. I considered trying to check if 'NewID' had been called, but was unable to find any accomplish that either.

Is there a way to achieve this, or is my solution to the NHibernate problem the real issue?

Body:
OK, so this took me a while but I like a challenge.

A caveat before we start: some of the OperandType values are not listed on MSDN in terms of byte size, so I can't be sure that this is parsing everything properly.

You pass in the derived and base constructors, and then it works out if that constructor has been called or not.

public bool IsCalled(ConstructorInfo derivedConstructor, ConstructorInfo baseConstructor)
{
    var body = derivedConstructor.GetMethodBody();
    var expectedConstructorToken = baseConstructor.MetadataToken;
    byte[] il = body.GetILAsByteArray();

    var codes = new Dictionary<short, OpCode>();
    var fields = typeof(OpCodes).GetFields(System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public);
    foreach (var field in fields)
    {
        var value = field.GetValue(null);
        if (!(value is OpCode)) { continue; }
        var opCode = (OpCode)value;
        codes.Add(opCode.Value, opCode);
    }

    var operandSizes = new Dictionary<OperandType, int>();
    // https://msdn.microsoft.com/en-us/library/system.reflection.emit.operandtype(v=vs.110).aspx
    operandSizes.Add(OperandType.InlineBrTarget, 4);
    operandSizes.Add(OperandType.InlineField, 4);
    operandSizes.Add(OperandType.InlineI, 4);
    operandSizes.Add(OperandType.InlineI8, 8);
    operandSizes.Add(OperandType.InlineMethod, 4);
    operandSizes.Add(OperandType.InlineNone, 0);
    operandSizes.Add(OperandType.InlineR, 8);
    operandSizes.Add(OperandType.InlineSig, 4);
    operandSizes.Add(OperandType.InlineString, 4);
    operandSizes.Add(OperandType.InlineSwitch, 4);
    operandSizes.Add(OperandType.InlineType, 32);
    operandSizes.Add(OperandType.InlineVar, 2);
    operandSizes.Add(OperandType.ShortInlineBrTarget, 1);
    operandSizes.Add(OperandType.ShortInlineI, 1);
    operandSizes.Add(OperandType.ShortInlineR, 4);
    operandSizes.Add(OperandType.ShortInlineVar, 1);

    var i = 0;
    while(i < il.Length) {
        OpCode operation = OpCodes.Nop;
        if (il[i] == 0xfe)
        {
            operation = codes[BitConverter.ToInt16(il, i)];
        }
        else
        {
            operation = codes[(short)il[i]];
        }
        i += operation.Size;

        if (operation.OperandType == OperandType.InlineMethod)
        {
            var token = BitConverter.ToInt32(il, i);
            if (token == expectedConstructorToken) { return true; }
        }

        i += operandSizes[operation.OperandType];
    }
    return false;
}

Usage:

var derivedConstructor = typeof(Derived).GetConstructor(new Type[] { typeof(int) });
var baseConstructor = typeof(Base).GetConstructor(new Type[] { typeof(int) });
bool isCalled = IsCalled(derivedConstructor, baseConstructor);


问:
Error : "could not find or load main class \lib\jamm-0.3.0.jar"
While running 'cassandra.bat' file on Windows, I am getting the error "could not find or load main class \lib\jamm-0.3.0.jar. Any pointers on how to resolve this? </p>

答: Make sure your directory structure is correct, check for the file jamm-0.3.0.jar under lib directory.</p>


问:
Given a view, how do I get its viewController?
I have a pointer to a UIView.  How do I access its UIViewController?  [self superview] is another UIView, but not the UIViewController, right?

答:
The fast and generic way in Swift 3:</p>

```<code>extension UIResponder {
    func parentController<T: UIViewController>(of type: T.Type) -> T? {
        guard let next = self.next else {
            return nil
        }
        return (next as? T) ?? next.parentController(of: T.self)
    }
}

//Use:
class MyView: UIView {
    ...
    let parentController = self.parentController(of: MyViewController.self)
}
</code>```

Body:
The fast and generic way in Swift 3:

extension UIResponder {
    func parentController<T: UIViewController>(of type: T.Type) -> T? {
        guard let next = self.next else {
            return nil
        }
        return (next as? T) ?? next.parentController(of: T.self)
    }
}

//Use:
class MyView: UIView {
    ...
    let parentController = self.parentController(of: MyViewController.self)
}


问:
Dynamic target in make
I am a newbie with make, and I'm trying to use it to deploy some javascript files. I have been struggling with the following problem for quite a while with no success.

My directory structure is as follows:

```<code>helpers/
    foo/
        foo.js
        test/
            test1.js
            test2.js
            ...
    bar/
        bar.js
        test/
            test1.js
            test2.js
            ...
    other helpers...
distrib/
    files ready for distribution
other stuff...
</code>```

My makefile should build, among other things, the helpers. For each helper foo I want to produce, under distrib, the following files: foo-version.js, foo-version-uncommented.js, foo-version-packed.js and foo-version-tests.zip. The first three are obtained by foo.js, respectively as a copy, by stripping the comments and by running a javascript minifier. I already have commands to perform these tasks.

The version number should be read in the comments of the file itself, which I can easily do with

```<code>def version
    $(shell cat $1 | grep @version | sed -e"s/.*version *//")
endef
</code>```

My problem is that targets like foo-version.js are dynamic, since they depend on the version number, which is read while running make. I have tried to use patterns, but I have failed to make this work. The problem is that something like this will not work

```<code>helpers := foo bar
helpers: $(helpers)
$(helpers): %: $(call version, %)
</code>```

because the second % is not expanded in the macro call, but it is used literally.

I need to be able to do make helpers to build all helpers or make foo to build a single one. A second step would be to delete all files under distrib with a lower version number. Any ideas how to do this?

As a side question: would a task like this be easier with a different build tool? I'm not expert and it may be worth the pain to learn something else.

答:
At the end I decided to write my own build tool PHPmake. It has a syntax reminiscent of standard makefiles, but it is already more powerful than standard make, and it is easily extensible as the makefiles themselves are written in plain PHP.

No more debugging spaces, tabs and dollar signs! :-)

ContentLicense: CC BY-SA 2.5

Title: Dynamic target in make

Body:
I am a newbie with make, and I'm trying to use it to deploy some javascript files. I have been struggling with the following problem for quite a while with no success.

My directory structure is as follows:

helpers/
    foo/
        foo.js
        test/
            test1.js
            test2.js
            ...
    bar/
        bar.js
        test/
            test1.js
            test2.js
            ...
    other helpers...
distrib/
    files ready for distribution
other stuff...

My makefile should build, among other things, the helpers. For each helper foo I want to produce, under distrib, the following files: foo-version.js, foo-version-uncommented.js, foo-version-packed.js and foo-version-tests.zip. The first three are obtained by foo.js, respectively as a copy, by stripping the comments and by running a javascript minifier. I already have commands to perform these tasks.

The version number should be read in the comments of the file itself, which I can easily do with

def version
    $(shell cat $1 | grep @version | sed -e"s/.*version *//")
endef

My problem is that targets like foo-version.js are dynamic, since they depend on the version number, which is read while running make. I have tried to use patterns, but I have failed to make this work. The problem is that something like this will not work

helpers := foo bar
helpers: $(helpers)
$(helpers): %: $(call version, %)

because the second % is not expanded in the macro call, but it is used literally.

I need to be able to do make helpers to build all helpers or make foo to build a single one. A second step would be to delete all files under distrib with a lower version number. Any ideas how to do this?

As a side question: would a task like this be easier with a different build tool? I'm not expert and it may be worth the pain to learn something else.


问:
How to update elegantly the Failure exception of a Try?
I would like to update the Failure exception of a Try to provide a more understandable failure.

I successfully do this by using the following implementation:

```<code>case class NoDataAvailableException() extends Exception

[...]

    Try(...) match {
      case Success(f) => Success(f)
      case Failure(_) => Failure(NoDataAvailableException())
    }
</code>```

But I think this implementation is not really elegant, so my question is:

Is there a way to do this more elegantly ?

答:
You could use recoverWith with accepts a PartialFunction[Throwable, Try[U]]. This would allow you to map specific exceptions to successes or failures, as you wish.

```<code>case class MyException() extends Exception

Try(1 / 0) recoverWith {
    case _: ArithmeticException => Failure(new MyException())
    // other exceptions ...
}
</code>```

You could also use an implicit class to add method of your own to Try that lets you specifically map exceptions.

```<code>implicit class TryExtension[A](t: Try[A]) {
    def mapFailure(pf: PartialFunction[Throwable, Throwable]): Try[A] =
        t.recoverWith(pf.andThen(Failure.apply))
}

scala> Try(1 / 0).mapFailure { case _ => new MyException }
res3: scala.util.Try[Int] = Failure(MyException)
</code>```

Body:
I would like to update the Failure exception of a Try to provide a more understandable failure.

I successfully do this by using the following implementation:

case class NoDataAvailableException() extends Exception

[...]

    Try(...) match {
      case Success(f) => Success(f)
      case Failure(_) => Failure(NoDataAvailableException())
    }

But I think this implementation is not really elegant, so my question is:

Is there a way to do this more elegantly ?

Body:
You could use recoverWith with accepts a PartialFunction[Throwable, Try[U]]. This would allow you to map specific exceptions to successes or failures, as you wish.

case class MyException() extends Exception

Try(1 / 0) recoverWith {
    case _: ArithmeticException => Failure(new MyException())
    // other exceptions ...
}

You could also use an implicit class to add method of your own to Try that lets you specifically map exceptions.

implicit class TryExtension[A](t: Try[A]) {
    def mapFailure(pf: PartialFunction[Throwable, Throwable]): Try[A] =
        t.recoverWith(pf.andThen(Failure.apply))
}

scala> Try(1 / 0).mapFailure { case _ => new MyException }
res3: scala.util.Try[Int] = Failure(MyException)


问:
unable to see output as expected when using forEach logic in js file
My requirement is to display the bar graph.I'm using angularjs and Zingchart to display the bar. Belowis the javascript code which gets invoked to generate the bar. I'm facing issue in iterating the logic(angular.forEach..) in the below mentioned code.

My alert statement inside angular.forEach is displayed 3 times, but on the UI i can only see one bar displayed(i.e.,bar with final data is displayed, first two bars are not getting displayed).
I know i'm missing something which draws each and every bar instead of the last displayed bar. Do i need to use any push statemetns. Please advice.

```<code>app.controller('myController',['$rootScope','$scope','$uibModal','myService',function($rootScope,$scope,$uibModal,myService)  {
    $scope.chart = {};
    $scope.chart.options = {
        "isStacked": "true",
         axisFontSize : 10,
        chartArea: {left:0, width: 400,}
    };
    $scope.chart.type = "bar";
    $scope.chart.cssStyle = "height:300px; width:650px;";

    $scope.loadChartData = function(){
        alert("Chart data loading");
        MyService.getChartData($rootScope.myID).then(
            function(response) {
                $scope.myJson=response;
                  angular.forEach($scope.myJson,function(value,key){
                      alert("in foreach"); //displaying 3 times
                      sub =  value.myResults.sub;
                      spread = value.myResults.spread;
                      active  =value.myResults.active;
                    $scope.data = {};
                    $scope.data.valuesOne = [sub];
                    $scope.data.valuesTwo = [spread];
                    $scope.data.valuesThree = [active];
                    $scope.aValues = [$scope.data.valuesOne,$scope.data.valuesTwo,$scope.data.valuesThree];
                    $scope.myJson = {
                        type : "bar",
                        "background-color": "white",
                        "plot": {
                            "stacked": true,
                            "stack-type":"normal"
                        },
                        title:{
                            backgroundColor : "transparent",
                            fontColor :"black",
                            text : "Hello world"
                        },
                        backgroundColor : "white",
                        series : [
                            {
                                backgroundColor : '#00baf2'
                            },
                            {
                                backgroundColor : '#4caf4f'
                            }
                        ]
                    };
             });
            },
            function(errResponse){
                console.error('Error while data retrieval');
            });
    }

}]);
</code>```

html code:

```<code>  <div ng-controller="myController">
            <div zingchart id="chart-2" zc-json="myJson" zc-width="700px" zc-height="568px" zc-values="aValues"></div>
  </div>
</code>```

With the above mentioned js code i should see 3 bars on the UI, i could able to view only one bar.Please suggest.

答:
You need to call foreach on the data, rather than the whole chart. Like this:</p>

```<code>...
function(response) {

    $scope.myJson = {
        type: "bar",
        "background-color": "white",
        "plot": {
            "stacked": true,
            "stack-type": "normal"
        },
        title: {
            backgroundColor: "transparent",
            fontColor: "black",
            text: "Hello world"
        },
        backgroundColor: "white",
        series: [
            {
                backgroundColor: '#00baf2'
            },
            {
                backgroundColor: '#4caf4f'
            }
        ]
    };

    var subs = []
    var spreads = []
    var actives = []

    $scope.aValues = [subs, spreads, actives]

    angular.forEach(response, function (value, key) {
        subs.push(value.myResults.sub)
        spreads.push(value.myResults.spreads)
        actives.push(value.myResults.active)
    });
},
function(errResponse) {
    console.error('Error while data retrieval');
});
...
</code>```

Body:
My requirement is to display the bar graph.I'm using angularjs and Zingchart to display the bar. Belowis the javascript code which gets invoked to generate the bar. I'm facing issue in iterating the logic(angular.forEach..) in the below mentioned code.

My alert statement inside angular.forEach is displayed 3 times, but on the UI i can only see one bar displayed(i.e.,bar with final data is displayed, first two bars are not getting displayed).
I know i'm missing something which draws each and every bar instead of the last displayed bar. Do i need to use any push statemetns. Please advice.

app.controller('myController',['$rootScope','$scope','$uibModal','myService',function($rootScope,$scope,$uibModal,myService)  {
    $scope.chart = {};
    $scope.chart.options = {
        "isStacked": "true",
         axisFontSize : 10,
        chartArea: {left:0, width: 400,}
    };
    $scope.chart.type = "bar";
    $scope.chart.cssStyle = "height:300px; width:650px;";

    $scope.loadChartData = function(){
        alert("Chart data loading");
        MyService.getChartData($rootScope.myID).then(
            function(response) {
                $scope.myJson=response;
                  angular.forEach($scope.myJson,function(value,key){
                      alert("in foreach"); //displaying 3 times
                      sub =  value.myResults.sub;
                      spread = value.myResults.spread;
                      active  =value.myResults.active;
                    $scope.data = {};
                    $scope.data.valuesOne = [sub];
                    $scope.data.valuesTwo = [spread];
                    $scope.data.valuesThree = [active];
                    $scope.aValues = [$scope.data.valuesOne,$scope.data.valuesTwo,$scope.data.valuesThree];
                    $scope.myJson = {
                        type : "bar",
                        "background-color": "white",
                        "plot": {
                            "stacked": true,
                            "stack-type":"normal"
                        },
                        title:{
                            backgroundColor : "transparent",
                            fontColor :"black",
                            text : "Hello world"
                        },
                        backgroundColor : "white",
                        series : [
                            {
                                backgroundColor : '#00baf2'
                            },
                            {
                                backgroundColor : '#4caf4f'
                            }
                        ]
                    };
             });
            },
            function(errResponse){
                console.error('Error while data retrieval');
            });
    }

}]);

html code:

With the above mentioned js code i should see 3 bars on the UI, i could able to view only one bar.Please suggest.

Body:
You need to call foreach on the data, rather than the whole chart. Like this:

...
function(response) {

    $scope.myJson = {
        type: "bar",
        "background-color": "white",
        "plot": {
            "stacked": true,
            "stack-type": "normal"
        },
        title: {
            backgroundColor: "transparent",
            fontColor: "black",
            text: "Hello world"
        },
        backgroundColor: "white",
        series: [
            {
                backgroundColor: '#00baf2'
            },
            {
                backgroundColor: '#4caf4f'
            }
        ]
    };

    var subs = []
    var spreads = []
    var actives = []

    $scope.aValues = [subs, spreads, actives]

    angular.forEach(response, function (value, key) {
        subs.push(value.myResults.sub)
        spreads.push(value.myResults.spreads)
        actives.push(value.myResults.active)
    });
},
function(errResponse) {
    console.error('Error while data retrieval');
});
...


问:
Docker: how to update changes in php.ini inside of container
I have a docker container which has php5.6 inside. When I test some things I get this error : strtotime(): It is not safe to rely on the system's timezone settings. You are *required* to use the date.timezone setting or the date_default_timezone_set() function. In case you used any of those methods and you are still getting this warning, you most likely misspelled the timezone identifier. We selected the timezone 'UTC' for now, but please set date.timezone to select your timezone. This can be changed with appending date.timezone = America/New_York to my php.ini file. That's exactly what I am doing. But it is not working, it seems, that I should restart some service to really "update" my php.ini file. So, what should I do to update my php.ini file changes ?

答:
So, what should I do to update my php.ini file changes ?

change your source php.ini file and re-build your image

if you change the file in teh container itself, the moment you stop the container and restart it, the change will be gone.

so, you need to update your php.ini file from your source and then rebuild the image to include this change


问:
Stack depth Limit INSERT trigger
I have this table on PostgreSQL and I'd like to make a trigger that every time I edit one row of the table publications the last_edit_date is updated to now():

```<code>CREATE FUNCTION trigger_update_question_timestamp()
  RETURNS "trigger" AS $func$
BEGIN
    UPDATE publications SET last_edit_date = now() WHERE publicationid = NEW.publicationid;
    RETURN NULL;
END;
$func$  LANGUAGE plpgsql;

CREATE TRIGGER answer_update_question_timestamp AFTER INSERT OR UPDATE ON publications
   FOR EACH ROW EXECUTE PROCEDURE trigger_update_question_timestamp();

CREATE TABLE publications
(
    publicationid SERIAL PRIMARY KEY,
    body VARCHAR(1000) NOT NULL ,
    creation_date TIMESTAMP DEFAULT now() NOT NULL,
    userid INTEGER NOT NULL,
    last_edit_date TIMESTAMP,
    CONSTRAINT body_length CHECK (CHAR_LENGTH(body) >= 10 AND CHAR_LENGTH(body) <= 1000),
    CONSTRAINT "FK_publications_users"
        FOREIGN KEY ("userid") REFERENCES users ("userid") ON DELETE SET NULL ON UPDATE CASCADE
);
</code>```

I'm using PhpStorm and when I manually edit a line I get the following error:

```<code>[54001] ERROR: stack depth limit exceeded Hint: Increase the configuration parameter "max_stack_depth" (currently 2048kB), after ensuring the platform's stack depth limit is adequate. Where: SQL statement "SELECT 1 FROM ONLY "public"."users" x WHERE "userid" OPERATOR(pg_catalog.=) $1 FOR KEY SHARE OF x" SQL statement "UPDATE publications SET last_edit_date = now() WHERE publicationid = NEW.publicationid" PL/pgSQL function trigger_update_question_timestamp()
</code>```

What does this exactly means? Does it have to do with my trigger or any other definition?

答:
Your trigger is recursive, that is, the trigger function executes an UPDATE that calls the trigger function again.

The solution here is to use a BEFORE INSERT OR UPDATE trigger, that modifies NEW as follows:

```<code>BEGIN
   NEW.last_edit_date := current_timestamp;
   RETURN NEW;
END;
</code>```

Title: Stack depth Limit INSERT trigger

Body:
I have this table on PostgreSQL and I'd like to make a trigger that every time I edit one row of the table publications the last_edit_date is updated to now():

CREATE FUNCTION trigger_update_question_timestamp()
  RETURNS "trigger" AS $func$
BEGIN
    UPDATE publications SET last_edit_date = now() WHERE publicationid = NEW.publicationid;
    RETURN NULL;
END;
$func$  LANGUAGE plpgsql;

CREATE TRIGGER answer_update_question_timestamp AFTER INSERT OR UPDATE ON publications
   FOR EACH ROW EXECUTE PROCEDURE trigger_update_question_timestamp();

CREATE TABLE publications
(
    publicationid SERIAL PRIMARY KEY,
    body VARCHAR(1000) NOT NULL ,
    creation_date TIMESTAMP DEFAULT now() NOT NULL,
    userid INTEGER NOT NULL,
    last_edit_date TIMESTAMP,
    CONSTRAINT body_length CHECK (CHAR_LENGTH(body) >= 10 AND CHAR_LENGTH(body) <= 1000),
    CONSTRAINT "FK_publications_users"
        FOREIGN KEY ("userid") REFERENCES users ("userid") ON DELETE SET NULL ON UPDATE CASCADE
);

I'm using PhpStorm and when I manually edit a line I get the following error:

[54001] ERROR: stack depth limit exceeded Hint: Increase the configuration parameter "max_stack_depth" (currently 2048kB), after ensuring the platform's stack depth limit is adequate. Where: SQL statement "SELECT 1 FROM ONLY "public"."users" x WHERE "userid" OPERATOR(pg_catalog.=) $1 FOR KEY SHARE OF x" SQL statement "UPDATE publications SET last_edit_date = now() WHERE publicationid = NEW.publicationid" PL/pgSQL function trigger_update_question_timestamp()

What does this exactly means? Does it have to do with my trigger or any other definition?

Body:
Your trigger is recursive, that is, the trigger function executes an UPDATE that calls the trigger function again.

The solution here is to use a BEFORE INSERT OR UPDATE trigger, that modifies NEW as follows:

BEGIN
   NEW.last_edit_date := current_timestamp;
   RETURN NEW;
END;


问:
Recursive Fibonacci Function
I have an assignment where I have create a Fibonacci suite using recursion. The code below works in some cases, but not all.

```<code>org 100h
 jmp debut
val dw 0008h
debut:
  push word ptr 0000h
  push word ptr 0001h
  call fibo
  Add  sp,04
  hlt
fibo proc near
  Sub  sp,04
  mov  dx,[sp+6]
  mov  [sp+02],dx
  add  dx,[sp+8]
  mov  [sp],dx
  cmp  dx,val
  jae  Fin
  Call Fibo
Fin:
  ret 04
endp fibo
</code>```

but the problem is when I try to put in VAL a number like 0 or 1 or negative number like -0003h, Will not stop.

Any help would be appreciated thanks.

答:
thanks @rcgldr for you reply, I tried to create a new code and more simple , but I need to change this instructions

```<code>xchg dx,[bp+4]
    xchg dx,[bp+6]
</code>```

with another instructions like mov for example,there is the new program

```<code>    ORG 100H

jmp debut

val dw 0005h
F dw ?

debut: mov al,1
mov cx,val
cmp cx,0000h
je stopp
cmp cx,0001h
je stopp
push cx
push 0000h
push 0001h
call fibo
saut: add sp,4
pop F
stopp:
hlt

fibo proc
push bp
mov bp,sp
push dx
mov cx,[bp+8]
mov dx,[bp+4]
add dx,[bp+6]
inc al
cmp cl,al
je fin
xchg dx,[bp+4]
xchg dx,[bp+6]
add sp,6
call fibo
jmp saut

fin: mov [bp+8],dl
pop dx
pop bp
ret
endp fibo
</code>```

Title: Recursive Fibonacci Function

Body:
I have an assignment where I have create a Fibonacci suite using recursion. The code below works in some cases, but not all.

org 100h
 jmp debut
val dw 0008h
debut:
  push word ptr 0000h
  push word ptr 0001h
  call fibo
  Add  sp,04
  hlt
fibo proc near
  Sub  sp,04
  mov  dx,[sp+6]
  mov  [sp+02],dx
  add  dx,[sp+8]
  mov  [sp],dx
  cmp  dx,val
  jae  Fin
  Call Fibo
Fin:
  ret 04
endp fibo

but the problem is when I try to put in VAL a number like 0 or 1 or negative number like -0003h, Will not stop.

Any help would be appreciated thanks.

Body:
thanks @rcgldr for you reply, I tried to create a new code and more simple , but I need to change this instructions

xchg dx,[bp+4]
    xchg dx,[bp+6]

with another instructions like mov for example,there is the new program

    ORG 100H

jmp debut

val dw 0005h
F dw ?

debut: mov al,1
mov cx,val
cmp cx,0000h
je stopp
cmp cx,0001h
je stopp
push cx
push 0000h
push 0001h
call fibo
saut: add sp,4
pop F
stopp:
hlt

fibo proc
push bp
mov bp,sp
push dx
mov cx,[bp+8]
mov dx,[bp+4]
add dx,[bp+6]
inc al
cmp cl,al
je fin
xchg dx,[bp+4]
xchg dx,[bp+6]
add sp,6
call fibo
jmp saut

fin: mov [bp+8],dl
pop dx
pop bp
ret
endp fibo


问:
Insert javascript at top of including file in Jinja 2
In Jinja2, I would like the following to work as it looks like it should, by running:

```<code>from jinja2 import Environment, FileSystemLoader
env = Environment(loader=FileSystemLoader('.'))
template = env.get_template('x.html')
print template.render()
</code>```

Essentially the objective is to coalesce all the javascript into the  tags by using a a {% call js() %} /* some js */ {% endcall %} macro.

x.html

```<code><html>
<head>
  <script type="text/javascript>
  {% block head_js %}{% endblock %}
  </script>
  </head>
<body>
  {% include "y.html" %}
</body>
</html>
</code>```

 y.html

```<code>{% macro js() -%}
    // extend head_js
    {%- block head_js -%}
    {{ super() }}
    try { {{ caller() }} } catch (e) {
       my.log.error(e.name + ": " + e.message);
    }
    {%- endblock -%}
{%- endmacro %}

Some ... <div id="abc">text</div> ...

{% call js() %}
    // jquery parlance:
    $(function () {
        $("#abc").css("color", "red");
    });
{% endcall %}
</code>```

Expected result

When I run X.html through jinja2, I would expect the result to be:

```<code><html>
<head>
  <script type="text/javascript>
  try { {{ $("#abc").css("color", "red"); }} } catch (e) {
       usf.log.error(e.name + ": " + e.message);
    }
  </script>
  </head>
<body>
      Some ... <div id="abc">text</div> ...
</body>
</html>
</code>```

Actual result

The actual results are not encouraging. I get a couple types of potentially illuminating errors, e.g.:

TypeError: macro 'js' takes no keyword argument 'caller'

or, when I try adding another basis macro such as

```<code>{% macro js2() -%}
{%- block head_js -%}
//     ... something
{%- endblock -%}
{%- endmacro %}
</code>```

I get the following exception

jinja2.exceptions.TemplateAssertionError: block 'head_js' defined twice

I feel as though I am running into a design issue regarding the precedence of the block tags over the macro tags (i.e. macros do not seem to encapsulate block tags in the way I expect).

I suppose my questions are quite simple:

Can Jinja2 do what I am attempting? If so, how?

If not, is there another Python based templating engine that does support this sort of pattern (e.g. mako, genshi, etc.), which would work without issue in Google App Engine

Thank you for reading - I appreciate your input.

Brian

 Edit:

I'm trying to write an extension to resolve this problem. I'm halfway there -- using the following code:

```<code>from jinja2 import nodes, Environment, FileSystemLoader
from jinja2.ext import Extension

class JavascriptBuilderExtension(Extension):
    tags = set(['js', 'js_content'])

    def __init__(self, environment):
        super(JavascriptBuilderExtension, self).__init__(environment)
        environment.extend(
            javascript_builder_content = [],
        )

    def parse(self, parser):
        """Parse tokens """
        tag = parser.stream.next()
        return getattr(self, "_%s" % str(tag))(parser, tag)

    def _js_content(self, parser, tag):
        """ Return the output """
        content_list = self.environment.javascript_builder_content
        node = nodes.Output(lineno=tag.lineno)
        node.nodes = []

        for o in content_list:
            print "\nAppending node: %s" % str(o)
            node.nodes.extend(o[0].nodes)
        print "Returning node: %s \n" % node
        return node

    def _js(self, parser, tag):
        body = parser.parse_statements(['name:endjs'], drop_needle=True)
        print "Adding: %s" % str(body)
        self.environment.javascript_builder_content.append(body)
        return nodes.Const('<!-- Slurped Javascript -->')

env = Environment(
    loader      = FileSystemLoader('.'),
    extensions  = [JavascriptBuilderExtension],
    )
</code>```

This makes it simple to add Javascript to the end of a template ... e.g.

```<code><html>
<head></head>
<body>
    {% js %}
    some javascript {{ 3 + 5 }}
    {% endjs %}
    {% js %}
    more {{ 2 }}
    {% endjs %}

<script type="text/javascript">
{% js_content %}
</script>
</body>
</html>
</code>```

Running env.get_template('x.html').render() will result in some illuminating comments and the expected output of:

```<code><html>
<head>
  <script type="text/javascript>
  </script>
  </head>
<body>
    <!-- Slurped Javascript -->
    <!-- Slurped Javascript -->
<script type="text/javascript">
    some javascript 8
    more 2
</script>
</body>
</html>
</code>```

Of course, this isn't the same as having the script in the head, as hoped, but at least it's conveniently coalesced into one place.

However, the solution is not complete because when you have a {% include "y.html" %} in there, where "y.html" includes a {% js %} statement, the {% js_content %} gets called before the include's {% js %} statement (i.e. x.html is fully parsed before y.html starts).

I also need to, but have not yet, inserted constant nodes that would have the static javascript try/catch, which I indicated I wanted to have in there. This is not an issue.

I'm pleased to be making progress, and I'm grateful for input.

I have opened the related question: Jinja2 compile extension after includes

答:
From my comment:

If you would use extend instead of
  include you could do it. But because
  of the full separation between the
  parse and render step you won't be
  able to change the context of the
  parent scope till after it's too late.
  Also, the Jinja context is supposed to
  be immutable.

Example:

base.html

```<code><html>
   <head>
      {% block head %}

      <title>{% block title %}This is the main template{% endblock %}</title>

      <script type="text/javascript">
      {% block head_js %}
      $(function () {
        $("#abc").css("color", "red");
      });
      {% endblock %}
      </script>

      {% endblock head_js %}
   </head>
   <body>
      {% block body %}
      <h1>{% block body_title %}This is the main template{% endblock body_title %}</h1>

      {% endblock body %}
   </body>
 </html>
</code>```

some_page.html

```<code>{% block title %}This is some page{% endblock title %}

{% block head_js %}
{{ super() }}
try { {{ caller() }} } catch (e) {
   my.log.error(e.name + ": " + e.message);
}        // jquery parlance:
{% endblock head_js %}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
In Jinja2, I would like the following to work as it looks like it should, by running:

from jinja2 import Environment, FileSystemLoader
env = Environment(loader=FileSystemLoader('.'))
template = env.get_template('x.html')
print template.render()

Essentially the objective is to coalesce all the javascript into the  tags by using a a {% call js() %} /* some js */ {% endcall %} macro.

x.html

  {% include "y.html" %}

 y.html

{% macro js() -%}
    // extend head_js
    {%- block head_js -%}
    {{ super() }}
    try { {{ caller() }} } catch (e) {
       my.log.error(e.name + ": " + e.message);
    }
    {%- endblock -%}
{%- endmacro %}

Some ...
text
 ...

{% call js() %}
    // jquery parlance:
    $(function () {
        $("#abc").css("color", "red");
    });
{% endcall %}

Expected result

When I run X.html through jinja2, I would expect the result to be:

      Some ...
text
 ...

Actual result

The actual results are not encouraging. I get a couple types of potentially illuminating errors, e.g.:

TypeError: macro 'js' takes no keyword argument 'caller'

or, when I try adding another basis macro such as

{% macro js2() -%}
{%- block head_js -%}
//     ... something
{%- endblock -%}
{%- endmacro %}

I get the following exception

jinja2.exceptions.TemplateAssertionError: block 'head_js' defined twice

I feel as though I am running into a design issue regarding the precedence of the block tags over the macro tags (i.e. macros do not seem to encapsulate block tags in the way I expect).

I suppose my questions are quite simple:

Can Jinja2 do what I am attempting? If so, how?

If not, is there another Python based templating engine that does support this sort of pattern (e.g. mako, genshi, etc.), which would work without issue in Google App Engine

Thank you for reading - I appreciate your input.

Brian

 Edit:

I'm trying to write an extension to resolve this problem. I'm halfway there -- using the following code:

from jinja2 import nodes, Environment, FileSystemLoader
from jinja2.ext import Extension

class JavascriptBuilderExtension(Extension):
    tags = set(['js', 'js_content'])

    def __init__(self, environment):
        super(JavascriptBuilderExtension, self).__init__(environment)
        environment.extend(
            javascript_builder_content = [],
        )

    def parse(self, parser):
        """Parse tokens """
        tag = parser.stream.next()
        return getattr(self, "_%s" % str(tag))(parser, tag)

    def _js_content(self, parser, tag):
        """ Return the output """
        content_list = self.environment.javascript_builder_content
        node = nodes.Output(lineno=tag.lineno)
        node.nodes = []

        for o in content_list:
            print "\nAppending node: %s" % str(o)
            node.nodes.extend(o[0].nodes)
        print "Returning node: %s \n" % node
        return node

    def _js(self, parser, tag):
        body = parser.parse_statements(['name:endjs'], drop_needle=True)
        print "Adding: %s" % str(body)
        self.environment.javascript_builder_content.append(body)
        return nodes.Const('')

env = Environment(
    loader      = FileSystemLoader('.'),
    extensions  = [JavascriptBuilderExtension],
    )

This makes it simple to add Javascript to the end of a template ... e.g.

    {% js %}
    some javascript {{ 3 + 5 }}
    {% endjs %}
    {% js %}
    more {{ 2 }}
    {% endjs %}

Running env.get_template('x.html').render() will result in some illuminating comments and the expected output of:

Of course, this isn't the same as having the script in the head, as hoped, but at least it's conveniently coalesced into one place.

However, the solution is not complete because when you have a {% include "y.html" %} in there, where "y.html" includes a {% js %} statement, the {% js_content %} gets called before the include's {% js %} statement (i.e. x.html is fully parsed before y.html starts).

I also need to, but have not yet, inserted constant nodes that would have the static javascript try/catch, which I indicated I wanted to have in there. This is not an issue.

I'm pleased to be making progress, and I'm grateful for input.

I have opened the related question: Jinja2 compile extension after includes

Body:
From my comment:

If you would use extend instead of
  include you could do it. But because
  of the full separation between the
  parse and render step you won't be
  able to change the context of the
  parent scope till after it's too late.
  Also, the Jinja context is supposed to
  be immutable.

Example:

base.html

<html>
   <head>
      {% block head %}

      <title>{% block title %}This is the main template{% endblock %}</title>

      <script type="text/javascript">
      {% block head_js %}
      $(function () {
        $("#abc").css("color", "red");
      });
      {% endblock %}
      </script>

      {% endblock head_js %}
   </head>
   <body>
      {% block body %}
      <h1>{% block body_title %}This is the main template{% endblock body_title %}</h1>

      {% endblock body %}
   </body>
 </html>

some_page.html

{% block title %}This is some page{% endblock title %}

{% block head_js %}
{{ super() }}
try { {{ caller() }} } catch (e) {
   my.log.error(e.name + ": " + e.message);
}        // jquery parlance:
{% endblock head_js %}


问:
I need to find EST current offset value using javascript
I need to find current EST offset value using javascript without any server side code

Because I am hardcoding Offset value in my javascript file,i need to pass dynamically because of Day Light Saving.

Kindly Help me on that
Thanks in advance..,

答:
Using moment-timezone:

```<code>var currentUSEasternTime = moment.tz('America/New_York');
var minutesOffset = currentUSEasternTime.utcOffset();    // -240
var hoursOffset = minutesOffset / 60;                    // -4
var offsetString1 = currentUSEasternTime.format('Z');    // "-04:00"
var offsetString2 = currentUSEasternTime.format('ZZ');   // "-0400"
</code>```

Not sure what output you were looking for, so gave you a few options.

Body:
Using moment-timezone:

var currentUSEasternTime = moment.tz('America/New_York');
var minutesOffset = currentUSEasternTime.utcOffset();    // -240
var hoursOffset = minutesOffset / 60;                    // -4
var offsetString1 = currentUSEasternTime.format('Z');    // "-04:00"
var offsetString2 = currentUSEasternTime.format('ZZ');   // "-0400"

Not sure what output you were looking for, so gave you a few options.


问:
Image hover displaying all images at the same time
I'm working with Jquery and attempting to create a hover effect. The end result is simply hovering over a
 elements and a single feature image should appear for the respective element content group. However multiple images appear at once where it should only be one image. Heres working pen

HTML

```<code><p>Hover over titles</p>

<div class="content1">
  <h2>Title 1 goes here </h2>
  <img src="http://lorempixel.com/400/400/sports" alt="Image"/>
</div>

<div class="content2">
  <h2>Title 2 goes here </h2>
  <img src="http://lorempixel.com/300/300/people" alt="Image"/>
</div>

<div class="content2">
  <h2>Title 3 goes here </h2>
  <img src="http://lorempixel.com/200/300/technology" alt="Image"/>
</div>
</code>```

CSS

```<code>img {
  position: absolute;
  display: none;
}
</code>```

Jquery

```<code>$(document).ready(function(){
    $('h2').on('mouseenter mousemove', function(evt){
        $('h2,img').css({left: evt.pageX+30, top: evt.pageY-15}).show();
        $(this).on('mouseleave', function(){
            $('img').hide();
        });
    });
});
</code>```

Why are all the images showing at once? and how can I resolve it to only show the one image in context?

Thanks!

答:
Because you're telling it to show all images at once on the h2 event. Try this code:

```<code>$(document).ready(function(){
    $('h2').on('mouseenter mousemove', function(evt){
        $(this).siblings('img').css({left: evt.pageX+30, top: evt.pageY-15}).show();
        $(this).on('mouseleave', function(){
            $(this).siblings('img').hide();
        });
    });
});
</code>```

You can see it working here: https://jsfiddle.net/zaj200mL/

Body:
I'm working with Jquery and attempting to create a hover effect. The end result is simply hovering over a
 elements and a single feature image should appear for the respective element content group. However multiple images appear at once where it should only be one image. Heres working pen

HTML

Hover over titles

Title 1 goes here

Title 2 goes here

Title 3 goes here

CSS

img {
  position: absolute;
  display: none;
}

Jquery

$(document).ready(function(){
    $('h2').on('mouseenter mousemove', function(evt){
        $('h2,img').css({left: evt.pageX+30, top: evt.pageY-15}).show();
        $(this).on('mouseleave', function(){
            $('img').hide();
        });
    });
});

Why are all the images showing at once? and how can I resolve it to only show the one image in context?

Thanks!

Body:
Because you're telling it to show all images at once on the h2 event. Try this code:

$(document).ready(function(){
    $('h2').on('mouseenter mousemove', function(evt){
        $(this).siblings('img').css({left: evt.pageX+30, top: evt.pageY-15}).show();
        $(this).on('mouseleave', function(){
            $(this).siblings('img').hide();
        });
    });
});

You can see it working here: https://jsfiddle.net/zaj200mL/


问:
Rails routes: Can object ids be separated by non-backslash strings?
I'd like to do the following:

```<code>/products/compare/:product_a_id--vs--:product_b_id
</code>```

Is this possible?

答:
So, a little hacky, but here's my solution:

```<code>resources "products" do
  constraints( compare: /compare/ ) do
    constraints( lambda { |request| Product.find_by(slug: request.params["product_a"]) } ) do
      constraints( compare: /--vs--/ ) do
        constraints( lambda { |request| Product.find_by(slug: request.params["product_b"]) } ) do
          collection do
            get 'compare/:product_a--vs--:product_b', to: 'products#compare', as: 'compare'
          end
        end
      end
    end
  end
end
</code>```

Rake routes:

```<code>rake routes | grep compare

compare_products GET

/products/compare/:product_a--vs--:product_b(.:format)       products#compare
</code>```

Body:
I'd like to do the following:

/products/compare/:product_a_id--vs--:product_b_id

Is this possible?

Body:
So, a little hacky, but here's my solution:

resources "products" do
  constraints( compare: /compare/ ) do
    constraints( lambda { |request| Product.find_by(slug: request.params["product_a"]) } ) do
      constraints( compare: /--vs--/ ) do
        constraints( lambda { |request| Product.find_by(slug: request.params["product_b"]) } ) do
          collection do
            get 'compare/:product_a--vs--:product_b', to: 'products#compare', as: 'compare'
          end
        end
      end
    end
  end
end

Rake routes:

rake routes | grep compare

compare_products GET

/products/compare/:product_a--vs--:product_b(.:format)       products#compare


问:
UITableView Subclass method not calling
I've created a class called "ParseMessages" which is a subclass of UITableView. In the StoryBoard, I've added a UITableView and changed the class to "ParseMessages".

In the ViewDidLoad method of the ViewController containing the UITableView, I'm trying to call one of the "ParseMessages" class methods - there isn't a crash, but the function never executed.

ParseMessages Class (.m)

```<code>- (void)setupMessageTableViewWithThread:(Thread *)thread {
    NSLog(@"function working!");
}
</code>```

ViewController containing UITableView (ParseMessages)

```<code>@property (strong, nonatomic) IBOutlet ParseMessages *table_view;

- (void)viewDidLoad {

    Thread *tempthread = [[Thread alloc] init];
    tempthread.threadid = @"82";
    [self.table_view setupMessageTableViewWithThread:tempthread];

}
</code>```

Suggestions anyone?

答: As suggested by @vitormm - the "ParseMessages" outlet wasn't connected to the StoryBoard object. I simply connected them together and the code ran perfectly!</p>

Title: UITableView Subclass method not calling

Body:
I've created a class called "ParseMessages" which is a subclass of UITableView. In the StoryBoard, I've added a UITableView and changed the class to "ParseMessages".

In the ViewDidLoad method of the ViewController containing the UITableView, I'm trying to call one of the "ParseMessages" class methods - there isn't a crash, but the function never executed.

ParseMessages Class (.m)

- (void)setupMessageTableViewWithThread:(Thread *)thread {
    NSLog(@"function working!");
}

ViewController containing UITableView (ParseMessages)

@property (strong, nonatomic) IBOutlet ParseMessages *table_view;

- (void)viewDidLoad {

    Thread *tempthread = [[Thread alloc] init];
    tempthread.threadid = @"82";
    [self.table_view setupMessageTableViewWithThread:tempthread];

}

Suggestions anyone?


问:
Which way is the best to run a thread in java?

Possible Duplicate:

  Java: “implements Runnable” vs. “extends Thread”

Should I use Runnable interface or extends from Thread class? Is there any advantage on one and another?

Thanks in advance.

答:
As far as I know it's just a matter of preference.

My own preference is to pass a Runnable, because I don't like the subclassing approach nor the fact that Thread implements Runnable.  (Subclassing Thread to implement run() abuses the "is-a" relationship that subclassing is supposed to represent.  Making Thread implement Runnable doesn't really add any value, and it allows for nonsensical things like using one thread as the runnable construction parameter of another thread.)


问:
How can I set a layout to a tab in QTabWidget?
I have created a QTabWidget (with no tabs) using the Qt Design tool, and now I need to create tabs and add widgets dynamically.

I can create the tab and add the widget using the following code:

```<code>MyCustomWidget *myCustomWidget = new MyCustomWidget(this);
ui->myTabWidget->addTab(myCustomWidget, "New Tab");
</code>```

The problem is that the widget stays in the top left corner of my QTabWidget but I need to align it in the center (horizontally) of my QTabWidget.

How can I set a horizontal layout to this new tab created?

Note 1: My widget (MyCustomWidget) has a fixed size.

Note 2: I'm using Qt 5.3.

答:
Following @Satus idea, I create a new QFrame, set the minimum size as the size of myTabWidget, set a horizontal layout and add myCustomWidget inside it, adding two QSpacerItem (left and right):

```<code>QFrame *frame= new QFrame(this);
frame->setMinimumWidth(ui->myTabWidget->width());
frame->setMinimumHeight(ui->myTabWidget->height());

MyCustomWidget *myCustomWidget = new MyCustomWidget(frame);

QHBoxLayout *hLayout = new QHBoxLayout();

hLayout->addItem(new QSpacerItem(10, 10, QSizePolicy::Expanding, QSizePolicy::Expanding));
hLayout->addWidget(myCustomWidget);
hLayout->addItem(new QSpacerItem(10, 10, QSizePolicy::Expanding, QSizePolicy::Expanding));

frame->setLayout(hLayout);

ui->myTabWidget->addTab(frame, "New Tab");
</code>```

It worked, but if someone has a more elegant way to do so, please share with us.

Body:
I have created a QTabWidget (with no tabs) using the Qt Design tool, and now I need to create tabs and add widgets dynamically.

I can create the tab and add the widget using the following code:

MyCustomWidget *myCustomWidget = new MyCustomWidget(this);
ui->myTabWidget->addTab(myCustomWidget, "New Tab");

The problem is that the widget stays in the top left corner of my QTabWidget but I need to align it in the center (horizontally) of my QTabWidget.

How can I set a horizontal layout to this new tab created?

Note 1: My widget (MyCustomWidget) has a fixed size.

Note 2: I'm using Qt 5.3.

Body:
Following @Satus idea, I create a new QFrame, set the minimum size as the size of myTabWidget, set a horizontal layout and add myCustomWidget inside it, adding two QSpacerItem (left and right):

QFrame *frame= new QFrame(this);
frame->setMinimumWidth(ui->myTabWidget->width());
frame->setMinimumHeight(ui->myTabWidget->height());

MyCustomWidget *myCustomWidget = new MyCustomWidget(frame);

QHBoxLayout *hLayout = new QHBoxLayout();

hLayout->addItem(new QSpacerItem(10, 10, QSizePolicy::Expanding, QSizePolicy::Expanding));
hLayout->addWidget(myCustomWidget);
hLayout->addItem(new QSpacerItem(10, 10, QSizePolicy::Expanding, QSizePolicy::Expanding));

frame->setLayout(hLayout);

ui->myTabWidget->addTab(frame, "New Tab");

It worked, but if someone has a more elegant way to do so, please share with us.


问:
Angular: Observable model property does not exist
After upgrading from Angular 2 to Angular 4 I get these errors when trying to compile using AOT:

```<code>Property 'total' does not exist on type 'Observable<any>'.
</code>```

This is how I have used observables until now...

First I have assigned a variable like this:

```<code>public myData: Observable<any>;
</code>```

Then I have a call to my service which I subscribe to like this:

```<code>this.mySubscription = this.apiService.get('URL-HERE')
                        .subscribe(
                            response => this.myData = response,
                            error => this.feedbackService.displayError(<any>error),
                            () => this.feedbackService.stopLoading()
                        );
</code>```

This works in development mode (ng serve), and I can use stuff like *ngFor to iterate over the results.

After getting these errors I tried to add a model class like this:

```<code>export class MyData {
    total: number;
    count: number;
    data: Array<any> = [];
}
... rest of component here
</code>```

And then use it with my observable like this:

```<code>public myData: Observable<MyData>;
</code>```

But I still get errors when trying to compile:

```<code>Property 'total' does not exist on type 'Observable<MyData>'.
</code>```

What am I doing wrong?

Update:

This is what the service method looka like:

```<code>return this.http
        .get(apiUrl + apiPath, {headers: headersWithToken})
        .timeoutWith(appSettings.maxTimeHttpCalls, Observable.defer(() => Observable.throw(this.feedbackService.timeout())))
        .map((response: Response) => {
            return response.json();
        })
        .catch((err: Response) => {
            return err.json();
        });
</code>```

All values (including total) exists on the returned JSON and I can use it in my HTML without a problem.

答:
What you're seeing in terms of changed compiler behaviour, might have less to do with aot and much more with updated typescript (if you were on anything earlier than I think angular 2.4.9, you had to have used typescript 2.0 or lower, and angular 4 requires 2.1 or higher).

Given the upgrade to typescript, you may need to also revisit your tsconfig settings and make sure they are still doing what you want.

Body:
After upgrading from Angular 2 to Angular 4 I get these errors when trying to compile using AOT:

Property 'total' does not exist on type 'Observable<any>'.

This is how I have used observables until now...

First I have assigned a variable like this:

public myData: Observable<any>;

Then I have a call to my service which I subscribe to like this:

this.mySubscription = this.apiService.get('URL-HERE')
                        .subscribe(
                            response => this.myData = response,
                            error => this.feedbackService.displayError(<any>error),
                            () => this.feedbackService.stopLoading()
                        );

This works in development mode (ng serve), and I can use stuff like *ngFor to iterate over the results.

After getting these errors I tried to add a model class like this:

export class MyData {
    total: number;
    count: number;
    data: Array<any> = [];
}
... rest of component here

And then use it with my observable like this:

public myData: Observable<MyData>;

But I still get errors when trying to compile:

Property 'total' does not exist on type 'Observable<MyData>'.

What am I doing wrong?

Update:

This is what the service method looka like:

return this.http
        .get(apiUrl + apiPath, {headers: headersWithToken})
        .timeoutWith(appSettings.maxTimeHttpCalls, Observable.defer(() => Observable.throw(this.feedbackService.timeout())))
        .map((response: Response) => {
            return response.json();
        })
        .catch((err: Response) => {
            return err.json();
        });

All values (including total) exists on the returned JSON and I can use it in my HTML without a problem.


问:
Run-time creation of typed pointer?
Would there be a way to create a typed pointer to a record during run-time?

E.g. achieve the same in run-time as the pMyRecord assignment in

```<code>TMyRecord = record
  s1: string;
  s2: string;
end;

TpMyRecord = ^TMyRecord;
</code>```

...

```<code> var pMyRecord: TpMyRecord;
 begin
   New(pMyRecord)
</code>```

but then without the TpMyRecord = ^TMyRecord declaration.

I know I could use GetMem and FreeMem but I want to keep life-time management of the strings.

The question is a bit out there, I know, and I could just use the TpMyRecord = ^TMyRecord declaration, but I'm curious if there were a run-time way to do this (although I'm suspecting it to be too much of an RTTI hassle).

答:
This is possible with a bit of trickery. Here is an demonstration program:

```<code>{$APPTYPE CONSOLE}

uses
  TypInfo;

type
  PMyRecord = ^TMyRecord;
  TMyRecord = record
    s1: string;
    s2: string;
  end;

var
  SystemNew: function(Size: NativeInt; TypeInfo: Pointer): Pointer;
  SystemDispose: procedure(P: Pointer; TypeInfo: Pointer);

function GetSystemNewAddress: Pointer;
asm
  MOV EAX, offset System.@New
end;

function GetSystemDisposeAddress: Pointer;
asm
  MOV EAX, offset System.@Dispose
end;

var
  p: PMyRecord;
  typeInfo: Pointer;

begin
  ReportMemoryLeaksOnShutdown := True;

  @SystemNew := GetSystemNewAddress;
  @SystemDispose := GetSystemDisposeAddress;

  typeInfo := System.TypeInfo(TMyRecord);
  p := SystemNew(TypInfo.GetTypeData(typeInfo).RecSize, typeInfo);
  p.s1 := 'foo';
  p.s2 := 'bar';
  SystemDispose(p, typeInfo);
end.
</code>```

The New function is an intrinsic function, and receives special treatment from the compiler. When you call New the compiler emits code to call System._New passing the size of the type, and its type info. In turn System._New allocates the memory, using the size of the type, and then initializes the instance using the type info.

The code in the program above shows how to make those calls from your code. The tricky part is obtaining the address of System._New. The code here shows how to do it for the 32 bit Windows compiler.

If you want to call New you will also want to call Dispose. This is also an intrinsic and is treated quite similarly. The code above shows how.

It should go without saying that this relies on implementation details that may change in the future.

Title: Run-time creation of typed pointer?

Body:
Would there be a way to create a typed pointer to a record during run-time?

E.g. achieve the same in run-time as the pMyRecord assignment in

TMyRecord = record
  s1: string;
  s2: string;
end;

TpMyRecord = ^TMyRecord;

...

 var pMyRecord: TpMyRecord;
 begin
   New(pMyRecord)

but then without the TpMyRecord = ^TMyRecord declaration.

I know I could use GetMem and FreeMem but I want to keep life-time management of the strings.

The question is a bit out there, I know, and I could just use the TpMyRecord = ^TMyRecord declaration, but I'm curious if there were a run-time way to do this (although I'm suspecting it to be too much of an RTTI hassle).

Body:
This is possible with a bit of trickery. Here is an demonstration program:

{$APPTYPE CONSOLE}

uses
  TypInfo;

type
  PMyRecord = ^TMyRecord;
  TMyRecord = record
    s1: string;
    s2: string;
  end;

var
  SystemNew: function(Size: NativeInt; TypeInfo: Pointer): Pointer;
  SystemDispose: procedure(P: Pointer; TypeInfo: Pointer);

function GetSystemNewAddress: Pointer;
asm
  MOV EAX, offset System.@New
end;

function GetSystemDisposeAddress: Pointer;
asm
  MOV EAX, offset System.@Dispose
end;

var
  p: PMyRecord;
  typeInfo: Pointer;

begin
  ReportMemoryLeaksOnShutdown := True;

  @SystemNew := GetSystemNewAddress;
  @SystemDispose := GetSystemDisposeAddress;

  typeInfo := System.TypeInfo(TMyRecord);
  p := SystemNew(TypInfo.GetTypeData(typeInfo).RecSize, typeInfo);
  p.s1 := 'foo';
  p.s2 := 'bar';
  SystemDispose(p, typeInfo);
end.

The New function is an intrinsic function, and receives special treatment from the compiler. When you call New the compiler emits code to call System._New passing the size of the type, and its type info. In turn System._New allocates the memory, using the size of the type, and then initializes the instance using the type info.

The code in the program above shows how to make those calls from your code. The tricky part is obtaining the address of System._New. The code here shows how to do it for the 32 bit Windows compiler.

If you want to call New you will also want to call Dispose. This is also an intrinsic and is treated quite similarly. The code above shows how.

It should go without saying that this relies on implementation details that may change in the future.


问:
Parallax effect – hero image overlayed/stack by content
I came across the website for the Moonlight Movie: http://moonlight.movie/

In the top there is a fullscreen image, when scrolling this is being overlayed by a fullscreen section.

It is a niffty little parallax-like effect, that also works on mobile (ios)

Does anybody know how to achieve this effect?

答:
I would encourage you to check pagePiling.js or the parallax fullPage.js extension with an offset of 100%.

If you opt to use pagePiling.js here's an article that explains how to achieve something similar with it.

Reproduction online


问:
How to combine models using Mongoose Population
At the moment I'm defining different models in different files depending on where I use them but there are relations between them and I find myself constantly fetching one, then the other using an ID from the first. E.g.:

File 'models/users.js'

```<code>var mongoose = require('mongoose');
var db = mongoose.connection;
var UserSchema = mongoose.Schema({
    // fields
    companyId: {
        type: String
    }
});

var User = module.exports = mongoose.model('User', UserSchema);

module.exports.getUserById = function(id, callback){
    User.findById(id, callback);
}
</code>```

File 'models/company.js'

```<code>var mongoose = require('mongoose');
var db = mongoose.connection;
var CompanySchema = mongoose.Schema({
    // fields
});
// module export and functions etc.
</code>```

So in that example the User companyId is the ID of one of the companies. Then in my routes I'll import both models, get a User, find the company ID and then fetch that company data:

```<code>var Promise = require('bluebird');
var User = Promise.promisifyAll(require('../models/user'));
var Company = Promise.promisifyAll(require('../models/company'));

User.getUserByIdAsync()
.then(function(user){
    return [user, Company.getCompanyByIdAsync(user.companyId)];
}).spread(function(user,company){
    // Do stuff
}).catch(function(err)... etc });
</code>```

I've been reading about population on the Mongoose docs here: http://mongoosejs.com/docs/populate.html but in the examples everything is in one file. I'm trying to keep models separate for maintainability (and my sanity) so any calls to other models will throw errors.

Is there a way to join the models or reference other external models so I can do this? Is the schema even right?...

I'm using Express and Mongoose.

答:
For reference, the fix is pretty simple. The models being in different files makes no difference.

Change the user model so that the data type is an ObjectID and the ref field references the correct model like so:

```<code>companyId: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Company'
}
</code>```

And use it:

```<code>User.find({}).populate('companyId').exec(callback);
</code>```

Really simple in the end..

Body:
At the moment I'm defining different models in different files depending on where I use them but there are relations between them and I find myself constantly fetching one, then the other using an ID from the first. E.g.:

File 'models/users.js'

var mongoose = require('mongoose');
var db = mongoose.connection;
var UserSchema = mongoose.Schema({
    // fields
    companyId: {
        type: String
    }
});

var User = module.exports = mongoose.model('User', UserSchema);

module.exports.getUserById = function(id, callback){
    User.findById(id, callback);
}

File 'models/company.js'

var mongoose = require('mongoose');
var db = mongoose.connection;
var CompanySchema = mongoose.Schema({
    // fields
});
// module export and functions etc.

So in that example the User companyId is the ID of one of the companies. Then in my routes I'll import both models, get a User, find the company ID and then fetch that company data:

var Promise = require('bluebird');
var User = Promise.promisifyAll(require('../models/user'));
var Company = Promise.promisifyAll(require('../models/company'));

User.getUserByIdAsync()
.then(function(user){
    return [user, Company.getCompanyByIdAsync(user.companyId)];
}).spread(function(user,company){
    // Do stuff
}).catch(function(err)... etc });

I've been reading about population on the Mongoose docs here: http://mongoosejs.com/docs/populate.html but in the examples everything is in one file. I'm trying to keep models separate for maintainability (and my sanity) so any calls to other models will throw errors.

Is there a way to join the models or reference other external models so I can do this? Is the schema even right?...

I'm using Express and Mongoose.

Body:
For reference, the fix is pretty simple. The models being in different files makes no difference.

Change the user model so that the data type is an ObjectID and the ref field references the correct model like so:

companyId: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Company'
}

And use it:

User.find({}).populate('companyId').exec(callback);

Really simple in the end..


问:
How to parse TCP packet payload
I'm using pcap to capture TCP packets for which I would like to parse the payload. My strategy is as follows:

Get the ethernet header and check if it has type ETHERTYPE_IP (IP packet)

Check if the IP packet has protocol IPPROTO_TCP (TCP packet)

Check for payload size > 0 (size = ntohs(ip_header->total_length - ip->header_length*4 - sizeof(struct tcp_header)).

parse payload (grab the host url)

I haven't begun parsing the payload yet because I am getting discrepancies. Below is a printout of the payload of 10 captured TCP packets, using filter "host = www.google.com".

packet number: 3 : TCP Packet: Source Port: 80 Dest Port: 58723
No Data in packet

packet number: 4 : TCP Packet: Source Port: 58723 Dest Port: 80
No Data in packet

packet number: 5 : TCP Packet: Source Port: 58723 Dest Port: 80 Payload :
GET / HTTP/1.1
Host: www.google.com
User-Agent: Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_5; en-us) AppleWebKit/533.19.4 (KHTML, like Gecko) Version/5.0.3 Safari/533.19.4
Accept: application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,/;q=0.5
Accept-Language: en-us
Accept-Encoding: gzip, deflate
Cookie: THICNT=25; SID=DQAAAKIAAAB2ktMrEftADifGm05WkZmlHQsiy1Z2v-
Connection: keep-alive

packet number: 6 : TCP Packet: Source Port: 80 Dest Port: 58723
No Data in packet

packet number: 7 : TCP Packet: Source Port: 80 Dest Port: 58723 Payload:
\272نu\243\255\375\375}\336H\221\227\206\312~\322\317N\236\255A\343#\226\370֤\245[\327`\306ըnE\263\204\313\356\3268 )p\344\301_Y\255\267\240\222x\364

packet number: 8 : TCP Packet: Source Port: 58723 Dest Port: 80
No Data in packet

packet number: 9 : TCP Packet: Source Port: 80 Dest Port: 58723 Payload:
HTTP/1.1 200 OK
Date: Mon, 29 Nov 2010 10:11:36 GMT
Expires: -1
Cache-Control: private, max-age=0
Content-Type: text/html; charset=UTF-8
Content-Encoding: gzip
Server: gws
Content-Length: 8806
X-XSS-Protection: 1; mode=block
\213

Why is there a discrepancy in the payloads and the ports? Ideally I would like to only parse packets like packet 5. How do I ignore packets like 7 and 9?

答:
Your size calculation is incorrect - you can't do the subtraction in network-host-order, you have to convert each field to host-byte-order first:

```<code>size = ntohs(ip_header->total_length) - ntohs(ip->header_length) * 4 - sizeof(struct tcp_header))
</code>```

However, as Remy Lebeau points out, you actually need to examine the offset field in the TCP header to know where the payload starts.

The difference between packet 5 and packet 7 is that the former is going from the client, to the server, and the latter is a response from the server to the client.  This is why the ports are switched around - the source and destination addresses will be switched also.

If you want to only look at packets coming from the client, check that the source address is equal to the client's address.

Title: How to parse TCP packet payload

Body:
Your size calculation is incorrect - you can't do the subtraction in network-host-order, you have to convert each field to host-byte-order first:

size = ntohs(ip_header->total_length) - ntohs(ip->header_length) * 4 - sizeof(struct tcp_header))

However, as Remy Lebeau points out, you actually need to examine the offset field in the TCP header to know where the payload starts.

The difference between packet 5 and packet 7 is that the former is going from the client, to the server, and the latter is a response from the server to the client.  This is why the ports are switched around - the source and destination addresses will be switched also.

If you want to only look at packets coming from the client, check that the source address is equal to the client's address.


问:
Google Search safety advisor
I want to get a hint in Google search results page, classifying each result as a safe website or not safe.

I'm using Google Chrome on Fedora 25 operating system.

I searched a lot, but didn't succeed to find a working one.

Only found it working by using Norton safe search https://search.norton.com which searches in ask.com not google.com.

Any suggestion?

答:
I found this extensions from avast :
https://chrome.google.com/webstore/detail/avast-online-security/gomekmidlodglbbmalcneegieacbdmki?utm_source=chrome-app-launcher-info-dialog

Which did what I want.
Thank you all.

Title: Google Search safety advisor


问:
The heroku command exists in these Ruby versions?
After I updated my Ruby version with rbenv I wasn't able to use the Heroku command-line tool.
I got this error:

```<code>> heroku
rbenv: heroku: command not found

The `heroku' command exists in these Ruby versions:
  2.0.0-p195
</code>```

Reinstalling the tool belt from toolbelt.heroku.com didn't help.

答:
On MacOS, the thing here is that rbenv was getting confused along with brew and the heroku binary.

Heroku recommends a brew install for Macs. Now, you need to make sure that you don't have the gem installed with any other Ruby version managed with rbenv.

If you do, just reinstall them, and you'll be good to go.

Body:
After I updated my Ruby version with rbenv I wasn't able to use the Heroku command-line tool.
I got this error:

> heroku
rbenv: heroku: command not found

The `heroku' command exists in these Ruby versions:
  2.0.0-p195

Reinstalling the tool belt from toolbelt.heroku.com didn't help.