text:
Q: Slow datagrid - improve performance I have a pretty huge Datagrid.
Here's the datagrid with just one column:
<DataGrid x:Name="dgVarConfig"
              ItemsSource="{Binding VarConfigList, Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
              SelectedItem="{Binding Path=SelectedVarConfig, Mode=TwoWay}"
              Margin="8,56,557,80"
              AutoGenerateColumns="False"
              CanUserDeleteRows="False"
              CanUserResizeRows="False"
              HeadersVisibility="Column"
              CanUserAddRows="False"
              HorizontalScrollBarVisibility="Auto"
              PreviewKeyDown="dgVarConfig_PreviewKeyDown"
              BeginningEdit="dgVarConfig_BeginningEdit"
              CellEditEnding="dgVarConfig_CellEditEnding"
              SelectionChanged="dgVarConfig_SelectionChanged"
              EnableRowVirtualization="True"
              EnableColumnVirtualization="False"
              VerticalGridLinesBrush="Black"
              VirtualizingStackPanel.VirtualizationMode ="Standard"
              VirtualizingStackPanel.IsVirtualizing="true">

<DataGrid.Columns>
    <DataGridTemplateColumn Width="auto"  MinWidth="150" SortMemberPath="Match_expression">

        <DataGridTemplateColumn.CellTemplate>
                    <DataTemplate>
                        <ContentControl>
                            <MultiBinding Converter="{StaticResource highlightConverter}" ConverterParameter="MATCHEXPRESSION">
                                <Binding Path="Match_expression"></Binding>
                            </MultiBinding>
                        </ContentControl>
                    </DataTemplate>
                </DataGridTemplateColumn.CellTemplate>

                <DataGridTemplateColumn.CellEditingTemplate >
                    <DataTemplate>
                        <TextBox Text="{Binding Match_expression}" FocusManager.FocusedElement="{Binding RelativeSource={RelativeSource Self}}" Style="{StaticResource GridTextBox}"></TextBox>
                    </DataTemplate>
                </DataGridTemplateColumn.CellEditingTemplate>

                <DataGridTemplateColumn.HeaderStyle>
                    <Style TargetType="DataGridColumnHeader">
                        <Setter Property="Template">
                            <Setter.Value>
                                <ControlTemplate TargetType="DataGridColumnHeader">
                                    <Grid>
                                        <Grid.ColumnDefinitions>
                                            <ColumnDefinition Width="auto"></ColumnDefinition>
                                            <ColumnDefinition Width="*"></ColumnDefinition>
                                            <ColumnDefinition Width="auto"></ColumnDefinition>
                                            <ColumnDefinition Width="auto"></ColumnDefinition>
                                            <ColumnDefinition Width="auto"></ColumnDefinition>
                                        </Grid.ColumnDefinitions>

                                        <Label Grid.Column="1" Padding="5 0" Content="Auswahlformel" VerticalAlignment="Center" Cursor="Hand" Foreground="White"/>
                                        <TextBox x:Name="txtMatchExpressionFilter" Margin="0 5" Grid.Column="2" Width="150" Visibility="Collapsed"></TextBox>
                                        <Button Grid.Column="3" Margin="5 0" x:Name="btnFilterMatchExpresion" Style="{StaticResource MyButton}" Width="16" Height="16" VerticalAlignment="Center" HorizontalAlignment="Right"  Click="btnFilterMatchExpresion_Click">
                                            <Button.Background>
                                                <ImageBrush ImageSource="Resources/filter.png"/>
                                            </Button.Background>
                                        </Button>

                                        <Path x:Name="SortArrow"
                                        Grid.Column="0"
                                        HorizontalAlignment="Right" VerticalAlignment="Center"
                                        Width="8" Height="6" Margin="2,0,5,0"
                                        Stretch="Fill" Opacity="0.5" Fill="White"
                                        RenderTransformOrigin="0.5,0.4"
                                        Visibility="Collapsed"
                                        Data="M0,0 L1,0 0.5,1 z" />

                                        <Thumb x:Name="PART_RightHeaderGripper" Grid.Column="4" HorizontalAlignment="Right" Width="1" BorderThickness="1"
                                               BorderBrush="{Binding VerticalGridLinesBrush, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type DataGrid}}}" Cursor="SizeWE"/>
                                    </Grid>

                                    <ControlTemplate.Triggers>
                                        <Trigger Property="SortDirection" Value="Ascending">
                                            <Setter TargetName="SortArrow" Property="Visibility" Value="Visible" />
                                            <Setter TargetName="SortArrow" Property="RenderTransform">
                                                <Setter.Value>
                                                    <RotateTransform Angle="180" />
                                                </Setter.Value>
                                            </Setter>
                                        </Trigger>
                                        <Trigger Property="SortDirection" Value="Descending">
                                            <Setter TargetName="SortArrow" Property="Visibility" Value="Visible" />
                                        </Trigger>
                                    </ControlTemplate.Triggers>
                                </ControlTemplate>
                            </Setter.Value>
                        </Setter>
                    </Style>
                </DataGridTemplateColumn.HeaderStyle>

    </DataGridTemplateColumn>
</DataGrid.Columns>

<DataGrid.GroupStyle>
            <GroupStyle>
                <GroupStyle.ContainerStyle>
                    <Style TargetType="{x:Type GroupItem}">
                        <Setter Property="Template">
                            <Setter.Value>
                                <ControlTemplate TargetType="{x:Type GroupItem}">
                                    <StackPanel Background="Gray" Margin="-5 0 0 0">
                                        <TextBlock Foreground="White" FontWeight="Bold" Text="{Binding Path=Name, StringFormat=Gruppe: {0}}" Margin="10 5 0 5"/>
                                        <ItemsPresenter />
                                    </StackPanel>
                                </ControlTemplate>
                            </Setter.Value>
                        </Setter>
                    </Style>
                </GroupStyle.ContainerStyle>
            </GroupStyle>

            <GroupStyle>
                <GroupStyle.HeaderTemplate>
                    <DataTemplate>
                        <DockPanel Background="LightGray">
                            <TextBlock Text="{Binding Path=Name}" Foreground="Black" Margin="10 2 0 2"/>
                            <ItemsPresenter></ItemsPresenter>
                        </DockPanel>
                    </DataTemplate>
                </GroupStyle.HeaderTemplate>
            </GroupStyle>
</DataGrid.GroupStyle>

<DataGrid.ContextMenu>
    <ContextMenu>
    <MenuItem x:Name="cmAddGroup" Header="Gruppe zuweisen" Click="cmAddGroup_Click" ></MenuItem>
    <MenuItem x:Name="cmRemoveDeleteFlag" Header="Löschvermerk entfernen" Click="cmRemoveDeleteFlag_Click"></MenuItem>
    </ContextMenu>
</DataGrid.ContextMenu>

