问:
Superimposing a landscape page with 90 degree rotation onto a landscape page with 0 rotation
I have used the superimpose example to superimpose one pdf onto another. I am running into some trouble when trying to superimpose a page from a source file with a rotation of 90 degrees onto the destination page which has 0 rotation but is landscape (it's wider than it is tall).

When i first tried to stamp the content as in the example, it got the content rotated -90 as in the left example in the image below. When I tried to set the rotation of the destination page, the source content was placed in the right orientation but the destination page had turn (right example in the image below).

```<code>var sourcePageRotation = sourcePage.GetRotation();
destinationPage.SetRotation(sourcePageRotation);
</code>```

How can I manipulate either the source or destination page to change the rotation value without actually changing the way it displays?

答:
(As you referenced a Java example, I'll also refer to iText for Java.)

In the SuperImpose example the pages to superimpose are added using

```<code>canvas.addXObject(page, 0, 0);
</code>```

but there are other PdfCanvas.addXObject overloads, too, in particular

```<code>public PdfCanvas addXObject(PdfXObject xObject, float a, float b, float c, float d, float e, float f)
</code>```

The 6 floats represent an affine transformation applied to the XObject, e.g. a rotation. Thus, you can rotate the imported page XObject from the source document to match the orientation of the destination document page, e.g. replace

```<code>canvas.addXObject(page, 0, 0);
</code>```

by

```<code>canvas.addXObject(page, 0, 1, -1, 0, page.getHeight(), 0);
</code>```

or, if that makes the page contents stand upside down, by

```<code>canvas.addXObject(page, 0, -1, 1, 0, 0, page.getWidth());
</code>```

Just like the example you referenced I here assume the lower left corner of the pages involved are the respective coordinate system origin. If that assumption is wrong, one needs to adapt the last two float parameters respectively  in the replacements above.

Body:
I have used the superimpose example to superimpose one pdf onto another. I am running into some trouble when trying to superimpose a page from a source file with a rotation of 90 degrees onto the destination page which has 0 rotation but is landscape (it's wider than it is tall).

When i first tried to stamp the content as in the example, it got the content rotated -90 as in the left example in the image below. When I tried to set the rotation of the destination page, the source content was placed in the right orientation but the destination page had turn (right example in the image below).

var sourcePageRotation = sourcePage.GetRotation();
destinationPage.SetRotation(sourcePageRotation);

How can I manipulate either the source or destination page to change the rotation value without actually changing the way it displays?

Body:
(As you referenced a Java example, I'll also refer to iText for Java.)

In the SuperImpose example the pages to superimpose are added using

canvas.addXObject(page, 0, 0);

but there are other PdfCanvas.addXObject overloads, too, in particular

public PdfCanvas addXObject(PdfXObject xObject, float a, float b, float c, float d, float e, float f)

The 6 floats represent an affine transformation applied to the XObject, e.g. a rotation. Thus, you can rotate the imported page XObject from the source document to match the orientation of the destination document page, e.g. replace

canvas.addXObject(page, 0, 0);

by

canvas.addXObject(page, 0, 1, -1, 0, page.getHeight(), 0);

or, if that makes the page contents stand upside down, by

canvas.addXObject(page, 0, -1, 1, 0, 0, page.getWidth());

Just like the example you referenced I here assume the lower left corner of the pages involved are the respective coordinate system origin. If that assumption is wrong, one needs to adapt the last two float parameters respectively  in the replacements above.


来源: stackexchange

问:
Updating multiple rows in single column
I need to update newly added column(store the sum of all items of the invoice) with result from subquery which generates more than one rows. I added new column to Invoice table.

```<code>ALTER TABLE Invoice
ADD ItemsSum int NULL
</code>```

I tried following query but it gave error because of multiple results

```<code>UPDATE Invoice
SET ItemsSum = (SELECT SUM(Amount)
               FROM InvoiceItem it
               INNER JOIN Invoice i ON it.InvoiceID = i.ID
               GROUP BY i.ID)
</code>```

How to achieve this correctly in SQL Server?

答:
correlated is :</p>

```<code>UPDATE Invoice
     SET ItemsSum = (SELECT SUM(invc.Amount)
                     FROM InvoiceItem invc
                     WHERE invc.InvoiceID = Invoice.ID
                     GROUP BY Invoice.ID;
                    );
</code>```

ContentLicense: CC BY-SA 4.0

Title: Updating multiple rows in single column

Body:
I need to update newly added column(store the sum of all items of the invoice) with result from subquery which generates more than one rows. I added new column to Invoice table.

ALTER TABLE Invoice
ADD ItemsSum int NULL

I tried following query but it gave error because of multiple results

UPDATE Invoice
SET ItemsSum = (SELECT SUM(Amount)
               FROM InvoiceItem it
               INNER JOIN Invoice i ON it.InvoiceID = i.ID
               GROUP BY i.ID)

How to achieve this correctly in SQL Server?

Body:
correlated is :

UPDATE Invoice
     SET ItemsSum = (SELECT SUM(invc.Amount)
                     FROM InvoiceItem invc
                     WHERE invc.InvoiceID = Invoice.ID
                     GROUP BY Invoice.ID;
                    );


问:
Unable to create SharePoint item & update external columns content (business connectivity services)?
I am having trouble creating a new item within a SharePoint 2013 list. I'm able to actually create the item, though the external data (business connectivity services [bcs]) does not autopopulate as it would during the creation of the item via the SharePoint UI. Is there any way to actually make this work, or to send the function that needs to run via POST? I've pasted my current item creation sub below. </p>

```<code>Dim oXMLHTTP As Object

Dim sListNameOrGuid As String
Dim sBatchXml As String
sWTF As String

Set oXMLHTTP = CreateObject("MSXML2.XMLHTTP.6.0")
sCurrentUser = fGetUserID

With oXMLHTTP

    .Open "POST", "MYSPSITE.COM/_api/web/lists/GetByTitle('THELIST')/items", True
    .setRequestHeader "Accept", "application/json;odata=verbose"
    .setRequestHeader "Content-Type", "application/json;odata=verbose"
'    .setRequestHeader "X-HTTP-Method", "PATCH"
'    .setRequestHeader "If-Match", "*"
    .setRequestHeader "X-RequestDigest", fGetLoginToken

        sWTF = "{ 'User': " & Int(sCurrentUser) & ", 'newComment': 'TESTING TESTING'}"
    .send (sWTF)

    Do While .readyState <> 4:
        DoEvents
    Loop

    Debug.Print (.responseText)

    .abort

End With

Set oXMLHTTP = Nothing

End Sub
</code>```

答: Lower the timer job frequency.</p>

Body:
I am having trouble creating a new item within a SharePoint 2013 list. I'm able to actually create the item, though the external data (business connectivity services [bcs]) does not autopopulate as it would during the creation of the item via the SharePoint UI. Is there any way to actually make this work, or to send the function that needs to run via POST? I've pasted my current item creation sub below.

Dim oXMLHTTP As Object

Dim sListNameOrGuid As String
Dim sBatchXml As String
sWTF As String

Set oXMLHTTP = CreateObject("MSXML2.XMLHTTP.6.0")
sCurrentUser = fGetUserID

With oXMLHTTP

    .Open "POST", "MYSPSITE.COM/_api/web/lists/GetByTitle('THELIST')/items", True
    .setRequestHeader "Accept", "application/json;odata=verbose"
    .setRequestHeader "Content-Type", "application/json;odata=verbose"
'    .setRequestHeader "X-HTTP-Method", "PATCH"
'    .setRequestHeader "If-Match", "*"
    .setRequestHeader "X-RequestDigest", fGetLoginToken

        sWTF = "{ 'User': " & Int(sCurrentUser) & ", 'newComment': 'TESTING TESTING'}"
    .send (sWTF)

    Do While .readyState <> 4:
        DoEvents
    Loop

    Debug.Print (.responseText)

    .abort

End With

Set oXMLHTTP = Nothing

End Sub

Body: Lower the timer job frequency.


问:
Can onDestroy() be called without onHandleWork() in JobIntentService?
I am using JobIntentService.enqueueWork()

I would like to know if it's ever possible for the onDestroy() to be called even without onHandleWork() called in a JobIntentService.

Basically, what's the lifecycle of a JobIntentService. Is onHandleWork() guaranteed to be called at least once before onDestroy() gets invoked?

答:
The behaviour of JobIntentService is different depending on the version of Android running on the target device (prior to API level 26, or API level 26 or higher).

However, generally you can assume that onHandleWork() is called at least once before onDestroy(). There would be no reason to start the Service if there was no work for it. Generally the Service would only be started when there is work in the queue, in which case onHandleWork() would be called immediately after the Service is started.


问:
In CakePHP, why would $this->params['form'] be empty if I've just posted a form?
Using CakePHP 1.3, I post a form which correctly fills in $this->data. According to the docs, it seems like $this->params['form'] should be populated with some information as well, but it's simply an empty array. Is there a particular reason for that?

The form is built using the Form Helper, as follows...

Some relevant code:

```<code>$default_form_create_options = array(
    'inputDefaults' => array(
        'label'=>false,
        'div'=>false
    )
);

echo $form->create('Preappform', $default_form_create_options);
// --- snip, a bunch of form elements created via $form->input()
echo $form->end(array('label'=>'Send This Form »', 'class'=>'submit-button', 'escape'=>false));
</code>```

I know that the form data is available in $this->data, so maybe this is just a documentation/curiosity issue. If so... my bad.

答: I too faced the same while working with CakePHP 1.3. Later I solved the issue by using the $this->params['data']. But I have some questions, I'm a newbie to cakephp and using the manual as my reference, it seems that the manual is not at all updated, while searching about this issue, I found out that it was working well in earlier versions and after 1.2, it is not at all there in Cakephp. Is there any CakePHP experts to clarify this stuff ?</p>

ContentLicense: CC BY-SA 2.5

Body:
Using CakePHP 1.3, I post a form which correctly fills in $this->data. According to the docs, it seems like $this->params['form'] should be populated with some information as well, but it's simply an empty array. Is there a particular reason for that?

The form is built using the Form Helper, as follows...

Some relevant code:

$default_form_create_options = array(
    'inputDefaults' => array(
        'label'=>false,
        'div'=>false
    )
);

echo $form->create('Preappform', $default_form_create_options);
// --- snip, a bunch of form elements created via $form->input()
echo $form->end(array('label'=>'Send This Form »', 'class'=>'submit-button', 'escape'=>false));

I know that the form data is available in $this->data, so maybe this is just a documentation/curiosity issue. If so... my bad.

ContentLicense: CC BY-SA 3.0


问:
Is this a bad way to implement a graph?
When I look at a book, I only show examples of how to implement graphs in almost every book by adjacent matrix method and adjacent list method.

I'm trying to create a node-based editor, in which case the number of edges that stretch out on each node is small, but there's a lot of vertex.

So I'm trying to implement the adjacent list method rather than the adjacent matrix method.
However, adjacent lists store and use each edge as a connection list.

But, I would like to use the node in the form listed below.

```<code>class GraphNode
{
    int x, y;
    dataType data;
    vector<GraphNode*> in;
    vector<GraphNode*> out;
public:
    GraphNode(var...) = 0;
};
</code>```

So like this, I want to make the node act as a vertex and have access to other nodes that are connected.

Because when I create a node-based editor program, I have to access and process different nodes that are connected to each node.

I want to implement this without using a linked list.

And, I'm going to use graph algorithms in this state.

Is this a bad method?

Lastly, I apologize for my poor English.

Thank you for reading.

答:
Short answer: It is probably a reasonable way for implementing a graph.

Long answer: What graph data structure to use is always dependent on what you want to use it for. A adjacency matrix is good for very dense graphs were it will not waste space due to many 0 entries and if we want to answer the question "Is there an edge between A and B?" fast. The iteration over all members of a node can take pretty long, since it has to look at a whole row and not just the neighbors.

An adjacency list is good for sparse graphs and if we mostly want to look up all neighbors of a node (which is very often the case for graph mustering algorithms). In a directed graph were we want to treat ingoing and outgoing edges seperately, it is probably a good idea to have a seperate adjacency list for ingoing and outgoing egdes (as has your code).

Regarding what container to use for the list, it depends on the use case. If you will much more often iterate over the graph and not so often delete something from it, using a vector over a list is a very good idea (basically all graph programms I ever wrote were of this type). If you have a graph that changes very often, you have to delete edges very often, you don't want to have iterator invalidation and so on, maybe it is better having a list. But that is very seldom the case.

A good design would be to make it very easy to change between list and vector so you can easily profile both and then use what is better for your program.

Btw if you often delete one edge, this is also pretty easily done fast with a vector, if you do not care about the order of your edges in adjacency list (so do not do this without thinking while iterating over the vector):

```<code>void delte_in_edge(size_t index) {
    std::swap(in[i], in.back());  // The element to be deleted is now at the last position,
                                  // the formerly last element is at position i
    in.pop_back();                // Delete the current last element
}
</code>```

This has O(1) complexity (and the swap is probably pretty fast).

Title: Is this a bad way to implement a graph?

Body:
When I look at a book, I only show examples of how to implement graphs in almost every book by adjacent matrix method and adjacent list method.

I'm trying to create a node-based editor, in which case the number of edges that stretch out on each node is small, but there's a lot of vertex.

So I'm trying to implement the adjacent list method rather than the adjacent matrix method.
However, adjacent lists store and use each edge as a connection list.

But, I would like to use the node in the form listed below.

class GraphNode
{
    int x, y;
    dataType data;
    vector<GraphNode*> in;
    vector<GraphNode*> out;
public:
    GraphNode(var...) = 0;
};

So like this, I want to make the node act as a vertex and have access to other nodes that are connected.

Because when I create a node-based editor program, I have to access and process different nodes that are connected to each node.

I want to implement this without using a linked list.

And, I'm going to use graph algorithms in this state.

Is this a bad method?

Lastly, I apologize for my poor English.

Thank you for reading.

Body:
Short answer: It is probably a reasonable way for implementing a graph.

Long answer: What graph data structure to use is always dependent on what you want to use it for. A adjacency matrix is good for very dense graphs were it will not waste space due to many 0 entries and if we want to answer the question "Is there an edge between A and B?" fast. The iteration over all members of a node can take pretty long, since it has to look at a whole row and not just the neighbors.

An adjacency list is good for sparse graphs and if we mostly want to look up all neighbors of a node (which is very often the case for graph mustering algorithms). In a directed graph were we want to treat ingoing and outgoing edges seperately, it is probably a good idea to have a seperate adjacency list for ingoing and outgoing egdes (as has your code).

Regarding what container to use for the list, it depends on the use case. If you will much more often iterate over the graph and not so often delete something from it, using a vector over a list is a very good idea (basically all graph programms I ever wrote were of this type). If you have a graph that changes very often, you have to delete edges very often, you don't want to have iterator invalidation and so on, maybe it is better having a list. But that is very seldom the case.

A good design would be to make it very easy to change between list and vector so you can easily profile both and then use what is better for your program.

Btw if you often delete one edge, this is also pretty easily done fast with a vector, if you do not care about the order of your edges in adjacency list (so do not do this without thinking while iterating over the vector):

void delte_in_edge(size_t index) {
    std::swap(in[i], in.back());  // The element to be deleted is now at the last position,
                                  // the formerly last element is at position i
    in.pop_back();                // Delete the current last element
}

This has O(1) complexity (and the swap is probably pretty fast).


问:
How to measure performance with async functions in javascript
I've created a small app that compares the speeds of WebAssembly and Javascript. To my surprise, JavaScript is way faster at calculating factorials of a large number. Or at least it seems like it is. I am pretty sure this is not right and is caused by the await syntax I'm using. (The functions are the same.) Also, what are some really time heavy tasks I can use to compare those two? This doesn't really seem that time consuming, since it takes less than a 0.1 millisecond.

AssemblyScript (this gets compiled into wasm)

```<code>// The entry file of your WebAssembly module.
export function fib(num: i32): i32 {
  var a: i32 = 1,
    b: i32 = 0,
    temp: i32;

  while (num > 0) {
    temp = a;
    a = a + b;
    b = temp;
    num--;
  }

  return b;
}

</code>```

App.js

```<code>import waApi from "./api";
...
  <button
       onClick={async () => {
       const t0 = performance.now();
       (await waApi).fib(200);
       const t1 = performance.now();
       this.updateGraph(t1 - t0, "wa");
       const t2 = performance.now();
       this.fib(200);
       const t3 = performance.now();
       this.updateGraph(t3 - t2, "js");
       }}>
Calculate with both
  </button>
</code>```

api.js

```<code>import { instantiateStreaming } from "assemblyscript/lib/loader";

export default instantiateStreaming(fetch("./assembly.wasm"));
</code>```

答:
It should be

```<code>import waApi from "./api";

class Test extends React.Component {
  async componentDidMount() {
    this.wasmModule = await waApi;
  }

  render() {
    return (
      <button
        onClick={() => {
          const module = this.wasmModule;
          if (!module) {
            console.warn("module not yet loaded. Try later");
            return;
          }
          const t0 = performance.now();
          module.fib(200);
          const t1 = performance.now();
          this.updateGraph(t1 - t0, "wa");
          const t2 = performance.now();
          this.fib(200);
          const t3 = performance.now();
          this.updateGraph(t3 - t2, "js");
        }}>
    );
  }
}
</code>```

Because in your example for wasm part you also measured loading and instantiation of module.

Body:
I've created a small app that compares the speeds of WebAssembly and Javascript. To my surprise, JavaScript is way faster at calculating factorials of a large number. Or at least it seems like it is. I am pretty sure this is not right and is caused by the await syntax I'm using. (The functions are the same.) Also, what are some really time heavy tasks I can use to compare those two? This doesn't really seem that time consuming, since it takes less than a 0.1 millisecond.

AssemblyScript (this gets compiled into wasm)

// The entry file of your WebAssembly module.
export function fib(num: i32): i32 {
  var a: i32 = 1,
    b: i32 = 0,
    temp: i32;

  while (num > 0) {
    temp = a;
    a = a + b;
    b = temp;
    num--;
  }

  return b;
}

App.js

import waApi from "./api";
...
  <button
       onClick={async () => {
       const t0 = performance.now();
       (await waApi).fib(200);
       const t1 = performance.now();
       this.updateGraph(t1 - t0, "wa");
       const t2 = performance.now();
       this.fib(200);
       const t3 = performance.now();
       this.updateGraph(t3 - t2, "js");
       }}>
Calculate with both
  </button>

api.js

import { instantiateStreaming } from "assemblyscript/lib/loader";

export default instantiateStreaming(fetch("./assembly.wasm"));

Body:
It should be

import waApi from "./api";

class Test extends React.Component {
  async componentDidMount() {
    this.wasmModule = await waApi;
  }

  render() {
    return (
      <button
        onClick={() => {
          const module = this.wasmModule;
          if (!module) {
            console.warn("module not yet loaded. Try later");
            return;
          }
          const t0 = performance.now();
          module.fib(200);
          const t1 = performance.now();
          this.updateGraph(t1 - t0, "wa");
          const t2 = performance.now();
          this.fib(200);
          const t3 = performance.now();
          this.updateGraph(t3 - t2, "js");
        }}>
    );
  }
}

Because in your example for wasm part you also measured loading and instantiation of module.


问:
How can I ban keys of one interface from appearing in another interface
Basically what I'm trying to achieve is prevention of certain properties of an existing object to be passed as arguments to an interface. I believe this is possible through some combination of conditional types, but having a hard time working out the right combination.

```<code>export interface Dictionary<T> {
  [index: string]: T;
}

type StandardContext = {
    myKeyOne?: string;
    myKeyTwo?: number;
}

type NonStandardContext = Exclude<Dictionary<any>, StandardContext>

const standard: StandardContext = {
    myKeyOne: '2', // ok!
}

const nonStandardError: NonStandardContext = {
    myKeyOne: '2' // should error (good so far)
}

const nonStandardGood: NonStandardContext = {
    foo: '2' // should not error, but it does!
}
</code>```

Playground link

答:
A union between Dictionary<any> and {[P in keyof StandardContext]?: never} does it:

```<code>type NonStandardContext = Dictionary<any> & { [P in keyof StandardContext]?: never };
</code>```

On the playground

You don't need the ? on that second part with your example StandardContext, but that's only because your example StandardContext doesn't have any required properties. If it did have some, without the ? the type above would be impossible to satisfy since it would require you to have a property with type never! :-) (Example)

(Thank you kaya3 for pointing out the need for ?!)

I have to admit not fully understanding why Exclude<Dictionary<any>, StandardContext> doesn't work. :-) But I think Exclude only works for types that don't use index signatures. I could be wrong about why. I suspect that from reading this answer which says that Exclude is, roughly speaking, the following (except this is only for string keys, not string and number):

```<code>type Diff<T extends string, U extends string> = ({[P in T]: P } & {[P in U]: never } & { [x: string]: never })[T]
// −−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−^^^^^^^^^^^^^^^^^^^^^^^^
</code>```

Notice that last part excluding index keys.

Body:
Basically what I'm trying to achieve is prevention of certain properties of an existing object to be passed as arguments to an interface. I believe this is possible through some combination of conditional types, but having a hard time working out the right combination.

export interface Dictionary<T> {
  [index: string]: T;
}

type StandardContext = {
    myKeyOne?: string;
    myKeyTwo?: number;
}

type NonStandardContext = Exclude<Dictionary<any>, StandardContext>

const standard: StandardContext = {
    myKeyOne: '2', // ok!
}

const nonStandardError: NonStandardContext = {
    myKeyOne: '2' // should error (good so far)
}

const nonStandardGood: NonStandardContext = {
    foo: '2' // should not error, but it does!
}

<a href="https://www.typescriptlang.org/play/?ssl=1&ssc=1&pln=22&pc=2#code/KYDwDg9gTgLgBASwHY2FAZgQwMbDgEQWxgQiUygE8AeAFQD44BvAWACg44BtZAE1ABccAM4woyAOYBdIbQDc7AL7t2MSmDwBlGJiS8KvAMJlUIeAF5m7TpwC2lANLBKAeSTAA-ENHikEhRw29k6UtADuEF5wSACutgBGaAHKbKrqeAByZNq6%20lBGJqAWcACiINgANjH81ITEpORU1LqU9AA0cDl6BsYoRfQqbNhkoiI63flCXXkFfWZwlqyBdo7ObsBCAOQATJsdAPT7cBAA1gCESoPDSKNI2eMzJVBQ0EJZSNM9hfOL1kGrrncW12cEOIgAFhAYhVeHA0C8oHAABQSCAQWHCCBwLBQACUl1SQxG8DuHweBgA4mjeG97rkvnNiksbNi0cDNqCjsJIdDYXd4PDoB14jF4Ah4LwIMBhBc2IogA" rel="nofollow noreferrer">Playground link

Body:
A union between Dictionary<any> and {[P in keyof StandardContext]?: never} does it:

type NonStandardContext = Dictionary<any> & { [P in keyof StandardContext]?: never };

<a href="https://www.typescriptlang.org/play/#code/KYDwDg9gTgLgBASwHY2FAZgQwMbDgEQWxgQiUygE8AeAFQD44BvAWACg44BtZAE1ABccAM4woyAOYBdIbQDc7AL7t2MSmDwBlGJiS8KvAMJlUIeAF5m7TpwC2lANLBKAeSTAA-ENHikEhRw29k6UtADuEF5wSACutgBGaAHKbKrqeAByZNq6+lBGJqAWBEQkZBQ0upSMAGTM3AAKiEhwANbOEOhwOXoGxihFUlHuAG5ocIoB7NhkoiI6vflCPXkFA2ZwlqyBdo7ObsBCAOQATEcANHAA9FdwEK0AhEoqbDNIc0jZC6sAolBQ0CEWSQKz6hQ2W2sQT2rncxzO11uwgAFhAYgAbXhwNAAqBwAAUEggECxwggcCwUAAlM9Uq9ZvBPiDvgYAOLE3hAr65MHrYrbGwU4nwo6IkSojFYz7wHHQS7xGLwBDwXgQYDCJ5sRRAA" rel="nofollow noreferrer">On the playground

You don't need the ? on that second part with your example StandardContext, but that's only because your example StandardContext doesn't have any required properties. If it did have some, without the ? the type above would be impossible to satisfy since it would require you to have a property with type never! :-) (<a href="https://www.typescriptlang.org/play/?ssl=7&ssc=1&pln=6&pc=1#code/KYDwDg9gTgLgBASwHY2FAZgQwMbDgEQWxgQiUygE8AeAFQD44BvAWACg44BtZAE1ABccAM4woyAOYBdIbQDc7AL7t2MSmDwBlGJiS8KvAMJlUIeAF5m7TpyjAAjgFcEd3kNHikEhRxsBbSgBpYEoAeSRgAH53MUkfGzgA4MpaAHcIaLgkRz8AIzQfZTZVdTwAOTJtXX0oIxNQCwIiEjIKGl1KRgAyZm4ABUQkOABrEIh0OCq9A2MUBpks4AA3NDhFH3ZsMlERHWnaoSmaurmzOEtWX1sHZ1chACJ0CAh7gBprfyCQ8OAhAHIAEx-V5wAD0oLgEGGAEIlCo2FskDskJU9scAKJQKDQIQVJBHGb1M4XD6cJLfCL-IFgiHCAAWEEcABteHA0NioHAABQSZ6s4QQOBYKAASjhxQR23gKPxaIMAHE+bjUdVCadGpcEk8IFS-jSRAzmayUfB2dAQblHPAEPBeBBgMJYWxFEA" rel="nofollow noreferrer">Example)

(Thank you kaya3 for pointing out the need for ?!)

I have to admit not fully understanding why Exclude<Dictionary<any>, StandardContext> doesn't work. :-) But I think Exclude only works for types that don't use index signatures. I could be wrong about why. I suspect that from reading this answer which says that Exclude is, roughly speaking, the following (except this is only for string keys, not string and number):

type Diff<T extends string, U extends string> = ({[P in T]: P } & {[P in U]: never } & { [x: string]: never })[T]
// −−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−^^^^^^^^^^^^^^^^^^^^^^^^

Notice that last part excluding index keys.


问:
how to prevent visual studio from messing with my code's identation?
Visual Basic 2010 automatically changes indentation of my code from this ::

```<code>public void fetchWebserviceCounters()  {
    csv = new StringBuilder();
    try  {
       Category = new PerformanceCounterCategory("Web Service");
       foreach (String instance in Category.GetInstanceNames())  {
          counters = Category.GetCounters(instance);
          foreach (PerformanceCounter counter in counters)  {
              if (counter.CounterName == "Total Bytes Sent" | counter.CounterName == "Total Bytes Recieved") {
                 csv.Append(counter.CounterName + ",");
                 csv.Append(counter.NextValue().ToString() + ", ");
              }
          }
       }
   }
   catch (Exception e) {
            Console.WriteLine(e.Message);
   }
   Console.Write(csv.ToString());
</code>```

}

to this

```<code>public void fetchWebserviceCounters()
    {
        csv = new StringBuilder();
        try
        {
            Category = new PerformanceCounterCategory("Web Service");
            foreach (String instance in Category.GetInstanceNames())
            {
                counters = Category.GetCounters(instance);
                foreach (PerformanceCounter counter in counters)
                {
                    if (counter.CounterName == "Total Bytes Sent" | counter.CounterName == "Total Bytes Recieved")
                    {
                        csv.Append(counter.CounterName + ",");
                        csv.Append(counter.NextValue().ToString() + ", ");
                    }
                }
            }
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
        }
        Console.Write(csv.ToString());
    }
</code>```

 How can i prevent Visual Basic from Doing this to My code

答:
If you're passing C# to Visual Basic editor expect it to mess up.

There are lots of text formatting options in VS: Tools | Options | Text Editor | language | Formatting.

The extent of these depends on the language, and includes options about when code is automatically re-formatted.

Body:
Visual Basic 2010 automatically changes indentation of my code from this ::

public void fetchWebserviceCounters()  {
    csv = new StringBuilder();
    try  {
       Category = new PerformanceCounterCategory("Web Service");
       foreach (String instance in Category.GetInstanceNames())  {
          counters = Category.GetCounters(instance);
          foreach (PerformanceCounter counter in counters)  {
              if (counter.CounterName == "Total Bytes Sent" | counter.CounterName == "Total Bytes Recieved") {
                 csv.Append(counter.CounterName + ",");
                 csv.Append(counter.NextValue().ToString() + ", ");
              }
          }
       }
   }
   catch (Exception e) {
            Console.WriteLine(e.Message);
   }
   Console.Write(csv.ToString());

}

to this

public void fetchWebserviceCounters()
    {
        csv = new StringBuilder();
        try
        {
            Category = new PerformanceCounterCategory("Web Service");
            foreach (String instance in Category.GetInstanceNames())
            {
                counters = Category.GetCounters(instance);
                foreach (PerformanceCounter counter in counters)
                {
                    if (counter.CounterName == "Total Bytes Sent" | counter.CounterName == "Total Bytes Recieved")
                    {
                        csv.Append(counter.CounterName + ",");
                        csv.Append(counter.NextValue().ToString() + ", ");
                    }
                }
            }
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
        }
        Console.Write(csv.ToString());
    }

 How can i prevent Visual Basic from Doing this to My code


问:
ReactJS SyntheticEvent stopPropagation() only works with React events?
I'm trying to use event.stopPropagation() within a ReactJS component to stop a click event from bubbling up and triggering a click event that was attached with JQuery in legacy code, but it seems like React's stopPropagation() only stops propagation to events also attached in React, and JQuery's stopPropagation() doesn't stop propagation to events attached with React.

Is there any way to make stopPropagation() work across these events?  I wrote a simple JSFiddle to demonstrate these behaviors:

```<code>/** @jsx React.DOM */
var Propagation = React.createClass({
    alert: function(){
        alert('React Alert');
    },
    stopPropagation: function(e){
        e.stopPropagation();
    },
    render: function(){
        return (
            <div>
                <div onClick={this.alert}>
                    <a href="#" onClick={this.stopPropagation}>React Stop Propagation on React Event</a>
                </div>
                <div className="alert">
                    <a href="#" onClick={this.stopPropagation}>React Stop Propagation on JQuery Event</a>
                </div>
                <div onClick={this.alert}>
                    <a href="#" className="stop-propagation">JQuery Stop Propagation on React Event</a>
                </div>
                <div className="alert">
                    <a href="#" className="stop-propagation">JQuery Stop Propagation on JQuery Event</a>
                </div>
            </div>
        );
    }
});

React.renderComponent(<Propagation />, document.body);

$(function(){
    $(document).on('click', '.alert', function(e){
        alert('Jquery Alert');
    });

    $(document).on('click', '.stop-propagation', function(e){
        e.stopPropagation();
    });
});
</code>```

答: A quick workaround is using window.addEventListener instead of document.addEventListener.

Body:
I'm trying to use event.stopPropagation() within a ReactJS component to stop a click event from bubbling up and triggering a click event that was attached with JQuery in legacy code, but it seems like React's stopPropagation() only stops propagation to events also attached in React, and JQuery's stopPropagation() doesn't stop propagation to events attached with React.

Is there any way to make stopPropagation() work across these events?  I wrote a simple JSFiddle to demonstrate these behaviors:

/** @jsx React.DOM */
var Propagation = React.createClass({
    alert: function(){
        alert('React Alert');
    },
    stopPropagation: function(e){
        e.stopPropagation();
    },
    render: function(){
        return (

                    React Stop Propagation on React Event

                    React Stop Propagation on JQuery Event

                    JQuery Stop Propagation on React Event

                    JQuery Stop Propagation on JQuery Event

        );
    }
});

React.renderComponent(<Propagation />, document.body);

$(function(){
    $(document).on('click', '.alert', function(e){
        alert('Jquery Alert');
    });

    $(document).on('click', '.stop-propagation', function(e){
        e.stopPropagation();
    });
});


问:
iTerm2 closing curly brace not working
in the last weeks I had the problem that in iTerm2 the closing curly brace is not working anymore.
It works in all other applications (including Terminal), but iTerm2 is not showing the curly brace. The opening curly brace works.

I have got a German keyboard, so it should be ALT+9

I uninstalled the shell integration, because I thought this problem occurs since the installation of the integration, but no success so far.

Any ideas how to fix this issue?

答:
For me it turns out the right ALT key works but not the left and it's because the left ALT key had a different setting.

You can change this by going to Preferences -> Profiles -> Keys and changing from Esc+ to Normal

Title: iTerm2 closing curly brace not working


问:
Yahoo sign in with Selenium, missing click
I am trying to write a login function. When I try to login into my yahoo account, I send the correct keys for my email address, which works, but then when I click "next" it 'misses' the click and instead clicks the banner which opens up some sort of advertisement be it travel related or Norton anti-security, or something. I've been working on this issue intermittently throughout the past week surfing and digging through forums before finally making my first post.

I am aware of the different ways of element selectors via css, id, class name, xpath, etc... I tried sleep(), implicit_wait(), things along those lines. I also tried something with wait until clickable with the expected conditions module from selenium.webdriver.

I've attached an image of what I have so far. My python version is up-to-date as are my selenium and chrome driver installations. I saw a similar post already up, but the OP didn't seem to be encountering my issue. (how to click on the yahoo sign in link using selenium web driver?)

I tried this as well, and it opens the advertisement; in my executions, Norton seems to be the most frequently appearing advertisement. (login to Yahoo using Python Selenium)

I've looked at the API documentation, but there doesn't seem to be any clear direction on what I could do. I've attached screenshots of what happens on the running of the script as well as the code I have.

I got it to work for some runs where I was able to go to the next form to send my password keys, but it happened randomly and inexplicably.

```<code>from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from login import password, email
from time import sleep

class yahoo():

def __init__(self):

    # INITIALIZE CHROME WEBDRIVER
    self.driver = webdriver.Chrome()
    self.driver.maximize_window()

def login(self):

    # OPEN BROWSER TO LOGIN PAGE AND MAXIMIZE
    self.driver.get("https://login.yahoo.com/config/login?.\
    src=fpctx&.intl=us&.lang=en-US&.done=https://www.yahoo.com")
    # LOGIN ACTIONS

    {# 1. send email address and click next
    self.driver.find_element_by_id('login-username').send_keys(email)
    element = WebDriverWait(self.driver, 10).until(\
            EC.presence_of_element_located((By.ID, "login-signin")))
    element.click()

    # 2. send password and click sign in
    self.driver.find_element_by_xpath('//*[@id="login-passwd"]').send_keys(password)
    self.driver.find_element_by_id('login-signin').click()}`enter code here

x = yfscreeners()
x.login()
</code>```

Any help is well appreciated.

答:
To send a character sequence to the Email address field and invoke click() on the button with text as Next you need to induce WebDriverWait for the element_to_be_clickable() and you can use either of the following  Locator Strategies:

Using css_selector:

```<code>from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

options = webdriver.ChromeOptions()
options.add_argument("start-maximized")
options.add_experimental_option("excludeSwitches", ["enable-automation"])
options.add_experimental_option('useAutomationExtension', False)
driver = webdriver.Chrome(options=options, executable_path=r'C:\Utility\BrowserDrivers\chromedriver.exe')
driver.get('https://login.yahoo.com')
WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "input.phone-no#login-username"))).send_keys('my_username@yahoo.co.in')
driver.find_element_by_css_selector("input#login-signin").submit()
</code>```

Using xpath:

```<code>from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

