问:
The Class-Path manifest attribute in [path] referenced one or more files that do not exist
I am having a problem with Java 11/Spring Boot 2.1 migration where the project compiles but when run returns only:

```<code>Connected to the target VM, address: '127.0.0.1:5754', transport: 'socket'
The Class-Path manifest attribute in C:\Users\{user}\.m2\repository\xalan\serializer\2.7.2\serializer-2.7.2.jar referenced one or more files that do not exist:
file:/C:/Users/{user}/.m2/repository/xalan/serializer/2.7.2/xml-apis.jar
The Class-Path manifest attribute in C:\Users\{user}\.m2\repository\xalan\xalan\2.7.2\xalan-2.7.2.jar referenced one or more files that do not exist:
file:/C:/Users/{user}/.m2/repository/xalan/xalan/2.7.2/xercesImpl.jar,file:/C:/Users/{user}/.m2/repository/xalan/xalan/2.7.2/xml-apis.jar,file:/C:/Users/{user}/.m2/repository/xalan/xalan/2.7.2/serializer.jar
Disconnected from the target VM, address: '127.0.0.1:5754', transport: 'socket'

Process finished with exit code 1
</code>```

I have tried updating maven versions, maven compiler version, etc.

How do I fix this?

答:
I had a similar problem after changing my logback-spring.xml file.

The application wouldn't start anymore and I could only see some INFO messages like those you described but that wasn't the actual cause of the problem.

The application was failing after that point but couldn't log any erros messages exactly because of a issue in my logback-spring.xml.

So if you don't see any other error messages, try to double check that your logging mechanism is configured correctly.

Body:
I am having a problem with Java 11/Spring Boot 2.1 migration where the project compiles but when run returns only:

Connected to the target VM, address: '127.0.0.1:5754', transport: 'socket'
The Class-Path manifest attribute in C:\Users\{user}\.m2\repository\xalan\serializer\2.7.2\serializer-2.7.2.jar referenced one or more files that do not exist:
file:/C:/Users/{user}/.m2/repository/xalan/serializer/2.7.2/xml-apis.jar
The Class-Path manifest attribute in C:\Users\{user}\.m2\repository\xalan\xalan\2.7.2\xalan-2.7.2.jar referenced one or more files that do not exist:
file:/C:/Users/{user}/.m2/repository/xalan/xalan/2.7.2/xercesImpl.jar,file:/C:/Users/{user}/.m2/repository/xalan/xalan/2.7.2/xml-apis.jar,file:/C:/Users/{user}/.m2/repository/xalan/xalan/2.7.2/serializer.jar
Disconnected from the target VM, address: '127.0.0.1:5754', transport: 'socket'

Process finished with exit code 1

I have tried updating maven versions, maven compiler version, etc.

How do I fix this?


来源: stackexchange

问:
How to bind SelectionChanged Event to Visibility Property on other Element in XAML Only
Given is an ComboBox after SelectionChanged should become an TextBlock visible. I build this functionality using ViemModel.

View:

```<code><ComboBox SelectionChanged="{mvvmHelper:EventBinding OnSelectionChanged}" />
<TextBlock Visibility="{Binding LanguageChanged, Converter={StaticResource BooleanVisibilityConverter}}"/>
</code>```

ViewModel:

```<code>bool LanguageChanged = false;

void OnSelectionChanged() => LanguageChanged = true;
</code>```

I looking for a elegant solution done in XAML only

What i try so far:

```<code><Style TargetType="{x:Type TextBlock}">
    <Setter Property="Visibility" Value="Collapsed" />
    <Style.Triggers>
        <DataTrigger Binding="{Binding IsDropDownOpen, ElementName=Box, Mode=OneWay, UpdateSourceTrigger=PropertyChanged}" Value="True">
            <Setter Property="Visibility" Value="Visible" />
        </DataTrigger>
    </Style.Triggers>
</Style>
</code>```

I guess I have to use Storyboard

```<code><ComboBox.Style>
    <Style TargetType="{x:Type ComboBox}">
        <Style.Triggers>
            <EventTrigger RoutedEvent="SelectionChanged">
                <BeginStoryboard>
                    <Storyboard>
                        ???
                    </Storyboard>
                </BeginStoryboard>
            </EventTrigger>
        </Style.Triggers>
    </Style>
</ComboBox.Style>
</code>```

the other option would be System.Windows.Interactivity but this is not available in WpfCore 3.1

答:
I feel like @BionicCode has given quite the comprehensive answer, but I'll add my 2¢.

The best solution that meets your requirements I think is the style trigger.

I see that Bionic included that, but here is an MCVE:

```<code><Window x:Class="project-name.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="120" Width="300">
    <StackPanel HorizontalAlignment="Left" VerticalAlignment="Top" Margin="15,15,0,0">
        <StackPanel Orientation="Horizontal">
            <TextBlock Text="Language:   " VerticalAlignment="Center"/>
            <ComboBox x:Name="LanguageCB" HorizontalAlignment="Left" SelectedIndex="0">
                <ComboBoxItem Content="None ?"/>
                <ComboBoxItem Content="English"/>
            </ComboBox>
        </StackPanel>
        <Border Margin="0,10,0,0" BorderThickness="1" BorderBrush="Black" Padding="2">
            <TextBlock Text="Becomes visible when "LanguageCB" changes selection">
                <TextBlock.Style>
                    <Style TargetType="{x:Type TextBlock}">
                        <Setter Property="Visibility" Value="Hidden"/>
                        <Style.Triggers>
                            <DataTrigger Binding="{Binding ElementName=LanguageCB, Path=SelectedIndex}" Value="1">
                                <Setter Property="Visibility" Value="Visible"/>
                            </DataTrigger>
                        </Style.Triggers>
                    </Style>
                </TextBlock.Style>
            </TextBlock>
        </Border>
    </StackPanel>
</Window>
</code>```

However... If you are really doing localization in your application and not just using this as an example, then I think there is a better solution.

First take a few minutes to read about WPF Globalization and Localization.

Then add at least 1 language resource file to your project's properties (for example 'Resources.ja-JP.resx', and don't forget to mark your Resources.resx file to public. Put some localized strings in these .resx files.

Then bind your TextBlock's text to the property:

```<code><TextBlock Text="{Binding Path=ResourceName, Source={StaticResource Resources}}"/>
</code>```

Next you need some code to handle switching cultures.
There a lots of options here, but I'll include some code I've used in the past.

CultureResources.cs

namespace Multi_Language_Base_App.Cultures
{
    using System;
    using System.Collections.Generic;
    using System.Globalization;
    using System.IO;
    using System.Diagnostics;
    using System.Windows.Data;

    ///
    /// Wraps up XAML access to instance of Properties.Resources,
    /// list of available cultures, and method to change culture
    public class CultureResources
    {
        private static ObjectDataProvider provider;

        public static event EventHandler<EventArgs> CultureUpdateEvent;

        //only fetch installed cultures once
        private static bool bFoundInstalledCultures = false;

        private static List<CultureInfo> pSupportedCultures = new List<CultureInfo>();
        ///
        /// List of available cultures, enumerated at startup
        ///
        public static List<CultureInfo> SupportedCultures
        {
            get { return pSupportedCultures; }
        }

        public CultureResources()
        {
            if (!bFoundInstalledCultures)
            {
                //determine which cultures are available to this application
                Debug.WriteLine("Get Installed cultures:");
                CultureInfo tCulture = new CultureInfo("");

                foreach (string dir in Directory.GetDirectories(AppDomain.CurrentDomain.BaseDirectory))
                {
                    try
                    {
                        //see if this directory corresponds to a valid culture name
                        DirectoryInfo dirinfo = new DirectoryInfo(dir);
                        tCulture = CultureInfo.GetCultureInfo(dirinfo.Name);

                        //determine if a resources dll exists in this directory that matches the executable name
                        string exe = System.Reflection.Assembly.GetExecutingAssembly().Location;

                        if (dirinfo.GetFiles(Path.GetFileNameWithoutExtension(exe) + ".resources.dll").Length > 0)
                        {
                            pSupportedCultures.Add(tCulture);
                            Debug.WriteLine(string.Format(" Found Culture: {0} [{1}]", tCulture.DisplayName, tCulture.Name));
                        }
                    }
                    catch (ArgumentException) //ignore exceptions generated for any unrelated directories in the bin folder
                    {
                    }
                }
                bFoundInstalledCultures = true;
            }
        }

        ///
        /// The Resources ObjectDataProvider uses this method to get
        /// an instance of the _This Application Namespace_.Properties.Resources class
        ///
        public Properties.Resources GetResourceInstance()
        {
            return new Properties.Resources();
        }

        public static ObjectDataProvider ResourceProvider
        {
            get
            {
                if (provider == null)
                    provider = (ObjectDataProvider)App.Current.FindResource("Resources");
                return provider;
            }
        }

        ///
        /// Change the current culture used in the application.
        /// If the desired culture is available all localized elements are updated.
        ///
        /// <param name="culture">Culture to change to</param>
        public static void ChangeCulture(CultureInfo culture)
        {
            // Remain on the current culture if the desired culture cannot be found
            // - otherwise it would revert to the default resources set, which may or may not be desired.
            if (pSupportedCultures.Contains(culture))
            {
                Properties.Resources.Culture = culture;
                ResourceProvider.Refresh();

                RaiseCultureUpdateEvent(null, new EventArgs());

                Debug.WriteLine(string.Format("Culture changed to [{0}].", culture.NativeName));
            }
            else
            {
                Debug.WriteLine(string.Format("Culture [{0}] not available", culture));
            }
        }

        private static void RaiseCultureUpdateEvent(object sender, EventArgs e)
        {
            EventHandler<EventArgs> handleit = CultureUpdateEvent;
            CultureUpdateEvent?.Invoke(sender, e);
        }

    }
}
```
<p>The last piece of the puzzle should be a way to provide access to the culture resources from xaml. This is done using an ObjectDataProvider.</p>
<p>You can put this directly in App.xaml or a separate file and reference it in App.xaml.</p>
```<ResourceDictionary
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:Cultures="clr-namespace:Multi_Language_Base_App.Cultures">

    <ObjectDataProvider x:Key="Resources"
                        ObjectType="{x:Type Cultures:CultureResources}"
                        MethodName="GetResourceInstance"/>

    <ObjectDataProvider x:Key="CultureResourcesDS"
                        ObjectType="{x:Type Cultures:CultureResources}"/>