Let me explain:
"highlightConverter" checks the value of the cell and does some sort of syntaxhighlighting, syntaxcheck and returns a colored TextBlock
If i want to edit that TextBlock i had to convert it to a TextBox
The grid has two groups (i havent posted all columns, so the groups aren't here, but the GroupStyle)
Two have the SortingArrows i added them here too.
On each column Header there is a filterButton to filter the rows.
That leads me to my problem: The grid gets really really slow on filtering, sorting, resize rows/columns, reorder columns, scrolling etc.
I think its because of the TextBlock and TextBox items. Is there any better solution to improve the performance?
Here's the HighlightConverter.cs
public class HighlightConverter : IMultiValueConverter
{
    public static Dictionary<String, SyntaxResult> calcFormulaCache;
    public static Dictionary<String, SyntaxResult> matchExpressionCache;

    public HighlightConverter()
    {
        calcFormulaCache = new Dictionary<string, SyntaxResult>();
        matchExpressionCache = new Dictionary<string, SyntaxResult>();
    }

    ClientSettings clientSettings = new ClientSettings();

    Brush[] colorArray;

    Regex subFormula = new Regex(@"\w+\(\)");
    Regex sapFormula = new Regex(@"\w+\(([^)]+)\)");
    Regex strings = new Regex(@"\'[^']+\'");
    Regex numerals = new Regex(@"\b[0-9\.]+\b");
    Regex characteristic = new Regex(@"(?:)?\w+(?:)?");
    Regex andOr = new Regex(@"( and )|( AND )|( or )|( OR )");
    Regex not = new Regex(@"(not )|(NOT )");

    VariantConfigurationTestDAO variantConfigurationTestDAO = new VariantConfigurationTestDAO();

    public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
    {
        if (!clientSettings.SyntaxCheck && !clientSettings.SyntaxCheck)
            return values[0];

        TextBlock textBlock = new TextBlock();

        string input = values[0] as String;

        if (!String.IsNullOrEmpty(input))
        {
            if (clientSettings.SyntaxHighlighting)
            {
                colorArray = new Brush[input.Length];

                for (int i = 0; i < input.Length; i++)
                    colorArray[i] = Brushes.Black;

                //Reihenfolge beibehalten!!
                assignColor(Brushes.Blue, characteristic.Matches(input));
                assignColor(Brushes.Black, andOr.Matches(input));
                assignColor(Brushes.Black, numerals.Matches(input));
                assignColor(Brushes.Orange, strings.Matches(input));
                assignColor(Brushes.DeepPink, subFormula.Matches(input));
                assignColor(Brushes.Green, sapFormula.Matches(input));
                assignColor(Brushes.Green, not.Matches(input));

                List<Char> splittedInput = input.ToCharArray().ToList();
                int index = 0;
                foreach (Char character in splittedInput)
                {
                    textBlock.Inlines.Add(new Run(character.ToString()) { Foreground = colorArray[index] });
                    index++;
                }

                colorArray = null;
            }
            else
            {
                colorArray = null;
                textBlock.Text = input;
            }

            if (clientSettings.SyntaxCheck)
            {
                Pen pen = new Pen(Brushes.Red, 3);
                TextDecoration textDec = new TextDecoration(TextDecorationLocation.Underline, pen, 4, TextDecorationUnit.Pixel, TextDecorationUnit.FontRecommended);

                 if (!String.IsNullOrEmpty((String)parameter))
                 {
                     String para = (String)parameter;
                     SyntaxResult syntaxResult = null;

                     switch (para)
                     {
                         case "VARIANT":
                             if (para == "VARIANT")
                             {
                                 if (characteristic.IsMatch(input) || subFormula.IsMatch(input))
                                 {
                                     if (andOr.IsMatch(input) || numerals.IsMatch(input) || strings.IsMatch(input) || sapFormula.IsMatch(input) || not.IsMatch(input))
                                     {
                                         textBlock.TextDecorations.Add(textDec);
                                         textBlock.ToolTip = "Hier darf nur ein Merkmal oder eine Subformel stehen";
                                     }
                                 }
                             }
                             break;
                         case "CALCFORMULA":
                             if (!calcFormulaCache.ContainsKey(input))
                                 calcFormulaCache.Add(input, variantConfigurationTestDAO.vcCalculateFormula3(input, true));

                             syntaxResult = calcFormulaCache[input];
                             break;
                         case "MATCHEXPRESSION":
                             if (!matchExpressionCache.ContainsKey(input))
                                 matchExpressionCache.Add(input, variantConfigurationTestDAO.vcEvalMatchEx(input, true));

                             syntaxResult = matchExpressionCache[input];;
                             break;
                         default:
                             break;
                     }

                     if (syntaxResult != null)
                     {
                         if (syntaxResult.syntax > 0)
                         {
                             textBlock.TextDecorations.Add(textDec);

                             if (syntaxResult.errors.Count == 0)
                                 textBlock.ToolTip = "Allgemeiner Syntaxfehler";
                             else
                                 textBlock.ToolTip = String.Join(",", syntaxResult.errors);
                         }
                     }

                 }

                if (values.Count() == 2)
                {
                    string input2 = values[1] as String;

                    if (String.IsNullOrEmpty(input2))
                    {
                        textBlock.TextDecorations.Add(textDec);
                        textBlock.ToolTip = "Es müssen Variante und Kalkulationsformel gefüllt sein";
                    }
                }
            }
        }

        return textBlock;
    }

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

    private void assignColor(Brush brush, MatchCollection matchCollection)
    {
        foreach (Match match in matchCollection)
        {
            int start = match.Index;
            int end = start + match.Length;

            for (int i = start; i < end; i++)
            {
                colorArray[i] = brush;
            }
        }
    }

}

A: In my view, it is not a problem of using IMultiConverter, but Virtualization and Column Rendering.
Try to use these properties to your DataGrid:

*

*Enabled VirtualizingStackPanel.VirtualizationMode for a Grid

*Set VirtualizingStackPanel.IsVirtualizing="true" for DataGrid

*MaxWidth="2560" MaxHeight="1600"

Never put a DataGrid in a ScrollViewer, because you will essentially lose virtualization.
For example:
<DataGrid ItemsSource="{Binding EmployeeDataTable, IsAsync=True}"
          VirtualizingStackPanel.IsVirtualizing="true" EnableRowVirtualization="True"
        EnableColumnVirtualization="True" MaxWidth="2560" MaxHeight="1600"
        VirtualizingStackPanel.VirtualizationMode="Recycling"
        VirtualizingPanel.IsVirtualizingWhenGrouping="True"/>

A: You have rather big Convert method. Imagine that it invokes for each cell in your DataGrid.

*

*Try to take syntax analysis to another thread. For user it will look like - text entered and in couple of seconds syntax will be checked and/or highlighted.

*Regex.Matches use lazy initialization, so when you are iterating through matches - it actually perform search in string based on regular expression, each time. Try to exclude assignColor methods group in Convert()and check execution time. If it helps - try to write your own string parser, without regular expressions.

*In this line List<Char> splittedInput = input.ToCharArray().ToList(); you are iterating twice through input characters. First time - when you are creating array from string characters, and second time - when you are creating list from array items. And then you are iterating again through this string in foreach (Char character in splittedInput). You can actually iterate through input itself : foreach (var character in input).

*In this line: if (values.Count() == 2) use .Length (property of array) instead of .Count() (extension LINQ method), because in each moment of time array knows it's length, and calling extension linq method cause to deal with array like with IEnumerable with lazy initialization.
But in my opinion main problem is in consecutive text analysis. Frequent solution is to perform string analysis in parallel thread - for non-pausing user input (or performing any actions on this).


text:
Q: Puppet 5.5.22, dnfmodule reset I've been trying to figure out how to convert
dnf module reset php
dnf module install php:remi-7.4

to a stanza in a puppet module for several hours without any success.
Has anyone figured out how to do that?  The doco on the puppet website is somewhat lacking, shall we say.

A: I believe that reset isn't implemented with dnf module yet, just enable and disable, but it can be used as a package manager directly.
From a quick test on a CentOS 8 docker image this worked for me:
  package { 'dnf-utils':
    ensure      =>  present,
  }
  package { 'redhat-rpm-config':
    ensure      =>  present,
  }
  package { 'epel-release':
    ensure      =>  present,
    provider    =>  rpm,
    source      =>  'https://dl.fedoraproject.org/pub/epel/epel-release-latest-8.noarch.rpm',
    require     =>  Package['redhat-rpm-config']
  }
  package { 'remi-release':
    ensure      =>  present,
    provider    =>  rpm,
    source      =>  'https://rpms.remirepo.net/enterprise/remi-release-8.rpm',
    require     =>  Package['epel-release']
  }
  exec { 'dnf-enable':
    path        =>  $path,
    command     =>  'dnf config-manager --enable remi remi-test remi-modular-test',
    require     =>  Package['remi-release']
    refreshonly =>  true,
  }
  exec { 'dnf-modules':
    path        =>  $path,
    command     =>  'dnf -y module reset php',
    require     =>  Exec['dnf-enable']
    refreshonly => true,
  }

  package { 'php':
    provider    => 'dnfmodule',
    ensure      =>  'remi-7.4',
  }

I think the repos could be refactored to yumrepo resources, but this is a good base to use dnf module with Puppet.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Cube root of the $j$-invariant Let
$$\Gamma=\bigg \lbrace \begin{pmatrix} a&b\\c&d\end{pmatrix}\in\Gamma(1):b\equiv c~(\text{mod }3)\text{ or } a\equiv d\equiv 0~(\text{mod }3)\bigg \rbrace.$$
Then $\Gamma$ has exactly one cusp and its hauptmodul is the modular function $g=j^{1/3}$ usually denoted by $\gamma_2$.
Now pretend that we do not know that $ g^3=j $ and let $h$ be a Hauptmodul for $\Gamma$ which is holomorphic on the upper half-plane $\mathfrak H$.
Now let's try and find a relation between $j$ and $h$ using the description of $\Gamma$.
Since $j$ is holomorphic on $\mathfrak H$, there is a polynomial $P$ such that $j=P(h)$. Because the only zero of $j$ is at $\rho=e^{2\pi i /3}$ (modulo the action of $\Gamma(1)$),the coset representatives for $\Gamma$ in $\Gamma(1)$ are $I,T,T^2$, and $h$ has a simple pole at infinity (that is, its Fourier expansion begins with $q^{-1/3}$), we can write
$$j=(g-g(\rho))(g-g(T\rho))(g-g(T^2\rho)).$$
On the other hand, $ST\rho= \rho$. Therefore, as $S\in \Gamma $, we have $g(T\rho)=g(\rho)$.
However, I am at loss trying to prove that $g(\rho)=g(T^2\rho)$. What am I missing?

A: Because $S \in  \Gamma$ and $\Gamma$ is a normal subgroup of $\Gamma(1)$, we may as well take the coset representatives to be $1, ST , (ST)^2$.
Or alternately we have $\rho = ST ST \rho = S (TS T^{-1})  T^2 \rho$ and $S (TST^{-1}) \in \Gamma$ because $\Gamma$ is a normal subgroup (or by explicit calculation).


text:
Q: ReactJS and bootstrap I have a reactJS application and I would like to integrate bootstrap.  I have the following index.html file:

    <title>Whats my junk worth</title>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
    <link href='http://fonts.googleapis.com/css?family=Pacifico' rel='stylesheet' type='text/css'>
    <link href='http://fonts.googleapis.com/css?family=Just+Another+Hand' rel='stylesheet' type='text/css'>

I tried laying out some simple pages with code such as this:

        Put out some test code

        Put out some test code

        Put out some test code

The above sample generated 3 lines of output instead of spanning across a single row.  I also tried changing class= to className= but that had no effect.
Is there anything else that I need to include in order to make use of bootstrap classes?

A: Consider using react-bootstrap package. You wouldn't waste you time on such things. Just components, just functionality.
It'll look something like this:
<Row className="show-grid">
    <Col xs={6} md={4}></Col>
    <Col xs={6} md={4}></Col>
    <Col xs={6} md={4}></Col>
</Row>

UPD
Bootstrap has getting started guide which explains how should you handle your assets. Hope it'll help

A: You can use react-bootstrap and convert your code into the following:
<Row className="show-grid">
    <Col xs={6} md={4}></Col>
    <Col xs={6} md={4}></Col>
    <Col xs={6} md={4}></Col>
</Row>

A: The code and Bootstrap references should work the way you have it.

"I tried laying out some simple pages with code"

How? Did you put the html into a Component render(), or did you put it directly in the template? Either way it should work. Remember too that the sm breakpoint is 576px so the columns will stack vertically if the viewport with is less than 576px.
Working demo: https://codesandbox.io/s/5vm72q34qk
P.S. - react-bootstrap doesn't yet support Bootstrap 4.


text:
Q: Article usage in "AI technology" vs. "the English language" Why some noun phrases require the definite article, some don't? They are quite similar in structure. Why do we say "the NYC area", "the English language", but "AI technology", "blockchain technology"? How are latter phrases different from former ones?
My hunch: technology here is a category? Is that the (only) reason?

A: The definite article is used to refer to a particular member of a group or class. (See Wikipedia for more on definite and indefinite articles.)
Some might disagree with where the borders are drawn, but there is exactly one NYC area. There are different varieties of English, but they are all part of one English language.
Usually when we talk about AI technology, we are not talking about a single invention. "AI technology" usually refers collectively to all of the inventions, mechanisms, and techniques related to artificial intelligence.
We would only use "the AI technology" if we did intend to talk about a specific type of AI technology in contrast to all of the other AI technologies, such when saying, "neural networks are the AI technology with the most success". (This is just an example; I am not trying to make this claim.)

A: As far as I can tell, it's because area and language are countable while technology is uncountable.
The phrases NYC area and English language take "the" because the words area and language take "the". The phrases AI technology and blockchain technology don't usually take "the" because the word technology doesn't usually take "the".


text:
Q: Draw nodes in ring form I want to use this drawing of a neural network and extend it to a recurrent neural network. To do so I'd like to arrange the hidden nodes to a ring and connect every hidden node with the other hidden nodes. This is a simple feed forward network I got from here. Could someone show me how I can accomplish what I need?
\documentclass{article}

\usepackage{tikz}
\begin{document}
\pagestyle{empty}

\def\layersep{2.5cm}

\begin{tikzpicture}[shorten >=1pt,->,draw=black!50, node distance=\layersep]
    \tikzstyle{every pin edge}=[<-,shorten <=1pt]
    \tikzstyle{neuron}=[circle,fill=black!25,minimum size=17pt,inner sep=0pt]
    \tikzstyle{input neuron}=[neuron, fill=green!50];
    \tikzstyle{output neuron}=[neuron, fill=red!50];
    \tikzstyle{hidden neuron}=[neuron, fill=blue!50];
    \tikzstyle{annot} = [text width=4em, text centered]

    % Draw the input layer nodes
    \foreach \name / \y in {1,...,4}
    % This is the same as writing \foreach \name / \y in {1/1,2/2,3/3,4/4}
        \node[input neuron, pin=left:Input \#\y] (I-\name) at (0,-\y) {};

    % Draw the hidden layer nodes
    \foreach \name / \y in {1,...,5}
        \path[yshift=0.5cm]
            node[hidden neuron] (H-\name) at (\layersep,-\y cm) {};

    % Draw the output layer node
    \node[output neuron,pin={[pin edge={->}]right:Output}, right of=H-3] (O) {};

    % Connect every node in the input layer with every node in the
    % hidden layer.
    \foreach \source in {1,...,4}
        \foreach \dest in {1,...,5}
            \path (I-\source) edge (H-\dest);

    % Connect every node in the hidden layer with the output layer
    \foreach \source in {1,...,5}
        \path (H-\source) edge (O);

    % Annotate the layers
    \node[annot,above of=H-1, node distance=1cm] (hl) {Hidden layer};
    \node[annot,left of=hl] {Input layer};
    \node[annot,right of=hl] {Output layer};
\end{tikzpicture}
% End of code
\end{document}

Best regards.

A: It is somehow unclear what you are asking. Do you want to have multiple hidden layers? Then how about output layer connections. I did something based on my understanding of your question. Please comment if it is not exactly what you want. My answer is based on your own code and this example.
\documentclass{article}
\usepackage{tikz}
\usetikzlibrary[topaths]

\newcount\mycount
\begin{document}
\begin{tikzpicture}[transform shape]
    \tikzstyle{every pin edge}=[<-,shorten <=1pt]
    \tikzstyle{neuron}=[circle,fill=black!25,minimum size=17pt,inner sep=0pt]
    \tikzstyle{input neuron}=[neuron, fill=green!50];
    \tikzstyle{output neuron}=[neuron, fill=red!50];
    \tikzstyle{hidden neuron}=[neuron, fill=blue!50];
    \tikzstyle{annot} = [text width=4em, text centered]

    % input layer
    \foreach \name / \y in {1,...,4}
        \node[input neuron, pin=left:Input \#\y] (I-\name) at (0,-\y) {};

    % hidden layer nodes
    \foreach \number in {1,...,6}{
        \mycount=\number
        \advance\mycount by -1
        \multiply\mycount by 60
        \advance\mycount by 0
        \node[xshift=5cm, yshift=-2.5cm, hidden neuron] (N-\number) at (\the\mycount:3cm) {};
    }

    % hidden layer interconnections
    \foreach \number in {1,...,5}{
        \mycount=\number
        \advance\mycount by 1
        \foreach \numbera in {\the\mycount,...,6}{
            \path (N-\number) edge[<->] (N-\numbera);
        }
    }

    % output layer
    \node[xshift=10cm, yshift=-2.5cm,output neuron,pin={[pin edge={->}]right:Output}] (O) {};

    % input-hidden-output connections
    \foreach \source in {1,...,4}
        \foreach \dest in {3,4,5}
            \path (I-\source) edge[->] (N-\dest);

    \foreach \source in {1,2,6}
        \path (N-\source) edge[->] (O);

\end{tikzpicture}
\end{document}


text:
Q: Magento 2.3 - Paypal Credit Wont Go away from MiniCart I 100% have Paypal Credit disabled in all sections of Configuration -> Payment methods.
The only section enabled is Paypal Express Checkout, and "advertise PayPal Credit" is definteluy not filled in. All the other Paypal sections that are not enabled also have "Enable Paypal Credit" set to "No"
Yet, I am still getting the checkout with PayPal credit on my minicart.
Only in Magento Version 2.3. Any ideas?

A: There is an option hidden away under many levels of the PayPal config! All funding options are enabled by default so you have to disable them even if the actual methods are disabled.
Stores > Config > Payment Methods > PayPal Configure > Basic Settings - PayPal Express Checkout > Advanced Settings > Frontend Experience Settings > Disable Funding Options
I am using 2.3.1 Commerce.

A: bin/magento config:set paypal/style/disable_funding_options CREDIT,CARD,ELV
bin/magento cache:clean


text:
Q: Remove first character from a string if it is 0 I know it is related to Remove first character from a string if it is a comma but in this case that solution doesn't work for me. Maybe its because now I'm dealing with a number. Simply I want javascript to remove 0 from 08 but don't touch 10; only remove 0 when it is the first character.
This solution doesn't work: replace(/^0/, "")

A: You can try this:
alert("08".replace(/^0+/, ''));

DEMO
And if you are dealing with numbers then you can use parseInt() function.

A: Easy way with regex :

^0+(?!$)

and feel free to use String replaceFirst function.


text:
Q: Is there any way to change image within a time period in react JS I want to change the image on the left side in every 3 seconds. Is there any techniques to do it without using react image slider?
I have attached my code here. I have tried to do it using react hooks. I have stored the images inside an array. The images changes perfectly only for first 8-10 seconds.
import React, { useEffect, useState } from "react";
import bannerImg1 from "../../Assets/Images/bannerProduct1.png";
import bannerImg2 from "../../Assets/Images/bannerProduct2.png";
import { Row, Col, Container } from "react-bootstrap";
import { FaCaretRight, FaChevronLeft, FaChevronRight } from "react-icons/fa";
import "./BannerSlider.css";

const BannerSlider = () => {
  const imageArray = [bannerImg1, bannerImg2];
  let [count, setCount] = useState(0);
  const [image, setImage] = useState(imageArray[count]);

  useEffect(() => {
    setImage(imageArray[count]);
  }, [count]);

  useEffect(() => {
    setInterval(() => {
      setCount(count + 1);
    }, 3000);
  }, []);

  return (

      <Container>

          <Row className="d-flex align-items-center">
            <Col lg={6} className="banner-image">

            </Col>
            <Col lg={6} className="banner-text">

Where your imagination come true

                {" "}
                Lorem ipsum dolor sit amet, consectetur adipisicing elit. Illo
                porro neque odio, at aspernatur explicabo?{" "}

              <button>
                Explore More <FaCaretRight className="banner-button-icon" />{" "}
              </button>
            </Col>
          </Row>

      </Container>

  );
};

A: Issues
From what I can read of your code you've a few issues:

*

*The useEffect doesn't clear any running timers when the component unmounts.

*You've closed over the initial count state in the interval callback so it's not updating correctly.

*You don't account for incrementing past the array length.

Solution
// move image array outside component so it's not a dependency
const imageArray = [bannerImg1, bannerImg2, bannerImg3];

const BannerSlider = () => {
  const [count, setCount] = useState(0);

  // Save timer ref and return cleanup function to clear it
  useEffect(() => {
    const timerId = setInterval(() => {
      // Use a functional state update to correctly increment the count
      setCount(count => count + 1);
    }, 3000);

    return () => clearInterval(timerId);
  }, []);

  // `image` is derived state from the image array and current count
  // Take the count mod array length to get the correct computed index
  const image = imageArray[count % imageArray.length];

  return (

      <Container>

          <Row className="d-flex align-items-center">
            <Col lg={6} className="banner-image">

            </Col>
            <Col lg={6} className="banner-text">

Where your imagination come true

                {" "}
                Lorem ipsum dolor sit amet, consectetur adipisicing elit. Illo
                porro neque odio, at aspernatur explicabo?{" "}

              <button>
                Explore More <FaCaretRight className="banner-button-icon" />{" "}
              </button>
            </Col>
          </Row>

      </Container>

  );
};


text:
Q: My webpage messes up when re-sized My webpage looks very awkward whenever I re-size it to any width length pass the absolute highest. Just check it out, it messes up in the header sections and I have no clue how to fix it. Please help me, this is my very first website and I'm starting to get a little furstrated by these simple things.
I don't know how to demonstrate it, but I'll just say that the personal sessions and contact buttons, when resized past a certain point end up under the header instead of embedded in the header, causing it to interfere with the content area. thank you!
Header Code:

header{
height: 100px;
width: 100%;
margin: 0;
background-color: black;
border-bottom: solid white;
box-shadow: 0 5px 30px #888888;
}

#logo{
background-image: url("images/logo.png");
float: left;
height: 100px;
color: white;
margin: 0;
margin-left: 40px;
padding: 14px 100px 0 115px;
}

A: Read this
To have your website less messed up, use % for width and sometimes for height as well and not pixels.

A: You have to add viewport meta tag  and make your website responsive
<meta name="viewport" content="width=device-width, initial-scale=1.0">


text:
Q: Finding a column count by day/month How do I find the sum of a column eg. 'PlanTotal' by either day or month of another column eg. 'PlanStartDate' within the last six months?
I've got as far as this but don't know how to separate the sum into days or month.
SELECT SUM(PlanTotal) as PlanTotal
FROM TEST.dbo.Plans
WHERE DATEDIFF(MONTH, cast(cast(PlanStartDate as varchar(8)) as datetime), GETDATE()) <= 6

Thanks
.....
I've used
SELECT SUM(PlanTotal) as PlanTotal,PlanStartDate
FROM TEST.dbo.Plans
WHERE  DATEDIFF(MONTH, cast(cast(PlanStartDate as varchar(8)) as datetime), GETDATE()) <= 6
GROUP BY PlanStartDate
ORDER BY PlanStartDate

This brings up the Plan Total and PlanStartDate by individual day but I still can't seem to work out grouping each month.
If I do this:
SELECT SUM(PlanTotal) as PlanTotal,MONTH(PlanStartDate)
FROM TEST.dbo.Plans
WHERE  DATEDIFF(MONTH, cast(cast(PlanStartDate as varchar(8)) as datetime), GETDATE()) <= 6
GROUP BY MONTH(PlanStartDate)
ORDER BY PlanStartDate

Using the month group by, it just throws an error;
Column "TEST.dbo.Plans.PlanStartDate" is invalid in the ORDER BY clause because
it is not contained in either an aggregate function or the GROUP BY clause.
How do I correct this?

A: The following should help, however it wont display any records for dates which are non-existent in the PlanStartDate column
SELECT SUM(PlanTotal) as PlanTotal
       ,PlanStartDate
FROM TEST.dbo.Plans
WHERE DATEDIFF(MONTH, cast(cast(PlanStartDate as varchar(8)) as datetime), GETDATE())<= 6
Group By PlanStartDate


text:
Q: Animation repeats after keyup event I made a svg, css animation and added some jquery keyboard events.
Everytime when I hit the key the animation starts again and again.
Is there any way to only play the animation once the page is loaded?
also the swipe event doesn't work anymore (i tested it with an image before)
jquery:
$(document).ready(function(){
    $(document).keyup(function(e) {
        if (e.keyCode === 40) {
            $(".arrow_down").animate({
                top:"+=20px",
                opacity:"0"
            });
            $(".button").animate({
                opacity:"1"
            });
        }
          if (e.keyCode === 37) {
            $(".arrow_down").effect("bounce",{times:3}, 500 );
        }
         if (e.keyCode === 39) {
            $(".arrow_down").effect("bounce",{times:3}, 500 );
        }
         if (e.keyCode === 38) {
            $(".arrow_down").effect("bounce",{times:3}, 500 );
        }
    });
    $(".arrow_down").swipe({
        swipeDown:function(){
            $(".arrow_down svg").animate({top:"+=5%", opacity:"0"});
            $(".button").animate({opacity:"1"});
        }
    });
});

fiddle:
http://jsfiddle.net/9KwLW/

A: Okay; I figured it out.
It's maybe not the most elegant soloution, but I can't find a better one.
So I changed the class with the animation from "line" to "animline". Then after 700ms I search all items with class "line" and remove their class "animline" - I can't use jQuery for that, because jQuery can't search elements within SVG just now without any plugins, so why not to use some plain JavaScript.
See the fiddle: http://jsfiddle.net/9KwLW/2/
JS:
window.setTimeout(function(){
       lines = document.getElementsByClassName('line');
        for (i=0;i<lines.length;i++) {
             lines[i].classList.remove("animline");
        }
    },700);

CSS:
.animline {
  stroke-dasharray: 1000;
  stroke-dashoffset: 1000;
 -moz-animation: dash 5s linear forwards;
 -webkit-animation: dash 5s linear forwards;
 -moz-animation-timing-function: ease;
 -webkit-animation-timing-function: ease;
}

HTML:
<svg version="1.1" id="Ebene_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="7px" height="193px" viewBox="0 0 7 193" enable-background="new 0 0 7 193" xml:space="preserve"><line class="line animline" fill="none" stroke="#000000" stroke-width="7" stroke-miterlimit="10" x1="3.5" y1="0" x2="3.5" y2="193"/>
</svg>

<svg class="arrow_head" version="1.1" id="Ebene_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"width="63.25px" height="36.75px" viewBox="0 0 63.25 36.75" enable-background="new 0 0 63.25 36.75" xml:space="preserve"><polyline class="line animline" fill="none" stroke="#000000" stroke-width="7" stroke-miterlimit="10" points="60.5,2.686 31.688,30.509 2.875,2.686 "/></svg>

A: I may have a better solution for you:
Set the default stroke-dashoffset to 1 for .line and then set a from element to your dash animation that sets the stroke-dashoffset to 1000 at the beginning of the animation.
from {
        stroke-dashoffset: 1000;
    }
  to {
    stroke-dashoffset: 0;
  }

Now if you remove the animation attribute to .line, the arrow will be shown and no more animation will be triggered.
$(".line").css("-webkit-animation", "none").css("-moz-animation", "none");

http://jsfiddle.net/9KwLW/3/


text:
Q: If all things are equal (RAM, cores, database) is there any noticeable difference between SQL Server Web Edition and Standard Edition? I created a small project to learn web development using an SQL Server Web Edition 2019 database. It has 4 cores assigned to it and my web server has 64 gb RAM.
The project has grown a lot and now has over 10,000 users.
I want to improve the performance of the application I created which heavily uses the SQL Server database and I'm trying to get good value out of my next upgrade.
Is it worth upgrading to SQL Server Standard or am I best to max out the cores on Web Edition to 8 or 12? If all things are equal is there a noticeable difference in performance with low specs (4 cores, 64 gb RAM).
SQL Server Web edition maxes out at 64 GB RAM, so will updating the RAM to 128GB help in any way?
Thank you all in advance


text:
Q: Filltering 2nd combobox according to 1st combobox using PyQGIS? I have a layer of districts. Each district belongs to a different state. I want to write code that once you choose a state in the 2end combobox, you can only see districts from that certain state in the 3rd combobox.
I wrote the following code:
       def myFunction(self, layer, featureSet2):
    Feature_list3 = []
    del Feature_list3[0:len(Feature_list3)]
    indx = self.dlg.comboBox.currentIndex()
    Data = featureSet2[indx]
    layer.removeSelection()

    # Fill 3rd combobox
    self.dlg.comboBox_3.clear()
    for feature in layer.getFeatures():
        name = feature["NAME_2"]
        if Data==feature["TYPE_2"]:
            #print (Data)
            Feature_list3.append(name)

    self.dlg.comboBox_3.addItems(Feature_list3)
    # Fill 3rd combobox

def run(self):
    """Run method that performs all the real work"""
    layer = iface.addVectorLayer("C:/Users/carmel.han/Documents/QGIS/qgis_sample_data/shapefiles/regions.shp",
                                 "regions", "ogr")

    Feature_list = []
    Feature_list2 = []

    selection = []

#Fill 1st combobox
    self.dlg.comboBox.clear()
    for feature in layer.getFeatures():
        name = feature["name_1"]

        Feature_list.append(name)
    featureSet = set(Feature_list)
    self.dlg.comboBox.addItems(featureSet)
# Fill 1st combobox

# Fill 2end combobox
    Feature_list2 = []
    self.dlg.comboBox_2.clear()
    for feature in layer.getFeatures():
        name = feature["TYPE_2"]

        Feature_list2.append(name)
    featureSet2 = set(Feature_list2)
    self.dlg.comboBox_2.addItems(featureSet2)
    Feature_set2list2 = list(featureSet2)
# Fill 2end combobox

    slotLambda = lambda: self.myFunction(layer, Feature_set2list2)
    self.dlg.comboBox_2.currentIndexChanged.connect(slotLambda)

The if statment does not seem to work,it only gives me the districts of the first state, and does not change after further changes. can somebody point out the problem or show me how it's done?

A: Below is an example of how to do this using two functions. One for populating the first combobox.
Another that you connect to the currentIndexChanged signal of the first combobox that populates the second combobox with values depending on the first combobox (yes, I like to make complicated sentences...):
def populate_combobox1(self):
    #clear combobox 1 before populate it
    self.dlg.combobox1.clear()
    #retrieve the list to populate the combobox (unique values of field 'name_1')
    values = layer.uniqueValues(layerfieldNameIndex('name_1'))
    self.dlg.combobox1.addItems(values)

def on_combobox1_change(self):
    #clear combobox 2 before populate it
    self.dlg.combobox2.clear()
    # retrieve the values to populate combobox2
      # get the current value of combobox 1
    filter = self.dlg.combobox1.currentText()
      # get the corresponding values of TYPE_2 field to populate combobox2
    values = [feat['TYPE_2'] for feat in layer.getFeatures() if feat['name_1'] == filter]
    self.dlg.combobox2.addItems(values)

def run():
    #populate the first combobox
    self.populate_combobox1()
    #connect the function on the change of current index in combobox 1
    self.dlg.combobox1.currentIndexChanged.connect(self.on_combobox1_change)


text:
Q: Create a mysql view from sql server tables I'm trying to create a mysql view from some sql server tables but I have not found the way. I have created a lot of views and tables in sql server from mysql tables with a linked server on sql server management studio but now I'm trying to do it to the other side.

A: You cannot do that, MySQL does not have the concept of linked servers connecting to other RDBMS products. The federated table engine can only connect to other MySQL servers.
You have to push the data from the ms sql server side into MySQL tables and you can create a view based on those tables within MySQL.


text:
Q: Upload files to Cloud Storage from iOS, authenticated by App Engine We have an iOS app with App Engine and Cloud Endpoints as backend running java. We use custom user authentication so the user can log in with their own account or with Facebook. We do not use the built in user authentication in App Engine because it requires Google accounts.
We want to let users upload photos and videos from the app to Cloud Storage. In order to do this, the user must be authenticated in our App Engine backend first. What is the correct approach for combining these technologies in the given scenario?

A: First I find letting the control to iOS app to directly upload files to GCS is hard behaviour,
My suggestion to this will be have an endpoint which let the iOS app to upload the file then so do any processing (if required) and upload it to the GCS, this way the API have complete control over the process where you can have authentication checks , processing , custom actions etc

A: To play the devil's advocate, I'll remind that it's not necessary to send it to your app first, only this is preferred since you can take custom actions, deal with file duplicates, take actions based on the file contents, etc...
Technically, however, you could use the javascript API to GCS and bypass the need to send the traffic through your instance. This is particularly attractive if you're designing a web-app that uses rich client-side technology (various JS frameworks) to present a UI and manage application logic, rather than a traditional server-heavy web-app, in which case it makes sense to have the upload logic closer to the rest of your application logic, in the browser's JS.
This is also attractive if you expect high volume on your file uploads, in which case you'll want to avoid as much traffic costs as you can, freeing your instances to serve the site's dynamic resources.


text:
Q: Simple way of getting a file with ajax? Is there a way of getting a filename without having to upload information to a database using ajax?
I basically want to click on an html element, trigger a jquery function, and run php code to read a directory.
I know I can upload the filenames to a DB, then just pull the info off it with ajax, but it's a really small project and I'd like to not use a database.

A: AJAX doesnt care where you get you data. Because its just run the PHP script you are directing through when your ajax is triggered.To make it short what matters is the script you write to run when ajax trigerred it.
BASIC PHP FILE HANDLING


text:
Q: How do I filter a SQL query by a number of relations? I am having some problems with this homework question:

I have been able to successfully complete almost all of the query except for the "Only include states with at least 3 diamond mines". I would like to ask how I can add this part to the query.
select I.state, sum(P.capacity)
from Infrastructure I
natural join Mine M
join produces P
on P.mine = M.entryno
join Commodity C
on C.comID = P.commodity
where C.name like '%Diamond%'
group by I.state

A: If your attempt works fine other than condition mentioned in question following query should work:
select I.state, sum(P.capacity)
from Infrastructure I
natural join Mine M
join produces P
on P.mine = M.entryno
join Commodity C
on C.comID = P.commodity
where C.name like '%Diamond%'
group by I.state
having count(P.mine) >=3;

It will count the no. of commodity for each state as you already has group by on State.
Hope it helps!

A: Use a HAVING clause to count and assert the number of diamond mines:
SELECT
    I.state,
    SUM(P.capacity)
FROM Infrastructure I
NATURAL JOIN Mine M
INNER JOIN produces P
    ON P.mine = M.entryno
INNER JOIN Commodity C
    ON C.comID = P.commodity
WHERE
    C.name LIKE '%Diamond%'
GROUP BY
    I.state
HAVING
    COUNT(*) >= 3;

Note: Natural join seems error prone to me and could break at some point.  The best thing to use are explicit joins.


text:
Q: Broken axis slash marks inside bar chart in matplotlib? I've seen matplotlib examples of placing the broken axis slash marks on the axes, such as this one.
My questions, how can I place it where the bars are broken? Can this be done in a programmatic way for updating time-series plots month over month?
Below is an example of what I want done, using excel. Notice the tildes in the Paris June bar and the Madrid May bar. The tildes hide a portion of the bar it's covering.

I'm also providing easier sample data and what I've been able to do so far.
XX = pd.Series([200,400,100,1400],index=['x1','x2','x3','x4'])
fig, (ax1,ax2) = plt.subplots(2,1,sharex=True,
                         figsize=(5,6))
ax1.spines['bottom'].set_visible(False)
ax1.tick_params(axis='x',which='both',bottom=False)
ax2.spines['top'].set_visible(False)
ax2.set_ylim(0,500)
ax1.set_ylim(1200,1500)
ax1.set_yticks(np.arange(1000,1501,100))
XX.plot(ax=ax1,kind='bar')
XX.plot(ax=ax2,kind='bar')
for tick in ax2.get_xticklabels():
    tick.set_rotation(0)
d = .015
kwargs = dict(transform=ax1.transAxes, color='k', clip_on=False)
ax1.plot((-d, +d), (-d, +d), **kwargs)
ax1.plot((1 - d, 1 + d), (-d, +d), **kwargs)
kwargs.update(transform=ax2.transAxes)
ax2.plot((-d, +d), (1 - d, 1 + d), **kwargs)
ax2.plot((1 - d, 1 + d), (1 - d, 1 + d), **kwargs)
plt.show()

A: Just to show the principle, you can put the same kind of line at every position where a bar exceeds the upper limit of the lower axes and also where a bar exceeds the lower limit of the upper axes.
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np

XX = pd.Series([200,400,100,1400],index=['x1','x2','x3','x4'])
fig, (ax1,ax2) = plt.subplots(2,1,sharex=True,
                         figsize=(5,6))
ax1.spines['bottom'].set_visible(False)
ax1.tick_params(axis='x',which='both',bottom=False)
ax2.spines['top'].set_visible(False)

bs = 500
ts = 1000

ax2.set_ylim(0,bs)
ax1.set_ylim(ts,1500)
ax1.set_yticks(np.arange(1000,1501,100))

bars1 = ax1.bar(XX.index, XX.values)
bars2 = ax2.bar(XX.index, XX.values)

for tick in ax2.get_xticklabels():
    tick.set_rotation(0)
d = .015
kwargs = dict(transform=ax1.transAxes, color='k', clip_on=False)
ax1.plot((-d, +d), (-d, +d), **kwargs)
ax1.plot((1 - d, 1 + d), (-d, +d), **kwargs)
kwargs.update(transform=ax2.transAxes)
ax2.plot((-d, +d), (1 - d, 1 + d), **kwargs)
ax2.plot((1 - d, 1 + d), (1 - d, 1 + d), **kwargs)

for b1, b2 in zip(bars1, bars2):
    posx = b2.get_x() + b2.get_width()/2.
    if b2.get_height() > bs:
        ax2.plot((posx-3*d, posx+3*d), (1 - d, 1 + d), color='k', clip_on=False,
                 transform=ax2.get_xaxis_transform())
    if b1.get_height() > ts:
        ax1.plot((posx-3*d, posx+3*d), (- d, + d), color='k', clip_on=False,
                 transform=ax1.get_xaxis_transform())
plt.show()

It doesn't look great, but can of course be adapted with a nicer shape.

A: I needed broken y-axis some time ago and created some code to do it. Now, I have submitted it to PyPi so that others can use it. It's far from being a final version though. Any comments are welcome, and there is also the GitHub project, in which anyone can collaborate of course. Any issue, code and anything else is welcome.
Also, consider reading the following post. It gives some good reasons why a broken y-axis might not be desirable, before deciding on using it or not. One of the main points in my opinion is that breaking the y-axis makes the sense of proportion go away entirely. As it happens with limited y-axis ranges, it can be rather confusing to see a plot like this. That said, if used, I would recommend that the audience is made aware of the strange proportions that can arise from the use of this kind of plot.

*

*Broken Y Axis in an Excel Chart at Peltier Tech Blog

Installing:
pip install plotinpy

Here is some example usages of the broken y-axis:
Examples
Simple broken bars
plt.figure()
pnp.plot_bars_with_breaks(
    [1, 2, 30],
    [(15, 25)]
    )
plt.savefig("img/example1.png")

Styled broken bars
plt.figure()
pnp.plot_bars_with_breaks(
    [1, 2, 30, 1000],
    [(15, 25), (50, 975)],
    style="~~",
    break_args={"hatch": '///'}
    )
plt.savefig("img/example2.png")


text:
Q: Subversion and "protected/secure" files I have a requirement where certain code cannot be seen by all developers, but it's required for the full functional system.
So regular developers will be able to pull the main parts and authorized dev or manager will pull the rest and provide the artifact for the rest.
So for instance in SQL I have individual SQL files per SP. 2 of these SPs must be installed on the SQl server as encrypted SPs. The regular dev will pull and deploy everything but those 2 SPs and then the manager will pull the 2 SPs and install them for the dev.
There is very few cases like that in the project structure. So what is the best way to handle this?

A: That's an interesting setup. I've seen where people are not allowed to commit to a repository, but very few where people are not even allowed to look at the files that it contains -- especially developers. There are a couple of suggestions:

*

*Two Separate Repositories: This keeps the hidden code more easily hidden. Building is a bit more difficult, but the security is simple: Users have access to the repository, or they don't.

*Specifying Individual Directories: You can specify who has read/write requirements upon individual directories. This must be handled via the front-end security access, and not pre-commit scripts. Path-Based Authorization is discussed in the Subversion manual. Word of warning: Any change in authorization requires you to restart your Subversion repository server. It all depends whether you're using http:// or svn:// as your repository server.

I highly recommend using a completely separate repository for the secret code.


text:
Q: JQuery ASP.NET MVC drag and drop shopping cart doesnt retain cart items when navigating to different category I am very new to ASP.NET MVC and JQuery, I have built a e-commerce website in ASP.NET MVC, JQuery & C#. I used the Drag & Drop model from  http://www.codeproject.com/Articles/301620/Drag-Drop-Shopping-Cart-Using-Asp-net-MVC-and-JQuery which is great. I have modified the JQuery to meet all of my needs in regards to data retrieval, posting back data etc.
The problem I am having is I have different product categories that use my products.cshtml (view) so when a user wants to add more items to the current cart and the navigate to a new category all the existing items in the cart are removed when the postback occurs. My question is how do I keeps the current items in the cart when navigating to a different category.

A: You need to save changes of you cart somewhere. That somewhere may be cookie, database, session, etc. I would recommend to save that to database. To save that to database there may be various approaches, but you'll need for sure call action on server side, as long as you're using jQuery and Drag&Drop, probably that would be ajax call to MVC Action, that would save cart contents.
If you'll look at the comments of an article you've mentioned, I think there's solution for saving cart contents to database.


text:
Q: Long term voltage change - analog voltmeter, op-amps and logarithmic scale I want to display one minute voltage change on analog voltmeter.
Voltage change: from -0.5V/min to +0.5V/min.
My analog voltmeter has 0-10V scale (I will replace it with homemade printed scale).
I don't want to use any microcontroller, PWM etc.
I want to learn how to do it by using op-amps and single supply.
In future - I want to scale it logarithmically (-0.5, -0.05, -0.005, 0, +0.005, +0.05, +0.5), but for now - let's assume that I need just linear delta-V read.
WHAT I KNOW FOR NOW
I know that I need active differentiator block. I can use formula from Wikipedia, find resistor and capacitor value. After that block I can use some non-inverting block to amplify voltage to desired range and add 5V with summing amplifier block to have 0V/min at the center of my voltmeter scale.
WHAT IS MY PROBLEM
My problem is single supply. When voltage change will be negative - I guess single supply op-amp will not work properly.
How can I deal with that?
BACKGROUND
Long time ago I was bored and I built custom thermometer that measures water temperature at the output pipe of old central heating furnace. It is supposed to inform me about temperature and temperature change. I can see how fast temperature is rising or dropping, and I can estimate when I should go to basement and put some logs or coal into furnace.
There is analog LM35 temperature to voltage converter (linear, 10mV/°C), microcontroller with 10-bit ADC with high oversampling and low pass filter at input.
Display looks like this:

I realize that 0.01°C resolution for temperature read is huge overkill and my thermometer acurracy is about +/- 1°C, so please don't comment that.
Now I want to build analog version of this and use two analog voltmeters similar to this:

One will show temperature, another temperature change.

A: Let's take the straightforward part first. In order to deal with both positive and negative voltages from a single supply, what you need is a virtual ground, centered between ground and the positive supply.

simulate this circuit – Schematic created using CircuitLab
Use the new signal ground for all analog processing, with the op amps powered by ground and V1.
Now for the harder part. Your approach to measuring temperature differences will be very difficult. Your active differentiator is OK as far as it goes, but you haven't tried to calculate the RC values, and you need to do so. 0.5 V/min is .008 V/sec, and if you want to get 10 volts out, RC needs to be 10/.008, or 1200. You can get this, for instance, with a 1 uF capacitor and a 1.2 Gohm resistor. You may have some difficulty finding a resistor like this. So let's say you use a 1.2 Mohm resistor - then you need a 1000 uF capacitor. That may seem like no big deal, but you have to use a very special capacitor, one with a leakage current less than 80 nA if you want leakage to cause less than a 1% error. And that will be harder to find than a Gohm resistor. Either way, you'll have to learn all about managing leakage currents in your circuit.
Worse, even if you manage to get this working, it won't tell you what you want to know, which is the temperature trend over 1 minute intervals. All you'll know is what's happening right now, this very second - and that is likely to be very noisy. If you want to know about 1-minute intervals, you need to sample at one-minute intervals and display the difference. You can do this with, for instance, a pair of sample-and-hold circuits. But making a sample-and-hold which does not droop over a one minute hold interval is probably even harder than making your differentiator.
You can, of course, use discrete logic, an A/D converter and a D/A converter to do the job. A microcontroller will be much more compact. There's a reason this sort of display has only recently become widely available, and that is the proliferation of cheap, low-cost processors and peripherals. Some things just don't lend themselves to a pure analog approach.


text:
Q: Recover from problem in Linq submit If I change the values of a Linq class and then try to submit the changes to the database and get a conflict like string is to long or value can not be null, the database will not be changes. But the question is what's the best way is to recover from this commit problem and role back the values in the class to the unchanged values.

A: Linq to SQL creates a transaction for each query you execute, which will rollback on failure.  If you'd like more control over the transaction, like say if you want to perform many operations on your own, you can create a TransactionScope around your queries.

A: I would think more in terms of how do you prevent the error from occuring in the first place.  If you know there is a possibility that a submit will fail due to a string length, or null value, you should be checking for this prior to committing the records.
Remember, an exception is exactly that -- an exception to something you didn't think about when you were developing the solution.


text:
Q: Error while trying to get data from API - Blazor I built an API in ASP.NET Core and the code looks like this:
public async Task<IEnumerable<Applicant>> GetApplicants()
{
    return await appDbContext.Applicants.ToListAsync();
}

[HttpGet]
public async Task<ActionResult> GetApplicants()
{
    try
    {
        return Ok(await applicantRepository.GetApplicants());
    }
    catch (Exception)
    {
        return StatusCode(StatusCodes.Status500InternalServerError, "Error retreiving data from the database");
    }
}

Here we have how it looks in browser(guess that is fine):

Blazor (server) code:
public interface IApplicantService
{
    Task<IEnumerable<Applicant>> GetApplicants();
}

public class ApplicantService : IApplicantService
{
    private readonly HttpClient httpClient;
    public ApplicantService(HttpClient httpClient)
    {
        this.httpClient = httpClient;
    }
    public async Task<IEnumerable<Applicant>> GetApplicants()
    {
        return await httpClient.GetJsonAsync<Applicant[]>("api/applicants");
    }
}

public class ApplicantList : ComponentBase
{
    [Inject]
    public IApplicantService ApplicantService { get; set; }
    public IEnumerable<Applicant> Applicants { get; set; }

    protected override async Task OnInitializedAsync()
    {
        Applicants = (await ApplicantService.GetApplicants()).ToList();
    }
}

And the page:
@page "/"
@inherits ApplicantList

Applicants

    @foreach (var applicant in Applicants)
    {

@applicant.Name

                View

                Edit

                Delete

    }

I am facing null reference error. While debugging I see that Applicants is null

A: The solution to this is simple: wrap the foreach loop with an if statement like this:
@if( Applicants != null)
   {
       @foreach (var applicant in Applicants)
       {
        //...
       }
   }

Explanation: When you call the ApplicantService.GetApplicants() method in the lifecycle OnInitializedAsync method, the following occurs:
ApplicantService.GetApplicants() is called and awaited, the execution control is yielded to the calling code, till GetApplicants() completes...Blazor starts rendering the view portion of your component, but alas, the Applicants variable is not yet populated with data. It contains the null value, thus the exception.
Note: that when the GetApplicants() method completes, re-rendering occurs again, this time the Applicants variable contains the retrieved data.
Note: Don't use the GetJsonAsync method. Use instead the new set of methods and objects: Install-Package System.Net.Http.Json -Version 5.0.0


text:
Q: R code that iteratively creates a "rank_order" column for every column in a given dataframe Given a data frame such as the following, how do I get a rank order (e.g. integer column ranking the value in order from descending as "1,2,3") column output for every single column without writing out ever single column?
df <- data.frame(
  col1 = rnorm(100),
  col2 = rnorm(100),
  col3 = rnorm(100),
  col4 = rnorm(100))

rank_col1
rank_col2
rank_col3
etc...

A: Is this what you want?
df <- cbind(df, as.data.frame(apply(df, 2, rank)))


text:
Q: Numbering IDs based on group R I have the dataframe below called df1. I'd like to assign an ID based on as soon as it approaches 'Apple', it changes the ID number to the next ordinal number. When it's assigned 'Apple', I want all the corresponding labels after to be what was assigned for 'Apple'. But as soon as 'Apple' comes up, it goes up a number as with the following labels.
Thanks and much appreciated!
df1 <- data.frame (fruit_name  = c("Apple", "Banana", "Cherry",
                           "Orange", "Blueberry", "Peach",
                           "Apple", "Banana", "Cherry",
                           "Orange", "Blueberry", "Peach",
                           "Apple", "Banana", "Cherry",
                           "Orange", "Blueberry",
                           "Apple", "Cherry"))

into the following
df2 <- data.frame (ID  = c("1", "1", "1", "1", "1", "1", "2", "2",
                           "2", "2", "2", "2", "3", "3", "3", "3", "3",
                           "4", "4"),
                   fruit_name = c("Apple", "Banana", "Cherry",
                                  "Orange", "Blueberry", "Peach",
                                  "Apple", "Banana", "Cherry",
                                  "Orange", "Blueberry", "Peach",
                                  "Apple", "Banana", "Cherry",
                                  "Orange", "Blueberry",
                                  "Apple", "Cherry"))

A: We can use rowid
library(data.table)
df1$ID <- rowid(df1$fruit_name)

A: You can use cumsum
df1$ID <- cumsum(df1$fruit_name == 'Apple')


text:
Q: WPF UserControl container to Drag Window I am trying to make a container UserControl (like a border) which can drag the current Window when you hold left click inside the UserControl.
UserControl.XAML :
<UserControl.InputBindings>
    <MouseBinding Gesture="LeftClick" Command="{Binding DragWindowCommand, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=UserControl}}" CommandParameter="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Window}}"/>
</UserControl.InputBindings>

UserControl.CS (Code Behind) :
    public partial class DragWindowBorder : UserControl
    {
        #region Commands
        public BaseCommand<Window> DragWindowCommand
        {
            get => new BaseCommand<Window>(/*async*/(window) => {
                window.DragMove();
            });
        }
        #endregion

        public DragWindowBorder()
        {
            InitializeComponent();
        }
    }

BaseCommand.CS :
    public class BaseCommand<T> : ICommand
    {
        #region Variables

        private readonly Action<T> _execute;
        private readonly Func<T, bool> _canExecute;
        public event EventHandler CanExecuteChanged;

        #endregion

        #region Methods
        public BaseCommand(Action<T> execute) : this(execute, null) { }

        public BaseCommand(Action<T> execute, Func<T, bool> canExecute)
        {
            if (execute == null)
            {
                throw new ArgumentNullException("execute");
            }

            _execute = execute;
            _canExecute = canExecute;
        }

        public void OnCanExecuteChanged()
        {
            if (CanExecuteChanged != null)
            {
                CanExecuteChanged(this, EventArgs.Empty);
            }
        }

        public bool CanExecute(object parameter)
        {
            return _canExecute == null || _canExecute((T)parameter);
        }

        public void Execute(object parameter)
        {
            if (CanExecute(parameter) && _execute != null)
            {
                T param = default(T);
                try
                {
                    param = (T)parameter;
                }
                catch { }

                _execute(param);
            }
        }

        #endregion
    }

My problem is the following :

*

*When I call my UserControl containing a TextBlock the drag works fine

*When I call my UserControl containing a TextBox or a Grid for example, the drag doesn't work

MainWindow.XAML :
<!-- Working -->
<controls:DragWindowBorder>
       <TextBlock Text="test"/>
</controls:DragWindowBorder>

<!-- Not Working -->
<controls:DragWindowBorder>
       <TextBox Text="test"/>
</controls:DragWindowBorder>

<!-- Not Working -->
<controls:DragWindowBorder>
         <Grid>
               <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="*"/>
               </Grid.ColumnDefinitions>
         </Grid>
</controls:DragWindowBorder>

For some reason my UserControl seems not being able to capture left clicks when containing certain controls.
Can you help me figure out how to fix this issue?

A: I managed to solve my problem.
1 - For the TextBox example, the TextBox is over my UserControl so it is capturing the left click instead of my User control.
2 - For the Gid example, I need to set a background in my UserControl as so :
<UserControl x:Class="Default.Common.Controls.Views.DragWindowBorder"
             ...
             Background="Transparent">

By default UserControls do not have any background, so they can not capture mouse clicks if they are filled with empty components (like an empty grid column in my example).


text:
Q: ¿Cómo validar un RFC de México y su digito verificador? Pregunta: ¿Cómo puedo verificar que el formato de un RFC mexicano sea válido?
¿Qué es el RFC? El Registro Federal de Contribuyentes (RFC) es una clave única que requiere toda persona física o moral en México para realizar cualquier actividad económica lícita. Es el código tributario de personas y empresas expedido por el SAT.
El RFC se genera a partir de las letras del nombre y los apellidos (personas), o de las siglas o las primeras letras del nombre y la fecha de creación (empresas). Las reglas de generación y validación están descriptas en el Algoritmo para generar el RFC con homoclave para personas fisicas y morales.odt .
Contexto: Quiero validar que un RFC podría ser válido. No me interesa ver si efectivamente existe. Implementé una validación muy genérica que permite que los últimos 3 dígitos sean opcionales:
/^[A-ZÑ&]{3,4}\d{6}(?:[A-Z\d]{3})?$/

pero ahora me interesa validar más estrictamente el RFC completo, viendo que el dígito verificador sea correcto (el último caracter).

A: Expresión regular
La siguiente expresión regular verifica:

*

*Los primeros 3 (persona moral) o 4 (persona física) caracteres en mayúsculas.

*Fecha válida (aunque para simplificarlo, no se están validando meses con menos de 31 días).

*El dígito verificador sea un dígito o una letra A.

*Permitiendo que haya guiones y/o espacios entre las partes.

*Capturando cada parte en un grupo.

/^([A-ZÑ&]{3,4}) ?(?:- ?)?(\d{2}(?:0[1-9]|1[0-2])(?:0[1-9]|[12]\d|3[01])) ?(?:- ?)?([A-Z\d]{2})([A\d])$/

Validación completa
Publico el código en JavaScript para poder correrlo acá, pero es muy sencillo de llevar a cualquier otro lenguaje.

//Función para validar un RFC
// Devuelve el RFC sin espacios ni guiones si es correcto
// Devuelve false si es inválido
// (debe estar en mayúsculas, guiones y espacios intermedios opcionales)
function rfcValido(rfc, aceptarGenerico = true) {
    const re       = /^([A-ZÑ&]{3,4}) ?(?:- ?)?(\d{2}(?:0[1-9]|1[0-2])(?:0[1-9]|[12]\d|3[01])) ?(?:- ?)?([A-Z\d]{2})([A\d])$/;
    var   validado = rfc.match(re);

    if (!validado)  //Coincide con el formato general del regex?
        return false;

    //Separar el dígito verificador del resto del RFC
    const digitoVerificador = validado.pop(),
          rfcSinDigito      = validado.slice(1).join(''),
          len               = rfcSinDigito.length,

    //Obtener el digito esperado
          diccionario       = "0123456789ABCDEFGHIJKLMN&OPQRSTUVWXYZ Ñ",
          indice            = len + 1;
    var   suma,
          digitoEsperado;

    if (len == 12) suma = 0
    else suma = 481; //Ajuste para persona moral

    for(var i=0; i<len; i++)
        suma += diccionario.indexOf(rfcSinDigito.charAt(i)) * (indice - i);
    digitoEsperado = 11 - suma % 11;
    if (digitoEsperado == 11) digitoEsperado = 0;
    else if (digitoEsperado == 10) digitoEsperado = "A";

    //El dígito verificador coincide con el esperado?
    // o es un RFC Genérico (ventas a público general)?
    if ((digitoVerificador != digitoEsperado)
     && (!aceptarGenerico || rfcSinDigito + digitoVerificador != "XAXX010101000"))
        return false;
    else if (!aceptarGenerico && rfcSinDigito + digitoVerificador == "XEXX010101000")
        return false;
    return rfcSinDigito + digitoVerificador;
}

//Handler para el evento cuando cambia el input
// -Lleva la RFC a mayúsculas para validarlo
// -Elimina los espacios que pueda tener antes o después
function validarInput(input) {
    var rfc         = input.value.trim().toUpperCase(),
        resultado   = document.getElementById("resultado"),
        valido;

    var rfcCorrecto = rfcValido(rfc);   // ⬅ Acá se comprueba

    if (rfcCorrecto) {
     valido = "Válido";
      resultado.classList.add("ok");
    } else {
     valido = "No válido"
     resultado.classList.remove("ok");
    }

    resultado.innerText = "RFC: " + rfc
                        + "\nResultado: " + rfcCorrecto
                        + "\nFormato: " + valido;
}
#resultado {
    background-color: red;
    color: white;
    font-weight: bold;
}
#resultado.ok {
    background-color: green;
}
RFC:
<input type="text" id="rfc_input" style="width:100%;"
       oninput="validarInput(this)"
       placeholder="Ingrese su RFC">

