问:
Comparing referenced internal struct field to string type in go
Say I have two structs that define a linked list:

```<code>....
....

type node struct {
    item interface{}
    next *node
}

type LinkedList struct {
    first *node
    N int
}

...
...

</code>```

and I want to compare the value of the type of the underlying node, say, in a find function where we check if k == node.item such that:

```<code>func (l *LinkedList) find (key interface{}) bool {

    result := false
    if !l.isEmpty() {
        for x:= l.first; x != nil; x = x.next {
            if x.item == key {
                result = true
                break
            }
        }
    return result
}

</code>```

this will not work for the expected find function because the underlying types are different, hence the func will always return false. We can confirm this upon reflecting the type:

```<code>fmt.Println(reflect.TypeOf(key), reflect.TypeOf(x.item))
>>> string, *main.node
</code>```

Tried workarounds?

I've tried asserting the type but alas this does not work and panics

tmp := x.item.(string)
>>>panic: interface conversion: interface {} is *main.node, not string
```

<p>This case is the same for using <code>fmt.Sprintf(x.item)</code></p>

<p>I'm a bit stumped as to where to go from here. Is there a way to do this? </p>

<p><strong>Inserting item to linked list</strong>
The following snippet should clarify how insertion is handled</p>

```func (l *LinkedList) insertFirst(item interface{}) {
    var first *node = new(node)
    oldfirst := l.first
    first.item = item
    first.next = oldfirst
    l.first = first
    l.N++
}

.....
//which gets called somewhere like
var n *node = new(node)
n.item = item
l.insertFirst(n)

.....wait no theres the error!
----------

```

burak-serdar you are 100% correct that I am inserting the node in the node!

答: The interface comparison in find() is a valid comparison and it will work if the type of the key and the type of the value stored in the node are the same. However, evidence points to you adding a node in place of a value.

Body:
Say I have two structs that define a linked list:

....
....

type node struct {
    item interface{}
    next *node
}

type LinkedList struct {
    first *node
    N int
}

...
...

and I want to compare the value of the type of the underlying node, say, in a find function where we check if k == node.item such that:

func (l *LinkedList) find (key interface{}) bool {

    result := false
    if !l.isEmpty() {
        for x:= l.first; x != nil; x = x.next {
            if x.item == key {
                result = true
                break
            }
        }
    return result
}

this will not work for the expected find function because the underlying types are different, hence the func will always return false. We can confirm this upon reflecting the type:

fmt.Println(reflect.TypeOf(key), reflect.TypeOf(x.item))
>>> string, *main.node

Tried workarounds?

I've tried asserting the type but alas this does not work and panics

tmp := x.item.(string)
>>>panic: interface conversion: interface {} is *main.node, not string

This case is the same for using fmt.Sprintf(x.item)

I'm a bit stumped as to where to go from here. Is there a way to do this?

Inserting item to linked list
The following snippet should clarify how insertion is handled

func (l *LinkedList) insertFirst(item interface{}) {
    var first *node = new(node)
    oldfirst := l.first
    first.item = item
    first.next = oldfirst
    l.first = first
    l.N++
}

.....
//which gets called somewhere like
var n *node = new(node)
n.item = item
l.insertFirst(n)

.....wait no theres the error!
----------

burak-serdar you are 100% correct that I am inserting the node in the node!


来源: stackexchange

问:
Why are Slice Labels disabled when changing Title/SubTitle in Google Sheets?
Earlier it was pointed out to me how to change a title or subtitle in a 3D pie chart with a pieHole and have the title remain as a floating text box.

One of the unpleasant side effects of this was the removal of the slice labels, that is from this

to this

The code I'm using for this is

```<code>function UpdateSubTitleAdvanced(sheetName, chartId, newTitle) {
  const active = SpreadsheetApp.getActiveSpreadsheet();
  const ssId = active.getId();
  const sheets = Sheets.Spreadsheets.get(ssId).sheets;
  for (let s in sheets) {
    let sheet = sheets[s];
    if (sheet.properties.title === sheetName) {
      for (let c in sheet.charts) {
        let chart = sheet.charts[c];
        if (chart.chartId === chartId) {
          Logger.log("Sheet %s, Chart %s, Title '%s', SubTitle '%s'", sheet.properties.title, String(chart.chartId), chart.spec.title, chart.spec.subtitle);
          delete chart.position;
          chart.spec.subtitle = newTitle;
          Sheets.Spreadsheets.batchUpdate({requests:[{updateChartSpec: chart}]}, ssId);
        }
      }
    }
  }
}

function _UpdateSubTitle() {
  UpdateSubTitleAdvanced("Group0",713335354,"### new sub title");
}
</code>```

There doesn't appear to be anything in the code that explicitly knobbles the slice labels. Nor is there much of anything in the documentation regarding how to put them back.

I have had some success in capturing the HAR of the browser session and extracting the JSON structure describing the graphic.

```<code>{
    "chartType": "PieChart",
    "options": {
        "pieSliceTextStyle": {
            "fontSize": 10
        },
        "legend": "none",
        "annotations": {
            "total": {
                "textStyle": {}
            },
            "domain": {
                "textStyle": {}
            }
        },
        "is3D": true,
        "title": "### new sub title",
        "titleTextStyle": {
            "fontName": "serif",
            "alignment": "center"
        },
        "pieSliceText": "label",
        "fontName": "serif",
        "legendTextStyle": {},
        "pieHole": 0.5,
        "bubble": {
            "textStyle": {}
        },
        "useFirstColumnAsDomain": true,
        "subtitleTextStyle": {
            "fontName": "sans-serif",
            "color": "#000000",
            "fontSize": 16,
            "bold": true,
            "alignment": "center"
        },
        "subtitle": "influencer marketing",
        "width": 600,
        "textStyle": {
            "fontName": "serif"
        },
        "chartArea": {
            "top": "1.8585131894484377%",
            "left": "1.4962121212121169%",
            "width": "98.50378787878789%",
            "height": "96.88249400479617%"
        },
        "height": 371
    },
    "initialView": {}
}
</code>```

I haven't tried changing any of them programmatically as yet.

What can be done here? I want to achieve the following:

Keep the title or subtitle box movable.

Keep the slices named.

Find a way to have the title or subtitle centred in the image.

Keep the image maximised within the chart frame (the images would seem to indicate that the above code affects the image size.)

答:
How about this answer?

Current issue:

The reason of this issue is that in the current stage, the property of "Slice label" is not included in the object retrieved by the method of "spreadsheets.get" in Sheets API. This can be seen at the following object of the chart. This object is retrieved by the method of "spreadsheets.get" in Sheets API.

```<code>{
  "chartId": ###,
  "spec": {
    "title": "sample title",
    "pieChart": {
      "legendPosition": "LABELED_LEGEND",
      "domain": {
        "sourceRange": {
          "sources": [
            {
              "sheetId": ###,
              "startRowIndex": 0,
              "endRowIndex": 5,
              "startColumnIndex": 0,
              "endColumnIndex": 1
            }
          ]
        }
      },
      "series": {
        "sourceRange": {
          "sources": [
            {
              "sheetId": ###,
              "startRowIndex": 0,
              "endRowIndex": 5,
              "startColumnIndex": 1,
              "endColumnIndex": 2
            }
          ]
        }
      },
      "threeDimensional": true,
      "pieHole": 0.5
    },
    "hiddenDimensionStrategy": "SKIP_HIDDEN_ROWS_AND_COLUMNS",
    "titleTextFormat": {
      "fontFamily": "Roboto"
    },
    "fontName": "Roboto"
  },
  "position": {
    "overlayPosition": {
      "anchorCell": {
        "sheetId": ###,
        "rowIndex": 1,
        "columnIndex": 1
      },
      "offsetXPixels": 69,
      "offsetYPixels": 17,
      "widthPixels": 600,
      "heightPixels": 371
    }
  }
}
</code>```

From above chart object, it is found that the property of "Slice label" is not included. By this, when the chart is updated using the retrieved values from the chart, "Slice label" is removed. And also, "UpdateChartSpecRequest" has no property for setting "Slice label" yet. By this, the workaround cannot be used yet.

And also, about the last your 4 requests, in the current stage, these are not included in the chart object of both the method of "spreadsheets.get" and "UpdateChartSpecRequest".

Unfortunately, these are the current specification at Google side. The Sheets API is growing now. So I believe that these properties will be added in the future update.

Future:

I thought that the reason of such issue is due to that "updateChartSpec" was not updated with fields property. When fields property could be used, for example, only the chart title can be updated. By this, even when the property of "Slice label" is not included in the current "UpdateChartSpecRequest", only the chart title can be updated. In this case, your current issue will not occur. So I have already reported this as the future request at the issue tracker at May 28, 2020. Ref And that has already been accepted. So I think that Google might modify this in the near future.

Reference:

UpdateChartSpecRequest

ContentLicense: CC BY-SA 4.0

Body:
Earlier it was pointed out to me how to change a title or subtitle in a 3D pie chart with a pieHole and have the title remain as a floating text box.

One of the unpleasant side effects of this was the removal of the slice labels, that is from this

to this

The code I'm using for this is

function UpdateSubTitleAdvanced(sheetName, chartId, newTitle) {
  const active = SpreadsheetApp.getActiveSpreadsheet();
  const ssId = active.getId();
  const sheets = Sheets.Spreadsheets.get(ssId).sheets;
  for (let s in sheets) {
    let sheet = sheets[s];
    if (sheet.properties.title === sheetName) {
      for (let c in sheet.charts) {
        let chart = sheet.charts[c];
        if (chart.chartId === chartId) {
          Logger.log("Sheet %s, Chart %s, Title '%s', SubTitle '%s'", sheet.properties.title, String(chart.chartId), chart.spec.title, chart.spec.subtitle);
          delete chart.position;
          chart.spec.subtitle = newTitle;
          Sheets.Spreadsheets.batchUpdate({requests:[{updateChartSpec: chart}]}, ssId);
        }
      }
    }
  }
}

function _UpdateSubTitle() {
  UpdateSubTitleAdvanced("Group0",713335354,"### new sub title");
}

There doesn't appear to be anything in the code that explicitly knobbles the slice labels. Nor is there much of anything in the documentation regarding how to put them back.

I have had some success in capturing the HAR of the browser session and extracting the JSON structure describing the graphic.

{
    "chartType": "PieChart",
    "options": {
        "pieSliceTextStyle": {
            "fontSize": 10
        },
        "legend": "none",
        "annotations": {
            "total": {
                "textStyle": {}
            },
            "domain": {
                "textStyle": {}
            }
        },
        "is3D": true,
        "title": "### new sub title",
        "titleTextStyle": {
            "fontName": "serif",
            "alignment": "center"
        },
        "pieSliceText": "label",
        "fontName": "serif",
        "legendTextStyle": {},
        "pieHole": 0.5,
        "bubble": {
            "textStyle": {}
        },
        "useFirstColumnAsDomain": true,
        "subtitleTextStyle": {
            "fontName": "sans-serif",
            "color": "#000000",
            "fontSize": 16,
            "bold": true,
            "alignment": "center"
        },
        "subtitle": "influencer marketing",
        "width": 600,
        "textStyle": {
            "fontName": "serif"
        },
        "chartArea": {
            "top": "1.8585131894484377%",
            "left": "1.4962121212121169%",
            "width": "98.50378787878789%",
            "height": "96.88249400479617%"
        },
        "height": 371
    },
    "initialView": {}
}

I haven't tried changing any of them programmatically as yet.

What can be done here? I want to achieve the following:

Keep the title or subtitle box movable.

Keep the slices named.

Find a way to have the title or subtitle centred in the image.

Keep the image maximised within the chart frame (the images would seem to indicate that the above code affects the image size.)

Body:
How about this answer?

Current issue:

The reason of this issue is that in the current stage, the property of "Slice label" is not included in the object retrieved by the method of "spreadsheets.get" in Sheets API. This can be seen at the following object of the chart. This object is retrieved by the method of "spreadsheets.get" in Sheets API.

{
  "chartId": ###,
  "spec": {
    "title": "sample title",
    "pieChart": {
      "legendPosition": "LABELED_LEGEND",
      "domain": {
        "sourceRange": {
          "sources": [
            {
              "sheetId": ###,
              "startRowIndex": 0,
              "endRowIndex": 5,
              "startColumnIndex": 0,
              "endColumnIndex": 1
            }
          ]
        }
      },
      "series": {
        "sourceRange": {
          "sources": [
            {
              "sheetId": ###,
              "startRowIndex": 0,
              "endRowIndex": 5,
              "startColumnIndex": 1,
              "endColumnIndex": 2
            }
          ]
        }
      },
      "threeDimensional": true,
      "pieHole": 0.5
    },
    "hiddenDimensionStrategy": "SKIP_HIDDEN_ROWS_AND_COLUMNS",
    "titleTextFormat": {
      "fontFamily": "Roboto"
    },
    "fontName": "Roboto"
  },
  "position": {
    "overlayPosition": {
      "anchorCell": {
        "sheetId": ###,
        "rowIndex": 1,
        "columnIndex": 1
      },
      "offsetXPixels": 69,
      "offsetYPixels": 17,
      "widthPixels": 600,
      "heightPixels": 371
    }
  }
}

From above chart object, it is found that the property of "Slice label" is not included. By this, when the chart is updated using the retrieved values from the chart, "Slice label" is removed. And also, "UpdateChartSpecRequest" has no property for setting "Slice label" yet. By this, the workaround cannot be used yet.

And also, about the last your 4 requests, in the current stage, these are not included in the chart object of both the method of "spreadsheets.get" and "UpdateChartSpecRequest".

Unfortunately, these are the current specification at Google side. The Sheets API is growing now. So I believe that these properties will be added in the future update.

Future:

I thought that the reason of such issue is due to that "updateChartSpec" was not updated with fields property. When fields property could be used, for example, only the chart title can be updated. By this, even when the property of "Slice label" is not included in the current "UpdateChartSpecRequest", only the chart title can be updated. In this case, your current issue will not occur. So I have already reported this as the future request at the issue tracker at May 28, 2020. Ref And that has already been accepted. So I think that Google might modify this in the near future.

Reference:

UpdateChartSpecRequest


问:
.Net string parsing library, or regex for parsing .Net code files
I would like to be able to parse vb.net code files, so I can examine the collection of Subs, Functions (and their contents, including comments), private variables, etc.

I can be open the actual source code files.

So for example, if I have:

```<code>Public Function FunctionOne(arg1 As String, arg2 as String) as Integer
   here is some code
   ''//here are some comments
