问:
pyautocad - automate drawing - import DWG - write text - import image
i'm not a professional coder and i'm so sorry for my english :)
i hope you understand.

I'm trying to automate part of my job.
i have to create dwg; every layer for me is a sheet (like A4 paper), for that reason i have to change layer and import specific dwg/dxf from my repository symbol.

For example i have to:
(start new project)
open newproject.dwg
(paste dwg)
import C:\repository_cad\symbol1.dwg in layer n°3 with coordinate X 100 Y 200.
(write text in the middle of symbol)
write "SYMBOL_1" layer n°3 coordinate X 150 Y200 alignment center.
(insert logo image)
import C:\repository_cad\image1.jpg in coordinate X 10 Y 20

i'm trying to use pyautocad, but i cant find a command for import dxf, and i dont find information about changing layer.
i find out only the command for draw the line, circle ecc, but if i have to re-draw all my repository by python i need to much time, i hope is possible copy draw from another dwg and paste it in my new dwg.

can someone give to me a little help with these 3 command?
maybe is not possible making this stuff on pyautocad? is there other library for python?

i read the docs but i dont see info about some import function.
so, i tried:

```<code>from pyautocad import Autocad, APoint
acad = Autocad(create_if_not_exists=False)
acad.prompt("Hello, Autocad from Python\n")
print (acad.doc.Name)
</code>```

and it's works, on autocad terminal i can see "Hello, Autocad from Python"
in the Docs i find out how write a autocad-command from python.
The function is:
prompt()
i tried:

```<code>acad.prompt('-INSERT') #-INSERT is the autocad command for import dxf or dwg
acad.prompt('C:\SPAC\Librerie\Elettr\02-15-04.dwg')#this is the path of the cad
acad.prompt('-15 -15') #coord X Y of the point where i want to paste
acad.prompt('1') # 1 is the scale factor in X
acad.prompt('1') # 1 is the scale factor in Y (autocad askt first in X and after in Y
acad.prompt('0') #degree of rotation
</code>```

at this point i havent error on python and no error on autocad terminal, but the draw not appear on cad

thanks
Max

答:
acad.prompt() will just echo the string to the command line. What you are looking for is acad.doc.SendCommand(), e.g.

```<code>acad.doc.SendCommand('-INSERT ')
</code>```

Notice there is a blank space after the autocad command, that stands for  to activate the command.

Body:
i'm not a professional coder and i'm so sorry for my english :)
i hope you understand.

I'm trying to automate part of my job.
i have to create dwg; every layer for me is a sheet (like A4 paper), for that reason i have to change layer and import specific dwg/dxf from my repository symbol.

For example i have to:
(start new project)
open newproject.dwg
(paste dwg)
import C:\repository_cad\symbol1.dwg in layer n°3 with coordinate X 100 Y 200.
(write text in the middle of symbol)
write "SYMBOL_1" layer n°3 coordinate X 150 Y200 alignment center.
(insert logo image)
import C:\repository_cad\image1.jpg in coordinate X 10 Y 20

i'm trying to use pyautocad, but i cant find a command for import dxf, and i dont find information about changing layer.
i find out only the command for draw the line, circle ecc, but if i have to re-draw all my repository by python i need to much time, i hope is possible copy draw from another dwg and paste it in my new dwg.

can someone give to me a little help with these 3 command?
maybe is not possible making this stuff on pyautocad? is there other library for python?

i read the docs but i dont see info about some import function.
so, i tried:

from pyautocad import Autocad, APoint
acad = Autocad(create_if_not_exists=False)
acad.prompt("Hello, Autocad from Python\n")
print (acad.doc.Name)

and it's works, on autocad terminal i can see "Hello, Autocad from Python"
in the Docs i find out how write a autocad-command from python.
The function is:
prompt()
i tried:

acad.prompt('-INSERT') #-INSERT is the autocad command for import dxf or dwg
acad.prompt('C:\SPAC\Librerie\Elettr\02-15-04.dwg')#this is the path of the cad
acad.prompt('-15 -15') #coord X Y of the point where i want to paste
acad.prompt('1') # 1 is the scale factor in X
acad.prompt('1') # 1 is the scale factor in Y (autocad askt first in X and after in Y
acad.prompt('0') #degree of rotation

at this point i havent error on python and no error on autocad terminal, but the draw not appear on cad

thanks
Max

Body:
acad.prompt() will just echo the string to the command line. What you are looking for is acad.doc.SendCommand(), e.g.

acad.doc.SendCommand('-INSERT ')

Notice there is a blank space after the autocad command, that stands for  to activate the command.


来源: stackexchange

问:
Google automl translate with tags
I have created a custom Model with Google AutoML. And I would like to use some "tags" such has  and make sure it doesn't get translated by Google AutoML. I expect that these tags would be copied as is in the target language at the corresponding place. `

Is there such a feature? I didn't find anything in their documentation.

Example:

The dog is walking <tag> outside.  --- >  Le chien marche <tag> dehors.

答:
I finally found the answer.

You first need to specify "text/html" as mime_type in your request.

And you need to put any text you want to keep as is between these tags:
(you can use any of the two ways)

```<code><span translate="no">Your text</span>

<span class="notranslate">Your text</span>
</code>```

ContentLicense: CC BY-SA 4.0

Title: Google automl translate with tags

Body:
I finally found the answer.

You first need to specify "text/html" as mime_type in your request.

And you need to put any text you want to keep as is between these tags:
(you can use any of the two ways)

<span translate="no">Your text</span>

<span class="notranslate">Your text</span>


问:
How to delete a row in 2 tables which has the same id. How to use join
DELETE FROM tbl_usergroups,'tbl_group' WHERE (tbl_usergroups.tbl_group_GroupID='tbl_group.GroupID') AND(tbl_usergroups.tbl_group_GroupID=27)

GroupID is a foreign key to tbl_usergroups

答:
if the rows are 1:1 mapping then you could use a view over the two tables and delete joined row from the view.

See this answer Does deleting row from view delete row from base table - MYsql? for more information.

ContentLicense: CC BY-SA 3.0


问:
Request blocked by CORS policy after update to Edge 98.0.1108.43: Request had no target IP address space, yet the resource is in address space private
This problem also happens in Chrome.

Error in console:

Access to XMLHttpRequest at 'http://192.168.x.xxx:xxxx/' from origin
'http://xx.xxxx.com' has been blocked by CORS policy: Request had no
target IP address space, yet the resource is in address space
private.

My Edge worked fine last month. The problem started to happen after  updating Edge.

The flag #block-insecure-private-network-requests is set to disabled.

Does anyone know how to fix this problem without reverting the browser to an old version?

答:
Similar problem solved

So for edge, just replace the regedit path

"Computer\HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Google\Chrome"

to

"Computer\HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Edge"

Note that changing this setting will effect all urls.

More secure way is setting another regedit key, which is InsecurePrivateNetworkRequestsAllowedForUrls

Steps:

open regedit

go to the path "Computer\HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Edge\InsecurePrivateNetworkRequestsAllowedForUrls" (create if it not exists)

add string(REG_SZ), the key should be integers like "1,2,3,...", and the value for each string is the url you want to pass cors policy

E.g.

```<code>SOFTWARE\Policies\Microsoft\Edge\InsecurePrivateNetworkRequestsAllowedForUrls\1 = "http://www.example.com:8080"
SOFTWARE\Policies\Microsoft\Edge\InsecurePrivateNetworkRequestsAllowedForUrls\2 = "[*.]example.edu"
</code>```

Body:
Similar problem solved

So for edge, just replace the regedit path

"Computer\HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Google\Chrome"

to

"Computer\HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Edge"

Note that changing this setting will effect all urls.

More secure way is setting another regedit key, which is InsecurePrivateNetworkRequestsAllowedForUrls

Steps:

open regedit

go to the path "Computer\HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Edge\InsecurePrivateNetworkRequestsAllowedForUrls" (create if it not exists)

add string(REG_SZ), the key should be integers like "1,2,3,...", and the value for each string is the url you want to pass cors policy

E.g.

SOFTWARE\Policies\Microsoft\Edge\InsecurePrivateNetworkRequestsAllowedForUrls\1 = "http://www.example.com:8080"
SOFTWARE\Policies\Microsoft\Edge\InsecurePrivateNetworkRequestsAllowedForUrls\2 = "[*.]example.edu"


问:
python time complexity quick sort algorithm
```<code>def partition(A, l, r):
    p = A[l]
    stack = A[l]
    A[l] = A[r]
    A[r] = stack
    s = l

    for i in range(l, r):

        if A[i] <= p:

            stack2 = A[i]
            A[i] = A[s]
            A[s] = stack2
            s += 1

    stack3 = A[s]
    A[s] = A[r]
    A[r] = stack3

    return s

def quicksort(A, l, r):

    if l < r:

        q = partition(A, l, r)
        quicksort(A, l, q - 1)
        quicksort(A, q + 1, r)
    return A
</code>```

I've written "maybe" quicksort algorithm, as I've noticed here the time complexity of partition was O(n) because of the for loop, Also the complexity in quicksort seems to be at least O(n). The question: how is it possible for the entire code to have total time complexity of O(nlogn).

答:
You partition by 2 each level till you get individual elements. Partitioning and comparison what makes the time complexity. You make n comparisons in each level and you will be partioning log2(n) times.

In the worst case, your array is already sorted and you will be partitioning n times and still make n comparisons in each level.

Body:
def partition(A, l, r):
    p = A[l]
    stack = A[l]
    A[l] = A[r]
    A[r] = stack
    s = l

    for i in range(l, r):

        if A[i] <= p:

            stack2 = A[i]
            A[i] = A[s]
            A[s] = stack2
            s += 1

    stack3 = A[s]
    A[s] = A[r]
    A[r] = stack3

    return s

def quicksort(A, l, r):

    if l < r:

        q = partition(A, l, r)
        quicksort(A, l, q - 1)
        quicksort(A, q + 1, r)
    return A

I've written "maybe" quicksort algorithm, as I've noticed here the time complexity of partition was O(n) because of the for loop, Also the complexity in quicksort seems to be at least O(n). The question: how is it possible for the entire code to have total time complexity of O(nlogn).


问:
Detecting corrupted OGG files
I have recently been converting large batches of WEM files, from a video game.
When I use a tool to convert them, it converts them into an OGG file. I then use Audacity to convert them into a WAV file so I can use it practically. When I do batch converting in Audacity, it works, but every once in a while Audacity freezes. This is because Audacity is trying to read a corrupt OGG file, and crashes. This wouldn't be so hard to weed out the corrupt files, if they weren't named after numbers! (e.g. 3147685.ogg) I am used to programming in Java. Is their any program, script, or website I can use to delete the corrupt ogg files, so I can convert the rest to WAVs easily.
Please help.
Thank You,
-Blue</p>