Descripción
Tomando como referencia la forma en que se construye el RFC:

*

*Los primeros 3-4 caracteres se toman del nombre ([A-ZÑ&]{3,4}) Grupo 1.

*

*Inicial del apellido paterno (o primera inicial de la empresa).

*Primera vocal interna del apellido paterno (o segunda inicial de la empresa).
* En este caso, podríamos haber validado que sea sólo una vocal o una "X", pero si el primer apellido tiene 1 o 2 letras, se toma la primera letra del apellido materno (puede ser una consonante).
* Para las empresas, si no tienen 3 palabras, se toman las siguientes letras del primer nombre.

*Inicial del apellido materno (o tercera inicial de la empresa).

*Inicial del nombre (nada para empresas, tienen 3 caracteres en total).

*Espacios o guiones opcionales ?(?:- ?)?.
Acepta: " ", "-", " -", " - ", "- ", o sin guiones ni espacios.
* El patrón se ve gracioso pero es: un espacio opcional, seguido de un grupo opcional (sin capturar), éste coincide con un guión seguido opcionalmente de un espacio. Si no se quiere permitir espacios ni guiones, se puede eliminar este patrón.

*La fecha de nacimiento (o de creación de la empresa).
(\d{2}(?:0[1-9]|1[0-2])(?:0[1-9]|[12]\d|3[01])) Grupo 2.