options = webdriver.ChromeOptions()
options.add_argument("start-maximized")
options.add_experimental_option("excludeSwitches", ["enable-automation"])
options.add_experimental_option('useAutomationExtension', False)
driver = webdriver.Chrome(options=options, executable_path=r'C:\Utility\BrowserDrivers\chromedriver.exe')
driver.get('https://login.yahoo.com')
WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, "//input[@class='phone-no ' and @id='login-username']"))).send_keys('my_username@yahoo.co.in')
driver.find_element_by_xpath("//input[@id='login-signin']").submit()
</code>```

Browser Snapshot:

Body:
I am trying to write a login function. When I try to login into my yahoo account, I send the correct keys for my email address, which works, but then when I click "next" it 'misses' the click and instead clicks the banner which opens up some sort of advertisement be it travel related or Norton anti-security, or something. I've been working on this issue intermittently throughout the past week surfing and digging through forums before finally making my first post.

I am aware of the different ways of element selectors via css, id, class name, xpath, etc... I tried sleep(), implicit_wait(), things along those lines. I also tried something with wait until clickable with the expected conditions module from selenium.webdriver.

I've attached an image of what I have so far. My python version is up-to-date as are my selenium and chrome driver installations. I saw a similar post already up, but the OP didn't seem to be encountering my issue. (how to click on the yahoo sign in link using selenium web driver?)

I tried this as well, and it opens the advertisement; in my executions, Norton seems to be the most frequently appearing advertisement. (login to Yahoo using Python Selenium)

I've looked at the API documentation, but there doesn't seem to be any clear direction on what I could do. I've attached screenshots of what happens on the running of the script as well as the code I have.

I got it to work for some runs where I was able to go to the next form to send my password keys, but it happened randomly and inexplicably.

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from login import password, email
from time import sleep

class yahoo():

def __init__(self):

    # INITIALIZE CHROME WEBDRIVER
    self.driver = webdriver.Chrome()
    self.driver.maximize_window()

def login(self):

    # OPEN BROWSER TO LOGIN PAGE AND MAXIMIZE
    self.driver.get("https://login.yahoo.com/config/login?.\
    src=fpctx&.intl=us&.lang=en-US&.done=https://www.yahoo.com")
    # LOGIN ACTIONS

    {# 1. send email address and click next
    self.driver.find_element_by_id('login-username').send_keys(email)
    element = WebDriverWait(self.driver, 10).until(\
            EC.presence_of_element_located((By.ID, "login-signin")))
    element.click()

    # 2. send password and click sign in
    self.driver.find_element_by_xpath('//*[@id="login-passwd"]').send_keys(password)
    self.driver.find_element_by_id('login-signin').click()}`enter code here

