问:
Find the maximum value for each group in dataframe and retrieve the entire row
I've the following dataframe (With many records) and would like to retrieve the entire row for each day with maximum differences.

```<code>require(dplyr)
# This gets the maximum value for each date
maxInfo = results %>% group_by(t) %>% summarise(Value = max(differences))
</code>```

I'm able to get the max value for each day but how to get the entire row?

答:
A possible solution, using slice_max:

```<code>library(dplyr)

results %>% group_by(t) %>% slice_max(differences)
</code>```

Body:
I've the following dataframe (With many records) and would like to retrieve the entire row for each day with maximum differences.

require(dplyr)
# This gets the maximum value for each date
maxInfo = results %>% group_by(t) %>% summarise(Value = max(differences))

I'm able to get the max value for each day but how to get the entire row?

Body:
A possible solution, using slice_max:

library(dplyr)

results %>% group_by(t) %>% slice_max(differences)


来源: stackexchange

问:
Constrained function template vs un-constrained function template with different parameter type
In the following two template functions, one tries to be more constrained:

```<code>template<typename T>
concept SmallVar = (sizeof(T) <= sizeof(int));

void print(SmallVar auto t) { // 1
    std::cout << t << std::endl;
}

void print(const auto& t) {   // 2
    std::cout << t << std::endl;
}
</code>```

When called with an int, Clang and GCC differ:

```<code>int main() {
    print(6);  // clang accepts and prefers 1, gcc sees here ambiguity
}
</code>```

Which one is right?

Code: https://godbolt.org/z/x71zjzoTa

答:
Based on a feedback from Patrick Palka from GCC, it seems to be that Clang is wrong, and GCC is right in rejecting the code on ambiguity, as the function parameters that positionally correspond between the two templates are not of the same type, thus neither template should be more specialized than the other.

[temp.func.order]#6.2.2:

[...] if the function parameters that positionally correspond between the two templates are not of the same type, neither template is more specialized than the other.

An issue was opened for Clang: https://github.com/llvm/llvm-project/issues/53640

Of course if the function parameters are of the same type, both compilers agree that there is a more constrained template and prefer it.

It is worth noting (as the OP probably knows) that the ambiguity can be resolved by constraining both functions:

```<code>template<SmallVar T>
void print(T t) {
    std::cout << t << std::endl;
}

template<typename T> requires (!SmallVar<T>)
void print(const T& t) {
    std::cout << t << std::endl;
}
</code>```

Code: https://godbolt.org/z/6GGWeTsW9

ContentLicense: CC BY-SA 4.0

Body:
In the following two template functions, one tries to be more constrained:

template<typename T>
concept SmallVar = (sizeof(T) <= sizeof(int));

void print(SmallVar auto t) { // 1
    std::cout << t << std::endl;
}

void print(const auto& t) {   // 2
    std::cout << t << std::endl;
}

When called with an int, Clang and GCC differ:

int main() {
    print(6);  // clang accepts and prefers 1, gcc sees here ambiguity
}

Which one is right?

Code: https://godbolt.org/z/x71zjzoTa

Body:
Based on a feedback from Patrick Palka from GCC, it seems to be that Clang is wrong, and GCC is right in rejecting the code on ambiguity, as the function parameters that positionally correspond between the two templates are not of the same type, thus neither template should be more specialized than the other.

[temp.func.order]#6.2.2:

[...] if the function parameters that positionally correspond between the two templates are not of the same type, neither template is more specialized than the other.

An issue was opened for Clang: https://github.com/llvm/llvm-project/issues/53640

Of course if the function parameters are of the same type, both compilers agree that there is a more constrained template and prefer it.

It is worth noting (as the OP probably knows) that the ambiguity can be resolved by constraining both functions:

template<SmallVar T>
void print(T t) {
    std::cout << t << std::endl;
}

template<typename T> requires (!SmallVar<T>)
void print(const T& t) {
    std::cout << t << std::endl;
}

Code: https://godbolt.org/z/6GGWeTsW9


问:
Debug a VBA Script that highlights similarities in text strings:
Here is a sample of the code that I currently have. The image shows the results I am currently getting and what I need to have. I need to compare one string in a cell to a whole row of cells, but this script only allows me to select one column at a a time. I am not a coder and need help finding the issue. See my work below.

SEE CURRENT RESULTS <<<-- CLICK ME

```<code>Sub highlight()
    Dim xRg1 As Range
    Dim xRg2 As Range
    Dim xTxt As String
    Dim xCell1 As Range
    Dim xCell2 As Range
    Dim I As Long
    Dim J As Integer
    Dim xLen As Integer
    Dim xDiffs As Boolean
    On Error Resume Next
    If ActiveWindow.RangeSelection.Count > 1 Then
      xTxt = ActiveWindow.RangeSelection.AddressLocal
    Else
      xTxt = ActiveSheet.UsedRange.AddressLocal
    End If
lOne:
    Set xRg1 = Application.InputBox("Range A:", "Kutools for Excel", xTxt, , , , , 8)
    If xRg1 Is Nothing Then Exit Sub
    If xRg1.Columns.Count > 1 Or xRg1.Areas.Count > 1 Then
        MsgBox "Multiple ranges or columns have been selected ", vbInformation, "Kutools for Excel"
        GoTo lOne
    End If
lTwo:
    Set xRg2 = Application.InputBox("Range B:", "Kutools for Excel", "", , , , , 8)
    If xRg2 Is Nothing Then Exit Sub
    If xRg2.Columns.Count > 1 Or xRg2.Areas.Count > 1 Then
        MsgBox "Multiple ranges or columns have been selected ", vbInformation, "Kutools for Excel"
        GoTo lTwo
    End If
    If xRg1.CountLarge <> xRg2.CountLarge Then
       MsgBox "Two selected ranges must have the same numbers of cells ", vbInformation, "Kutools for Excel"
       GoTo lTwo
    End If
    xDiffs = (MsgBox("Click Yes to highlight similarities, click No to highlight differences ", vbYesNo + vbQuestion, "Kutools for Excel") = vbNo)
    Application.ScreenUpdating = False
    xRg2.Font.ColorIndex = xlAutomatic
    For I = 1 To xRg1.Count
        Set xCell1 = xRg1.Cells(I)
        Set xCell2 = xRg2.Cells(I)
        If xCell1.Value2 = xCell2.Value2 Then
            If Not xDiffs Then xCell2.Font.Color = vbRed
        Else
            xLen = Len(xCell1.Value2)
            For J = 1 To xLen
                If Not xCell1.Characters(J, 1).Text = xCell2.Characters(J, 1).Text Then Exit For
            Next J
            If Not xDiffs Then
                If J <= Len(xCell2.Value2) And J > 1 Then
                    xCell2.Characters(1, J - 1).Font.Color = vbRed
                End If
            Else
                If J <= Len(xCell2.Value2) Then
                    xCell2.Characters(J, Len(xCell2.Value2) - J + 1).Font.Color = vbRed
                End If
            End If
        End If
    Next
    Application.ScreenUpdating = True
End Sub
</code>```

答:
Try this - assuming your search terms are in Col A starting in A1

Adjust as necessary.

Sub HiliteSubstrings()

    Dim c As Range, cCheck As Range, txt, v
    Dim ws As Worksheet, pos As Long, st As Long

    Set ws = ActiveSheet 'or whatever

    'loop the strings to search for
    For Each c In ws.Range("A1:A" & ws.Cells(Rows.Count, "A").End(xlUp).Row).Cells
        txt = Trim(c.Value) 'find this
        If Len(txt) > 0 Then
            'loop all values to the right of the search string cell
            For Each cCheck In ws.Range(c.Offset(0, 1), ws.Cells(c.Row, Columns.Count).End(xlToLeft)).Cells
                v = cCheck.Value                           'value to search in
                st = 1                                     'reset search start position
                Do
                    pos = InStr(st, v, txt, vbTextCompare) 'case-insensitive
                    If pos > 0 Then                        'got a match?
                        cCheck.Characters(pos, Len(txt)).Font.Color = vbRed
                        st = pos + 1                       'increment start position
                    End If
                Loop While pos > 0                         'loop while have a hit
            Next cCheck
        End If
    Next c
End Sub
```

Body:
Here is a sample of the code that I currently have. The image shows the results I am currently getting and what I need to have. I need to compare one string in a cell to a whole row of cells, but this script only allows me to select one column at a a time. I am not a coder and need help finding the issue. See my work below.

SEE CURRENT RESULTS <<<-- CLICK ME

Sub highlight()
    Dim xRg1 As Range
    Dim xRg2 As Range
    Dim xTxt As String
    Dim xCell1 As Range
    Dim xCell2 As Range
    Dim I As Long
    Dim J As Integer
    Dim xLen As Integer
    Dim xDiffs As Boolean
    On Error Resume Next
    If ActiveWindow.RangeSelection.Count > 1 Then
      xTxt = ActiveWindow.RangeSelection.AddressLocal
    Else
      xTxt = ActiveSheet.UsedRange.AddressLocal
    End If
lOne:
    Set xRg1 = Application.InputBox("Range A:", "Kutools for Excel", xTxt, , , , , 8)
    If xRg1 Is Nothing Then Exit Sub
    If xRg1.Columns.Count > 1 Or xRg1.Areas.Count > 1 Then
        MsgBox "Multiple ranges or columns have been selected ", vbInformation, "Kutools for Excel"
        GoTo lOne
    End If
lTwo:
    Set xRg2 = Application.InputBox("Range B:", "Kutools for Excel", "", , , , , 8)
    If xRg2 Is Nothing Then Exit Sub
    If xRg2.Columns.Count > 1 Or xRg2.Areas.Count > 1 Then
        MsgBox "Multiple ranges or columns have been selected ", vbInformation, "Kutools for Excel"
        GoTo lTwo
    End If
    If xRg1.CountLarge <> xRg2.CountLarge Then
       MsgBox "Two selected ranges must have the same numbers of cells ", vbInformation, "Kutools for Excel"
       GoTo lTwo
    End If
    xDiffs = (MsgBox("Click Yes to highlight similarities, click No to highlight differences ", vbYesNo + vbQuestion, "Kutools for Excel") = vbNo)
    Application.ScreenUpdating = False
    xRg2.Font.ColorIndex = xlAutomatic
    For I = 1 To xRg1.Count
        Set xCell1 = xRg1.Cells(I)
        Set xCell2 = xRg2.Cells(I)
        If xCell1.Value2 = xCell2.Value2 Then
            If Not xDiffs Then xCell2.Font.Color = vbRed
        Else
            xLen = Len(xCell1.Value2)
            For J = 1 To xLen
                If Not xCell1.Characters(J, 1).Text = xCell2.Characters(J, 1).Text Then Exit For
            Next J
            If Not xDiffs Then
                If J <= Len(xCell2.Value2) And J > 1 Then
                    xCell2.Characters(1, J - 1).Font.Color = vbRed
                End If
            Else
                If J <= Len(xCell2.Value2) Then
                    xCell2.Characters(J, Len(xCell2.Value2) - J + 1).Font.Color = vbRed
                End If
            End If
        End If
    Next
    Application.ScreenUpdating = True
End Sub


问:
Sudo install on remote machine
I need to install some packages using yum (I am trying to follow the steps from here: https://root.cern/install/dependencies/), but when I try, I am told that I need to be root to perform this command. However, I am just a user on the remote linux compute cluster I am trying to install this on. Is there a way to do this without root privileges? Thank you!</p>

答:
I'm afraid not.

This question is too general but I will try to answer:

It is possible to unpack the contents of packages into the home directory, but it is very likely that they will want to write to folders where the average user does not have write permission. Also, configuration files are usually loaded from folders where it is not possible to write files.

Rather, I recommend compiling the required program from source code. Then it is possible to specify that the program will work only within the user's directory.

A similar situation can occur for other programming languages, but there are already specific solutions and there is no room to discuss them in more detail.

Title: Sudo install on remote machine


问:
What's the difference between find, where and find_by_id?
What's the difference between find, where and find_by_id?  They all work when you try to find a user given an ID.

答:
Not big deal, but there is another difference between find and where when you try to retrieve 1+ records and then you need to update each record and you want to use the find_each, it gonna work over the where method because the result of the where query is a ActiveRecord::Relation. But if you try to use find_each over the result with the find, you gonna have an error.

Profile.find([1, 2, 3]).find_each { |e| puts e.id }
=> NoMethodError (undefined method `find_each' for
 <Array:0x0000555e923d3f38>)