*

*\d{2} año.

*(?:0[1-9]|1[0-2]) mes.

*(?:0[1-9]|[12]\d|3[01]) día.
* Estoy aceptando hasta 31 para cualquier mes. Considero que un error al ingresar los datos de la fecha se validaría más adelante con el dígito verificador. No obstante, si se quisiera ser más estricto, y aunque se podría validar en la expresión regular, recomendaría hacerlo con las funciones del lenguaje de programación utilizado.

*Espacios o guiones opcionales ?(?:- ?)?.

*Homoclave de 2 caracteres alfanuméricos ([A-Z\d]{2}) Grupo 3.

*Dígito verificador (dígito o letra A) ([A\d]) Grupo 4.

Luego de validar con el regex, comprobamos que el dígito verificador esperado para los primeros 11 o 12 caracteres coincida con el dígito verificador ingresado (el último caracter). Se utiliza una adaptación del método para códigos de control llamado Módulo 11 o ISBN 10.
Ya tenemos capturas por separado del texto de las 4 partes del RFC, en donde rfcSinDigito serán los primeros 11 o 12 caracteres y digitoVerificador será el último caracter.
//Separar el dígito verificador del resto del RFC
const digitoVerificador = validado.pop(),
      rfcSinDigito      = validado.slice(1).join(''),

