问:
How to get the values from inside the code when exception occurs?
I have a worker service in .net core 3.1
in my Program.cs i have the below codes

```<code>   public static void Main(string[] args)
    {
        try
        {
            CreateHostBuilder(args).Build().Run();
        }
        catch(Exception ex)
        {
            Handler(ex);
        }

    }

 static void Handler( Exception e)
    {
        var logger = NLogBuilder.ConfigureNLog("nlog.config").GetCurrentClassLogger();
        List<Test> _Test = new List<Test>()
        {
            new Test()
            {

            }
        };
        LogEventInfo eventInfo = new LogEventInfo
        {
            Level = LogLevel.Error,
            Properties = { { "Application",_Test } }
        };
        logger.Log(eventInfo);
    }

private class Test
{
 public string Name{get;set;}
 public string Place{get;set;}
}
</code>```

In my worker class i have code as below

```<code>public class Worker : BackgroundService
{

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {

        do
        {

           string Name  ="MyName";// These values will be fetched from different file
           string Place="MyPlace";
        //Some Logic where an exception may occur
        }
        while (!stoppingToken.IsCancellationRequested);

    }
}
</code>```

Is there anyway to get the values of Name and Place of worker class to Handler method in program class when an exception arises. Since I'm thinking of a global exception handler I'm thinking of not putting any more try catch blocks. I want to handle all the exception with the try catch in the program.cs file. How can i get the Name and Place values onto my handler on such scenario so that it can be logged?

答:
Create a custom Exception class where you can set Name & Place as properties.
In the Worker, add a try catch block around the code that may throw an exception. Create and throw your custom exception, setting the original exception as the InnerException (https://learn.microsoft.com/en-us/dotnet/api/system.exception.innerexception?view=net-6.0)

Then in your handler get the name / place from the wrapper exception, and then use the InnerException for the rest.

Body:
I have a worker service in .net core 3.1
in my Program.cs i have the below codes

   public static void Main(string[] args)
    {
        try
        {
            CreateHostBuilder(args).Build().Run();
        }
        catch(Exception ex)
        {
            Handler(ex);
        }

    }

 static void Handler( Exception e)
    {
        var logger = NLogBuilder.ConfigureNLog("nlog.config").GetCurrentClassLogger();
        List<Test> _Test = new List<Test>()
        {
            new Test()
            {

            }
        };
        LogEventInfo eventInfo = new LogEventInfo
        {
            Level = LogLevel.Error,
            Properties = { { "Application",_Test } }
        };
        logger.Log(eventInfo);
    }

private class Test
{
 public string Name{get;set;}
 public string Place{get;set;}
}

In my worker class i have code as below

public class Worker : BackgroundService
{

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {

        do
        {

           string Name  ="MyName";// These values will be fetched from different file
           string Place="MyPlace";
        //Some Logic where an exception may occur
        }
        while (!stoppingToken.IsCancellationRequested);

    }
}

Is there anyway to get the values of Name and Place of worker class to Handler method in program class when an exception arises. Since I'm thinking of a global exception handler I'm thinking of not putting any more try catch blocks. I want to handle all the exception with the try catch in the program.cs file. How can i get the Name and Place values onto my handler on such scenario so that it can be logged?


来源: stackexchange

问:
Wikidata SPARQL - Duplicate results for spouse start time and end time
I am trying to construct a query to return a list of actors and their spouses while including marriage and divorce dates for each couple. So I would expect to see each actor duplicate with each instance of a new relationship... however when I try and include the start time and end time properties in the query, I am getting duplicate results. I suspect this is because the "name" of the spouses and the is stored in a different wikidata prefix and I'm not grouping them correctly.

Here is a sample query:

```<code>SELECT ?person ?personLabel ?spouse ?spouseLabel ?starttime ?endtime
WHERE
{
  ?person wdt:P106 wd:Q33999, wd:Q2526255, wd:Q28389, wd:Q3282637;
          wdt:P26 ?spouse.
  ?person p:P26 [pq:P580 ?starttime; pq:P582 ?endtime].
  SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
}
ORDER BY ASC(UCASE(str(?personLabel)))
LIMIT 10
</code>```

here is a link to the sparql interactive service so you can see the duped results I'm referring to:
https://query.wikidata.org/#SELECT%20%3Fperson%20%3FpersonLabel%20%3Fspouse%20%3FspouseLabel%20%3Fstarttime%20%3Fendtime%0AWHERE%0A%7B%0A%20%20%3Fperson%20wdt%3AP106%20wd%3AQ33999%2C%20wd%3AQ2526255%2C%20wd%3AQ28389%2C%20wd%3AQ3282637%3B%0A%20%20%20%20%20%20%20%20%20%20wdt%3AP26%20%3Fspouse.%0A%20%20%3Fperson%20p%3AP26%20%5Bpq%3AP580%20%3Fstarttime%3B%20pq%3AP582%20%3Fendtime%5D.%0A%20%20SERVICE%20wikibase%3Alabel%20%7B%20bd%3AserviceParam%20wikibase%3Alanguage%20%22en%22.%20%7D%0A%7D%0AORDER%20BY%20ASC%28UCASE%28str%28%3FpersonLabel%29%29%29%0ALIMIT%2010%0A

screencap of duped results

答:
The problem with your query is that there was no link between the spouse and the statement about their marriage.

So for every actor, you are returning all their spouses, and also all the start/end dates of their marriages, regardless of whether they relate to the specific spouse.

What you need to do is to use the ps: namespace, like so:

```<code>SELECT ?person ?personLabel ?spouse ?spouseLabel ?starttime ?endtime
    WHERE
    {
      ?person wdt:P106 wd:Q33999, wd:Q2526255, wd:Q28389, wd:Q3282637 .
      ?person p:P26 [ ps:P26 ?spouse ; #This is the necessary change.
                      pq:P580 ?starttime;
                      pq:P582 ?endtime ].
      SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
    }
    ORDER BY ASC(?personLabel)
    LIMIT 10
</code>```

In general, the wdt: namespace is for linking entities directly, the p: namespace links an entity to a statement, ps: links a statement to an entity, and pq: tells us something about the statement.

ContentLicense: CC BY-SA 4.0

Body:
I am trying to construct a query to return a list of actors and their spouses while including marriage and divorce dates for each couple. So I would expect to see each actor duplicate with each instance of a new relationship... however when I try and include the start time and end time properties in the query, I am getting duplicate results. I suspect this is because the "name" of the spouses and the is stored in a different wikidata prefix and I'm not grouping them correctly.

Here is a sample query:

SELECT ?person ?personLabel ?spouse ?spouseLabel ?starttime ?endtime
WHERE
{
  ?person wdt:P106 wd:Q33999, wd:Q2526255, wd:Q28389, wd:Q3282637;
          wdt:P26 ?spouse.
  ?person p:P26 [pq:P580 ?starttime; pq:P582 ?endtime].
  SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
}
ORDER BY ASC(UCASE(str(?personLabel)))
LIMIT 10

here is a link to the sparql interactive service so you can see the duped results I'm referring to:
<a href="https://query.wikidata.org/#SELECT%20%3Fperson%20%3FpersonLabel%20%3Fspouse%20%3FspouseLabel%20%3Fstarttime%20%3Fendtime%0AWHERE%0A%7B%0A%20%20%3Fperson%20wdt%3AP106%20wd%3AQ33999%2C%20wd%3AQ2526255%2C%20wd%3AQ28389%2C%20wd%3AQ3282637%3B%0A%20%20%20%20%20%20%20%20%20%20wdt%3AP26%20%3Fspouse.%0A%20%20%3Fperson%20p%3AP26%20%5Bpq%3AP580%20%3Fstarttime%3B%20pq%3AP582%20%3Fendtime%5D.%0A%20%20SERVICE%20wikibase%3Alabel%20%7B%20bd%3AserviceParam%20wikibase%3Alanguage%20%22en%22.%20%7D%0A%7D%0AORDER%20BY%20ASC%28UCASE%28str%28%3FpersonLabel%29%29%29%0ALIMIT%2010%0A" rel="nofollow noreferrer">https://query.wikidata.org/#SELECT%20%3Fperson%20%3FpersonLabel%20%3Fspouse%20%3FspouseLabel%20%3Fstarttime%20%3Fendtime%0AWHERE%0A%7B%0A%20%20%3Fperson%20wdt%3AP106%20wd%3AQ33999%2C%20wd%3AQ2526255%2C%20wd%3AQ28389%2C%20wd%3AQ3282637%3B%0A%20%20%20%20%20%20%20%20%20%20wdt%3AP26%20%3Fspouse.%0A%20%20%3Fperson%20p%3AP26%20%5Bpq%3AP580%20%3Fstarttime%3B%20pq%3AP582%20%3Fendtime%5D.%0A%20%20SERVICE%20wikibase%3Alabel%20%7B%20bd%3AserviceParam%20wikibase%3Alanguage%20%22en%22.%20%7D%0A%7D%0AORDER%20BY%20ASC%28UCASE%28str%28%3FpersonLabel%29%29%29%0ALIMIT%2010%0A

screencap of duped results

Body:
The problem with your query is that there was no link between the spouse and the statement about their marriage.

So for every actor, you are returning all their spouses, and also all the start/end dates of their marriages, regardless of whether they relate to the specific spouse.

What you need to do is to use the ps: namespace, like so:

SELECT ?person ?personLabel ?spouse ?spouseLabel ?starttime ?endtime
    WHERE
    {
      ?person wdt:P106 wd:Q33999, wd:Q2526255, wd:Q28389, wd:Q3282637 .
      ?person p:P26 [ ps:P26 ?spouse ; #This is the necessary change.
                      pq:P580 ?starttime;
                      pq:P582 ?endtime ].
      SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
    }
    ORDER BY ASC(?personLabel)
    LIMIT 10

In general, the wdt: namespace is for linking entities directly, the p: namespace links an entity to a statement, ps: links a statement to an entity, and pq: tells us something about the statement.


问:
XAML Collapsed bullet point list with hyperlink
Need some pointers on XAML styling for a collapsed bullet point list with a hyperlink to display all data items, i.e. show only the first option by default, with some hyperlink text which when clicked, would display the remaining items in the list.
E.g.:

Collapsed List

Option 1

Click me

Expanded List on clicking "Click me"

Option 1

Option 2

Option 3....

答:
Not sure if this is exactly what you're asking for. Generally this is not a "Please write code for me" website

That said, here's some code

It's not terribly difficult to do what you're asking. You just need to create a custom user control. Below is the Xaml and Xaml.cs for a custom user control I made for you

SampleCollapsedList.xaml.cs

```<code>public partial class SampleCollapsedList : UserControl, INotifyPropertyChanged
{
            public bool IsExpanded { get; set; }
            public string FirstItem
            {
                get
                {
                    return ListItems != null && ListItems.Count > 0 ? ListItems?.First() : string.Empty;
                }
            }

            public ObservableCollection<string> ListItems
            {
                get { return (ObservableCollection<string>)GetValue(ListItemsProperty); }
                set { SetValue(ListItemsProperty, value); }
            }

            public static readonly DependencyProperty ListItemsProperty =
                DependencyProperty.Register(nameof(ListItems), typeof(ObservableCollection<string>), typeof(SampleCollapsedList), new PropertyMetadata(null,CollectionUpdated));

            public event PropertyChangedEventHandler PropertyChanged;

            public SampleCollapsedList()
            {
                InitializeComponent();
            }

            private static void CollectionUpdated(DependencyObject d, DependencyPropertyChangedEventArgs e)
            {
                if (d is SampleCollapsedList sampleCollapsedList)
                {
                    sampleCollapsedList.OnPropertyChanged(nameof(FirstItem));
                }
            }

            private void OnHyperlinkClicked(object sender, RoutedEventArgs e)
            {
                IsExpanded = !IsExpanded;
                OnPropertyChanged(nameof(IsExpanded));
            }

            private void OnPropertyChanged(string propName)
            {
                PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propName));
            }
}
</code>```

SampleCollapsedList.xaml

```<code><UserControl x:Class="WpfApp1.SampleCollapsedList"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             xmlns:local="clr-namespace:WpfApp1"
             mc:Ignorable="d"
             d:DesignHeight="450"
             d:DesignWidth="800"
             x:Name="self">

    <UserControl.Resources>
        <local:BoolToVisConverter x:Key="BoolToVisibilityConverter" />
    </UserControl.Resources>
    <Grid Height="250"
          Width="500">
        <StackPanel Orientation="Vertical"
                    Visibility="{Binding Path=IsExpanded, ElementName=self, Converter={StaticResource ResourceKey=BoolToVisibilityConverter}, ConverterParameter=opposite}">
            <TextBlock Text="{Binding Path=FirstItem, ElementName=self}" />
            <TextBlock><Hyperlink Click="OnHyperlinkClicked">Click Me</Hyperlink></TextBlock>
        </StackPanel>
        <ListBox Visibility="{Binding Path=IsExpanded, ElementName=self, Converter={StaticResource ResourceKey=BoolToVisibilityConverter}}"
                 ItemsSource="{Binding Path=ListItems, ElementName=self}"
                 BorderThickness="0">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <TextBlock><Run>- </Run><Run Text="{Binding Path=.}" /></TextBlock>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>
    </Grid>
</UserControl>

</code>```

Also a simple converter to make the hide show magic happen

```<code>using System;
using System.Globalization;
using System.Windows.Data;
using System.Windows;

namespace WpfApp1
{
    public class BoolToVisConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if(parameter is string param && param.ToLower().Contains("opposite"))
            {
                return (bool)value ? Visibility.Collapsed : Visibility.Visible;
            }
            else
            {
                return (bool)value ? Visibility.Visible : Visibility.Collapsed;
            }
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
}

</code>```

Body:
Not sure if this is exactly what you're asking for. Generally this is not a "Please write code for me" website

That said, here's some code

It's not terribly difficult to do what you're asking. You just need to create a custom user control. Below is the Xaml and Xaml.cs for a custom user control I made for you

SampleCollapsedList.xaml.cs

public partial class SampleCollapsedList : UserControl, INotifyPropertyChanged
{
            public bool IsExpanded { get; set; }
            public string FirstItem
            {
                get
                {
                    return ListItems != null && ListItems.Count > 0 ? ListItems?.First() : string.Empty;
                }
            }

            public ObservableCollection<string> ListItems
            {
                get { return (ObservableCollection<string>)GetValue(ListItemsProperty); }
                set { SetValue(ListItemsProperty, value); }
            }

            public static readonly DependencyProperty ListItemsProperty =
                DependencyProperty.Register(nameof(ListItems), typeof(ObservableCollection<string>), typeof(SampleCollapsedList), new PropertyMetadata(null,CollectionUpdated));

            public event PropertyChangedEventHandler PropertyChanged;

            public SampleCollapsedList()
            {
                InitializeComponent();
            }

            private static void CollectionUpdated(DependencyObject d, DependencyPropertyChangedEventArgs e)
            {
                if (d is SampleCollapsedList sampleCollapsedList)
                {
                    sampleCollapsedList.OnPropertyChanged(nameof(FirstItem));
                }
            }

            private void OnHyperlinkClicked(object sender, RoutedEventArgs e)
            {
                IsExpanded = !IsExpanded;
                OnPropertyChanged(nameof(IsExpanded));
            }

            private void OnPropertyChanged(string propName)
            {
                PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propName));
            }
}