</ResourceDictionary>
```
<p>When you do this, your string bindings can automatically match the system culture from the get-go (or else end up as the defaults in your generic resources). Also the user can switch the culture on the fly.</p>
<p>In your example, the ComboBox SelectionChanged event would be used as a starting point to change the culture like this:</p>
```CultureInfo CultureJapanese = new CultureInfo("ja-JP");
Cultures.CultureResources.ChangeCulture(CultureJapanese);
```

I prefer to use commanding to get this done, but it's up to you.

ContentLicense: CC BY-SA 4.0

Body:
Given is an ComboBox after SelectionChanged should become an TextBlock visible. I build this functionality using ViemModel.

View:

<ComboBox SelectionChanged="{mvvmHelper:EventBinding OnSelectionChanged}" />
<TextBlock Visibility="{Binding LanguageChanged, Converter={StaticResource BooleanVisibilityConverter}}"/>

ViewModel:

bool LanguageChanged = false;

void OnSelectionChanged() => LanguageChanged = true;

I looking for a elegant solution done in XAML only

What i try so far:

</Style>

I guess I have to use Storyboard

<ComboBox.Style>

    </Style>
</ComboBox.Style>

the other option would be System.Windows.Interactivity but this is not available in WpfCore 3.1

Body:
I feel like @BionicCode has given quite the comprehensive answer, but I'll add my 2¢.

The best solution that meets your requirements I think is the style trigger.

I see that Bionic included that, but here is an MCVE:

<Window x:Class="project-name.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="120" Width="300">
    <StackPanel HorizontalAlignment="Left" VerticalAlignment="Top" Margin="15,15,0,0">
        <StackPanel Orientation="Horizontal">
            <TextBlock Text="Language:   " VerticalAlignment="Center"/>
            <ComboBox x:Name="LanguageCB" HorizontalAlignment="Left" SelectedIndex="0">
                <ComboBoxItem Content="None ?"/>
                <ComboBoxItem Content="English"/>
            </ComboBox>
        </StackPanel>
        <Border Margin="0,10,0,0" BorderThickness="1" BorderBrush="Black" Padding="2">
            <TextBlock Text="Becomes visible when &quot;LanguageCB&quot; changes selection">
                <TextBlock.Style>
                    <Style TargetType="{x:Type TextBlock}">
                        <Setter Property="Visibility" Value="Hidden"/>
                        <Style.Triggers>
                            <DataTrigger Binding="{Binding ElementName=LanguageCB, Path=SelectedIndex}" Value="1">
                                <Setter Property="Visibility" Value="Visible"/>
                            </DataTrigger>
                        </Style.Triggers>
                    </Style>
                </TextBlock.Style>
            </TextBlock>
        </Border>
    </StackPanel>
</Window>

However... If you are really doing localization in your application and not just using this as an example, then I think there is a better solution.

First take a few minutes to read about WPF Globalization and Localization.

Then add at least 1 language resource file to your project's properties (for example 'Resources.ja-JP.resx', and don't forget to mark your Resources.resx file to public. Put some localized strings in these .resx files.

Then bind your TextBlock's text to the property:

<TextBlock Text="{Binding Path=ResourceName, Source={StaticResource Resources}}"/>

Next you need some code to handle switching cultures.
There a lots of options here, but I'll include some code I've used in the past.

CultureResources.cs

namespace Multi_Language_Base_App.Cultures
{
    using System;
    using System.Collections.Generic;
    using System.Globalization;
    using System.IO;
    using System.Diagnostics;
    using System.Windows.Data;

    /// <summary>
    /// Wraps up XAML access to instance of Properties.Resources,
    /// list of available cultures, and method to change culture </summary>
    public class CultureResources
    {
        private static ObjectDataProvider provider;

        public static event EventHandler<EventArgs> CultureUpdateEvent;

        //only fetch installed cultures once
        private static bool bFoundInstalledCultures = false;

        private static List<CultureInfo> pSupportedCultures = new List<CultureInfo>();
        /// <summary>
        /// List of available cultures, enumerated at startup
        /// </summary>
        public static List<CultureInfo> SupportedCultures
        {
            get { return pSupportedCultures; }
        }

        public CultureResources()
        {
            if (!bFoundInstalledCultures)
            {
                //determine which cultures are available to this application
                Debug.WriteLine("Get Installed cultures:");
                CultureInfo tCulture = new CultureInfo("");

                foreach (string dir in Directory.GetDirectories(AppDomain.CurrentDomain.BaseDirectory))
                {
                    try
                    {
                        //see if this directory corresponds to a valid culture name
                        DirectoryInfo dirinfo = new DirectoryInfo(dir);
                        tCulture = CultureInfo.GetCultureInfo(dirinfo.Name);

                        //determine if a resources dll exists in this directory that matches the executable name
                        string exe = System.Reflection.Assembly.GetExecutingAssembly().Location;

                        if (dirinfo.GetFiles(Path.GetFileNameWithoutExtension(exe) + ".resources.dll").Length > 0)
                        {
                            pSupportedCultures.Add(tCulture);
                            Debug.WriteLine(string.Format(" Found Culture: {0} [{1}]", tCulture.DisplayName, tCulture.Name));
                        }
                    }
                    catch (ArgumentException) //ignore exceptions generated for any unrelated directories in the bin folder
                    {
                    }
                }
                bFoundInstalledCultures = true;
            }
        }

        /// <summary>
        /// The Resources ObjectDataProvider uses this method to get
        /// an instance of the _This Application Namespace_.Properties.Resources class
        /// </summary>
        public Properties.Resources GetResourceInstance()
        {
            return new Properties.Resources();
        }

        public static ObjectDataProvider ResourceProvider
        {
            get
            {
                if (provider == null)
                    provider = (ObjectDataProvider)App.Current.FindResource("Resources");
                return provider;
            }
        }

        /// <summary>
        /// Change the current culture used in the application.
        /// If the desired culture is available all localized elements are updated.
        /// </summary>
        /// <param name="culture">Culture to change to</param>
        public static void ChangeCulture(CultureInfo culture)
        {
            // Remain on the current culture if the desired culture cannot be found
            // - otherwise it would revert to the default resources set, which may or may not be desired.
            if (pSupportedCultures.Contains(culture))
            {
                Properties.Resources.Culture = culture;
                ResourceProvider.Refresh();

                RaiseCultureUpdateEvent(null, new EventArgs());

                Debug.WriteLine(string.Format("Culture changed to [{0}].", culture.NativeName));
            }
            else
            {
                Debug.WriteLine(string.Format("Culture [{0}] not available", culture));
            }
        }

        private static void RaiseCultureUpdateEvent(object sender, EventArgs e)
        {
            EventHandler<EventArgs> handleit = CultureUpdateEvent;
            CultureUpdateEvent?.Invoke(sender, e);
        }

    }
}

The last piece of the puzzle should be a way to provide access to the culture resources from xaml. This is done using an ObjectDataProvider.

You can put this directly in App.xaml or a separate file and reference it in App.xaml.

<ResourceDictionary
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:Cultures="clr-namespace:Multi_Language_Base_App.Cultures">
    <!-- Contains the current instance of the ProjectName.Properties.Resources class.
         Used in bindings to get localized strings and automatic updates when the culture is updated -->
    <ObjectDataProvider x:Key="Resources"
                        ObjectType="{x:Type Cultures:CultureResources}"
                        MethodName="GetResourceInstance"/>

    <!-- Provides access to list of currently available cultures -->
    <ObjectDataProvider x:Key="CultureResourcesDS"
                        ObjectType="{x:Type Cultures:CultureResources}"/>

</ResourceDictionary>

When you do this, your string bindings can automatically match the system culture from the get-go (or else end up as the defaults in your generic resources). Also the user can switch the culture on the fly.

In your example, the ComboBox SelectionChanged event would be used as a starting point to change the culture like this:

CultureInfo CultureJapanese = new CultureInfo("ja-JP");
Cultures.CultureResources.ChangeCulture(CultureJapanese);

I prefer to use commanding to get this done, but it's up to you.


问:
Odd casting issue

Odd Casting Issue

To conserve time, I'm going to skip directly to the question.

While in one of my return functions, I've set up a reference by making a using statement like so:

Example: using T = int( __thiscall* )( void* );

Now, within this statement I have a return which will in return gather an offset from returning the reference type pointer:

Example: return ( *reinterpret_cast< T** >( this ) )[0X0]( this );

When I use the reference utilizing my using statement, then the operation returns successful and my function will work correctly. However, when not using the statement and assessing the reference native, my compiler will throw some tokens back at me stating that it can't be processed.

Example of what I'm attempting to do: return ( *reinterpret_cast< int( __thiscall* )( void* )** >( this ) )[0X0]( this );

Is there something I'm missing, or is this just not possible?

答:
As purely a syntax question and without delving into exactly why you're doing this, the syntax for pointer-to-pointer-to-pointer-to-function is to increase the number of * qualifiers where you would normally put just one:

```<code>return ( *reinterpret_cast< int( __thiscall*** )( void* ) >( this ) )[0X0]( this );
                                           ^^^
</code>```

Rather than just tacking them on the end -- that works for a type alias but not in a multi-level pointer-to-function type.

Title: Odd casting issue

Body:
As purely a syntax question and without delving into exactly why you're doing this, the syntax for pointer-to-pointer-to-pointer-to-function is to increase the number of * qualifiers where you would normally put just one:

return ( *reinterpret_cast< int( __thiscall*** )( void* ) >( this ) )[0X0]( this );
                                           ^^^

Rather than just tacking them on the end -- that works for a type alias but not in a multi-level pointer-to-function type.


问:
XML Tag grouping in RTF Template to suppress duplicates
My XML Tag generated is as follows-

```<code><P_MONTH>01</P_MONTH>

-<G_1>

<DIVISION>CA Division</DIVISION>

<DISTRICT>CA District</DISTRICT>

<DEPARTMENT>Global Operations</DEPARTMENT>

<DEP_EMPL_COUNT>9</DEP_EMPL_COUNT>

</G_1>

-<G_1>

<DIVISION>CA Division</DIVISION>

<DISTRICT>CA District</DISTRICT>

<DEPARTMENT>Laboratory Services</DEPARTMENT>

<DEP_EMPL_COUNT>11</DEP_EMPL_COUNT>

</G_1>

-<G_1>

<DIVISION>CA Division</DIVISION>

<DISTRICT>CA District</DISTRICT>

<DEPARTMENT>Corporate</DEPARTMENT>

<DEP_EMPL_COUNT>3</DEP_EMPL_COUNT>

</G_1>

-<G_1>

<DIVISION>CA Division</DIVISION>

<DISTRICT>S District</DISTRICT>

<DEPARTMENT>Corporate Administration</DEPARTMENT>

<DEP_EMPL_COUNT>6</DEP_EMPL_COUNT>

</G_1>

-<G_1>

<DIVISION>CA Division</DIVISION>

<DISTRICT>S District</DISTRICT>

<DEPARTMENT>Corporate Technology</DEPARTMENT>

<DEP_EMPL_COUNT>1</DEP_EMPL_COUNT>

</G_1>
</code>```

When I am using these tag like below in the RTF template-

```<code>DIVISION                            DISTRICT                    DEPARTMENT                 COUNT
<?for-each:G_1?> <DIVISION>         <DISTRICT>                   <DEPARTMENT>             <COUNT> <?end for-each?>
</code>```

This is giving an output like -

```<code>DIVISION              DISTRICT                          DEPARTMENT                      COUNT
CA Division           CA District                     Global Operations                  9
CA Division           CA District                     Laboratory Services                11
CA Division           CA District                     Corporate                          3
CA Division           S District                      Corporate Administration           6
CA Division           S District                      Corporate Technology               1
</code>```

I want the repeated values in division and district to be suppressed and the output to look like -

```<code>DIVISION              DISTRICT                          DEPARTMENT                      COUNT
CA Division           CA District                     Global Operations                  9
                                                      Laboratory Services                11
                                                      Corporate                          3
                      S District                      Corporate Administration           6
                                                      Corporate Technology               1