Pero si son 11 caracteres (RFC de persona moral -empresa), se lo ajusta para poder usar el mismo algoritmo para ambos. Se lo puede preceder con un espacio, o directamente ingresar el valor calculado.
if (len == 12) suma = 0
else suma = 481; //Ajuste para persona moral

Para calcular el dígito esperado, primero se suma el índice de cada caracter desde 13 hasta 2, multiplicado por el valor de cada uno de los 12 caracteres, los cuales tienen un valor de 0 a 38 según este orden (diccionario):
0123456789ABCDEFGHIJKLMN&OPQRSTUVWXYZ Ñ

for(var i=0; i<len; i++)
    suma = suma + diccionario.indexOf(rfcSinDigito.charAt(i)) * (indice - i);

Y sobre la suma, se toma el complemento a 11 del resto de dividir por 11 (o módulo 11, de ahí el nombre del método).
digitoEsperado = 11 - suma % 11;

Si da 11, se convierte en 0. Si da 10, se convierte en A.
if (digitoEsperado == 11) digitoEsperado = 0;
else if (digitoEsperado == 10) digitoEsperado = "A";

Ahora sí, podemos comparar si coinciden para devolver el resultado.
if (digitoVerificador != digitoEsperado)
    return false;

Pero agregamos 2 excepciones, para los casos especiales de RFCs genéricos (Preguntas y respuestas sobre Comprobación Fiscal, puntos 5 y 6 ), que no son RFCs válidos de personas físicas o morales, pero se utilizan para:
1. XAXX010101000 ::: Operaciones efectuadas con público en general.
2. XEXX010101000 ::: Operaciones efectuadas con residentes en el extranjero que no se encuentren inscritos en el RFC.
if ((digitoVerificador != digitoEsperado)
 && (!aceptarGenerico || rfcSinDigito + digitoVerificador != "XAXX010101000"))
    return false;