SampleCollapsedList.xaml

<UserControl x:Class="WpfApp1.SampleCollapsedList"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             xmlns:local="clr-namespace:WpfApp1"
             mc:Ignorable="d"
             d:DesignHeight="450"
             d:DesignWidth="800"
             x:Name="self">

    <UserControl.Resources>
        <local:BoolToVisConverter x:Key="BoolToVisibilityConverter" />
    </UserControl.Resources>
    <Grid Height="250"
          Width="500">
        <StackPanel Orientation="Vertical"
                    Visibility="{Binding Path=IsExpanded, ElementName=self, Converter={StaticResource ResourceKey=BoolToVisibilityConverter}, ConverterParameter=opposite}">
            <TextBlock Text="{Binding Path=FirstItem, ElementName=self}" />
            <TextBlock><Hyperlink Click="OnHyperlinkClicked">Click Me</Hyperlink></TextBlock>
        </StackPanel>
        <ListBox Visibility="{Binding Path=IsExpanded, ElementName=self, Converter={StaticResource ResourceKey=BoolToVisibilityConverter}}"
                 ItemsSource="{Binding Path=ListItems, ElementName=self}"
                 BorderThickness="0">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <TextBlock><Run>- </Run><Run Text="{Binding Path=.}" /></TextBlock>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>
    </Grid>
</UserControl>

Also a simple converter to make the hide show magic happen

using System;
using System.Globalization;
using System.Windows.Data;
using System.Windows;

namespace WpfApp1
{
    public class BoolToVisConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if(parameter is string param && param.ToLower().Contains("opposite"))
            {
                return (bool)value ? Visibility.Collapsed : Visibility.Visible;
            }
            else
            {
                return (bool)value ? Visibility.Visible : Visibility.Collapsed;
            }
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
}


问:
Core Data With NSData Attribute
I am working on a Core Data  based iOS application , in which i stored an array strings in coredata as NSData(binary data).
While  fetching  the data , how can i write  a NSPredicate which will only retrieve the result with  NSData value contain given string .

if name attribute is a string then i can write a predicate like below.

```<code>NSString *inputName = @"bbb";
NSPredicate * predicate = [NSPredicate predicateWithFormat:@"name = %@",inputName];
</code>```

my question is

what will be the predicate if name is NSData and this NSData from

```<code>NSArray *anArray = [NSArray arrayWithObjects:@"aaa",@"bbb",@"ccc",nil];
NSData *arrayData = [NSArchiver archivedDataWithRootObject:anArray];
</code>```

arrayData is stored as name attribute in Core Data .

I hope this information is enough to understand  my problem.
Thanks in advance.

答:
Based on your comments, I think you need to revisit your schema. If you have a one-many relationship between Supervisor & Employee (Many employees can have the same supervisor), you should create an Entity Employee, and add an attribute supervisorID to it. Then you can query your Employee table with something like- where supervisorID="123".

If you cannot redesign your schema, you can convert NSData to NSString & save it in CoreData using -initWithData:encoding:.

HTH,

Akshay

ContentLicense: CC BY-SA 3.0

Title: Core Data With NSData Attribute

Body:
I am working on a Core Data  based iOS application , in which i stored an array strings in coredata as NSData(binary data).
While  fetching  the data , how can i write  a NSPredicate which will only retrieve the result with  NSData value contain given string .

if name attribute is a string then i can write a predicate like below.

NSString *inputName = @"bbb";
NSPredicate * predicate = [NSPredicate predicateWithFormat:@"name = %@",inputName];

my question is

what will be the predicate if name is NSData and this NSData from

NSArray *anArray = [NSArray arrayWithObjects:@"aaa",@"bbb",@"ccc",nil];
NSData *arrayData = [NSArchiver archivedDataWithRootObject:anArray];

arrayData is stored as name attribute in Core Data .

I hope this information is enough to understand  my problem.
Thanks in advance.


问:
how to fix npm audit error with loadVirtual and ENOLOCK?
```<code>➜   npm audit
npm ERR! code ENOLOCK
npm ERR! audit This command requires an existing lockfile.
npm ERR! audit Try creating one first with: npm i --package-lock-only
npm ERR! audit Original error: loadVirtual requires existing shrinkwrap file
</code>```

I ran npm audit and got this error.

When I run below:

```<code>➜ npm config get package-lock
true

➜ npm config get shrinkwrap
true
</code>```

Can anybody help with this? as to how to fix it? and npm audit fix --force is not working as well...

答:
I read this and really helpful:

https://medium.com/illumination/how-to-fix-npm-audit-error-with-loadvirtual-and-enolock-deprecated-dependencies-1f07ba65eef9

```<code>npm i --package-lock-only
npm config get package-lock
npm config get shrinkwrap
npm i --package-lock-only
npm audit fix
</code>```

(When running ‘npm config get package-lock’ and ‘npm config get shrinkwrap’, you will receive ‘true’ for both)
— → After running ‘npm audit fix’, you will see: “up to date, audited… found 0 vulnerabilities”

Body:
➜   npm audit
npm ERR! code ENOLOCK
npm ERR! audit This command requires an existing lockfile.
npm ERR! audit Try creating one first with: npm i --package-lock-only
npm ERR! audit Original error: loadVirtual requires existing shrinkwrap file

I ran npm audit and got this error.

When I run below:

➜ npm config get package-lock
true

➜ npm config get shrinkwrap
true

Can anybody help with this? as to how to fix it? and npm audit fix --force is not working as well...

Body:
I read this and really helpful:

https://medium.com/illumination/how-to-fix-npm-audit-error-with-loadvirtual-and-enolock-deprecated-dependencies-1f07ba65eef9

npm i --package-lock-only
npm config get package-lock
npm config get shrinkwrap
npm i --package-lock-only
npm audit fix

(When running ‘npm config get package-lock’ and ‘npm config get shrinkwrap’, you will receive ‘true’ for both)
— → After running ‘npm audit fix’, you will see: “up to date, audited… found 0 vulnerabilities”


问:
Parsing XML: How can I get all the information from lines with same name but different text in XML file using Python?
I'm trying to parse an ICD10 XML file and I'm having some trouble extracting information.

```<code><diag>
<name>A00</name>
<desc>Cholera</desc>
<diag>
  <name>A00.0</name>
  <desc>Cholera due to Vibrio cholerae 01, biovar cholerae</desc>
  <inclusionTerm>
    <note>Classical cholera</note>
    <note>Classical cholera again</note>
  </inclusionTerm>
</diag>
<diag>
  <name>A00.1</name>
  <desc>Cholera due to Vibrio cholerae 01, biovar eltor</desc>
  <inclusionTerm>
    <note>Cholera eltor</note>
  </inclusionTerm>
</diag>
<diag>
  <name>A00.9</name>
  <desc>Cholera, unspecified</desc>
</diag>
</diag>
</code>```

Using this:

```<code>from xml.etree import ElementTree as ET
root = ET.parse('cut.xml')
diag = root.find(".//*[name='A00.0']")
inclusionTerm = diag.find('inclusionTerm')
if inclusionTerm is not None:
    print('Inclusion Term: '+diag.find('inclusionTerm').find('note').text)
</code>```

the code only prints the first note inside the "inclusion Term" from A00.0 ID. How can I write the code to get all of the 'notes' inside the 'inclusionTerm'?

答:
An XPath expression could be written to access all note elements:

```<code>from xml.etree import ElementTree as ET

xml = '''<diag>
<name>A00</name>
<desc>Cholera</desc>
<diag>
  <name>A00.0</name>
  <desc>Cholera due to Vibrio cholerae 01, biovar cholerae</desc>
  <inclusionTerm>
    <note>Classical cholera</note>
    <note>Classical cholera again</note>
  </inclusionTerm>
</diag>
<diag>
  <name>A00.1</name>
  <desc>Cholera due to Vibrio cholerae 01, biovar eltor</desc>
  <inclusionTerm>
    <note>Cholera eltor</note>
  </inclusionTerm>
</diag>
<diag>
  <name>A00.9</name>
  <desc>Cholera, unspecified</desc>
</diag>
</diag>'''

root = ET.fromstring(xml)

notes = root.findall('.//diag[name="A00.0"]/inclusionTerm/note')

for note in notes:
  print(note.text)
</code>```

Body:
I'm trying to parse an ICD10 XML file and I'm having some trouble extracting information.

<diag>
<name>A00</name>
<desc>Cholera</desc>
<diag>
  <name>A00.0</name>
  <desc>Cholera due to Vibrio cholerae 01, biovar cholerae</desc>
  <inclusionTerm>
    <note>Classical cholera</note>
    <note>Classical cholera again</note>
  </inclusionTerm>
</diag>
<diag>
  <name>A00.1</name>
  <desc>Cholera due to Vibrio cholerae 01, biovar eltor</desc>
  <inclusionTerm>
    <note>Cholera eltor</note>
  </inclusionTerm>
</diag>
<diag>
  <name>A00.9</name>
  <desc>Cholera, unspecified</desc>
</diag>
</diag>

Using this:

from xml.etree import ElementTree as ET
root = ET.parse('cut.xml')
diag = root.find(".//*[name='A00.0']")
inclusionTerm = diag.find('inclusionTerm')
if inclusionTerm is not None:
    print('Inclusion Term: '+diag.find('inclusionTerm').find('note').text)

the code only prints the first note inside the "inclusion Term" from A00.0 ID. How can I write the code to get all of the 'notes' inside the 'inclusionTerm'?

Body:
An XPath expression could be written to access all note elements:

from xml.etree import ElementTree as ET

xml = '''<diag>
<name>A00</name>
<desc>Cholera</desc>
<diag>
  <name>A00.0</name>
  <desc>Cholera due to Vibrio cholerae 01, biovar cholerae</desc>
  <inclusionTerm>
    <note>Classical cholera</note>
    <note>Classical cholera again</note>
  </inclusionTerm>
</diag>
<diag>
  <name>A00.1</name>
  <desc>Cholera due to Vibrio cholerae 01, biovar eltor</desc>
  <inclusionTerm>
    <note>Cholera eltor</note>
  </inclusionTerm>
</diag>
<diag>
  <name>A00.9</name>
  <desc>Cholera, unspecified</desc>
</diag>
</diag>'''

root = ET.fromstring(xml)

notes = root.findall('.//diag[name="A00.0"]/inclusionTerm/note')

for note in notes:
  print(note.text)


问:
Error in my code: Syntax error: Expected ")" or "," but got "("
<pre class="lang-sql prettyprint-override"><code>$ CREATE TABLE `2021.dates_times` (
    ride_id STRING NOT NULL,
    start_hour TIME NOT NULL,
    start_day INT NOT NULL,
    start_month INT NOT NULL,
    end_hour TIME NOT NULL,
    end_day INT NOT NULL,
    end_month INT NOT NULL

    PRIMARY KEY (ride_id)
)$
</code>```

答:
You have left a comma before primary key.Your code should be

CREATE TABLE 2021.dates_times (  ride_id STRING NOT NULL,  start_hour TIME NOT NULL,  start_day INT NOT NULL,  start_month INT NOT NULL,  end_hour TIME NOT NULL,  end_day INT NOT NULL,  end_month INT NOT NULL, PRIMARY KEY (ride_id) )


问:
How to extract the lines between patterns?
I have a file with format like :

```<code>[PATTERN]
line1
line2
line3
.
.
.
line
[PATTERN]
line1
line2
line3
.
.
.
line
[PATTERN]
line1
line2
line3
.
.
.
line
</code>```

I want to extract the following blocks from above file :

```<code>[PATTERN]
line1
line2
line3
.
.
.
line
</code>```

Note: Number of lines between 2 [PATTERN] may varies, so can't rely on number of lines.

Basically, I want to store each pattern and the lines following it to Database, so I wil have to iterate all such blocks in my file.

How do this with Shell Scripting ?

答:
This can be for sure improved, but if you want to store lines in an array here is something I did in past:

```<code>#!/bin/bash
file=$1
gp_cnt=-1
i=-1

while read line
do
  # Match pattern
  if [[ "$line" == "[PATTERN]" ]]; then
    let "gp_cnt +=1"
    # If this is not the first match process group
    if [[ $gp_cnt -gt 0 ]]; then
      # Process the group
      echo "Processing group #`expr $gp_cnt - 1`"
      echo ${parsed[*]}
    fi
    # Start new group
    echo "Pattern #$gp_cnt catched"
    i=0
    unset parsed
    parsed[$i]="$line"

    # Other lines (lines before first pattern are not processed)
  elif [[ $gp_cnt != -1 ]]; then
    let "i +=1"
    parsed[$i]="$line"
  fi
done < <(cat $file)

# Process last group
echo "Processing group #$gp_cnt"
echo ${parsed[*]}
</code>```

I don't like the processing of the last group out of the loop...

Body:
I have a file with format like :

[PATTERN]
line1
line2
line3
.
.
.
line
[PATTERN]
line1
line2
line3
.
.
.
line
[PATTERN]
line1
line2
line3
.
.
.
line

I want to extract the following blocks from above file :

[PATTERN]
line1
line2
line3
.
.
.
line

Note: Number of lines between 2 [PATTERN] may varies, so can't rely on number of lines.

Basically, I want to store each pattern and the lines following it to Database, so I wil have to iterate all such blocks in my file.

How do this with Shell Scripting ?

Body:
This can be for sure improved, but if you want to store lines in an array here is something I did in past:

#!/bin/bash
file=$1
gp_cnt=-1
i=-1

while read line
do
  # Match pattern
  if [[ "$line" == "[PATTERN]" ]]; then
    let "gp_cnt +=1"
    # If this is not the first match process group
    if [[ $gp_cnt -gt 0 ]]; then
      # Process the group
      echo "Processing group #`expr $gp_cnt - 1`"
      echo ${parsed[*]}
    fi
    # Start new group
    echo "Pattern #$gp_cnt catched"
    i=0
    unset parsed
    parsed[$i]="$line"

    # Other lines (lines before first pattern are not processed)
  elif [[ $gp_cnt != -1 ]]; then
    let "i +=1"
    parsed[$i]="$line"
  fi
done < <(cat $file)

# Process last group
echo "Processing group #$gp_cnt"
echo ${parsed[*]}

I don't like the processing of the last group out of the loop...


问:
stdout log files are empty in azure web service
I have created an azure web service app used for testing purposes and run into a .Net / http issue (500.30). Ive looked into a lot of troubleshooting but nothing has worked or pointed me in the right direction.

It seems to get more info on the issue, I can use the stdout logs in the Azure app service through Kudu. This has been configured this and the files it creates are blank? Has anyone encountered this before?

What have I did, I set it up in the web.config file setting the stdlog to true but this creates the files with no info. I then removed the inprocess=hosting section as I read this fixed it for others but no joy.

Any pointers in the right direction would be appreciated

答:
You need to enable application logging first.

Click on the App Service logs menu

In Application logging, select File System

In Quota (MB), specify the disk quota for the application logs. In Retention Period (Days), set the number of days the logs should be retained.

Save

You can stream the logs from the portal or by using the CLI

```<code>az webapp log tail --name appname --resource-group myResourceGroup
</code>```

Body:
You need to enable application logging first.

Click on the App Service logs menu

In Application logging, select File System

In Quota (MB), specify the disk quota for the application logs. In Retention Period (Days), set the number of days the logs should be retained.

Save

You can stream the logs from the portal or by using the CLI

az webapp log tail --name appname --resource-group myResourceGroup


问:
Installing a local module using npm?
I have a downloaded module repo, I want to install it locally, not globally in another directory?

What is an easy way to do this?

答:
For more recent versions of npm (I'm using 8.1.3 under macOS Big Sur), the sequence of commands is even easier...

cd /path-where-your-local-project-is/
npm init
```
<p>This will ask you for some data related to your project and properly initialises your <code>project.json</code> file.</p>
<p>Once that is done, you can install additional modules with:</p>
<pre class="lang-sh prettyprint-override"><code>cd /path-where-your-local-project-is/
npm install --save-dev some-npm-module .
</code>```

That's all you need!

Note: I believe that the trailing dot is not necessary if you're inside the project directory, but I also think that it doesn't hurt to add it :-)

(I wonder why the official docs still don't explain this...)

Title: Installing a local module using npm?

Body:
For more recent versions of npm (I'm using 8.1.3 under macOS Big Sur), the sequence of commands is even easier...

cd /path-where-your-local-project-is/
npm init

This will ask you for some data related to your project and properly initialises your project.json file.

Once that is done, you can install additional modules with:

cd /path-where-your-local-project-is/
npm install --save-dev some-npm-module .

That's all you need!

Note: I believe that the trailing dot is not necessary if you're inside the project directory, but I also think that it doesn't hurt to add it :-)

(I wonder why the official docs still don't explain this...)


问:
How can I build a Go Library and use it in Flutter?
I'm currently trying to use Azure Authentication within my Flutter app. I've searched and have not found an existing library that supports MSAL/AAD for Flutter on Windows.

If I use the MSAL package within Visual Studio for a WPF app, the authentication works fine, so the app within Azure is set up correctly. I think I need to use the legitimate client tooling that Microsoft provides in order to get my tokens and such.

Unfortunately, Flutter doesn't provide any integration with .NET, so I can't write a platform-specific integration in .NET and then the rest of my app in Flutter, so that's a shame. But it seems like Flutter can reference a standard C library.

It also seems like Microsoft makes a client for Go, and Go can compile to a C Shared library. So, in my mind, I should be able to compile this library to a C Shared library, and then write up my platform specific implementation in Flutter. In my attempts to build the MSAL GO library so far, it seems like because the MSAL GO library (https://github.com/AzureAD/microsoft-authentication-library-for-go) lacks a main method, and is more to be used as a plugin, so it can't be built directly into a c-shared library by Go.

How can I build the Microsoft MSAL library as a c-shared library? Please note, I am hilariously new to Go.

答:
This does not answer your question directly, but it has been done without any plugin or native development, as far as I understand:

https://blog.objektkultur.de/azure-ad-authentication-flutter-apps/

I also looked up available libraries for AzureAD, and besides the Go library there seem to be versions for Java and ObjectiveC, which you could use to develop your own integration using Flutter platform channels for example.

If you really want to use Go from within Dart / Flutter, I would try to compile the Go code to web assembly and use something like:

https://pub.dev/packages/wasm

No guarantee, this leads in the right direction, though.


问:
BigQuery / Count the number of rows until a specific row is reached
I have data in BigQuery.

I want to count the number of 'pending' events before their 'approved' event per ID.

How would I get the value for every individual ID?

Table events

```<code>id  event
1   pending
1   pending
1   pending
1   approved
2   pending
1   pending
1   pending
1   approved
2   approved
</code>```

In this example the right result is

```<code>id  count_events
1   3
1   2
2   1
</code>```

答:
Consider below approach

```<code>select id, countif(not flag) count_events
from (
  select *, countif(flag) over(partition by id order by ts desc) grp
  from (
    select *,
      if(lag(event) over(partition by id order by ts) = 'pending' and event = 'approved', true, false) flag
    from your_table
  )
)
group by id, grp
order by max(ts)
</code>```

if applied to sample data in your question - output is

Note use of ts - you must have some column in your table that defines order of events - usually it is timestamp , but can be date, or just sequential number etc.

Body:
I have data in BigQuery.

I want to count the number of 'pending' events before their 'approved' event per ID.

How would I get the value for every individual ID?

Table events

id  event
1   pending
1   pending
1   pending
1   approved
2   pending
1   pending
1   pending
1   approved
2   approved

In this example the right result is

id  count_events
1   3
1   2
2   1

Body:
Consider below approach

select id, countif(not flag) count_events
from (
  select *, countif(flag) over(partition by id order by ts desc) grp
  from (
    select *,
      if(lag(event) over(partition by id order by ts) = 'pending' and event = 'approved', true, false) flag
    from your_table
  )
)
group by id, grp
order by max(ts)

if applied to sample data in your question - output is

Note use of ts - you must have some column in your table that defines order of events - usually it is timestamp , but can be date, or just sequential number etc.


问:
Dodge geom_points according to specific boxplot group/color
How can I dodge the geom_points into their specific boxplot group (provided by the aesthetic colour)? I have provided the following (simplified) example:

```<code>library(ggplot2)