</code>```

How can this be achieved ? I am not being able to use for-each-group properly to group the tags. Can someone please help ?

答:
I'd use nested tables and for-each-group functionality.

RTF:

Output

Body:
My XML Tag generated is as follows-

<P_MONTH>01</P_MONTH>

-<G_1>

<DIVISION>CA Division</DIVISION>

<DISTRICT>CA District</DISTRICT>

<DEPARTMENT>Global Operations</DEPARTMENT>

<DEP_EMPL_COUNT>9</DEP_EMPL_COUNT>

</G_1>

-<G_1>

<DIVISION>CA Division</DIVISION>

<DISTRICT>CA District</DISTRICT>

<DEPARTMENT>Laboratory Services</DEPARTMENT>

<DEP_EMPL_COUNT>11</DEP_EMPL_COUNT>

</G_1>

-<G_1>

<DIVISION>CA Division</DIVISION>

<DISTRICT>CA District</DISTRICT>

<DEPARTMENT>Corporate</DEPARTMENT>

<DEP_EMPL_COUNT>3</DEP_EMPL_COUNT>

</G_1>

-<G_1>

<DIVISION>CA Division</DIVISION>

<DISTRICT>S District</DISTRICT>

<DEPARTMENT>Corporate Administration</DEPARTMENT>

<DEP_EMPL_COUNT>6</DEP_EMPL_COUNT>

</G_1>

-<G_1>

<DIVISION>CA Division</DIVISION>

<DISTRICT>S District</DISTRICT>

<DEPARTMENT>Corporate Technology</DEPARTMENT>

<DEP_EMPL_COUNT>1</DEP_EMPL_COUNT>

</G_1>

When I am using these tag like below in the RTF template-

DIVISION                            DISTRICT                    DEPARTMENT                 COUNT
<?for-each:G_1?> <DIVISION>         <DISTRICT>                   <DEPARTMENT>             <COUNT> <?end for-each?>

This is giving an output like -

DIVISION              DISTRICT                          DEPARTMENT                      COUNT
CA Division           CA District                     Global Operations                  9
CA Division           CA District                     Laboratory Services                11
CA Division           CA District                     Corporate                          3
CA Division           S District                      Corporate Administration           6
CA Division           S District                      Corporate Technology               1

I want the repeated values in division and district to be suppressed and the output to look like -

DIVISION              DISTRICT                          DEPARTMENT                      COUNT
CA Division           CA District                     Global Operations                  9
                                                      Laboratory Services                11
                                                      Corporate                          3
                      S District                      Corporate Administration           6
                                                      Corporate Technology               1

How can this be achieved ? I am not being able to use for-each-group properly to group the tags. Can someone please help ?


问:
Pandas: use groupby to sum while aggregating certain values
I have the following pandas dataframe:

      Pasture  Surface
Farm
01     Sown 1        2
01     Sown 2        3
01    Natural        3
01        Hay        5
02       Sown        7
```

<p>I'd like to group over the farm, in a way that for each farm there will be only 2 pasture values, <code>sown</code> and <code>not sown</code>, with the first having the sum of the surfaces that have "Sown" in the relative <code>Pasture</code> value and the second the sum of all the others. Basically what I want to obtain is:
</p>

```      Pasture  Surface
Farm
01       Sown        5
     Not sown        8
02       Sown        7
```

I managed to do it by replacing the names before with the relative one and then using .groupby(), but I was wondering if there was a way to it all in a .groupby() call, or in any case which would be the best way. Thanks!

(P.S.: this is my first question on Stack Overflow, please let me know if I could have done something better!)

答:
I would do:

```<code>sown_or_not = np.where(df.Pasture.str.contains('Sown'), 'Sown', 'Not Sown')

df.groupby(['Farm', sown_or_not]).Surface.sum()
</code>```

Output:

```<code>Farm
1     Not Sown    8
      Sown        5
2     Sown        7
Name: Surface, dtype: int64
</code>```

Body:
I have the following pandas dataframe:

      Pasture  Surface
Farm
01     Sown 1        2
01     Sown 2        3
01    Natural        3
01        Hay        5
02       Sown        7

I'd like to group over the farm, in a way that for each farm there will be only 2 pasture values, sown and not sown, with the first having the sum of the surfaces that have "Sown" in the relative Pasture value and the second the sum of all the others. Basically what I want to obtain is:

      Pasture  Surface
Farm
01       Sown        5
     Not sown        8
02       Sown        7

I managed to do it by replacing the names before with the relative one and then using .groupby(), but I was wondering if there was a way to it all in a .groupby() call, or in any case which would be the best way. Thanks!

(P.S.: this is my first question on Stack Overflow, please let me know if I could have done something better!)

Body:
I would do:

sown_or_not = np.where(df.Pasture.str.contains('Sown'), 'Sown', 'Not Sown')

df.groupby(['Farm', sown_or_not]).Surface.sum()

Output:

Farm
1     Not Sown    8
      Sown        5
2     Sown        7
Name: Surface, dtype: int64


问:
YUV_420_888 (byte) format
I capture an image on Android in YUV_420_888 format (YCbCr).

Image dimension is 4032 X 3024 and I get three planes from the ImageReader.

Y with 12192768 bytes

  U with 6096383 bytes

  V with 6096383 bytes

My understanding is that for every pixel in Y there is a corresponding value in U/V planes with 2:1 ratio (2 pixel Y correspond to one pixel U/V).

But doing the math 12192768/2 there is one byte missing in U/V plane.

Why is that one byte missing? How is the relation between Y and U/V for Android camera2 YUV_420_888.

答:
Okay Let's try this again.  Originally I asked if anyone had found an answer as I was also looking for resolution on this. Finally though I've been able to figure our the answer to this question:

The answer lies in the image acquisition format.  Android till default to a NV21 format, meaning a V byte followed by a U byte interwoven plane after the Y plane.  NV12 is an alternate that has the U byte prior to the V byte (see: How to render Android's YUV-NV21 camera image on the background in libgdx with OpenGLES 2.0 in real-time?)

The Image object returned by the ImageReader then creates a ByteBuffer which directly access's this memory location.  Calling isDirect() on the ByteBuffer verifies this. You can also see this by modifying vBuffer (getPlane()[2]) index 1.  Since index 1 of the vBuffer points to the same memory location of uBuffer index 0, the uBuffer.get(0) will be the same.

Thus the UV plane, VU plane for NV21, is equal to Y-plane/2=length (as noted 6096384 in the example above). If you start with the first V (VU-plane[0]) and count to the last V (VU-plane[length-1]), it will be one less because the last byte in this plane is U.  Likewise the first U byte is at index 1 of the VU-plane until VU-plane[length].

Here is an image that hopefully visually explains the above wording:

This is all predicated on the fact that the image is captured in NV21 format and not NV12, or Y12.  Here is another good visual for reference (https://www.twblogs.net/a/5d7ede57bd9eee541c3480f3)

Title: YUV_420_888 (byte) format


问:
Azure Functions (Durable) - Type is an interface or abstract class and cannot be instantiated
Problem
I have a C# Durable Azure Functions app (v2) containing an orchestration and activity function.

The orchestration calls the activity as follows:

```<code>propBag.CE = await context.CallActivityAsync<CEData>(nameof(GetCEByExternalIdActivity), propBag);
</code>```

The call works ok and the Activity function executes, builds up the content for propBag.CE and returns.

The CE object contains a few other objects, including:

```<code>        public List<IParty> Individuals { get; set; }
        public List<IParty> Organisations { get; set; }
</code>```

These properties are assigned to as follows:

```<code>        consPort.Individuals = await GetParties(clientRel.RelatedIndividuals, CEEntityType.Individual);
        consPort.Organisations = await GetParties(clientRel.RelatedOrganisations, CEEntityType.Organisation);
</code>```

The fact that it contains an Interface seems to give the Durable Functions runtime a problem. When it attempts to deserialize the value returned from the activity function, I get the following error:

Could not create an instance of type Interfaces.Avaloq.Application.Models.CE.IParty. Type is an interface or abstract class and cannot be instantiated

Does anyone know of a good fix for this? Maybe there's a way to configure how the function will attempt to deserialize the json?

Workaround
I worked-around the problem by changing the class to contain lists of the concrete types of IParty as follows:

```<code>        public List<Individual> Individuals { get; set; }
        public List<Organisation> Organisations { get; set; }
</code>```

I then had to ensure that I cast to the concrete type from the IParty before assigning to those properties, as follows:

```<code>var myList = (await GetParties(clientRel.RelatedIndividuals, CEEntityType.Individual));
        foreach (var party in myList)
        {
            consPort.Individuals.Add((Individual)party);
        }
        myList = (await GetParties(clientRel.RelatedOrganisations, CEEntityType.Organisation));
        foreach (var party in myList)
        {
            consPort.Organisations.Add((Organisation)party);
        }
</code>```

Not pretty but gets me around the problem.

答: It looks like you're running into this issue on GitHub. In addition to your workaround, you can customize the serializer settings used by Durable Functions to include type information. There is another StackOverflow post which describes this and has an example.</p>

Body:
Problem
I have a C# Durable Azure Functions app (v2) containing an orchestration and activity function.

The orchestration calls the activity as follows:

propBag.CE = await context.CallActivityAsync<CEData>(nameof(GetCEByExternalIdActivity), propBag);

The call works ok and the Activity function executes, builds up the content for propBag.CE and returns.

The CE object contains a few other objects, including:

        public List<IParty> Individuals { get; set; }
        public List<IParty> Organisations { get; set; }

These properties are assigned to as follows:

        consPort.Individuals = await GetParties(clientRel.RelatedIndividuals, CEEntityType.Individual);
        consPort.Organisations = await GetParties(clientRel.RelatedOrganisations, CEEntityType.Organisation);

The fact that it contains an Interface seems to give the Durable Functions runtime a problem. When it attempts to deserialize the value returned from the activity function, I get the following error:

Could not create an instance of type Interfaces.Avaloq.Application.Models.CE.IParty. Type is an interface or abstract class and cannot be instantiated

Does anyone know of a good fix for this? Maybe there's a way to configure how the function will attempt to deserialize the json?

Workaround
I worked-around the problem by changing the class to contain lists of the concrete types of IParty as follows:

        public List<Individual> Individuals { get; set; }
        public List<Organisation> Organisations { get; set; }

I then had to ensure that I cast to the concrete type from the IParty before assigning to those properties, as follows:

var myList = (await GetParties(clientRel.RelatedIndividuals, CEEntityType.Individual));
        foreach (var party in myList)
        {
            consPort.Individuals.Add((Individual)party);
        }
        myList = (await GetParties(clientRel.RelatedOrganisations, CEEntityType.Organisation));
        foreach (var party in myList)
        {
            consPort.Organisations.Add((Organisation)party);
        }

Not pretty but gets me around the problem.


问:
Pass Symfony project to developer
I have moved my symfony website to production but I need to pass it back to developer. Someone could help me?

I have tried putting app_dev.php but I don't really know how.

I also have .env like this

###> symfony/framework-bundle ###
APP_ENV=dev
APP_SECRET=****************
#TRUSTED_PROXIES=127.0.0.0/8,10.0.0.0/8,172.16.0.0/12,192.168.0.0/16
#TRUSTED_HOSTS='^(localhost|example\.com)$'
###< symfony/framework-bundle ###
```

答:
```<code>APP_ENV=dev APP_DEBUG=1 php bin/console cache:clear
</code>```

This will switch you back to dev mode with debugging on, you can disable that (app_debug=0)

It's the same as moving to prod but in reverse.

Title: Pass Symfony project to developer

Body:
APP_ENV=dev APP_DEBUG=1 php bin/console cache:clear

This will switch you back to dev mode with debugging on, you can disable that (app_debug=0)

It's the same as moving to prod but in reverse.


问:
Dynamic scope for accessing Model Attributes
I'm currently using the mass assignment security baked into rails 3 to scope what level of users can update about their model.  For example this code allows me to protect attributes based on the user level.

```<code>  class Customer
    attr_accessor :name, :credit_rating

    attr_accessible :name
    attr_accessible :name, :credit_rating, :as => :admin
  end
</code>```

I would like to be able to use this same idea for which attributes appear when I do a find.  For example I would like to be able to say

```<code>Customer.all.as(:admin)
</code>```

and get back the credit rating.  Compare this to doing

```<code>Customer.all
</code>```

and getting back all the attributes except the credit_rating

Is this something rails supports and I've missed?

答:
attr_accessible is used to filter incoming attributes on mass assignment. This is a convenience method created so that a developer does not need to manually clean the incoming hash of params, something he does not control.

When displaying information a developer is in full control of what he/she desires to show, so there seems to be no reason to limit the read functionality.

However, rails allows you to "select" the attributes you desire in a query: see http://guides.rubyonrails.org/active_record_querying.html#selecting-specific-fields

You could easily create a scope with the name admin that would limit the selected values.

If you do not desire to have the full models, but only the values, you could use the generated sql. e:g.

```<code>ActiveRecord::Base.connection.select_values(Customer.select('name').to_sql)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm currently using the mass assignment security baked into rails 3 to scope what level of users can update about their model.  For example this code allows me to protect attributes based on the user level.

  class Customer
    attr_accessor :name, :credit_rating

    attr_accessible :name
    attr_accessible :name, :credit_rating, :as => :admin
  end

I would like to be able to use this same idea for which attributes appear when I do a find.  For example I would like to be able to say

Customer.all.as(:admin)

and get back the credit rating.  Compare this to doing

Customer.all

and getting back all the attributes except the credit_rating

Is this something rails supports and I've missed?

Body:
attr_accessible is used to filter incoming attributes on mass assignment. This is a convenience method created so that a developer does not need to manually clean the incoming hash of params, something he does not control.

When displaying information a developer is in full control of what he/she desires to show, so there seems to be no reason to limit the read functionality.

However, rails allows you to "select" the attributes you desire in a query: see http://guides.rubyonrails.org/active_record_querying.html#selecting-specific-fields

You could easily create a scope with the name admin that would limit the selected values.

If you do not desire to have the full models, but only the values, you could use the generated sql. e:g.

ActiveRecord::Base.connection.select_values(Customer.select('name').to_sql)


问:
Import Data into Cloud SQL Using Cloud SQL Client Connection Ended
I am trying to run a SQL script from MySQL workbench, and have it import data to Cloud SQL using Cloud SQL Client proxy. This SQL script is about 10 GB. I have tried this a few times, and it takes too long, and says the certification of the connection will expire soon. Soon after that, the so the connection ends, and I see an error on workbench saying lost connection to MySQL server.

Are there any suggestions on what I should do / do different?
I am not wanting to use Cloud SQL Buckets to import data, and hence am going the route of Cloud SQL Client.

答:
Your connection ended error can be due to many different reasons. One being your script is too large and is causing the connection to timeout. I would suggest splitting your script and importing them separately.

It is possible that the “certification of the connection will expire soon” error can be resolved by rotating your server certificates. You can find how to do that here: https://cloud.google.com/sql/docs/mysql/manage-ssl-instance#manage-server-certs


问:
Where is the correct place to initialize BigDecimal limit when using Puma
I have a rails initializer that sets the limit on Big Decimal

```<code>BigDecimal.limit(20)
</code>```

This is executed and seems to set the limit properly.

But when a web request comes in (I am using Puma), the limit does not appear to be set on the thread that handles the request.  The limit is set to 0 which is the default.

Is there somewhere else I should be setting the limit?

If you want to reproduce:

create a brand new rails app and add an initializer that sets limit

```<code>BigDecimal.limit(20)
puts "*** Set #{BigDecimal.limit}"
</code>```

in your application controller add

```<code>before_action :check_big_decimal

def check_big_decimal
  puts "***request #{BigDecimal.limit}"
end
</code>```

start your server, refresh page and make a request

You should see it set to 20 but then it is back to 0 when the request comes in.

答:
A hacky and not recommended way is by monkey patching the class. You can add this in an initializer

```<code>class BigDecimal
  def self.limit(val = 25)
    25
  end
end
</code>```

The question is, do you really really want to limit to 25 everywhere? if yes, then you can try this as a LAST RESORT, because I'm not sure about the side effects of hardcoding that value (and overriding that method at all)

Body:
I have a rails initializer that sets the limit on Big Decimal

BigDecimal.limit(20)

This is executed and seems to set the limit properly.

But when a web request comes in (I am using Puma), the limit does not appear to be set on the thread that handles the request.  The limit is set to 0 which is the default.

Is there somewhere else I should be setting the limit?

If you want to reproduce:

create a brand new rails app and add an initializer that sets limit

BigDecimal.limit(20)
puts "*** Set #{BigDecimal.limit}"

in your application controller add

before_action :check_big_decimal

def check_big_decimal
  puts "***request #{BigDecimal.limit}"
end

start your server, refresh page and make a request

You should see it set to 20 but then it is back to 0 when the request comes in.

Body:
A hacky and not recommended way is by monkey patching the class. You can add this in an initializer

class BigDecimal
  def self.limit(val = 25)
    25
  end
end

The question is, do you really really want to limit to 25 everywhere? if yes, then you can try this as a LAST RESORT, because I'm not sure about the side effects of hardcoding that value (and overriding that method at all)


问:
“MSXML2.ServerXMLHTTP” request returns NULL in SQL Server
That's my first time trying to implement HTTP requests in SQL Server to get a JSON object and insert in my DB, but for some rease is always returning NULL for me.

I'm using Json placeholder to test it but no success.

```<code>sp_configure 'show advanced options', 1;
GO
RECONFIGURE;
GO
sp_configure 'Ole Automation Procedures', 1;
GO
RECONFIGURE;
GO

Declare @Object as Int;
Declare @ResponseText as Varchar(max);
Declare @Body as varchar(max);

Exec sp_OACreate 'MSXML2.ServerXMLHTTP', @Object OUT;
EXEC  sp_OAMethod @Object, 'open', NULL, 'get','https://jsonplaceholder.typicode.com/todos', 'false'

Exec sp_OAMethod @Object, 'setRequestHeader', null, 'Content-Type', 'application/json'
Exec sp_OAMethod @Object, 'send', null, @body

Exec sp_OAMethod @Object, 'responseText', @ResponseText OUTPUT
Select @ResponseText as response
</code>```

Response:

答:
Use

Declare @ResponseText as Varchar(8000);
```

<p>or</p>

<pre class="lang-sql prettyprint-override"><code>Declare @ResponseText as NVarchar(4000);
</code>```

instead of

Declare @ResponseText as Varchar(max);
```

Body:
That's my first time trying to implement HTTP requests in SQL Server to get a JSON object and insert in my DB, but for some rease is always returning NULL for me.

I'm using Json placeholder to test it but no success.

sp_configure 'show advanced options', 1;
GO
RECONFIGURE;
GO
sp_configure 'Ole Automation Procedures', 1;
GO
RECONFIGURE;
GO

Declare @Object as Int;
Declare @ResponseText as Varchar(max);
Declare @Body as varchar(max);

Exec sp_OACreate 'MSXML2.ServerXMLHTTP', @Object OUT;
EXEC  sp_OAMethod @Object, 'open', NULL, 'get','https://jsonplaceholder.typicode.com/todos', 'false'

Exec sp_OAMethod @Object, 'setRequestHeader', null, 'Content-Type', 'application/json'
Exec sp_OAMethod @Object, 'send', null, @body

Exec sp_OAMethod @Object, 'responseText', @ResponseText OUTPUT
Select @ResponseText as response

Response:

Body:
Use

Declare @ResponseText as Varchar(8000);

or

Declare @ResponseText as NVarchar(4000);

instead of

Declare @ResponseText as Varchar(max);


问:
How I can read and store the replies form Web activity (Post) - Azure datafactory
How I can read and store in database the replies form Web activity (Post)  . I would to check that post was successful

Please see attached the image for more easy detail

Thanks so much for your help
Javier

答:
I think in this case is better to user the Copy Data activity (https://learn.microsoft.com/en-us/azure/data-factory/copy-activity-overview), there you can define your Source Dataset and your Sink Dataset.

In your case the Source will be the HTTP request and the Sink will be the database, any type of the ones offer by Azure.

Please take into consideration the pagination support from the Copy Data activity.

Take care.


问:
How to ease-in y velocity of a game object in Unity?
I currently have a game object, and on a button press, I'm adding velocity on y axis, so the character jumps up... and this works as expected.

```<code>public float jumpForce

private void Jump()
{
    playerRigidbody.velocity = new Vector2(playerRigidbody.velocity.x, jumpForce);
    AudioManagerController.instance.PlaySfx(Util.AudioEffect.PlayerJump);
}
</code>```

However, this is pretty linear, the player jumps up with constant speed. I'd like to change it so that the player initially jumps up slow, gradually (exponentially? quickly? not sure what the right word is here) gains height quicker the longer the button is pressed.

Kind of like an ease-in:

I've tried increasing the velocity from 0 to jumpForce in update(), similar to:

```<code>jumpModifier = time.deltaTime; // In start()
...
jumpModifier = jumpModifier + time.deltaTime; // in update()
</code>```

I've tried a few variations of these and it doesn't quite do what I want it to do.

How do I make my character jump up in an ease-in sort of way please?

答:
EaseIn curve is the Cos+Lerp curve, or the "Coserp".</p>

```<code>//Ease in
public static float Coserp(float start, float end, float value)
{
    return Mathf.Lerp(start, end, 1.0f - Mathf.Cos(value * Mathf.PI * 0.5f));
}

public static Vector2 Coserp(Vector2 start, Vector2 end, float value)
{
    return new Vector2(Coserp(start.x,end.x,value),Coserp(start.y,end.y,value));
}

public static Vector3 Coserp(Vector3 start, Vector3 end, float value)
{
    return new Vector3(Coserp(start.x, end.x, value), Coserp(start.y, end.y, value), Coserp(start.z, end.z, value));
}
</code>```

Body:
I currently have a game object, and on a button press, I'm adding velocity on y axis, so the character jumps up... and this works as expected.

public float jumpForce

private void Jump()
{
    playerRigidbody.velocity = new Vector2(playerRigidbody.velocity.x, jumpForce);
    AudioManagerController.instance.PlaySfx(Util.AudioEffect.PlayerJump);
}

However, this is pretty linear, the player jumps up with constant speed. I'd like to change it so that the player initially jumps up slow, gradually (exponentially? quickly? not sure what the right word is here) gains height quicker the longer the button is pressed.

Kind of like an ease-in:

I've tried increasing the velocity from 0 to jumpForce in update(), similar to:

jumpModifier = time.deltaTime; // In start()
...
jumpModifier = jumpModifier + time.deltaTime; // in update()

I've tried a few variations of these and it doesn't quite do what I want it to do.

How do I make my character jump up in an ease-in sort of way please?

Body:
EaseIn curve is the Cos+Lerp curve, or the "Coserp".

//Ease in
public static float Coserp(float start, float end, float value)
{
    return Mathf.Lerp(start, end, 1.0f - Mathf.Cos(value * Mathf.PI * 0.5f));
}

public static Vector2 Coserp(Vector2 start, Vector2 end, float value)
{
    return new Vector2(Coserp(start.x,end.x,value),Coserp(start.y,end.y,value));
}

public static Vector3 Coserp(Vector3 start, Vector3 end, float value)
{
    return new Vector3(Coserp(start.x, end.x, value), Coserp(start.y, end.y, value), Coserp(start.z, end.z, value));
}


问:
Angular - How to get data from subscribed service few times and not overwrite previous results
I have a service which has following method:

room-service.ts

@Injectable()
export class RoomService {
  private readonly _equipment: BehaviorSubject<EquipmentDto[]> = new BehaviorSubject([]);
  public equipment$ = this._equipment.asObservable();

  getEquipmentForRoom(roomId: number) {
    this.restService.getEquipmentForRoom(roomId).subscribe(res => {
      this._equipment.next(res);
    });
  }
```

<p>room-component.ts:</p>

<pre class="lang-js prettyprint-override"><code>@Component()
export class RoomsComponent implements OnInit {
  @Input() room: RoomEntity;
  equipment$: Observable < EquipmentDto[] > ;
  equipmentList: Array < EquipmentDto > ;

  constructor(private equipmentService: EquipmentService) {}

  ngOnInit() {
      this.equipment$ = this.equipmentService.equipment$;
      this.equipmentService.getEquipmentForRoom(this.room.id);

      this.equipment$.subscribe(items => {
        this.equipmentList = items;
      });
</code>```

room-component.html

```

Now I have a parent component which contains multiple Room Components (those are added programmatically based on the amount of rooms). Anyway, list of equipment is the same for each of the rooms. It looks like once subscribed, the data in first components is overwritten by the component created as the last one.

My question is, how can I get a proper data for each of the rooms using the observable from my service?

答:
Adding onto Alexander’s answer.

The problem is that you are subscribing to the same BehaviourSubject for all the components and the components are taking the latest roomData that is emitted by the BehaviourSubject, which would be the last RoomComponent.

It would work if the BehaviuorSubject holds all the rooms which are fetched by the parent component, and passing each room data to each RoomComponent using @Input.

Body:
I have a service which has following method:

room-service.ts

@Injectable()
export class RoomService {
  private readonly _equipment: BehaviorSubject<EquipmentDto[]> = new BehaviorSubject([]);
  public equipment$ = this._equipment.asObservable();

  getEquipmentForRoom(roomId: number) {
    this.restService.getEquipmentForRoom(roomId).subscribe(res => {
      this._equipment.next(res);
    });
  }

room-component.ts:

@Component()
export class RoomsComponent implements OnInit {
  @Input() room: RoomEntity;
  equipment$: Observable < EquipmentDto[] > ;
  equipmentList: Array < EquipmentDto > ;

  constructor(private equipmentService: EquipmentService) {}

  ngOnInit() {
      this.equipment$ = this.equipmentService.equipment$;
      this.equipmentService.getEquipmentForRoom(this.room.id);

      this.equipment$.subscribe(items => {
        this.equipmentList = items;
      });

room-component.html

Now I have a parent component which contains multiple Room Components (those are added programmatically based on the amount of rooms). Anyway, list of equipment is the same for each of the rooms. It looks like once subscribed, the data in first components is overwritten by the component created as the last one.

My question is, how can I get a proper data for each of the rooms using the observable from my service?


问:
What is the file path location for QT Maintenance tool on Linux?
I have been searching and searching and cannot find where the QT Maintenance tool is located in Linux.

What is the default installation folder/file path for QT Maintenance tool for Ubuntu Linux distro.

答:
What is the default installation folder/file path for QT Maintenance tool for Ubuntu Linux distro?

As of Ubuntu 19.10, it is simply not contained in the Ubuntu repositories. You have basically two options:

Download the Qt Online Installer from the Qt website and use that to install a version of Qt for Android. The Qt Maintenance Tool will then be available at /opt/Qt/MaintenanceTool.

You can delete the version of Qt Creator installed by this process if you prefer to keep the version from the Ubuntu repositories: sudo rm -R /opt/Qt/Tools/QtCreator/

Or you could use aqtinstall, an unofficial Qt installer that can be used to install any Qt on any target platform. It's equivalent in function to the Qt Maintenance Tool while being equivalent in terms of interface to apt (means, it's a commandline tool rather than a GUI tool, allowing scripting with it).


问:
timer in thread problem
I have my application in which in three datagridview independently in three thread load data from wcf service. I execute in each thread timer which every second load this data.

My problem is that every time my thread go threw each thread but only like I show in method timerNowyYork_Elapsed

Any idea why this happens ? I bad lock thread?

this code :

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using System.Threading;

namespace Sprawdzanie_warunków_pogodowych
{
public partial class Form1 : Form
{
    PogodaEntities entity = new PogodaEntities();
    System.Timers.Timer timerKrakow = new System.Timers.Timer();
    System.Timers.Timer timerSzczecin = new System.Timers.Timer();
    System.Timers.Timer timerNowyYork = new System.Timers.Timer();
    KeyValuePair<string, string> krakowInfo;
    KeyValuePair<string, string> szczecinInfo;
    KeyValuePair<string, string> nowyYorkInfo;

    public Form1()
    {
        System.Net.ServicePointManager.Expect100Continue = false;
        InitializeComponent();
        List<MiastoContainer> miasta = (from miasto in entity.Miasta
                                        select new MiastoContainer()
                                   {
                                       MiastoName = miasto.Nazwa,
                                       Panstwo = miasto.Państwo
                                   }).ToList();
        krakowInfo = new KeyValuePair<string, string>(miasta[0].MiastoName, miasta[0].Panstwo);
        szczecinInfo = new KeyValuePair<string, string>(miasta[1].MiastoName, miasta[1].Panstwo);
        nowyYorkInfo = new KeyValuePair<string, string>(miasta[2].MiastoName, miasta[2].Panstwo);

        ParameterizedThreadStart ptsKrakow = new ParameterizedThreadStart(PobierzKrakow);
        Thread tKrakow = new Thread(ptsKrakow);
        tKrakow.Start(this.dataGridViewKrakow);

        ParameterizedThreadStart ptsSzczecin = new ParameterizedThreadStart(PobierzSzczecin);
        Thread tSzczecin = new Thread(ptsSzczecin);
        tSzczecin.Start(this.dataGridViewSzczecin);
    }

    private void oAutorzeToolStripMenuItem_Click(object sender, EventArgs e)
    {
        new AboutBox1().Show();
    }

    private void zapiszRaportToolStripMenuItem_Click(object sender, EventArgs e)
    {

    }

    public void PobierzKrakow(object parameters)
    {
        this.timerKrakow.Elapsed += new System.Timers.ElapsedEventHandler(timerKrakow_Elapsed);
        this.timerKrakow.Enabled = true;
        this.timerKrakow.Interval = 1000;
        this.timerKrakow.Start();
    }

    public void PobierzSzczecin(object parameters)
    {
        this.timerSzczecin.Elapsed += new System.Timers.ElapsedEventHandler(timerSzczecin_Elapsed);
        this.timerSzczecin.Enabled = true;
        this.timerSzczecin.Interval = 1000;
        this.timerSzczecin.Start();
    }

    public void PobierzNowyYork(object parameters)
    {
        this.timerNowyYork.Elapsed += new System.Timers.ElapsedEventHandler(timerNowyYork_Elapsed);
        this.timerNowyYork.Enabled = true;
        this.timerNowyYork.Interval = 1000;
        this.timerNowyYork.Start();
    }

    void timerNowyYork_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
    {  GlobalWeather.Weather weather = new GlobalWeather.Weather();
        lock (weather)
        {
            //thread always start from here
            List<object> weatherList = new List<object>();
            weatherList.Add(weather.GetTempreature(nowyYorkInfo.Key, nowyYorkInfo.Value));
           //and end here , never come any line further
            weatherList.Add(weather.GetPressure(nowyYorkInfo.Key, nowyYorkInfo.Value));
            weatherList.Add(weather.GetHumidity(nowyYorkInfo.Key, nowyYorkInfo.Value));
            weatherList.Add(weather.GetVisibility(nowyYorkInfo.Key, nowyYorkInfo.Value));
            entity.SaveChanges();

            WarunkiPogodowe warunki = new WarunkiPogodowe()
            {
                Temperatura = weatherList[0].ToString(),
                Ciśnienie = weatherList[1].ToString(),
                Wilgotność = weatherList[2].ToString(),
                Widoczność = weatherList[3].ToString(),
                DataSprawdzenia = DateTime.Now
            };
            entity.AddToWarunkiPogodowe(warunki);
            entity.SaveChanges();
            int miastoId = entity.Miasta.First(m => m.Nazwa == nowyYorkInfo.Key).id;
            Miasto_has_WarunkiPogodowe m_has_wp = new Miasto_has_WarunkiPogodowe()
            {
                idMiasto_FK = miastoId,
                idWarunkiPogodowe_FK = warunki.id
            };
            entity.AddToMiasto_has_WarunkiPogodowe(m_has_wp);
            entity.SaveChanges();

            this.dataGridViewNowyYork.Rows.Add(warunki);
        }
    }

    void timerSzczecin_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
    {
        GlobalWeather.Weather weather = new GlobalWeather.Weather();

        lock (weather)
        {
            List<object> weatherList = new List<object>();
            weatherList.Add(weather.GetTempreature(szczecinInfo.Key, szczecinInfo.Value));
            weatherList.Add(weather.GetPressure(szczecinInfo.Key, szczecinInfo.Value));
            weatherList.Add(weather.GetHumidity(szczecinInfo.Key, szczecinInfo.Value));
            weatherList.Add(weather.GetVisibility(szczecinInfo.Key, szczecinInfo.Value));
            entity.SaveChanges();

            WarunkiPogodowe warunki = new WarunkiPogodowe()
            {
                Temperatura = weatherList[0].ToString(),
                Ciśnienie = weatherList[1].ToString(),
                Wilgotność = weatherList[2].ToString(),
                Widoczność = weatherList[3].ToString(),
                DataSprawdzenia = DateTime.Now
            };
            entity.AddToWarunkiPogodowe(warunki);
            entity.SaveChanges();
            int miastoId = entity.Miasta.First(m => m.Nazwa == szczecinInfo.Key).id;
            Miasto_has_WarunkiPogodowe m_has_wp = new Miasto_has_WarunkiPogodowe()
            {
                idMiasto_FK = miastoId,
                idWarunkiPogodowe_FK = warunki.id
            };
            entity.AddToMiasto_has_WarunkiPogodowe(m_has_wp);
            entity.SaveChanges();

            this.dataGridViewSzczecin.Rows.Add(warunki);
        }
    }
    void timerKrakow_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
    {
        GlobalWeather.Weather weather = new GlobalWeather.Weather();

        lock (weather)
        {
            List<object> weatherList = new List<object>();
            weatherList.Add(weather.GetTempreature(krakowInfo.Key, krakowInfo.Value));
            weatherList.Add(weather.GetPressure(krakowInfo.Key, krakowInfo.Value));
            weatherList.Add(weather.GetHumidity(krakowInfo.Key, krakowInfo.Value));
            weatherList.Add(weather.GetVisibility(krakowInfo.Key, krakowInfo.Value));
            entity.SaveChanges();

            WarunkiPogodowe warunki = new WarunkiPogodowe()
            {
                Temperatura = weatherList[0].ToString(),
                Ciśnienie = weatherList[1].ToString(),
                Wilgotność = weatherList[2].ToString(),
                Widoczność = weatherList[3].ToString(),
                DataSprawdzenia = DateTime.Now
            };
            entity.AddToWarunkiPogodowe(warunki);
            entity.SaveChanges();
            int miastoId = entity.Miasta.First(m => m.Nazwa == krakowInfo.Key).id;
            Miasto_has_WarunkiPogodowe m_has_wp = new Miasto_has_WarunkiPogodowe()
            {
                idMiasto_FK = miastoId,
                idWarunkiPogodowe_FK = warunki.id
            };
            entity.AddToMiasto_has_WarunkiPogodowe(m_has_wp);
            entity.SaveChanges();

            this.dataGridViewKrakow.Rows.Add(warunki);
        }
    }
}

class MiastoContainer
{
    string miastoName;

    public string MiastoName
    {
        get { return miastoName; }
        set { miastoName = value; }
    }
    string panstwo;

    public string Panstwo
    {
        get { return panstwo; }
        set { panstwo = value; }
    }

    public MiastoContainer()
    { }

    public MiastoContainer(string miasto, string panstwo)
    {
        this.MiastoName = miasto;
        this.Panstwo = panstwo;
    }

    public void Add(MiastoContainer item)
    {
        ((ICollection<MiastoContainer>)this).Add(item);
    }

}
</code>```

}

答: I don't fully understand your question, but (unless I'm mistaken) the timer callbacks occur in the ThreadPool (or the GUI thread, dependent on usage), so starting them in different threads is pointless.</p>

Title: timer in thread problem

Body:
I have my application in which in three datagridview independently in three thread load data from wcf service. I execute in each thread timer which every second load this data.

My problem is that every time my thread go threw each thread but only like I show in method timerNowyYork_Elapsed

Any idea why this happens ? I bad lock thread?

this code :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using System.Threading;

namespace Sprawdzanie_warunków_pogodowych
{
public partial class Form1 : Form
{
    PogodaEntities entity = new PogodaEntities();
    System.Timers.Timer timerKrakow = new System.Timers.Timer();
    System.Timers.Timer timerSzczecin = new System.Timers.Timer();
    System.Timers.Timer timerNowyYork = new System.Timers.Timer();
    KeyValuePair<string, string> krakowInfo;
    KeyValuePair<string, string> szczecinInfo;
    KeyValuePair<string, string> nowyYorkInfo;

    public Form1()
    {
        System.Net.ServicePointManager.Expect100Continue = false;
        InitializeComponent();
        List<MiastoContainer> miasta = (from miasto in entity.Miasta
                                        select new MiastoContainer()
                                   {
                                       MiastoName = miasto.Nazwa,
                                       Panstwo = miasto.Państwo
                                   }).ToList();
        krakowInfo = new KeyValuePair<string, string>(miasta[0].MiastoName, miasta[0].Panstwo);
        szczecinInfo = new KeyValuePair<string, string>(miasta[1].MiastoName, miasta[1].Panstwo);
        nowyYorkInfo = new KeyValuePair<string, string>(miasta[2].MiastoName, miasta[2].Panstwo);

        ParameterizedThreadStart ptsKrakow = new ParameterizedThreadStart(PobierzKrakow);
        Thread tKrakow = new Thread(ptsKrakow);
        tKrakow.Start(this.dataGridViewKrakow);

        ParameterizedThreadStart ptsSzczecin = new ParameterizedThreadStart(PobierzSzczecin);
        Thread tSzczecin = new Thread(ptsSzczecin);
        tSzczecin.Start(this.dataGridViewSzczecin);
    }

    private void oAutorzeToolStripMenuItem_Click(object sender, EventArgs e)
    {
        new AboutBox1().Show();
    }

    private void zapiszRaportToolStripMenuItem_Click(object sender, EventArgs e)
    {

    }

    public void PobierzKrakow(object parameters)
    {
        this.timerKrakow.Elapsed += new System.Timers.ElapsedEventHandler(timerKrakow_Elapsed);
        this.timerKrakow.Enabled = true;
        this.timerKrakow.Interval = 1000;
        this.timerKrakow.Start();
    }

    public void PobierzSzczecin(object parameters)
    {
        this.timerSzczecin.Elapsed += new System.Timers.ElapsedEventHandler(timerSzczecin_Elapsed);
        this.timerSzczecin.Enabled = true;
        this.timerSzczecin.Interval = 1000;
        this.timerSzczecin.Start();
    }

    public void PobierzNowyYork(object parameters)
    {
        this.timerNowyYork.Elapsed += new System.Timers.ElapsedEventHandler(timerNowyYork_Elapsed);
        this.timerNowyYork.Enabled = true;
        this.timerNowyYork.Interval = 1000;
        this.timerNowyYork.Start();
    }

    void timerNowyYork_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
    {  GlobalWeather.Weather weather = new GlobalWeather.Weather();
        lock (weather)
        {
            //thread always start from here
            List<object> weatherList = new List<object>();
            weatherList.Add(weather.GetTempreature(nowyYorkInfo.Key, nowyYorkInfo.Value));
           //and end here , never come any line further
            weatherList.Add(weather.GetPressure(nowyYorkInfo.Key, nowyYorkInfo.Value));
            weatherList.Add(weather.GetHumidity(nowyYorkInfo.Key, nowyYorkInfo.Value));
            weatherList.Add(weather.GetVisibility(nowyYorkInfo.Key, nowyYorkInfo.Value));
            entity.SaveChanges();

            WarunkiPogodowe warunki = new WarunkiPogodowe()
            {
                Temperatura = weatherList[0].ToString(),
                Ciśnienie = weatherList[1].ToString(),
                Wilgotność = weatherList[2].ToString(),
                Widoczność = weatherList[3].ToString(),
                DataSprawdzenia = DateTime.Now
            };
            entity.AddToWarunkiPogodowe(warunki);
            entity.SaveChanges();
            int miastoId = entity.Miasta.First(m => m.Nazwa == nowyYorkInfo.Key).id;
            Miasto_has_WarunkiPogodowe m_has_wp = new Miasto_has_WarunkiPogodowe()
            {
                idMiasto_FK = miastoId,
                idWarunkiPogodowe_FK = warunki.id
            };
            entity.AddToMiasto_has_WarunkiPogodowe(m_has_wp);
            entity.SaveChanges();

            this.dataGridViewNowyYork.Rows.Add(warunki);
        }
    }

    void timerSzczecin_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
    {
        GlobalWeather.Weather weather = new GlobalWeather.Weather();

        lock (weather)
        {
            List<object> weatherList = new List<object>();
            weatherList.Add(weather.GetTempreature(szczecinInfo.Key, szczecinInfo.Value));
            weatherList.Add(weather.GetPressure(szczecinInfo.Key, szczecinInfo.Value));
            weatherList.Add(weather.GetHumidity(szczecinInfo.Key, szczecinInfo.Value));
            weatherList.Add(weather.GetVisibility(szczecinInfo.Key, szczecinInfo.Value));
            entity.SaveChanges();

            WarunkiPogodowe warunki = new WarunkiPogodowe()
            {
                Temperatura = weatherList[0].ToString(),
                Ciśnienie = weatherList[1].ToString(),
                Wilgotność = weatherList[2].ToString(),
                Widoczność = weatherList[3].ToString(),
                DataSprawdzenia = DateTime.Now
            };
            entity.AddToWarunkiPogodowe(warunki);
            entity.SaveChanges();
            int miastoId = entity.Miasta.First(m => m.Nazwa == szczecinInfo.Key).id;
            Miasto_has_WarunkiPogodowe m_has_wp = new Miasto_has_WarunkiPogodowe()
            {
                idMiasto_FK = miastoId,
                idWarunkiPogodowe_FK = warunki.id
            };
            entity.AddToMiasto_has_WarunkiPogodowe(m_has_wp);
            entity.SaveChanges();

            this.dataGridViewSzczecin.Rows.Add(warunki);
        }
    }
    void timerKrakow_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
    {
        GlobalWeather.Weather weather = new GlobalWeather.Weather();

        lock (weather)
        {
            List<object> weatherList = new List<object>();
            weatherList.Add(weather.GetTempreature(krakowInfo.Key, krakowInfo.Value));
            weatherList.Add(weather.GetPressure(krakowInfo.Key, krakowInfo.Value));
            weatherList.Add(weather.GetHumidity(krakowInfo.Key, krakowInfo.Value));
            weatherList.Add(weather.GetVisibility(krakowInfo.Key, krakowInfo.Value));
            entity.SaveChanges();

            WarunkiPogodowe warunki = new WarunkiPogodowe()
            {
                Temperatura = weatherList[0].ToString(),
                Ciśnienie = weatherList[1].ToString(),
                Wilgotność = weatherList[2].ToString(),
                Widoczność = weatherList[3].ToString(),
                DataSprawdzenia = DateTime.Now
            };
            entity.AddToWarunkiPogodowe(warunki);
            entity.SaveChanges();
            int miastoId = entity.Miasta.First(m => m.Nazwa == krakowInfo.Key).id;
            Miasto_has_WarunkiPogodowe m_has_wp = new Miasto_has_WarunkiPogodowe()
            {
                idMiasto_FK = miastoId,
                idWarunkiPogodowe_FK = warunki.id
            };
            entity.AddToMiasto_has_WarunkiPogodowe(m_has_wp);
            entity.SaveChanges();

            this.dataGridViewKrakow.Rows.Add(warunki);
        }
    }
}

class MiastoContainer
{
    string miastoName;

    public string MiastoName
    {
        get { return miastoName; }
        set { miastoName = value; }
    }
    string panstwo;

    public string Panstwo
    {
        get { return panstwo; }
        set { panstwo = value; }
    }

    public MiastoContainer()
    { }

    public MiastoContainer(string miasto, string panstwo)
    {
        this.MiastoName = miasto;
        this.Panstwo = panstwo;
    }

    public void Add(MiastoContainer item)
    {
        ((ICollection<MiastoContainer>)this).Add(item);
    }

}

}


问:
Using Go to generate hashed password strings suitable for `/etc/shadow`
The task in front of me is to take a user supplied plain-text string (i.e. a password), and turn it into something that can be inserted into /etc/shadow as the hashed password string such that a user could then log in with the password originally supplied to generate the hash.  This is a very common thing that we (re)solve over and over in the sysadmin world.  There are a myriad of command line utils for doing this.

In this specific case, however, my constraint is that I need a pure Go solution that I can use in multiple contexts (a cli tool, an api, etc).  My first attempt was just to use the bcrypt library.  At a glance it seemed to possess the attributes I required.  It's pure Go, it's super simple to use (bonus), and it generates output that looks about like what I was after ... but it didn't work.  The output resulting from use of this library cannot be (for example) pasted into /etc/shadow as a user's password and then the user successfully able to log in with the original password.

I'm just wondering if anyone has run across this need in their day to day and solved it, who is willing to share their experiences and (gasp) code?  I'm mainly wondering if there's a library targeting this approximate use-case someone would recommend?  (my google fu may just have 'rona).

答:
I'm sharing this here because the first thing I tried didn't work, and since I publicly asked, I felt it was fair to also publicly share the solution.  This is a solution, specific to my situation.  I'm not proclaiming it to be the solution, or that there aren't better solutions (please post those!).  For my specific situation, here's what I came up with ... [EDIT: please note that user Marc suggested looking at this library in a comment above while I was composing this.  Thank you, Marc, my fu is feeling better apparently]

As stated, my first attempt was just to use the bcrypt library, but it didn't work.  On closer examination, I found that bcrypt only output in one format (i.e. uses one algorithm for hashing), which is apparently NOT compatible with the password system in Linux (at least not my particular distro).  So while the output generally looked the way it should, the detail was:

bcrypt gives me something like: $2$10$sdfUILYhjd.HEdhjsdfgjhfdgjh.HEWjhndcjv

In that first field ($2), my distro of Linux does not support type $2 apparently (?) (widely supported ones are $1, $5, $6 (i.e. md5, sha256, and sha512)).  There didn't seem to be a way for me to specify a different algorithm in the bcrypt go library.  So, I cast about for other approaches/solutions.  What I arrived at was:

```<code>package main

import (
    "fmt"
    "math/rand"
    "os"
    "time"
    "github.com/tredoe/osutil/user/crypt/sha512_crypt"
)

func encryptPassword(userPassword string) string {
    // Generate a random string for use in the salt
    const charset = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
    seededRand := rand.New(rand.NewSource(time.Now().UnixNano()))
    s := make([]byte, 8)
    for i := range s {
        s[i] = charset[seededRand.Intn(len(charset))]
    }
    salt := []byte(fmt.Sprintf("$6$%s", s))
    // use salt to hash user-supplied password
    c := sha512_crypt.New()
    hash, err := c.Generate([]byte(userPassword), salt)
    if err != nil {
        fmt.Printf("error hashing user's supplied password: %s\n", err)
        os.Exit(1)
    }
    return string(hash)
}
</code>```

This function returns strings that look like:

$6$tZeuYPZ3$3mj70WOprJj5ytFFzC8gUFYk7eymQvaR4lDg5C0WzwBAMupRAan7BaC6EAbL9Eiyi2GZR6PQIQQa.y6kZLqh6

which you can simply paste directly into /etc/shadow or supply to an installer as a hashed password (kickstart, cloud-init, etc) and go about your business.  In my case, I'm writing a library function for an application that I can call from a command-line utility or from an api service that in turn supplies that hashed string as a parameter to cloud-init.

HTH others who may find this in the future.

Body:
I'm sharing this here because the first thing I tried didn't work, and since I publicly asked, I felt it was fair to also publicly share the solution.  This is a solution, specific to my situation.  I'm not proclaiming it to be the solution, or that there aren't better solutions (please post those!).  For my specific situation, here's what I came up with ... [EDIT: please note that user Marc suggested looking at this library in a comment above while I was composing this.  Thank you, Marc, my fu is feeling better apparently]

As stated, my first attempt was just to use the bcrypt library, but it didn't work.  On closer examination, I found that bcrypt only output in one format (i.e. uses one algorithm for hashing), which is apparently NOT compatible with the password system in Linux (at least not my particular distro).  So while the output generally looked the way it should, the detail was:

bcrypt gives me something like: $2$10$sdfUILYhjd.HEdhjsdfgjhfdgjh.HEWjhndcjv

In that first field ($2), my distro of Linux does not support type $2 apparently (?) (widely supported ones are $1, $5, $6 (i.e. md5, sha256, and sha512)).  There didn't seem to be a way for me to specify a different algorithm in the bcrypt go library.  So, I cast about for other approaches/solutions.  What I arrived at was:

package main

import (
    "fmt"
    "math/rand"
    "os"
    "time"
    "github.com/tredoe/osutil/user/crypt/sha512_crypt"
)

func encryptPassword(userPassword string) string {
    // Generate a random string for use in the salt
    const charset = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
    seededRand := rand.New(rand.NewSource(time.Now().UnixNano()))
    s := make([]byte, 8)
    for i := range s {
        s[i] = charset[seededRand.Intn(len(charset))]
    }
    salt := []byte(fmt.Sprintf("$6$%s", s))
    // use salt to hash user-supplied password
    c := sha512_crypt.New()
    hash, err := c.Generate([]byte(userPassword), salt)
    if err != nil {
        fmt.Printf("error hashing user's supplied password: %s\n", err)
        os.Exit(1)
    }
    return string(hash)
}

This function returns strings that look like:

$6$tZeuYPZ3$3mj70WOprJj5ytFFzC8gUFYk7eymQvaR4lDg5C0WzwBAMupRAan7BaC6EAbL9Eiyi2GZR6PQIQQa.y6kZLqh6

which you can simply paste directly into /etc/shadow or supply to an installer as a hashed password (kickstart, cloud-init, etc) and go about your business.  In my case, I'm writing a library function for an application that I can call from a command-line utility or from an api service that in turn supplies that hashed string as a parameter to cloud-init.

HTH others who may find this in the future.


问:
Regex: Handle an Optional url part with delimiter
I am trying to match some url which are built up like so:

```<code>https://tenantName-dev.somedomain.com/somefile.js
https://tenantName-qa.somedomain.com/somefile.js
https://tenantName.somedomain.com/somefile.js
</code>```

Note the last one that has no "environment" since it's prod.

my C# regex so far:

```<code>https://(?<tenantName>.+)-(?<environment>[^.]*).(?<rootDomain>[^/]+)/somefile.js
</code>```

This mostly works but would not match the last one as it always expects a '-'.
If I simply make that dash optinal, then it would match something like 'https://tenant-.somedomain...' which is not good.

I tried looking at lookaheads and non capturing groups to express the fact that I want a '-' only if there is a tenant behind but haven't been successful.

答:
In most flavors of regex (and in .Net's version) there is an conditional pattern which allows for a check such as if...then...else. This is done by (?({conditon})X|Y) where if the match condition is true X is done or if not then Y is done).

Test it out by doing this (note turn on the flag IgnorePatternWhitespace because I am commenting the regex):

```<code> (?(?:.+-)   # If a dash
  (?<A>.+)   # Match for dash
 |           # Else Then
  (?<B>.+)   # Match this
)
</code>```

So the condition is a lookahead which is ?:.+- which means somewhere ahead there is a -. If true match on and create a named capture group A. Otherwise create a match on group B.

So taking your pattern we can distill it down and just focus on the -. Such as

```<code>https://
(?(?:.+-)    # If a dash
  (
    (?<tenantName>[^-]+)-(?<environment>[^.]+)
  )
 |           # Else Then
  (
    (?<tenantName>[^.]+)
  )
)
\.(?<rootDomain>[^/]+)
</code>```

So if we dump the match when there is a - the groups profile in the match looks like this:

```<code>Match #0
                    [0]:  https://tenantName-dev.somedomain.com
            ["1"] → [1]:
            ["2"] → [2]:
   ["tenantName"] → [3]:  tenantName
            →3 Captures:  tenantName
  ["environment"] → [4]:  dev
            →4 Captures:  dev
   ["rootDomain"] → [5]:  somedomain.com
            →5 Captures:  somedomain.com
</code>```

Note the indexes above are valid of [3] or better to used the named capture of ["tenantName"] which gives us "tenantName" and ["environment"] which gives us "dev".

Take out the -dev and the match dump looks like this:

```<code>Match #0
                    [0]:  https://tenantName.somedomain.com
            ["1"] → [1]:  tenantName
            →1 Captures:  tenantName
            ["2"] → [2]:
   ["tenantName"] → [3]:  tenantName
            →3 Captures:  tenantName
  ["environment"] → [4]:
   ["rootDomain"] → [5]:  somedomain.com
            →5 Captures:  somedomain.com
</code>```

For that ["environment"] group is not represented and we can check Success as mtch.Groups["Dev"].Success. Example:

```<code>var pattern = @"https://
(?(?:.+-)    # If a dash
  (
    (?<tenantName>[^-]+)-(?<environment>[^.]+)
  )
 |           # Else Then
  (
    (?<tenantName>[^.]+)
  )
)
\.(?<rootDomain>[^/]+)";

var url = "https://tenantName.somedomain.com/somefile.js";

var mtch = Regex.Match(url, pattern, RegexOptions.IgnorePatternWhitespace);

if (mtch.Groups["Dev"].Success)
   ...
</code>```

Body:
I am trying to match some url which are built up like so:

https://tenantName-dev.somedomain.com/somefile.js
https://tenantName-qa.somedomain.com/somefile.js
https://tenantName.somedomain.com/somefile.js

Note the last one that has no "environment" since it's prod.

my C# regex so far:

https://(?<tenantName>.+)-(?<environment>[^.]*).(?<rootDomain>[^/]+)/somefile.js

This mostly works but would not match the last one as it always expects a '-'.
If I simply make that dash optinal, then it would match something like 'https://tenant-.somedomain...' which is not good.

I tried looking at lookaheads and non capturing groups to express the fact that I want a '-' only if there is a tenant behind but haven't been successful.

Body:
In most flavors of regex (and in .Net's version) there is an conditional pattern which allows for a check such as if...then...else. This is done by (?({conditon})X|Y) where if the match condition is true X is done or if not then Y is done).

Test it out by doing this (note turn on the flag IgnorePatternWhitespace because I am commenting the regex):

 (?(?:.+-)   # If a dash
  (?<A>.+)   # Match for dash
 |           # Else Then
  (?<B>.+)   # Match this
)

So the condition is a lookahead which is ?:.+- which means somewhere ahead there is a -. If true match on and create a named capture group A. Otherwise create a match on group B.

So taking your pattern we can distill it down and just focus on the -. Such as

https://
(?(?:.+-)    # If a dash
  (
    (?<tenantName>[^-]+)-(?<environment>[^.]+)
  )
 |           # Else Then
  (
    (?<tenantName>[^.]+)
  )
)
\.(?<rootDomain>[^/]+)

So if we dump the match when there is a - the groups profile in the match looks like this:

Match #0
                    [0]:  https://tenantName-dev.somedomain.com
            ["1"] → [1]:
            ["2"] → [2]:
   ["tenantName"] → [3]:  tenantName
            →3 Captures:  tenantName
  ["environment"] → [4]:  dev
            →4 Captures:  dev
   ["rootDomain"] → [5]:  somedomain.com
            →5 Captures:  somedomain.com

Note the indexes above are valid of [3] or better to used the named capture of ["tenantName"] which gives us "tenantName" and ["environment"] which gives us "dev".

Take out the -dev and the match dump looks like this:

Match #0
                    [0]:  https://tenantName.somedomain.com
            ["1"] → [1]:  tenantName
            →1 Captures:  tenantName
            ["2"] → [2]:
   ["tenantName"] → [3]:  tenantName
            →3 Captures:  tenantName
  ["environment"] → [4]:
   ["rootDomain"] → [5]:  somedomain.com
            →5 Captures:  somedomain.com

For that ["environment"] group is not represented and we can check Success as mtch.Groups["Dev"].Success. Example:

var pattern = @"https://
(?(?:.+-)    # If a dash
  (
    (?<tenantName>[^-]+)-(?<environment>[^.]+)
  )
 |           # Else Then
  (
    (?<tenantName>[^.]+)
  )
)
\.(?<rootDomain>[^/]+)";

var url = "https://tenantName.somedomain.com/somefile.js";

var mtch = Regex.Match(url, pattern, RegexOptions.IgnorePatternWhitespace);

if (mtch.Groups["Dev"].Success)
   ...


问:
how to fix cannot read property in Angular
so I'm working on existing code base and I'm trying make the mat-form filed to get TextData that written in mam-chart.model.ts file but some reason I'm getting this error " ERROR TypeError: Cannot read property 'text' of undefined' "

and the same thing for color " ERROR TypeError: Cannot read property 'color' of undefined' "

Any suggestion or help will be really apppreciated

design.ts

```<code>import { Chart, TextData, ChartData} from 'src/app/mam-chart/models';
export class ChartDesignComponent implements OnInit {
 chart: Chart;
 chartData: ChartData;
}
</code>```

design.html

```<code>            <mat-form-field appearance="fill">
                <mat-label>Text</mat-label>
                <input matInput  [(ngModel)]="chartData.textData.text" />
            </mat-form-field >

            <mat-form-field appearance="fill">
                <mat-label>Color(# + hex color code)</mat-label>
                <input matInput [(ngModel)]="chartData.textData.color"/>
            </mat-form-field >
</code>```

mam-chart.model.ts

```<code>export class Chart {
    id: number;
    chartType: ChartType = ChartType.chart;
    version: number = 2;
    dataType: ChartDataType = ChartDataType.static;
    template: ChartTemplate;

    .........

}
export class TextCard extends Chart {
    public chartData: CardDataChart;

    constructor(json?: any) {
        super(json)
        if (json == null) {
            return;
        }
        this.chartData = new ChartData(json.chartData);
    }
}

export class TextData {
    public text:  string;
    public color:  string;
    public size: string;
    public sizePx: number;

    constructor(json?: any) {
        if (json == null) {
            this.text = "";
            this.color = "";
            this.size = "";
            this.sizePx = 20;
            return;
        }
       ......

export class ChartData {
    filteredData: FilteredData[];
    figures: Figure[];
    textData: TextData;
}
</code>```

答:
It is probably because 'chartData' is undefined initially on page load.
You might solve this error and get the appropriate result if you slightly modify the html to link the ngModel chartData.textData.text when chartData is actually present; or initialize chartData as an object of the required type.

Code :

```<code>       <div *ngIf="chartData && chartData.textData">
       <mat-form-field appearance="fill">
            <mat-label>Text</mat-label>
            <input matInput  [(ngModel)]="chartData.textData.text" />
        </mat-form-field >

        <mat-form-field appearance="fill">
            <mat-label>Color(# + hex color code)</mat-label>
            <input matInput [(ngModel)]="chartData.textData.color"/>
        </mat-form-field >
        </div>
</code>```

Now the  form field will only be visible when chartData Object has a key 'textData'

Body:
so I'm working on existing code base and I'm trying make the mat-form filed to get TextData that written in mam-chart.model.ts file but some reason I'm getting this error " ERROR TypeError: Cannot read property 'text' of undefined' "

and the same thing for color " ERROR TypeError: Cannot read property 'color' of undefined' "

Any suggestion or help will be really apppreciated

design.ts

import { Chart, TextData, ChartData} from 'src/app/mam-chart/models';
export class ChartDesignComponent implements OnInit {
 chart: Chart;
 chartData: ChartData;
}

design.html

            <mat-form-field appearance="fill">
                <mat-label>Text</mat-label>
                <input matInput  [(ngModel)]="chartData.textData.text" />
            </mat-form-field >

            <mat-form-field appearance="fill">
                <mat-label>Color(# + hex color code)</mat-label>
                <input matInput [(ngModel)]="chartData.textData.color"/>
            </mat-form-field >

mam-chart.model.ts

export class Chart {
    id: number;
    chartType: ChartType = ChartType.chart;
    version: number = 2;
    dataType: ChartDataType = ChartDataType.static;
    template: ChartTemplate;

    .........

}
export class TextCard extends Chart {
    public chartData: CardDataChart;

    constructor(json?: any) {
        super(json)
        if (json == null) {
            return;
        }
        this.chartData = new ChartData(json.chartData);
    }
}

export class TextData {
    public text:  string;
    public color:  string;
    public size: string;
    public sizePx: number;

    constructor(json?: any) {
        if (json == null) {
            this.text = "";
            this.color = "";
            this.size = "";
            this.sizePx = 20;
            return;
        }
       ......

export class ChartData {
    filteredData: FilteredData[];
    figures: Figure[];
    textData: TextData;
}

Body:
It is probably because 'chartData' is undefined initially on page load.
You might solve this error and get the appropriate result if you slightly modify the html to link the ngModel chartData.textData.text when chartData is actually present; or initialize chartData as an object of the required type.

Code :

       <div *ngIf="chartData && chartData.textData">
       <mat-form-field appearance="fill">
            <mat-label>Text</mat-label>
            <input matInput  [(ngModel)]="chartData.textData.text" />
        </mat-form-field >

        <mat-form-field appearance="fill">
            <mat-label>Color(# + hex color code)</mat-label>
            <input matInput [(ngModel)]="chartData.textData.color"/>
        </mat-form-field >
        </div>

Now the  form field will only be visible when chartData Object has a key 'textData'


问:
Get orders of a user with orderItems and product details in Laravel
I have 3 tables (foods, orders and orderItems). I want to get orders of a user with orderItems and foods, but i failed.

Here's a result what i am getting right now, but i need to get food details instead of food_id.

```<code>[
    {
        "id": 16,
        "user_id": 2,
        "total": "12.50",
        "items": [
            {
                "id": 20,
                "order_id": 16,
                "food_id": 1,
                "quantity": 1,
                "food_price": "12.50",
            }
        ]
    }
]
</code>```

OrderController

```<code>$user = Auth::user();
return response()->json($user->deliveredOrders()->with('items')->get());
</code>```

User Model

```<code>public function deliveredOrders()
{
    return $this->hasMany(Order::class)->where('status', '=', 'delivered');
}
</code>```

Order Model

```<code>public function items()
    {
        return $this->hasMany(OrderItem::class);
    }
</code>```

答:
You should define food() method on OrderItem model.

```<code>public function food()
{
   return $this->belongsTo('App\Food');
}
</code>```

And get relation data using this:

```<code>$user = Auth::user();
return response()->json($user->deliveredOrders()->with('items.food')->get());
</code>```

Body:
I have 3 tables (foods, orders and orderItems). I want to get orders of a user with orderItems and foods, but i failed.

Here's a result what i am getting right now, but i need to get food details instead of food_id.

[
    {
        "id": 16,
        "user_id": 2,
        "total": "12.50",
        "items": [
            {
                "id": 20,
                "order_id": 16,
                "food_id": 1,
                "quantity": 1,
                "food_price": "12.50",
            }
        ]
    }
]

OrderController

$user = Auth::user();
return response()->json($user->deliveredOrders()->with('items')->get());

User Model

public function deliveredOrders()
{
    return $this->hasMany(Order::class)->where('status', '=', 'delivered');
}

Order Model

public function items()
    {
        return $this->hasMany(OrderItem::class);
    }

Body:
You should define food() method on OrderItem model.

public function food()
{
   return $this->belongsTo('App\Food');
}

And get relation data using this:

$user = Auth::user();
return response()->json($user->deliveredOrders()->with('items.food')->get());


问:
Truncate a float in Erlang
I am using a function to create a list from a float.

```<code> float_to_list(0.02).
</code>```

It returns:

```<code>"2.00000000000000000000e-002"
</code>```

I need it to give me a number exactly like:

"0.20"

If I fed it 5.23

"5.23"

If I fed it 5.5

"5.50"

So basically the number rounded to two decimal places.
Probably an easy fix.

Thanks

EDIT:

I would like to use the io format it looks like it might work,

but it dosen't in this example:

```<code>wxTextCtrl:setValue( TcGrossProfit, io:format("~p", [NUMBER]), ),
</code>```

seems textctrl wants a string,  I don't want to print it to the screen.

答:
mochinum:digits converts a float to a string with an appropriate level of precision.

```<code>1> mochinum:digits(1.1).
"1.1"
2> mochinum:digits(1.2345).
"1.2345"
</code>```

Not exactly what the OP requested, but useful nonetheless.

ContentLicense: CC BY-SA 2.5

Title: Truncate a float in Erlang

Body:
I am using a function to create a list from a float.

 float_to_list(0.02).

It returns:

"2.00000000000000000000e-002"

I need it to give me a number exactly like:

"0.20"

If I fed it 5.23

"5.23"

If I fed it 5.5

"5.50"

So basically the number rounded to two decimal places.
Probably an easy fix.

Thanks

EDIT:

I would like to use the io format it looks like it might work,

but it dosen't in this example:

wxTextCtrl:setValue( TcGrossProfit, io:format("~p", [NUMBER]), ),

seems textctrl wants a string,  I don't want to print it to the screen.

Body:
mochinum:digits converts a float to a string with an appropriate level of precision.

1> mochinum:digits(1.1).
"1.1"
2> mochinum:digits(1.2345).
"1.2345"

Not exactly what the OP requested, but useful nonetheless.


问:
AWS Application Load Balancer real user ip problem
I run laravel application on AWS Elasticbeanstalk, I use Application Load Balancer.

```<code>Route::get('/what-is-my-ip', function(){
    return request()->ip();
});
</code>```

When I run this code, my ip doesn't show, it shows the load balancer's ip addresses.

Those who used the same problem with cloudflare also experienced and have solutions for cloudflare, but I couldn't find a solution for the AWS Application Load Balancer.

I am having trouble getting users' ip addresses and adding --allow-ip in maintenance mode.

```<code>function real_IP() {

    $real_IP = '';

    if (getenv('HTTP_CLIENT_IP'))
        $real_IP = getenv('HTTP_CLIENT_IP');
    else if(getenv('HTTP_X_FORWARDED_FOR'))
        $real_IP = getenv('HTTP_X_FORWARDED_FOR');
    else if(getenv('HTTP_X_FORWARDED'))
        $real_IP = getenv('HTTP_X_FORWARDED');
    else if(getenv('HTTP_FORWARDED_FOR'))
        $real_IP = getenv('HTTP_FORWARDED_FOR');
    else if(getenv('HTTP_FORWARDED'))
        $real_IP = getenv('HTTP_FORWARDED');
    else if(getenv('REMOTE_ADDR'))
        $real_IP = getenv('REMOTE_ADDR');
    else
        $real_IP = 'UNKNOWN';

    return $real_IP;
}
</code>```

when i run this code it gives the correct ip address, i want to fix it across laravel.

答:
You'll need to trust the AWS load balancers as a proxy.

If you are using AWS Elastic Load Balancing, your $headers value should be Request::HEADER_X_FORWARDED_AWS_ELB. For more information on the constants that may be used in the $headers property, check out Symfony's documentation on trusting proxies.

If you are using Amazon AWS or another "cloud" load balancer provider,
  you may not know the IP addresses of your actual balancers. In this
  case, you may use * to trust all proxies:

```<code>protected $proxies = '*';
</code>```

Body:
I run laravel application on AWS Elasticbeanstalk, I use Application Load Balancer.

Route::get('/what-is-my-ip', function(){
    return request()->ip();
});

When I run this code, my ip doesn't show, it shows the load balancer's ip addresses.

Those who used the same problem with cloudflare also experienced and have solutions for cloudflare, but I couldn't find a solution for the AWS Application Load Balancer.

I am having trouble getting users' ip addresses and adding --allow-ip in maintenance mode.

function real_IP() {

    $real_IP = '';

    if (getenv('HTTP_CLIENT_IP'))
        $real_IP = getenv('HTTP_CLIENT_IP');
    else if(getenv('HTTP_X_FORWARDED_FOR'))
        $real_IP = getenv('HTTP_X_FORWARDED_FOR');
    else if(getenv('HTTP_X_FORWARDED'))
        $real_IP = getenv('HTTP_X_FORWARDED');
    else if(getenv('HTTP_FORWARDED_FOR'))
        $real_IP = getenv('HTTP_FORWARDED_FOR');
    else if(getenv('HTTP_FORWARDED'))
        $real_IP = getenv('HTTP_FORWARDED');
    else if(getenv('REMOTE_ADDR'))
        $real_IP = getenv('REMOTE_ADDR');
    else
        $real_IP = 'UNKNOWN';

    return $real_IP;
}

when i run this code it gives the correct ip address, i want to fix it across laravel.

Body:
You'll need to trust the AWS load balancers as a proxy.

If you are using AWS Elastic Load Balancing, your $headers value should be Request::HEADER_X_FORWARDED_AWS_ELB. For more information on the constants that may be used in the $headers property, check out Symfony's documentation on trusting proxies.

If you are using Amazon AWS or another "cloud" load balancer provider,
  you may not know the IP addresses of your actual balancers. In this
  case, you may use * to trust all proxies:

protected $proxies = '*';