else if (!aceptarGenerico && rfcSinDigito + digitoVerificador == "XEXX010101000")
    return false;

* Como se ve, estoy usando un segundo parámetro opcional (aceptarGenerico), en caso de que no se permitan.

Finalmente, si pasó todas las reglas anteriores, se devuelve el RFC limpio.
return rfcSinDigito + digitoVerificador;

A: Ingresando a la pagina del SAT https://portalsat.plataforma.sat.gob.mx/ConsultaRFC/
pude obtener la expresión regular y la función que ellos utilizán espero les sirva:
// patron del RFC, persona moral
_rfc_pattern_pm = "^(([A-ZÑ&]{3})([0-9]{2})([0][13578]|[1][02])(([0][1-9]|[12][\\d])|[3][01])([A-Z0-9]{3}))|" +
                  "(([A-ZÑ&]{3})([0-9]{2})([0][13456789]|[1][012])(([0][1-9]|[12][\\d])|[3][0])([A-Z0-9]{3}))|" +
                  "(([A-ZÑ&]{3})([02468][048]|[13579][26])[0][2]([0][1-9]|[12][\\d])([A-Z0-9]{3}))|" +
                  "(([A-ZÑ&]{3})([0-9]{2})[0][2]([0][1-9]|[1][0-9]|[2][0-8])([A-Z0-9]{3}))$";
 // patron del RFC, persona fisica
 _rfc_pattern_pf = "^(([A-ZÑ&]{4})([0-9]{2})([0][13578]|[1][02])(([0][1-9]|[12][\\d])|[3][01])([A-Z0-9]{3}))|" +
                       "(([A-ZÑ&]{4})([0-9]{2})([0][13456789]|[1][012])(([0][1-9]|[12][\\d])|[3][0])([A-Z0-9]{3}))|" +
                       "(([A-ZÑ&]{4})([02468][048]|[13579][26])[0][2]([0][1-9]|[12][\\d])([A-Z0-9]{3}))|" +
                       "(([A-ZÑ&]{4})([0-9]{2})[0][2]([0][1-9]|[1][0-9]|[2][0-8])([A-Z0-9]{3}))$";