End Function

Public Sub FunctionOne(arg1 As integer, arg2 as integer)
   here is some code
   ''//here are some comments
End Sub
</code>```

I would like to be able to parse out all of the subs and functions and all of the code between the Public Function and End Function (actually, it would be nice to have the option to either include just the code within, or the entire function definition.

This would seem to call for some sort of a parsing library, or else fairly decent regex skills.

Any suggestions?

UPDATE:
The main thing I'm trying to achieve is the parsing of the source code, so reflection is just fine perhaps for getting the list of functions and what not and I know how to do that, but it is a proper way of parsing the source code I am trying to figure out.

答:
This code is crude but more or less accomplishes what I was intending to do:  </p>

```<code>Private _SourceCode As String = Nothing
Private ReadOnly Property SourceCode() As String
                Get
                    If _SourceCode = Nothing Then
                        Dim thisCodeFile As String = Server.MapPath("~").ToString & "\" & Type.GetType(Me.GetType.BaseType.FullName).ToString & ".aspx.vb"
                        _SourceCode = My.Computer.FileSystem.ReadAllText(thisCodeFile)
                    End If
                    Return _SourceCode
                End Get
End Property

Private Function extractProcedureDefinition(ByVal procedureName As String) As String
   Return extractStringContents(Me.SourceCode, "Sub " & procedureName & "()", "End Sub", True)
End Function

Private Function extractFunctionDefinition(ByVal procedureName As String) As String
   'TODO: This works now, but wouldn't if we wanted includeTags = False, as it does not properly handle the "As xxxxx" portion
   Return extractStringContents(Me.SourceCode, "Function " & procedureName, "End Sub", True)
End Function

    Private Function extractStringContents(ByVal body As String, ByVal openTag As String, ByVal closeTag As String, ByVal includeTags As Boolean) As String
                Dim iStart As Integer = body.IndexOf(openTag)
                Dim iEnd As Integer = body.IndexOf(closeTag, iStart)
                If includeTags Then
                    iEnd += closeTag.Length
                Else
                    iStart += openTag.Length
                End If
                Return body.Substring(iStart, iEnd - iStart)
    End Function
</code>```

OwnerDisplayName: tbone

ContentLicense: CC BY-SA 2.5

Body:
I would like to be able to parse vb.net code files, so I can examine the collection of Subs, Functions (and their contents, including comments), private variables, etc.

I can be open the actual source code files.

So for example, if I have:

Public Function FunctionOne(arg1 As String, arg2 as String) as Integer
   here is some code
   ''//here are some comments
End Function

Public Sub FunctionOne(arg1 As integer, arg2 as integer)
   here is some code
   ''//here are some comments
End Sub

I would like to be able to parse out all of the subs and functions and all of the code between the Public Function and End Function (actually, it would be nice to have the option to either include just the code within, or the entire function definition.

This would seem to call for some sort of a parsing library, or else fairly decent regex skills.

Any suggestions?

UPDATE:
The main thing I'm trying to achieve is the parsing of the source code, so reflection is just fine perhaps for getting the list of functions and what not and I know how to do that, but it is a proper way of parsing the source code I am trying to figure out.

LastEditorDisplayName: Iraimbilanja

Body:
This code is crude but more or less accomplishes what I was intending to do:

Private _SourceCode As String = Nothing
Private ReadOnly Property SourceCode() As String
                Get
                    If _SourceCode = Nothing Then
                        Dim thisCodeFile As String = Server.MapPath("~").ToString & "\" & Type.GetType(Me.GetType.BaseType.FullName).ToString & ".aspx.vb"
                        _SourceCode = My.Computer.FileSystem.ReadAllText(thisCodeFile)
                    End If
                    Return _SourceCode
                End Get
End Property

Private Function extractProcedureDefinition(ByVal procedureName As String) As String
   Return extractStringContents(Me.SourceCode, "Sub " & procedureName & "()", "End Sub", True)
End Function

Private Function extractFunctionDefinition(ByVal procedureName As String) As String
   'TODO: This works now, but wouldn't if we wanted includeTags = False, as it does not properly handle the "As xxxxx" portion
   Return extractStringContents(Me.SourceCode, "Function " & procedureName, "End Sub", True)
End Function

    Private Function extractStringContents(ByVal body As String, ByVal openTag As String, ByVal closeTag As String, ByVal includeTags As Boolean) As String
                Dim iStart As Integer = body.IndexOf(openTag)
                Dim iEnd As Integer = body.IndexOf(closeTag, iStart)
                If includeTags Then
                    iEnd += closeTag.Length
                Else
                    iStart += openTag.Length
                End If
                Return body.Substring(iStart, iEnd - iStart)
    End Function


问:
Django non-rel - how do I install it?
As a new python and django developer, I'm creating a Django app on Google app engine.

Today I realized GAE helper did not support model formsets - after some research, I understand Django non-rel  is the best helper patch for Django _ GAE

So I downloaded it : but I cannot find instructions on how to install it - I've spend over an hour searching and searching - but there is no instructions!!!

I even found instructions on installing Django on non-rel download but not of non-rel -

How do I install Django non-rel?

do I need Django 1.3 - if so how can I install 1.3 in a way that I can deploy it to GAE since GAE has Django 1.2 native?

答:
Yes, the instructions are a little hidden and you can not find it via django-nonrel for some reason. Look for django-appengine instead. Check this tutorial about django-appengine. There you will also find all the installation instructions, how to use it and what to keep in mind when using it.

And about your specific question (1). You must use the modified Django 1.3 version of django-appengine (everything described in the link above). Don't use the official Django version. Also it must be in your project directory to work properly with GAE.

ContentLicense: CC BY-SA 3.0

Title: Django non-rel - how do I install it?


问:
Can't override target-specific variable
I have such Makefile:

```<code>print: var1=inside

print:
    @echo $(var1)
</code>```

When I run var1=outside make -e print. I expected to see:

```<code>outside
</code>```

Because of:

Variables provided on the command line (and in the environment if the ‘-e’ option is in force) will take precedence.

But I get:

```<code>inside
</code>```

Is it a correct output?

答:
It is expected; whether or not it's correct I guess depends on who you ask.

The -e option is in effect for "global" variables in makefiles, but target-specific variables take precedence over globally-scoped variables.

Personally I think -e was a mistake and never should have existed.  But, you know, POSIX and all.  Even though it exists I recommend that it be avoided.  It's far, far too easy to completely mess up your build in confusing and surprising ways.

ETA Well, maybe it's not expected.  Maybe it is a bug.  Where did you get that quote you provided?  With just that sentence from a 225-page document it's hard to say... a link or at least a section name would be helpful.

Title: Can't override target-specific variable

Body:
I have such Makefile:

print: var1=inside

print:
    @echo $(var1)

When I run var1=outside make -e print. I expected to see:

outside

Because of:

Variables provided on the command line (and in the environment if the ‘-e’ option is in force) will take precedence.

But I get:

inside

Is it a correct output?


问:
Indexing with pointers - How pointer works with slices?
In the below main() code:

```<code>package main

import (
    "fmt"

    "github.com/myhub/cs61a/poetry"
)