Profile.where(id: [1, 2, 3]).find_each { |e| puts e.id }
=> 1
=> 2
=> 3
```

ContentLicense: CC BY-SA 3.0


问:
How to handle concurrency in faunadb
I've some backend APIs which connect to faunadb; I'm able to do everything I need with data but I've some serious doubts about concurrent modifications (which maybe are not strictly related to faunadb only, but I'd like to understand how to deal with it using this technology).

One example above all: I want to create a new document (A) in a collection (X) which is linked (via reference or other fields) to other documents (B and C) in another collection (Y); in order to be linked, these documents (B and C) must satisfy a condition (e.g. field F = "V"). Once A has been created, B and C cannot be modified (or the condition will be invalidated!).
Of course the API to create the document A can run concurrently with the API used to modify documents B and C.

Here comes the doubt: what if, while creating the document A linked to document B and C, someone else changes field F of document B to something different from "V"?
I could end up with A linked to a wrong document, because both APIs don't know what the other one is doing..

Do I need to use the "Do" function in both APIs to create atomic transactions? So I can:

Check if B and C are valid and, if yes, create A in a single transaction

Check if B is linked to A and, if it doesn't, modify it in a single transaction

Thanks everyone.

答:
Fauna tries to present a consistent data view no matter or when your clients need to ask. Isolation of transaction effects is what matters on short time scales (typically less than 10ms).

The Do function merely lets you combine multiple disparate FQL expressions into a single query. There is no conditional processing aspect to Do.

You can certainly check conditions before undertaking operations, and all Fauna queries are atomic transactions: all of the query succeeds or none of its does.

Arranging for intermediate query values in order to perform conditional logic does tend to make FQL queries more complex, but they are definitely possible:

The query for your first API might look something like this:

```<code>Let(
  {
    document_b: Get(<reference to B document>),
    document_c: Get(<reference to C document>),
    required_b: Select(["data", "required_field"], Var("document_b"),
    required_c: Select(["data", "other_required"], Var("document_c"),
    condition: And(Var("required_b"), Var("required_c")),
  },
  If(
    Var("condition"),
    Create(Collection("A"), { data: { <document A data }}),
    Abort("Cannot create A because the conditions have not been met.")
  )
)
</code>```

The Let function allows you to compose named values for intermediate expressions, which can read or write whatever they need, along with logical operations that determine which conditions need to be tested. The value composition is followed by an expression which, in this example, tests the conditions and only creates the document in the A collection when the conditions are met. When the conditions are not met, the transaction is aborted with an appropriate error message.

Let can nest Lets as much as required, provide the query fits within the maximum query length of 16MB, so you can embed a significant amount of logic into your queries. When the length of a single query is not sufficient, you can define UDFs that can be called, which allow you to store business logic that you can use any number of times.

See the E-commerce tutorial for a UDF that performs all of the processing required to submit an order, check if there is sufficient product in stock, deduct requested quantities from inventory, set backordered status, and create the order.

Title: How to handle concurrency in faunadb

Body:
Fauna tries to present a consistent data view no matter or when your clients need to ask. Isolation of transaction effects is what matters on short time scales (typically less than 10ms).

The Do function merely lets you combine multiple disparate FQL expressions into a single query. There is no conditional processing aspect to Do.

You can certainly check conditions before undertaking operations, and all Fauna queries are atomic transactions: all of the query succeeds or none of its does.

Arranging for intermediate query values in order to perform conditional logic does tend to make FQL queries more complex, but they are definitely possible:

The query for your first API might look something like this:

Let(
  {
    document_b: Get(<reference to B document>),
    document_c: Get(<reference to C document>),
    required_b: Select(["data", "required_field"], Var("document_b"),
    required_c: Select(["data", "other_required"], Var("document_c"),
    condition: And(Var("required_b"), Var("required_c")),
  },
  If(
    Var("condition"),
    Create(Collection("A"), { data: { <document A data }}),
    Abort("Cannot create A because the conditions have not been met.")
  )
)

The Let function allows you to compose named values for intermediate expressions, which can read or write whatever they need, along with logical operations that determine which conditions need to be tested. The value composition is followed by an expression which, in this example, tests the conditions and only creates the document in the A collection when the conditions are met. When the conditions are not met, the transaction is aborted with an appropriate error message.

Let can nest Lets as much as required, provide the query fits within the maximum query length of 16MB, so you can embed a significant amount of logic into your queries. When the length of a single query is not sufficient, you can define UDFs that can be called, which allow you to store business logic that you can use any number of times.

See the E-commerce tutorial for a UDF that performs all of the processing required to submit an order, check if there is sufficient product in stock, deduct requested quantities from inventory, set backordered status, and create the order.


问:
Issue in asterisk server
I tried to enter Date Of Birth as 11211971 through my phone, but IVR (Interactive Voice Response) has 11121197.

please tell anybody what is the root cause for this issue

It is my code

```<code>exten => s,n,Read(dateofbirth,${ANOUNCEMENT_RECORDINGS}/HIP-5A1,8,s)
exten => s,n,GotoIf($["${dateofbirth}" = ""]?retry-dateofbirth-notentered)
exten => s,n,Set(monthofbirth=${dateofbirth:0:2})
exten => s,n,Set(dayofbirth=${dateofbirth:2:2})
exten => s,n,Set(yearofbirth=${dateofbirth:4:4})
exten => s,n,Goto(${IF($[$[${LEN(${monthofbirth})} != 2]|$[${monthofbirth} > 12] |$["${monthofbirth}" ="00"]|$["${monthofbirth}" ="**"]|$[${LEN(${dayofbirth})}!=2]|$[${dayofbirth} > 31]|$["${dayofbirth}" ="00"]|$["${dayofbirth}" ="**"]|$[${LEN(${yearofbirth})} !=4]|$["${yearofbirth}" ="0000"]|$["${yearofbirth}" ="****"]]?retry-dateofbirth-invalid:saydateofbirth)})
</code>```

答:
My assumption is if you are caling from DID and entering DTMF there might be some problem with DTMF receiving or DTMF negotiations in asterisk side you need to put relaxdtmf=yes , rfc2833compensate=yes and dtmfmode=rfc2833 if your provider support it.

if you are calling from softphone then try to enable dtmf type in softphone or sip hard phone.

Title: Issue in asterisk server

Body:
I tried to enter Date Of Birth as 11211971 through my phone, but IVR (Interactive Voice Response) has 11121197.

please tell anybody what is the root cause for this issue

It is my code

exten => s,n,Read(dateofbirth,${ANOUNCEMENT_RECORDINGS}/HIP-5A1,8,s)
exten => s,n,GotoIf($["${dateofbirth}" = ""]?retry-dateofbirth-notentered)
exten => s,n,Set(monthofbirth=${dateofbirth:0:2})
exten => s,n,Set(dayofbirth=${dateofbirth:2:2})
exten => s,n,Set(yearofbirth=${dateofbirth:4:4})
exten => s,n,Goto(${IF($[$[${LEN(${monthofbirth})} != 2]|$[${monthofbirth} > 12] |$["${monthofbirth}" ="00"]|$["${monthofbirth}" ="**"]|$[${LEN(${dayofbirth})}!=2]|$[${dayofbirth} > 31]|$["${dayofbirth}" ="00"]|$["${dayofbirth}" ="**"]|$[${LEN(${yearofbirth})} !=4]|$["${yearofbirth}" ="0000"]|$["${yearofbirth}" ="****"]]?retry-dateofbirth-invalid:saydateofbirth)})


问:
Access protected member function in C++
There are two external class (A and B)that I cannot change. I would like to access protected member of the class A:: doSomething in C (which I can do edit). Is there any way to access it. I understand its not good practice but I did not find any other way of doing it.</p>
```<code>// External code starts
struct A {
    friend class B;
protected:
    void doSomething() {
        std::cout << "A" << std::endl;
    }
};

struct B {
protected:
    void doSomething() {
        A a;
        a.doSomething();
    }
};

// External code ends

// This will not compile as doSomething is a protected member.
struct C : B {
protected:
    void doSomethingElse() {
        A a;
        a.doSomething();
    }
};
</code>```

答:
Friendship is not transitive, so inheriting from B doesn't help with this.

Inherit from A and form a pointer-to-member to doSomething:

```<code>struct Helper : A
{
    static constexpr auto ptr = &Helper::doSomething;
};
</code>```

Use that pointer to call a function on a:

```<code>void doSomethingElse()
{
    A a;
    (a.*Helper::ptr)();
}
</code>```

Title: Access protected member function in C++

Body:
There are two external class (A and B)that I cannot change. I would like to access protected member of the class A:: doSomething in C (which I can do edit). Is there any way to access it. I understand its not good practice but I did not find any other way of doing it.

// External code starts
struct A {
    friend class B;
protected:
    void doSomething() {
        std::cout << "A" << std::endl;
    }
};

struct B {
protected:
    void doSomething() {
        A a;
        a.doSomething();
    }
};

// External code ends

// This will not compile as doSomething is a protected member.
struct C : B {
protected:
    void doSomethingElse() {
        A a;
        a.doSomething();
    }
};

Body:
Friendship is not transitive, so inheriting from B doesn't help with this.

Inherit from A and form a pointer-to-member to doSomething:

struct Helper : A
{
    static constexpr auto ptr = &Helper::doSomething;
};

Use that pointer to call a function on a:

void doSomethingElse()
{
    A a;
    (a.*Helper::ptr)();
}


问:
Less repetitive way of selecting an image
Hello is there a way to make it less repetetive? It is React with typescript. On the given type I would like to input correct image.</p>
```<code>import { Box, Heading, Image, Text, Button, Icon } from "@chakra-ui/react";
import { Link } from "react-router-dom";
import { Recipe } from "../../shared/types/Recipe";
import Breakfast from "../../images/Breakfast.jpg";
import Lunch from "../../images/Lunch.jpg";
import Dinner from "../../images/Dinner.jpg";
import Supper from "../../images/Supper.jpg";
import { FaHeart } from "react-icons/fa";
import { useState } from "react";

const RecipeItem: React.FC<Recipe> = (props) => {
  const [isLiked, setIsLiekd] = useState < boolean > false;
  const onClickHandler = () => {
    setIsLiekd(true);
  };
  let imgName;
  if (props.type === "Breakfast") imgName = Breakfast;
  if (props.type === "Lunch") imgName = Lunch;
  if (props.type === "Dinner") imgName = Dinner;
  if (props.type === "Supper") imgName = Supper;
  // ...
};
</code>```

答:
Since the type name in props.type is the same as the variable name for the image, you can use the object shorthand syntax for a very succinct:

```<code>const imgName = ({Breakfast, Lunch, Dinner, Supper})[props.type];
</code>```

Body:
Hello is there a way to make it less repetetive? It is React with typescript. On the given type I would like to input correct image.

import { Box, Heading, Image, Text, Button, Icon } from "@chakra-ui/react";
import { Link } from "react-router-dom";
import { Recipe } from "../../shared/types/Recipe";
import Breakfast from "../../images/Breakfast.jpg";
import Lunch from "../../images/Lunch.jpg";
import Dinner from "../../images/Dinner.jpg";
import Supper from "../../images/Supper.jpg";
import { FaHeart } from "react-icons/fa";
import { useState } from "react";

const RecipeItem: React.FC<Recipe> = (props) => {
  const [isLiked, setIsLiekd] = useState < boolean > false;
  const onClickHandler = () => {
    setIsLiekd(true);
  };
  let imgName;
  if (props.type === "Breakfast") imgName = Breakfast;
  if (props.type === "Lunch") imgName = Lunch;
  if (props.type === "Dinner") imgName = Dinner;
  if (props.type === "Supper") imgName = Supper;
  // ...
};

Body:
Since the type name in props.type is the same as the variable name for the image, you can use the object shorthand syntax for a very succinct:

const imgName = ({Breakfast, Lunch, Dinner, Supper})[props.type];


问:
Change placeholder text
How can I change the placeholder text of an input element?

For example I have 3 inputs of type text.

```<code><input type="text" name="Email" placeholder="Some Text">
<input type="text" name="First Name" placeholder="Some Text">
<input type="text" name="Last Name"placeholder="Some Text">
</code>```

How can I change the Some Text text using JavaScript or jQuery?

答:
In your javascript file

document.getElementsByName('Email')[0].placeholder = 'new text for email';

Title: Change placeholder text

Body:
How can I change the placeholder text of an input element?

For example I have 3 inputs of type text.

<input type="text" name="Email" placeholder="Some Text">
<input type="text" name="First Name" placeholder="Some Text">
<input type="text" name="Last Name"placeholder="Some Text">

How can I change the Some Text text using JavaScript or jQuery?


问:
How to remove dash/ hyphen from each line in .txt file
I wrote a little program to turn pages from book scans to a .txt file. On some lines, words are moved to another line. I wonder if this is any way to remove the dashes and merge them with the syllables in the line below?

E.g.:

```<code>effects on the skin is fully under-
stood one fights
</code>```

to:

```<code> effects on the skin is fully understood
 one fights
</code>```

or:

```<code>effects on the skin is fully
understood one fights
</code>```

Or something like that. As long as it was connected. Python is my third language and so far I can't think of anything, so maybe someone will give mea hint.

Edit:
The point is that the last symbol, if it is a dash, is removed and merged with the rest of the word below

答:
This is a generator which takes the input line-by-line. If it ends with a - it extracts the last word and holds it over for the next line. It then yields any held-over word from the previous line combined with the current line.

To combine the results back into a single block of text, you can join it against the line separator of your choice:

source = """effects on the skin is fully under-
stood one fights
check-out Daft Punk's new sin-
le "Get Lucky" if you hav-
e the chance. Sound of the sum-
mer."""

def reflow(text):
    holdover = ""
    for line in text.splitlines():
        if line.endswith("-"):
            lin, _, e = line.rpartition(" ")
        else:
            lin, e = line, ""
        yield f"{holdover}{lin}"
        holdover = e[:-1]

print("\n".join(reflow(source)))
""" which is:
effects on the skin is fully
understood one fights
check-out Daft Punk's new
single "Get Lucky" if you
have the chance. Sound of the
summer.
"""
```
<p>To read one file line-by-line and write directly to a new file:</p>
<pre class="lang-py prettyprint-override"><code>def reflow(infile, outfile):
    with open(infile) as source, open(outfile, "w") as dest:
        holdover = ""
        for line in source.readlines():
            line = line.rstrip("\n")
            if line.endswith("-"):
                lin, _, e = line.rpartition(" ")
            else:
                lin, e = line, ""
            dest.write(f"{holdover}{lin}\n")
            holdover = e[:-1]

if __name__ == "__main__":
    reflow("source.txt", "dest.txt")
</code>```

Body:
I wrote a little program to turn pages from book scans to a .txt file. On some lines, words are moved to another line. I wonder if this is any way to remove the dashes and merge them with the syllables in the line below?

E.g.:

effects on the skin is fully under-
stood one fights

to:

 effects on the skin is fully understood
 one fights

or:

effects on the skin is fully
understood one fights

Or something like that. As long as it was connected. Python is my third language and so far I can't think of anything, so maybe someone will give mea hint.

Edit:
The point is that the last symbol, if it is a dash, is removed and merged with the rest of the word below

Body:
This is a generator which takes the input line-by-line. If it ends with a - it extracts the last word and holds it over for the next line. It then yields any held-over word from the previous line combined with the current line.

To combine the results back into a single block of text, you can join it against the line separator of your choice:

source = """effects on the skin is fully under-
stood one fights
check-out Daft Punk's new sin-
le "Get Lucky" if you hav-
e the chance. Sound of the sum-
mer."""

def reflow(text):
    holdover = ""
    for line in text.splitlines():
        if line.endswith("-"):
            lin, _, e = line.rpartition(" ")
        else:
            lin, e = line, ""
        yield f"{holdover}{lin}"
        holdover = e[:-1]

print("\n".join(reflow(source)))
""" which is:
effects on the skin is fully
understood one fights
check-out Daft Punk's new
single "Get Lucky" if you
have the chance. Sound of the
summer.
"""

To read one file line-by-line and write directly to a new file:

def reflow(infile, outfile):
    with open(infile) as source, open(outfile, "w") as dest:
        holdover = ""
        for line in source.readlines():
            line = line.rstrip("\n")
            if line.endswith("-"):
                lin, _, e = line.rpartition(" ")
            else:
                lin, e = line, ""
            dest.write(f"{holdover}{lin}\n")
            holdover = e[:-1]

if __name__ == "__main__":
    reflow("source.txt", "dest.txt")


答:
You can explode multiple columns at once:

```<code>cols = ['Subject', 'Marks']
df[cols] = df[cols].apply(lambda x: x.str.split(','))
df.explode(cols)
</code>```

Output:

```<code>   ID    Subject Marks
0   1      maths    80
0   1    physics    90
1   2   Computer    73
2   3      music    76
2   3     sports    89
2   3  chemistry    85
</code>```

Title: Pyspark: Is there a function to split dataframe column values on the basis of comma

Body:
input

+--------------+-----------------------+-----------------------+
|ID            |Subject                |Marks                  |
+--------------+-----------------------+-----------------------+
|1             |maths,physics          |80,90                  |
|2             |Computer               |73                     |
|3             |music,sports,chemistry |76,89,85               |
+--------------+-----------+-----------+-----------------------+

Expected output

+--------------+-----------------------+-----------------------+
|ID            |Subject                |Marks                  |
+--------------+-----------------------+-----------------------+
|1             |maths                  |80                     |
|1             |physics                |90                     |
|2             |Computer               |73                     |
|3             |music                  |76                     |
|3             |sports                 |89                     |
|3             |chemistry              |85                     |
+--------------+-----------+-----------+-----------------------+

need help in getting this expected output
,have already tried explode function but that only works on single column

Body:
You can explode multiple columns at once:

cols = ['Subject', 'Marks']
df[cols] = df[cols].apply(lambda x: x.str.split(','))
df.explode(cols)

Output:

   ID    Subject Marks
0   1      maths    80
0   1    physics    90
1   2   Computer    73
2   3      music    76
2   3     sports    89
2   3  chemistry    85


问:
How to convert 64 bit int to binary presentation?
How to convert 64 bit int to binary presentation (big endian)? For reverse task I use these functions:</p>

```<code>int readInt (struct str *buf) {
    buf -> cur_len = buf -> cur_len + 4;
    return
    (((buf -> data[buf -> cur_len - 3 ] & 0xff) << 24) |
    ((buf -> data[buf -> cur_len - 2 ] & 0xff) << 16) |
    ((buf -> data[buf -> cur_len - 1 ] & 0xff) <<  8) |
    ((buf -> data[buf -> cur_len ] & 0xff) <<  0));
};

long unsigned int 32Bit(struct str *buf) {  // 32
    return ((long unsigned int)readInt(buf)) & 0xffffffffL;
};

long unsigned int 64Bit(struct str *buffer) { //64
    long unsigned int result = 32Bit(buf);
    result *= 4294967296.0;
    return result;
}
</code>```

答:
Serialising a 64 bit unsigned number into an array of unsigned char, storing 8 bits in each in big-endian order, can be done like so:

```<code>void serialise_64bit(unsigned char dest[8], unsigned long long n)
{
    dest[0] = (n >> 56) & 0xff;
    dest[1] = (n >> 48) & 0xff;
    dest[2] = (n >> 40) & 0xff;
    dest[3] = (n >> 32) & 0xff;
    dest[4] = (n >> 24) & 0xff;
    dest[5] = (n >> 16) & 0xff;
    dest[6] = (n >>  8) & 0xff;
    dest[7] = (n >>  0) & 0xff;
}
</code>```

Body:
How to convert 64 bit int to binary presentation (big endian)? For reverse task I use these functions:

int readInt (struct str *buf) {
    buf -> cur_len = buf -> cur_len + 4;
    return
    (((buf -> data[buf -> cur_len - 3 ] & 0xff) << 24) |
    ((buf -> data[buf -> cur_len - 2 ] & 0xff) << 16) |
    ((buf -> data[buf -> cur_len - 1 ] & 0xff) <<  8) |
    ((buf -> data[buf -> cur_len ] & 0xff) <<  0));
};

long unsigned int 32Bit(struct str *buf) {  // 32
    return ((long unsigned int)readInt(buf)) & 0xffffffffL;
};

long unsigned int 64Bit(struct str *buffer) { //64
    long unsigned int result = 32Bit(buf);
    result *= 4294967296.0;
    return result;
}

Body:
Serialising a 64 bit unsigned number into an array of unsigned char, storing 8 bits in each in big-endian order, can be done like so:

void serialise_64bit(unsigned char dest[8], unsigned long long n)
{
    dest[0] = (n >> 56) & 0xff;
    dest[1] = (n >> 48) & 0xff;
    dest[2] = (n >> 40) & 0xff;
    dest[3] = (n >> 32) & 0xff;
    dest[4] = (n >> 24) & 0xff;
    dest[5] = (n >> 16) & 0xff;
    dest[6] = (n >>  8) & 0xff;
    dest[7] = (n >>  0) & 0xff;
}


问:
Passing JSON file in Postgres with Python
```<code>connection = psycopg2.connect("dbname=db1 user=postgres password=postgres")
cursor = connection.cursor()
cursor.execute("set search_path to public")

with open('json_template') as file:
    data = file.read()

query_sql = """
insert into table1 select * from
json_populate_recordset(NULL::table1, %s);
"""

# change .execute(query_sql) to .execute(query_sql, (data,))
cursor.execute(query_sql, (data,))
connection.commit()
</code>```

So I am trying to pass the contents of "json_template.json" to a Postgres table, but when I do I get the this error:
psycopg2.errors.InvalidParameterValue: cannot call json_populate_recordset on an object

I've created the table through psql cmd. Also, here are the contents of my json_template file:

{"key": "A123", "value": "15.6", "ts":"2020-10-07 13:28:43.399620+02:00"}
Attaching screenshot: json_template.json.

Did some research on the error, however nothing came out. Also tried to rewrite the code in other fashion several times  - still the same error.

Thank you in advance!

答:
You got a JSON object, so you need to use json_populate_record instead of json_populate_recordset, which works for an array of objects.

```<code>import psycopg2

con = psycopg2.connect(...)
cursor = con.cursor()

with open('json_template') as file:
    data = file.read()

query_sql = """
insert into table1 select * from
json_populate_record(NULL::table1, %s);
"""

cursor.execute(query_sql, (data,))
con.commit()
cursor.execute('select * from table1')
print(cursor.fetchall())
</code>```

Out:

```<code>[('A123', '15.6', '2020-10-07 13:28:43.399620+02:00')]
</code>```

Body:
connection = psycopg2.connect("dbname=db1 user=postgres password=postgres")
cursor = connection.cursor()
cursor.execute("set search_path to public")

with open('json_template') as file:
    data = file.read()

query_sql = """
insert into table1 select * from
json_populate_recordset(NULL::table1, %s);
"""

# change .execute(query_sql) to .execute(query_sql, (data,))
cursor.execute(query_sql, (data,))
connection.commit()

So I am trying to pass the contents of "json_template.json" to a Postgres table, but when I do I get the this error:
psycopg2.errors.InvalidParameterValue: cannot call json_populate_recordset on an object

I've created the table through psql cmd. Also, here are the contents of my json_template file:

{"key": "A123", "value": "15.6", "ts":"2020-10-07 13:28:43.399620+02:00"}
Attaching screenshot: json_template.json.

Did some research on the error, however nothing came out. Also tried to rewrite the code in other fashion several times  - still the same error.

Thank you in advance!

Body:
You got a JSON object, so you need to use json_populate_record instead of json_populate_recordset, which works for an array of objects.

import psycopg2

con = psycopg2.connect(...)
cursor = con.cursor()

with open('json_template') as file:
    data = file.read()

query_sql = """
insert into table1 select * from
json_populate_record(NULL::table1, %s);
"""

cursor.execute(query_sql, (data,))
con.commit()
cursor.execute('select * from table1')
print(cursor.fetchall())

Out:

[('A123', '15.6', '2020-10-07 13:28:43.399620+02:00')]


问:
Vuejs 3 alternative select binding
I'm trying to get a select element bound to a value for a custom object. The crux here is that the object property in question has a custom getter. The value is set as a number, but when accessed returns an associated value as a string. Why I do this is a long story.

So I have an object of key-value pairs making some options:

```<code><select v-model="myObject.myProperty">
    <option v-for="v, k in myOptions" :key="k" :value="k">{{v}}</option>
</select>
{{myObject.myProperty}} //this line prints out the correct value
</code>```

But the options are not showing as selected. The value is updated for myObject.myProperty and it returns what I expect. I suspect that behind the scenes, it's correctly assigning k to my custom object, but that because it returns a different string value, Vue can't inherently figure out which option to mark 'selected'.

Manually adding :selected does not help:

```<code><option v-for="v, k in myOptions" :key="k" :value="k" :selected="v === myObject.myProperty">{{v}}</option>
</code>```

I also tried to manually bind the select instead of using the v-model attribute, also no:

```<code><select :value="myObject.myProperty" @input="myObject.myProperty = $event.target.value"
</code>```

Is there an alternative way to wire up a select/option situation? If not, building a custom component with faux-select functionality is my next step.

For clarity, myOptions is a key-value like this

```<code>{
    0 : 'Option 1',
    1 : 'Option 2',
}
</code>```

But myObject has special setters that take and remember the key, then also a special getter than returns the value from myOptions.

So then:

```<code>myObject.myProperty = 0;
console.log(myObject.myProperty) //logs 'Option 1'
</code>```

When when I set the value to the key (k) I get back the corresponding value when the option is selected and the value of 'myObject.myProperty' is what I expect. Example: I pick 'Option 1' from the drop-down, which has a value of 0 derived from the key k.

However, although myObject.myProperty has the value I want, I can't get Vue to display the the actual html option as selected, probably because the value returned by myObject.myProperty is 'Option 1' and not 0

答:
Alright, the actual answer:

```<code><select @input="myObject.myProperty = $event.target.value">
    <option v-for="v, k in myOptions" :selected="myObject.myProperty === v" :key="k" :value="k">{{v}}</option>
</select>
</code>```

v-model won't work here because it simply doesn't care that you've manually applied selected: it will always try to match the option value to the the v-model property value. As this object takes one value with a setter and returns another with a getter, these will never align.

Instead, manually assign the value to the object with @input and match the value from the getter to the value in the options for selected.

Title: Vuejs 3 alternative select binding

Body:
I'm trying to get a select element bound to a value for a custom object. The crux here is that the object property in question has a custom getter. The value is set as a number, but when accessed returns an associated value as a string. Why I do this is a long story.

So I have an object of key-value pairs making some options:

<select v-model="myObject.myProperty">
    <option v-for="v, k in myOptions" :key="k" :value="k">{{v}}</option>
</select>
{{myObject.myProperty}} //this line prints out the correct value

But the options are not showing as selected. The value is updated for myObject.myProperty and it returns what I expect. I suspect that behind the scenes, it's correctly assigning k to my custom object, but that because it returns a different string value, Vue can't inherently figure out which option to mark 'selected'.

Manually adding :selected does not help:

<option v-for="v, k in myOptions" :key="k" :value="k" :selected="v === myObject.myProperty">{{v}}</option>

I also tried to manually bind the select instead of using the v-model attribute, also no:

<select :value="myObject.myProperty" @input="myObject.myProperty = $event.target.value"

Is there an alternative way to wire up a select/option situation? If not, building a custom component with faux-select functionality is my next step.

For clarity, myOptions is a key-value like this

{
    0 : 'Option 1',
    1 : 'Option 2',
}

But myObject has special setters that take and remember the key, then also a special getter than returns the value from myOptions.

So then:

myObject.myProperty = 0;
console.log(myObject.myProperty) //logs 'Option 1'

When when I set the value to the key (k) I get back the corresponding value when the option is selected and the value of 'myObject.myProperty' is what I expect. Example: I pick 'Option 1' from the drop-down, which has a value of 0 derived from the key k.

However, although myObject.myProperty has the value I want, I can't get Vue to display the the actual html option as selected, probably because the value returned by myObject.myProperty is 'Option 1' and not 0

Body:
Alright, the actual answer:

<select @input="myObject.myProperty = $event.target.value">
    <option v-for="v, k in myOptions" :selected="myObject.myProperty === v" :key="k" :value="k">{{v}}</option>
</select>

v-model won't work here because it simply doesn't care that you've manually applied selected: it will always try to match the option value to the the v-model property value. As this object takes one value with a setter and returns another with a getter, these will never align.

Instead, manually assign the value to the object with @input and match the value from the getter to the value in the options for selected.


答:
Here is one way to do it</p>
```<code>with open('test.txt') as file:
    combined_strings = []
    merge_line = False
    for item in file:
        item = item.replace('\n', '') # remove new line character at end of line
        if '-' in item[-1]:  # check that it is the last character
            merge_line = True
            combined_strings.append(item[:-1])
        elif merge_line:
            merge_line = False
            combined_strings[-1] = combined_strings[-1] + item
        else:
            combined_strings.append(item)
</code>```

Title: How to remove dash/ hyphen from each line in .txt file

Body:
Here is one way to do it

with open('test.txt') as file:
    combined_strings = []
    merge_line = False
    for item in file:
        item = item.replace('\n', '') # remove new line character at end of line
        if '-' in item[-1]:  # check that it is the last character
            merge_line = True
            combined_strings.append(item[:-1])
        elif merge_line:
            merge_line = False
            combined_strings[-1] = combined_strings[-1] + item
        else:
            combined_strings.append(item)


问:
Create dictionary from values extracted through regex
I have a sparql query (qres1) that fetches strings from concepts of an RDF file (eg. below), on which I am applying regex to get two values. I would like to store these values as key-value pair in dictionary.

eg. (rdflib.term.Literal('skin sarcoma', lang='en'), rdflib.term.URIRef('http://purl.obolibrary.org/obo/DOID_2687'))

```<code>pattern_doid = '.*\/(DOID.*)'
pattern_label = '.*\(\'(.*)\',.*'
doid = []
label = []
dict = {}

for line in qres1:
    doid = re.findall(pattern_doid, str(line[0]), re.MULTILINE)
    label = re.findall(pattern_label, str(line[1]), re.MULTILINE)

   #create dictionary with doid as key and prefLabel as value
    dict[doid[0]] = label[0]

</code>```

This gives me the following error.
IndexError: list index out of range

How can I create such dictionary. Any help is highly appreciated.

答:
I've tweaked the regex but generally it seems okay.

>>> import re
>>> re.findall(r'.*\/(DOID_\d+).*', "rdflib.term.URIRef('http://purl.obolibrary.org/obo/DOID_2687'))", re.MULTILINE)
['DOID_2687']
>>> re.findall(r'.*\(\'(.*)\'\).*', "rdflib.term.URIRef('http://purl.obolibrary.org/obo/DOID_2687'))", re.MULTILINE)
['http://purl.obolibrary.org/obo/DOID_2687']
```
<p>You will get an indexing error if the string doesn't have a 'doid' or 'label'.</p>
<p>e.g.</p>
<pre class="lang-py prettyprint-override"><code>>>> re.findall(r'.*\(\'(.*)\'\).*', "rdflib.term.URIRef'))", re.MULTILINE)[0]
Traceback (most recent call last):
  File "<pyshell#3>", line 1, in <module>
    re.findall(r'.*\(\'(.*)\'\).*', "rdflib.term.URIRef'))", re.MULTILINE)[0]
IndexError: list index out of range
</code>```

Body:
I have a sparql query (qres1) that fetches strings from concepts of an RDF file (eg. below), on which I am applying regex to get two values. I would like to store these values as key-value pair in dictionary.

eg. (rdflib.term.Literal('skin sarcoma', lang='en'), rdflib.term.URIRef('http://purl.obolibrary.org/obo/DOID_2687'))

pattern_doid = '.*\/(DOID.*)'
pattern_label = '.*\(\'(.*)\',.*'
doid = []
label = []
dict = {}

for line in qres1:
    doid = re.findall(pattern_doid, str(line[0]), re.MULTILINE)
    label = re.findall(pattern_label, str(line[1]), re.MULTILINE)

   #create dictionary with doid as key and prefLabel as value
    dict[doid[0]] = label[0]

This gives me the following error.
IndexError: list index out of range

How can I create such dictionary. Any help is highly appreciated.

Body:
I've tweaked the regex but generally it seems okay.

>>> import re
>>> re.findall(r'.*\/(DOID_\d+).*', "rdflib.term.URIRef('http://purl.obolibrary.org/obo/DOID_2687'))", re.MULTILINE)
['DOID_2687']
>>> re.findall(r'.*\(\'(.*)\'\).*', "rdflib.term.URIRef('http://purl.obolibrary.org/obo/DOID_2687'))", re.MULTILINE)
['http://purl.obolibrary.org/obo/DOID_2687']

You will get an indexing error if the string doesn't have a 'doid' or 'label'.

e.g.

>>> re.findall(r'.*\(\'(.*)\'\).*', "rdflib.term.URIRef'))", re.MULTILINE)[0]
Traceback (most recent call last):
  File "<pyshell#3>", line 1, in <module>
    re.findall(r'.*\(\'(.*)\'\).*', "rdflib.term.URIRef'))", re.MULTILINE)[0]
IndexError: list index out of range


问:
Variable route parameter with different datatypes
I have a controller with the following RouteAttribute:

```<code>[Route("api/[controller]/{customerId}")]
</code>```

Now I have the following action method with the route:

```<code>[HttpGet("CustomerDetails")]
public async Task<ActionResult<GetCustomerDetailsQueryResponse>> GetCustomerDetail(Guid customerId)
</code>```

Now, I would like to re-purpose this endpoint such that when I provide customer number, I should be able to get customer details based on that.

So if I make a postman call to: /api/Customers/XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX/CustomerDetails, I would get customer details based on the Guid Id.

Now the same endpoint should work if I make the call /api/Customers/01234/CustomerDetails.

What I have tried: I have tried the following:

```<code>[HttpGet("{customerNumber:int?}/CustomerDetails")]
public async Task<ActionResult<GetCustomerDetailsQueryResponse>> GetCustomerDetail(Guid customerId, int customerNumber)
</code>```

But unfortunately, this doesn't work. Any ideas on making this work?

答:
minimal example</p>
```<code>[ApiController]
[Route("[controller]")]
public class TestController : ControllerBase
{
    public TestController(){}

    [HttpGet("{guid:guid}/details")]
    public System.Guid GetIdGuid(System.Guid guid)
    {
        return guid;
    }

    [HttpGet("{id:int}/details")]
    public int GetIdInt(int id)
    {
        return id;
    }

}
</code>```

Body:
I have a controller with the following RouteAttribute:

[Route("api/[controller]/{customerId}")]

Now I have the following action method with the route:

[HttpGet("CustomerDetails")]
public async Task<ActionResult<GetCustomerDetailsQueryResponse>> GetCustomerDetail(Guid customerId)

Now, I would like to re-purpose this endpoint such that when I provide customer number, I should be able to get customer details based on that.

So if I make a postman call to: /api/Customers/XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX/CustomerDetails, I would get customer details based on the Guid Id.

Now the same endpoint should work if I make the call /api/Customers/01234/CustomerDetails.

What I have tried: I have tried the following:

[HttpGet("{customerNumber:int?}/CustomerDetails")]
public async Task<ActionResult<GetCustomerDetailsQueryResponse>> GetCustomerDetail(Guid customerId, int customerNumber)

But unfortunately, this doesn't work. Any ideas on making this work?

Body:
minimal example

[ApiController]
[Route("[controller]")]
public class TestController : ControllerBase
{
    public TestController(){}

    [HttpGet("{guid:guid}/details")]
    public System.Guid GetIdGuid(System.Guid guid)
    {
        return guid;
    }

    [HttpGet("{id:int}/details")]
    public int GetIdInt(int id)
    {
        return id;
    }

}


问:
How can I know the address of owner object in C++?
I would like to create in C++ a Notifier class that I will use in other objects to notify various holders when the object gets destroyed.

```<code>template <class Owner>
class Notifier<Owner> {
public:
  Notifier(Owner* owner);
  ~Notifier(); // Notifies the owner that an object is destroyed
};

class Owner;

class Owned {
public:
  Owned(Owner* owner);
private:
  Notifier<Owner> _notifier;
};
</code>```

My point is that as I have a dense and complicated object graph, I'd like to avoid storing the address of the owned object in the notifier.  Is there a way to change my notifier class so that it can deduce the owned object's address from its own address and an offset that would be computed at compile time?

Note also that any object may have to notify several 'owners', possibly from the same class.

Thanks.

答:
fa.'s answer is a good start. However, it does not resolve the problem of having multiple owners of the same type. One solution is to have the notifier store a list of owners instead of a single one. Here is a quick implementation, to show the idea:

```<code>template <typename Owner, typename Owned>
class Notifier
{
  protected:
    Notifier()
    {}

    // Constructor taking a single owner
    Notifier(Owner & o)
    {
        owners.push_back(&o);
    }

    // Constructor taking a range of owners
    template <typename InputIterator>
    Notifier(InputIterator firstOwner, InputIterator lastOwner)
        : owners(firstOwner, lastOwner) {}

    ~Notifier()
    {
        OwnerList::const_iterator it = owners.begin();
        OwnerList::const_iterator end = owners.end();
        for ( ; it != end ; ++it)
        {
            (*it)->notify(static_cast<Owned*>(this));
        }
    }

    // Method for adding a new owner
    void addOwner(Owner & o)
    {
        owners.push_back(&o);
    }

private:
    typedef std::vector<Owner *> OwnerList;
    OwnerList owners;
};
</code>```

You can use it this way:

```<code>class Owner;

class Owned : public Notifier<Owner, Owned>
{
    typedef Notifier<Owner, Owned> base;

    //Some possible constructors:
    Owned(Owner & o) : base(o) { }

    Owned(Owner & o1, Owner & o2)
    {
        base::addOwner(o1); //qualified call of base::addOwner
        base::addOwner(o2); //in case there are other bases
    }

    Owned(std::list<Owner*> lo) : base(lo.begin(), lo.end()) { }
};
</code>```

In the case where you have many different types of Owners, this solution can become rather difficult to use. In this case, you might want to look at the boost metaprogramming libraries (MPL, Fusion), with which you could end up with a code that let you do stuffs like that:

```<code>class Owned : public Notifier<Owned, OwnerType1, OwnerType1, OwnerType2>
{
    Owned(OwnerType1 & o1, OwnerType1 & o2, OwnerType2 & o3)
        : base(o1,o2,o3)
};
</code>```

However, implementing this solution would be a little longer than the previous one.

OwnerDisplayName: Xavier Nodet

ContentLicense: CC BY-SA 2.5

Body:
I would like to create in C++ a Notifier class that I will use in other objects to notify various holders when the object gets destroyed.

template <class Owner>
class Notifier<Owner> {
public:
  Notifier(Owner* owner);
  ~Notifier(); // Notifies the owner that an object is destroyed
};

class Owner;

class Owned {
public:
  Owned(Owner* owner);
private:
  Notifier<Owner> _notifier;
};

My point is that as I have a dense and complicated object graph, I'd like to avoid storing the address of the owned object in the notifier.  Is there a way to change my notifier class so that it can deduce the owned object's address from its own address and an offset that would be computed at compile time?

Note also that any object may have to notify several 'owners', possibly from the same class.

Thanks.

LastEditorDisplayName: Xavier Nodet

Body:
fa.'s answer is a good start. However, it does not resolve the problem of having multiple owners of the same type. One solution is to have the notifier store a list of owners instead of a single one. Here is a quick implementation, to show the idea:

template <typename Owner, typename Owned>
class Notifier
{
  protected:
    Notifier()
    {}

    // Constructor taking a single owner
    Notifier(Owner & o)
    {
        owners.push_back(&o);
    }

    // Constructor taking a range of owners
    template <typename InputIterator>
    Notifier(InputIterator firstOwner, InputIterator lastOwner)
        : owners(firstOwner, lastOwner) {}

    ~Notifier()
    {
        OwnerList::const_iterator it = owners.begin();
        OwnerList::const_iterator end = owners.end();
        for ( ; it != end ; ++it)
        {
            (*it)->notify(static_cast<Owned*>(this));
        }
    }

    // Method for adding a new owner
    void addOwner(Owner & o)
    {
        owners.push_back(&o);
    }

private:
    typedef std::vector<Owner *> OwnerList;
    OwnerList owners;
};

You can use it this way:

class Owner;

class Owned : public Notifier<Owner, Owned>
{
    typedef Notifier<Owner, Owned> base;

    //Some possible constructors:
    Owned(Owner & o) : base(o) { }

    Owned(Owner & o1, Owner & o2)
    {
        base::addOwner(o1); //qualified call of base::addOwner
        base::addOwner(o2); //in case there are other bases
    }

    Owned(std::list<Owner*> lo) : base(lo.begin(), lo.end()) { }
};

In the case where you have many different types of Owners, this solution can become rather difficult to use. In this case, you might want to look at the boost metaprogramming libraries (MPL, Fusion), with which you could end up with a code that let you do stuffs like that:

class Owned : public Notifier<Owned, OwnerType1, OwnerType1, OwnerType2>
{
    Owned(OwnerType1 & o1, OwnerType1 & o2, OwnerType2 & o3)
        : base(o1,o2,o3)
};

However, implementing this solution would be a little longer than the previous one.

OwnerDisplayName: Luc Touraille


问:
Return multiple values for antd form item, value pass in array of items
I am working in react on a ruby on rails backend using antd. I have an antd form that passes in options from the controller in the backend. The point of this form item is to get an item id number, but I would also like to pass in a couple other attributes that are included in the controller.

The data works for me, so in the code example if I change <Option key={"item_" + o.id} value={o.id}> to <Option key={"item_" + o.id} value={o.attribute2}> I correctly get the other attribute I want. The problem is I want id, attribute2, and attribute3 to all pass in.

Is it possible for an antd form item to have multiple values. In my code example the commented out lines are things I have tried. I tried doing an array like value={o.id, o.attribute2, o.attribute3} and then extracting them with value.attribute2 or value[1], but nothing seems to work.

Or if I can pass in the data as just information like have value={} and then otherdata = {} that would work too, but that didn't seem to work either.

Below is my code,

```<code>
    <Form.Item name="item_id" label={"item"} style={{ marginBottom: "0px" }}>
  <Select style={{width:"200px"}} onChange={(value, attribute2) => {
                              id_variable = value;
                              // id_variable = value[0];
                              // attribute2_variable = value.attribute2;
                              // attribute2_variable = value[1];
                              // attribute2_variable = attribute2
                            }}>
    {options.tanks.map((o) => <Option key={"item_" + o.id} value={o.id}>{o.label}</Option>)}
    {/* {options.tanks.map((o) => <Option key={"item_" + o.id} value={o.id, o.attribute2, o.attribute3} attribute2={o.attribute2}>{o.label}</Option>)} */}
  </Select>
</Form.Item>
</code>```

答:
Figured out what I was doing wrong. In case anyone sees this and has a similar problem: I wasn't making value an array correctly.

```<code>value={o.id, o.attribute2, o.attribute3}
</code>```

should be

```<code>value={[o.id, o.attribute2, o.attribute3]}
</code>```

Then you can call

```<code><Select onChange={(value) => {
                              id_variable = value[0];
                              attribute2_variable = value[1];
                              attribute2_variable = value[2];
</code>```

Body:
I am working in react on a ruby on rails backend using antd. I have an antd form that passes in options from the controller in the backend. The point of this form item is to get an item id number, but I would also like to pass in a couple other attributes that are included in the controller.

The data works for me, so in the code example if I change <Option key={"item_" + o.id} value={o.id}> to <Option key={"item_" + o.id} value={o.attribute2}> I correctly get the other attribute I want. The problem is I want id, attribute2, and attribute3 to all pass in.

Is it possible for an antd form item to have multiple values. In my code example the commented out lines are things I have tried. I tried doing an array like value={o.id, o.attribute2, o.attribute3} and then extracting them with value.attribute2 or value[1], but nothing seems to work.

Or if I can pass in the data as just information like have value={} and then otherdata = {} that would work too, but that didn't seem to work either.

Below is my code,

    <Form.Item name="item_id" label={"item"} style={{ marginBottom: "0px" }}>
  <Select style={{width:"200px"}} onChange={(value, attribute2) => {
                              id_variable = value;
                              // id_variable = value[0];
                              // attribute2_variable = value.attribute2;
                              // attribute2_variable = value[1];
                              // attribute2_variable = attribute2
                            }}>
    {options.tanks.map((o) => <Option key={"item_" + o.id} value={o.id}>{o.label}</Option>)}
    {/* {options.tanks.map((o) => <Option key={"item_" + o.id} value={o.id, o.attribute2, o.attribute3} attribute2={o.attribute2}>{o.label}</Option>)} */}
  </Select>
</Form.Item>

Body:
Figured out what I was doing wrong. In case anyone sees this and has a similar problem: I wasn't making value an array correctly.

value={o.id, o.attribute2, o.attribute3}

should be

value={[o.id, o.attribute2, o.attribute3]}

Then you can call

<Select onChange={(value) => {
                              id_variable = value[0];
                              attribute2_variable = value[1];
                              attribute2_variable = value[2];


问:
indices in MaxPool2d in pytorch
I am studying the documentation at https://pytorch.org/docs/stable/generated/torch.nn.MaxPool2d.html.

In the parameters section, it states

return_indices – if True, will return the max indices along with the outputs. Useful for torch.nn.MaxUnpool2d later

Could someone explain to me what max indices mean here? I believe it is the indices corresponding to the maximal value. If the maximal value is unique, does that mean only 1 index will be returned?

答:
I assume you already know how max pooling works.
Then, let's print some results to get more insights.

import torch
import torch.nn as nn

pool = nn.MaxPool2d(kernel_size=2, return_indices=True)
input = torch.zeros(1, 1, 4, 4)
input[..., 0, 1] = input[..., 1, 3] = input[..., 2, 2] = input[..., 3, 0] = 1.
print(input)
```
<h6>output</h6>
```tensor([[[[0., 1., 0., 0.],
          [0., 0., 0., 1.],
          [0., 0., 1., 0.],
          [1., 0., 0., 0.]]]])
```
<pre class="lang-py prettyprint-override"><code>output, indices = pool(input)
print(output)
</code>```

output

```<code>tensor([[[[1., 1.],
          [1., 1.]]]])
</code>```

print(indices)
```
<h6>output</h6>
```tensor([[[[ 1,  7],
          [12, 10]]]])
```

If you stretch the input tensor and make it 1d, you can see that indices contains the positions of each 1 value (the maximum for each window of MaxPool2d). As written in the documentation of torch.nn.MaxPool2d, indices is required for the torch.nn.MaxUnpool2d module:

MaxUnpool2d takes in as input the output of MaxPool2d including the indices of the maximal values and computes a partial inverse in which all non-maximal values are set to zero.

Title: indices in MaxPool2d in pytorch

Body:
I assume you already know how max pooling works.
Then, let's print some results to get more insights.

import torch
import torch.nn as nn

pool = nn.MaxPool2d(kernel_size=2, return_indices=True)
input = torch.zeros(1, 1, 4, 4)
input[..., 0, 1] = input[..., 1, 3] = input[..., 2, 2] = input[..., 3, 0] = 1.
print(input)

output

tensor([[[[0., 1., 0., 0.],
          [0., 0., 0., 1.],
          [0., 0., 1., 0.],
          [1., 0., 0., 0.]]]])

output, indices = pool(input)
print(output)

output

tensor([[[[1., 1.],
          [1., 1.]]]])

print(indices)

output

tensor([[[[ 1,  7],
          [12, 10]]]])

If you stretch the input tensor and make it 1d, you can see that indices contains the positions of each 1 value (the maximum for each window of MaxPool2d). As written in the documentation of torch.nn.MaxPool2d, indices is required for the torch.nn.MaxUnpool2d module:

MaxUnpool2d takes in as input the output of MaxPool2d including the indices of the maximal values and computes a partial inverse in which all non-maximal values are set to zero.


问:
FOUND_ROWS() in MariaDB 10
I have a function which needs the number of rows returned by a select. After some googling i found the FOUND_ROWS() function. But i don't think it works:

```<code>SELECT * FROM tipfirme LIMIT 20;
SELECT FOUND_ROWS();
</code>```

because it always returns 1 as the found value.

However, if i run it in one line, it works.

```<code>  SELECT FOUND_ROWS() FROM (SELECT * FROM tipfirme LIMIT 20) as T
</code>```

Am i doing something wrong or is the function broken?

答:
FOUND_ROWS returns the number of rows the previous request (entire select statement) returned.  It sounds to me like you are wanting just:

```<code>select count(1) from (select * From tipfirme limit 20) as T
</code>```

select found_rows(); separately would not always return 1; I suspect you were not testing what you meant to test.  If it immediately follows select * from tipfirme limit 20; it would indeed return the number of rows the select returned (after the limit, or before the limit if you specified sql_calc_found_rows in the previous select).

SELECT FOUND_ROWS() FROM (SELECT * FROM tipfirme LIMIT 20) as T isn't doing what you think; it will return as many rows as the subselect returned, and each will have the number of rows the previously executed select returned, not related to the number of rows from the subselect at all.

Title: FOUND_ROWS() in MariaDB 10

Body:
I have a function which needs the number of rows returned by a select. After some googling i found the FOUND_ROWS() function. But i don't think it works:

SELECT * FROM tipfirme LIMIT 20;
SELECT FOUND_ROWS();

because it always returns 1 as the found value.

However, if i run it in one line, it works.

  SELECT FOUND_ROWS() FROM (SELECT * FROM tipfirme LIMIT 20) as T

Am i doing something wrong or is the function broken?

Body:
FOUND_ROWS returns the number of rows the previous request (entire select statement) returned.  It sounds to me like you are wanting just:

select count(1) from (select * From tipfirme limit 20) as T

select found_rows(); separately would not always return 1; I suspect you were not testing what you meant to test.  If it immediately follows select * from tipfirme limit 20; it would indeed return the number of rows the select returned (after the limit, or before the limit if you specified sql_calc_found_rows in the previous select).

SELECT FOUND_ROWS() FROM (SELECT * FROM tipfirme LIMIT 20) as T isn't doing what you think; it will return as many rows as the subselect returned, and each will have the number of rows the previously executed select returned, not related to the number of rows from the subselect at all.


问:
Why does the y-axis of my stacked bar chart not match the values in my data frame?
I have a data frame (190 x 27) where each sample has a certain proportion of different cell types. Below is a snapshot of this data frame.

# A tibble: 3 × 5
  projid   age_cat Monocytes_EPIC Neutrophils_EPIC Vascular_endothelial_cells
  <chr>    <fct>            <dbl>            <dbl>                      <dbl>
1 02525608 95-99            0.062            0.832                      0.066
2 03052480 85-89            0.075            0.762                      0.051
3 03283241 75-79            0.021            0.876                      0.031
```
<p>I need to create a stacked bar chart, where the x-axis is age category, the bars are colored/filled by cell type, and the y-axis reflect the proportion of each cell type within each age-category.</p>
<p>I tried the code below and generated the following data frame and stacked bar chart:</p>
<pre class="lang-r prettyprint-override"><code>df_long <- df %>% gather( CellType, Proportion, 3:27 )
df_long
# A tibble: 4,750 × 4
   projid   age_cat CellType       Proportion
   <chr>    <fct>   <chr>               <dbl>
 1 02525608 95-99   Monocytes_EPIC      0.062
 2 03052480 85-89   Monocytes_EPIC      0.075
 3 03283241 75-79   Monocytes_EPIC      0.021
 4 03430444 75-79   Monocytes_EPIC      0.032
 5 03806878 85-89   Monocytes_EPIC      0.127
 6 03889845 85-89   Monocytes_EPIC      0.025
 7 04576591 90-94   Monocytes_EPIC      0.129
 8 05498462 85-89   Monocytes_EPIC      0.021
 9 05522533 75-79   Monocytes_EPIC      0
10 06073025 80-84   Monocytes_EPIC      0.07
# … with 4,740 more rows
</code>```

ggplot( pd2_long, aes( x = age_cat, y = Proportion, fill = CellType ) ) +
  geom_col( position = position_stack( ) ) +
  scale_fill_manual( values = mycolors, name = "Cell Type" ) +
  scale_y_continuous( expand = c( 0.01,1 ) ) +
  theme( axis.text.x = element_text( angle = -90 ) ) +
  xlab( "Age Category" ) +
  ylab( "Proportion" ) +
  labs( title = "Proportion of Cell Types" ) +
  theme( axis.text.x = element_text( angle = 0 ) )
```

As you can see, the Y-axis seems to reflect a count of the number of samples within each category, not the proportion of each cell type. Can someone please explain why this is happening and how I can obtain a similar graph where the Y-axis reflects the proportion of each cell type within each age category?

答:
It's summing the Proportion values for celltype within each age. If you then want to represent that summed data as the proportion (summing to 1.00 for each age group) of celltype within each age you can change geom_col -></p>
```<code>geom_col(position = "fill")
</code>```

Body:
I have a data frame (190 x 27) where each sample has a certain proportion of different cell types. Below is a snapshot of this data frame.

# A tibble: 3 × 5
  projid   age_cat Monocytes_EPIC Neutrophils_EPIC Vascular_endothelial_cells
  <chr>    <fct>            <dbl>            <dbl>                      <dbl>
1 02525608 95-99            0.062            0.832                      0.066
2 03052480 85-89            0.075            0.762                      0.051
3 03283241 75-79            0.021            0.876                      0.031

I need to create a stacked bar chart, where the x-axis is age category, the bars are colored/filled by cell type, and the y-axis reflect the proportion of each cell type within each age-category.

I tried the code below and generated the following data frame and stacked bar chart:

df_long <- df %>% gather( CellType, Proportion, 3:27 )
df_long
# A tibble: 4,750 × 4
   projid   age_cat CellType       Proportion
   <chr>    <fct>   <chr>               <dbl>
 1 02525608 95-99   Monocytes_EPIC      0.062
 2 03052480 85-89   Monocytes_EPIC      0.075
 3 03283241 75-79   Monocytes_EPIC      0.021
 4 03430444 75-79   Monocytes_EPIC      0.032
 5 03806878 85-89   Monocytes_EPIC      0.127
 6 03889845 85-89   Monocytes_EPIC      0.025
 7 04576591 90-94   Monocytes_EPIC      0.129
 8 05498462 85-89   Monocytes_EPIC      0.021
 9 05522533 75-79   Monocytes_EPIC      0
10 06073025 80-84   Monocytes_EPIC      0.07
# … with 4,740 more rows

ggplot( pd2_long, aes( x = age_cat, y = Proportion, fill = CellType ) ) +
  geom_col( position = position_stack( ) ) +
  scale_fill_manual( values = mycolors, name = "Cell Type" ) +
  scale_y_continuous( expand = c( 0.01,1 ) ) +
  theme( axis.text.x = element_text( angle = -90 ) ) +
  xlab( "Age Category" ) +
  ylab( "Proportion" ) +
  labs( title = "Proportion of Cell Types" ) +
  theme( axis.text.x = element_text( angle = 0 ) )

As you can see, the Y-axis seems to reflect a count of the number of samples within each category, not the proportion of each cell type. Can someone please explain why this is happening and how I can obtain a similar graph where the Y-axis reflects the proportion of each cell type within each age category?

Body:
It's summing the Proportion values for celltype within each age. If you then want to represent that summed data as the proportion (summing to 1.00 for each age group) of celltype within each age you can change geom_col ->

geom_col(position = "fill")


问:
How can I obtain the default value for a type in Scala?
I'm trying to write a Scala function that returns the default value of a type (0, 0.0, false, '\0', etc. for value types and null for reference types). I came up with this:

```<code>def defaultValue[U]: U = {
  class Default[U] { var default: U = _ }
  new Default[U].default
}
</code>```

and while this works well if called directly, it returns null even for value types when called through a function that itself is generic, as shown in this REPL session:

```<code>Welcome to Scala version 2.8.1.final (Java HotSpot(TM) 64-Bit Server VM, Java 1.6.0_24).
Type in expressions to have them evaluated.
Type :help for more information.

scala> def defaultValue[U]: U = { class Default[U] {var default: U = _ }; new Default[U].default }
defaultValue: [U]U

scala> defaultValue[Boolean] // direct call works
res0: Boolean = false

scala> var res: Any = 0
res: Any = 0

scala> def setRes[U] = { res = defaultValue[U]; defaultValue[U] }
setRes: [U]U

scala> setRes[Boolean] // returns a Boolean, but...
res1: Boolean = false

scala> res
res2: Any = null // ... sets the res variable to null.
</code>```

Can someone explain to me:

why this happens (and why the compiler/interpreter doesn't complain if there is not enough information for it to return a true Boolean); and

how I can fix it?

答:
I have written a blog post on building a defaulting mechanism for Scala. You can find it here.

If you do not want Option[_] to default to None, String to "" etc then get rid of the respective implicits from the object Default.

Body:
I'm trying to write a Scala function that returns the default value of a type (0, 0.0, false, '\0', etc. for value types and null for reference types). I came up with this:

def defaultValue[U]: U = {
  class Default[U] { var default: U = _ }
  new Default[U].default
}

and while this works well if called directly, it returns null even for value types when called through a function that itself is generic, as shown in this REPL session:

Welcome to Scala version 2.8.1.final (Java HotSpot(TM) 64-Bit Server VM, Java 1.6.0_24).
Type in expressions to have them evaluated.
Type :help for more information.

scala> def defaultValue[U]: U = { class Default[U] {var default: U = _ }; new Default[U].default }
defaultValue: [U]U

scala> defaultValue[Boolean] // direct call works
res0: Boolean = false

scala> var res: Any = 0
res: Any = 0

scala> def setRes[U] = { res = defaultValue[U]; defaultValue[U] }
setRes: [U]U

scala> setRes[Boolean] // returns a Boolean, but...
res1: Boolean = false

scala> res
res2: Any = null // ... sets the res variable to null.

Can someone explain to me:

why this happens (and why the compiler/interpreter doesn't complain if there is not enough information for it to return a true Boolean); and

how I can fix it?


问:
Tweepy error 'API' object has no attribute 'me'
I am trying to run the code from https://github.com/CreepyD246/Twitter-Reply-Bot/blob/main/TwitterReplyBot.py on Replit.

```<code>#Importing modules/libraries
import tweepy
import time
import os

# Initialization code
auth = tweepy.OAuthHandler(os.getenv("key2"),os.getenv("skey2"))
auth.set_access_token(os.getenv("token2"),os.getenv("stoken2"))
api = tweepy.API(auth)

# Some important variables which will be used later
bot_id = int(api.me().id_str)
#Other things after
</code>```

But I get this error:

```<code>Traceback (most recent call last):
File "main.py", line 12, in <module>
bot_id = int(api.me().id_str)
AttributeError: 'API' object has no attribute 'me'
</code>```

I don't find anything in the Tweepy's documentation about API.me() so what's wrong?
The Tweepy version is 4.1.0.

答:
Tweepy v4.0.0 removed API.me use API.get_user
That is the replacement for now

Body:
I am trying to run the code from https://github.com/CreepyD246/Twitter-Reply-Bot/blob/main/TwitterReplyBot.py on Replit.

#Importing modules/libraries
import tweepy
import time
import os

# Initialization code
auth = tweepy.OAuthHandler(os.getenv("key2"),os.getenv("skey2"))
auth.set_access_token(os.getenv("token2"),os.getenv("stoken2"))
api = tweepy.API(auth)

# Some important variables which will be used later
bot_id = int(api.me().id_str)
#Other things after

But I get this error:

Traceback (most recent call last):
File "main.py", line 12, in <module>
bot_id = int(api.me().id_str)
AttributeError: 'API' object has no attribute 'me'

I don't find anything in the Tweepy's documentation about API.me() so what's wrong?
The Tweepy version is 4.1.0.


问:
how to Use Metafiled in Jquery like using .html({{current_variant.metafields.my_fields.pack_size_m2_}}); but not working
Hi there i want to know how to embbed Shopify Metafield in Jquery
like in want to do this

```<code>$(selectors.vareintMeta, this.$container)
.html("{{variant.metafields.my_fields.pack_size_m2_}}");
</code>```

Its Printing {{variant.metafields.my_fields.pack_size_m2_}}

but it should print values in this metafield like 20 or 30 or so on

答: Your file needs to be .liquid to be able to use liquid code.</p>

Body:
Hi there i want to know how to embbed Shopify Metafield in Jquery
like in want to do this

$(selectors.vareintMeta, this.$container)
.html("{{variant.metafields.my_fields.pack_size_m2_}}");

Its Printing {{variant.metafields.my_fields.pack_size_m2_}}

but it should print values in this metafield like 20 or 30 or so on


问:
tokio::net::TcpStream how to handle any kind of errors?
I stuck with proper handling panics in case of tokio::net::TcpStream

```<code>use tokio::*;
use tokio::{net::{ TcpStream }, io::AsyncWriteExt};

#[tokio::main]
async fn main() {
    let mut stream = TcpStream::connect("10.20.30.40:6142").await.unwrap();
    println!("created stream");

    let result = stream.write(b"hello world\n").await;
    println!("wrote to stream; success={:?}", result.is_ok());
}
</code>```

or in playground

Can guru teach me how to catch these errors like

thread 'main' panicked at 'called Result::unwrap() on an Err
value: Os { code: 101, kind: NetworkUnreachable, message: "Network is
unreachable" }', src/main.rs:6:67

答:
You'll want to change main() to handle errors, and use the ? operator instead of unwrap() to propagate them.

```<code>type SomeResult<T> = Result<T, Box<dyn std::error::Error>>;

#[tokio::main]
async fn main() -> SomeResult<()> {
    let mut stream = TcpStream::connect("10.20.30.40:6142").await?;
    println!("created stream");

    let result = stream.write(b"hello world\n").await;
    println!("wrote to stream; success={:?}", result.is_ok());

    Ok(())
}
</code>```

The last line (Ok(())) is because main() now expects a result returned. I also added an alias so you can reuse the SomeResult for other functions from which you might want to propagate errors. Here is a playground.

Body:
I stuck with proper handling panics in case of tokio::net::TcpStream

use tokio::*;
use tokio::{net::{ TcpStream }, io::AsyncWriteExt};

#[tokio::main]
async fn main() {
    let mut stream = TcpStream::connect("10.20.30.40:6142").await.unwrap();
    println!("created stream");

    let result = stream.write(b"hello world\n").await;
    println!("wrote to stream; success={:?}", result.is_ok());
}

or in playground

Can guru teach me how to catch these errors like

thread 'main' panicked at 'called Result::unwrap() on an Err
value: Os { code: 101, kind: NetworkUnreachable, message: "Network is
unreachable" }', src/main.rs:6:67

Body:
You'll want to change main() to handle errors, and use the ? operator instead of unwrap() to propagate them.

type SomeResult<T> = Result<T, Box<dyn std::error::Error>>;

#[tokio::main]
async fn main() -> SomeResult<()> {
    let mut stream = TcpStream::connect("10.20.30.40:6142").await?;
    println!("created stream");

    let result = stream.write(b"hello world\n").await;
    println!("wrote to stream; success={:?}", result.is_ok());

    Ok(())
}

The last line (Ok(())) is because main() now expects a result returned. I also added an alias so you can reuse the SomeResult for other functions from which you might want to propagate errors. Here is a playground.


问:
Typescript Inferring parameter types from function records
I have a object fn with name:function pairs that can take arbitrary parameters. I want to be able to map these functions in order to wrap them with another default function to handle errors in a single location. I have the following code which doesn't even compile giving A spread argument must either have a tuple type or be passed to a rest parameter. on fn[f](...args)

```<code>const fn = {
    ...userActions,
    ...companyActions,
    ...dataActions
};

type A<T extends Array<any>, U> = Record<keyof typeof fn, (...args: T) => Promise<U>>;

function map<T extends Array<any>, U>(f: keyof A<T, U>, ...args: T) {
    fn[f](...args);
}
</code>```

I can wrap functions using the code below but it requires importing the relevant function into the caller file and passing it into fn parameter

```<code>async function run<T extends Array<any>, U>(fn: (...args: T) => Promise<U>, ...temp: Parameters<typeof fn>) {
    await fn(...temp); // works but needs to pass the function itself.
}
</code>```

Is there a way to get around the issue on first piece of code? Basically I want to infer the parameter type by using just the key from a record.

答:
I think your mistake is, you didn't specify the type of the fn object, so the typescript couldn't understand whatever you want from him.

As a test I have specified the type the following way:

const fn: { [key: string]: (...args: any[]) => any } = {
    ...userActions,
    ...companyActions,
    ...dataActions
};
```

This way you letting the typescript to know that any of the fn properties can take a certain amount of parameters.

And now it compiles and works when I call the map function!

Body:
I have a object fn with name:function pairs that can take arbitrary parameters. I want to be able to map these functions in order to wrap them with another default function to handle errors in a single location. I have the following code which doesn't even compile giving A spread argument must either have a tuple type or be passed to a rest parameter. on fn[f](...args)

const fn = {
    ...userActions,
    ...companyActions,
    ...dataActions
};

type A<T extends Array<any>, U> = Record<keyof typeof fn, (...args: T) => Promise>;

function map<T extends Array<any>, U>(f: keyof A<T, U>, ...args: T) {
    fn[f](...args);
}

I can wrap functions using the code below but it requires importing the relevant function into the caller file and passing it into fn parameter

async function run<T extends Array<any>, U>(fn: (...args: T) => Promise, ...temp: Parameters<typeof fn>) {
    await fn(...temp); // works but needs to pass the function itself.
}

Is there a way to get around the issue on first piece of code? Basically I want to infer the parameter type by using just the key from a record.

Body:
I think your mistake is, you didn't specify the type of the fn object, so the typescript couldn't understand whatever you want from him.

As a test I have specified the type the following way:

const fn: { [key: string]: (...args: any[]) => any } = {
    ...userActions,
    ...companyActions,
    ...dataActions
};

This way you letting the typescript to know that any of the fn properties can take a certain amount of parameters.

And now it compiles and works when I call the map function!


问:
How to add two elements of arrays with each others and have a new array with a new shape?
I have the following two numpy arrays 'a' and 'b':

a = np.array([[1, -1], [1, 0], [1, 1]]) with a shape = (3, 2)

b = np.array([[1, 1], [2, 2]]) with shape = (2, 2)

I want to add each element of the 'b' array with each element of the 'a' array so that I have as an output the following 'c' array

c = np.array([[2, 0], [2, 1], [2, 2], [3, 1], [3, 2], [3, 3]])
with a shape = (6, 2)

Is the any function that can do it? Thanks

Body:
An idea is to repeat b for the number of rows of a. And to tile a given the number of rows of b.  This would work for any number of columns or rows, provided both arrays have the same number of columns.

import numpy as np

a = np.array([[1, -1], [1, 0], [1, 1]])
b = np.array([[1, 1], [2, 2]])

c = np.repeat(b, a.shape[0], axis=0) + np.tile(a, (b.shape[0], 1))

A larger example:

a = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
b = np.array([[10, 20, 30], [40, 50, 60], [70, 80, 90], [100, 200, 300]])

c = np.repeat(b, a.shape[0], axis=0) + np.tile(a, (b.shape[0], 1))

gives:

[[11, 22, 33],
 [14, 25, 36],
 [17, 28, 39],
 [41, 52, 63],
 [44, 55, 66],
 [47, 58, 69],
 [71, 82, 93],
 [74, 85, 96],
 [77, 88, 99],
 [101, 202, 303],
 [104, 205, 306],
 [107, 208, 309]]


问:
ReferenceError: localStorage is not defined
I am trying to make User Authentication with Angular and ASP.NET Core.

I am following the tutorial found here:

https://fullstackmark.com/post/10/user-authentication-with-angular-and-asp-net-core

I followed all the steps with no errors.

The app runs, but when I go to "/register" or "/login" routes, I get

```<code>NodeInvocationException: Uncaught (in promise): ReferenceError: localStorage is not defined
ReferenceError: localStorage is not defined
</code>```

the service that uses it is:

```<code>import { Injectable, Inject } from '@angular/core';
import { Http, Response, Headers, RequestOptions } from '@angular/http';

import { UserRegistration } from '../shared/models/user.registration.interface';
import { ConfigService } from '../shared/utils/config.service';

import { BaseService } from "./base.service";

import { Observable } from 'rxjs/Rx';
import { BehaviorSubject } from 'rxjs/Rx';

//import * as _ from 'lodash';

// Add the RxJS Observable operators we need in this app.
import '../rxjs-operators';

@Injectable()
export class UserService extends BaseService {

  baseUrl: string = '';

  // Observable navItem source
  private _authNavStatusSource = new BehaviorSubject<boolean>(false);
  // Observable navItem stream
  authNavStatus$ = this._authNavStatusSource.asObservable();

  private loggedIn = false;

  constructor(private http: Http, private configService: ConfigService) {
    super();
    this.loggedIn = !!localStorage.getItem('auth_token');
    // ?? not sure if this the best way to broadcast the status but seems to resolve issue on page refresh where auth status is lost in
    // header component resulting in authed user nav links disappearing despite the fact user is still logged in
    this._authNavStatusSource.next(this.loggedIn);
    this.baseUrl = configService.getApiURI();
  }

    register(email: string, password: string, firstName: string, lastName: string,location: string): Observable<UserRegistration> {
    let body = JSON.stringify({ email, password, firstName, lastName,location });
    let headers = new Headers({ 'Content-Type': 'application/json' });
    let options = new RequestOptions({ headers: headers });

    return this.http.post(this.baseUrl + "/accounts", body, options)
      .map(res => true)
      .catch(this.handleError);
  }

   login(userName: any, password: any) {
    let headers = new Headers();
    headers.append('Content-Type', 'application/json');

    return this.http
      .post(
      this.baseUrl + '/login',
      JSON.stringify({ userName, password }),{ headers }
      )
      .map(res => res.json())
      .map(res => {
        localStorage.setItem('auth_token', res.auth_token);
        this.loggedIn = true;
        this._authNavStatusSource.next(true);
        return true;
      })
      .catch(this.handleError);
  }

  logout() {
    localStorage.removeItem('auth_token');
    this.loggedIn = false;
    this._authNavStatusSource.next(false);
  }

  isLoggedIn() {
    return this.loggedIn;
  }
}
</code>```

the register ts is:

```<code>import { Component, OnInit, Inject } from '@angular/core';
import { Router } from '@angular/router';

import { UserRegistration } from '../../shared/models/user.registration.interface';
import { UserService } from "../../services/user.service";

declare var localStorage: any;

@Component({
  selector: 'app-registration-form',
  templateUrl: './registration-form.component.html'
})
export class RegistrationFormComponent implements OnInit {

 errors: string;
 isRequesting: boolean;
 submitted: boolean = false;

 constructor(private userService: UserService, private router: Router) {

 }

  ngOnInit() {

  }

  registerUser({ value, valid }: { value: UserRegistration, valid: boolean }) {
     this.submitted = true;
     this.isRequesting = true;
     this.errors='';
     if(valid)
     {
         this.userService.register(value.email,value.password,value.firstName,value.lastName,value.location)
                   .finally(() => this.isRequesting = false)
                   .subscribe(
                     result  => {if(result){
                         this.router.navigate(['/login'],{queryParams: {brandNew: true,email:value.email}});
                     }},
                     errors =>  this.errors = errors);
     }
  }
}
</code>```

the login is:

```<code>import { Subscription } from 'rxjs';
import { Component, OnInit,OnDestroy } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';

import { Credentials } from '../../shared/models/credentials.interface';
import { UserService } from '../../services/user.service';

@Component({
  selector: 'app-login-form',
  templateUrl: './login-form.component.html'
})
export class LoginFormComponent implements OnInit, OnDestroy {

  private subscription: Subscription;

  brandNew: boolean;
  errors: string;
  isRequesting: boolean;
  submitted: boolean = false;
  credentials: Credentials = { email: '', password: '' };

  constructor(private userService: UserService, private router: Router,private activatedRoute: ActivatedRoute) { }

    ngOnInit() {

    // subscribe to router event
    this.subscription = this.activatedRoute.queryParams.subscribe(
      (param: any) => {
         this.brandNew = param['brandNew'];
         this.credentials.email = param['email'];
      });
  }

   ngOnDestroy() {
    // prevent memory leak by unsubscribing
    this.subscription.unsubscribe();
  }

  login({ value, valid }: { value: Credentials, valid: boolean }) {
    this.submitted = true;
    this.isRequesting = true;
    this.errors='';
    if (valid) {
      this.userService.login(value.email, value.password)
        .finally(() => this.isRequesting = false)
        .subscribe(
        result => {
          if (result) {
             this.router.navigate(['/home']);
          }
        },
        error => this.errors = error);
    }
  }
}
</code>```

I tried the solution from:

localStorage is not defined (Angular Universal)

but it does not work...

What am I missing

答:
You are probably getting this error because the component is looking for localStorage when rendering server side, which is why it cannot be found and you are getting this error message.

I had a similar problem in React and solved it by simply importing the component dynamically, disabling SSR. Even just disabling SSR should be fine, you can choose whether to do this on import or export.

Hope this solves your problem

Body:
I am trying to make User Authentication with Angular and ASP.NET Core.

I am following the tutorial found here:

https://fullstackmark.com/post/10/user-authentication-with-angular-and-asp-net-core

I followed all the steps with no errors.

The app runs, but when I go to "/register" or "/login" routes, I get

NodeInvocationException: Uncaught (in promise): ReferenceError: localStorage is not defined
ReferenceError: localStorage is not defined

the service that uses it is:

import { Injectable, Inject } from '@angular/core';
import { Http, Response, Headers, RequestOptions } from '@angular/http';

import { UserRegistration } from '../shared/models/user.registration.interface';
import { ConfigService } from '../shared/utils/config.service';

import { BaseService } from "./base.service";

import { Observable } from 'rxjs/Rx';
import { BehaviorSubject } from 'rxjs/Rx';

//import * as _ from 'lodash';

// Add the RxJS Observable operators we need in this app.
import '../rxjs-operators';

@Injectable()
export class UserService extends BaseService {

  baseUrl: string = '';

  // Observable navItem source
  private _authNavStatusSource = new BehaviorSubject<boolean>(false);
  // Observable navItem stream
  authNavStatus$ = this._authNavStatusSource.asObservable();

  private loggedIn = false;

  constructor(private http: Http, private configService: ConfigService) {
    super();
    this.loggedIn = !!localStorage.getItem('auth_token');
    // ?? not sure if this the best way to broadcast the status but seems to resolve issue on page refresh where auth status is lost in
    // header component resulting in authed user nav links disappearing despite the fact user is still logged in
    this._authNavStatusSource.next(this.loggedIn);
    this.baseUrl = configService.getApiURI();
  }

    register(email: string, password: string, firstName: string, lastName: string,location: string): Observable<UserRegistration> {
    let body = JSON.stringify({ email, password, firstName, lastName,location });
    let headers = new Headers({ 'Content-Type': 'application/json' });
    let options = new RequestOptions({ headers: headers });

    return this.http.post(this.baseUrl + "/accounts", body, options)
      .map(res => true)
      .catch(this.handleError);
  }

   login(userName: any, password: any) {
    let headers = new Headers();
    headers.append('Content-Type', 'application/json');

    return this.http
      .post(
      this.baseUrl + '/login',
      JSON.stringify({ userName, password }),{ headers }
      )
      .map(res => res.json())
      .map(res => {
        localStorage.setItem('auth_token', res.auth_token);
        this.loggedIn = true;
        this._authNavStatusSource.next(true);
        return true;
      })
      .catch(this.handleError);
  }

  logout() {
    localStorage.removeItem('auth_token');
    this.loggedIn = false;
    this._authNavStatusSource.next(false);
  }

  isLoggedIn() {
    return this.loggedIn;
  }
}

the register ts is:

import { Component, OnInit, Inject } from '@angular/core';
import { Router } from '@angular/router';

import { UserRegistration } from '../../shared/models/user.registration.interface';
import { UserService } from "../../services/user.service";

declare var localStorage: any;

@Component({
  selector: 'app-registration-form',
  templateUrl: './registration-form.component.html'
})
export class RegistrationFormComponent implements OnInit {

 errors: string;
 isRequesting: boolean;
 submitted: boolean = false;

 constructor(private userService: UserService, private router: Router) {

 }

  ngOnInit() {

  }

  registerUser({ value, valid }: { value: UserRegistration, valid: boolean }) {
     this.submitted = true;
     this.isRequesting = true;
     this.errors='';
     if(valid)
     {
         this.userService.register(value.email,value.password,value.firstName,value.lastName,value.location)
                   .finally(() => this.isRequesting = false)
                   .subscribe(
                     result  => {if(result){
                         this.router.navigate(['/login'],{queryParams: {brandNew: true,email:value.email}});
                     }},
                     errors =>  this.errors = errors);
     }
  }
}

the login is:

import { Subscription } from 'rxjs';
import { Component, OnInit,OnDestroy } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';

import { Credentials } from '../../shared/models/credentials.interface';
import { UserService } from '../../services/user.service';

@Component({
  selector: 'app-login-form',
  templateUrl: './login-form.component.html'
})
export class LoginFormComponent implements OnInit, OnDestroy {

  private subscription: Subscription;

  brandNew: boolean;
  errors: string;
  isRequesting: boolean;
  submitted: boolean = false;
  credentials: Credentials = { email: '', password: '' };

  constructor(private userService: UserService, private router: Router,private activatedRoute: ActivatedRoute) { }

    ngOnInit() {

    // subscribe to router event
    this.subscription = this.activatedRoute.queryParams.subscribe(
      (param: any) => {
         this.brandNew = param['brandNew'];
         this.credentials.email = param['email'];
      });
  }

   ngOnDestroy() {
    // prevent memory leak by unsubscribing
    this.subscription.unsubscribe();
  }

  login({ value, valid }: { value: Credentials, valid: boolean }) {
    this.submitted = true;
    this.isRequesting = true;
    this.errors='';
    if (valid) {
      this.userService.login(value.email, value.password)
        .finally(() => this.isRequesting = false)
        .subscribe(
        result => {
          if (result) {
             this.router.navigate(['/home']);
          }
        },
        error => this.errors = error);
    }
  }
}

I tried the solution from:

localStorage is not defined (Angular Universal)

but it does not work...

What am I missing