ggplot(diamonds, aes(x = cut, y = carat, color = color)) +
    geom_boxplot(outlier.shape = NA) +
    geom_point(aes(group = color))
</code>```

Which provides the following plot:

Boxplot with points not in corresponding boxplot

I would like to have have the points aligned to the boxplot color (group) they belong to. How could I achieve this?

答:
To dodge your points and align them with the box plots use position = position_dodge(width = .75) where .75 is the default width by which box plots get dodged:

library(ggplot2)

ggplot(diamonds, aes(x = cut, y = carat, color = color)) +
  geom_boxplot(outlier.shape = NA) +
  geom_point(aes(group = color), position = position_dodge(width = .75))
```

Body:
How can I dodge the geom_points into their specific boxplot group (provided by the aesthetic colour)? I have provided the following (simplified) example:

library(ggplot2)

ggplot(diamonds, aes(x = cut, y = carat, color = color)) +
    geom_boxplot(outlier.shape = NA) +
    geom_point(aes(group = color))

Which provides the following plot:

Boxplot with points not in corresponding boxplot

I would like to have have the points aligned to the boxplot color (group) they belong to. How could I achieve this?


问:
Radius of largest circle which fits the curve in Python
How do I find the radius of the largest circle which fits the following curve, y=sin(x)?

```<code>import matplotlib.pyplot as plt
import numpy as np
x = np.arange(0,1.01*np.pi,0.01)   # start,stop,step
y = np.sin(x)
plt.plot(x,y)
plt.show()
</code>```