x = yfscreeners()
x.login()

Any help is well appreciated.

Body:
To send a character sequence to the Email address field and invoke click() on the button with text as Next you need to induce WebDriverWait for the element_to_be_clickable() and you can use either of the following  Locator Strategies:

Using css_selector:

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

options = webdriver.ChromeOptions()
options.add_argument("start-maximized")
options.add_experimental_option("excludeSwitches", ["enable-automation"])
options.add_experimental_option('useAutomationExtension', False)
driver = webdriver.Chrome(options=options, executable_path=r'C:\Utility\BrowserDrivers\chromedriver.exe')
driver.get('https://login.yahoo.com')
WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "input.phone-no#login-username"))).send_keys('my_username@yahoo.co.in')
driver.find_element_by_css_selector("input#login-signin").submit()

Using xpath:

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

options = webdriver.ChromeOptions()
options.add_argument("start-maximized")
options.add_experimental_option("excludeSwitches", ["enable-automation"])
options.add_experimental_option('useAutomationExtension', False)
driver = webdriver.Chrome(options=options, executable_path=r'C:\Utility\BrowserDrivers\chromedriver.exe')
driver.get('https://login.yahoo.com')
WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, "//input[@class='phone-no ' and @id='login-username']"))).send_keys('my_username@yahoo.co.in')
driver.find_element_by_xpath("//input[@id='login-signin']").submit()