func main() {

    p := poetry.NewPoem([][]string{
        {
            "And from my pillow, looking forth by light",
            "Of moon or favoring stars, I could behold",
            "The antechapel where the statue stood",
            "Of Newton, with his prism and silent face,",
            "The marble index of a mind forever",
            "Voyaging through strange seas of thought, alone.",
        },
        {
            "inducted into Greek and Christian",
            "modes of thinking, must take a longer way around.",
            "Like children born into love, they exult in the here",
            "who have felt separation and grave misgivings, they",
            "and of humanity, and of God. Great literature, like",
            "struggles to reconcile suffering with faith in the ",
        },
    })

    fmt.Printf("%T\n", p[0])

}
</code>```

p[0] works fine by pointing to first stanza using below function constructor:

```<code>package poetry

type Line string
type Stanza []Line
type Poem []Stanza

func NewPoem(s [][]string) Poem {
    var poem Poem
    for _, stanza := range s {
        var newStanza Stanza
        for _, line := range stanza {
            newStanza = append(newStanza, Line(line))
        }
        poem = append(poem, newStanza)
    }

    return poem
}
</code>```

If, NewPoem() returns value of type *Poem, as shown below:

```<code>package poetry

type Line string
type Stanza []Line
type Poem []Stanza

func NewPoem(s [][]string) *Poem {
    var poem Poem
    for _, stanza := range s {
        var newStanza Stanza
        for _, line := range stanza {
            newStanza = append(newStanza, Line(line))
        }
        poem = append(poem, newStanza)
    }

    return &poem
}
</code>```

then, p[0] in main() gives below error:

```<code>     Invalid operation: p[0] (type *poetry.Poem does not support indexing)
</code>```

Why pointer to slice of slice of strings does not support p[0] syntax?

答:
Why pointer to slice of slice of strings does not support p[0] syntax?

Because a pointer to a slice of (anything) is not a type that the language defines to support indexing. Here's the spec:

A primary expression of the form a[x] denotes the element of the array, pointer to array, slice, string or map a indexed by x. The value x is called the index or map key, respectively. The following rules apply:

Source: https://golang.org/ref/spec#Index_expressions

It goes on and explicitly defines how indexing works for each of the supported types, and ends by saying that Otherwise a[x] is illegal.

So basically you're trying to do something that the language doesn't allow.

As for why, and talking a bit about your design, pointers to slices rarely make sense.

First, when you pass a slice around, the amount of data moving is absolutely minimal (it's just a slice header, which is generally a dozen bytes), so there's no visible gain compared to passing a pointer.

Then, in your comments in the question you say, "it looks as a better abstraction to provide a pointer to Poem type." It really depends on what you want to do with the type Poem. With the few details you gave, I'd argue that it's actually a worse design choice to pass *Poem around rather than just Poem, since you gain nothing with the pointer, and you actually complicate things. For example, you can't use indexing (p[0])...

In a comment to this answser, you asked: do you see [][]string{...} passing to NewPoem() a good approach?.

Like I mentioned in a comment, we don't have a lot of details, so it's hard to say. But currently, you can do this to create a Poem:

```<code>p := poetry.Poem{
    {
        "And from my pillow, looking forth by light",
        "Of moon or favoring stars, I could behold",
        "The antechapel where the statue stood",
        "Of Newton, with his prism and silent face,",
        "The marble index of a mind forever",
        "Voyaging through strange seas of thought, alone.",
    },
    {
        "inducted into Greek and Christian",
        "modes of thinking, must take a longer way around.",
        "Like children born into love, they exult in the here",
        "who have felt separation and grave misgivings, they",
        "and of humanity, and of God. Great literature, like",
        "struggles to reconcile suffering with faith in the ",
    },
}

fmt.Printf("%T\n", p[0])
</code>```

No need for loops or appends or a NewPoem function or anything to create a Poem directly from strings. Just use the type Poem{...} directly!

If you need to do something different like creating a Poem by reading data from, say, a file, you could maybe create a function like this instead:

```<code>package poetry

func ReadFrom(rd io.Reader) Poem { ... }
</code>```

But for simply creating a Poem in the code, directly, there's no need to complicate things.

Body:
In the below main() code:

package main

import (
    "fmt"

    "github.com/myhub/cs61a/poetry"
)

func main() {

    p := poetry.NewPoem([][]string{
        {
            "And from my pillow, looking forth by light",
            "Of moon or favoring stars, I could behold",
            "The antechapel where the statue stood",
            "Of Newton, with his prism and silent face,",
            "The marble index of a mind forever",
            "Voyaging through strange seas of thought, alone.",
        },
        {
            "inducted into Greek and Christian",
            "modes of thinking, must take a longer way around.",
            "Like children born into love, they exult in the here",
            "who have felt separation and grave misgivings, they",
            "and of humanity, and of God. Great literature, like",
            "struggles to reconcile suffering with faith in the ",
        },
    })

    fmt.Printf("%T\n", p[0])

}

p[0] works fine by pointing to first stanza using below function constructor:

package poetry

type Line string
type Stanza []Line
type Poem []Stanza

func NewPoem(s [][]string) Poem {
    var poem Poem
    for _, stanza := range s {
        var newStanza Stanza
        for _, line := range stanza {
            newStanza = append(newStanza, Line(line))
        }
        poem = append(poem, newStanza)
    }

    return poem
}

If, NewPoem() returns value of type *Poem, as shown below:

package poetry

type Line string
type Stanza []Line
type Poem []Stanza

func NewPoem(s [][]string) *Poem {
    var poem Poem
    for _, stanza := range s {
        var newStanza Stanza
        for _, line := range stanza {
            newStanza = append(newStanza, Line(line))
        }
        poem = append(poem, newStanza)
    }

    return &poem
}

then, p[0] in main() gives below error:

     Invalid operation: p[0] (type *poetry.Poem does not support indexing)

Why pointer to slice of slice of strings does not support p[0] syntax?

Body:
Why pointer to slice of slice of strings does not support p[0] syntax?

Because a pointer to a slice of (anything) is not a type that the language defines to support indexing. Here's the spec:

A primary expression of the form a[x] denotes the element of the array, pointer to array, slice, string or map a indexed by x. The value x is called the index or map key, respectively. The following rules apply:

Source: https://golang.org/ref/spec#Index_expressions

It goes on and explicitly defines how indexing works for each of the supported types, and ends by saying that Otherwise a[x] is illegal.

So basically you're trying to do something that the language doesn't allow.

As for why, and talking a bit about your design, pointers to slices rarely make sense.

First, when you pass a slice around, the amount of data moving is absolutely minimal (it's just a slice header, which is generally a dozen bytes), so there's no visible gain compared to passing a pointer.

Then, in your comments in the question you say, "it looks as a better abstraction to provide a pointer to Poem type." It really depends on what you want to do with the type Poem. With the few details you gave, I'd argue that it's actually a worse design choice to pass *Poem around rather than just Poem, since you gain nothing with the pointer, and you actually complicate things. For example, you can't use indexing (p[0])...

In a comment to this answser, you asked: do you see [][]string{...} passing to NewPoem() a good approach?.

Like I mentioned in a comment, we don't have a lot of details, so it's hard to say. But currently, you can do this to create a Poem:

p := poetry.Poem{
    {
        "And from my pillow, looking forth by light",
        "Of moon or favoring stars, I could behold",
        "The antechapel where the statue stood",
        "Of Newton, with his prism and silent face,",
        "The marble index of a mind forever",
        "Voyaging through strange seas of thought, alone.",
    },
    {
        "inducted into Greek and Christian",
        "modes of thinking, must take a longer way around.",
        "Like children born into love, they exult in the here",
        "who have felt separation and grave misgivings, they",
        "and of humanity, and of God. Great literature, like",
        "struggles to reconcile suffering with faith in the ",
    },
}

fmt.Printf("%T\n", p[0])

No need for loops or appends or a NewPoem function or anything to create a Poem directly from strings. Just use the type Poem{...} directly!

If you need to do something different like creating a Poem by reading data from, say, a file, you could maybe create a function like this instead:

package poetry

func ReadFrom(rd io.Reader) Poem { ... }

But for simply creating a Poem in the code, directly, there's no need to complicate things.


问:
julia implement convert for struct containing NTuple
I'm trying to implement a convert for struct containing NTuple:

```<code>import Base: convert

abstract type AbstractMyType{N, T} end

struct MyType1{N, T} <: AbstractMyType{N, T}
    data::NTuple{T, N}
end

struct MyType2{N, T} <: AbstractMyType{N, T}
    data::NTuple{T, N}
end

foo(::Type{MyType2}, x::AbstractMyType{N, T}) where {N, T} = x
convert(::Type{MyType2}, x::AbstractMyType{N, T}) where {N, T} = MyType2{T}(x.data)

println(foo(MyType2, MyType1((1,2,3))))         # MyType1{Int64,3}((1, 2, 3))
println(convert(MyType2, MyType1((1,2,3))))     # MethodError
</code>```

Defined functions foo and convert have the same signature. For some reason function foo returns normally while convert throws MethodError. Why Julia cannot find my convert method?

julia version 1.4.1

答:
Just define the method

```<code>convert(::Type{MyType2}, x::AbstractMyType{N, T}) where {N, T} = MyType2(x.data)
</code>```

Testing:

```<code>julia> convert(MyType2, MyType1((1,2,3)))
MyType2{Int64,3}((1, 2, 3))
</code>```

Body:
I'm trying to implement a convert for struct containing NTuple:

import Base: convert

abstract type AbstractMyType{N, T} end

struct MyType1{N, T} <: AbstractMyType{N, T}
    data::NTuple{T, N}
end

struct MyType2{N, T} <: AbstractMyType{N, T}
    data::NTuple{T, N}
end

foo(::Type{MyType2}, x::AbstractMyType{N, T}) where {N, T} = x
convert(::Type{MyType2}, x::AbstractMyType{N, T}) where {N, T} = MyType2{T}(x.data)

println(foo(MyType2, MyType1((1,2,3))))         # MyType1{Int64,3}((1, 2, 3))
println(convert(MyType2, MyType1((1,2,3))))     # MethodError

Defined functions foo and convert have the same signature. For some reason function foo returns normally while convert throws MethodError. Why Julia cannot find my convert method?

julia version 1.4.1

Body:
Just define the method

convert(::Type{MyType2}, x::AbstractMyType{N, T}) where {N, T} = MyType2(x.data)

Testing:

julia> convert(MyType2, MyType1((1,2,3)))
MyType2{Int64,3}((1, 2, 3))


问:
Parse Email Reply from Thread in Zapier
I'm looking at parsing out just the most recent reply/message from an email thread as part of a zap.

I've found this link but how to I use it within a Zap? https://github.com/zapier/email-reply-parser

i.e. when I pick up a thread from gmail how do I just extract the most recent message?

Is this possible in Code by Zapier and if so how?

E.g.

Input:

Yes that is fine, I will email you in the morning.

On Fri, Nov 16, 2012 at 1:48 PM, Zapier  wrote:

Our support team just commented on your open Ticket:
  "Hi Royce, can we chat in the morning about your question?"

Ouput: i.e. the parsed email:

Yes that is fine, I will email you in the morning.

答:
First off: it's not possible to use that in a code step directly. Python code steps don't have access to external packages.

That said, that package is just Python code, and there's nothing stopping you copying all of the important code into the Code step and using it that way.

It's worth noting that the linked code is pretty old and looks to be unmaintained, so it's unlikely to work without modifications.

Title: Parse Email Reply from Thread in Zapier


问:
Homework-C Programming- Recursive Program
Hey guys! I was assigned this program which was pretty simple and didn't take long to code, yet I can't get it to run. Nothing prints and I think it's because it goes into an endless loop. Just looking for a fix on this.

Assignment:

Write and test a recursive function
  that returns the value of the
  following recursive definition:

```<code>f(x) = 0        if x <= 0
f(x- 1) + 2       otherwise
</code>```

My program:

```<code>#include <stdio.h>
int main(void)
{
    int n, x;

    int factorial(int n) {

        if (x <= 0) {
            printf("x equals: ");
            return 1;
        } else {
            return n * factorial(n - 1); //error here
        }
        f(x) = f(x - 1) + 2;
    }
    return 0;
}
</code>```

答:
Am i seeing this incorrectly?
Why is there a

f(x)=f(x-1)+2;

in your int factorial function?

Body:
Hey guys! I was assigned this program which was pretty simple and didn't take long to code, yet I can't get it to run. Nothing prints and I think it's because it goes into an endless loop. Just looking for a fix on this.

Assignment:

Write and test a recursive function
  that returns the value of the
  following recursive definition:

f(x) = 0        if x <= 0
f(x- 1) + 2       otherwise

My program:

#include <stdio.h>
int main(void)
{
    int n, x;

    int factorial(int n) {

        if (x <= 0) {
            printf("x equals: ");
            return 1;
        } else {
            return n * factorial(n - 1); //error here
        }
        f(x) = f(x - 1) + 2;
    }
    return 0;
}


问:
JBAS015852: Could not index class module-info.class - Spring boot + Jboss 7.1.1
I am trying to deploy a simple Spring boot application on a Jboss 7.1.1.
I have made the corresponding settings, but the error continuously appears:
"JBAS015852: Could not index class module-info.class"

I made the following settings:

```<code>@SpringBootApplication
public class DemoApplication extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
    return application.sources(DemoApplication.class);
}