function ValidaRFC(){
    var rfc = document.getElementById("ConsultaForm:rfc").value;
    if (rfc.match(_rfc_pattern_pm) || rfc.match(_rfc_pattern_pf)){
            alert("La estructura de la clave de RFC es valida");
            return true;
        }else {
            alert("La estructura de la clave de RFC es incorrecta.");
            return false;
        }
}

A: Algoritmo de validación de RFC
Un RFC es válido si y solo si cumple las siguientes 7 condiciones:

*

*El RFC debe tener exactamente 12 o 13 carácteres (12 para personas morales y 13 para personas físicas). Es posible que nuestra interfaz de usuario permita introducir guiones, espacios u otros carácteres separadores. Aquí hablo solo de los carácteres que componen el RFC, los separadores se tratarían a otro nivel.

*Los carácteres del nombre pueden solo contener las letras mayúsculas A-Z, el símbolo & y la Ñ. Para RFC de 12 carácteres el nombre son los 3 primeros y para 13 son los 4 primeros.

*El nombre no es inconveniente. Hay una tabla con 41 nombres inconvenientes en el documento, por ejemplo MOCO, un RFC valido no puede tener ese nombre. Todos los nombres inconvenientes son para personas físicas (son todos de cuatro letras) pero al hacer la comprobación no es necesario comprobar que el RFC sea de 13 carácteres. Podemos comprobar contra los cuatro primeros directamente, si diésemos como incorrecto un RFC de persona moral por este motivo el resultado sería válido porque esto solo puede suceder si el primer dígito de la fecha no es una cifra, que sería un RFC incorrecto.

*La fecha es válida. La fecha son los 6 carácteres que siguen al nombre. En formato AAMMDD ( dos últimas cifras del año, mes 01 a 12 y día 01 a 31). No sería válido ni 331403 (3 del mes 14 de algún año acabado en 33). Tampoco sería válido 010229 (29 de febrero de algún año acabado en 01).

*El primer carácter diferenciador de homonimia es válido.Este es el primero que sigue a la fecha. Debe ser una letra mayúscula de la A a la V, ambas inclusive, o una cifra del 1 al 9 ambas inclusive, la Ñ y el 0 no son válidas. Esto es así porque en el apartado PROCEDIMIENTO PARA OBTENER LA CLAVE DIFERENCIADORA DE HOMONIMIA del documento que figura en la pregunta hay un paso en que se divide un número de 3 cifras entre 34 y se consulta una tabla. 999/34 = 29 . En esa tabla el 29 es la letra V

*El segundo carácter diferenciador de homonimia es válido. Este es el que sigue al anterior. Debido al procedimiento que se sigue este puede ser cualquier carácter de la tabla correspondiente, es decir, de la A a la Z y del 1 al 9. La Ñ y el 0 no son válidos. El documento describe cómo se calculan los 2 carácteres diferenciadores de homonimia, pero esto no nos interesa porque solo disponemos del RFC y no del nombre que dio lugar a esos 2 carácteres diferenciadores de homonimia.

*El dígito Verificador debe ser correcto. El dígito verificador es el último. Solo puede ser una cifra del 0 al 9 o la letra A. Y se calcula en función de los otros carácteres del RFC. Este dígito actúa como un código detector de errores que permite detectar la mayoría de errores cometidos por usuarios al introducir un RFC.

Nótese que por válido nos referimos a un RFC que cumple todas las normas del documento, es decir, existe una combinación de nombre y fecha de nacimiento o creación que genera ese RFC. Mientras que para un RFC inválido no hay ningún nombre y fecha que acabe generando ese RFC. Que sea válido no significa que exista.
Cálculo del dígito de verificación.
Si el RFC tiene 12 carácteres añadimos un espacio en blanco al principio.
Usamos todos los carácteres del RFC excepto el último. Es decir, usamos 12 carácteres siempre.
Cada carácter se corresponde con un valor según la siguiente tabla:

El valor del primer carácter se multiplica por 13, el segundo por 12, el tercero por 11 y así sucesivamente hasta el carácter duodécimo que se multiplica por 2.
Todos estos valores se suman. Y con la suma el documento describe unas operaciones innecesariamente complicadas que son equivalentes a :

*

*A 11000 le restas la suma. Calculas el módulo 11 de la resta.

*Si el resultado del módulo es 10 el dígito verificador es la A. En otro caso es el mismo número que has obtenido.

Ejemplo para el RFC GODE561231GR8
Carácter Valor Multiplicador  Resultado
    G     16  *     13      =    208
    O     25  *     12      =    300
    D     13  *     11      =    143
    E     14  *     10      =    140
    5      5  *      9      =     45
    6      6  *      8      =     48
    1      1  *      7      =      7
    2      2  *      6      =     12
    3      3  *      5      =     15
    1      1  *      4      =      4
    G     16  *      3      =     48
    R     28  *      2      =     56
-------------------------------------
                         SUMA : 1026
( 11000 - 1026 ) % 11 = 8 -> El dígito verificador es 8
El RFC es Válido.

Expresión Regular
Si fuese a utilizar una expresión regular como paso previo a la validación usaría :
[A-ZÑ&]{3,4}\d{6}[A-V1-9][A-Z1-9][0-9A]

Esta expresión acepta fechas incorrectas como 999999. Ni el día 99 ni el mes 99 existen.
No le veo sentido al complicar el regex, para rechazar los días que empiecen por 9 por ejemplo, puesto que de todas formas se van a quedar fechas no comprobadas por el regex (salvo que use un regex muy complicado). Es mejor dejar el análisis léxico para los regex (ver si los carácteres son válidos) y el semántico para otros niveles (ver si la fecha es correcta). Pero esto es opinable.
Usando Python y una biblioteca.
Con frecuencia la mejor manera de implementar algo es no hacerlo y usar una implementación ya hecha si está disponible y es fiable. Salvo para fines educativos o ciertos requisitos muy especiales.
Hay varias librerías que comprueban un RFC. Por ejemplo stdnum de Arthur de Jong and others.
Disponible en https://github.com/arthurdejong/python-stdnum bajo licencia GNU Lesser General Public License versión 2.1 o posterior.
#!/usr/bin/env python
from stdnum.mx.rfc import (validate,InvalidComponent,InvalidFormat,
InvalidLength,InvalidChecksum)

# Devuelve true si el RFC pasado es valido
# rfc es un string
def esValido(rfc):
  try:
    validate( rfc, validate_check_digits=True)
    return True
  except (InvalidComponent,InvalidFormat,InvalidLength,InvalidChecksum):
    return False

Poco hay que comentar, ya viene todo hecho por la biblioteca.
Usando programación funcional. En Scala
La función que hace la comprobación es la única pública y también se llama esValido. Al igual que la de Python devuelve true si el RFC pasado es válido.
El código incluye comentarios que explican su funcionamiento.
object RFCcheck extends  App {
  private val caracteres = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"

  // Estos son los carácteres permitidos en las 3 primeras posiciones (personas
  // morales, longitud total RFC es 12) o las 4 primeras posiciones (personas
  // físicas, longitud total RFC es 3)
  private val caracteresPrimeraParte = caracteres + "Ñ&"

  // Cifras permitidas en los 6 carácteres de la fecha
  private val cifras = "0123456789"