Browser Snapshot:


问:
ASP.Net Core 3.1 razor page show error for list of employee
I am trying to convert Blazor example to ASP.Net Core Razor page for learning purpose but i am getting bunch of errors in Employees.cshtml page and Employees.cshtml.cs where i am trying to call data.

I am simply trying to show data on this page, i am not sure how & where to define functions call data. I not using WebAPI.

I am also trying to find simple CRUD example related to asp.net core 3.1 so that i know how flow works later on i can convert same using dapper etc..

I have no prior experience of MVC or Core

UPDATE: I had few error which have been resolved but only error i am getting when running is in programe.cs

```<code>public static void Main(string[] args)
{
    CreateHostBuilder(args).Build().Run();
}
</code>```

error message

InvalidOperationException: Error while validating the service
  descriptor 'ServiceType: RazorCore31.Data.IEmployeeService Lifetime:
  Scoped ImplementationType: RazorCore31.Data.EmployeeService': Unable
  to resolve service for type 'RazorCore31.Data.SqlDbContext' while
  attempting to activate 'RazorCore31.Data.EmployeeService'.

System.AggregateException: 'Some services are not able to be
  constructed (Error while validating the service descriptor
  'ServiceType: RazorCore31.Data.IEmployeeService Lifetime: Scoped
  ImplementationType: RazorCore31.Data.EmployeeService': Unable to
  resolve service for type 'RazorCore31.Data.SqlDbContext' while
  attempting to activate 'RazorCore31.Data.EmployeeService'.)'

EmployeeService.cs

```<code>using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using RazorCore31.Models;

namespace RazorCore31.Data
{
    public class EmployeeService: IEmployeeService
    {

        private readonly SqlDbContext _dbContext;

        public EmployeeService(SqlDbContext dbContext)
        {
            _dbContext = dbContext;
        }
        public async Task<List<Employee>> GetEmployees()
        {
            return await _dbContext.Employees.ToListAsync();
        }
        public async Task<bool> CreateEmployee(Employee employee)
        {
            employee.Id = Guid.NewGuid().ToString();
            _dbContext.Add(employee);
            try
            {
                await _dbContext.SaveChangesAsync();
                return true;
            }
            catch (DbUpdateException)
            {
                return false;
            }

        }
        public async Task<Employee> SingleEmployee(string id)
        {
            return await _dbContext.Employees.FindAsync(id);
        }
        public async Task<bool> EditEmployee(string id, Employee employee)
        {
            if (id != employee.Id)
            {
                return false;
            }

            _dbContext.Entry(employee).State = EntityState.Modified;
            await _dbContext.SaveChangesAsync();
            return true;
        }
        public async Task<bool> DeleteEmployee(string id)
        {
            var patient = await _dbContext.Employees.FindAsync(id);
            if (patient == null)
            {
                return false;
            }

            _dbContext.Employees.Remove(patient);
            await _dbContext.SaveChangesAsync();
            return true;
        }

        Task<List<Employee>> IEmployeeService.GetEmployees()
        {
            throw new NotImplementedException();
        }

    }
}
</code>```

IEmployeeService.cs

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using RazorCore31.Models;