public static void main(String[] args) {
    SpringApplication.run(DemoApplication.class, args);
}

@RestController
class Hellocontroller {
    @RequestMapping("/hello")
    @GetMapping
    String hello() {
        return "Hola";
    }
}
</code>```

and in the pom.xml

```<code><dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
        <exclusions>
            <exclusion>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-tomcat</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
</code>```

but I have the following result

```<code>16:12:16,317 WARN  [org.jboss.as.server.deployment] (MSC service thread 1-4) JBAS015852: Could not index class org/hibernate/validator/spi/scripting/AbstractCachingScriptEvaluatorFactory.class at /C:/Users/User/Downloads/jboss-as-7.1.1.Final/jboss-as-7.1.1.Final/standalone/deployments/demo.war/WEB-INF/lib/hibernate-validator-6.0.19.Final.jar: java.lang.IllegalStateException: Unknown tag! pos=4 poolCount = 71
at org.jboss.jandex.Indexer.processConstantPool(Indexer.java:606) [jandex-1.0.3.Final.jar:1.0.3.Final]
at org.jboss.jandex.Indexer.index(Indexer.java:640) [jandex-1.0.3.Final.jar:1.0.3.Final]
at org.jboss.as.server.deployment.annotation.ResourceRootIndexer.indexResourceRoot(ResourceRootIndexer.java:77) [jboss-as-server-7.1.1.Final.jar:7.1.1.Final]
at org.jboss.as.server.deployment.annotation.AnnotationIndexProcessor.deploy(AnnotationIndexProcessor.java:51) [jboss-as-server-7.1.1.Final.jar:7.1.1.Final]
at org.jboss.as.server.deployment.DeploymentUnitPhaseService.start(DeploymentUnitPhaseService.java:113) [jboss-as-server-7.1.1.Final.jar:7.1.1.Final]
at org.jboss.msc.service.ServiceControllerImpl$StartTask.startService(ServiceControllerImpl.java:1811) [jboss-msc-1.0.2.GA.jar:1.0.2.GA]
at org.jboss.msc.service.ServiceControllerImpl$StartTask.run(ServiceControllerImpl.java:1746) [jboss-msc-1.0.2.GA.jar:1.0.2.GA]
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) [rt.jar:1.7.0_80]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) [rt.jar:1.7.0_80]
at java.lang.Thread.run(Thread.java:745) [rt.jar:1.7.0_80]
</code>```

I need your support, thanks.

答:
The problem was due to dependency conflict, which I could exclude using the following jboss-deployment-structure.xml</p>

```<code>    <?xml version='1.0' encoding='UTF-8'?>
<jboss-deployment-structure
    xmlns="urn:jboss:deployment-structure:1.1">
    <deployment>
        <exclusions>
            <module name="com.fasterxml.jackson.core.jackson-annotations" />
            <module name="com.fasterxml.jackson.core.jackson-core" />
            <module name="com.fasterxml.jackson.core.jackson-databind" />
            <module
                name="com.fasterxml.jackson.jaxrs.jackson-jaxrs-json-provider" />
            <module name="org.jboss.resteasy.resteasy-jackson2-provider" />
            <module name="org.slf4j" />
        </exclusions>
    </deployment>
</jboss-deployment-structure>
</code>```

Body:
I am trying to deploy a simple Spring boot application on a Jboss 7.1.1.
I have made the corresponding settings, but the error continuously appears:
"JBAS015852: Could not index class module-info.class"

I made the following settings:

@SpringBootApplication
public class DemoApplication extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
    return application.sources(DemoApplication.class);
}

public static void main(String[] args) {
    SpringApplication.run(DemoApplication.class, args);
}

@RestController
class Hellocontroller {
    @RequestMapping("/hello")
    @GetMapping
    String hello() {
        return "Hola";
    }
}

and in the pom.xml

<dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
        <exclusions>
            <exclusion>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-tomcat</artifactId>
            </exclusion>
        </exclusions>
    </dependency>

but I have the following result

16:12:16,317 WARN  [org.jboss.as.server.deployment] (MSC service thread 1-4) JBAS015852: Could not index class org/hibernate/validator/spi/scripting/AbstractCachingScriptEvaluatorFactory.class at /C:/Users/User/Downloads/jboss-as-7.1.1.Final/jboss-as-7.1.1.Final/standalone/deployments/demo.war/WEB-INF/lib/hibernate-validator-6.0.19.Final.jar: java.lang.IllegalStateException: Unknown tag! pos=4 poolCount = 71
at org.jboss.jandex.Indexer.processConstantPool(Indexer.java:606) [jandex-1.0.3.Final.jar:1.0.3.Final]
at org.jboss.jandex.Indexer.index(Indexer.java:640) [jandex-1.0.3.Final.jar:1.0.3.Final]
at org.jboss.as.server.deployment.annotation.ResourceRootIndexer.indexResourceRoot(ResourceRootIndexer.java:77) [jboss-as-server-7.1.1.Final.jar:7.1.1.Final]
at org.jboss.as.server.deployment.annotation.AnnotationIndexProcessor.deploy(AnnotationIndexProcessor.java:51) [jboss-as-server-7.1.1.Final.jar:7.1.1.Final]
at org.jboss.as.server.deployment.DeploymentUnitPhaseService.start(DeploymentUnitPhaseService.java:113) [jboss-as-server-7.1.1.Final.jar:7.1.1.Final]
at org.jboss.msc.service.ServiceControllerImpl$StartTask.startService(ServiceControllerImpl.java:1811) [jboss-msc-1.0.2.GA.jar:1.0.2.GA]
at org.jboss.msc.service.ServiceControllerImpl$StartTask.run(ServiceControllerImpl.java:1746) [jboss-msc-1.0.2.GA.jar:1.0.2.GA]
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) [rt.jar:1.7.0_80]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) [rt.jar:1.7.0_80]
at java.lang.Thread.run(Thread.java:745) [rt.jar:1.7.0_80]

I need your support, thanks.

Body:
The problem was due to dependency conflict, which I could exclude using the following jboss-deployment-structure.xml

    <?xml version='1.0' encoding='UTF-8'?>
<jboss-deployment-structure
    xmlns="urn:jboss:deployment-structure:1.1">
    <deployment>
        <exclusions>
            <module name="com.fasterxml.jackson.core.jackson-annotations" />
            <module name="com.fasterxml.jackson.core.jackson-core" />
            <module name="com.fasterxml.jackson.core.jackson-databind" />
            <module
                name="com.fasterxml.jackson.jaxrs.jackson-jaxrs-json-provider" />
            <module name="org.jboss.resteasy.resteasy-jackson2-provider" />
            <module name="org.slf4j" />
        </exclusions>
    </deployment>
</jboss-deployment-structure>


问:
Dynamically -webkit-linear-gradient
I need to fill my row in the table with different colors dynamically.
I use:

```<code>-webkit-linear-gradient
</code>```

for example,I have #729fcf 20%, #93971c 20% 30%, #16eab7 30% 20%, #427b70 20%  20%, #861d53 20% 10% but I get three colors instead five

the number of colors and columns may be different, and should not depend on each other.
http://jsfiddle.net/01wy9Lso/1/

* {margin:0;padding:0;border:0;border-collapse:collapse;}

table {
width:100%;
}

th {
         border: 2px solid black;
}

tbody {
    background: -webkit-linear-gradient(left, #729fcf 20%, #93971c 20% 30%, #16eab7 30% 20%, #427b70 20%  20%, #861d53 20% 10%);

    background-attachment:fixed;}

thead tr, thead th { background:transparent; }

/* #a13131  #93971c  #93971c   #16eab7 #861d53 #427b70 */```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table>
 <thead>
  <tr>
   <th>One</th>
   <th>Two</th>
   <th>Three</th>
  </tr>
 </thead>
 <tbody>
  <tr>
   <td>un</td>
   <td>deux</td>
   <td>trois</td>
  </tr>
 </tbody>
</table></code>```

答:
You are missunderstanding how color stop works, they need to always increment:

* {
  margin: 0;
  padding: 0;
  border: 0;
  border-collapse: collapse;
}

table {
  width: 100%;
}

th {
  border: 2px solid black;
}

tbody {
  background:
    linear-gradient(to left,
      #729fcf 20%,
       /* 20% = the value of the previous color */
       /* 50% = 20%
              + 30% (the with of the color)  */
      #93971c 20% 50%,
      #16eab7 50% 70%,
      #427b70 70% 80%,
      #861d53 0); /* the last one can be 0 and it will take the remaining */
  background-attachment: fixed;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table>
  <thead>
    <tr>
      <th>One</th>
      <th>Two</th>
      <th>Three</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>un</td>
      <td>deux</td>
      <td>trois</td>
    </tr>
  </tbody>
</table></code>```

Title: Dynamically -webkit-linear-gradient

Body:
I need to fill my row in the table with different colors dynamically.
I use:

-webkit-linear-gradient