答:
oggz-validate validates only the container, but it does not try to decode contents. You can try instead:

```<code>ffmpeg -i file.ogg -f null -err_detect +crccheck+bitstream+buffer+explode+careful+compliant+aggressive -v error -xerror -
</code>```

Title: Detecting corrupted OGG files

Body:
oggz-validate validates only the container, but it does not try to decode contents. You can try instead:

ffmpeg -i file.ogg -f null -err_detect +crccheck+bitstream+buffer+explode+careful+compliant+aggressive -v error -xerror -


问:
Show Only NaT rows in python
Can anyone help me?

I want to check how many transactions are not paid.

Which is I need to show the table that 'paid_at' columns is NaT right?(CMIIW)

How to solve it?

Here is the table

答:
Try this:</p>
```<code>not_paid = df[df['paid_at'].isna()]
</code>```

Title: Show Only NaT rows in python

Body:
Try this:

not_paid = df[df['paid_at'].isna()]


问:
What is this -Command error and how do i get rid of it?
So I've been following a online tutorial and writing it myself so I could get used to the errors, but I now have a error "unknown Option "-Command"

It seems to only effect the ok button that should close the window.

Any help into understanding the problem and how to get rid of it would be greatly appreciated

in order to make user file for login, simply create a document titled "user" with text in document as:
user
123

This will be the username and password for login

Code is below:

```<code>from tkinter import *
import os

def delete2():
    screen3.destroy()

def delete3():
    screen4.destry()

def delete4():
    screen5.destroy()

def login_sucess():
    global screen3
    screen3 = Toplevel(screen)
    screen3.title("Sucess")
    screen3.geometry("150x100")
    Label(screen3, text = "Login Sucess").pack()
    Button(screen3, text = "OK", Command =delete2).pack()

def password_not_recognised():
    global screen4
    screen4 = Toplevel(screen)
    screen4.title("Sucess")
    screen4.geometry("150x100")
    Label(screen4, text = "Password Error").pack()
    Button(screen4, text = "OK", Command =delete2).pack()

def user_not_found():
    global screen5
    screen5 = Toplevel(screen)
    screen5.title("Sucess")
    screen5.geometry("150x100")
    Label(screen5, text = "User Not Found").pack()
    Button(screen5, text = "OK", Command =delete2).pack()

def login_verify():
    username1 = username_verify.get()
    password1 = password_verify.get()
    username_entry1.delete(0, END)
    password_entry1.delete(0, END)

    list_of_files = os.listdir()
    if username1 in list_of_files:
        file1 = open(username1, "r")
        verify = file1.read().splitlines()
        if password1 in verify:
            login_sucess()
        else:
            password_not_recognised()

    else:
        user_not_found()

def login():
    global screen2
    screen2 = Toplevel(screen)
    screen2.title("Login")
    screen2.geometry("300x250")
    Label(screen2, text = "please enter details below to login").pack()
    Label(screen2, text = "").pack()

    global username_verify
    global password_verify

    username_verify = StringVar()
    password_verify = StringVar()

    global username_entry1
    global password_entry1

    Label(screen2, text = "Username * ").pack()
    username_entry1 = Entry(screen2, textvariable = username_verify)
    username_entry1.pack()
    Label(screen2, text = "").pack()
    Label(screen2, text = "Password * ").pack()
    password_entry1 = Entry(screen2, textvariable = password_verify)
    password_entry1.pack()
    Label(screen2, text = "").pack()
    Button(screen2, text = "Login", width = 10, height = 1, command = login_verify).pack()

def main_screen():
    global screen
    screen = Tk()
    screen.geometry("300x250")
    screen.title("Remote Monitoring Site 1")
    Label(text = "Remote Monitoring Site 1", bg = "grey", width = "300", height = "2", font = ("Calibri", 13)).pack()
    Label(text = "").pack()
    Button(text = "Login", width = "30", height = "2", command = login).pack()
    Label(text = "").pack()
    Button(text = "Register", width = "30", height = "2", command = register).pack()

    screen.mainloop()

main_screen()
</code>```

Full error is as follows:

self.tk.call(
_tkinter.TclError: unknown option "-Command"

I have tried researching but have found no solution to my issue.

答: Options for python functions are case-sensitive, meaning command (which is the option you want to set) is not the same as Command. Change Button(screen4, text = "OK", Command =delete2).pack() to Button(screen4, text = "OK", command =delete2).pack() in all instances.

Body:
So I've been following a online tutorial and writing it myself so I could get used to the errors, but I now have a error "unknown Option "-Command"

It seems to only effect the ok button that should close the window.

Any help into understanding the problem and how to get rid of it would be greatly appreciated

in order to make user file for login, simply create a document titled "user" with text in document as:
user
123

This will be the username and password for login

Code is below:

from tkinter import *
import os

def delete2():
    screen3.destroy()

def delete3():
    screen4.destry()

def delete4():
    screen5.destroy()

def login_sucess():
    global screen3
    screen3 = Toplevel(screen)
    screen3.title("Sucess")
    screen3.geometry("150x100")
    Label(screen3, text = "Login Sucess").pack()
    Button(screen3, text = "OK", Command =delete2).pack()

def password_not_recognised():
    global screen4
    screen4 = Toplevel(screen)
    screen4.title("Sucess")
    screen4.geometry("150x100")
    Label(screen4, text = "Password Error").pack()
    Button(screen4, text = "OK", Command =delete2).pack()

def user_not_found():
    global screen5
    screen5 = Toplevel(screen)
    screen5.title("Sucess")
    screen5.geometry("150x100")
    Label(screen5, text = "User Not Found").pack()
    Button(screen5, text = "OK", Command =delete2).pack()

def login_verify():
    username1 = username_verify.get()
    password1 = password_verify.get()
    username_entry1.delete(0, END)
    password_entry1.delete(0, END)

    list_of_files = os.listdir()
    if username1 in list_of_files:
        file1 = open(username1, "r")
        verify = file1.read().splitlines()
        if password1 in verify:
            login_sucess()
        else:
            password_not_recognised()

    else:
        user_not_found()

def login():
    global screen2
    screen2 = Toplevel(screen)
    screen2.title("Login")
    screen2.geometry("300x250")
    Label(screen2, text = "please enter details below to login").pack()
    Label(screen2, text = "").pack()

    global username_verify
    global password_verify

    username_verify = StringVar()
    password_verify = StringVar()

    global username_entry1
    global password_entry1

    Label(screen2, text = "Username * ").pack()
    username_entry1 = Entry(screen2, textvariable = username_verify)
    username_entry1.pack()
    Label(screen2, text = "").pack()
    Label(screen2, text = "Password * ").pack()
    password_entry1 = Entry(screen2, textvariable = password_verify)
    password_entry1.pack()
    Label(screen2, text = "").pack()
    Button(screen2, text = "Login", width = 10, height = 1, command = login_verify).pack()

def main_screen():
    global screen
    screen = Tk()
    screen.geometry("300x250")
    screen.title("Remote Monitoring Site 1")
    Label(text = "Remote Monitoring Site 1", bg = "grey", width = "300", height = "2", font = ("Calibri", 13)).pack()
    Label(text = "").pack()
    Button(text = "Login", width = "30", height = "2", command = login).pack()
    Label(text = "").pack()
    Button(text = "Register", width = "30", height = "2", command = register).pack()

    screen.mainloop()

main_screen()

Full error is as follows:

self.tk.call(
_tkinter.TclError: unknown option "-Command"

I have tried researching but have found no solution to my issue.


问:
vb.net modify column in CSV file
I have a CSV file with many rows in which I need to update/replace column four's value using VB.NET. There are no headers on the columns so the loop can start on row one.

infile.csv

   "value1","value2","value3","value4"

After much googling, there are lots of examples on how to read and write CSV files, but none quite what is needed. I know there are multiple ways to accomplish this task, but a requirement is that it's done with VB.NET. Any help would be greatly appreciated.

Final code ported from Marco's C# answer

```<code>    Private Sub CSVmod(ByVal strFileName As String, ByVal newFileName As String)

    Dim strLines As String() = File.ReadAllLines(strFileName)
    Dim strList As New List(Of String)
    Dim strReplace As String = "test"

    For Each line In strLines
        Dim strValues As String() = line.Split(",")
        If (strValues.Length = 14) Then
            strValues(3) = strReplace

            strList.Add(String.Join(",", strValues))
        End If

    Next

    File.WriteAllLines(newFileName, strList.ToArray())
</code>```

答:
Use python....one line of code

df = pandas.read_csv('file.csv)

Title: vb.net modify column in CSV file

Body:
I have a CSV file with many rows in which I need to update/replace column four's value using VB.NET. There are no headers on the columns so the loop can start on row one.

infile.csv

   "value1","value2","value3","value4"

After much googling, there are lots of examples on how to read and write CSV files, but none quite what is needed. I know there are multiple ways to accomplish this task, but a requirement is that it's done with VB.NET. Any help would be greatly appreciated.

Final code ported from Marco's C# answer

    Private Sub CSVmod(ByVal strFileName As String, ByVal newFileName As String)

    Dim strLines As String() = File.ReadAllLines(strFileName)
    Dim strList As New List(Of String)
    Dim strReplace As String = "test"

    For Each line In strLines
        Dim strValues As String() = line.Split(",")
        If (strValues.Length = 14) Then
            strValues(3) = strReplace

            strList.Add(String.Join(",", strValues))
        End If

    Next

    File.WriteAllLines(newFileName, strList.ToArray())


问:
Powershell even and odd numbers
It get a file as a parameter and I need the sum of the even and odd numbers in the even and odd lines of the file

```<code>Input:
1 2 3 4 5
2 3 9 5
4 6 1
6 3 1 2 4
Output:
Sum of odd numbers:(1+3+5+1)=10
Sum of even numbers:(2+6+2+4)=12
</code>```

I tried with foreach and without it, but I don't know how to convert strings from a file to an integer and put it an array

答:
Looking at others I felt the string generation could be simplified. Also use (abuse?) of Powershell dynamic casting. A bit of google research including random other pages provided inspiration and useful bits.</p>
```<code>#read input, split on any whitespace
$inputFile = (Get-Content "C:\temp\numbers.txt") -split "\s"

#generate odds and evens arrays.
$inputFile | foreach{ if($_ % 2 -eq 0) {$evens += $_} else{$odds += $_}}

#make output strings
"Sum of odd numbers:(" + ($odds -join '+') + ")=" + (($odds|Measure-Object -Sum).Sum)
"Sum of even numbers:(" + ($evens -join '+') + ")=" + (($evens|Measure-Object -Sum).Sum)
</code>```

Title: Powershell even and odd numbers

Body:
It get a file as a parameter and I need the sum of the even and odd numbers in the even and odd lines of the file

Input:
1 2 3 4 5
2 3 9 5
4 6 1
6 3 1 2 4
Output:
Sum of odd numbers:(1+3+5+1)=10
Sum of even numbers:(2+6+2+4)=12

I tried with foreach and without it, but I don't know how to convert strings from a file to an integer and put it an array

Body:
Looking at others I felt the string generation could be simplified. Also use (abuse?) of Powershell dynamic casting. A bit of google research including random other pages provided inspiration and useful bits.

#read input, split on any whitespace
$inputFile = (Get-Content "C:\temp\numbers.txt") -split "\s"

#generate odds and evens arrays.
$inputFile | foreach{ if($_ % 2 -eq 0) {$evens += $_} else{$odds += $_}}

#make output strings
"Sum of odd numbers:(" + ($odds -join '+') + ")=" + (($odds|Measure-Object -Sum).Sum)
"Sum of even numbers:(" + ($evens -join '+') + ")=" + (($evens|Measure-Object -Sum).Sum)


问:
Accessing Data in Nested []struct
I'm working on unmarshaling some nested json data that I have already written a struct for. I've used a tool that will generate a struct based off json data, but am a bit confused how to work with accessing nested json data (and fields can sometimes be emtpy).

Here is an example of struct:

```<code>type SomeJson struct {
status         string `json:"status"`
message        string `json:"message"`
someMoreData []struct {
    constant bool `json:"constant,omitempty"`
    inputs   []struct {
        name string `json:"name"`
        type string `json:"type"`
    } `json:"inputs,omitempty"`
    Name    string `json:"name,omitempty"`
    Outputs []struct {
        Name string `json:"name"`
        Type string `json:"type"`
    } `json:"outputs,omitempty"`
</code>```

I'm able to unmarshal the json data and access the top level fields (such as status and message), but am having trouble accessing any data under the someMoreData field. I understand this field is a (I assume an unknown) map of structs, but only have experience working with basic single level json blobs.

For reference this is the code I have to unmarshal the json and am able to access the top level fields.

```<code>someData := someJson{}
json.Unmarshal(body, &someData)
</code>```

So what is exactly the best to access some nested fields such as inputs.name or outputs.name?

答:
to iterate over your particular struct you can use:

```<code>for _, md := range someData.someMoreData {
    println(md.Name)
    for _, out := range md.Outputs {
        println(out.Name, out.Type)
    }
}
</code>```

to access specific field:

```<code>someData.someMoreData[0].Outputs[0].Name
</code>```

Title: Accessing Data in Nested []struct

Body:
I'm working on unmarshaling some nested json data that I have already written a struct for. I've used a tool that will generate a struct based off json data, but am a bit confused how to work with accessing nested json data (and fields can sometimes be emtpy).

Here is an example of struct:

type SomeJson struct {
status         string `json:"status"`
message        string `json:"message"`
someMoreData []struct {
    constant bool `json:"constant,omitempty"`
    inputs   []struct {
        name string `json:"name"`
        type string `json:"type"`
    } `json:"inputs,omitempty"`
    Name    string `json:"name,omitempty"`
    Outputs []struct {
        Name string `json:"name"`
        Type string `json:"type"`
    } `json:"outputs,omitempty"`

I'm able to unmarshal the json data and access the top level fields (such as status and message), but am having trouble accessing any data under the someMoreData field. I understand this field is a (I assume an unknown) map of structs, but only have experience working with basic single level json blobs.

For reference this is the code I have to unmarshal the json and am able to access the top level fields.

someData := someJson{}
json.Unmarshal(body, &someData)

So what is exactly the best to access some nested fields such as inputs.name or outputs.name?

Body:
to iterate over your particular struct you can use:

for _, md := range someData.someMoreData {
    println(md.Name)
    for _, out := range md.Outputs {
        println(out.Name, out.Type)
    }
}

to access specific field:

someData.someMoreData[0].Outputs[0].Name


问:
How to work with messages from WTelegramClient updates? (get chat/user infos)
I'm new to the WTelegramClient C# Library and was used to TLSharp (not working anymore)

I'm trying to understand how I get User info after update is received,
I have the example code that listen to updates and write them in console
but I can't understand how I can respond to the user that sent the message (new update)

I think I need the user id/access_hash to send message to the sender but I can't understand how

Here is how I get the new messages but it can get only username or name/id

```<code>   private static void DisplayMessage(MessageBase messageBase, bool edit = false)
            {
                if (edit) Console.Write("(Edit): ");
                switch (messageBase)
                {
                    case Message m: Console.WriteLine($"{Peer(m.from_id) ?? m.post_author} in {Peer(m.peer_id)}> {m.message}"); break;
                    case MessageService ms: Console.WriteLine($"{Peer(ms.from_id)} in {Peer(ms.peer_id)} [{ms.action.GetType().Name[13..]}]"); break;
                }
            }
</code>```

Here i can get the name or username of sender(if have) and the message itself
MessageService ('user' not channel or group) for example get me only firstname and lastname

How to get all info of sender or chat itself (i want to try mark as read the message)

I'm used to TLSharp and the new library WTelegramClient is different.

Thanks!!!

答:
Below is a quick example on how to modify DisplayMessage to react to a message sent in private from a user, get the details about this user, verify who it is and which text was sent to us, and then send him a message back.

Notes:

For this example to work, you will need the latest version of Program_ListenUpdates.cs with static variables

DisplayMessage is now async Task, in order to use await

You can pass user to send a message because class User is implicitly converted to InputPeerUser (with the user id/access_hash).

You can do similarly for messages coming from chats, using PeerChat/PeerChannel classes and the _chats dictionary to get chat details

private static async Task DisplayMessage(MessageBase messageBase, bool edit = false)
{
    if (edit) Console.Write("(Edit): ");
    switch (messageBase)
    {
        case Message m:
            Console.WriteLine($"{Peer(m.from_id) ?? m.post_author} in {Peer(m.peer_id)}> {m.message}");
            if (m.flags.HasFlag(Message.Flags.out_))
                break; // ignore our own outgoing messages
            if (m.Peer is PeerUser pu) // got a message in a direct chat with a user
            {
                if (_users.TryGetValue(pu.user_id, out var user)) // get user details
                {
                    if (user.username == "Wiz0u" && m.message == "hello")
                    {
                        await Client.SendMessageAsync(user, $"hi {user.first_name}, I'm {My.first_name}");
                    }
                }
            }
            break;
        case MessageService ms:
            Console.WriteLine($"{Peer(ms.from_id)} in {Peer(ms.peer_id)} [{ms.action.GetType().Name[13..]}]");
            break;
    }
}
```

Body:
I'm new to the WTelegramClient C# Library and was used to TLSharp (not working anymore)

I'm trying to understand how I get User info after update is received,
I have the example code that listen to updates and write them in console
but I can't understand how I can respond to the user that sent the message (new update)

I think I need the user id/access_hash to send message to the sender but I can't understand how

Here is how I get the new messages but it can get only username or name/id

   private static void DisplayMessage(MessageBase messageBase, bool edit = false)
            {
                if (edit) Console.Write("(Edit): ");
                switch (messageBase)
                {
                    case Message m: Console.WriteLine($"{Peer(m.from_id) ?? m.post_author} in {Peer(m.peer_id)}> {m.message}"); break;
                    case MessageService ms: Console.WriteLine($"{Peer(ms.from_id)} in {Peer(ms.peer_id)} [{ms.action.GetType().Name[13..]}]"); break;
                }
            }

Here i can get the name or username of sender(if have) and the message itself
MessageService ('user' not channel or group) for example get me only firstname and lastname

How to get all info of sender or chat itself (i want to try mark as read the message)

I'm used to TLSharp and the new library WTelegramClient is different.

Thanks!!!


问:
int issue in g++/mysql/redhat
I haven't written C in quite some time and am writing an app using the MySQL C API, compiling in g++ on redhat.

So i start outputting some fields with printfs... using the oracle api, with PRO*C, which i used to use (on suse, years ago), i could select an int and output it as:

```
int some_int;
printf("%i",some_int);
```

I tried to do that with mysql ints and i got 8 random numbers displayed... i thought this was  a mysql api issue and some config issue with my server, and i wasted a few hours trying to fix it, but couldn't, and found that i could do:

```
int some_int;
printf("%s",some_int);
```

and it would print out the integer properly. Because i'm not doing computations on the values i am extracting, i thought this an okay solution.

UNTIL I TRIED TO COUNT SOME THINGS....

I did a simple:

```
int rowcount;
for([stmt]){
rowcount++;
}
printf("%i",rowcount);
```

i am getting an 8 digit random number again... i couldn't figure out what the deal is with ints on this machine.

then i realized that if i initialize the int to zero, then i get a proper number.

can someone please explain to me under what conditions you need to initialize int variables to zero? i don't recall doing this every time in my old codebase, and i didn't see it in the example that i was modeling my mysql_stmt code from...

is there something i'm missing? also, it's entirely possible i've forgotten this is required each time

thanks...

答:
Only global and static values will be initialized to zero. The variables on the stack will always contain garbage value if not initialized.</p>

```<code>int g_var; //This is a global varibale. So, initialized to zero
int main()
{

int s_var = 0; //This is on stack. So, you need to explicitly initialize
static int stat_var;  //This is a static variable,  So, initialized to zero
}
</code>```

OwnerDisplayName: hcmk

LastEditorDisplayName: FreeMemory

ContentLicense: CC BY-SA 2.5

Title: int issue in g++/mysql/redhat

Body:
I haven't written C in quite some time and am writing an app using the MySQL C API, compiling in g++ on redhat.

So i start outputting some fields with printfs... using the oracle api, with PRO*C, which i used to use (on suse, years ago), i could select an int and output it as:

int some_int;
printf("%i",some_int);

I tried to do that with mysql ints and i got 8 random numbers displayed... i thought this was  a mysql api issue and some config issue with my server, and i wasted a few hours trying to fix it, but couldn't, and found that i could do:

int some_int;
printf("%s",some_int);

and it would print out the integer properly. Because i'm not doing computations on the values i am extracting, i thought this an okay solution.

UNTIL I TRIED TO COUNT SOME THINGS....

I did a simple:

int rowcount;
for([stmt]){
rowcount++;
}
printf("%i",rowcount);

i am getting an 8 digit random number again... i couldn't figure out what the deal is with ints on this machine.

then i realized that if i initialize the int to zero, then i get a proper number.

can someone please explain to me under what conditions you need to initialize int variables to zero? i don't recall doing this every time in my old codebase, and i didn't see it in the example that i was modeling my mysql_stmt code from...

is there something i'm missing? also, it's entirely possible i've forgotten this is required each time

thanks...

Body:
Only global and static values will be initialized to zero. The variables on the stack will always contain garbage value if not initialized.

int g_var; //This is a global varibale. So, initialized to zero
int main()
{

int s_var = 0; //This is on stack. So, you need to explicitly initialize
static int stat_var;  //This is a static variable,  So, initialized to zero
}

OwnerDisplayName: chappar

LastEditorDisplayName: chappar


问:
What are convincing examples where pointer arithmetic is preferable to array subscripting?
I'm preparing some slides for an introductory C class, and I'm trying to present good examples (and motivation) for using pointer arithmetic over array subscripting.

A lot of the examples I see in books are fairly equivalent. For example, many books show how to reverse the case of all values in a string, but with the exception of replacing an a[i]  with a *p the code is identical.

I am looking for a good (and short) example with single-dimensional arrays where pointer arithmetic can produce significantly more elegant code. Any ideas?

答:
```<code>#include ctype.h
void skip_spaces( const char **ppsz )
{
  const char *psz = *ppsz;
  while( isspace(*psz) )
    psz++;
  *ppsz = psz;
}

void fn(void)
{
  char a[]="  Hello World!";
  const char *psz = a;
  skip_spaces( &psz );
  printf("\n%s", psz);
}
</code>```

OwnerDisplayName: Uri


问:
How can we insert text into Header/Footer after creating Header/Footer in google docs api using PHP?
I am working on google docs api. I want to insert content in header/footer in google docs using google docs API with PHP.

So, Firstly I am creating header/Footer request by the following request-

```<code>$requests[] = new Google_Service_Docs_Request(array(
  "createFooter" => [
    "sectionBreakLocation" => [
      "index" => 0,
      "segmentId" => "",
    ],
    "type" => "DEFAULT",
  ],
));

$requests[] = new Google_Service_Docs_Request(array(
  "createHeader" => [
    "sectionBreakLocation" => [
      "index" => 0,
      "segmentId" => "",
    ],
    "type" => "DEFAULT",
  ],
));

$batchUpdateRequest = new Google_Service_Docs_BatchUpdateDocumentRequest(array(
    'requests' => $requests
));

$response = $service->documents->batchUpdate($documentId, $batchUpdateRequest);
</code>```

After this I am able to get the Header Id and Footer Id from the response, like this-

```<code>$footerId = $response->replies[0]->createFooter->footerId;
$headerId = $response->replies[1]->createHeader->headerId;
print("footerid".$footerId);
print("headerid".$headerId);
</code>```

But, now I want to insert some texts in this above created header/footer.For that I was doing like this-

```<code>$requests[] = new Google_Service_Docs_Request(array(
  "createFooter" => [
    "sectionBreakLocation" => [
      "index" => 0,
      "segmentId" => "",
    ],
    "type" => "DEFAULT",
  ],
));

$requests[] = new Google_Service_Docs_Request(array(
  "createHeader" => [
    "sectionBreakLocation" => [
      "index" => 0,
      "segmentId" => "",
    ],
    "type" => "DEFAULT",
  ],
));

$batchUpdateRequest = new Google_Service_Docs_BatchUpdateDocumentRequest(array(
    'requests' => $requests
));

$response = $service->documents->batchUpdate($documentId, $batchUpdateRequest);

$footerId = $response->replies[0]->createFooter->footerId;
$headerId = $response->replies[1]->createHeader->headerId;
print("footerid".$footerId);
print("headerid".$headerId);

$requests [] = new Google_Service_Docs_Request([
  'insertText' => [
        'text' => "Sample7",
        'location' => [
          'segmentId' => $footerId,
          'index' => 0,
        ],
        'text' => 'sample text',
    ]
]);
$batchUpdateRequest = new Google_Service_Docs_BatchUpdateDocumentRequest(array(
  'requests' => $requests
));

$responses = $service->documents->batchUpdate($documentId, $batchUpdateRequest);
</code>```

I thought by updating my batch again I can able to insert text in my header/footer, but unfortunately it is not the right way and I am stuck at this point.If this is not the way then how we can insert text into header/footer in google docs using PHP.

答:
When the text is inserted into the header and footer, I thought that there is an important point. When the header and footer are created to the new Google Document, your batch request can be used. But when the header and footer have already been existing in the Google Document, when "createHeader" and "createFooter" requests are run, an error occurs. Because the header and footer can be created one time. I thought that this might be the reason for your issue.

If my understanding is correct, how about the following sample script?

Sample script:

$documentId = "###"; // Please set your Google Document ID.

// Check the header and footer IDs.
$obj = $service->documents->get($documentId);
$documentStyle = $obj->getDocumentStyle();
$headerId = $documentStyle->getDefaultHeaderId();
$footerId = $documentStyle->getDefaultFooterId();

// If the header or the footer are not existing, those are created. And, retrieve the header ID and the footer ID.
$requests = [];
if (empty($headerId)) {
    array_push($requests,
        new Google_Service_Docs_Request(array(
            "createHeader" => [
            "sectionBreakLocation" => [
                "index" => 0,
            ],
            "type" => "DEFAULT",
            ],
        ))
    );
}
if (empty($footerId)) {
    array_push($requests,
        new Google_Service_Docs_Request(array(
            "createFooter" => [
            "sectionBreakLocation" => [
                "index" => 0,
            ],
            "type" => "DEFAULT",
            ],
        ))
    );
}
if (count($requests) > 0) {
    $batchUpdateRequest = new Google_Service_Docs_BatchUpdateDocumentRequest(array(
        'requests' => $requests
    ));
    $response = $service->documents->batchUpdate($documentId, $batchUpdateRequest);
    $r = $response->getReplies();
    foreach ($r as &$v) {
        $h = $v->getCreateHeader();
        $f = $v->getCreateFooter();
        if (!empty($h)) {
            $headerId = $h->getHeaderId();
        }
        if (!empty($f)) {
            $footerId = $f->getFooterId();
        }
    }
}

// Insert the texts to the header and footer using the header ID and footer ID.
$requests = [
    new Google_Service_Docs_Request([
        'insertText' => [
            'location' => [
                'segmentId' => $headerId,
                'index' => 0,
            ],
            'text' => 'sample text for header',
        ]
    ]),
    new Google_Service_Docs_Request([
        'insertText' => [
            'location' => [
                'segmentId' => $footerId,
                'index' => 0,
            ],
            'text' => 'sample text for footer',
        ]
    ])
];
$batchUpdateRequest = new Google_Service_Docs_BatchUpdateDocumentRequest(array(
    'requests' => $requests
));
$responses = $service->documents->batchUpdate($documentId, $batchUpdateRequest);
```

References:

Method: documents.get

Method: documents.batchUpdate

Body:
I am working on google docs api. I want to insert content in header/footer in google docs using google docs API with PHP.

So, Firstly I am creating header/Footer request by the following request-

$requests[] = new Google_Service_Docs_Request(array(
  "createFooter" => [
    "sectionBreakLocation" => [
      "index" => 0,
      "segmentId" => "",
    ],
    "type" => "DEFAULT",
  ],
));

$requests[] = new Google_Service_Docs_Request(array(
  "createHeader" => [
    "sectionBreakLocation" => [
      "index" => 0,
      "segmentId" => "",
    ],
    "type" => "DEFAULT",
  ],
));

$batchUpdateRequest = new Google_Service_Docs_BatchUpdateDocumentRequest(array(
    'requests' => $requests
));

$response = $service->documents->batchUpdate($documentId, $batchUpdateRequest);

After this I am able to get the Header Id and Footer Id from the response, like this-

$footerId = $response->replies[0]->createFooter->footerId;
$headerId = $response->replies[1]->createHeader->headerId;
print("footerid".$footerId);
print("headerid".$headerId);

But, now I want to insert some texts in this above created header/footer.For that I was doing like this-

$requests[] = new Google_Service_Docs_Request(array(
  "createFooter" => [
    "sectionBreakLocation" => [
      "index" => 0,
      "segmentId" => "",
    ],
    "type" => "DEFAULT",
  ],
));

$requests[] = new Google_Service_Docs_Request(array(
  "createHeader" => [
    "sectionBreakLocation" => [
      "index" => 0,
      "segmentId" => "",
    ],
    "type" => "DEFAULT",
  ],
));

$batchUpdateRequest = new Google_Service_Docs_BatchUpdateDocumentRequest(array(
    'requests' => $requests
));

$response = $service->documents->batchUpdate($documentId, $batchUpdateRequest);

$footerId = $response->replies[0]->createFooter->footerId;
$headerId = $response->replies[1]->createHeader->headerId;
print("footerid".$footerId);
print("headerid".$headerId);

$requests [] = new Google_Service_Docs_Request([
  'insertText' => [
        'text' => "Sample7",
        'location' => [
          'segmentId' => $footerId,
          'index' => 0,
        ],
        'text' => 'sample text',
    ]
]);
$batchUpdateRequest = new Google_Service_Docs_BatchUpdateDocumentRequest(array(
  'requests' => $requests
));

$responses = $service->documents->batchUpdate($documentId, $batchUpdateRequest);

I thought by updating my batch again I can able to insert text in my header/footer, but unfortunately it is not the right way and I am stuck at this point.If this is not the way then how we can insert text into header/footer in google docs using PHP.

Body:
When the text is inserted into the header and footer, I thought that there is an important point. When the header and footer are created to the new Google Document, your batch request can be used. But when the header and footer have already been existing in the Google Document, when "createHeader" and "createFooter" requests are run, an error occurs. Because the header and footer can be created one time. I thought that this might be the reason for your issue.

If my understanding is correct, how about the following sample script?

Sample script:

$documentId = "###"; // Please set your Google Document ID.

// Check the header and footer IDs.
$obj = $service->documents->get($documentId);
$documentStyle = $obj->getDocumentStyle();
$headerId = $documentStyle->getDefaultHeaderId();
$footerId = $documentStyle->getDefaultFooterId();

// If the header or the footer are not existing, those are created. And, retrieve the header ID and the footer ID.
$requests = [];
if (empty($headerId)) {
    array_push($requests,
        new Google_Service_Docs_Request(array(
            "createHeader" => [
            "sectionBreakLocation" => [
                "index" => 0,
            ],
            "type" => "DEFAULT",
            ],
        ))
    );
}
if (empty($footerId)) {
    array_push($requests,
        new Google_Service_Docs_Request(array(
            "createFooter" => [
            "sectionBreakLocation" => [
                "index" => 0,
            ],
            "type" => "DEFAULT",
            ],
        ))
    );
}
if (count($requests) > 0) {
    $batchUpdateRequest = new Google_Service_Docs_BatchUpdateDocumentRequest(array(
        'requests' => $requests
    ));
    $response = $service->documents->batchUpdate($documentId, $batchUpdateRequest);
    $r = $response->getReplies();
    foreach ($r as &$v) {
        $h = $v->getCreateHeader();
        $f = $v->getCreateFooter();
        if (!empty($h)) {
            $headerId = $h->getHeaderId();
        }
        if (!empty($f)) {
            $footerId = $f->getFooterId();
        }
    }
}

// Insert the texts to the header and footer using the header ID and footer ID.
$requests = [
    new Google_Service_Docs_Request([
        'insertText' => [
            'location' => [
                'segmentId' => $headerId,
                'index' => 0,
            ],
            'text' => 'sample text for header',
        ]
    ]),
    new Google_Service_Docs_Request([
        'insertText' => [
            'location' => [
                'segmentId' => $footerId,
                'index' => 0,
            ],
            'text' => 'sample text for footer',
        ]
    ])
];
$batchUpdateRequest = new Google_Service_Docs_BatchUpdateDocumentRequest(array(
    'requests' => $requests
));
$responses = $service->documents->batchUpdate($documentId, $batchUpdateRequest);

References:

Method: documents.get

Method: documents.batchUpdate


问:
How do I add a hyperlink in my text using JavaScript?
I'm really new to JS and I tried googling but it did not help. All I'm trying to do is add the medium Post link into my text as a hyperlink. I'm pretty sure I'm half way there but I can't figure it out:

_$ = document.querySelector.bind(document) ;
var AppendLinkHere = _$("body") // <- put in here some CSS selector that'll be more to your needs
var a = document.createElement('a');
a.text = "Medium Post";
a.href = "https://medium.com/@FundsFi/fundsfi-presale-terms-are-here-whitelisting-requirements-fc798d85b284";

// AppendLinkHere.appendChild(a)
// a.title = 'Well well ...
// a.setAttribute('title', 'Well well that\'s a link');```
<pre class="snippet-code-html lang-html prettyprint-override"><code><s.TextDescription style={{ textAlign: "center", color: "var(--primary-text)", }}>
  blah blah blah blah blah blah blah blah blah blah  Medium Post.
</s.TextDescription></code>```

All I want to do is make it so that when people click on the word Medium Post it takes them to a new tab with the medium link. Also, I got the code from this post while searching for an answer: How do I create a link using javascript? And then I realized that I need to added a CSS selector which I can't figure out how to do. So far I've found this post about: How do you add CSS with Javascript?

答:
In the solution below, the
 element with an id value of link is added to the  element when the page's load event occurs.

let linkElement = document.getElementById('link');
const targetAddress = "https://medium.com/@FundsFi/fundsfi-presale-terms-are-here-whitelisting-requirements-fc798d85b284";

/* The load event is triggered when the page loads. */
window.onload = function() {
  /* The new  element is created. */
  var newLinkElement = document.createElement('a');

  /* A new text node is created. */
  var newContent = document.createTextNode("Medium Post");

  /* The text node is added to the  element. */
  newLinkElement.appendChild(newContent);

  /* The class attribute of the  element is assigned the value "aElementStyle". */
  newLinkElement.setAttribute('class', 'aElementStyle');

  /* The targetAddress variable content is assigned to the href attribute of the  element. */
  newLinkElement.setAttribute('href', targetAddress);

  /* The  element is linked as a child to the
 element whose id value is "link". */
  linkElement.appendChild(newLinkElement);
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.aElementStyle {
  color: white;
  background-color: black;
  text-decoration: none;
}</code>```

```

Body:
I'm really new to JS and I tried googling but it did not help. All I'm trying to do is add the medium Post link into my text as a hyperlink. I'm pretty sure I'm half way there but I can't figure it out:

_$ = document.querySelector.bind(document) ;
var AppendLinkHere = _$("body") // <- put in here some CSS selector that'll be more to your needs
var a = document.createElement('a');
a.text = "Medium Post";
a.href = "https://medium.com/@FundsFi/fundsfi-presale-terms-are-here-whitelisting-requirements-fc798d85b284";

// AppendLinkHere.appendChild(a)
// a.title = 'Well well ...
// a.setAttribute('title', 'Well well that\'s a link');

<s.TextDescription style={{ textAlign: "center", color: "var(--primary-text)", }}>
  blah blah blah blah blah blah blah blah blah blah  Medium Post.
</s.TextDescription>

All I want to do is make it so that when people click on the word Medium Post it takes them to a new tab with the medium link. Also, I got the code from this post while searching for an answer: How do I create a link using javascript? And then I realized that I need to added a CSS selector which I can't figure out how to do. So far I've found this post about: How do you add CSS with Javascript?

Body:
In the solution below, the <div> element with an id value of link is added to the <a> element when the page's load event occurs.

let linkElement = document.getElementById('link');
const targetAddress = "https://medium.com/@FundsFi/fundsfi-presale-terms-are-here-whitelisting-requirements-fc798d85b284";

/* The load event is triggered when the page loads. */
window.onload = function() {
  /* The new <a> element is created. */
  var newLinkElement = document.createElement('a');

  /* A new text node is created. */
  var newContent = document.createTextNode("Medium Post");

  /* The text node is added to the <a> element. */
  newLinkElement.appendChild(newContent);

  /* The class attribute of the <a> element is assigned the value "aElementStyle". */
  newLinkElement.setAttribute('class', 'aElementStyle');

  /* The targetAddress variable content is assigned to the href attribute of the <a> element. */
  newLinkElement.setAttribute('href', targetAddress);

  /* The <a> element is linked as a child to the <div> element whose id value is "link". */
  linkElement.appendChild(newLinkElement);
}

.aElementStyle {
  color: white;
  background-color: black;
  text-decoration: none;
}

<body>
  <div id="link"></div>
</body>


问:
Update with Sub Query Derived Table Error
I have the following SQL statement to simply update the #temp temp table with the latest package version number in our Sybase 15 database.

```<code>UPDATE t
SET versionId = l.latestVersion
FROM #temp t INNER JOIN (SELECT gp.packageId
                                , MAX(gp.versionId) latestVersion
                         FROM Group_Packages gp
                         WHERE gp.groupId IN (SELECT groupId
                                              FROM User_Group
                                              WHERE userXpId = 'someUser')
                         GROUP BY gp.packageId) l
ON t.packageId = l.packageId
</code>```

To me (mainly Oracle & SQL Server experience more than Sybase) there is little wrong with this statement. However, Sybase throws an exception:

```<code>You cannot use a derived table in the FROM clause of an UPDATE or DELETE statement.
</code>```

Now, I don't get what the problem is here. I assume it is because of the aggregation / GROUP BY being used. Of course, I could put the sub query in a temp table and join on it but I really want to know what the 'correct' method should be and what the hell is wrong.

Any ideas or guidance would be much appreciated.

答:
Does this syntax work in Sybase?

```<code>update dstTable T
set (T.field1, T.field2, T.field3) =
       (select S.value1, S.value2, S.value3
        from srcTable S
         where S.key = T.Key);
</code>```

I believe the correlated subquery can be as complicated as you like (including using CTE. etc).  It just has to project the right number (and type) of values.

Body:
I have the following SQL statement to simply update the #temp temp table with the latest package version number in our Sybase 15 database.

UPDATE t
SET versionId = l.latestVersion
FROM #temp t INNER JOIN (SELECT gp.packageId
                                , MAX(gp.versionId) latestVersion
                         FROM Group_Packages gp
                         WHERE gp.groupId IN (SELECT groupId
                                              FROM User_Group
                                              WHERE userXpId = 'someUser')
                         GROUP BY gp.packageId) l
ON t.packageId = l.packageId

To me (mainly Oracle & SQL Server experience more than Sybase) there is little wrong with this statement. However, Sybase throws an exception:

You cannot use a derived table in the FROM clause of an UPDATE or DELETE statement.

Now, I don't get what the problem is here. I assume it is because of the aggregation / GROUP BY being used. Of course, I could put the sub query in a temp table and join on it but I really want to know what the 'correct' method should be and what the hell is wrong.

Any ideas or guidance would be much appreciated.

Body:
Does this syntax work in Sybase?

update dstTable T
set (T.field1, T.field2, T.field3) =
       (select S.value1, S.value2, S.value3
        from srcTable S
         where S.key = T.Key);

I believe the correlated subquery can be as complicated as you like (including using CTE. etc).  It just has to project the right number (and type) of values.


答:
Couple of things to note:

The struct definition is syntactically incorrect. There are couple of closing braces missing.

type is a keyword.

The status and message and other fields with lower case first letter fields are unexported. So, the Json parser will not throw error, but you will get zero values as output. Not sure that's what you observed.

someMoreData is an array of structs not map.

Title: Accessing Data in Nested []struct


问:
Java RestAssured API POJO Class Cannot deserialize value of type `POJO.Category` from Array value (token `JsonToken.START_ARRAY`)
I have created couple of POJO classes for serializing/deserializing. When I create a request to receive all categories I am expecting to receive an array of category objects. But I am getting the following error:-

Exception in thread "main"
com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot
deserialize value of type POJO.Categories from Array value (token
JsonToken.START_ARRAY)

See classes below:-

Category Class:-

```<code>package POJO;

public class Category {
    String _id;
    String name;
    Integer __v;
    String color;
    String icon;
    String id;

    public String get_id() {
        return _id;
    }
    public void set_id(String _id) {
        this._id = _id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Integer get__v() {
        return __v;
    }
    public void set_v(Integer __v) {
        this.__v = __v;
    }
    public String getColor() {
        return color;
    }
    public void setColor(String color) {
        this.color = color;
    }
    public String getIcon() {
        return icon;
    }
    public void setIcon(String icon) {
        this.icon = icon;
    }
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }

}
</code>```

Categories Class:-

```<code>package POJO;

import java.util.ArrayList;
import java.util.List;

public class Categories {
    ArrayList<Category> categories;

    public ArrayList<Category> getCategories() {
        return categories;
    }

    public void setCategory(ArrayList<Category> categories) {
        this.categories = categories;
    }
}
</code>```

See my test class below:-

```<code>    import io.restassured.RestAssured;
    import io.restassured.parsing.Parser;
    import io.restassured.path.json.JsonPath;
    import io.restassured.response.Response;

    import static io.restassured.RestAssured.*;
    import static org.hamcrest.Matchers.*;

    import java.util.ArrayList;
    import java.util.List;

    import org.testng.Assert;

    import POJO.Categories;
    import POJO.Category;

public class c_GetCategoryUsingPOJOClass {

    public static void main(String[] args) {

        RestAssured.baseURI = "https://eshop-backend-101.herokuapp.com/api/v1/";
        String getCategoriesResource = "categories";

            // Get all Categories
            Categories categoriesRes = given().log().all()

                .header("Content-Type", "application/json")
                .expect().defaultParser(Parser.JSON)

                .when().get(getCategoriesResource).as(Categories.class);

                // print the category name
                System.out.println("Categories:- ");
                System.out.println(categoriesRes);
    }

}
</code>```

Further information - When using postman to connect to the GET Categories end point this is a response body I receive:-

```<code>[
    {
        "_id": "5f15d467f3a046427a1c26e1",
        "name": "Mobile",
        "__v": 0,
        "color": "#6e4035",
        "icon": "mobile",
        "id": "5f15d467f3a046427a1c26e1"
    },
    {
        "_id": "5f15d5b2cb4a6642bddc0fe7",
        "name": "House",
        "__v": 0,
        "color": "#E2E1F0",
        "icon": "home",
        "id": "5f15d5b2cb4a6642bddc0fe7"
    },
    {
        "_id": "5f9d7e938680aa1d979d7e19",
        "name": "Games",
        "__v": 0,
        "color": "#ffb8b8",
        "icon": "sun",
        "id": "5f9d7e938680aa1d979d7e19"
    },
    {
        "_id": "5f15d54cf3a046427a1c26e3",
        "name": "Computers",
        "__v": 0,
        "color": "#E1F0E7",
        "icon": "desktop",
        "id": "5f15d54cf3a046427a1c26e3"
    },
    {
        "_id": "5f15d545f3a046427a1c26e2",
        "name": "Beauty",
        "__v": 0,
        "color": "#F0E8DE",
        "icon": "palette",
        "id": "5f15d545f3a046427a1c26e2"
    },
    {
        "_id": "608fe08365074604f45ce544",
        "name": "Cameras",
        "icon": "camera",
        "color": "#ede4da",
        "__v": 0,
        "id": "608fe08365074604f45ce544"
    }
]
</code>```

I have now updated by test class as follows:-

```<code>import POJO.Category;
import io.restassured.RestAssured;
import io.restassured.common.mapper.TypeRef;
import io.restassured.parsing.Parser;

public class c_GetCategoryUsingPOJOClass {

    public static void main(String[] args) {

        RestAssured.baseURI = "https://eshop-backend-101.herokuapp.com/api/v1/";
        String getCategoriesResource = "categories";

            // Get all Categories
            List<Category> categoriesRes = given().log().all()

                .header("Content-Type", "application/json")
                .expect().defaultParser(Parser.JSON)

                .when().get(getCategoriesResource).as(new TypeRef<List<Category>>() {});

                // print the category name
                System.out.println("Categories:- ");
                System.out.println(categoriesRes);
                System.out.println(categoriesRes.get(0).toString());

    }

}
</code>```

答:
The problem here is with your POJO, it will match to json structure:

```<code>{
  "categories": [
    {...},
    {...}
  ]
}
</code>```

but your json structure is

```<code>[
    {...},
    {...}
]
</code>```

--> you just remove Categories class and change the way you deserialize json, mapping to List<Category>

```<code>List<Category> as = given()...as(new TypeRef<List<Category>>() {});
System.out.println(as);
</code>```

One more thing, override toString method before print the object.

Body:
I have created couple of POJO classes for serializing/deserializing. When I create a request to receive all categories I am expecting to receive an array of category objects. But I am getting the following error:-

Exception in thread "main"
com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot
deserialize value of type POJO.Categories from Array value (token
JsonToken.START_ARRAY)

See classes below:-

Category Class:-

package POJO;

public class Category {
    String _id;
    String name;
    Integer __v;
    String color;
    String icon;
    String id;

    public String get_id() {
        return _id;
    }
    public void set_id(String _id) {
        this._id = _id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Integer get__v() {
        return __v;
    }
    public void set_v(Integer __v) {
        this.__v = __v;
    }
    public String getColor() {
        return color;
    }
    public void setColor(String color) {
        this.color = color;
    }
    public String getIcon() {
        return icon;
    }
    public void setIcon(String icon) {
        this.icon = icon;
    }
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }

}

Categories Class:-

package POJO;

import java.util.ArrayList;
import java.util.List;

public class Categories {
    ArrayList<Category> categories;

    public ArrayList<Category> getCategories() {
        return categories;
    }

    public void setCategory(ArrayList<Category> categories) {
        this.categories = categories;
    }
}

See my test class below:-

    import io.restassured.RestAssured;
    import io.restassured.parsing.Parser;
    import io.restassured.path.json.JsonPath;
    import io.restassured.response.Response;

    import static io.restassured.RestAssured.*;
    import static org.hamcrest.Matchers.*;

    import java.util.ArrayList;
    import java.util.List;

    import org.testng.Assert;

    import POJO.Categories;
    import POJO.Category;

public class c_GetCategoryUsingPOJOClass {

    public static void main(String[] args) {

        RestAssured.baseURI = "https://eshop-backend-101.herokuapp.com/api/v1/";
        String getCategoriesResource = "categories";

            // Get all Categories
            Categories categoriesRes = given().log().all()

                .header("Content-Type", "application/json")
                .expect().defaultParser(Parser.JSON)

                .when().get(getCategoriesResource).as(Categories.class);

                // print the category name
                System.out.println("Categories:- ");
                System.out.println(categoriesRes);
    }

}

Further information - When using postman to connect to the GET Categories end point this is a response body I receive:-

[
    {
        "_id": "5f15d467f3a046427a1c26e1",
        "name": "Mobile",
        "__v": 0,
        "color": "#6e4035",
        "icon": "mobile",
        "id": "5f15d467f3a046427a1c26e1"
    },
    {
        "_id": "5f15d5b2cb4a6642bddc0fe7",
        "name": "House",
        "__v": 0,
        "color": "#E2E1F0",
        "icon": "home",
        "id": "5f15d5b2cb4a6642bddc0fe7"
    },
    {
        "_id": "5f9d7e938680aa1d979d7e19",
        "name": "Games",
        "__v": 0,
        "color": "#ffb8b8",
        "icon": "sun",
        "id": "5f9d7e938680aa1d979d7e19"
    },
    {
        "_id": "5f15d54cf3a046427a1c26e3",
        "name": "Computers",
        "__v": 0,
        "color": "#E1F0E7",
        "icon": "desktop",
        "id": "5f15d54cf3a046427a1c26e3"
    },
    {
        "_id": "5f15d545f3a046427a1c26e2",
        "name": "Beauty",
        "__v": 0,
        "color": "#F0E8DE",
        "icon": "palette",
        "id": "5f15d545f3a046427a1c26e2"
    },
    {
        "_id": "608fe08365074604f45ce544",
        "name": "Cameras",
        "icon": "camera",
        "color": "#ede4da",
        "__v": 0,
        "id": "608fe08365074604f45ce544"
    }
]

I have now updated by test class as follows:-

import POJO.Category;
import io.restassured.RestAssured;
import io.restassured.common.mapper.TypeRef;
import io.restassured.parsing.Parser;

public class c_GetCategoryUsingPOJOClass {

    public static void main(String[] args) {

        RestAssured.baseURI = "https://eshop-backend-101.herokuapp.com/api/v1/";
        String getCategoriesResource = "categories";

            // Get all Categories
            List<Category> categoriesRes = given().log().all()

                .header("Content-Type", "application/json")
                .expect().defaultParser(Parser.JSON)

                .when().get(getCategoriesResource).as(new TypeRef<List<Category>>() {});

                // print the category name
                System.out.println("Categories:- ");
                System.out.println(categoriesRes);
                System.out.println(categoriesRes.get(0).toString());

    }

}

Body:
The problem here is with your POJO, it will match to json structure:

{
  "categories": [
    {...},
    {...}
  ]
}

but your json structure is

[
    {...},
    {...}
]

--> you just remove Categories class and change the way you deserialize json, mapping to List<Category>

List<Category> as = given()...as(new TypeRef<List<Category>>() {});
System.out.println(as);

One more thing, override toString method before print the object.


问:
How Do I Clear The Credentials In AWS Configure?
I have deleted the AWS credentials in sudo nano ~/.aws/config. But, the credentials are still in aws configure. Is there a way to reset aws configure with clear state?

答: Not sure if this clears the credentials but I was able to simply change the credentials by running aws configure again and entering in new credentials. I was also able to make multiple profiles by running aws configure --newusername and I could run a future command with that user by appending --profile newusername. Good tutorial here: https://www.crybit.com/configure-iam-user-on-your-linux-machine/</p>


问:
Create report from wizard in odoo 15
I want to create a report pdf from wizard, but it's not working, here's my code:

/var/www/html/odoo_15/addons/school/wizard/search_and_print_calendar_wizard_view.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<odoo>
    <record id="view_school_search_and_print_calendar_wizard" model="ir.ui.view">
        <field name="name">Search and Print Calendar</field>
        <field name="model">school.search.and.print.calendar.wizard</field>
        <field name="arch" type="xml">
            <form string="Search and Print Calendar">
                <sheet>
                    <group>
                        <field name="student_id"/>
                        <field name="date_from"/>
                        <field name="date_to"/>
                    </group>
                </sheet>
                <footer>
<!--                    <button name="school_view_calendars" string="View Calendars" type="object" class="btn-primary"/>-->
                    <button name="school_print_calendars" string="Print Calendars" type="object" class="btn-primary"/>
                    <button string="Cancel" class="btn-secondary" special="cancel" data-hotkey="z" />
                </footer>
            </form>
        </field>
    </record>

    <record id="action_school_search_and_print_calendar" model="ir.actions.act_window">
        <field name="name">School Search and Print Calendar</field>
        <field name="res_model">school.search.and.print.calendar.wizard</field>
        <field name="view_mode">form</field>
        <field name="target">new</field>
    </record>
</odoo>
</code>```

/var/www/html/odoo_15/addons/school/wizard/search_and_print_calendar_wizard.py

```<code>from odoo import api, models, fields, _

class SearchAndPrintCalendarWizard(models.TransientModel):
    _name = "school.search.and.print.calendar.wizard"
    _description = "Search and Print Calendar Wizard"

    student_id = fields.Many2one('school.students', string='Student', required=True)
    date_from = fields.Datetime(string='Date From')
    date_to = fields.Datetime(string='Date To')

    # view list calendars based on student id
    # def school_view_calendars(self):
    #     print('aaa')

    def school_print_calendars(self):
        data = {
            'form': self.read()[0]
        }
        report_action = self.env.ref('school.action_report_calendar').report_action(self, data=data)

        return report_action
</code>```

/var/www/html/odoo_15/addons/school/report/calendar_report.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<odoo>
    <data>
        <!-- pdf version -->
        <record id="action_report_calendar" model="ir.actions.report">
            <!-- this field will show as name of the button,
            also will be the name of exported file, unless we use print_report_name as below -->
            <field name="name">Calendar Report</field>
            <field name="model">school.search.and.print.calendar.wizard</field>
            <field name="report_type">qweb-pdf</field>
            <!-- In single report, this print_report_name will be use as dynamic name of the file.
            But in multiple reports, this will not work, it will use <field name="name"> as file name.
            So we should use print_report_name for single report, and <field name="name"> to multiple reports.
            -->
            <field name="print_report_name">'Calendar - [%s]' % (object.sequence).replace('/', '')</field>
            <!-- the view file is declare in this variable -->
            <field name="report_name">school.report_calendar</field>
            <!-- not sure what this for -->
            <field name="report_file">school.report_calendar</field>
            <!-- not sure what this for -->
            <field name="binding_model_id" ref="model_school_search_and_print_calendar_wizard"/>
            <field name="binding_type">report</field>
        </record>
    </data>
</odoo>
</code>```

/var/www/html/odoo_15/addons/school/report/calendar_report_template.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<odoo>
    <!-- this template id is called in report/calendar_report.xml -->
    <template id="report_calendar">
        <t t-call="web.html_container">
            <!-- docs is the record data -->
            <!-- this command equal to foreach(docs as o) -->
            <t t-call="web.external_layout">
                <!-- html code -->
                <div class="page">
                    <div class="oe_structure"/>
                    <div>
                        <h2>This is a test</h2>
                    </div>
                </div>
            </t>
        </t>
    </template>
</odoo>
</code>```

I got this issue:

```<code>AttributeError: 'NoneType' object has no attribute 'compile'
AttributeError: 'NoneType' object has no attribute 'CompileError'
</code>```

Full issue:

```<code>Traceback (most recent call last):
  File "/var/www/html/odoo-server/odoo/odoo/api.py", line 886, in get
    return field_cache[record._ids[0]]
KeyError: <NewId 0x7f3bbbc7b7f0>

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/var/www/html/odoo-server/odoo/odoo/fields.py", line 1057, in __get__
    value = env.cache.get(record, self)
  File "/var/www/html/odoo-server/odoo/odoo/api.py", line 889, in get
    raise CacheMiss(record, field)
odoo.exceptions.CacheMiss: 'base.document.layout(<NewId 0x7f3bbbc7b7f0>,).preview'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/var/www/html/odoo-server/odoo/addons/web/models/base_document_layout.py", line 290, in _compile_scss
    return libsass.compile(
AttributeError: 'NoneType' object has no attribute 'compile'

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/var/www/html/odoo-server/odoo/odoo/addons/base/models/ir_http.py", line 237, in _dispatch
    result = request.dispatch()
  File "/var/www/html/odoo-server/odoo/odoo/http.py", line 688, in dispatch
    result = self._call_function(**self.params)
  File "/var/www/html/odoo-server/odoo/odoo/http.py", line 360, in _call_function
    return checked_call(self.db, *args, **kwargs)
  File "/var/www/html/odoo-server/odoo/odoo/service/model.py", line 94, in wrapper
    return f(dbname, *args, **kwargs)
  File "/var/www/html/odoo-server/odoo/odoo/http.py", line 349, in checked_call
    result = self.endpoint(*a, **kw)
  File "/var/www/html/odoo-server/odoo/odoo/http.py", line 917, in __call__
    return self.method(*args, **kw)
  File "/var/www/html/odoo-server/odoo/odoo/http.py", line 536, in response_wrap
    response = f(*args, **kw)
  File "/var/www/html/odoo-server/odoo/addons/web/controllers/main.py", line 1335, in call_kw
    return self._call_kw(model, method, args, kwargs)
  File "/var/www/html/odoo-server/odoo/addons/web/controllers/main.py", line 1327, in _call_kw
    return call_kw(request.env[model], method, args, kwargs)
  File "/var/www/html/odoo-server/odoo/odoo/api.py", line 464, in call_kw
    result = _call_kw_multi(method, model, args, kwargs)
  File "/var/www/html/odoo-server/odoo/odoo/api.py", line 451, in _call_kw_multi
    result = method(recs, *args, **kwargs)
  File "/var/www/html/odoo-server/odoo/odoo/models.py", line 6475, in onchange
    snapshot1 = Snapshot(record, nametree)
  File "/var/www/html/odoo-server/odoo/odoo/models.py", line 6257, in __init__
    self.fetch(name)
  File "/var/www/html/odoo-server/odoo/odoo/models.py", line 6267, in fetch
    self[name] = record[name]
  File "/var/www/html/odoo-server/odoo/odoo/models.py", line 5874, in __getitem__
    return self._fields[key].__get__(self, type(self))
  File "/var/www/html/odoo-server/odoo/odoo/fields.py", line 1106, in __get__
    self.compute_value(recs)
  File "/var/www/html/odoo-server/odoo/odoo/fields.py", line 1265, in compute_value
    records._compute_field_value(self)
  File "/var/www/html/odoo-server/odoo/odoo/models.py", line 4256, in _compute_field_value
    getattr(self, field.compute)()
  File "/var/www/html/odoo-server/odoo/addons/web/models/base_document_layout.py", line 121, in _compute_preview
    preview_css = markupsafe.Markup(self._get_css_for_preview(styles, wizard_with_logo.id))
  File "/var/www/html/odoo-server/odoo/addons/web/models/base_document_layout.py", line 270, in _get_css_for_preview
    css_code = self._compile_scss(scss)
  File "/var/www/html/odoo-server/odoo/addons/web/models/base_document_layout.py", line 298, in _compile_scss
    except libsass.CompileError as e:
Exception

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/var/www/html/odoo-server/odoo/odoo/http.py", line 644, in _handle_exception
    return super(JsonRequest, self)._handle_exception(exception)
  File "/var/www/html/odoo-server/odoo/odoo/http.py", line 302, in _handle_exception
    raise exception.with_traceback(None) from new_cause
AttributeError: 'NoneType' object has no attribute 'CompileError'
</code>```

I'm following Odoo Mates Odoo-14 Tutorial.

Here's my github code:
https://github.com/saxsax1995/odoo-15-school

Please help, thanks.

答:
I've ask my leader to help me on this, and after debug, this issue is because missing library "sass", "libsass"

Here's how to resolve the problem:

```<code>sudo apt-get install python3.8-dev
pip install --upgrade setuptools
pip install sass
pip install libsass
</code>```

Title: Create report from wizard in odoo 15

Body:
I want to create a report pdf from wizard, but it's not working, here's my code:

/var/www/html/odoo_15/addons/school/wizard/search_and_print_calendar_wizard_view.xml

<?xml version="1.0" encoding="utf-8"?>
<odoo>
    <record id="view_school_search_and_print_calendar_wizard" model="ir.ui.view">
        <field name="name">Search and Print Calendar</field>
        <field name="model">school.search.and.print.calendar.wizard</field>
        <field name="arch" type="xml">
            <form string="Search and Print Calendar">
                <sheet>
                    <group>
                        <field name="student_id"/>
                        <field name="date_from"/>
                        <field name="date_to"/>
                    </group>
                </sheet>

                    <button name="school_print_calendars" string="Print Calendars" type="object" class="btn-primary"/>
                    <button string="Cancel" class="btn-secondary" special="cancel" data-hotkey="z" />

            </form>
        </field>
    </record>

    <record id="action_school_search_and_print_calendar" model="ir.actions.act_window">
        <field name="name">School Search and Print Calendar</field>
        <field name="res_model">school.search.and.print.calendar.wizard</field>
        <field name="view_mode">form</field>
        <field name="target">new</field>
    </record>
</odoo>

/var/www/html/odoo_15/addons/school/wizard/search_and_print_calendar_wizard.py

from odoo import api, models, fields, _

class SearchAndPrintCalendarWizard(models.TransientModel):
    _name = "school.search.and.print.calendar.wizard"
    _description = "Search and Print Calendar Wizard"

    student_id = fields.Many2one('school.students', string='Student', required=True)
    date_from = fields.Datetime(string='Date From')
    date_to = fields.Datetime(string='Date To')

    # view list calendars based on student id
    # def school_view_calendars(self):
    #     print('aaa')

    def school_print_calendars(self):
        data = {
            'form': self.read()[0]
        }
        report_action = self.env.ref('school.action_report_calendar').report_action(self, data=data)

        return report_action

/var/www/html/odoo_15/addons/school/report/calendar_report.xml

<?xml version="1.0" encoding="utf-8"?>
<odoo>
    <data>

        <record id="action_report_calendar" model="ir.actions.report">

            <field name="name">Calendar Report</field>
            <field name="model">school.search.and.print.calendar.wizard</field>
            <field name="report_type">qweb-pdf</field>

            <field name="print_report_name">'Calendar - [%s]' % (object.sequence).replace('/', '')</field>

            <field name="report_name">school.report_calendar</field>

            <field name="report_file">school.report_calendar</field>

            <field name="binding_model_id" ref="model_school_search_and_print_calendar_wizard"/>
            <field name="binding_type">report</field>
        </record>
    </data>
</odoo>

/var/www/html/odoo_15/addons/school/report/calendar_report_template.xml

<?xml version="1.0" encoding="utf-8"?>
<odoo>

    <template id="report_calendar">
        <t t-call="web.html_container">

            <t t-call="web.external_layout">

This is a test

            </t>
        </t>
    </template>
</odoo>

I got this issue:

AttributeError: 'NoneType' object has no attribute 'compile'
AttributeError: 'NoneType' object has no attribute 'CompileError'

Full issue:

Traceback (most recent call last):
  File "/var/www/html/odoo-server/odoo/odoo/api.py", line 886, in get
    return field_cache[record._ids[0]]
KeyError: <NewId 0x7f3bbbc7b7f0>

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/var/www/html/odoo-server/odoo/odoo/fields.py", line 1057, in __get__
    value = env.cache.get(record, self)
  File "/var/www/html/odoo-server/odoo/odoo/api.py", line 889, in get
    raise CacheMiss(record, field)
odoo.exceptions.CacheMiss: 'base.document.layout(<NewId 0x7f3bbbc7b7f0>,).preview'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/var/www/html/odoo-server/odoo/addons/web/models/base_document_layout.py", line 290, in _compile_scss
    return libsass.compile(
AttributeError: 'NoneType' object has no attribute 'compile'

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/var/www/html/odoo-server/odoo/odoo/addons/base/models/ir_http.py", line 237, in _dispatch
    result = request.dispatch()
  File "/var/www/html/odoo-server/odoo/odoo/http.py", line 688, in dispatch
    result = self._call_function(**self.params)
  File "/var/www/html/odoo-server/odoo/odoo/http.py", line 360, in _call_function
    return checked_call(self.db, *args, **kwargs)
  File "/var/www/html/odoo-server/odoo/odoo/service/model.py", line 94, in wrapper
    return f(dbname, *args, **kwargs)
  File "/var/www/html/odoo-server/odoo/odoo/http.py", line 349, in checked_call
    result = self.endpoint(*a, **kw)
  File "/var/www/html/odoo-server/odoo/odoo/http.py", line 917, in __call__
    return self.method(*args, **kw)
  File "/var/www/html/odoo-server/odoo/odoo/http.py", line 536, in response_wrap
    response = f(*args, **kw)
  File "/var/www/html/odoo-server/odoo/addons/web/controllers/main.py", line 1335, in call_kw
    return self._call_kw(model, method, args, kwargs)
  File "/var/www/html/odoo-server/odoo/addons/web/controllers/main.py", line 1327, in _call_kw
    return call_kw(request.env[model], method, args, kwargs)
  File "/var/www/html/odoo-server/odoo/odoo/api.py", line 464, in call_kw
    result = _call_kw_multi(method, model, args, kwargs)
  File "/var/www/html/odoo-server/odoo/odoo/api.py", line 451, in _call_kw_multi
    result = method(recs, *args, **kwargs)
  File "/var/www/html/odoo-server/odoo/odoo/models.py", line 6475, in onchange
    snapshot1 = Snapshot(record, nametree)
  File "/var/www/html/odoo-server/odoo/odoo/models.py", line 6257, in __init__
    self.fetch(name)
  File "/var/www/html/odoo-server/odoo/odoo/models.py", line 6267, in fetch
    self[name] = record[name]
  File "/var/www/html/odoo-server/odoo/odoo/models.py", line 5874, in __getitem__
    return self._fields[key].__get__(self, type(self))
  File "/var/www/html/odoo-server/odoo/odoo/fields.py", line 1106, in __get__
    self.compute_value(recs)
  File "/var/www/html/odoo-server/odoo/odoo/fields.py", line 1265, in compute_value
    records._compute_field_value(self)
  File "/var/www/html/odoo-server/odoo/odoo/models.py", line 4256, in _compute_field_value
    getattr(self, field.compute)()
  File "/var/www/html/odoo-server/odoo/addons/web/models/base_document_layout.py", line 121, in _compute_preview
    preview_css = markupsafe.Markup(self._get_css_for_preview(styles, wizard_with_logo.id))
  File "/var/www/html/odoo-server/odoo/addons/web/models/base_document_layout.py", line 270, in _get_css_for_preview
    css_code = self._compile_scss(scss)
  File "/var/www/html/odoo-server/odoo/addons/web/models/base_document_layout.py", line 298, in _compile_scss
    except libsass.CompileError as e:
Exception

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/var/www/html/odoo-server/odoo/odoo/http.py", line 644, in _handle_exception
    return super(JsonRequest, self)._handle_exception(exception)
  File "/var/www/html/odoo-server/odoo/odoo/http.py", line 302, in _handle_exception
    raise exception.with_traceback(None) from new_cause
AttributeError: 'NoneType' object has no attribute 'CompileError'

I'm following Odoo Mates Odoo-14 Tutorial.

Here's my github code:
https://github.com/saxsax1995/odoo-15-school

Please help, thanks.

Body:
I've ask my leader to help me on this, and after debug, this issue is because missing library "sass", "libsass"

Here's how to resolve the problem:

sudo apt-get install python3.8-dev
pip install --upgrade setuptools
pip install sass
pip install libsass


问:
What IDE should I use for Linux module development?
I have Ubuntu 11.04 and am looking to start developing Linux modules. I use Visual Studio for C development in Windows, but I guess that's not an option for Linux. What would be a good IDE to work Linux modules ?</p>

答: Eclispe is always a popular choice and a very nice IDE</p>


问:
How to disable and enable scrolling in LazyColumn/LazyRow in Jetpack Compose?
I want to dynamically enable and disable scrolling programmatically in a LazyColumn.

There don't seem to be any relevant functions on LazyListState or relevant parameters on LazyColumn itself. How can I achieve this in Compose?

答:
NestedScrollConnection allows you to consume any scroll applied to a lazy column or row. When true, all of the available scroll is consumed. If false, none is consumed and scrolling happens normally. With this information, you can see how this can be extended for slow/fast scrolls by returning the offset multiple by some factor.

```<code>fun Modifier.scrollEnabled(
    enabled: Boolean,
) = nestedScroll(
    connection = object : NestedScrollConnection {
        override fun onPreScroll(
            available: Offset,
            source: NestedScrollSource
        ): Offset = if(enabled) Offset.Zero else available
    }
)
</code>```

it can be used like this:

```<code>LazyColumn(
    modifier = Modifier.scrollEnabled(
        enabled = enabled, //provide a mutable state boolean here
    )
){
    ...
</code>```

However, this does block programmatic scrolls.

Body:
NestedScrollConnection allows you to consume any scroll applied to a lazy column or row. When true, all of the available scroll is consumed. If false, none is consumed and scrolling happens normally. With this information, you can see how this can be extended for slow/fast scrolls by returning the offset multiple by some factor.

fun Modifier.scrollEnabled(
    enabled: Boolean,
) = nestedScroll(
    connection = object : NestedScrollConnection {
        override fun onPreScroll(
            available: Offset,
            source: NestedScrollSource
        ): Offset = if(enabled) Offset.Zero else available
    }
)

it can be used like this:

LazyColumn(
    modifier = Modifier.scrollEnabled(
        enabled = enabled, //provide a mutable state boolean here
    )
){
    ...

However, this does block programmatic scrolls.


问:
Can I create Azure File Share using Ansible?
Is it possible to create an azure storage file share using Ansible ?

There is an Ansible module to create Azure Storage Account, so I am good there.

I dont see anything for File Share.

There is something called azure_rm_resource but I have not been able to get it to work with it.

Any input will be appreciated.

答:
Posting my answer as it will help someone in the community:

The latest commit contains this enhancement !

https://github.com/ansible-collections/azure/pull/603/commits/83a6600417faccf56752a8ae5b1e52a0bac37dfb

Copying the example from the link above :

```<code>- name: Create storage share
  azure_rm_storageshare:
    name: testShare
    resource_group: myResourceGroup
    account_name: testStorageAccount
    state: present
    access_tier: Cool
    quota: 2048
    metadata:
      key1: value1
      key2: value2
</code>```

Body:
Posting my answer as it will help someone in the community:

The latest commit contains this enhancement !

https://github.com/ansible-collections/azure/pull/603/commits/83a6600417faccf56752a8ae5b1e52a0bac37dfb

Copying the example from the link above :

- name: Create storage share
  azure_rm_storageshare:
    name: testShare
    resource_group: myResourceGroup
    account_name: testStorageAccount
    state: present
    access_tier: Cool
    quota: 2048
    metadata:
      key1: value1
      key2: value2


问:
npm Install : unable to resolve dependency tree
Eveytime i try npm install i go this errors it is a boilerplate project is downloaded from : https://aspnetboilerplate.com/Templates.
I cant generate node_modules folder or start the server it s only on these boilerpart projects.any suggestions please im really tired.
here is a screenshot of the issue issue Screenshot

also here is some versions of my environment:

```<code>npm: '8.3.1',node: '16.14.0',Angular CLI: 13.2.3

>   Package                      Version
> ------------------------------------------------------ @angular-devkit/architect    0.1302.3 (cli-only) @angular-devkit/core
> 13.2.3 (cli-only) @angular-devkit/schematics   13.2.3 (cli-only) @schematics/angular          13.2.3 (cli-only)
</code>```

答:
Looks like that template is expecting you to use yarn (not npm). You need to get yarn and then, in the terminal (instead of npm install), you do yarn to install the packages.

By the way, the tip off that it's expecting you to use yarn is the presence of the yarn.lock file.

Body:
Eveytime i try npm install i go this errors it is a boilerplate project is downloaded from : https://aspnetboilerplate.com/Templates.
I cant generate node_modules folder or start the server it s only on these boilerpart projects.any suggestions please im really tired.
here is a screenshot of the issue issue Screenshot

also here is some versions of my environment:

npm: '8.3.1',node: '16.14.0',Angular CLI: 13.2.3

>   Package                      Version
> ------------------------------------------------------ @angular-devkit/architect    0.1302.3 (cli-only) @angular-devkit/core
> 13.2.3 (cli-only) @angular-devkit/schematics   13.2.3 (cli-only) @schematics/angular          13.2.3 (cli-only)


问:
why the error that row names contain missing values occur
My code is like below and I got an error in data.frame(c(b)) : row names contain missing values.

```<code>col_name<-colnames(portfolio_25)[2:26]
#b<-seq(from = 1, to=25, by=1) no error if I use this line of code instead of the below one
b<-seq(from =0.5, to=3, by =0.1)

names(b)<-col_name

for(i in col_name){
  lm2 = lm(paste0("I(`",i,"`- RF) ~ I(`Mkt-RF` - RF)"), data = Join_table)
  b[i] =  lm2$coefficients[2]
}

plot <- data.frame(c(b))
</code>```

The commented and uncommented codes are basically following the same logic, so I didn't get why this error occur.

Any help pls would be great!

答:
The error is because lengths of 2 sequence are different.

```<code>length(seq(from =0.5, to=3, by =0.1))
#[1] 26

length(seq(from = 1, to=25, by=1))
#[1] 25
</code>```

So for the first case you have 26 values whereas for the second one you have 25. The length of col_name is 25 since.

```<code>length(2:26)
#[1] 25
</code>```

So to avoid the error you need to reduce the length of first sequence by 1 to make it of same length as col_name.

Body:
My code is like below and I got an error in data.frame(c(b)) : row names contain missing values.

col_name<-colnames(portfolio_25)[2:26]
#b<-seq(from = 1, to=25, by=1) no error if I use this line of code instead of the below one
b<-seq(from =0.5, to=3, by =0.1)

names(b)<-col_name

for(i in col_name){
  lm2 = lm(paste0("I(`",i,"`- RF) ~ I(`Mkt-RF` - RF)"), data = Join_table)
  b[i] =  lm2$coefficients[2]
}

plot <- data.frame(c(b))

The commented and uncommented codes are basically following the same logic, so I didn't get why this error occur.

Any help pls would be great!

Body:
The error is because lengths of 2 sequence are different.

length(seq(from =0.5, to=3, by =0.1))
#[1] 26

length(seq(from = 1, to=25, by=1))
#[1] 25

So for the first case you have 26 values whereas for the second one you have 25. The length of col_name is 25 since.

length(2:26)
#[1] 25

So to avoid the error you need to reduce the length of first sequence by 1 to make it of same length as col_name.