namespace RazorCore31.Data
{
    public interface IEmployeeService
    {
        Task<List<Employee>> GetEmployees();
        Task<bool> CreateEmployee(Employee employee);
        Task<bool> EditEmployee(string id, Employee employee);
        Task<Employee> SingleEmployee(string id);
        Task<bool> DeleteEmployee(string id);
    }
}
</code>```

Employee.cs

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.ComponentModel.DataAnnotations;
using RazorCore31.Data;

namespace RazorCore31.Models
{
    public class Employee
    {

        [MaxLength(50)]
        public string Id { get; set; }

        [Required(ErrorMessage = "Name is RRRequired")]
        [StringLength(20, ErrorMessage = "Name is too long.")]
        public string Name { get; set; }

        [Required]
        [StringLength(20)]
        public string Department { get; set; }
        [MaxLength(100)]
        public string Designation { get; set; }
        [MaxLength(100)]
        public string Company { get; set; }
        [MaxLength(100)]
        public string City { get; set; }

    }
}
</code>```

Employees.cshtml

```<code>@page
@model RazorCore31.EmployeesModel
@using RazorCore31.Data
@using RazorCore31.Models
@using System.Collections.Generic
@{
    ViewData["Title"] = "Employees";
}

<h1>Employees list</h1>

<p>List of Employee</p>

@if (employees == null)
{
    <p>Loading page...</p>
}
else
{
    <table class='table'>
        <thead>
            <tr>
                <th>EmpName"</th>
                <th>L["EmpDepartment"]</th>
                <th>L["EmpDesignation"]</th>
                <th>L["EmpCompany"]</th>
                <th>L["EmpCity"]</th>
            </tr>
        </thead>
        <tbody>
            @foreach (var employee in employees)
            {
                <tr>
                    <td>@employee.Name</td>
                    <td>@employee.Department</td>
                    <td>@employee.Designation</td>
                    <td>@employee.Company</td>
                    <td>@employee.City</td>
                    <td>
                        <a href='/editemployee/@employee.Id'>Edit</a>
                        <a href='/deleteemployee/@employee.Id'>Delete</a>
                    </td>
                </tr>
            }
        </tbody>
    </table>
}
</code>```

Employees.cshtml.cs

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using RazorCore31.Models;
using RazorCore31.Data;

namespace RazorCore31
{
    public class EmployeesModel : PageModel
    {
       //public  List<Employee> employees ;

        private List<Employee> _empList;

        public void empRepository()
        {
            //_empList = Data.EmployeeService.
        }
        public void OnGet()
        {

        }

        public Task getEmployeesAsync()
        {
            _empList = EmployeeService.GetEmployees();
           // return _empList;
        }

    }
}

Startup.cs

public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<ApplicationDbContext>(options =>
        options.UseSqlServer(
            Configuration.GetConnectionString("DefaultConnection")));
    services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)
        .AddEntityFrameworkStores<ApplicationDbContext>();
    services.AddRazorPages();

    services.AddScoped<IEmployeeService, EmployeeService>();
    ///services.AddSingleton<IEmployeeService, EmployeeService>();

}
</code>```

ERROR in Program.cs

```<code>public static void Main(string[] args)
{
    CreateHostBuilder(args).Build().Run();
}
</code>```

InvalidOperationException: Error while validating the service
  descriptor 'ServiceType: RazorCore31.Data.IEmployeeService Lifetime:
  Scoped ImplementationType: RazorCore31.Data.EmployeeService': Unable
  to resolve service for type 'RazorCore31.Data.SqlDbContext' while
  attempting to activate 'RazorCore31.Data.EmployeeService'.

System.AggregateException: 'Some services are not able to be
  constructed (Error while validating the service descriptor
  'ServiceType: RazorCore31.Data.IEmployeeService Lifetime: Scoped
  ImplementationType: RazorCore31.Data.EmployeeService': Unable to
  resolve service for type 'RazorCore31.Data.SqlDbContext' while
  attempting to activate 'RazorCore31.Data.EmployeeService'.)'

ERROR MESSAGES (This error is resolved based on @TanvirArjel solution )

答:
Write your EmployeesModel as follows:

```<code>public class EmployeesModel : PageModel
{
    private readonly IEmployeeService _employeeService;

    public EmployeesModel(IEmployeeService employeeService)
    {
        _employeeService = employeeService;
    }

    public List<Employee> EmployeeList; // <-- Here is the EmployeeList property

    public async Task OnGetAsync()
    {
        EmployeeList = await _employeeService.GetEmployees(); // <-- Populate EmployeeList here
    }
}
</code>```

Then in the view:

```<code>@page
@model RazorCore31.EmployeesModel
@using RazorCore31.Data
@using RazorCore31.Models
@using System.Collections.Generic
@{
    ViewData["Title"] = "Employees";
}

<h1>Employees list</h1>

<table class='table'>
    <thead>
        <tr>
            <th>EmpName"</th>
            <th>L["EmpDepartment"]</th>
            <th>L["EmpDesignation"]</th>
            <th>L["EmpCompany"]</th>
            <th>L["EmpCity"]</th>
        </tr>
    </thead>
    <tbody>
        @foreach (var employee in Model.EmployeeList) //<-- Here it is
        {
            <tr>
                <td>@employee.Name</td>
                <td>@employee.Department</td>
                <td>@employee.Designation</td>
                <td>@employee.Company</td>
                <td>@employee.City</td>
                <td>
                    <a href='/editemployee/@employee.Id'>Edit</a>
                    <a href='/deleteemployee/@employee.Id'>Delete</a>
                </td>
            </tr>
        }
    </tbody>
</table>
</code>```

Body:
I am trying to convert Blazor example to ASP.Net Core Razor page for learning purpose but i am getting bunch of errors in Employees.cshtml page and Employees.cshtml.cs where i am trying to call data.

I am simply trying to show data on this page, i am not sure how & where to define functions call data. I not using WebAPI.

I am also trying to find simple CRUD example related to asp.net core 3.1 so that i know how flow works later on i can convert same using dapper etc..

I have no prior experience of MVC or Core

UPDATE: I had few error which have been resolved but only error i am getting when running is in programe.cs

public static void Main(string[] args)
{
    CreateHostBuilder(args).Build().Run();
}

error message

InvalidOperationException: Error while validating the service
  descriptor 'ServiceType: RazorCore31.Data.IEmployeeService Lifetime:
  Scoped ImplementationType: RazorCore31.Data.EmployeeService': Unable
  to resolve service for type 'RazorCore31.Data.SqlDbContext' while
  attempting to activate 'RazorCore31.Data.EmployeeService'.

System.AggregateException: 'Some services are not able to be
  constructed (Error while validating the service descriptor
  'ServiceType: RazorCore31.Data.IEmployeeService Lifetime: Scoped
  ImplementationType: RazorCore31.Data.EmployeeService': Unable to
  resolve service for type 'RazorCore31.Data.SqlDbContext' while
  attempting to activate 'RazorCore31.Data.EmployeeService'.)'

EmployeeService.cs

using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using RazorCore31.Models;

namespace RazorCore31.Data
{
    public class EmployeeService: IEmployeeService
    {

        private readonly SqlDbContext _dbContext;

        public EmployeeService(SqlDbContext dbContext)
        {
            _dbContext = dbContext;
        }
        public async Task<List<Employee>> GetEmployees()
        {
            return await _dbContext.Employees.ToListAsync();
        }
        public async Task<bool> CreateEmployee(Employee employee)
        {
            employee.Id = Guid.NewGuid().ToString();
            _dbContext.Add(employee);
            try
            {
                await _dbContext.SaveChangesAsync();
                return true;
            }
            catch (DbUpdateException)
            {
                return false;
            }

        }
        public async Task<Employee> SingleEmployee(string id)
        {
            return await _dbContext.Employees.FindAsync(id);
        }
        public async Task<bool> EditEmployee(string id, Employee employee)
        {
            if (id != employee.Id)
            {
                return false;
            }

            _dbContext.Entry(employee).State = EntityState.Modified;
            await _dbContext.SaveChangesAsync();
            return true;
        }
        public async Task<bool> DeleteEmployee(string id)
        {
            var patient = await _dbContext.Employees.FindAsync(id);
            if (patient == null)
            {
                return false;
            }

            _dbContext.Employees.Remove(patient);
            await _dbContext.SaveChangesAsync();
            return true;
        }

        Task<List<Employee>> IEmployeeService.GetEmployees()
        {
            throw new NotImplementedException();
        }

    }
}

IEmployeeService.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using RazorCore31.Models;

namespace RazorCore31.Data
{
    public interface IEmployeeService
    {
        Task<List<Employee>> GetEmployees();
        Task<bool> CreateEmployee(Employee employee);
        Task<bool> EditEmployee(string id, Employee employee);
        Task<Employee> SingleEmployee(string id);
        Task<bool> DeleteEmployee(string id);
    }
}

Employee.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.ComponentModel.DataAnnotations;
using RazorCore31.Data;

namespace RazorCore31.Models
{
    public class Employee
    {

        [MaxLength(50)]
        public string Id { get; set; }

        [Required(ErrorMessage = "Name is RRRequired")]
        [StringLength(20, ErrorMessage = "Name is too long.")]
        public string Name { get; set; }

        [Required]
        [StringLength(20)]
        public string Department { get; set; }
        [MaxLength(100)]
        public string Designation { get; set; }
        [MaxLength(100)]
        public string Company { get; set; }
        [MaxLength(100)]
        public string City { get; set; }

    }
}

Employees.cshtml

@page
@model RazorCore31.EmployeesModel
@using RazorCore31.Data
@using RazorCore31.Models
@using System.Collections.Generic
@{
    ViewData["Title"] = "Employees";
}

Employees list

List of Employee

@if (employees == null)
{

Loading page...

}
else
{

                EmpName"
                L["EmpDepartment"]
                L["EmpDesignation"]
                L["EmpCompany"]
                L["EmpCity"]

            @foreach (var employee in employees)
            {

                    @employee.Name
                    @employee.Department
                    @employee.Designation
                    @employee.Company
                    @employee.City

                        Edit
                        Delete

            }

}

Employees.cshtml.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using RazorCore31.Models;
using RazorCore31.Data;

namespace RazorCore31
{
    public class EmployeesModel : PageModel
    {
       //public  List<Employee> employees ;

        private List<Employee> _empList;

        public void empRepository()
        {
            //_empList = Data.EmployeeService.
        }
        public void OnGet()
        {

        }

        public Task getEmployeesAsync()
        {
            _empList = EmployeeService.GetEmployees();
           // return _empList;
        }

    }
}

Startup.cs

public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<ApplicationDbContext>(options =>
        options.UseSqlServer(
            Configuration.GetConnectionString("DefaultConnection")));
    services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)
        .AddEntityFrameworkStores<ApplicationDbContext>();
    services.AddRazorPages();

    services.AddScoped<IEmployeeService, EmployeeService>();
    ///services.AddSingleton<IEmployeeService, EmployeeService>();

}

ERROR in Program.cs

public static void Main(string[] args)
{
    CreateHostBuilder(args).Build().Run();
}

InvalidOperationException: Error while validating the service
  descriptor 'ServiceType: RazorCore31.Data.IEmployeeService Lifetime:
  Scoped ImplementationType: RazorCore31.Data.EmployeeService': Unable
  to resolve service for type 'RazorCore31.Data.SqlDbContext' while
  attempting to activate 'RazorCore31.Data.EmployeeService'.

System.AggregateException: 'Some services are not able to be
  constructed (Error while validating the service descriptor
  'ServiceType: RazorCore31.Data.IEmployeeService Lifetime: Scoped
  ImplementationType: RazorCore31.Data.EmployeeService': Unable to
  resolve service for type 'RazorCore31.Data.SqlDbContext' while
  attempting to activate 'RazorCore31.Data.EmployeeService'.)'

ERROR MESSAGES (This error is resolved based on @TanvirArjel solution )

Body:
Write your EmployeesModel as follows:

public class EmployeesModel : PageModel
{
    private readonly IEmployeeService _employeeService;

    public EmployeesModel(IEmployeeService employeeService)
    {
        _employeeService = employeeService;
    }

    public List<Employee> EmployeeList; // <-- Here is the EmployeeList property

    public async Task OnGetAsync()
    {
        EmployeeList = await _employeeService.GetEmployees(); // <-- Populate EmployeeList here
    }
}

Then in the view:

@page
@model RazorCore31.EmployeesModel
@using RazorCore31.Data
@using RazorCore31.Models
@using System.Collections.Generic
@{
    ViewData["Title"] = "Employees";
}

<h1>Employees list</h1>

<table class='table'>
    <thead>
        <tr>
            <th>EmpName"</th>
            <th>L["EmpDepartment"]</th>
            <th>L["EmpDesignation"]</th>
            <th>L["EmpCompany"]</th>
            <th>L["EmpCity"]</th>
        </tr>
    </thead>
    <tbody>
        @foreach (var employee in Model.EmployeeList) //<-- Here it is
        {
            <tr>
                <td>@employee.Name</td>
                <td>@employee.Department</td>
                <td>@employee.Designation</td>
                <td>@employee.Company</td>
                <td>@employee.City</td>
                <td>
                    <a href='/editemployee/@employee.Id'>Edit</a>
                    <a href='/deleteemployee/@employee.Id'>Delete</a>
                </td>
            </tr>
        }
    </tbody>
</table>


问:
Excel Interop from Windows Service crash in EXCEL.EXE, Version: 16.0.4966.1000, Moduls: oart.dll, Version: 16.0.4900.1000
Please don't comment, that Interop mode from Windows Service is not supported, I know that. :-)

I have an Excel file with tables and charts. It runs for several years under Windows Server 2012R2 with Excel 2003 as Windows service in Interop mode without any problems.

After changing to Windows Server 2019 and Excel 2016 it was no longer possible to open this file with the following code:

```<code>Application excelApp = new Application();
Workbooks  workBooks = excelApp.Workbooks;
workBook = workBooks.Open(<Path To Excel-File>, 0, false, 5,
     Missing.Value, Missing.Value, true, XlPlatform.xlWindows, "\t", true, false, 0, true);