  // Carácteres permitidos en el dígito validador
  private val caracteresValidador = cifras + "A"

  // Valores permitidos para los carácteres primero y segundo de la clave
  // diferenciadora de la homonimia
  // Estos valores estan en la tabla del anexo 2
  // Nótese que el primer carácter se obtiene dividiendo un numero de 3 cifras
  // entre 34
  // 999/34 = 29 . Por tanto el máximo carácter en ese caso es 'V'
  private val caracteresHomonimia1 = "123456789ABCDEFGHIJKLMNOPQRSTUV"
  private val caracteresHomonimia2 = caracteresHomonimia1 + "WXYZ"

  // Comprobar que la fecha es valida
  // Por ejemplo, no permitir el 97 de octubre o el mes 17
  // Nótese que se permite el 29 de febrero de los años acabados en 00
  //porque el año 2100 no tendrá ese día pero el 2000 sí lo tuvo
  private val maxDiaMes = -1::31::28::31::30::31::30::31::31::30::31::30::31::
    Nil
  private def fechaValida( s:String ):Boolean = {
    val anyo = s.substring( 0, 2).toInt
    val mes  = s.substring( 2, 4).toInt
    val dia  = s.substring( 4, 6).toInt
    if ( mes<1 || mes>12 ) return false
    if ( dia<1 ) return false
    if ( anyo%4==0 && mes==2 ) return dia<=29
    dia<=maxDiaMes(mes)
  }

  // Carácteres en el orden de la tabla del anexo 3. Su posición es igual al
  // valor que se les asigna en la tabla del Anexo 3
  private val tablaAnexo3 = "0123456789ABCDEFGHIJKLMN&OPQRSTUVWXYZ Ñ"

  // Cálculo del dígito verificador
  private def calculaDigitoVerificador( rfc:String ):Char = {
    // Usar el rfc sin el último carácter que es el verificador
    // Para las personas morales se añade un espacio al principio
    val rfcSinDigitoV = if (rfc.length==13 ) rfc.substring(0,12)
    else " " +rfc.substring(0,11)
    // Para cada carácter multiplicamos su valor por (13 - posicion)
    // Y calculamos la suma de todas esas multiplicaciones
    val suma = (0 until 12 zip rfcSinDigitoV) .
      foldLeft (0) ( (acu,p) => acu + tablaAnexo3.indexOf(p._2) * (13-p._1) )
    // Y calculamos el dígito verificador (11000-suma) módulo 11.
    // caracteresValidador tiene los carácteres en el orden que
    // necesitamos del 0 al 10 (el décimo es la A)
    caracteresValidador( (11000-suma) % 11)
  }

  // Palabras no permitidas según el anexo 4
  private val palabrasInconvenientes = "BUEI"::"BUEY"::"CACA"::"CACO"::"CAGA"::
    "CAGO"::"CAKA"::"CAKO"::"COGE"::"COJA"::"COJE"::"COJI"::"COJO"::"CULO"::
    "FETO"::"GUEY"::"JOTO"::"KACA"::"KACO"::"KAGA"::"KAGO"::"KOGE"::"COJO"::
    "KAKA"::"KULO"::"MAME"::"MAMO"::"MEAR"::"MEAS"::"MEON"::"MION"::"MOCO"::
    "MULA"::"PEDA"::"PEDO"::"PENE"::"PUTA"::"PUTO"::"QULO"::"RATA"::"RUIN"::
    Nil

  // Calcula si es válido un rfc
  // El RFC debe tener exáctamente 12 carácteres para personas morales
  // Y 13 carácteres para personas físicas
  // No se admiten separadores como espacios o guiones
  def esValido( rfc:String ):Boolean = {
    val nombre = rfc.substring(0, rfc.length - 9) // Primeros 3 o 4 carácteres
    val fecha  = rfc.substring(rfc.length - 9, rfc.length - 3) // 6 carácteres
    val homonimia1 = rfc(rfc.length-3) // 1º char de clave dif de homonimia
    val homonimia2 = rfc(rfc.length-2) // 2º char de clave dif de homonimia
    val digitoVerificador = rfc(rfc.length-1) // Último carácter
    // Un RFC es válido si se cumple todo lo siguiente:
    (rfc.length == 12 || rfc.length == 13) && // 12 o 13 de longitud
      // Solo carácteres permitidos en nombre
      nombre.foldLeft(true)(_ && caracteresPrimeraParte.contains(_)) &&
      // Solo carácteres permitidos en fecha
      fecha. foldLeft(true)(_ && cifras.contains(_)) &&
      // Solo carácteres permitidos en clave diferenciadora de homonimia
      caracteresHomonimia1.contains(homonimia1) &&
      caracteresHomonimia2.contains(homonimia2) &&
      // La fecha es valida
      fechaValida(fecha) &&
      // Nombre no es una palabra inconveniente
      !palabrasInconvenientes.contains(nombre) &&
      // El digito verificador es correcto
      digitoVerificador == calculaDigitoVerificador(rfc)
  }
}

Observaciones
En el documento Algoritmo para generar el RFC con homoclave para personas fisicas y morales.odt  en la regla 9ª de la sección 2.2 figuran 39 palabras inconvenientes que no se pueden usar en un RFC. Sin embargo en el Anexo 4 figuran 41 palabras. Las 2 palabras extra son CAKO y MEAS. Yo he supuesto que el anexo es el correcto.
He probado con un millón de RFCs aleatorios, correctos e incorrectos, y las dos implementaciones han dado el mismo resultado en todos los casos. Aunque esto tampoco es garantía de nada.
No doy como buenos XEXX010101000 ni XAXX010101000 porque en el documento no se mencionan. La biblioteca de python hace lo mismo. Caso de que fuese necesario darlos como buenos es trivial hacer la modificación.

A: API gratuita
API open source siempre gratuita con un tiempo de respuesta de 600 ms y en 2 pasos para verificar el rfc, saber si esta en la lista negra del SAT y en  LRFC: Documentacion.
Expresión regular
La siguiente expresión regular (en el codigo) verifica:

*

*De manera individual a la persona moral y a la persona fisica.

*Si acepta  XAXX010101000 y XEXX010101000

*Si acepta AAAA0101010A8, AAAA010101AZ3 y MOCO010101AA9, pero el SAT en su sistema busca en su base de datos y devuelve "RFC no registrado en el padrón de contribuyentes". Es decir, no estan en LRFC.

Seguiendo la logica de SAT SAT 2 por la respuesta Orlando Alfonso. Usando el codigo ejemplo de Mariano.

//Función para validar un RFC
// Devuelve el RFC sin espacios ni guiones si es correcto
// Devuelve false si es inválido
// (debe estar en mayúsculas, guiones y espacios intermedios opcionales)
function rfcValido(rfc, aceptarGenerico = true) {
     _rfc_pattern_pm = "^(([A-ZÑ&]{3})([0-9]{2})([0][13578]|[1][02])(([0][1-9]|[12][\\d])|[3][01])([A-Z0-9]{3}))|" +
              "(([A-ZÑ&]{3})([0-9]{2})([0][13456789]|[1][012])(([0][1-9]|[12][\\d])|[3][0])([A-Z0-9]{3}))|" +
              "(([A-ZÑ&]{3})([02468][048]|[13579][26])[0][2]([0][1-9]|[12][\\d])([A-Z0-9]{3}))|" +
              "(([A-ZÑ&]{3})([0-9]{2})[0][2]([0][1-9]|[1][0-9]|[2][0-8])([A-Z0-9]{3}))$";
 _rfc_pattern_pf = "^(([A-ZÑ&]{4})([0-9]{2})([0][13578]|[1][02])(([0][1-9]|[12][\\d])|[3][01])([A-Z0-9]{3}))|" +
                   "(([A-ZÑ&]{4})([0-9]{2})([0][13456789]|[1][012])(([0][1-9]|[12][\\d])|[3][0])([A-Z0-9]{3}))|" +
                   "(([A-ZÑ&]{4})([02468][048]|[13579][26])[0][2]([0][1-9]|[12][\\d])([A-Z0-9]{3}))|" +
                   "(([A-ZÑ&]{4})([0-9]{2})[0][2]([0][1-9]|[1][0-9]|[2][0-8])([A-Z0-9]{3}))$";
   return rfc.match(_rfc_pattern_pm) || rfc.match(_rfc_pattern_pf);
}

//Handler para el evento cuando cambia el input
// -Lleva la RFC a mayúsculas para validarlo
// -Elimina los espacios que pueda tener antes o después
function validarInput(input) {
    var rfc         = input.value.trim().toUpperCase(),
        resultado   = document.getElementById("resultado"),
        valido;

    var rfcCorrecto = rfcValido(rfc);   // ⬅ Acá se comprueba

    if (rfcCorrecto) {
        valido = "Válido";
      resultado.classList.add("ok");
    } else {
        valido = "No válido"
        resultado.classList.remove("ok");
    }

    resultado.innerText = "RFC: " + rfc
                        + "\nFormato: " + valido;
}
#resultado {
    background-color: red;
    color: white;
    font-weight: bold;
}
#resultado.ok {
    background-color: green;
}
RFC:
<input type="text" id="rfc_input" style="width:100%;"
       oninput="validarInput(this)"
       placeholder="Ingrese su RFC">

Funciona en otros lenguajes. Aqui un ejemplo en go.
func ensureRFC(rfc string) bool {
    naturalPerson, _ := regexp.MatchString("^(([A-ZÑ&]{4})([0-9]{2})([0][13578]|[1][02])(([0][1-9]|[12][\\d])|[3][01])([A-Z0-9]{3}))|(([A-ZÑ&]{4})([0-9]{2})([0][13456789]|[1][012])(([0][1-9]|[12][\\d])|[3][0])([A-Z0-9]{3}))|(([A-ZÑ&]{4})([02468][048]|[13579][26])[0][2]([0][1-9]|[12][\\d])([A-Z0-9]{3}))|(([A-ZÑ&]{4})([0-9]{2})[0][2]([0][1-9]|[1][0-9]|[2][0-8])([A-Z0-9]{3}))$",
    rfc)
    legalPerson, _ := regexp.MatchString("^(([A-ZÑ&]{3})([0-9]{2})([0][13578]|[1][02])(([0][1-9]|[12][\\d])|[3][01])([A-Z0-9]{3}))|(([A-ZÑ&]{3})([0-9]{2})([0][13456789]|[1][012])(([0][1-9]|[12][\\d])|[3][0])([A-Z0-9]{3}))|(([A-ZÑ&]{3})([02468][048]|[13579][26])[0][2]([0][1-9]|[12][\\d])([A-Z0-9]{3}))|(([A-ZÑ&]{3})([0-9]{2})[0][2]([0][1-9]|[1][0-9]|[2][0-8])([A-Z0-9]{3}))$",
    rfc)
    return !naturalPerson && !legalPerson
}

A: Actualmente ocupo esta expresion regular, valida lo siguiente:

*

*10 Digitos (sin homoclave)

*12 Digitos (moral)

*13 Digitos

/^[a-zA-Z]{3,4}(\d{6})((\D|\d){2,3})?$/

function validaRFC(){
  let pattern = /^[a-zA-Z]{3,4}(\d{6})((\D|\d){2,3})?$/;
  let rfc = document.getElementById("rfc").value;
  document.getElementById("estatus").innerHTML = pattern.test(rfc);
}
<input id="rfc" type="text" onkeyup="validaRFC()"/>