for example,I have #729fcf 20%, #93971c 20% 30%, #16eab7 30% 20%, #427b70 20%  20%, #861d53 20% 10% but I get three colors instead five

the number of colors and columns may be different, and should not depend on each other.
http://jsfiddle.net/01wy9Lso/1/

* {margin:0;padding:0;border:0;border-collapse:collapse;}

table {
width:100%;
}

th {
         border: 2px solid black;
}

tbody {
    background: -webkit-linear-gradient(left, #729fcf 20%, #93971c 20% 30%, #16eab7 30% 20%, #427b70 20%  20%, #861d53 20% 10%);

    background-attachment:fixed;}

thead tr, thead th { background:transparent; }

/* #a13131  #93971c  #93971c   #16eab7 #861d53 #427b70 */

   One
   Two
   Three

   un
   deux
   trois

Body:
You are missunderstanding how color stop works, they need to always increment:

* {
  margin: 0;
  padding: 0;
  border: 0;
  border-collapse: collapse;
}

table {
  width: 100%;
}

th {
  border: 2px solid black;
}

tbody {
  background:
    linear-gradient(to left,
      #729fcf 20%,
       /* 20% = the value of the previous color */
       /* 50% = 20%
              + 30% (the with of the color)  */
      #93971c 20% 50%,
      #16eab7 50% 70%,
      #427b70 70% 80%,
      #861d53 0); /* the last one can be 0 and it will take the remaining */
  background-attachment: fixed;
}

<table>
  <thead>
    <tr>
      <th>One</th>
      <th>Two</th>
      <th>Three</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>un</td>
      <td>deux</td>
      <td>trois</td>
    </tr>
  </tbody>
</table>


问:
Return class as JSON with one extra field in API using Entity Framework
I have a class Employee with many properties in it and when I want to read it from the database and return a list of it. I want to add an extra field to it.

Currently it's like this:

```<code>return await _context.Employees.ToListAsync();
</code>```

I don't want to use Select command after Employee because as far as I know I have to list all my properties in the Employee class to be able to add an extra one like below:

```<code>return await _context.Employees.Select(em => new
{
   em.Firstname, // In employee class
   em.Lastname, // In employee class
   ... // Other properties in employee class
   EXTRAFIELD = "Data" // Extra field with any data I want to add to employee
}).ToListAsync();
</code>```

But in the solution above I have to list all my fields in employee class.

I don't want to do as below as it puts employee in a new object names em:

```<code>return await _context.Employees.Select(em => new
    {
       em,
       EXTRAFIELD = "Data" // Extra field with any data I want to add to employee
    }).ToListAsync();
</code>```

Is there a way to tell DbContext (_context) to return Employee fields and add "this new field" in it (create new object which has same properties as Employee with one extra)?

答:
How about to create and return a custom object that will inherit Employee properties? And you can add extra generic field, for example:

```<code>public class CustomEmployee<T> : Employee
{
    public T Data { get; set; }
}
</code>```

I know you don't want to copy values from object to object with Select, but we can create something like this:

```<code>public class CustomEmployee<T> : Employee
{

    public CustomEmployee() { } //for cases if you don't want to copy values while creating an instance

    public CustomEmployee(Employee employee)
    {
        foreach (PropertyInfo prop in employee.GetType().GetProperties())
        {
            PropertyInfo prop2 = employee.GetType().GetProperty(prop.Name);
            prop2.SetValue(this, prop.GetValue(employee, null), null);
        }
    }

    public T Data { get; set; }
}
</code>```

In constructor you have to pass an inherited instance Employee, and code above will copy values from Employee to CustomEmployee.

And use like this:

```<code>return await _context.Employees.Select(em => new CustomEmployee(em)<string>
{
    Data = "Extra data"
}).ToListAsync();
</code>```

Body:
I have a class Employee with many properties in it and when I want to read it from the database and return a list of it. I want to add an extra field to it.

Currently it's like this:

return await _context.Employees.ToListAsync();

I don't want to use Select command after Employee because as far as I know I have to list all my properties in the Employee class to be able to add an extra one like below:

return await _context.Employees.Select(em => new
{
   em.Firstname, // In employee class
   em.Lastname, // In employee class
   ... // Other properties in employee class
   EXTRAFIELD = "Data" // Extra field with any data I want to add to employee
}).ToListAsync();

But in the solution above I have to list all my fields in employee class.

I don't want to do as below as it puts employee in a new object names em:

return await _context.Employees.Select(em => new
    {
       em,
       EXTRAFIELD = "Data" // Extra field with any data I want to add to employee
    }).ToListAsync();

Is there a way to tell DbContext (_context) to return Employee fields and add "this new field" in it (create new object which has same properties as Employee with one extra)?

Body:
How about to create and return a custom object that will inherit Employee properties? And you can add extra generic field, for example:

public class CustomEmployee<T> : Employee
{
    public T Data { get; set; }
}

I know you don't want to copy values from object to object with Select, but we can create something like this:

public class CustomEmployee<T> : Employee
{

    public CustomEmployee() { } //for cases if you don't want to copy values while creating an instance

    public CustomEmployee(Employee employee)
    {
        foreach (PropertyInfo prop in employee.GetType().GetProperties())
        {
            PropertyInfo prop2 = employee.GetType().GetProperty(prop.Name);
            prop2.SetValue(this, prop.GetValue(employee, null), null);
        }
    }

    public T Data { get; set; }
}

In constructor you have to pass an inherited instance Employee, and code above will copy values from Employee to CustomEmployee.

And use like this:

return await _context.Employees.Select(em => new CustomEmployee(em)<string>
{
    Data = "Extra data"
}).ToListAsync();


问:
near-api-js What is the difference between contractId and account.accountId in the contract interface?
Contract constructor takes both account: Account and contractId: string, but Account already provides account id of the contract as account.accountId. What is the difference between these two? https://github.com/near/near-api-js/blob/master/src/contract.ts#L22

Upd: We can even see in tests that they are passed the same value here: https://github.com/near/near-api-js/blob/master/test/test-utils.js#L39

答:
account.accountId specifies who is signing transaction, i.e. account which is performing actions.

contractId specifies the account name of contract which is receiving transactions.

They can be the same if it's necessary to perform actions on behalf of contract's account but basically this only applies to contact owners. They won't be the same if e.g. you have user logged in using WalletConnection and calling third-party contract.


问:
Exchange 2016 Error assigning TlsCertificateName to Receive Connector
I have spent 10+ hours working with Microsoft's support to configure a hybrid setup between our On-Premises Exchange 2016 Server and Azure AD environments and are currently stuck on an error (see below) when trying to assign the TlsCertificateName value to the On-Premises Receive Connector.

These commands create a variable $TLSCertName that include the certificate issuer and subject values:

```<code>$TLSCert = Get-ExchangeCertificate -Thumbprint <Thumbprint>
$TLSCertName = "<I>$($TLSCert.Issuer)<S>$($TLSCert.Subject)"
Set-ReceiveConnector "<Receive Connector Name" -TlsCertificateName $TLSCertName
</code>```

The error displayed when trying to execute this command is:

```<code>Cannot process argument transformation on parameter 'TlsCertificateName'. Cannot convert value "<TLSCertName>" to type "Microsoft.Exchange.Data.SmtpX509Identifier". Error:
""<TLSCertName>" isn't a valid Certificate Identifier."
+ CategoryInfo : InvalidData: (:) [Set-ReceiveConnector], ParameterBindin...mationException
+ FullyQualifiedErrorId : ParameterArgumentTransformationError,Set-ReceiveConnector
+ PSComputerName : <Server's FQDN>
</code>```

Microsoft believes the problem is caused by some of the values in the certificate subject that contain quotes, i.e. OU="Hosted by CONTOSO, Inc.", O="CONTOSO, Inc.", thus causing the command to truncate the contents of the TLSCertName variable.

I have tried manually entering the argument instead of using the variable (with and without quotes), using single quotes, escaping the quotes (`"), but nothing has worked.

Has anyone come across this issue? I have tried researching online but haven't been able to find a solution.

Any help will be greatly appreciated!

答:
So, after a few hours venturing on my own instead of working with Microsoft support I finally figured out the reason for the error by complete coincidence + guess work.

While reviewing values for the certificate's subject in EAC, I noticed when I clicked on the subject field a message popped up saying:

"In the subject of the certificate, the important value is the common
  name (CN), which indicates the host that the certificate can be used
  for."

The SSL certificate I'm using is a Multi-domain certificate, and since the common name can only contain up to one entry, the certificate uses a field called Subject Alternate Name (SAN) which allows multiple names to be included. Therefor there is no CN field available in the subject.

Exchange does not read/use the SAN field and wasn't accepting the command because of the missing CN (wish this was documented somewhere and their support knew it as well).

The solution was to use the contents of the TLSCertName variable in the command, and manually add the CN value to the subject section, as in:

```<code><S>CN=contoso.com, OU=Multi-Domain SSL, OU="Hosted by CONTOSO, INC.", O="CONTOSO, Inc."...
</code>```

Keep in mind the CN must exist in the SAN per standard mandates. You can read more information about this in https://support.dnsimple.com/articles/what-is-common-name/

Hope this helps someone looking for an answer for the same problem.

Now off to solve the issue that depended on this!

Body:
I have spent 10+ hours working with Microsoft's support to configure a hybrid setup between our On-Premises Exchange 2016 Server and Azure AD environments and are currently stuck on an error (see below) when trying to assign the TlsCertificateName value to the On-Premises Receive Connector.

These commands create a variable $TLSCertName that include the certificate issuer and subject values:

$TLSCert = Get-ExchangeCertificate -Thumbprint <Thumbprint>
$TLSCertName = "$($TLSCert.Issuer)<S>$($TLSCert.Subject)"
Set-ReceiveConnector "<Receive Connector Name" -TlsCertificateName $TLSCertName

The error displayed when trying to execute this command is:

Cannot process argument transformation on parameter 'TlsCertificateName'. Cannot convert value "<TLSCertName>" to type "Microsoft.Exchange.Data.SmtpX509Identifier". Error:
""<TLSCertName>" isn't a valid Certificate Identifier."
+ CategoryInfo : InvalidData: (:) [Set-ReceiveConnector], ParameterBindin...mationException
+ FullyQualifiedErrorId : ParameterArgumentTransformationError,Set-ReceiveConnector
+ PSComputerName : <Server's FQDN>

Microsoft believes the problem is caused by some of the values in the certificate subject that contain quotes, i.e. OU="Hosted by CONTOSO, Inc.", O="CONTOSO, Inc.", thus causing the command to truncate the contents of the TLSCertName variable.

I have tried manually entering the argument instead of using the variable (with and without quotes), using single quotes, escaping the quotes (`"), but nothing has worked.

Has anyone come across this issue? I have tried researching online but haven't been able to find a solution.

Any help will be greatly appreciated!

Body:
So, after a few hours venturing on my own instead of working with Microsoft support I finally figured out the reason for the error by complete coincidence + guess work.

While reviewing values for the certificate's subject in EAC, I noticed when I clicked on the subject field a message popped up saying:

"In the subject of the certificate, the important value is the common
  name (CN), which indicates the host that the certificate can be used
  for."

The SSL certificate I'm using is a Multi-domain certificate, and since the common name can only contain up to one entry, the certificate uses a field called Subject Alternate Name (SAN) which allows multiple names to be included. Therefor there is no CN field available in the subject.

Exchange does not read/use the SAN field and wasn't accepting the command because of the missing CN (wish this was documented somewhere and their support knew it as well).

The solution was to use the contents of the TLSCertName variable in the command, and manually add the CN value to the subject section, as in:

<S>CN=contoso.com, OU=Multi-Domain SSL, OU="Hosted by CONTOSO, INC.", O="CONTOSO, Inc."...

Keep in mind the CN must exist in the SAN per standard mandates. You can read more information about this in https://support.dnsimple.com/articles/what-is-common-name/

Hope this helps someone looking for an answer for the same problem.

Now off to solve the issue that depended on this!


问:
How to create document with subcollection
I can't find how to create a new document without any fields, but one subcollection - messages (and this message collection would have some fields).
This is what I want to do. But I don't want to create subcollection in document which already exist. I want to create new document and subcollection in it.

Honestly I stopped on that :

```<code>let chatRef = db.collection("chat_event").add({

})
</code>```

答:
This answer will greatly help.

let chatRef = db
 .collection("chat_event").document("chat1")
 .collection("messages").document("message1");
```
<p>If you don't want to hardcode the parent document's id or if you want a firestore generated id. Then get the id first from firestore's <code>createId()</code> function.</p>
<pre class="lang-js prettyprint-override"><code>let chatEventId = db.createId();
let chatRef = db
 .collection("chat_event").document(chatEventId)
 .collection("messages").document("message1");
</code>```

You could still use auto-generated id for the subcollection's document:

```<code>let chatEventId = db.createId();
let messageId = db.createId();
let chatRef = db
 .collection("chat_event").document(chatEventId)
 .collection("messages").document(messageId);
</code>```

Note that firestore's autogenerated IDs are entirely random and consequently the documents are not stored in any chronological order. If you will in anyway need some ordering, you could add timestamps to those documents either when you insert data or you update the document with the timestamp info.

docRef.update({
  timestamp: firebase.firestore.FieldValue.serverTimestamp()
});
```

With that, you can order chronologically both in the console and in your own queries.

Check out this answer for more information on auto-generating IDs

Body:
I can't find how to create a new document without any fields, but one subcollection - messages (and this message collection would have some fields).
This is what I want to do. But I don't want to create subcollection in document which already exist. I want to create new document and subcollection in it.

Honestly I stopped on that :

let chatRef = db.collection("chat_event").add({

})

Body:
This answer will greatly help.

let chatRef = db
 .collection("chat_event").document("chat1")
 .collection("messages").document("message1");

If you don't want to hardcode the parent document's id or if you want a firestore generated id. Then get the id first from firestore's createId() function.

let chatEventId = db.createId();
let chatRef = db
 .collection("chat_event").document(chatEventId)
 .collection("messages").document("message1");

You could still use auto-generated id for the subcollection's document:

let chatEventId = db.createId();
let messageId = db.createId();
let chatRef = db
 .collection("chat_event").document(chatEventId)
 .collection("messages").document(messageId);

Note that firestore's autogenerated IDs are entirely random and consequently the documents are not stored in any chronological order. If you will in anyway need some ordering, you could add timestamps to those documents either when you insert data or you update the document with the timestamp info.

docRef.update({
  timestamp: firebase.firestore.FieldValue.serverTimestamp()
});

With that, you can order chronologically both in the console and in your own queries.

Check out this answer for more information on auto-generating IDs


问:
Is it possible to create a function where [[prototype]] refers to another function
I would like to create function objects (yes, all functions are objects) with some control over the prototypal inheritance, that is, I would like one function to inherit from another.

I can make objects that have prototypal inheritance, and know to set the prototype property of a function performing as a constructor to initialize the [[prototype]] property of the object.

However, when creating a function, I must use the function operator or the Function constructor. I could try to swizzle Function.prototype, but (1) don't know if that is writable, and (2) that just seems quite dangerous [still, I should try doing that].

btw: I only care to do this for V8 within node.JS, so if there are means that work only for that environment, that would be acceptable.

For the record, I have seen this:
Is it possible to create a function with another prototype than Function.prototype?

答:
I came up with a solution that solves my needs. It is not cross-browser, but can be used cross-browser. My most important use case is as a module for node.JS. In that case, the mechanism of setting __proto__ works just fine, in which case I can call methods on the base function object

```<code>f.method(args...);
</code>```

and it executed by code in the "super" function. Because the method is invoked by the method invocation pattern, "this" is set to the base function object, and so the proper properties are accessed even though the method resides in the "super."

Now for the in-Browser case: when I use my library client-side, I provide a proxy mechanism. Alas, code intended for the browser must be written differently. The invocation is:

```<code>f.proxy(methodName, args...);
</code>```

The proxy method in the base function object is:

```<code>f.proxy = function (methodName) {
    var p = this.constructor.prototype;
    return p.proxy(this, methodName, arguments);
};
</code>```

The proxy in the "super" object's prototype is:

```<code>proxy: function (instance, methodName) {
    var args = Array.prototype.splice.apply(arguments, [2]),
        method = this[methodName];
    return (method) ? method.apply(instance, args) : undefined;
}
</code>```

I probably should have named this "forward" or some such, but "proxy" is good enough.

Perhaps this mechanism might be useful to someone...

Body:
I came up with a solution that solves my needs. It is not cross-browser, but can be used cross-browser. My most important use case is as a module for node.JS. In that case, the mechanism of setting __proto__ works just fine, in which case I can call methods on the base function object

f.method(args...);

and it executed by code in the "super" function. Because the method is invoked by the method invocation pattern, "this" is set to the base function object, and so the proper properties are accessed even though the method resides in the "super."

Now for the in-Browser case: when I use my library client-side, I provide a proxy mechanism. Alas, code intended for the browser must be written differently. The invocation is:

f.proxy(methodName, args...);

The proxy method in the base function object is:

f.proxy = function (methodName) {
    var p = this.constructor.prototype;
    return p.proxy(this, methodName, arguments);
};

The proxy in the "super" object's prototype is:

proxy: function (instance, methodName) {
    var args = Array.prototype.splice.apply(arguments, [2]),
        method = this[methodName];
    return (method) ? method.apply(instance, args) : undefined;
}

I probably should have named this "forward" or some such, but "proxy" is good enough.

Perhaps this mechanism might be useful to someone...


问:
Table bubble plot with pandas and altair
I have the following df_teams_full_stats:

```<code>Data columns (total 35 columns):
 #   Column                 Non-Null Count  Dtype
---  ------                 --------------  -----
 0   Unnamed: 0             428 non-null    int64
 1   MatchID                428 non-null    int64
 2   For Team               428 non-null    object
 3   Against Team           428 non-null    object
 4   Date                   428 non-null    object
 5   GameWeek               428 non-null    int64
 6   Home                   428 non-null    object
 7   Possession             428 non-null    float64
 8   Touches                428 non-null    int64
 9   Passes                 428 non-null    int64
 10  Tackles                428 non-null    int64
 11  Clearances             428 non-null    int64
 12  Corners                428 non-null    int64
 13  Offsides               428 non-null    int64
 14  Fouls Committed        428 non-null    int64
 15  Yellow Cards           428 non-null    int64
 16  Goals                  428 non-null    int64
 17  XG                     428 non-null    float64
 18  Shots On Target        428 non-null    int64
 19  Total Shots            428 non-null    int64
 20  Goals Conceded         428 non-null    int64
 21  Shots Conceded         428 non-null    int64
 22  XGC                    428 non-null    float64
 23  Shots In Box           428 non-null    int64
 24  Close Shots            428 non-null    int64
 25  Headers                428 non-null    int64
 26  Shots Centre           428 non-null    int64
 27  Shots Left             428 non-null    int64
 28  Shots Right            428 non-null    int64
 29  Shots In Box Conceded  428 non-null    int64
 30  Close Shots Conceded   428 non-null    int64
 31  Headers Conceded       428 non-null    int64
 32  Shots Centre Conceded  428 non-null    int64
 33  Shots Left Conceded    428 non-null    int64
 34  Shots Right Conceded   428 non-null    int64
dtypes: float64(3), int64(28), object(4)
memory usage: 117.2+ KB
</code>```

Which I'm trying to group and sort in order to achieve this chart:

Following this example: table_bubble_plot_github, the idea is to have some target 'x', say 'Goals', that will determine the bubble size of all teams playing against all others.

This is what I have so far:

```<code>def team_match_ups(df_teams_full_stats, x, y):
    target_x = x[0]
    target_y = y[0]

    df_temp =  df_teams_full_stats.set_index("For Team")
    df_temp.fillna(0.0, inplace=True)

    df_temp[target_x] = df_temp.groupby(['For Team'])[target_x].mean()
    X = df_temp[target_x].to_frame()
    print ("x", X)

    df_temp[target_y] = df_temp.groupby(['For Team'])[target_y].mean()
    Y = df_temp[target_y].to_frame()

    df = df_temp.reset_index()

    #sorted_teams = sorted(df_teams_full_stats['For Team'].unique())

    bubble_plot = alt.Chart(df).mark_circle().encode(
            alt.Y(f'{target_x}:O', bin=True),
            alt.X(f'{target_y}:O', bin=True),
            alt.Size(f'{target_x}:Q',
            scale=alt.Scale(range=[0, 1500])),
            #alt.Color('Color', legend=None, scale=None),
            tooltip = [alt.Tooltip(f'{target_x}:Q'),
                       alt.Tooltip(f'{target_y}:Q')],
        )

return bubble_plot
</code>```

But this is far from ideal:

QUESTION

How can I have teams names naming x and y grids and target_x setting the bubble size?

答:
If you want the x and y axis to be team names, you should map the x and y encodings to the columns containing team names. It might look something like this (untested because you did not provide access to your data):</p>

```<code>alt.Chart(df_teams_full_stats).mark_circle().encode(
  x='For Team:N',
  y='Against Team:N',
  size='Goals:Q'
)
</code>```

Body:
I have the following df_teams_full_stats:

Data columns (total 35 columns):
 #   Column                 Non-Null Count  Dtype
---  ------                 --------------  -----
 0   Unnamed: 0             428 non-null    int64
 1   MatchID                428 non-null    int64
 2   For Team               428 non-null    object
 3   Against Team           428 non-null    object
 4   Date                   428 non-null    object
 5   GameWeek               428 non-null    int64
 6   Home                   428 non-null    object
 7   Possession             428 non-null    float64
 8   Touches                428 non-null    int64
 9   Passes                 428 non-null    int64
 10  Tackles                428 non-null    int64
 11  Clearances             428 non-null    int64
 12  Corners                428 non-null    int64
 13  Offsides               428 non-null    int64
 14  Fouls Committed        428 non-null    int64
 15  Yellow Cards           428 non-null    int64
 16  Goals                  428 non-null    int64
 17  XG                     428 non-null    float64
 18  Shots On Target        428 non-null    int64
 19  Total Shots            428 non-null    int64
 20  Goals Conceded         428 non-null    int64
 21  Shots Conceded         428 non-null    int64
 22  XGC                    428 non-null    float64
 23  Shots In Box           428 non-null    int64
 24  Close Shots            428 non-null    int64
 25  Headers                428 non-null    int64
 26  Shots Centre           428 non-null    int64
 27  Shots Left             428 non-null    int64
 28  Shots Right            428 non-null    int64
 29  Shots In Box Conceded  428 non-null    int64
 30  Close Shots Conceded   428 non-null    int64
 31  Headers Conceded       428 non-null    int64
 32  Shots Centre Conceded  428 non-null    int64
 33  Shots Left Conceded    428 non-null    int64
 34  Shots Right Conceded   428 non-null    int64
dtypes: float64(3), int64(28), object(4)
memory usage: 117.2+ KB

Which I'm trying to group and sort in order to achieve this chart:

Following this example: table_bubble_plot_github, the idea is to have some target 'x', say 'Goals', that will determine the bubble size of all teams playing against all others.

This is what I have so far:

def team_match_ups(df_teams_full_stats, x, y):
    target_x = x[0]
    target_y = y[0]

    df_temp =  df_teams_full_stats.set_index("For Team")
    df_temp.fillna(0.0, inplace=True)

    df_temp[target_x] = df_temp.groupby(['For Team'])[target_x].mean()
    X = df_temp[target_x].to_frame()
    print ("x", X)

    df_temp[target_y] = df_temp.groupby(['For Team'])[target_y].mean()
    Y = df_temp[target_y].to_frame()

    df = df_temp.reset_index()

    #sorted_teams = sorted(df_teams_full_stats['For Team'].unique())

    bubble_plot = alt.Chart(df).mark_circle().encode(
            alt.Y(f'{target_x}:O', bin=True),
            alt.X(f'{target_y}:O', bin=True),
            alt.Size(f'{target_x}:Q',
            scale=alt.Scale(range=[0, 1500])),
            #alt.Color('Color', legend=None, scale=None),
            tooltip = [alt.Tooltip(f'{target_x}:Q'),
                       alt.Tooltip(f'{target_y}:Q')],
        )

return bubble_plot

But this is far from ideal:

QUESTION

How can I have teams names naming x and y grids and target_x setting the bubble size?

Body:
If you want the x and y axis to be team names, you should map the x and y encodings to the columns containing team names. It might look something like this (untested because you did not provide access to your data):

alt.Chart(df_teams_full_stats).mark_circle().encode(
  x='For Team:N',
  y='Against Team:N',
  size='Goals:Q'
)


问:
Checkmarx Postgres Query forming error SQL Injection error , SQL Second order injection error Java Springboot
I've some APIs that perform Database operations . Whenever I upload my code to checkmarx I get the following error and it is flagged as a high vulnerability error Can anyone help me ?

Error

The application's CreateDatabaseAndMapToDomain method executes an SQL query with executeQuery, at line 717 of daas-springboot-CheckMarxIntegration\src\main\java\com\it\daas\apis\service\PostgresConnectionServiceImpl.java. The application constructs this SQL query by embedding an untrusted string into the query without proper sanitization. The concatenated string is submitted to the database, where it is parsed and executed accordingly.

The attacker may be able to write arbitrary data to the database, which is then retrieved by the application with executeQuery in getDomains method at line 678 of daas-springboot-CheckMarxIntegration\src\main\java\com\it\daas\apis\service\PostgresConnectionServiceImpl.java. This data then flows through the code, until it is used directly in the SQL query without sanitization, and then submitted to the database server for execution

Here're my functions

```<code>    @Override
public String getDomains() throws SQLException {

    String domainquery = "SELECT id,domain FROM domain";
    Connection con = null;
    PreparedStatement st = null;
    ResultSet result = null;
    try
    {
        con = ConnectToPostgresapibuilderDatabase(apibuilderConnectionString, apibuilderUserName,apibuilderPassword);
        con.setSchema(this.schema);
        st = con.prepareStatement(domainquery);
        result = st.executeQuery();

        ArrayList<DatabaseDomainBean> list = new ArrayList<DatabaseDomainBean>();
        while (result.next()) {
            list.add(new DatabaseDomainBean(result.getString("domain"), result.getString("id")));
        }
        return new JSONObject().put("domainlist", list).toString();

    }
    catch(Exception e)
    {

        e.printStackTrace();
        return null;
    }
    finally{

        result.close();
        st.close();
        con.close();

    }

}

@Override
public String CreateDatabaseAndMapToDomain(String database, String[] domainIds, String password)
        throws SQLException {

    if (!this.apibuilderPassword.equals(password)) {
        return null;
    }
    else if(database==null || domainIds==null || password ==null)
    {
        return "Failure";
    }

    Connection con =null;
    PreparedStatement st =null;
    ResultSet ispresent =null;
    PreparedStatement mapquerystmnt =null;
    ResultSet resultMapping = null;

    try
    {
        con = ConnectToPostgresapibuilderDatabase(apibuilderConnectionString, apibuilderUserName,apibuilderPassword);
        con.setSchema(this.schema);

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

            con.setSchema(this.schema);

            String IfExists = MessageFormat.format(
                    "SELECT databasename,domainid FROM Databases WHERE databasename IN (?) AND domainid IN (?)",
                    Utilitymethods.ConvertToMessageFormatCompatibleForm(database),
                    Utilitymethods.ConvertToMessageFormatCompatibleForm(domainIds[i]));

            st = con.prepareStatement(IfExists);
            st.setString(1, database);
            st.setInt(2, Integer.parseInt(domainIds[i]));
            ispresent = st.executeQuery();

            if (!ispresent.next()) {
                // INSERT INTO Databases (databasename,domainid) VALUES ('Teradata','1')
                String mapquery = MessageFormat.format(
                        "INSERT INTO Databases (databasename,domainid) VALUES (?,?) returning Id",
                        Utilitymethods.ConvertToMessageFormatCompatibleForm(database),
                        Utilitymethods.ConvertToMessageFormatCompatibleForm(domainIds[i]));
                 mapquerystmnt = con.prepareStatement(mapquery);
                 mapquerystmnt.setString(1, database);
                 mapquerystmnt.setInt(2, Integer.parseInt(domainIds[i]));
                 resultMapping =  mapquerystmnt.executeQuery();
            }

        }

        return "Success";

    }
    catch(Exception e)
    {
        e.printStackTrace();
        return "Failure";

    }
    finally
    {

        ispresent.close();
        st.close();
        resultMapping.close();
        mapquerystmnt.close();
        con.close();
    }

}

@Override
public String getDomains() throws SQLException {

    String domainquery = "SELECT id,domain FROM domain";
    Connection con = null;
    PreparedStatement st = null;
    ResultSet result = null;
    try
    {
        con = ConnectToPostgresapibuilderDatabase(apibuilderConnectionString, apibuilderUserName,apibuilderPassword);
        con.setSchema(this.schema);
        st = con.prepareStatement(domainquery);
        result = st.executeQuery();

        ArrayList<DatabaseDomainBean> list = new ArrayList<DatabaseDomainBean>();
        while (result.next()) {
            list.add(new DatabaseDomainBean(result.getString("domain"), result.getString("id")));
        }
        return new JSONObject().put("domainlist", list).toString();

    }
    catch(Exception e)
    {

        e.printStackTrace();
        return null;
    }
    finally{

        result.close();
        st.close();
        con.close();

    }

}
</code>```

答: Try with st = con.prepareStatement("SELECT id,domain FROM domain") directly. Looks like checkmarx confused due to String domainquery = "SELECT id,domain FROM domain" statement and the possibility of sql injection.

Body:
I've some APIs that perform Database operations . Whenever I upload my code to checkmarx I get the following error and it is flagged as a high vulnerability error Can anyone help me ?

Error

The application's CreateDatabaseAndMapToDomain method executes an SQL query with executeQuery, at line 717 of daas-springboot-CheckMarxIntegration\src\main\java\com\it\daas\apis\service\PostgresConnectionServiceImpl.java. The application constructs this SQL query by embedding an untrusted string into the query without proper sanitization. The concatenated string is submitted to the database, where it is parsed and executed accordingly.

The attacker may be able to write arbitrary data to the database, which is then retrieved by the application with executeQuery in getDomains method at line 678 of daas-springboot-CheckMarxIntegration\src\main\java\com\it\daas\apis\service\PostgresConnectionServiceImpl.java. This data then flows through the code, until it is used directly in the SQL query without sanitization, and then submitted to the database server for execution

Here're my functions

    @Override
public String getDomains() throws SQLException {

    String domainquery = "SELECT id,domain FROM domain";
    Connection con = null;
    PreparedStatement st = null;
    ResultSet result = null;
    try
    {
        con = ConnectToPostgresapibuilderDatabase(apibuilderConnectionString, apibuilderUserName,apibuilderPassword);
        con.setSchema(this.schema);
        st = con.prepareStatement(domainquery);
        result = st.executeQuery();

        ArrayList<DatabaseDomainBean> list = new ArrayList<DatabaseDomainBean>();
        while (result.next()) {
            list.add(new DatabaseDomainBean(result.getString("domain"), result.getString("id")));
        }
        return new JSONObject().put("domainlist", list).toString();

    }
    catch(Exception e)
    {

        e.printStackTrace();
        return null;
    }
    finally{

        result.close();
        st.close();
        con.close();

    }

}

@Override
public String CreateDatabaseAndMapToDomain(String database, String[] domainIds, String password)
        throws SQLException {

    if (!this.apibuilderPassword.equals(password)) {
        return null;
    }
    else if(database==null || domainIds==null || password ==null)
    {
        return "Failure";
    }

    Connection con =null;
    PreparedStatement st =null;
    ResultSet ispresent =null;
    PreparedStatement mapquerystmnt =null;
    ResultSet resultMapping = null;

    try
    {
        con = ConnectToPostgresapibuilderDatabase(apibuilderConnectionString, apibuilderUserName,apibuilderPassword);
        con.setSchema(this.schema);

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

            con.setSchema(this.schema);

            String IfExists = MessageFormat.format(
                    "SELECT databasename,domainid FROM Databases WHERE databasename IN (?) AND domainid IN (?)",
                    Utilitymethods.ConvertToMessageFormatCompatibleForm(database),
                    Utilitymethods.ConvertToMessageFormatCompatibleForm(domainIds[i]));

            st = con.prepareStatement(IfExists);
            st.setString(1, database);
            st.setInt(2, Integer.parseInt(domainIds[i]));
            ispresent = st.executeQuery();

            if (!ispresent.next()) {
                // INSERT INTO Databases (databasename,domainid) VALUES ('Teradata','1')
                String mapquery = MessageFormat.format(
                        "INSERT INTO Databases (databasename,domainid) VALUES (?,?) returning Id",
                        Utilitymethods.ConvertToMessageFormatCompatibleForm(database),
                        Utilitymethods.ConvertToMessageFormatCompatibleForm(domainIds[i]));
                 mapquerystmnt = con.prepareStatement(mapquery);
                 mapquerystmnt.setString(1, database);
                 mapquerystmnt.setInt(2, Integer.parseInt(domainIds[i]));
                 resultMapping =  mapquerystmnt.executeQuery();
            }

        }

        return "Success";

    }
    catch(Exception e)
    {
        e.printStackTrace();
        return "Failure";

    }
    finally
    {

        ispresent.close();
        st.close();
        resultMapping.close();
        mapquerystmnt.close();
        con.close();
    }

}

@Override
public String getDomains() throws SQLException {

    String domainquery = "SELECT id,domain FROM domain";
    Connection con = null;
    PreparedStatement st = null;
    ResultSet result = null;
    try
    {
        con = ConnectToPostgresapibuilderDatabase(apibuilderConnectionString, apibuilderUserName,apibuilderPassword);
        con.setSchema(this.schema);
        st = con.prepareStatement(domainquery);
        result = st.executeQuery();

        ArrayList<DatabaseDomainBean> list = new ArrayList<DatabaseDomainBean>();
        while (result.next()) {
            list.add(new DatabaseDomainBean(result.getString("domain"), result.getString("id")));
        }
        return new JSONObject().put("domainlist", list).toString();

    }
    catch(Exception e)
    {

        e.printStackTrace();
        return null;
    }
    finally{

        result.close();
        st.close();
        con.close();

    }

}


问:
Callback and Testing Highcharts
I am currently using angular 9 with Highcharts.

Link to the code : https://stackblitz.com/edit/angular-ivy-wdejxk

Some instructions for running on application-side / test-side :

Test - side : inside angular.json file on line number 18, change

```<code>    "main": "src/main.ts",
</code>```

to

```<code>    "main": "src/main-testing.ts",
</code>```

and do a refresh of the browser.

Application - side : Change exactly the opposite of previous.

```<code>   "main": "src/main-testing.ts",
</code>```

to

```<code>   "main": "src/main.ts",
</code>```

Here are a few issues i am stuck upon :

I have used chart callback to get the chart instance , but it is not working ( inside hello.component.ts ,
line numbers 38 to 40 ). How should i call it and when does actually the callback happens in Highcharts ?

If suppose somehow i am able to assign the chart instance to chartCreated variable. Can i control the
chart now, like line numbers 60 to 62 ( if i uncomment that ), will it work ? Basically i wanted to
know the usefulness of updateFlag in Highcharts.

Unable to addSeries when ngOnChanges is called inside hello.component.ts

Inside the spec file  hello.component.spec.ts  i wanted to test the chart by putting a numeric data / adding a series
on my own , like i did when onClick() is called. But jasmine shows error

```<code>   TypeError : Cannot read series of undefined
   TypeError : Cannot read property 'addSeries' of undefined
</code>```

How to resolve these ?

EDIT 1 : Implemented ngOnChanges and ngOnInit and removed most of the code from app.component.ts to hello.component.ts

答:
```<code>    If you add the ngOnInit lifecycle hook, you will get values:

    1. export class AppComponent implements OnInit {.....

    2. ngOnInit(){
            this.chartCallback = (chart) => {
                this.chartCreated = chart;
                console.log('chart: ' + chart.chartHeight);         // shows 400
                console.log('this.chartCreated: ' + this.chartCreated.chartHeight); // shows 400
            }
          }

       addNewDataToChart(){
            this.updateFlag = false;
            this.chartCreated.addSeries({
            data: [3,4,2],
            type: 'line'
         });
            this.updateFlag = true;
       }

3. onClick(){
    if(this.clicked === false){
      this.chartCreated.series[0].data[0].update(4);
      this.clicked = true;
    } else {
      this.chartCreated.series[0].data[0].update(1);
      this.clicked = false;
    }
  }
</code>```

Title: Callback and Testing Highcharts

Body:
I am currently using angular 9 with Highcharts.

Link to the code : https://stackblitz.com/edit/angular-ivy-wdejxk

Some instructions for running on application-side / test-side :

Test - side : inside angular.json file on line number 18, change

    "main": "src/main.ts",

to

    "main": "src/main-testing.ts",

and do a refresh of the browser.

Application - side : Change exactly the opposite of previous.

   "main": "src/main-testing.ts",

to

   "main": "src/main.ts",

Here are a few issues i am stuck upon :

I have used chart callback to get the chart instance , but it is not working ( inside hello.component.ts ,
line numbers 38 to 40 ). How should i call it and when does actually the callback happens in Highcharts ?

If suppose somehow i am able to assign the chart instance to chartCreated variable. Can i control the
chart now, like line numbers 60 to 62 ( if i uncomment that ), will it work ? Basically i wanted to
know the usefulness of updateFlag in Highcharts.

Unable to addSeries when ngOnChanges is called inside hello.component.ts

Inside the spec file  hello.component.spec.ts  i wanted to test the chart by putting a numeric data / adding a series
on my own , like i did when onClick() is called. But jasmine shows error

   TypeError : Cannot read series of undefined
   TypeError : Cannot read property 'addSeries' of undefined

How to resolve these ?

EDIT 1 : Implemented ngOnChanges and ngOnInit and removed most of the code from app.component.ts to hello.component.ts


问:
Revit C#: Copy existing button to my Ribbon
I want to use the Create-Wall-Button from Architecture in my Ribbon.
I've tried debugging and found the splitbutton here: Autodesk.Windows.ComponentManager.Ribbon.Tabs[0].Panels[1].Source.Items[0]

How can I copy this SplitButton to my Ribbon or what I have to call in a new Button to use this function?

Thank you.

答:
It is posible to clone an built-in command button and add it to another tab, however you would need a couple of tricks and of course the non-supported Autodesk.Windows dll.

I think what you are looking for is the method PostCommand from the UIApplication. Just create a new command and the requested Postable Command will be executed after your own command is completed:

```<code>var app = cmdData.Application;
var cmdId = RevitCommandId.LookupPostableCommandId(PostableCommand.StructuralWall);
app.PostCommand(cmdId);
</code>```

Body:
It is posible to clone an built-in command button and add it to another tab, however you would need a couple of tricks and of course the non-supported Autodesk.Windows dll.

I think what you are looking for is the method PostCommand from the UIApplication. Just create a new command and the requested Postable Command will be executed after your own command is completed:

var app = cmdData.Application;
var cmdId = RevitCommandId.LookupPostableCommandId(PostableCommand.StructuralWall);
app.PostCommand(cmdId);


问:
Odoo module's menu root not showing
I just created a module and add a model and some menu items, But the menu item "Backup SQlite" is not showing on Odoo root menu, This is my code. Any Ideas why is this happening?

views.xml

```<code><record id="utepda_backup_sqlite.backup_log_action" model="ir.actions.act_window">
    <field name="name">Backup Log</field>
    <field name="res_model">utepda_backup_sqlite.backup</field>
    <field name="view_type">form</field>
    <field name="view_mode">tree,form</field>
    <field name="help" type="html">
        <p class="o_view_nocontent_smiling_face">No se han realizado backups</p>
    </field>
</record>

  <menuitem id="utepda_backup_sqlite.menu_root"
  name="Backup Sqlite" />

<!-- App menu items -->
  <menuitem id="menu_log"
  name="Backup log"
  parent="utepda_backup_sqlite.menu_root"
  sequence="10"
  action="utepda_backup_sqlite.backup_log_action" />
</code>```

models.py

```<code>class BackupInfo(models.Model):
    _name = 'utepda_backup_sqlite.backup'
    _description = 'Clase que guarda la informacion de las salvas realizadas'

    name = fields.Char("Nombre")
    fecha_hora = fields.Datetime(string='Fecha-Hora')
</code>```

ir.model.access.csv

```<code>id,name,model_id:id,group_id:id,perm_read,perm_write,perm_create,perm_unlink
access_backup_sqlite,access_backup_sqlite,model_utepda_backup_sqlite_backup,,1,1,1,1
</code>```

答:
It'll work if you have a menu root and a submenu root where your menu items will match on! Here is an example:</p>

```<code><!-- menu root -->
<menuitem id="sqlite_menu_root"
  name="Sqlite" />

<!-- submenu root -->
<menuitem id="sqlite_submenu_root"
  parent="sqlite_menu_root"
  name="Backup" />

<!-- App menu items -->
<menuitem id="sqlite_submenu_root"
  parent="sqlite_submenu_root"
  name="Backup Sqlite"
  sequence="10"
  action="backup_sqlite_action"/>

<menuitem id="menu_log"
  name="Backup log"
  parent="utepda_backup_sqlite.menu_root"
  sequence="10"
  action="backup_log_action" />
</code>```

Title: Odoo module's menu root not showing

Body:
I just created a module and add a model and some menu items, But the menu item "Backup SQlite" is not showing on Odoo root menu, This is my code. Any Ideas why is this happening?

views.xml

<record id="utepda_backup_sqlite.backup_log_action" model="ir.actions.act_window">
    <field name="name">Backup Log</field>
    <field name="res_model">utepda_backup_sqlite.backup</field>
    <field name="view_type">form</field>
    <field name="view_mode">tree,form</field>
    <field name="help" type="html">

No se han realizado backups

    </field>
</record>

  <menuitem id="utepda_backup_sqlite.menu_root"
  name="Backup Sqlite" />

  <menuitem id="menu_log"
  name="Backup log"
  parent="utepda_backup_sqlite.menu_root"
  sequence="10"
  action="utepda_backup_sqlite.backup_log_action" />

models.py

class BackupInfo(models.Model):
    _name = 'utepda_backup_sqlite.backup'
    _description = 'Clase que guarda la informacion de las salvas realizadas'

    name = fields.Char("Nombre")
    fecha_hora = fields.Datetime(string='Fecha-Hora')

ir.model.access.csv

id,name,model_id:id,group_id:id,perm_read,perm_write,perm_create,perm_unlink
access_backup_sqlite,access_backup_sqlite,model_utepda_backup_sqlite_backup,,1,1,1,1

Body:
It'll work if you have a menu root and a submenu root where your menu items will match on! Here is an example:

<!-- menu root -->
<menuitem id="sqlite_menu_root"
  name="Sqlite" />

<!-- submenu root -->
<menuitem id="sqlite_submenu_root"
  parent="sqlite_menu_root"
  name="Backup" />

<!-- App menu items -->
<menuitem id="sqlite_submenu_root"
  parent="sqlite_submenu_root"
  name="Backup Sqlite"
  sequence="10"
  action="backup_sqlite_action"/>

<menuitem id="menu_log"
  name="Backup log"
  parent="utepda_backup_sqlite.menu_root"
  sequence="10"
  action="backup_log_action" />