</code>```

It results inside my error handling in:

```<code>System.Runtime.InteropServices.COMException (0x80010105): The server threw an exception.
(Exception from HRESULT: 0x80010105 (RPC_E_SERVERFAULT))
</code>```

and the event log shows:

```<code>Name der fehlerhaften Anwendung: EXCEL.EXE, Version: 16.0.4966.1000, Zeitstempel: 0x5e205905
Name des fehlerhaften Moduls: oart.dll, Version: 16.0.4900.1000, Zeitstempel: 0x5d53033a
Ausnahmecode: 0xc0000005
Fehleroffset: 0x0006e67e
ID des fehlerhaften Prozesses: 0x1a38
Startzeit der fehlerhaften Anwendung: 0x01d5e64d380ea691
Pfad der fehlerhaften Anwendung: C:\Program Files (x86)\Microsoft Office\Office16\EXCEL.EXE
Pfad des fehlerhaften Moduls: C:\Program Files (x86)\Microsoft Office\Office16\oart.dll
Berichtskennung: b6eee871-9dca-4ddc-8d4b-cdd9f58f871b
</code>```

答:
After hours of testing with my file I craeted a new Excel file and it was no problem to open it and read or write data to cells. Than I deleted more and more tables and charts from my file and finally I found the crash reason:

Is there any embedded image in any chart or table than it is not possible to open the file with Interop from Windows Service.

It was at no time a problem to open the file (with inside images) with the same code using a command line Application.

But it is possible to place images in header or footer. That's no problem. Crazy.

Body:
Please don't comment, that Interop mode from Windows Service is not supported, I know that. :-)

I have an Excel file with tables and charts. It runs for several years under Windows Server 2012R2 with Excel 2003 as Windows service in Interop mode without any problems.

After changing to Windows Server 2019 and Excel 2016 it was no longer possible to open this file with the following code:

Application excelApp = new Application();
Workbooks  workBooks = excelApp.Workbooks;
workBook = workBooks.Open(<Path To Excel-File>, 0, false, 5,
     Missing.Value, Missing.Value, true, XlPlatform.xlWindows, "\t", true, false, 0, true);

It results inside my error handling in:

System.Runtime.InteropServices.COMException (0x80010105): The server threw an exception.
(Exception from HRESULT: 0x80010105 (RPC_E_SERVERFAULT))

and the event log shows:

Name der fehlerhaften Anwendung: EXCEL.EXE, Version: 16.0.4966.1000, Zeitstempel: 0x5e205905
Name des fehlerhaften Moduls: oart.dll, Version: 16.0.4900.1000, Zeitstempel: 0x5d53033a
Ausnahmecode: 0xc0000005
Fehleroffset: 0x0006e67e
ID des fehlerhaften Prozesses: 0x1a38
Startzeit der fehlerhaften Anwendung: 0x01d5e64d380ea691
Pfad der fehlerhaften Anwendung: C:\Program Files (x86)\Microsoft Office\Office16\EXCEL.EXE
Pfad des fehlerhaften Moduls: C:\Program Files (x86)\Microsoft Office\Office16\oart.dll
Berichtskennung: b6eee871-9dca-4ddc-8d4b-cdd9f58f871b


问:
Listen to Child window close event in Oauth Like Situation [ jQuery| Javascript ]
I am using oAuth 1.0 to access 3rd party data.

For this I am taking following steps :-

User clicks on "sync with 3rd party" button. ( It is necessary for user to click because this usually doesn't invoke popup blocker.)

When user click on this button following code is executed :

```<code>    $('#sync_with_thirdparty').click(function(){
       var child = window.open('/oauth');
       $(child).unload(function() {
           if (this.location != "about:blank") {
            alert("Child window closed");
        }
      });
    });
</code>```

Now in the new window PHP get the authentication URL from 3rd party then it redirects the user to the same URL. As soon as user redirects to 3rd party above code says that "child window closed.".

Then user makes himself login on third party site (if necessary) and gives access to our app. As soon as he clicks on allow button third party redirects the user to a new page in our website. On this page I am calling window.close() method which is working perfectly fine.

But upon window.close() in child window, parent window is not able to know that child is closed.

How I can solve this problem?

Note : This 3rd doesn't like Iframe and refreshes itself to open in top window. I don't have any control over 3rd party's content. Our webpage is in HTML5 format.

答:
The child window can communicate with the parent window via the window.opener() function. You could do something like this:

Child window

window.opener.messageFromChildWindow('closed');
```

<p><strong>Parent window</strong></p>