答:
You can solve this problem analytically using a basic maths (parametric) equation system. Indeed, the circle can be described by the algebraic expression x² + y² ≤ r². The one of the shape below your curve is 0 ≤ y ≤ sin(x). The definition domain of x is [0,π[ (you can find it analytically or numerically using the Newton's method). Then you search to maximize r.

You can quickly see that the biggest circle will "touch" the abscissa axis as well as the curve. Since a circle can be defined using only 3 points, then you only need to find the 2 that are on the curve but the best solution requires the two point to be in the same position and the circle to be centred in the domain. Tools like Geogebra or Wolfram Alpha are good to easily solve such analytic equation system. Here is an example:

The best solution is r=0.5.

Assuming the curve have a complex definition (possibly not an analytic one), you can solve this problem using optimization methods. For example, you can use scipy.optimize.

Body:
How do I find the radius of the largest circle which fits the following curve, y=sin(x)?

import matplotlib.pyplot as plt
import numpy as np
x = np.arange(0,1.01*np.pi,0.01)   # start,stop,step
y = np.sin(x)
plt.plot(x,y)
plt.show()


问:
Aws S3 to Databricks mount is not working
I have mounted 'mybucket' using mount commands and i could able to list all the objects using the below command-

```<code>%fs
ls /mnt/mybucket/
</code>```

however, i have folders inside the folders in 'mybucket' and i want to run the below command but it is not working.

```<code>%fs
ls /mnt/mybucket/*/*/
</code>```

Any help is much appreciated. Thanks

答:
Unmount and mount again.</p>
```<code>dbutils.fs.unmount("/mnt/mount_name")

dbutils.fs.mount("s3a://%s" % aws_bucket_name, "/mnt/%s" % mount_name)
</code>```

Body:
I have mounted 'mybucket' using mount commands and i could able to list all the objects using the below command-

%fs
ls /mnt/mybucket/

however, i have folders inside the folders in 'mybucket' and i want to run the below command but it is not working.

%fs
ls /mnt/mybucket/*/*/

Any help is much appreciated. Thanks

Body:
Unmount and mount again.

dbutils.fs.unmount("/mnt/mount_name")

dbutils.fs.mount("s3a://%s" % aws_bucket_name, "/mnt/%s" % mount_name)


问:
Unable to create process using '...\python.exe' | error in virtual environment
I'm unable to use python within the virtual environment. Python works fine outside of the virtual environment. I'm using Python 3.10.2

I keep on getting the error below when trying to run any python commands.

```<code>'C:\Users\User\AppData\Local\Programs\Python\Python310\python.exe'
</code>```

It might be relevant to mention that I was unable to create the virtual environment through the 'python -m venv env' command. Error generated was

```<code>Error: Command '['C:\\Users\\User\\Documents\\Python Projects\\PDFtoText\\env\\Scripts\\python.exe', '-Im', 'ensurepip', '--upgrade', '--default-pip']' returned non-zero exit status 101.
</code>```

I had to add 'without-pip' to the end of the command to create the virtual environment. Weird thing is, I was able to use pip within the virtual environment without having to manually install it.

The path to python is in the environmental variables.

I tried reinstalling python but that did not help.

Lastly, all these errors started occurring after I downloaded Visual Studio Community 2022.

答:
Short answer, I bet you have a space in your Window's account name (say Your Account is where your account is saved so you have C:\Users\Your Account folder, and there is also a text file C:\Users\Your ("Your" being the first part of your user name). MSVS2022 (maybe earlier versions, too) is known to leave this log file which exposes a bug in Python venv's python launcher. Delete this text file, and your problem should be solved.

See my question/answer for more details.

Body:
I'm unable to use python within the virtual environment. Python works fine outside of the virtual environment. I'm using Python 3.10.2

I keep on getting the error below when trying to run any python commands.

'C:\Users\User\AppData\Local\Programs\Python\Python310\python.exe'

It might be relevant to mention that I was unable to create the virtual environment through the 'python -m venv env' command. Error generated was

Error: Command '['C:\\Users\\User\\Documents\\Python Projects\\PDFtoText\\env\\Scripts\\python.exe', '-Im', 'ensurepip', '--upgrade', '--default-pip']' returned non-zero exit status 101.

I had to add 'without-pip' to the end of the command to create the virtual environment. Weird thing is, I was able to use pip within the virtual environment without having to manually install it.

The path to python is in the environmental variables.

I tried reinstalling python but that did not help.

Lastly, all these errors started occurring after I downloaded Visual Studio Community 2022.


问:
How to get Client ID in Stripe?
I want to know how to get Client ID in Stripe ? On new view, I feel hard to find Client ID.

Some instruction says that I need go to Connect panel.

But, when in Connect page, I can't get the Client ID.

答:
You can find your client_id here in docs: https://stripe.com/docs/connect/testing#using-oauth

Keep in mind that you should be logged in so your client_id would be displayed directly in the documentation

Title: How to get Client ID in Stripe?


问:
Sending a BlobMessage using JmsTemplate with CachingConnectionFactory
I am using ActiveMQ as my message broker and I have a JMS requirement of sending a big document as an input stream to be processed by consumers. The issue I have is that if I use Spring's org.springframework.jms.connection.CachingConnectionFactory to wrap an ActiveMQConnectionFactory, I'll have to cast the session object (javax.jms.Session) into an org.apache.activemq.ActiveMQSession which is what was suggested in here (Sending Files using Active MQ with BlobMessage).

I then get an exception if I cast the generic Session object into an ActiveMQSession because Spring only provides a Proxy for the javax.jms.Session and not the target object that it proxies to (ie org.apache.activemq.ActiveMQSession). So the solution I resorted to was to just use a plain ActiveMQConnectionFactory instead of using a CachingConnectionFactory. Is there a way for me to keep a CachingConnectionFactory without getting the ClassCastException from my sample code below?

```<code>  jmsTemplate.send(new MessageCreator() {
    public Message createMessage(Session session) throws JMSException {
      org.apache.activemq.ActiveMQSession activeMQSession = ((org.apache.activemq.ActiveMQSession) session);

      BlobMessage message = activeMQSession.createBlobMessage(inputStream);
      LOGGER.debug("created a blob message");
      return message;
    }
  });
</code>```

And here's what I currently have now in my application context which will prevent the ClassCastException from being thrown. See the commented blocks as well which shows the old configuration I have which throws the exception:

```<code><bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate">
  <property name="connectionFactory" ref="connectionFactory"/>
  <property name="defaultDestination" ref="gtJobRequestQueue"/>
</bean>

<!--   <bean id="connectionFactory" class="org.springframework.jms.connection.CachingConnectionFactory"> -->
<!--     <property name="targetConnectionFactory" ref="activeMqConnectionFactory" /> -->
<!--     <property name="sessionCacheSize" value="3"/> -->
<!--     <property name="cacheProducers" value="true"/> -->
<!--   </bean> -->

<!-- <bean id="activeMqConnectionFactory" class="org.apache.activemq.spring.ActiveMQConnectionFactory"> -->
<bean id="connectionFactory" class="org.apache.activemq.spring.ActiveMQConnectionFactory">
  <property name="brokerURL" value="${aurin.data-provider.broker.url}"/>
  <property name="prefetchPolicy" ref="prefetchPolicy" />
</bean>
</code>```

答:
SessionProxy sp = (SessionProxy)session;

ActiveMQSession as = (ActiveMQSession)sp.getTargetSession();

Body:
I am using ActiveMQ as my message broker and I have a JMS requirement of sending a big document as an input stream to be processed by consumers. The issue I have is that if I use Spring's org.springframework.jms.connection.CachingConnectionFactory to wrap an ActiveMQConnectionFactory, I'll have to cast the session object (javax.jms.Session) into an org.apache.activemq.ActiveMQSession which is what was suggested in here (Sending Files using Active MQ with BlobMessage).

I then get an exception if I cast the generic Session object into an ActiveMQSession because Spring only provides a Proxy for the javax.jms.Session and not the target object that it proxies to (ie org.apache.activemq.ActiveMQSession). So the solution I resorted to was to just use a plain ActiveMQConnectionFactory instead of using a CachingConnectionFactory. Is there a way for me to keep a CachingConnectionFactory without getting the ClassCastException from my sample code below?

  jmsTemplate.send(new MessageCreator() {
    public Message createMessage(Session session) throws JMSException {
      org.apache.activemq.ActiveMQSession activeMQSession = ((org.apache.activemq.ActiveMQSession) session);

      BlobMessage message = activeMQSession.createBlobMessage(inputStream);
      LOGGER.debug("created a blob message");
      return message;
    }
  });

And here's what I currently have now in my application context which will prevent the ClassCastException from being thrown. See the commented blocks as well which shows the old configuration I have which throws the exception:

<bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate">
  <property name="connectionFactory" ref="connectionFactory"/>
  <property name="defaultDestination" ref="gtJobRequestQueue"/>
</bean>

<bean id="connectionFactory" class="org.apache.activemq.spring.ActiveMQConnectionFactory">
  <property name="brokerURL" value="${aurin.data-provider.broker.url}"/>
  <property name="prefetchPolicy" ref="prefetchPolicy" />
</bean>


问:
How do I filter the below array and get ["h","a"] output?
```<code>Const array = [1,2,3,4,"h","a","$","@"]
// Here array of numbers, strings, special characters
</code>```

I wanted the output to be

```<code>["h","a"]
</code>```

答:
```<code>const array = [1,2,3,4,"h","a","$","@"]
let n =array.filter((x) => typeof x === "string" && /^[a-zA-
Z]+$/.test(x))
console.log(n)
</code>```

I used Regex to compare and filtered to a new array this should do what you want

Body:
Const array = [1,2,3,4,"h","a","$","@"]
// Here array of numbers, strings, special characters

I wanted the output to be

["h","a"]

Body:
const array = [1,2,3,4,"h","a","$","@"]
let n =array.filter((x) => typeof x === "string" && /^[a-zA-
Z]+$/.test(x))
console.log(n)

I used Regex to compare and filtered to a new array this should do what you want


问:
Sql exception in winforms form handling best practice
using c# vs2008 winforms.

My standard forms have a typical usage pattern of

Form load

Sqlconnection object open.

read/write datasets using sqldataadaptors

read many things using sql readers

write many data using stored procedures to write

close sql connection

close form

So whats best practice in handling exceptions in this type of usage pattern
I enclose all read and write code to the sql server in try catch clauses to trap exceptions.

So what do i do when i trap an exception ?

Should i close and dispose all sql objects ?

Should i close the form and dispose the form.

Should i try to let the user continue on

Should i try to re-open my sqlconnection if the exception is that the sql connection broken ?

Given that i open and close connections on form load and close, as that it only in theory opens once and closes once with many reads and writes inbetween.

I'm just not sure what action i should be taking when i trap an exception, to prevent memory and resource leaks.

any advice appreciated

thanks

答:
It depends on the exception you receive and its severity.  If it was error number 1205, you would want to retry, as that's the SQL Server deadlock error. e.g

```<code>catch (SqlException sqlEx)
{
    if (sqlEx.Number == 1205)
    {
        // Deadlock occurred, retry...
    }
    else
        throw;
}
</code>```

For unrecoverable errors, you would want to clean up and dispose of connections etc.

Best practice is to use using blocks whenever an object implements IDisposable (such as a SqlConnection, SqlCommand, etc.)

To get a complete list of error codes, run this TSQL:

```<code>SELECT * FROM sysmessages
</code>```

Body:
It depends on the exception you receive and its severity.  If it was error number 1205, you would want to retry, as that's the SQL Server deadlock error. e.g

catch (SqlException sqlEx)
{
    if (sqlEx.Number == 1205)
    {
        // Deadlock occurred, retry...
    }
    else
        throw;
}

For unrecoverable errors, you would want to clean up and dispose of connections etc.

Best practice is to use using blocks whenever an object implements IDisposable (such as a SqlConnection, SqlCommand, etc.)

To get a complete list of error codes, run this TSQL:

SELECT * FROM sysmessages


问:
Git - show remote name of remote branch
Is there a Git command to show the remote name of a remote branch?

Currently I stick with extracting the remote name from a remote branch ref using shell utils like ...

```<code>$ echo "remote-name/branch-name" | sed -r 's;^([^/]+)/.*;\1;'
remote-name
</code>```

sometimes passing it through for validation purposes

```<code>$ git rev-parse --symbolic-full-name "remote-name/branch-name" | ...
</code>```

I wonder if there's a builtin command like.

```<code>$ git wanted-command [wanted options] "remote-name/branch-name"
remote-name
</code>```

I've looked though the manpages of rev-parse, remote and ls-remote.

答:
If instead of the remote reference, you started with a local reference, you could use git for-each-ref with the %(upstream:remotename) format.

I use this together with git symbolic-ref -q HEAD to get the remote name for the current checkout:

remote=$(git for-each-ref --format='%(upstream:remotename)' "$(git symbolic-ref -q HEAD)")
```
<p>Demo with the most common remote:</p>
```% git for-each-ref --format='%(upstream:remotename)' "$(git symbolic-ref -q HEAD)"
origin
```

Title: Git - show remote name of remote branch

Body:
Is there a Git command to show the remote name of a remote branch?

Currently I stick with extracting the remote name from a remote branch ref using shell utils like ...

$ echo "remote-name/branch-name" | sed -r 's;^([^/]+)/.*;\1;'
remote-name

sometimes passing it through for validation purposes

$ git rev-parse --symbolic-full-name "remote-name/branch-name" | ...

I wonder if there's a builtin command like.

$ git wanted-command [wanted options] "remote-name/branch-name"
remote-name

I've looked though the manpages of rev-parse, remote and ls-remote.

Body:
If instead of the remote reference, you started with a local reference, you could use git for-each-ref with the %(upstream:remotename) format.

I use this together with git symbolic-ref -q HEAD to get the remote name for the current checkout:

remote=$(git for-each-ref --format='%(upstream:remotename)' "$(git symbolic-ref -q HEAD)")

Demo with the most common remote:

% git for-each-ref --format='%(upstream:remotename)' "$(git symbolic-ref -q HEAD)"
origin


问:
BI Publisher not compiling <xsl:attribute>?
I'm using MS Word to create rtf templates for Oracle BI Publisher.

My goal is to conditionally assign a color to the title in the header section.
My xsl code looks like this:

```<code><?if:DRUCKTITEL ="NICHT FREIGEGEBEN"?><xsl:attribute name="color">red</xsl:attribute><?end if?><?DRUCKTITEL?>
</code>```

I expect the words "NICHT FREIGEGEBEN" to appear in red, however what I get is this:

答:
Try:

```<code><?attribute@incontext:color;'red'?>
</code>```

Or, you can use this inside of a field's "Help Text" or BI Publisher code section.

```<code><xsl:attribute xdofo:ctx="block" name="color">red</xsl:attribute>
</code>```

I highly recommend installing the desktop tool if you have not already done so.

Body:
I'm using MS Word to create rtf templates for Oracle BI Publisher.

My goal is to conditionally assign a color to the title in the header section.
My xsl code looks like this:

<?if:DRUCKTITEL ="NICHT FREIGEGEBEN"?><xsl:attribute name="color">red</xsl:attribute><?end if?><?DRUCKTITEL?>

I expect the words "NICHT FREIGEGEBEN" to appear in red, however what I get is this:

Body:
Try:

<?attribute@incontext:color;'red'?>

Or, you can use this inside of a field's "Help Text" or BI Publisher code section.

<xsl:attribute xdofo:ctx="block" name="color">red</xsl:attribute>

I highly recommend installing the desktop tool if you have not already done so.


问:
How to return value from addEventListener
I use Javascript to catch the x and y position for when user clicks a link.

I can make it work, but I want it to return the two values to function init() when it is called.

How can I do it?

```<code><script type="text/javascript">

  document.addEventListener("DOMContentLoaded", init, false);

  function init()
  {
    var canvas = document.getElementById("canvas");
    canvas.addEventListener("mousedown", getPosition, false);

    // how can I get the return values here?

  }

  function getPosition(event)
  {
    var x = new Number();
    var y = new Number();
    var canvas = document.getElementById("canvas");

    if (event.x != undefined && event.y != undefined)
    {
      x = event.x;
      y = event.y;
    }
    else
    {
      x = event.clientX + document.body.scrollLeft +
          document.documentElement.scrollLeft;
      y = event.clientY + document.body.scrollTop +
          document.documentElement.scrollTop;
    }

    x -= canvas.offsetLeft;
    y -= canvas.offsetTop;

    alert("x: " + x + "  y: " + y); // here can print the correct position

    // if I add the two values here, and return them. How can I receive the values in funciton init()
    // var clickPosition={"x":x, "y":y};
    // return clickPosition;
  }

</script>
</code>```

答:
Event listeners return nothing by default, but you can get data out of them in clever ways.

This MDN article described 3 methods:

Getting data into an event listener using "this"

Getting data into an event listener using the outer scope property

Getting data into and out of an event listener using objects


问:
How can I identify the column, where two (or more) rows are different (same ID)?
I have a dataframe with duplicate IDs, but the rows are not identical. Is there a function, which identifies the column (or columns), where a difference appears?

My real application is a dataframe with hundreds of columns. I need some way to check, whether changes were made in important columns or in some irrelevant ones. So first of all I need to identify the changed columns.

Example:

```<code>ID <- c(1,2,2,4,5,5,5,6,6,7)
Info1 <- c(10,20,20,40,50,50,50,65,60,70)
Info2 <- c('A','B','A','D', 'E','E','F', 'Z','A','B')
Info3 <- c(999,998,997,995,995,995,995,946,800,805)

df <- data.frame(ID, Info1, Info2, Info3)
</code>```
```<code>   ID Info1 Info2 Info3
1   1    10     A   999
2   2    20     B   998
3   2    20     A   997
4   4    40     D   995
5   5    50     E   995
6   5    50     E   995
7   5    50     F   995
8   6    60     Z   946
9   6    60     A   800
10  7    70     B   805
</code>```

My goal would be an additional column, which contains the changed column, i.e. desired output:

```<code>   ID Info1 Info2 Info3            col_diff
1   1    10     A   999                <NA>
2   2    20     B   998        Info2; Info3
3   2    20     A   997        Info2; Info3
4   4    40     D   995                <NA>
5   5    50     H   995               Info2
6   5    50     E   995               Info2
7   5    50     F   995               Info2
8   6    65     Z   946 Info1; Info2; Info3
9   6    60     A   800 Info1; Info2; Info3
10  7    70     B   805                <NA>
</code>```

I hope my problem became clear. I hope there is some function within dplyr, which I do not know yet. Of course my solution with the additional column is not really elegant. So I am open to any ideas, which may solve my problem.

Thanks a lot!

答:
We may use across with cur_column() - grouped by 'ID', loop across the 'Info' columns, if the number of distinct elements (n_distinct) in the column is greater than 1, return the column name (cur_column()) or else return blank (""), then reduce the columns to a single string by paste (str_c) and remove any leading/lagging delimiter with trimws

```<code>library(dplyr)
library(stringr)
library(purrr)
df %>%
 group_by(ID) %>%
 mutate(col_diff = across(starts_with('Info'),
  ~ if(n_distinct(.x) > 1) cur_column() else "") %>%
   reduce(str_c, sep = "; ") %>%
      trimws(whitespace = ";\\s+") ) %>%
  ungroup
</code>```

-output

```<code># A tibble: 10 × 5
      ID Info1 Info2 Info3 col_diff
   <dbl> <dbl> <chr> <dbl> <chr>
 1     1    10 A       999 ""
 2     2    20 B       998 "Info2; Info3"
 3     2    20 A       997 "Info2; Info3"
 4     4    40 D       995 ""
 5     5    50 E       995 "Info2"
 6     5    50 E       995 "Info2"
 7     5    50 F       995 "Info2"
 8     6    65 Z       946 "Info1; Info2; Info3"
 9     6    60 A       800 "Info1; Info2; Info3"
10     7    70 B       805 ""
</code>```

Body:
I have a dataframe with duplicate IDs, but the rows are not identical. Is there a function, which identifies the column (or columns), where a difference appears?

My real application is a dataframe with hundreds of columns. I need some way to check, whether changes were made in important columns or in some irrelevant ones. So first of all I need to identify the changed columns.

Example:

ID <- c(1,2,2,4,5,5,5,6,6,7)
Info1 <- c(10,20,20,40,50,50,50,65,60,70)
Info2 <- c('A','B','A','D', 'E','E','F', 'Z','A','B')
Info3 <- c(999,998,997,995,995,995,995,946,800,805)

df <- data.frame(ID, Info1, Info2, Info3)

   ID Info1 Info2 Info3
1   1    10     A   999
2   2    20     B   998
3   2    20     A   997
4   4    40     D   995
5   5    50     E   995
6   5    50     E   995
7   5    50     F   995
8   6    60     Z   946
9   6    60     A   800
10  7    70     B   805

My goal would be an additional column, which contains the changed column, i.e. desired output:

   ID Info1 Info2 Info3            col_diff
1   1    10     A   999                <NA>
2   2    20     B   998        Info2; Info3
3   2    20     A   997        Info2; Info3
4   4    40     D   995                <NA>
5   5    50     H   995               Info2
6   5    50     E   995               Info2
7   5    50     F   995               Info2
8   6    65     Z   946 Info1; Info2; Info3
9   6    60     A   800 Info1; Info2; Info3
10  7    70     B   805                <NA>

I hope my problem became clear. I hope there is some function within dplyr, which I do not know yet. Of course my solution with the additional column is not really elegant. So I am open to any ideas, which may solve my problem.

Thanks a lot!

Body:
We may use across with cur_column() - grouped by 'ID', loop across the 'Info' columns, if the number of distinct elements (n_distinct) in the column is greater than 1, return the column name (cur_column()) or else return blank (""), then reduce the columns to a single string by paste (str_c) and remove any leading/lagging delimiter with trimws

library(dplyr)
library(stringr)
library(purrr)
df %>%
 group_by(ID) %>%
 mutate(col_diff = across(starts_with('Info'),
  ~ if(n_distinct(.x) > 1) cur_column() else "") %>%
   reduce(str_c, sep = "; ") %>%
      trimws(whitespace = ";\\s+") ) %>%
  ungroup

-output

# A tibble: 10 × 5
      ID Info1 Info2 Info3 col_diff
   <dbl> <dbl> <chr> <dbl> <chr>
 1     1    10 A       999 ""
 2     2    20 B       998 "Info2; Info3"
 3     2    20 A       997 "Info2; Info3"
 4     4    40 D       995 ""
 5     5    50 E       995 "Info2"
 6     5    50 E       995 "Info2"
 7     5    50 F       995 "Info2"
 8     6    65 Z       946 "Info1; Info2; Info3"
 9     6    60 A       800 "Info1; Info2; Info3"
10     7    70 B       805 ""


问:
Typescript: Property doesn't exist on Generic Type
I'm trying to learn Typescript and I've been following some exercises I've found on the internet. But the feedback on incorrect solutions aren't that great. So I've got the following code but TS keeps complaining that property type is not defined on T:

```<code>interface User {
    type: 'user';
    name: string;
    age: number;
    occupation: string;
}

interface Admin {
    type: 'admin';
    name: string;
    age: number;
    role: string;
}

export type Person = User | Admin;

export const persons: Person[] = [
    { type: 'user', name: 'Max Mustermann', age: 25, occupation: 'Chimney sweep' },
    { type: 'admin', name: 'Jane Doe', age: 32, role: 'Administrator' },
    { type: 'user', name: 'Kate Müller', age: 23, occupation: 'Astronaut' },
    { type: 'admin', name: 'Bruce Willis', age: 64, role: 'World saver' },
    { type: 'user', name: 'Wilson', age: 23, occupation: 'Ball' },
    { type: 'admin', name: 'Agent Smith', age: 23, role: 'Anti-virus engineer' }
];

export function filterPersons<T>(persons: T[], personType: string, criteria: T): T[] {
    return persons
        .filter((person) => person.type === personType)
        .filter((person) => {
            let criteriaKeys = Object.keys(criteria) as (keyof T)[];
            return criteriaKeys.every((fieldName) => {
                return person[fieldName] === criteria[fieldName];
            });
        });
}

export const usersOfAge23 = filterPersons<User>(persons, 'user', { age: 23 });
export const adminsOfAge23 = filterPersons<Admin>(persons, 'admin', { age: 23 });
</code>```

What am I doing wrong here? T should be a genertic type or in this case User or Admin that is passed right?

答:
In your function declaration, there is one thing you know about T: it extends Person so give this hint to TypeScript:

```<code>export function filterPersons<T extends Person>(persons: T[], personType: string, criteria: T): T[] {
</code>```

Your function implementation will work like this but it raises two other errors:

You are passing a Person[] to filterPersons<User> and filterPersons<Admin> which is wider than the required types. Quick fix: let TypeScript infer the type by omitting it when you call the function: filterPersons

The criteria is not a full T, only some properties of it so type it as Partial<T>

TypeScript playground

Body:
I'm trying to learn Typescript and I've been following some exercises I've found on the internet. But the feedback on incorrect solutions aren't that great. So I've got the following code but TS keeps complaining that property type is not defined on T:

interface User {
    type: 'user';
    name: string;
    age: number;
    occupation: string;
}

interface Admin {
    type: 'admin';
    name: string;
    age: number;
    role: string;
}

export type Person = User | Admin;

export const persons: Person[] = [
    { type: 'user', name: 'Max Mustermann', age: 25, occupation: 'Chimney sweep' },
    { type: 'admin', name: 'Jane Doe', age: 32, role: 'Administrator' },
    { type: 'user', name: 'Kate Müller', age: 23, occupation: 'Astronaut' },
    { type: 'admin', name: 'Bruce Willis', age: 64, role: 'World saver' },
    { type: 'user', name: 'Wilson', age: 23, occupation: 'Ball' },
    { type: 'admin', name: 'Agent Smith', age: 23, role: 'Anti-virus engineer' }
];

export function filterPersons<T>(persons: T[], personType: string, criteria: T): T[] {
    return persons
        .filter((person) => person.type === personType)
        .filter((person) => {
            let criteriaKeys = Object.keys(criteria) as (keyof T)[];
            return criteriaKeys.every((fieldName) => {
                return person[fieldName] === criteria[fieldName];
            });
        });
}

export const usersOfAge23 = filterPersons<User>(persons, 'user', { age: 23 });
export const adminsOfAge23 = filterPersons<Admin>(persons, 'admin', { age: 23 });

What am I doing wrong here? T should be a genertic type or in this case User or Admin that is passed right?

Body:
In your function declaration, there is one thing you know about T: it extends Person so give this hint to TypeScript:

export function filterPersons<T extends Person>(persons: T[], personType: string, criteria: T): T[] {

Your function implementation will work like this but it raises two other errors:

You are passing a Person[] to filterPersons<User> and filterPersons<Admin> which is wider than the required types. Quick fix: let TypeScript infer the type by omitting it when you call the function: filterPersons

The criteria is not a full T, only some properties of it so type it as Partial<T>

<a href="https://www.typescriptlang.org/play?#code/JYOwLgpgTgZghgYwgAgKoGdrIN4ChkHJgCeADhAFzIDkArplNQNz6EhwC2ly6YUoAcxaFkcAdxC0OAI2jDCAewQJapOGGAKQVXvxBDcAX1y5QkWIhQBBACYdQOVgRLkq1OHdDMnydlx18gvIEYhJSslDByFAKADbcukFGJhAAHqQKUGBEZCgACtDoWsgAvGgMyAA%20yLb2ICy4aRlZyAhavMjkUEUg6FQF3VoA2gC6pchDPtg5rjT00NQANL6c3NQAsnCpyOv05hxwICBLouJUAEwArMtKKmoaWm4AwgAWwBwgEMQ8AO4QEKRqMhDIspjM1h46ic-GsAFKHFAAEQUEBOoSoAGZzssYvE3LVQMBdOpMkCQWCXGt5oxljC3ABpdQodYAH9i8Rpp245wxN2UqnUmm0NCsui0cFoYDJoJE00pbkhXlpqzcACEoLQkMgAOrAdlEtFnZAANgALDi4mttZlYjYeHAAG4LYEywhy3JuanQlU0XWxHqG7m85C3AUPYXUVVwdnSikemiK47K-wi8TgZAAZXsYBegYuwdxays4GAAFoHcANehkBB9KB-oxgbgRg0mplsjBaCAEOHkDA9eYBj10AAeAAqNdSkBANmrQ60AD4ABRdYdUMejZarrRj%20OJfTLBD8czAOD9OBZU%20xccLgCU69GjhEUAgYFoUBAnUK7R8IgAdP2sTmEuK7fiAt6lAuX6DCAf6UqUJRlNuIC7uQt6-oQAEDtAIHIRBJRQXgIjEYQ8TZEewAnnA9JfNWZQAPLSAAVhAPZ-gA1rRS4UVREFwNWS6ccQCgwMgY63qMUQkQQL5vh%20rTHtAp40cQ6B-hATpQMQIH9hAtoAHKrPhhEYdJhCye%20n7IUMukGasYyIWUPFKXANnAHpNiGVwLamcRhi3lJhD%20SwxiNOk7atO02TUug9EwFY4g8uMgGDmB6CgTB6DLHQDAnNM6LIElwVhc05FRaIni9HFCUQElZQpdA869Blw7ZYmeVcvmwIBUAA" rel="nofollow noreferrer">TypeScript playground


问:
How can I hide methods in my C# code from documentation?
I have a bunch of classes of the following format, located in the various namespaces. Instances of these classes are serialized and de-serialized objects across the network.

```<code>public class Foo:INetSerializable
{

    public void ReadObjectData(Streamer stream)
    {

    }

    public void WriteObjectData(Streamer stream)
    {

   }
}
</code>```

In a different namespace, I have a Dispatcher class that uses some criteria to serialize/deserialize these instances.

However, I don't want users to see these methods in my documentation. I cannot make these guys internal because then Dispatcher wouldn't be able to access them.

I use Visual Studio 2005, so I cannot take advantage of C# 3.0.

How can I do this?

Another Error:

How do I deal with a class that inherits from Foo and overrides the Read and WriteObjectData for example, the following is giving me this error:
type does not implement interface INetSerializable

```<code>public class Bar:Foo
    {

        public void ReadObjectData(Streamer stream)
        {

        }

        public void WriteObjectData(Streamer stream)
        {

       }
    }
</code>```

答:
You can use explicit interface implementation. I believe the syntax would be

```<code>void INetSerializable.ReadObjectData(Streamer stream)
</code>```

Note that it doesn't say "public", so it's not public. It can only be  accessed through the interface.

OwnerDisplayName: Sasha

LastEditorDisplayName: Sasha

ContentLicense: CC BY-SA 2.5

Body:
I have a bunch of classes of the following format, located in the various namespaces. Instances of these classes are serialized and de-serialized objects across the network.

public class Foo:INetSerializable
{

    public void ReadObjectData(Streamer stream)
    {

    }

    public void WriteObjectData(Streamer stream)
    {

   }
}

In a different namespace, I have a Dispatcher class that uses some criteria to serialize/deserialize these instances.

However, I don't want users to see these methods in my documentation. I cannot make these guys internal because then Dispatcher wouldn't be able to access them.

I use Visual Studio 2005, so I cannot take advantage of C# 3.0.

How can I do this?

Another Error:

How do I deal with a class that inherits from Foo and overrides the Read and WriteObjectData for example, the following is giving me this error:
type does not implement interface INetSerializable

public class Bar:Foo
    {

        public void ReadObjectData(Streamer stream)
        {

        }

        public void WriteObjectData(Streamer stream)
        {

       }
    }

Body:
You can use explicit interface implementation. I believe the syntax would be

void INetSerializable.ReadObjectData(Streamer stream)

Note that it doesn't say "public", so it's not public. It can only be  accessed through the interface.

OwnerDisplayName: John Saunders


问:
jQuery Ui - Swapping thickbox for UI dialog
Thickbox is depreciated and causes problems when used within jQuery UI Tabs. Before moving to using tabs I was simply calling thickbox which worked as normal, with the url of my remote source included. Is there a generic way that jQuery UI dialogs can be made to work the same was as the thickbox solution?

I was calling thickbox like so:

```<code><a href="URLHERE" class="thickbox" disabled title='Select a value from the list provided'><img border=0  src='images/zoom.png'></a>
</code>```

答:
Replaced with UI Dialogs:</p>

```<code>$('.thickbox').click(function(){
        var href = $( this ).attr("rel");
        var dialogTitle= $(this).attr("title");

        $("#testDialogID").load(href, function() {
            var container = $(this);
            container.dialog({
                bgiframe: true,
                opacity: false,
                title: dialogTitle,
                modal: true
            })
        });

    });
</code>```

Body:
Replaced with UI Dialogs:

$('.thickbox').click(function(){
        var href = $( this ).attr("rel");
        var dialogTitle= $(this).attr("title");

        $("#testDialogID").load(href, function() {
            var container = $(this);
            container.dialog({
                bgiframe: true,
                opacity: false,
                title: dialogTitle,
                modal: true
            })
        });

    });


问:
Throw customer error when partial view is missing
I have a view say Order.cshtml

This view has a partial view ConfirmationPartial.cshtml and within this partial view there is another partial view OrderDetailsPartial.cshtml

Now my question is I want to throw some kind of error in case OrderDetailsPartial.cshtml is missing on deployment server.

答:
You can create a helper method and call it from view to check if its exist or not</p>
```<code>    public static HtmlString MyHelper(this HtmlHelper html)
    {
     var controllerContext = html.ViewContext.Controller.ControllerContext;
     var result = ViewEngines.Engines.FindView(controllerContext, name, null);
     ...
    }
</code>```

Body:
You can create a helper method and call it from view to check if its exist or not

    public static HtmlString MyHelper(this HtmlHelper html)
    {
     var controllerContext = html.ViewContext.Controller.ControllerContext;
     var result = ViewEngines.Engines.FindView(controllerContext, name, null);
     ...
    }


问:
Integrating a customer feedback form with Google Analytics
I'm attempting to implement a simple customer feedback system on my website and came across a couple of articles that used Google Analytics to collect feedback, which I've linked to below.

1./ Push customer feedback results directly to Google Analytics with this new integration

2./ Using Google Analytics with Website Feedback

I was wondering if this is a good practice? Is there any security risk, such as information exposure via query strings in URLs or web parameter tampering?

答:
There's no need to link to articles. It's pretty trivial and common implementation. What you can track in GA is limited. For example, in some countries you're not allowed to store PII (Personal identifiable information).  In other countries, they have GDPR, that has even more limitations.

And of course, getting data from GA to display it publicly is a bad idea too because GA was designed for internal use. Therefore, GA is a good solution if you can legally store that data on GA's servers and if you need it for personal analysis.


问:
UIViewControllerRepresentable not correctly taking up space
I am trying to use a custom UIViewController in a SwiftUI view. I set up a UIViewControllerRepresentable class which creates the UIViewController in the makeUIViewController method. This creates the UIViewController and displays the button, however, the UIViewControllerRepresentable does not take up any space.

I tried using a UIImagePickerController instead of my custom controller, and that sizes correctly. The only way I got my controller to take up space was by setting a fixed frame on the UIViewControllerRepresentable in my SwiftUI view, which I absolutely don't want to do.

Note: I do need to use a UIViewController because I am trying to implement a UIMenuController in SwiftUI. I got all of it to work besides this problem I am having with it not sizing correctly.

Here is my code:

```<code>struct ViewControllerRepresentable: UIViewControllerRepresentable {
    func makeUIViewController(context: Context) -> MenuViewController {
        let controller = MenuViewController()
        return controller
    }

    func updateUIViewController(_ uiViewController: MenuViewController, context: Context) {

    }
}

class MenuViewController: UIViewController {
    override func viewDidLoad() {
        let button = UIButton()
        button.setTitle("Test button", for: .normal)
        button.setTitleColor(.red, for: .normal)

        self.view.addSubview(button)
        button.translatesAutoresizingMaskIntoConstraints = false
        button.leadingAnchor.constraint(equalTo: self.view.leadingAnchor).isActive = true
        button.trailingAnchor.constraint(equalTo: self.view.trailingAnchor).isActive = true
        button.topAnchor.constraint(equalTo: self.view.topAnchor).isActive = true
        button.bottomAnchor.constraint(equalTo: self.view.bottomAnchor).isActive = true
    }
}
</code>```

My SwiftUI view:

```<code>struct ClientView: View {
    var body: some View {
        VStack(spacing: 0) {
            EntityViewItem(copyValue: "copy value", label: {
                Text("Name")
            }, content: {
                Text("Random name")
            })
            .border(Color.green)

            ViewControllerRepresentable()
                .border(Color.red)

            EntityViewItem(copyValue: "copy value", label: {
                Text("Route")
            }, content: {
                HStack(alignment: .center) {
                    Text("Random route name")
                }
            })
            .border(Color.blue)
        }
    }
}
</code>```

Screenshot:

I do not have much experience with UIKit - my only experience is writing UIKit views to use in SwiftUI. The problem could very possibly be related to my lack of UIKit knowledge.

Thanks in advance!

Edit:

Here is the code for EntityViewItem. I will also provide the container view that ClientView is in - EntityView.

I also cleaned up the rest of the code and replaced references to Entity with hardcoded values.

```<code>struct EntityViewItem<Label: View, Content: View>: View {
    var copyValue: String
    var label: Label
    var content: Content
    var action: (() -> Void)?

    init(copyValue: String, @ViewBuilder label: () -> Label, @ViewBuilder content: () -> Content, action: (() -> Void)? = nil) {
        self.copyValue = copyValue
        self.label = label()
        self.content = content()
        self.action = action
    }

    var body: some View {
        VStack(alignment: .leading, spacing: 2) {
            label
                .opacity(0.6)
            content
                .onTapGesture {
                    guard let unwrappedAction = action else {
                        return
                    }
                    unwrappedAction()
                }
                .contextMenu {
                    Button(action: {
                        UIPasteboard.general.string = copyValue
                    }) {
                        Text("Copy to clipboard")
                        Image(systemName: "doc.on.doc")
                    }
                }
        }
        .padding([.top, .leading, .trailing])
        .frame(maxWidth: .infinity, alignment: .leading)
    }
}
</code>```

The container of ClientView:

```<code>struct EntityView: View {
    let headerHeight: CGFloat = 56

    var body: some View {
        ZStack {
            ScrollView(showsIndicators: false) {
                VStack(spacing: 0) {
                    Color.clear.frame(
                        height: headerHeight
                    )
                    ClientView()
                }
            }
            VStack(spacing: 0) {
                HStack {
                    Button(action: {
                    }, label: {
                        Text("Back")
                    })
                    Spacer()
                    Text("An entity name")
                        .lineLimit(1)
                        .minimumScaleFactor(0.5)

                    Spacer()
                    Color.clear
                        .frame(width: 24, height: 0)
                }
                .frame(height: headerHeight)
                .padding(.leading)
                .padding(.trailing)
                .background(
                    Color.white
                        .ignoresSafeArea()
                        .opacity(0.95)
                )
                Spacer()
            }
        }
    }
}
</code>```

答:
For anyone looking for the simplest possible solution, it's a couple of lines in @Edudjr's answer:

```<code>let size = content.view.systemLayoutSizeFitting(UIView.layoutFittingCompressedSize)
content.preferredContentSize = size
</code>```

Just add that inside your makeUIViewController!

Body:
I am trying to use a custom UIViewController in a SwiftUI view. I set up a UIViewControllerRepresentable class which creates the UIViewController in the makeUIViewController method. This creates the UIViewController and displays the button, however, the UIViewControllerRepresentable does not take up any space.

I tried using a UIImagePickerController instead of my custom controller, and that sizes correctly. The only way I got my controller to take up space was by setting a fixed frame on the UIViewControllerRepresentable in my SwiftUI view, which I absolutely don't want to do.

Note: I do need to use a UIViewController because I am trying to implement a UIMenuController in SwiftUI. I got all of it to work besides this problem I am having with it not sizing correctly.

Here is my code:

struct ViewControllerRepresentable: UIViewControllerRepresentable {
    func makeUIViewController(context: Context) -> MenuViewController {
        let controller = MenuViewController()
        return controller
    }

    func updateUIViewController(_ uiViewController: MenuViewController, context: Context) {

    }
}

class MenuViewController: UIViewController {
    override func viewDidLoad() {
        let button = UIButton()
        button.setTitle("Test button", for: .normal)
        button.setTitleColor(.red, for: .normal)

        self.view.addSubview(button)
        button.translatesAutoresizingMaskIntoConstraints = false
        button.leadingAnchor.constraint(equalTo: self.view.leadingAnchor).isActive = true
        button.trailingAnchor.constraint(equalTo: self.view.trailingAnchor).isActive = true
        button.topAnchor.constraint(equalTo: self.view.topAnchor).isActive = true
        button.bottomAnchor.constraint(equalTo: self.view.bottomAnchor).isActive = true
    }
}

My SwiftUI view:

struct ClientView: View {
    var body: some View {
        VStack(spacing: 0) {
            EntityViewItem(copyValue: "copy value", label: {
                Text("Name")
            }, content: {
                Text("Random name")
            })
            .border(Color.green)

            ViewControllerRepresentable()
                .border(Color.red)

            EntityViewItem(copyValue: "copy value", label: {
                Text("Route")
            }, content: {
                HStack(alignment: .center) {
                    Text("Random route name")
                }
            })
            .border(Color.blue)
        }
    }
}

Screenshot:

I do not have much experience with UIKit - my only experience is writing UIKit views to use in SwiftUI. The problem could very possibly be related to my lack of UIKit knowledge.

Thanks in advance!

Edit:

Here is the code for EntityViewItem. I will also provide the container view that ClientView is in - EntityView.

I also cleaned up the rest of the code and replaced references to Entity with hardcoded values.

struct EntityViewItem: View {
    var copyValue: String
    var label: Label
    var content: Content
    var action: (() -> Void)?

    init(copyValue: String, @ViewBuilder label: () -> Label, @ViewBuilder content: () -> Content, action: (() -> Void)? = nil) {
        self.copyValue = copyValue
        self.label = label()
        self.content = content()
        self.action = action
    }

    var body: some View {
        VStack(alignment: .leading, spacing: 2) {
            label
                .opacity(0.6)
            content
                .onTapGesture {
                    guard let unwrappedAction = action else {
                        return
                    }
                    unwrappedAction()
                }
                .contextMenu {
                    Button(action: {
                        UIPasteboard.general.string = copyValue
                    }) {
                        Text("Copy to clipboard")
                        Image(systemName: "doc.on.doc")
                    }
                }
        }
        .padding([.top, .leading, .trailing])
        .frame(maxWidth: .infinity, alignment: .leading)
    }
}

The container of ClientView:

struct EntityView: View {
    let headerHeight: CGFloat = 56

    var body: some View {
        ZStack {
            ScrollView(showsIndicators: false) {
                VStack(spacing: 0) {
                    Color.clear.frame(
                        height: headerHeight
                    )
                    ClientView()
                }
            }
            VStack(spacing: 0) {
                HStack {
                    Button(action: {
                    }, label: {
                        Text("Back")
                    })
                    Spacer()
                    Text("An entity name")
                        .lineLimit(1)
                        .minimumScaleFactor(0.5)

                    Spacer()
                    Color.clear
                        .frame(width: 24, height: 0)
                }
                .frame(height: headerHeight)
                .padding(.leading)
                .padding(.trailing)
                .background(
                    Color.white
                        .ignoresSafeArea()
                        .opacity(0.95)
                )
                Spacer()
            }
        }
    }
}

Body:
For anyone looking for the simplest possible solution, it's a couple of lines in @Edudjr's answer:

let size = content.view.systemLayoutSizeFitting(UIView.layoutFittingCompressedSize)
content.preferredContentSize = size

Just add that inside your makeUIViewController!


问:
How to set a type of an array in an anonymous Object
How do I set the type of the array, because grid: []: number[] wont work

```<code>const game = {
  sizeX: 9,
  sizeY: 5,
  SCALE: 80,
  grid: [],  //Object literal's property 'grid' implicitly has an 'any[]' type.
  money: 600,
}
</code>```

答:
The simplest is to use a variable (typed) to put your array, and than use it :

const grid: number[] = [];

const game = {
  sizeX: 9,
  sizeY: 5,
  SCALE: 80,
  grid,
  money: 600,
};
```

Body:
How do I set the type of the array, because grid: []: number[] wont work

const game = {
  sizeX: 9,
  sizeY: 5,
  SCALE: 80,
  grid: [],  //Object literal's property 'grid' implicitly has an 'any[]' type.
  money: 600,
}


问:
return a new list from function in a for loop to pass in the updated list
I have a method that take a list as a parameter that performs some operation on it and returns the new list. However, in my for..loop I would to keep passing in the updated list until the for..loop has completed.

Is there a way to do this?

```<code>fun main(args: Array<String>) {
    val listOfSeatRows = (1..127).toList()

    // Just loop until all the listOfPass has completed.
    listOfPass.forEach { seatPass ->
        val seat = Seat.valueOf(seatPass.toString())
        // I want to pass in the new updated list not the same list
        getListOfSeatRows(listOfSeatRows, seat)
    }
}
</code>```

This method takes the list and return a updated list. However, in the for..loop above I would like to pass in the list that is returned from this method

```<code>private fun getListOfSeatRows(listOfSeat: List<Int>, seatPosition: Seat): List<Int> {
    return when(seatPosition) {
        Seat.F, Seat.L -> {
           listOfSeat.windowed(listOfSeat.count() / 2).first()
        }
        Seat.B, Seat.R -> {
            listOfSeat.windowed(listOfSeat.count() / 2).last()
        }
    }
}

enum class Seat(seat: Char) {
    F('F'),
    B('B'),
    L('L'),
    R('R')
}
</code>```

答:
recursion
maybe that's will help with some enhancement depending on your code:

```<code>var ss = 1
val listOfPass = listOf<Char>('F', 'L','B','R')

fun main(args: Array<String>) {
    val listOfSeatRows = (1..127).toList()
    val answer = getListOfSeatRows(
        listOfSeatRows,
        listOfSeatRows.count() / 2,
        Seat.valueOf(listOfPass[0].toString())
    )
    println(answer)
}

private fun getListOfSeatRows(listOfSeat: List<Int>, count: Int, seatPosition: Seat): List<Int> {
    val tempList: List<Int> = when (seatPosition) {
        Seat.F, Seat.L -> {
            listOfSeat.windowed(count).first()
        }
        Seat.B, Seat.R -> {
            listOfSeat.windowed(count).last()
        }
        else -> listOfSeat
    }
if(count == 0 || count == 1) return listOfSeat

    if (listOfPass.size > ss) {
        val seat = Seat.valueOf(listOfPass[ss++].toString())
        return getListOfSeatRows(tempList, count / 2, seat)
    }

    return listOfSeat
}
</code>```

Body:
I have a method that take a list as a parameter that performs some operation on it and returns the new list. However, in my for..loop I would to keep passing in the updated list until the for..loop has completed.

Is there a way to do this?

fun main(args: Array<String>) {
    val listOfSeatRows = (1..127).toList()

    // Just loop until all the listOfPass has completed.
    listOfPass.forEach { seatPass ->
        val seat = Seat.valueOf(seatPass.toString())
        // I want to pass in the new updated list not the same list
        getListOfSeatRows(listOfSeatRows, seat)
    }
}

This method takes the list and return a updated list. However, in the for..loop above I would like to pass in the list that is returned from this method

private fun getListOfSeatRows(listOfSeat: List<Int>, seatPosition: Seat): List<Int> {
    return when(seatPosition) {
        Seat.F, Seat.L -> {
           listOfSeat.windowed(listOfSeat.count() / 2).first()
        }
        Seat.B, Seat.R -> {
            listOfSeat.windowed(listOfSeat.count() / 2).last()
        }
    }
}

enum class Seat(seat: Char) {
    F('F'),
    B('B'),
    L('L'),
    R('R')
}

Body:
recursion
maybe that's will help with some enhancement depending on your code:

var ss = 1
val listOfPass = listOf<Char>('F', 'L','B','R')

fun main(args: Array<String>) {
    val listOfSeatRows = (1..127).toList()
    val answer = getListOfSeatRows(
        listOfSeatRows,
        listOfSeatRows.count() / 2,
        Seat.valueOf(listOfPass[0].toString())
    )
    println(answer)
}

private fun getListOfSeatRows(listOfSeat: List<Int>, count: Int, seatPosition: Seat): List<Int> {
    val tempList: List<Int> = when (seatPosition) {
        Seat.F, Seat.L -> {
            listOfSeat.windowed(count).first()
        }
        Seat.B, Seat.R -> {
            listOfSeat.windowed(count).last()
        }
        else -> listOfSeat
    }
if(count == 0 || count == 1) return listOfSeat

    if (listOfPass.size > ss) {
        val seat = Seat.valueOf(listOfPass[ss++].toString())
        return getListOfSeatRows(tempList, count / 2, seat)
    }

    return listOfSeat
}


问:
Error "Object reference chain is too long" on querySelectorAll request
I would like to get all the elements in my DOM with a specific css path:

```<code>var elements = await chromeless.evaluate(() => document.querySelectorAll('div a'))
console.log(elements[0].innerHTML)
console.log(elements[1].innerHTML)
</code>```

but this code gives me the error "Object reference chain is too long" on the first line

This code works though:

```<code>var element = await chromeless.evaluate(() => document.querySelectorAll('div a')[0].innerHTML)
console.log(element)
</code>```

and I could potentially use a loop to retrieve them all but I have no idea how many elements have this css in my DOM so I don't know how many times to loop.

What's the correct syntax to get all the desired elements?

答:
```<code>const elements = await chromeless.evaluateHandle(() => {
  const allOccurances = [...document.querySelectorAll("div a")];
  const data = allOccurances.map((node) => node.innerHTML);
  return data;
});
const response = await elements.jsonValue();

console.log(response);
</code>```

Instead of chromeless we can use page by creating a page as per puppeteer documentation https://pptr.dev/#?product=Puppeteer&version=v13.1.3&show=api-class-page

Body:
I would like to get all the elements in my DOM with a specific css path:

var elements = await chromeless.evaluate(() => document.querySelectorAll('div a'))
console.log(elements[0].innerHTML)
console.log(elements[1].innerHTML)

but this code gives me the error "Object reference chain is too long" on the first line

This code works though:

var element = await chromeless.evaluate(() => document.querySelectorAll('div a')[0].innerHTML)
console.log(element)

and I could potentially use a loop to retrieve them all but I have no idea how many elements have this css in my DOM so I don't know how many times to loop.

What's the correct syntax to get all the desired elements?

Body:
const elements = await chromeless.evaluateHandle(() => {
  const allOccurances = [...document.querySelectorAll("div a")];
  const data = allOccurances.map((node) => node.innerHTML);
  return data;
});
const response = await elements.jsonValue();

console.log(response);

Instead of chromeless we can use page by creating a page as per puppeteer documentation https://pptr.dev/#?product=Puppeteer&version=v13.1.3&show=api-class-page


问:
Disable form auto submit on button click
I have a HTML form where I use several buttons. The problem is that no matter which button I  click, the form will get submitted even if the button is not of type "submit". e.g. Buttons like :<button>Click to do something</button>, result in form submission.

It's quite painful to do an e.preventDefault() for each one of these buttons.

I use jQuery and jQuery UI and the website is in HTML5.

Is there a way to disable this automatic behavior?

答:
Like mas-designs said, call preventDefault(). You can call it on the form itself. Here's a function that does this for all forms, vanilla JS.

```<code>function forms_ini(){
  for(var form of document.getElementsByTagName('form')){
    form.addEventListener('submit', function(ev){
      ev.preventDefault()
    })
  }
}
</code>```

Body:
Like mas-designs said, call preventDefault(). You can call it on the form itself. Here's a function that does this for all forms, vanilla JS.

function forms_ini(){
  for(var form of document.getElementsByTagName('form')){
    form.addEventListener('submit', function(ev){
      ev.preventDefault()
    })
  }
}


问:
'Timestamp' object is not subscriptable
This is my code, I am trying to get months for a new column

```<code>import pandas as pd
df = pd.read_excel("..\Data.xlsx")
df.head(4)
p = df["Month"][0]
p[0:3]

</code>```

I don't know what's the issue is here but it was working well for other datasets with the same attributes

Dataset:

```<code>        Month  Passengers
0  1995-01-01         112
1  1995-02-01         118
2  1995-03-01         132
3  1995-04-01         129
4  1995-05-01         121

</code>```

P.S: In the excel data set month values are in Jan-1995 Feb-1995 format, it changed to YY:MM:DAY format because of pandas.

```<code>Traceback (most recent call last):

  File "C:\Users\sreen\AppData\Local\Temp/ipykernel_27276/630478717.py", line 1, in <module>
    p[0:3]

TypeError: 'Timestamp' object is not subscriptable
</code>```

答: Maybe you need to write p = df["Month"]? In you current code, p is the first value of the Month column, so p[0:3] is just a Timestamp, which can't be subscripted.

Title: 'Timestamp' object is not subscriptable

Body:
This is my code, I am trying to get months for a new column

import pandas as pd
df = pd.read_excel("..\Data.xlsx")
df.head(4)
p = df["Month"][0]
p[0:3]

I don't know what's the issue is here but it was working well for other datasets with the same attributes

Dataset:

        Month  Passengers
0  1995-01-01         112
1  1995-02-01         118
2  1995-03-01         132
3  1995-04-01         129
4  1995-05-01         121

P.S: In the excel data set month values are in Jan-1995 Feb-1995 format, it changed to YY:MM:DAY format because of pandas.

Traceback (most recent call last):

  File "C:\Users\sreen\AppData\Local\Temp/ipykernel_27276/630478717.py", line 1, in <module>
    p[0:3]

TypeError: 'Timestamp' object is not subscriptable