<pre class="lang-js prettyprint-override"><code>function messageFromChildWindow(msg) {
    if(msg === 'closed') {
        alert('child window closed');
    }
}
</code>```

Body:
I am using oAuth 1.0 to access 3rd party data.

For this I am taking following steps :-

User clicks on "sync with 3rd party" button. ( It is necessary for user to click because this usually doesn't invoke popup blocker.)

When user click on this button following code is executed :

    $('#sync_with_thirdparty').click(function(){
       var child = window.open('/oauth');
       $(child).unload(function() {
           if (this.location != "about:blank") {
            alert("Child window closed");
        }
      });
    });

Now in the new window PHP get the authentication URL from 3rd party then it redirects the user to the same URL. As soon as user redirects to 3rd party above code says that "child window closed.".

Then user makes himself login on third party site (if necessary) and gives access to our app. As soon as he clicks on allow button third party redirects the user to a new page in our website. On this page I am calling window.close() method which is working perfectly fine.

But upon window.close() in child window, parent window is not able to know that child is closed.

How I can solve this problem?

Note : This 3rd doesn't like Iframe and refreshes itself to open in top window. I don't have any control over 3rd party's content. Our webpage is in HTML5 format.

Body:
The child window can communicate with the parent window via the window.opener() function. You could do something like this:

Child window

window.opener.messageFromChildWindow('closed');

Parent window

function messageFromChildWindow(msg) {
    if(msg === 'closed') {
        alert('child window closed');
    }
}


问:
android: ZoomPicker breaks onTouchListener
I've got a webview which makes use of the built in zoom controls, as follows:

```<code>wv = new WebView(this);
wv.getSettings().setBuiltInZoomControls(true);
</code>```

Note: this activates two main functions - pinch-to-zoom and invokeZoomPicker() (the latter is only called when a swiping action is done on the view, a simple touch doesn't enable it)

and i also want things to happen when touch events occur, using the following

```<code>wv.setOnTouchListener(new View.OnTouchListener() {
    public boolean onTouch(View v, MotionEvent event) {
        Log.i("touch", "touched!");
        return false;
    }
});
</code>```

When the WebView loads, and I tap the screen, the log states "touched" every time I interact with the screen, as expected. However, if I do something that would set off invokeZoomPicker() (pinch to zoom doesn't seem to cause this problem, as long as the zoom widget doesn't appear), onTouchListener stops responding to my taps (even after a few seconds, when the widget disappears from view).

To make sure it was invokeZoomPicker(), I edited the second segment of my code as follows:

```<code>wv.setOnTouchListener(new View.OnTouchListener() {
    public boolean onTouch(View v, MotionEvent event) {
        wv.invokeZoomPicker();
        Log.i("touch", "touched!");
        return false;
    }
});
</code>```

This new onTouch method now only triggers once (as a result of which the zoomwidget appears on the view - and disappears a few seconds later), and then the onTouch method doesn't get called again until the view is reloaded - so it is definitely a problem with the invokeZoomPicker()/Zoom widget

Have I missed some vital piece of code that allows them to coexist, or do I just have to choose which one I can live without?

答: A dirty solution is to cover an invisible view on top of your web view and detects touches there, and you have to distinguish if the touch is consumed, or return false to pass touches to underlying web view.</p>

Body:
I've got a webview which makes use of the built in zoom controls, as follows:

wv = new WebView(this);
wv.getSettings().setBuiltInZoomControls(true);

Note: this activates two main functions - pinch-to-zoom and invokeZoomPicker() (the latter is only called when a swiping action is done on the view, a simple touch doesn't enable it)

and i also want things to happen when touch events occur, using the following

wv.setOnTouchListener(new View.OnTouchListener() {
    public boolean onTouch(View v, MotionEvent event) {
        Log.i("touch", "touched!");
        return false;
    }
});

When the WebView loads, and I tap the screen, the log states "touched" every time I interact with the screen, as expected. However, if I do something that would set off invokeZoomPicker() (pinch to zoom doesn't seem to cause this problem, as long as the zoom widget doesn't appear), onTouchListener stops responding to my taps (even after a few seconds, when the widget disappears from view).

To make sure it was invokeZoomPicker(), I edited the second segment of my code as follows:

wv.setOnTouchListener(new View.OnTouchListener() {
    public boolean onTouch(View v, MotionEvent event) {
        wv.invokeZoomPicker();
        Log.i("touch", "touched!");
        return false;
    }
});

This new onTouch method now only triggers once (as a result of which the zoomwidget appears on the view - and disappears a few seconds later), and then the onTouch method doesn't get called again until the view is reloaded - so it is definitely a problem with the invokeZoomPicker()/Zoom widget

Have I missed some vital piece of code that allows them to coexist, or do I just have to choose which one I can live without?


问:
How to send fcm notification when app is not running
I have tried many solutions but none of them are worked. I am able receive FCM notification when app is active, but not getting notification when app is background or killed.</p>

答:
you need to create a service class extending FirebaseMessagingService and override onMessageReceived method in that class to send notification

```<code>class MyFirebaseMessagingService : FirebaseMessagingService() {

    override fun onMessageReceived(message: RemoteMessage) {
        super.onMessageReceived(message)
        try {
            message.notification?.let {
                showNotification(
                    it.title ?: "",
                    it.body ?: ""
                )

            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }
}
</code>```

you are now getting the notification info from backend and showing it as a notification by using the function showNotification. of course, you must implement the function showNotification. it just a simple function for showing notifications in android

Edit: this the implementation of the function, add this to your class

```<code>class MyFirebaseMessagingService : FirebaseMessagingService() {

    companion object {
        const val channelId = "Channel"
        const val channelName = "MyChannel"
        const val smallIcon: Int = R.drawable.ic_logo
        const val notificationId = 1
    }

        fun showNotification(myTitle: String, myBody: String) {

        val notificationBuilder = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            Notification.Builder(applicationContext, channelId)
        } else {
            Notification.Builder(applicationContext)
        }

        val intent = Intent(applicationContext, HomeActivity::class.java)
        val pendingIntent = PendingIntent.getActivity(
            applicationContext,
            0,
            intent,
            PendingIntent.FLAG_UPDATE_CURRENT
        )
        val notificationManager =
            applicationContext.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager

        when {
            Build.VERSION.SDK_INT >= 26 -> {
                val channel = NotificationChannel(
                    channelId,
                    channelName,
                    NotificationManager.IMPORTANCE_DEFAULT
                )
                notificationManager.createNotificationChannel(channel)
                notificationBuilder
                    .setContentIntent(pendingIntent)
                    .setContentText(myBody)
                    .setSmallIcon(smallIcon)
                    .setContentTitle(myTitle)
            }

            Build.VERSION.SDK_INT >= 24 -> notificationBuilder
                .setContentText(myBody)
                .setContentTitle(myTitle)
                .setSmallIcon(smallIcon)
                .setContentIntent(pendingIntent)

            else -> notificationBuilder
                .setContentText(myBody)
                .setContentTitle(myTitle)
                .setSmallIcon(smallIcon)
                .setContentIntent(pendingIntent)
        }
        notificationManager.notify(notificationId, notificationBuilder.build())
    }

}
</code>```

Body:
you need to create a service class extending FirebaseMessagingService and override onMessageReceived method in that class to send notification

class MyFirebaseMessagingService : FirebaseMessagingService() {

    override fun onMessageReceived(message: RemoteMessage) {
        super.onMessageReceived(message)
        try {
            message.notification?.let {
                showNotification(
                    it.title ?: "",
                    it.body ?: ""
                )

            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }
}

you are now getting the notification info from backend and showing it as a notification by using the function showNotification. of course, you must implement the function showNotification. it just a simple function for showing notifications in android

Edit: this the implementation of the function, add this to your class

class MyFirebaseMessagingService : FirebaseMessagingService() {

    companion object {
        const val channelId = "Channel"
        const val channelName = "MyChannel"
        const val smallIcon: Int = R.drawable.ic_logo
        const val notificationId = 1
    }

        fun showNotification(myTitle: String, myBody: String) {

        val notificationBuilder = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            Notification.Builder(applicationContext, channelId)
        } else {
            Notification.Builder(applicationContext)
        }

        val intent = Intent(applicationContext, HomeActivity::class.java)
        val pendingIntent = PendingIntent.getActivity(
            applicationContext,
            0,
            intent,
            PendingIntent.FLAG_UPDATE_CURRENT
        )
        val notificationManager =
            applicationContext.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager

        when {
            Build.VERSION.SDK_INT >= 26 -> {
                val channel = NotificationChannel(
                    channelId,
                    channelName,
                    NotificationManager.IMPORTANCE_DEFAULT
                )
                notificationManager.createNotificationChannel(channel)
                notificationBuilder
                    .setContentIntent(pendingIntent)
                    .setContentText(myBody)
                    .setSmallIcon(smallIcon)
                    .setContentTitle(myTitle)
            }

            Build.VERSION.SDK_INT >= 24 -> notificationBuilder
                .setContentText(myBody)
                .setContentTitle(myTitle)
                .setSmallIcon(smallIcon)
                .setContentIntent(pendingIntent)

            else -> notificationBuilder
                .setContentText(myBody)
                .setContentTitle(myTitle)
                .setSmallIcon(smallIcon)
                .setContentIntent(pendingIntent)
        }
        notificationManager.notify(notificationId, notificationBuilder.build())
    }

}


问:
How to reliably determine last commit date in remote repository?
I have seen this answer and it is almost exactly what I need.

Difference is that will print date for human eyes, while I need to check it in a Makefile.

In particular I need to rebuild a certain file IFF something changed in repo after its creation.

I might not have a local copy of repo, so I might need a full "git clone" (possibly shallow), but I cannot directly use file dates because git does not preserve them.

I need something like:
   if myfile is_older $(git log -1 --format=%cd origin/master); then ... or, in Makefile:

```<code>myfile: $(somefunc $(shell git log -1 --format=%cd origin/master))
        commands to rebuild myfile
</code>```

but I don't know how to write it.

答:
If you need to change the date format, try to add --date option.

For example:

rfc

```<code>git log -1 --format=%cd --date=rfc
Wed, 5 Feb 2020 16:34:38 +0200
</code>```

relative

```<code>git log -1 --format=%cd --date=relative
13 days ago
</code>```

iso-strict

```<code>git log -1 --format=%cd --date=iso-strict
2020-02-05T16:34:38+02:00
</code>```

short

```<code>log -1 --format=%cd --date=short
2020-02-05
</code>```

raw

```<code>git log -1 --format=%cd --date=raw
1580913278 +0200
</code>```

For more documentation, look into: https://git-scm.com/docs/git-log

Maybe I would use "raw". Is this date formatting convenient for your script?

Body:
I have seen this answer and it is almost exactly what I need.

Difference is that will print date for human eyes, while I need to check it in a Makefile.

In particular I need to rebuild a certain file IFF something changed in repo after its creation.

I might not have a local copy of repo, so I might need a full "git clone" (possibly shallow), but I cannot directly use file dates because git does not preserve them.

I need something like:
   if myfile is_older $(git log -1 --format=%cd origin/master); then ... or, in Makefile:

myfile: $(somefunc $(shell git log -1 --format=%cd origin/master))
        commands to rebuild myfile

but I don't know how to write it.

Body:
If you need to change the date format, try to add --date option.

For example:

rfc

git log -1 --format=%cd --date=rfc
Wed, 5 Feb 2020 16:34:38 +0200

relative

git log -1 --format=%cd --date=relative
13 days ago

iso-strict

git log -1 --format=%cd --date=iso-strict
2020-02-05T16:34:38+02:00

short

log -1 --format=%cd --date=short
2020-02-05

raw

git log -1 --format=%cd --date=raw
1580913278 +0200

For more documentation, look into: https://git-scm.com/docs/git-log

Maybe I would use "raw". Is this date formatting convenient for your script?


问:
How to pick color from buttons
I have html tables,and I would like to change its colors by picking up from button and clicking cells.

First,I would like to select colors from buttons,

↓

Second,When I select colors from buttons,I would like to click cells to change color.

↓

Third,After selecting colors,Can I change cell's color by clicking on it?

```<code><tr>
<td>color</td>
</tr>

<button>yellow</button>
<button>aqua</button>
</code>```

At first I assume it will realize by changing td's class,but I couldn't find out the ways.

If someone has experienced such method,please let me know.

Thanks

```<code>td {
  background-color: yellow;
  }

td {
  background-color: aqua;
  }
</code>```

答:
Use this code-

$(document).ready(function(){
  $("#color1").click(function(){
    $(".table td").css("background","red");
  });
  $("#color2").click(function(){
    $(".table td").css("background","aqua");
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!doctype html>
<html>
<head>
<title>My First Web Page</title>
</head>
<body>
<h1>My Table</h1>
<table class="table">
    <tr>
        <th>Airport Code</th>
        <th>Common Name/City</th>
    </tr>
    <tr>
        <td>CWA</td>
        <td>Central Wisconsin Airport</td>
    </tr>
    <tr>
        <td>ORD</td>
        <td>Chicago O'Hare</td>
    </tr>
    <tr>
        <td>LHR</td>
        <td>London Heathrow</td>
    </tr>
</table>

<button id="color1">Select Red</button>
<button id="color2">Select aqua</button>

</body>
</html></code>```

Title: How to pick color from buttons

Body:
I have html tables,and I would like to change its colors by picking up from button and clicking cells.

First,I would like to select colors from buttons,

↓

Second,When I select colors from buttons,I would like to click cells to change color.

↓

Third,After selecting colors,Can I change cell's color by clicking on it?

color

<button>yellow</button>
<button>aqua</button>

At first I assume it will realize by changing td's class,but I couldn't find out the ways.

If someone has experienced such method,please let me know.

Thanks

td {
  background-color: yellow;
  }

td {
  background-color: aqua;
  }

Body:
Use this code-

$(document).ready(function(){
  $("#color1").click(function(){
    $(".table td").css("background","red");
  });
  $("#color2").click(function(){
    $(".table td").css("background","aqua");
  });
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!doctype html>
<html>
<head>
<title>My First Web Page</title>
</head>
<body>
<h1>My Table</h1>
<table class="table">
    <tr>
        <th>Airport Code</th>
        <th>Common Name/City</th>
    </tr>
    <tr>
        <td>CWA</td>
        <td>Central Wisconsin Airport</td>
    </tr>
    <tr>
        <td>ORD</td>
        <td>Chicago O'Hare</td>
    </tr>
    <tr>
        <td>LHR</td>
        <td>London Heathrow</td>
    </tr>
</table>

<button id="color1">Select Red</button>
<button id="color2">Select aqua</button>

</body>
</html>


问:
"a"+'b'+"c",What does two double quotes and one single quote combination mean in mysql
For example

SELECT "hello"'jacky'"hi" as value from dual;

the result is hellojackyhi

But it confuse me that the use of this pattern "a"+'b'+"c".

What does this pattern exactly mean?It's a use of double quotes and single quote, is it mean I can always combine 3 string using this pattern "a"+'b'+"c"?

答:
MySQL has a "feature" where it concatenates strings that are adjacent (and separated by a space):

```<code>select 'a' 'b' 'c'
---> abc
</code>```

This works for both single quotes and double quotes.  Of course, double quotes might also be a column name.

So, this is a short-cut for string concatenation.  I strongly recommend that you use CONCAT() instead, so the intention is clear.

Body:
MySQL has a "feature" where it concatenates strings that are adjacent (and separated by a space):

select 'a' 'b' 'c'
---> abc

This works for both single quotes and double quotes.  Of course, double quotes might also be a column name.

So, this is a short-cut for string concatenation.  I strongly recommend that you use CONCAT() instead, so the intention is clear.


问:
Wordpress Insert post create tne meta key and meta value
I am creating wp_insert_post to create post from json, while creating post i need to create meta values i have tried both add_post_meta and update_post_meta no results Can anybody help

foreach ( $response->data as $single_data ) {

```<code>$post_title    = $single_data->name;
$video_id = $single_data->uri;
$thumnbnail_url = $single_data->pictures->sizes[4]->link;

if (!post_exists($post_title)) { // Determine if a post exists based on title, content, and date
    $post_id = wp_insert_post(array(
        'post_type'  => 'vimeo_videos',
        'post_title' => $post_title,
        'post_status' => 'publish',
     ));

}
$newPostID = wp_insert_post($post_id);

global $post;

add_post_meta( $post->ID, 'vimeo_video_thumnbnail_url_key', $thumnbnail_url, true );
update_post_meta( $newPostID, 'video_url_id', $video_id );
</code>```

答:
You're using wp_insert_post twice which does not make sense. The first wp_insert_post is correct and will return the $post_id of the created post upon success. However, your

```<code>$newPostID = wp_insert_post($post_id);
</code>```

is totally wrong and will always store 0 as a result in $newPostID, regardless of whether the post existed beforehand or not since $post_id will never contain a valid post array. What you want is to get the ID of the existing post (which post_exists already returns if successful). Change your code like so:

```<code>$existingPostID = post_exists($post_title);
if (!$existingPostID) {
    $existingPostID = wp_insert_post(array(
        'post_type'  => 'vimeo_videos',
        'post_title' => $post_title,
        'post_status' => 'publish',
     ));
}
if ($existingPostID) {
  update_post_meta( $existingPostID, 'video_url_id', $video_id );
}

</code>```

Body:
I am creating wp_insert_post to create post from json, while creating post i need to create meta values i have tried both add_post_meta and update_post_meta no results Can anybody help

foreach ( $response->data as $single_data ) {

$post_title    = $single_data->name;
$video_id = $single_data->uri;
$thumnbnail_url = $single_data->pictures->sizes[4]->link;

if (!post_exists($post_title)) { // Determine if a post exists based on title, content, and date
    $post_id = wp_insert_post(array(
        'post_type'  => 'vimeo_videos',
        'post_title' => $post_title,
        'post_status' => 'publish',
     ));

}
$newPostID = wp_insert_post($post_id);

global $post;

add_post_meta( $post->ID, 'vimeo_video_thumnbnail_url_key', $thumnbnail_url, true );
update_post_meta( $newPostID, 'video_url_id', $video_id );

Body:
You're using wp_insert_post twice which does not make sense. The first wp_insert_post is correct and will return the $post_id of the created post upon success. However, your

$newPostID = wp_insert_post($post_id);

is totally wrong and will always store 0 as a result in $newPostID, regardless of whether the post existed beforehand or not since $post_id will never contain a valid post array. What you want is to get the ID of the existing post (which post_exists already returns if successful). Change your code like so:

$existingPostID = post_exists($post_title);
if (!$existingPostID) {
    $existingPostID = wp_insert_post(array(
        'post_type'  => 'vimeo_videos',
        'post_title' => $post_title,
        'post_status' => 'publish',
     ));
}
if ($existingPostID) {
  update_post_meta( $existingPostID, 'video_url_id', $video_id );
}


问:
Playing movie in iOS applicatione made in Flex
I'm writing the application for iOS in Flex (sdk 4.5). Is it possible to play movie in such built application?

I was trying to use Video component - which works well on my desktop, but it doesn't work on my iPod. Of course my application is running, but the video isn't playing.

答:
I think I have final results:
It is possible to play video in iOS app written for AIR 2.6 but it can't be decoded by using h.264 video and acc audio codecs.

For me it was working when video was decoded by using vp6 codec and standard Video component. There is an issue with low frame rate which can be partially resolved when setting renderMode to gpu in descriptor file, however as you can see here it's not recommended.

P.S. Thanks for help J_A_X.


问:
How to change chars between 2 strings?
I want to change a char in a String with another in second String, the distance is 3.

For example:

String s1:abc,
String s2:abcdef->s2 will be abadef then -> abadeb.

If it is possible all chars from first String should goes to second s2. I have to mention that upperCase letters from the first should be lowerCase, and only letters will be taken from the first String. I know Strings are immutable

```<code>public static void Encrypt(String s1, String s2) {
        s1 = s1.toLowerCase();
        StringBuilder finalS2 = new StringBuilder();
        finalS2.append(s2);

        for (int i = 0; i < finalS2.length(); i++) {

            if (s1.charAt(i) >= 'a' && s1.charAt(i) <= 'z') {

                finalS2.setCharAt(i + 2, s1.charAt(0));

                break;
            }
        }

        System.out.println(finalS2);
    }
</code>```

I think in my method, which I don't think is a good idea, I should place another for loop for s1 and a break somewhere. I tried many methods, with charArray, etc. but didn't managed.

答:
So you want to take the original text of s2 and replace every third character with characters from s1:

```<code>s1: abc
    ││└───── ignored
    │└───┐
    └─┐  │
s2: abcdef
</code>```

Best way to do incremental single-char replacements like that is to get the char[] of the original string (s2), replace the appropriate characters, then build the resultant string from that.

```<code>public static String encrypt(String s1, String s2) {
    char[] buf = s2.toCharArray();
    for (int i = 0, j = 2; i < s1.length() && j < buf.length; i++, j += 3) {
        buf[j] = Character.toLowerCase(s1.charAt(i));
    }
    return new String(buf);
}
</code>```

Test

```<code>System.out.println(encrypt("abc", "abcdef"));
</code>```

Output

abadeb
```

<p>If you want the code to handle characters from the Unicode supplemental planes, e.g. emojis, then you need to work with code points.</p>

<p>You also mentioned that you only want letters from <code>s1</code>, so we'll add that to the next version <em>(<code>codePoints()</code> requires Java 9+)</em>.</p>

```public static String encrypt(String s1, String s2) {
    int[] c1 = s1.codePoints().toArray();
    int[] c2 = s2.codePoints().toArray();
    for (int i = 0, j = 2; i < c1.length && j < c2.length; i++) {
        if (Character.isLetter(c1[i])) {
            c2[j] = Character.toLowerCase(c1[i]);
            j += 3;
        }
    }
    return new String(c2, 0, c2.length);
}
```

<p><em>Test</em></p>

```System.out.println(encrypt("abc", "abcdef"));
System.out.println(encrypt("ace", "acegikm"));
```

<p><em>Output</em></p>

<pre class="lang-none prettyprint-override"><code>abadeb
aaecgekm
</code>```

As you can see, emoji characters in s1 are skipped, since they are not "letters", and emojis in s2 are correctly replaced. Even though  takes up 2 char positions in s2, it is correct replaced by c, a single char value.

Title: How to change chars between 2 strings?

Body:
I want to change a char in a String with another in second String, the distance is 3.

For example:

String s1:abc,
String s2:abcdef->s2 will be abadef then -> abadeb.

If it is possible all chars from first String should goes to second s2. I have to mention that upperCase letters from the first should be lowerCase, and only letters will be taken from the first String. I know Strings are immutable

public static void Encrypt(String s1, String s2) {
        s1 = s1.toLowerCase();
        StringBuilder finalS2 = new StringBuilder();
        finalS2.append(s2);

        for (int i = 0; i < finalS2.length(); i++) {

            if (s1.charAt(i) >= 'a' && s1.charAt(i) <= 'z') {

                finalS2.setCharAt(i + 2, s1.charAt(0));

                break;
            }
        }

        System.out.println(finalS2);
    }

I think in my method, which I don't think is a good idea, I should place another for loop for s1 and a break somewhere. I tried many methods, with charArray, etc. but didn't managed.

Body:
So you want to take the original text of s2 and replace every third character with characters from s1:

s1: abc
    ││└───── ignored
    │└───┐
    └─┐  │
s2: abcdef

Best way to do incremental single-char replacements like that is to get the char[] of the original string (s2), replace the appropriate characters, then build the resultant string from that.

public static String encrypt(String s1, String s2) {
    char[] buf = s2.toCharArray();
    for (int i = 0, j = 2; i < s1.length() && j < buf.length; i++, j += 3) {
        buf[j] = Character.toLowerCase(s1.charAt(i));
    }
    return new String(buf);
}

Test

System.out.println(encrypt("abc", "abcdef"));

Output

abadeb

If you want the code to handle characters from the Unicode supplemental planes, e.g. emojis, then you need to work with code points.

You also mentioned that you only want letters from s1, so we'll add that to the next version (codePoints() requires Java 9+).

public static String encrypt(String s1, String s2) {
    int[] c1 = s1.codePoints().toArray();
    int[] c2 = s2.codePoints().toArray();
    for (int i = 0, j = 2; i < c1.length && j < c2.length; i++) {
        if (Character.isLetter(c1[i])) {
            c2[j] = Character.toLowerCase(c1[i]);
            j += 3;
        }
    }
    return new String(c2, 0, c2.length);
}

Test

System.out.println(encrypt("abc", "abcdef"));
System.out.println(encrypt("ace", "acegikm"));

Output

abadeb
aaecgekm

As you can see, emoji characters in s1 are skipped, since they are not "letters", and emojis in s2 are correctly replaced. Even though  takes up 2 char positions in s2, it is correct replaced by c, a single char value.