text:
Q: What mathematical treatment is there on the renormalization group flow in a space of Lagrangians? What mathematical treatment is there on the renormalization group flow in a space of Lagrangians?

A: David C Brydges and his collaborators have been using renormalization inspired ideas to prove theorems about statistical mechanical systems for a few years now.  From his page:

A large part of theoretical physics is built around the "functional integral" formulation of quantum field theory.  These functional integrals are defined in the sense of formal power series (renormalised perturbation theory).  It is widely, but wrongly believed, by mathematicians, that no precise definition that is useful for rigorous analysis is within sight.  The renormalization group (RG), as pioneered by Ken Wilson (Nobel prize in Physics, 1982),  provides a clear roadmap for defining functional integrals and studying the remarkable  range of phenomena contained within them, in particular, renormalisation, scaling limits and the phase transitions of statistical mechanics. In these cases one can work with integrals based on measures on spaces of functions as opposed to complex valued "measures" on spaces of functions.  The complex valued case (Feynman functional integrals) is indeed further toward the horizon of difficulty.  Without facing the difficulties of the complex valued case, there is already an enormous range of possible applications.  My interests in  recent years have been in applications to  self-avoiding walk in four dimensions.  Functional integrals  combine with supersymmetry to generate combinatoric identities so whenever I need a rest from the RG I like to think about that aspect as well. The papers below are a mixture of themes involving supersymmetry and analysis by RG.    My colleague Joel Feldman is using closely related ideas to prove results in the context of condensed matter physics.

A good place to start reading about this line of research is his lecture notes from a 2007 PCMI summer conference on Statistical Mechanics.  They are available for download from his webpage above, or in printed form as part of the proceedings from said conference.

A: Langlands has thought about field theories for some time and has written a paper about  renormalization group fixed points. The paper can be found among his collected works at his IAS website. The section on mathematical physics is located at this URL
http://publications.ias.edu/rpl/section/28.

A: Dec 2017 edit: I just put a hopefully useful detailed complement to this post on https://physics.stackexchange.com/questions/372306/wilsonian-definition-of-renormalizability

The answer to your question depends on whether you are interested in the perturbative RG
or the nonperturbative one.
Typically one starts with a Gaussian measure $d\mu_{0,\infty}$ on a space of fields $\phi$
given by a covariance
$$C_{0,\infty}(x,y)=\int \phi(x)\phi(y)\ d\mu_{0,\infty}(\phi)\ .
$$
For instance one can take for the covariance $\frac{1}{\xi^2}$ in Fourier space.
Then one introduces a UV regularization at length scale $l$ by multiplying
for instance by $\exp(-l^2 \xi^2)$ which cuts-off momenta $\xi$ which are larger than $l^{-1}$. This defines
$$
C_{l,\infty}(x,y)=\frac{1}{(2\pi)^d}\int_{\mathbb{R}^d}
\frac{e^{-l^2\xi^2}}{\xi^2} e^{i\xi(x-y)}\ d^d\xi\ .
$$
The RG is used in order to study quantities of the form
$$
\int e^{-V(\phi)}\ d\mu_{l,\infty}(\phi)\ .
$$
The idea is to use a ``rescaling to unit lattice'', i.e., a scaling change of variable
so one has an integral as before with $l=1$ (with a different $V$ that I will still call
$V$ to keep notations simple).
Then one uses a decomposition of Gaussian measures
$$
\int e^{-V(\phi)}\ d\mu_{1,\infty}(\phi)
=\int \int e^{-V(\psi+\zeta)} d\mu_{1,L}(\zeta)d\mu_{L,\infty}(\psi)
$$
where $d\mu_{1,L}$ is the Gaussian measure corresponding to the covariance
$C_{1,L}=C_{1,\infty}-C_{L,\infty}$ and $L$ is some number $>1$.
If one defines the constant $[\phi]=\frac{d-2}{2}$, called the scaling dimension
of the field, then
the law of the field $\psi(x)$ is the same as
that of $\phi_L(x)=L^{-[\phi]}\phi(L^{-1}x)$
where $\phi$ is sampled according to the original measure
$d\mu_{1,\infty}$. Hence
$$
\int e^{-V(\phi)}\ d\mu_{1,\infty}(\phi)
=\int \left(\int e^{-V(\phi_L+\zeta)} d\mu_{1,L}(\zeta)\right)d\mu_{1,\infty}(\phi)
$$
$$
=\int e^{-V'(\phi)}\ d\mu_{1,\infty}(\phi)
$$
where
$$
V'(\phi)=-\log\left(
\int e^{-V(\phi_L+\zeta)} d\mu_{1,L}(\zeta)
\right)\ .
$$
The renormalization group transformation on the space of Lagrangians
is the map $V\rightarrow V'$.
One can also do this infinitesimally by taking $L\rightarrow 1$, in which case
one talks about an RG flow rather than a transformation.
In the perturbative RG one writes the dynamical variable $V$ which is a complicated
functional of the field as a formal power series in some variable which you can think of as Planck's constant.
In the nonperturbative RG one essentially wants to use analysis to control the sum of this series. There are rigorous ways to study both RGs. The perturbative one is of course
much simpler.
What you will find in Costello's book is only the perturbative RG. He does treat
Yang-Mills in flat space using the Batalin-Vilkovisky formalism, which is quite
remarkable for an introductory
book. For the curved case, see the paper
http://arxiv.org/abs/0705.3340
by S. Hollands which appeared in J. Math. Phys.
If you would be happy learning about the RG flow on $\phi^4$ instead of Yang-Mills,
then much simpler perfectly rigorous presentations are available:

*

*the book "Renormalization: an introduction" by Manfred Salmhofer, Springer, 1999.

*the review article http://arxiv.org/abs/hep-th/0208211  by Volkhard Mueller which
appeared in Rev. Math. Phys.
As for the rigorous nonperturbative RG, the Park City lectures by Brydges mentioned by jc is definitely the best place to start.
The issue here is that for Bosons one cannot really take the log in the definition
of $V'$. This is called the large field problem, and one algebraic way around
it is to use a so-called polymer representation. All this is explained by Brydges.
Another nice introduction to the nonperturbative RG for Bosons is the set of lecture notes "Introduction to the Renormalization Group" by Antti Kupiainen.
For Fermions,
taking the log is not a problem and good mathematical presentation can be found, e.g.,
in:

*

*the book "Non-perturbative renormalization" by Vieri Mastropietro, World Sci. 2008.

*the book "Renormalization group" by Giuseppe Benfatto and Giovanni Gallavotti, Princeton University Press, 1995.

*the book "Fermionic Functional Integrals and the Renormalization Group"
by Joel Feldman, Horst Knoerrer and Eugene Trubowitz, AMS-CRM, 2002,
also available at http://www.math.ubc.ca/~feldman/papers/aisen-all.pdf
Also, for the nonperturbative RG there is another approach which is closer to BPHZ
renormalization. It is presented in the book "From Perturbative to Constructive Renormalization" by Vincent Rivasseau.
If you would like a very short account of the kind of theorems one would like to prove
in the nonperturbative RG setting you can also look up my recent Oberwolfach extended abstract: http://arxiv.org/abs/1104.2937

Edit: An in depth study of the rigorous nonperturbative RG
is in the paper I just posted on arXiv:
Rigorous quantum field theory functional integrals over the p-adics I: anomalous dimensions, with A. Chandra and G. Guadagni.

Update: A short pedagogical presentation, elaborating on the above answer can be found here. The slides of my recent talk "A Toy Model for Three-Dimensional Conformal Probability" also provides more details on how the renormalization group allows one to construct QFTs as weak limits of cut-off probability measures on spaces of Schwartz distributions, for the simplest example that contains the germs of generality. The precise formulation of the problem of constructing a QFT to be solved by renormalization group techniques can be found in my answer to this MO question.

A: Kevin Costello's book Renormalization and Effective Field Theory (Mathematical Surveys and Monographs) just came out. I've read a preliminary version of the text he was distributing earlier, and it is very good. It is by far the best mathematical treatment of renormalization from a path-integral/Lagrangian point-of-view that I know of.

A: A small complement to Abdelmalek Abdesselam's answer: on the rigorous, non-perturbative side, there is also a recent (originally two-part, now turned into three-part) exposition by Jonathan Dimock, available in the arXiv's. He uses the $\phi^4$ scalar field theory in 3 dimensions in finite volume as a model for his discussion - the three parts are listed below:

*

*J. Dimock, "The Renormalization Group According to Balaban I. Small Fields". arXiv:1108.1335 [math-ph]

*J. Dimock, "The Renormalization Group According to Balaban II. Large Fields". arXiv:1212.5562 [math-ph]

*J. Dimock, "The Renormalization Group According to Balaban III. Convergence". arXiv:1304.0705 [math-ph]

Tadeusz Balaban refined the method of block-spin renormalization group employed by Gallavotti, Kupiainen and many others for lattice field models in order to analyse "large field" regions, aiming at the treatment of the continuum limit of pure Yang-Mills models in finite volume and 4 dimensions. His long series of papers on the subject from the 80's remain essentially the state of the art towards the rigorous construction of realistic models in quantum field theory in 4 dimensions (see, for instance, the latest of the series), together with the paper of Magnen, Rivasseau and Sénéor, which was motivated by Balaban's work. The third part of Dimock's exposé is meant to establish the convergence of the expansion scheme laid down in Parts I and II.


text:
Q: Can't run batch file in Server 2012 This site rocks!  I am trying to run a simple .bat file on Server 2012 that will ping another server, filter out all the lines except one, and then write to a file for later use (I then want that file sent somewhere, but that is a project for another discussion!).
I have pieced together some commands from searching this forum, and have the commands needed to make this happen.  When I run these commands one at a time from ms-dos, it works.  However, when it stick them all into a bat file something gets messed up. I don't have much experience with Server os's, so it could be something simple I am missing.  Any help would be appreciated.
Here are my instructions
ping 10.18.89.154 >C:\pinglog.txt
FOR /F "skip=8 delims=" %i in (C:\pinglog.txt) do @echo %i >C:\TEMP.TXT
SET /P SHOW= < C:\TEMP.TXT
ECHO %SHOW% >C:\pinglog.txt

And here is the result when run manually:

Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),

But when I run those commands in a batch file, the cmd window hangs on the first line, shows the below text in the cmd window and produces a blank file...

C:\Users\administrator.WSI\Documents>ping 10.18.89.154 1>C:\pinglog.txt

Any Thoughts?

A: Can't run batch file in Server 2012
Here is a much simpler way to do what you want (in a one line command):
ping 10.18.89.154 | findstr "Packets" > c:\pinglog.txt

The above command will work as is from the command line or from a batch file.
The following batch file uses google.com as the ping target as I can't ping something on your network with a private IP address.
test.cmd:
ping www.google.com | findstr "Packets" > pinglog.txt

example output:
C:\test>test

C:\test>ping www.google.com   | findstr "Packets"  1>pinglog.txt

C:\test>type pinglog.txt
    Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),

C:\test>

To use your original commands, in the for /f command you need to replace % with %%:
FOR /F "skip=8 delims=" %%i in (C:\pinglog.txt) do @echo %%i >C:\TEMP.TXT

Is there a way to isolate the values in that line, or can you only produce the entire line?

The reason I wanted to bring back the the "received" value only, is if that file is "0" I could trigger an alert based on that.

The following batch file will find the value of "Received" and will output "Ping failed" if that value is 0, otherwise it will output nothing.
As a bonus it doesn't use any files.
You can replace echo "Ping failed" with your alert command when you decide what this should be.
test.cmd:
@echo off
for /f "usebackq skip=8 tokens=7" %%i in (`ping 10.18.89.154`) do (
   set _result=%%i
   goto :done
   )
:done
if "%_result:~0,1%"=="0" echo "Ping failed"

Further reading

*

*FOR /F

%%parameter A replaceable parameter: in a batch file use %%G (on
  the command line %G)

A: I had the same problem described in the original question. I found no answers. I finally resolved the issue by creating a shortcut to the batch file. When launching the batch file from a shortcut, the file executes as expected. Otherwise, it hangs on the first line.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Put an empty field in peewee union select I'm try to select two table that have some common field. in raw MySQL query, i can write this:
SELECT t1.id, t1.username, t1.date FROM table1 as 't1' UNION SELECT t2.id, "const_txt", t2.date FROM table2  as 't2'

In that query ,the username field is not in table2 and I set const_txt instead.
So, in peewee, i want to union two table that have the same above situation.
class PeeweeBaseModel(Model):
    class Meta:
        database = my_db

class Table1(PeeweeBaseModel):
    id = PrimaryKeyField()
    username = CharField(255)
    date = DateTimeField()
    #other fields ...

class Table2(PeeweeBaseModel):
    id = PrimaryKeyField()
    date = DateTimeField()
    #other fields ...

and then , union two model. something like this:
u = (
    Table1(
        Table1.id,
        Table1.username,
        Table1.date
    ).select()
    |
    Table2(
        Table2.id,
        "const_text_instead_real_field_value",
        Table2.date
    ).select()
).select().execute()

But the const_text is not accepted by a field and ignore in result query.
the question is: How can I define a field that does not exist in my table and set it manually in query?
(And I prefer not using SQL() function.)
thanks.

A: you can use SQL() in SELECT statement.
u = (
    Table1(
        Table1.id,
        Table1.username,
        Table1.date
    ).select()
    |
    Table2(
        Table2.id,
        SQL(" '' AS username "),
        Table2.date
    ).select()
).select().execute()


text:
Q: the javascript result array only print last XML line even though I use 0 I have subtitle XML file that had start, dur, and text to assign temporay array then pass to Subtitle array each index. When I want to see Subtitle array with 0 index, it should print first text line included start, dur, and text but instead it print the last text line.
The wrong result show,
467.071,3.643, Thanks for watching, please subscribe, rate and comment
I tried index 50 and it still print the last line. Does I add it in wrong loop or what?
Here is sample of first 3 lines of XML(total text lines is 136),
<transcript>
<text start="2.014" dur="1.276">Greetings fellow nerds.</text>
<text start="3.291" dur="3.446">In this video we're going to make glow sticks of various colors</text>
<text start="6.738" dur="2.277">and explain a few interesting points about them.</text>
</transcript>

here a javascript example,
<script type="text/javascript">
            function loadXMLDoc(dname)
            {
                if (window.XMLHttpRequest)
                {
                xhttp=new XMLHttpRequest();
                }
                else
                {
                xhttp=new ActiveXObject("Microsoft.XMLHTTP");
                }
                xhttp.open("GET",dname,false);
                xhttp.send();

                return xhttp.responseXML;
            }

            function init()
            {
                var subtitleArray = new Array();
                var tempArray = new Array();
                var c = document.getElementById('container');

                captionsDoc = loadXMLDoc("captions.xml");
                x=captionsDoc.getElementsByTagName('text');

                for(i=0;i<x.length;i++)
                {
                    tempArray[0] = x[i].getAttribute('start');
                    tempArray[1] = x[i].getAttribute('dur');
                    tempArray[2] = x[i].childNodes[0].nodeValue;

                    subtitleArray[i] = tempArray;

                }

                c.innerHTML = subtitleArray[0];
            }
            window.onload = init;
        </script>


text:
Q: How can I use Django Development Server with VM(Vagrant and VirtualBox)? I can see the "It Works!" page with my Django project host machine!
When I
vagrant ssh (enter into the VM) and then in /myprojectdir python manage.py runserver or
python manage.py runserver 0.0.0.0:8000 or
python manage.py runserver 10.0.2.2 (guest IP):8000 or
python manage.py runserver 10.0.2.2 (host IP):8000  it says

No issues (0)silenced...Date ...
Django Version 1.8.7...
Starting development server at...http://X.X.X.X:XXXX

Ok, great- I'll check the address to see the page but
I do not see the 'It works!' page.  And instead I see text in the top left corner of the page

SSH-2.0-OpenSSH_6.6.1

.
Binding the server or using the Guest's own IP address have not worked.
Note: the VM I'm using is a CentOS7 box but I tried this on the vagrant tutorial standard box, Precise32, and it behaved the same as I described above.
Food for thought:

*

*Again the Django side of things is working; I can use the same file to python manage.py runserver in the host (works) but not when I'm on the VM (does not work).

*I'm using a NAT connection and when I try to use a bridged connection vagrant requests a password which I don't know (can't access via bridging).

*I've included: config.vm.network :forwarded_port, guest: 22, host: 8000, id: 'ssh' in my Vagrantfile.  Otherwise vagrant defaults to port 2222.
What do I have to change in the Vagrantfile to get the Django Development Server- the 'It works!'- page up-and-running on my VM?
Current Vagrantfile
    Vagrant.configure(2) do |config|
  config.vm.box = "bento/centos-7.1"
  config.vm.box_check_update = false
  config.vm.network :forwarded_port, guest: 22, host: 8000, id: 'ssh'
  config.vm.synced_folder "myApp", "/myApp"
  config.vm.provider "virtualbox" do |vb|
    vb.memory = "1024"
  end
  config.vm.provision "shell", path: "vagrant-setup.sh"
end

A: config.vm.network :forwarded_port, guest: 22, host: 8000, id: 'ssh' forwards the port 22 on your guest machine (VM) to port 8000 on your host.
because you want port 8000, you should replace it with with
config.vm.network :forwarded_port, guest: 8000, host: 8000


text:
Q: Hardware/IO Bottlenecks Taking the following issues in the count, what would be the descending order from greatest to least of bottlenecks in a computer system?

*

*Network I/O

*Disk I/O

*RAM I/O

*Graphics I/O

*Processing I/O

I'm often explaining the concept of what can make a machine appear slow, and I'd like to get a good idea of what's mostly the greatest to lowest bottlenecks in a system. Considering an average computer which has a decent 7200RPM hard disk, an average 500 kilobytes per second up/down network connection, average speed RAM, a dual-core 2GHz processor, and a fairly cheap video card, what'd be the order of my list above? I'd assume it'd be the way I wrote it, but I'd like to be sure.
What are the greatest and least causes for bottlenecks in hardware and I/O?

A: It depends
If what you are doing is downloading files the bottleneck in your case will be the network I/O. If they are working with word documents, network I/O is totally irrelevant.
Here is perhaps a better way of describing it:

*

*If the problem is that applications are running slowly, then the bottleneck is usually CPU if there is RAM available, or because RAM is not not available, the disk (as the data was pages out to there). On the disk side there is an I/O bottleneck, if the processor is maxed out (or more likely, a core is maxed out and the application does not multi-thread) the CPU is the bottleneck, but not the CPU I/O.

*If the problem is that games are running slowly, this can generally be fixed by getting a better graphics card. This is almost never about I/O though, this is about computation.

*RAM speed only matters when the user is writing a lot (> 1 GB/s) to RAM. Unless the user is doing this often, or they care about millisecond differences, it almost never matters. RAM I/O is generally very fast (DDR2 can do 3200 to 8533 MB per second and DDR3 is faster) and so this is rarely a bottleneck

*Network I/O only matters if there is a lot of data going back and forth.

*Disk I/O matters at startup, and when copying or loading large files/applications, but generally, unless a lot of this is being done, it is not very noticeable.

Note: I/O refers to Input/Output. While this is a factor for some components (the disk for example) it is generally irrelevant for others. Many CPUs can take in 6 GB/s, as can GPUs. The time it takes them to finish a computation is generally far more a factor than how long it takes them to just read in the data and spit it out.


text:
Q: How to achieve clean code-behind files? Working with WPF it is good practice to keep your xaml.cs code behind files small and clean. The MVVM pattern helps achieving this goal through Data Bindings and Command Bindings where any business logic is handled in the ViewModel classes.
I am using the principles of the MVVM pattern and my code-behind files are rather nice and clean. Any button click events are handled using Command Bindings, and there are a few more controls that also supports Command Binding. However, there are several events on controls that does not have the Command and CommandParameter properties, and hence I see no direct way for using bindings. What is the best approach for getting rid of logic in the code-behind files for such events? E.g. handling mouse events inside a control.

A: A nice approach for this is to use an attached behaviour. The behaviour itself can hook the event you need and fire the appropriate command with the parameters you want. It's essentially the same code, but it just remove it from your code behind and lets you express your intent purely in XAML.
There are several example behaviours on CodePlex, or a here's a basic sample that executes a command:
using System.Windows;
using System.Windows.Input;
using System.Windows.Interactivity;

/// <summary>
/// Trigger action to execute an ICommand command
/// </summary>
public class ExecuteCommand : TriggerAction<FrameworkElement>
{
    #region Dependency Properties

    /// <summary>
    /// Command parameter
    /// </summary>
    public static readonly DependencyProperty CommandParameterProperty = DependencyProperty.Register("CommandParameter", typeof(object), typeof(ExecuteCommand), new UIPropertyMetadata(null, OnCommandParameterChanged));

    /// <summary>
    /// Command to be executed
    /// </summary>
    public static readonly DependencyProperty CommandProperty = DependencyProperty.Register("Command", typeof(ICommand), typeof(ExecuteCommand), new UIPropertyMetadata(null, OnCommandChanged));

    #region Public Properties

    /// <summary>
    /// Gets or sets the command
    /// </summary>
    public ICommand Command
    {
        get
        {
            return (ICommand)this.GetValue(CommandProperty);
        }

        set
        {
            this.SetValue(CommandProperty, value);
        }
    }

    /// <summary>
    /// Gets or sets the command parameter
    /// </summary>
    public object CommandParameter
    {
        get
        {
            return (object)this.GetValue(CommandParameterProperty);
        }

        set
        {
            this.SetValue(CommandParameterProperty, value);
        }
    }
    #endregion

    /// <summary>
    /// Executes the command if it is not null and is able to execute
    /// </summary>
    /// <param name="parameter">This argument not used</param>
    protected override void Invoke(object parameter)
    {
        if (this.Command != null && this.Command.CanExecute(this.CommandParameter))
        {
            this.Command.Execute(this.CommandParameter);
        }
    }

    /// <summary>
    /// Called on command change
    /// </summary>
    /// <param name="oldValue">old ICommand instance</param>
    /// <param name="newValue">new ICommand instance</param>
    protected virtual void OnCommandChanged(ICommand oldValue, ICommand newValue)
    {
    }

    /// <summary>
    /// Called on command parameter change
    /// </summary>
    /// <param name="oldValue">old ICommand instance</param>
    /// <param name="newValue">new ICommand instance</param>
    protected virtual void OnCommandParameterChanged(object oldValue, object newValue)
    {
    }

    /// <summary>
    /// Called on command parameter change
    /// </summary>
    /// <param name="o">Dependency object</param>
    /// <param name="e">Dependency property</param>
    private static void OnCommandParameterChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)
    {
        ExecuteCommand invokeCommand = o as ExecuteCommand;
        if (invokeCommand != null)
        {
            invokeCommand.OnCommandParameterChanged((object)e.OldValue, (object)e.NewValue);
        }
    }

    /// <summary>
    /// Called on command change
    /// </summary>
    /// <param name="o">Dependency object</param>
    /// <param name="e">Dependency property</param>
    private static void OnCommandChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)
    {
        ExecuteCommand invokeCommand = o as ExecuteCommand;
        if (invokeCommand != null)
        {
            invokeCommand.OnCommandChanged((ICommand)e.OldValue, (ICommand)e.NewValue);
        }
    }
    #endregion
}

}
You can then use the System.Windows.Interactivity namespace (the assembly is included with Blend 3) to hook the event and fire the command as follows:
<i:Interaction.Triggers>
    <i:EventTrigger EventName="MouseLeftButtonUp">
        <triggers:ExecuteCommand Command="{Binding MyCommand}" CommandParameter="MyParameter" />
    </i:EventTrigger>
</i:Interaction.Triggers>

For more complicated events with multiple parameters you may need to create a specific Behaviour, rather than using a generic one like the example above. I generally prefer to create my own type to store parameters, and map to it, rather than having a specific EventArgs requirement in my ViewModel.
*One thing I should add is that I'm definately not a "0 code in the Code Behind" kind of guy, and I think enforcing this religiously is missing the point of MVVM somewhat. As long as the code behind contains no logic, and therefore nothing that really need to be under test, then I can live with some small pieces of code behind for "bridging the gap" between View and ViewModel. This is also sometimes necessary if you have a "smart view", as I generally call it, such as a browser control, or something you need to commmunicate with from your ViewModel. Some people would get pitchforks out for even suggesting such a thing, that's why I left this bit until last and answered your question first :-)*

A: My advice would be controversial. Don't do this. I.e. do this, but be very careful. One of the main goals of MVVM is to simplify development. If it makes you write code, that is hard to understand and support - you've chosen wrong path.
Please, don't get me wrong. I'm not saying "write everything in code behind". I'm saying - it's totally fine to have some code in the code behind if this code simplifies understanding. And don't think you break pattern. Patterns are just recommendations...

A: I have solved this with the following strategy, but I don't know if this is the ideal solution.
For the events that does not support Command Binding I handle the event itself in the code behind file, but I don't actually do any business logic there. Then the related ViewModel class has a function to handle the event, so the code-behind event handler calls the corresponding function of its ViewModel class.
E.g. I have some mouse events. Let's look at the MouseDown event on a Canvas. This will trigger an event handler in the code-behind, and the event handler will simply pass the call to the ViewModel. In this case all I need to know is which mouse button is pressed, and what's the current possition, so I don't pass the MouseEventArgs:
private void CanvasMouseDown(object sender, MouseButtonEventArgs e)
{
    var mousePositionX = e.GetPosition(_myCanvas).X;
    var mousePositionY = e.GetPosition(_myCanvas).Y;
    _vm.MouseDown(e.ChangedButton, mousePositionX, mousePositionY);
}

The ViewModel then has a MouseDown function which is where I actually handle the event:
public void MouseDown(MouseButton button, double mousePositionX, mousePositionY)
{
    switch (button)
    {
        case MouseButton.Left:
            // Do something
            break;
        case MouseButton.Right:
            // Do something
            break;
        case MouseButton.Middle:
            // Do something
            break;
    }

    _mousePositionX = mousePositionX;
    _mousePositionY = mousePositionY;
}

Does this sound like a reasonable way of getting code out of your code behind? Any better solutions? Best practice?


text:
Q: Check for Duplicates in Array I have a custom struct Shift:
struct Shift: Identifiable, Encodable {
    var id: String = UUID().uuidString
    var weekday: String
    var startTime: Date
    var endTime: Date
}

I also have a variable that stores an Array of Shift:
@Published var shifts: [Shift] = []

Is there any way to check if there are duplicate entries of startTime and endTime rather than checking for the entire Shift object?
EDIT:
Basically what I am trying to do is make sure that there aren't multiple shifts on a particular weekday that overlap. For instance, if my first shift on Monday starts at 1 pm and ends at 2 pm, there shouldn't be any other shift on Monday within that timeframe. However, I should be able to add a shift on Tuesday, for example, that starts at 1 pm and ends at 2 pm.
Any help is appreciated :)

A: You could add conformance to the Comparable protocol, and implement the == operator yourself (by returning true if the two startDates and the two endDates match.) You could then use contains(:_) on your array. That would be slow for large arrays though, since each call to contains(:_) will take O(n) time, and trying to see if an array of objects contains duplicates would degenerate to O(n^2) time.
If you also have your Shift object conform to Hashable (and use the 2 dates to calculate the hash value) you could use a set to test for duplicates. You'd populate your set with your array and then use the set to test new items for membership. (Sets give nearly constant time for checking for membership.)


text:
Q: %n not working in printf I have a problem, %n in printf doesn't work, i'm using Dev-Cpp 5.3.0.4 on win7
#include<stdio.h>
int main(void)
{
int n;
char *x;
gets(x);
printf("\n%s%n\n",x,&n);
printf("n: %d\n",n);
return 0;
}

output:
hello how are you?

hello how are you?n: 2046

--------------------------------
Process exited with return value 0
Press any key to continue . . .

why? how can i solve? thanks in advance ;)

A: Have a look at the printf manpage:

   n      The  number of characters written so far is stored into the integer indicated by the int
          * (or variant) pointer argument.  No argument is converted.

So, you'll have to pass a pointer to an int. Also, as Xavier Holt pointed out, you'll have to use a valid buffer to read into. Try this:
#include <stdio.h>
int main(void)
{
  int n;
  char x[1000];
  fgets(x, 1000, stdin);
  printf("\n%s%n\n",x,&n);
  printf("n: %d\n",n);
  return 0;
}

This code works for me.

A: You need to pass a pointer to n.

A: The argument to n needs to be a pointer to a signed int, not a singed int.

A: That's not how to use the "%n" specifier.
See the C99 Standard.

n
     The argument shall be a pointer to signed integer into which is written the number of characters written to the output stream so far by this call to fprintf. No argument is converted, but one is consumed. If the conversion specification includes any flags, a field width, or a precision, the behavior is undefined.

Also you need some place to store the input (hint: initialize x)


text:
Q: Calculate total time with out overlapping Standard work time is Start at 08:00 and End at 16:00, so I declared 2 parameters for this :
DECLARE @StartTime TIME = '08:00',
        @EndTime TIME = '16:00'

All calculations of time must between the start and end time.
Table1 working hours
Id      Date        WorkStartTime     WorkEndTime
-------------------------------------------------------
 1   2019/04/20     08:30            14:20
 2   2019/04/21     09:05            15:15
 3   2019/04/22     08:37            14:22
 4   2019/04/23     08:05            15:00

Table2 Leaves
Id      Date       LeaveStartTime   LeaveEndTime
--------------------------------------------------------
 1   2019/04/20     08:00            09:00
 2   2019/04/21     08:30            16:00
 3   2019/04/22     07:00            08:45
 4   2019/04/22     14:20            17:00

and find total leave time for each day without overlap by table 1 (Working hours) (I mean calculate leavetime (from table2) - worktime (table1))
This is the result I need:
2019/04/20  30 min
2019/04/21  80 min -- (35' at first and 45' at end)
2019/04/22  98 min -- (calculate 14:22(workendtime bigger than lavestarttime)   to 16:00 (for @EndTime))

I'm hoping to do this in a SQL query. I am using SQL Server 2016

A: Your calculation is unclear.  For the third row, you specify 98 minutes, but that is leaving out the 37 minutes at the beginning of the day.
You can do this calculation in SQL Server.  Overlapping time periods are a little messy but definitely possible in SQL.
The following is the logic that I think you want:
select l.date,
       sum(datediff(minute, l.LeaveStartTime,
                    (case when l.LeaveStartTime < w.workStartTime then w.workStartTime else l.LeaveStartTime end)
                   ) +
           datediff(minute,
                    (case when l.LeaveEndTime > w.workEndTime then w.workEndTime else l.LeaveEndTime end),
                    l.LeaveEndTime
                   )
          ) as overlaps
from (select l.d, l.date,
             (case when LeaveStartTime < '08:00' then '08:00' else LeaveStartTime end) as LeaveStartTime,
             (case when LeaveEndTime > '16:00' then '16:00' else LeaveEndTime end) as LeaveEndTime
      from leaves l
      where LeaveEndTime > '08:00' and LeaveStartTime < '16:00'
     ) l join
     works w
     on w.date = l.date and
        (l.LeaveStartTime < w.WorkStartTime or
         l.leaveEndTime > w.workEndTime
        )
group by l.date;

Here is a db<>fiddle.
This is trickier than most such problems, because you don't want the overlap -- you want the pieces left over.  This requires considering the "before" and "after" cases for the work times.


text:
Q: What's the significance of the letters to the left of the => in a lambda for Entity Framework Fluent API? I was given the following as an example:
   public TestAccountConfiguration()
    {

        HasRequired(a => a.Application)
            .WithMany(t => t.TestAccounts)
            .HasForeignKey(d => d.ApplicationId)
            .WillCascadeOnDelete(false);
    }

Is there a significance with all the letters a, t, d ? When I look at examples it seems like people just choose any character sometimes.

A: They're lamdba expressions.  They're local variables, and they can be anything you want.
HasRequired(app => app.Application)
            .WithMany(test => test.TestAccounts)
            .HasForeignKey(testAccount => testAccount.ApplicationId)
            .WillCascadeOnDelete(false);

Personally, I try to name them something relevant, but it's really up to you.

A: From MSDN:

To create a lambda expression, you specify input parameters (if any) on the left side of the lambda operator =>, and you put the expression or statement block on the other side. For example, the lambda expression x => x * x specifies a parameter that's named x and returns the value of x squared. You can assign this expression to a delegate type, as the following example shows:

In other words, the parameter list of a function is on the left, and the function itself is on the right of the => symbol.

A: Those letters are the names of the parameters of the anonymous functions. Their names do not matter, you can use any name you like, except that it must not conflict with another variable with the same name. Particularly, event handlers often have a parameter named e already, that means that a lambda expression inside that event handler cannot use e again as a parameter name. Other than that, use whatever you like.
It's just like
int addOne1(int x)
{
   return x + 1;
}

int addOne2(int y)
{
   return y + 1;
}

Func<int, int> addOne3 = z => z + 1;

These functions all do exactly the same thing, there is (practically) no difference between them from outside the functions.


text:
Q: Dealing with TDD / Unit Testing fatigue So I'm getting used to TDD, but I've come across an unexpected problem: I'm getting really tired of 100% code coverage. The tests are getting more tedious to write than the code itself, and I'm not sure if I'm doing it right. My question is: What sort of things are you supposed to test, and what sort of things are overkill?
For example, I have a test as follows, and I'm not sure if its useful at all. What am I supposed to do so that I still follow TDD but don't get tired of writing tests?
describe 'PluginClass'

    describe '.init(id, type, channels, version, additionalInfo, functionSource, isStub)'

        it 'should return a Plugin object with correct fields'

            // Create test sets
            var testSets = new TestSets()
            var pluginData = {
                'id'                : null,
                'type'              : null,
                'channels'          : null,
                'version'           : null,
                'additionalInfo'    : null,
                'functionSource'    : null,
                'isStub'            : true
            }
            testSets.addSet({ 'pluginData' : pluginData })
            var pluginData = {
                'id'                : "testPlugin1",
                'type'              : "scanner",
                'channels'          : ['channelA', 'channelB'],
                'version'           : "1.0",
                'additionalInfo'    : {'test' : "testing"},
                'functionSource'    : "function () {alert('hi')}",
                'isStub'            : false
            }
            testSets.addSet({ 'pluginData' : pluginData })

            for (var t = 0; t < testSets.getSets().length; t ++) {
                var aTestSet = testSets.getSet(t)

                var plugin = new Plugin().init( aTestSet.pluginData.id,
                                                aTestSet.pluginData.type,
                                                aTestSet.pluginData.channels,
                                                aTestSet.pluginData.version,
                                                aTestSet.pluginData.additionalInfo,
                                                aTestSet.pluginData.functionSource,
                                                aTestSet.pluginData.isStub  )

                plugin.getID().should.eql aTestSet.pluginData.id
                plugin.getType().should.eql aTestSet.pluginData.type
                plugin.getChannels().should.eql aTestSet.pluginData.channels
                plugin.getVersion().should.eql aTestSet.pluginData.version
                plugin.getAdditionalInfo().should.eql aTestSet.pluginData.additionalInfo
                eval("fn = " + aTestSet.pluginData.functionSource)
                JSON.stringify(plugin.getFunction()).should.eql JSON.stringify(fn)
                plugin.getIsStub().should.eql aTestSet.pluginData.isStub
            }

        end

    end

end

A: Certainly the above 'test' is overkill in many respects. It is much too long and complicated, hardly readable, and asserts way too much things. I can hardly imagine how this could have been emerged from a TDD process. It is not surprising that you get tired of stuff like this...
Test-driven development means: You should go in baby steps, where every step is a separate test, asserts only one thing, and contains absolutely no logic (i.e. no for, if/else or similar...). So the above code would result in about 4-6 separate test methods, which you would then implement one by one. First assert correct property initalization (with different values as required), then make sure that the methods work as expected, and so on...
The code coverage metric does not tell you anything about your tests except that it can show you the production code which is not touched by any tests at all. Especially it doesn't tell you if the touched code really is tested (and not only touched...). That depends only on the quality of your tests. So don't take code coverage too serious, there are many cases where a lower coverage with better tests is much more preferrable...
In sum:
It is not overkill to have tests for just about everything (100% coverage), but it certainly is a problem to have tests like in your example.
I recommend you reviewing your TDD/unit testing practice, The Art Of Unit Testing book might be a good resource...
HTH!
Thomas

A: One thing that I think people forget is that with automated unit testing, it's still a coding practice.  It's perfectly acceptable to set up templated / generic classes, base classes, helper classes, or any other regular software development patterns that you're familiar with to do your unit testing.  IF you feel like you're doing the same thing over and over, you probably are!  It's a sign that your brain is telling you: "There's a better way".
So go for it.

A: The goal of unit testing should be to test the parts of the code that are likely to contain bugs.  Achieving 100% test coverage should not be a goal, and AFAIK, TDD does not call it out as a goal.
Creating exhaustive tests for code that is unlikely to contain significant bugs is a tedious waste of time both now, and as your system evolves.  (In the future, duplicative unit tests are likely to be a source of meaningless regressions in the tests themselves that just waste someone's time to find and fix.)
Finally, you and your management should always use common sense when applying some development methodology to a project.  No methodology ever invented will be a perfect fit to all problems / projects.  Part of your job is to spot the situations where the methodology is not working optimally ... and if necessary adapt, or even abandon it.  And in this case, the fact that the way that you/your project is using TDD is driving you nuts is a clear sign that something is not right.

A: Your test is trying to verify too many things at once. Split it up into several tests and refactor your test code too (yes, helper methods are allowed).
Also, I get the impression that the code under test is also doing too much. Decouple your code (refactor by using Extract Class and Extract Method etc) and test each piece of production code in isolation. You'll find that those tests will become fewer, simpler and easier to both read and write.

A: It seems that you're

*

*testing constructors with simple member assignment. This is overkill unless there is some non-trivial logic in the constructor. Instead rely on this to get tested as part of some other tests where the members would be used.

*comparing equality between 2 value objects. Redefine/define the equality check on the plugin type/class, by overriding the equals method. so plugin.should.eql expected_plugin should be the solitary assert

*also consider using helper objects to construct complex test data.

A: Fatigue, laziness and apathy is our natural instinct to avoid pointless work, such as writing trivial tests, which is probably the case. Try to stop unit-testing trivial stuff and you should instantly feel better.
Your particular test far from being complicated. I've been involved as code reviewer in many projects with thousands of unit and integration tests and yet to see a project where tests would be more easier to read and understand than actual live code.
TDD readability, "test as documentation" and that sort of promises are simply not true. It's easy to prove - try to learn new code base by reading only tests or by reading only live code. Which way is more comprehensive?
Properly designed live code provide full and holistic picture of the component, whereas tests are just fragmented assertions about it.
The one and only benefit of tests is automation - some extra verification of your code which you don't have to do manually / that can't be done by compiler or code analysis. Period.
And this benefit comes at significant cost - writing and maintenance of tests, so choose carefully what to test.


text:
Q: How can i read multiple lines in file.csv I want to read information from the file but can only read the first line in the file:
int deserialize(Contact **head) {
    FILE *file = fopen("contacts.csv", "rb");
    Contact *temp = (Contact *)malloc(5 * sizeof(Contact));
    *head = (Contact *)malloc(50 * sizeof(Contact));
    if (file == NULL)
        return 0;

    while (*head != NULL &&
           (fscanf(file, "%d,%[^,],%[^,],%[^,],%[^,],%[^,],%[^,],%[^,],%[^,],%[^,],%[^,],%d\n",
                   &((*head)->id), &((*head)->firstName),
                   &((*head)->middleName), &((*head)->lastName),
                   &((*head)->company), &((*head)->phone),
                   &((*head)->company), &((*head)->address),
                   &((*head)->birthday), &((*head)->website),
                   &((*head)->note), &((*head)->status))) > 0)
    {
        printf(" head: %s\n", (*head)->firstName);
        *head = (*head)->next;
    }
    fclose(file);
    return 1;
}

My file.csv:
4,d,d,d,,,,,,,,0
3,c,c,c,,,,,,,,0
2,b,b,b,,,,,,,,0
1,a,a,a,,,,,,,,0

my output:
head: d

A: There are multiple problems in the posted code:

*

*you have a memory leak in case of fopen failure

*opening the text file in binary mode is not recommended: you will need to handle legacy line termination sequences explicitly. Better use text mode ("r") and let the library handle them.

*you allocate an array of 50 contacts for head to point to, but this is not a linked list.

**head = (*head)->next has undefined behavior as (*head)->next was never set. You could instead store the next entry to (*head)[1] or use an actual pointer instead of a double pointer.

*%[^,] is a risky conversion specifier: you may have a buffer overflow if the file contains a long string before the ,

*%[^,] cannot parse an empty field and you have many such fields in your file

*you do not check the number of conversions returned by fscanf() so you do not detect conversion error caused by the first empty field and the next call, returns 0 because the empty field cannot be converted as an integer, causing the loop to exit.

*for more reliable error recovery, you should read the file one line at a time and convert the CSV line, check the result and report failures explicitly

*to parse empty fields, you cannot use fscanf(), nor strtok and friends, you should instead write custom function to parse number and string fields.

Here is a safer approach, assuming string members of the Contact object are all char arrays.
#include <errno.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int parse_csv_number(const char **pp, int *dest) {
    char *p = *pp;
    char *end;
    long num;
    errno = 0;
    num = strtol(p, &end, 10);
    if (p == end)
        return 1;  // not a number
    if (errno != 0 || num < INT_MIN || num > INT_MAX)
        return 2;  // number too large
    if (*end == ',')
        end++;
    else
    if (*end != '\0' && *end != '\n')
        return 3;  // extra characters after number
    *dest = num;
    return 0;
}

int parse_csv_string(const char **pp, char *dest, size_t len) {
    char *p = *pp;
    size_t i = 0;
    p += strspn(" \t");  // skip banks
    while (*p != ',' &&*p != '\n' && *p != '\0') {
        if (i + 1 >= len)
            return 1;    // string too long
        dest[i++] = *p++;
    }
    dest[i] = '\0';
    if (*p == ',')
        p++;
    *pp = p;
    return 0;
}

int deserialize(Contact **headp) {
    const char *filename = "contacts.csv";
    char buf[256];
    char *p;
    int count = 0;
    FILE *file = fopen(filename, "rb");

    if (file == NULL) {
        fprintf(stderr, "cannot open %s: %s\n", filename,
                strerror(errno));
        return -1;
    }
    Contact *head = NULL;
    Contact *tail = NULL;
    while (fgets(buf, sizeof buf, file)) {
        Contact *cp = malloc(sizeof(*cp));
        if (cp == NULL) {
             fprintf(stderr, "memory allocation error: %s\n", strerror(errno));
             break;
        }
        p = buf;
        if (parse_csv_number(&p, &cp->id)
        ||  parse_csv_string(&p, cp->firstName, sizeof cp->firstName)
        ||  parse_csv_string(&p, cp->middleName, sizeof cp->middleName)
        ||  parse_csv_string(&p, cp->lastName, sizeof cp->lastName)
        ||  parse_csv_string(&p, cp->phone, sizeof cp->phone)
        ||  parse_csv_string(&p, cp->company, sizeof cp->company)
        ||  parse_csv_string(&p, cp->address, sizeof cp->address)
        ||  parse_csv_string(&p, cp->birthday, sizeof cp->birthday)
        ||  parse_csv_string(&p, cp->website, sizeof cp->website)
        ||  parse_csv_string(&p, cp->note, sizeof cp->note)
        ||  parse_csv_number(&p, &cp->status)
        ||  p[strspn(p, " \t")] != '\n') {
            fprintf(stderr, "invalid CSV line: %s\n" buf);
            continue;
        }
        count++;
        cp->next = NULL;
        if (head == NULL)
            tail = head = cp;
        else
            tail = tail->next = cp;
    }
    *headp = head;
    fclose(file);
    return count;
}

If the strings in the Contact object are string pointers (char *), you must allocate the strings. Here is a modified version:
#include <errno.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int parse_csv_number(const char **pp, int *dest) {
    char *p = *pp;
    char *end;
    long num;
    errno = 0;
    num = strtol(p, &end, 10);
    if (p == end)
        return 1;  // not a number
    if (errno != 0 || num < INT_MIN || num > INT_MAX)
        return 2;  // number too large
    if (*end == ',')
        end++;
    else
    if (*end != '\0' && *end != '\n')
        return 3;  // extra characters after number
    *dest = num;
    return 0;
}

int parse_csv_string(const char **pp, char **dest) {
    char *p = *pp;
    char *str;
    size_t i = 0, len;
    p += strspn(" \t");       // skip banks
    len = strcspn(p, ",\n");  // locate end of string
    str = strndup(p, len);
    if (str == NULL) {
        fprintf(stderr, "memory allocation error: %s\n", strerror(errno));
        return -1;
    }
    p += len;
    if (*p == ',')
        p++;
    *dest = str;
    return 0;
}

int deserialize(Contact **headp) {
    const char *filename = "contacts.csv";
    char buf[256];
    char *p;
    int count = 0;
    FILE *file = fopen(filename, "rb");

    if (file == NULL) {
        fprintf(stderr, "cannot open %s: %s\n", filename,
                strerror(errno));
        return -1;
    }
    Contact *head = NULL;
    Contact *tail = NULL;
    while (fgets(buf, sizeof buf, file)) {
        Contact *cp = malloc(sizeof(*cp));
        if (cp == NULL) {
             fprintf(stderr, "memory allocation error: %s\n", strerror(errno));
             break;
        }
        p = buf;
        if (parse_csv_number(&p, &cp->id)
        ||  parse_csv_string(&p, &cp->firstName)
        ||  parse_csv_string(&p, &cp->middleName)
        ||  parse_csv_string(&p, &cp->lastName)
        ||  parse_csv_string(&p, &cp->phone)
        ||  parse_csv_string(&p, &cp->company)
        ||  parse_csv_string(&p, &cp->address)
        ||  parse_csv_string(&p, &cp->birthday)
        ||  parse_csv_string(&p, &cp->website)
        ||  parse_csv_string(&p, &cp->note)
        ||  parse_csv_number(&p, &cp->status)
        ||  p[strspn(p, " \t")] != '\n') {
            fprintf(stderr, "invalid CSV line: %s\n" buf);
            continue;
        }
        count++;
        cp->next = NULL;
        if (head == NULL)
            tail = head = cp;
        else
            tail = tail->next = cp;
    }
    *headp = head;
    fclose(file);
    return count;
}

A: *

*The hard-coded file name ("contacts.csv") doesn't match the file name you claim "file.csv".  This appears to be an error in your question.

*You probably don't want to open a text .csv file in binary mode.

*fscanf() returns number of fields matched which in this case 4, and it would not match the last status field. > 0 is a defective test of success.

*%[,] "Matches a nonempty sequence of characters from the specified set" but you have an empty set so it doesn't match.  You cannot use fscanf() to match empty fields.

*(*head)->next is not initialized to an address and quite possibly NULL which would terminate your loop.  After your malloc() your array you would have loop through the .next pointer to the following entry in the array.  Or just use the array and forget about the linked list:
for(size_t i = 0; i < 50; i++) {
   (*head)[i].id ...
}

*Always specify a maximum field when reading strings to avoid buffer overflows.

I suggest you use an existing csv library.
If you need to write a parser yourself then I I suggest you use fgets() to read a line from your file then use strchr() to find the next separator.  Remember to strdup() each field values as the line read would change for each loop iteration.  Here's a sample to get your started:
#define _POSIX_C_SOURCE 200809L
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define LINE_LEN 100

typedef struct Contact {
    int id;
    char *firstName;
    char *middleName;
    char *lastName;
    char *company;
    char *phone;
    char *address;
    char *birthday;
    char *website;
    char *note;
    int status;
} Contact;

const char *parse_chr(const char *s, char chr) {
    if(*s == chr)
        return s + 1;
    return NULL;
}

const char *parse_int(const char *s, int *d, int fallback) {
    char *next;
    long l = strtol(s, &next, 10);
    if(l > INT_MAX || l < INT_MIN || s == next) {
        *d = fallback;
        return NULL;
    }
    *d = l;
    return next;
}

const char *parse_str(const char *s, char **v, char *fallback) {
    size_t n = strcspn(s, ",");
    if(!n)
        *v = fallback ? strdup(fallback) : fallback;
    else
        *v = strndup(s, n);
    return s + n;
}

#define PARSE_CHR(CHR) \
        next = parse_chr(s, CHR);\
        if(!next)\
            goto err;\
        s = next

#define PARSE_INT(NAME) \
        next = parse_int(s, &(*c)[*n].id, -1);\
        if(next)\
            s = next

#define PARSE_STR(NAME) \
        next = parse_str(s, &(*c)[*n].NAME, NULL);\
        if(next)\
            s = next

int deserialize(FILE *f, Contact **c, size_t *n) {
    if(!f)
        return EXIT_FAILURE;
    for(*c = NULL, *n = 0;; (*n)++) {
        char line[LINE_LEN];
        if(!fgets(line, LINE_LEN, f))
            break;

        Contact *tmp = realloc(*c, (*n + 1) * sizeof **c);
        if(!tmp)
            return EXIT_FAILURE;
        *c = tmp;

        const char *s = line;
        const char *next;
        PARSE_INT(id); PARSE_CHR(',');
        PARSE_STR(firstName); PARSE_CHR(',');
        PARSE_STR(middleName); PARSE_CHR(',');
        PARSE_STR(lastName); PARSE_CHR(',');
        PARSE_STR(company); PARSE_CHR(',');
        PARSE_STR(phone);  PARSE_CHR(',');
        PARSE_STR(company); PARSE_CHR(',');
        PARSE_STR(address); PARSE_CHR(',');
        PARSE_STR(birthday); PARSE_CHR(',');
        PARSE_STR(website); PARSE_CHR(',');
        PARSE_STR(note); PARSE_CHR(',');
        PARSE_INT(status); PARSE_CHR('\n');
        continue;
err:
        printf("Could not parse %s\n", line);
        return EXIT_FAILURE;
    }
    return EXIT_SUCCESS;
}

int main() {
    Contact *c;
    size_t n;
    deserialize(fopen("contacts.csv", "r"), &c, &n);
    for(size_t i = 0; i < n; i++) {
        printf(
            "%d, %s, %s, %s, %s, %s, %s, %s, %s, %s, %d\n",
            c[i].id,
            c[i].firstName,
            c[i].middleName,
            c[i].lastName,
            c[i].company,
            c[i].phone,
            c[i].address,
            c[i].birthday,
            c[i].website,
            c[i].note,
            c[i].status
        );
        free(c[i].firstName);
        free(c[i].middleName);
        free(c[i].lastName);
        free(c[i].company);
        free(c[i].phone);
        free(c[i].address);
        free(c[i].birthday);
        free(c[i].website);
        free(c[i].note);
    }
    free(c);
}

and example output:
4, d, d, d, (null), (null), (null), (null), (null), (null), 0
3, c, c, c, (null), (null), (null), (null), (null), (null), 0
2, b, b, b, (null), (null), (null), (null), (null), (null), 0
1, a, a, a, (null), (null), (null), (null), (null), (null), 0

PARSE_INT() and PARSE_STR() considers their respective field values optional.  PARSE_CHR() is required.  The underlying functions support optional values with fallback or required values.


text:
Q: C++ template style, geared towards easier to understand compiler error messages I have heard it been said that unless a good compiler error message friendly style is adopted upfront, C++ templates can make developing and maintaining a project overwhelmingly difficult.
I would appreciate pointers to a resource that describes such a style, and explains it.
Though I seek specific pointers, the question can be interpreted to be open ended, in which case I am open to suggestions on how best to pose it, or remove it from SO altogether, or make it a wiki

A: Template error messages tend to become unwieldy when a type incompatibility error occurs deep within a series of templates.  Code can be written in such a way that template errors are detected early on using type sanity-check techniques such as std::enable_if to ensure that the type used to instantiate a class or function template meets certain requirements upfront.  Indeed, this was the goal of the proposed C++11 concepts, which never materialized.

A: andrei alexandrescu's book, modern c++ design, might be what youre looking for.

A: The main thing you can do with coding style is use things like static_assert to check the template parameters before you try to use them. [Note: while enable_if can also be useful, I think static_assert is generally more suitable for this sort of task.]
This helps give at least some chance of (for example) an error message something along the lines of "error: X must be an integer type", instead of something like: "error: cannot instantiate _Detail::_Some_internal_type<double>", or the (always beloved) "No overload of _Foo takes a parameter of type ZZZ or there was no suitable conversion. Candidates were: [insert 5 pages of seeming unrelated crap here]."


text:
Q: How can I leverage MEF in my MVVM application? Can anybody give me a simple wpf application using mef and following mvvm pattern. I have looked a lot on the internet but i found very few examples and those example are very complex to understand. some examples are wpf, mef but dont follow mvvm pattern.
here is what i am trying to do.
There will a main wpf application. This will load all the modules (plugins) and show it to user. A module will contain 2 or 3 pages with next back buttons (used for navigation). Now when in main application i select a module, module opens or what you can say it replaces current window and on button navigation it changes views of the module.

Main Window -> Module 1 -> Page 1
                       Page 2

                       Page 3

           Module 2 -> Page 1

                       Page 2

                       Page 3

So it look clean now. Module 1 is a seperate project, module 2 is a seperate project. main window reads modules from dll and show them. clicking a module will go through its pages.

A: Microsoft has a few reference implementations lying around that you may find useful. they are a good showcase of MVVM / MEF and WPF. here's the very first blog about the StockTrader RI implementation with the download link pointing here. the Microsoft overview of the StockTrader RI and MVVM RI implementations are here, and here's the StockTrader RI implementation specifically. hth.

A: i did 2 projects these days which do that what you want. what i have done is to set up a main project which does nothing more than collecting the modules via MEF and handle the selection of the module. you also need a component project where you set up the interfaces and export attributes.
here some sample code pieces:
MainProject app.xaml.cs
public partial class App : Application
{
    [ImportMany]
    private IEnumerable<Lazy<IComponent, IComponentMetadata>> _components;
    private CompositionContainer _mefcontainer;

    protected override void OnStartup(StartupEventArgs e)
    {
        ShutdownMode = ShutdownMode.OnExplicitShutdown;

        //i do login stuff here

        //i use task.factory here and dynamic splashscreen here

        this.MefContainer.ComposeParts(rahmen, this);

        foreach (var component in _components)
        {
            //check metadata and fill modules collection
        }

        //add modules collection to mainwindowviewmodel

         ShutdownMode = ShutdownMode.OnMainWindowClose;

         this.MainWindow.Show();

    }
}

Component.dll
public interface IComponent//Marker interface
{
    bool HasChanges { get; }
}

public interface IComponentMetadata
{
    string Displayname { get; }

    int SortIndex { get; }

    string ImagePath { get; }

    string IconPath { get; }
}

[MetadataAttribute]
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false)]
public class ComponentExportAttribute : ExportAttribute, IComponentMetadata
{
    private const string DEFAULTICON = "pack://application:,,,/MyComponent;Component/Images/Default.png";

    public ComponentExportAttribute(string displayname, int sortindex): base(typeof(IComponent))
    {
        this.Displayname = displayname;
        this.SortIndex = sortindex;

        this.ImagePath = DEFAULTICON;
        this.IconPath = DEFAULTICON;
    }

    public ComponentExportAttribute(string displayname, int sortindex, string imagepath, string iconpath): base(typeof(IComponent))
    {
        this.Displayname = displayname;
        this.SortIndex = sortindex;

        this.ImagePath = String.IsNullOrWhiteSpace(imagepath) ? DEFAULTICON : imagepath;
        this.IconPath = String.IsNullOrWhiteSpace(iconpath) ? DEFAULTICON : iconpath;
    }

    #region Implementation of IComponentMetadata

    public string Displayname { get; private set; }

    public int SortIndex { get; private set; }

    public string ImagePath { get; private set; }

    public string IconPath { get; private set; }

    #endregion
}

Modul example
[ComponentExport("Test1",  150
    , "pack://application:,,,/TestProject;Component/Test/Logo1.png"
    , "pack://application:,,,/TestProject;Component/Test/Icon1.png")]
public partial class Test1MainWindow : UserControl, IComponent
{
    [ImportingConstructor]//if you want to do DI
    public Test1MainWindow ()
    {
        InitializeComponent();
        this.DataContext = this;
    }

    #region Implementation of IComponent

    public bool HasChanges
    {
        get { return false; }
    }

    #endregion
}

or viewmodel export --> (if you do this you have to export a datatemplate to the mainapp, i can show this if you want)
[ComponentExport("Test2", 500
    , "pack://application:,,,/TestProject;Component/Test/Logo2.png"
    , "pack://application:,,,/TestProject;Component/Test/Icon2.png")]
public class Test2: INPCBase, IComponent
{

    [ImportingConstructor]
    public Test2()
    {
    }

    #region Implementation of IKabuComponent

    public bool HasChanges
    {
        get { return false; }
    }

    #endregion
}


text:
Q: Creation of URLSession freezing the app in swift I am creating a URLSession for a background download task as follows,
class ViewController: UIViewController, URLSessionDelegate {
    var session: URLSession!
    lazy var downloadsSession: URLSession = {
      let configuration = URLSessionConfiguration.background(withIdentifier:
        "bgDownloader")
//        configuration.sessionSendsLaunchEvents = true
        let session = URLSession(configuration: configuration, delegate: self, delegateQueue: nil)
      return session
    } ()

    override func viewDidLoad() {
        super.viewDidLoad()
        print("started")
        session = downloadsSession
        print("done")
        // Do any additional setup after loading the view.
    }
}

Whenever the control hits the let session = URLSession(...) line in viewdidload() the app freezes. Any help?

A: There's something going on because this code, alone is not sufficient to manifest the problem. E.g. I ran your project and see both print statements:

This is in Xcode 11.4.1 (11E503a) and iPhone 11 Pro Max simulator running on macOS Catalina 10.15.4 (19E287), though I've used this sort of pattern for many different Xcode versions, without incident.
If you're getting weird behavior, you can:

*

*Reset the simulator: Choosing "Device" » "Erase All Content and Settings..." » "Erase".

*Empty Derived Data: When getting inexplicable behaviors, it's prudent to empty the Derived Data folder ("Xcode" » "Preferences..." » "Locations", tap on the arrow next to the derived data path; quit Xcode; delete everything in the Derived Data folder; and restart Xcode). I can't imagine that this will help, but is a good first step whenever you get incorrect/inexplicable behaviors.

*Reboot and/or try other computer: If you're really still seeing this behavior, reboot your machine, try it on another person's computer, etc. But there's nothing wrong with the instantiation of the background session.
(Needless to say, longer term, this download session shouldn't be a property of the view controller, but that's a bigger picture issue you can tackle once you've got your immediate problem behind you.)


text:
Q: momentjs date comparison with timezone I have been using momentjs and moment-timezone for a while. While using date comparison using isAfter method today, I discovered strange behaviour.
Suppose one moment date is configured with timezone value and other isn't then what should be the behaviour of date comparison?
In my case, we are converting an epoch time to specific timezone value for one date. Other date is in format yyyy-mm-dd without any timezone value. When I am comparing these two days, it is failing for same day value.
//Wed Sep 27 2017 01:13:04 GMT-0700
var localtime = moment(1506499984924).tz("America/Los_Angeles");

//Wed Sep 27 2017 00:00:00
var date = moment('2017-09-27');

//returns true
var value = localtime.isAfter(date, 'day');

Ideally since both dates are Sept 27 2017, it should return false.
Using diff method instead isAfter returns 0 which is true.
Any help is appreciated to solve this issue.
I have created a pen with this code: Moment

A: In your code:

var date = moment('2017-09-27');

This create a value at midnight local time.  How that relates to a specific instant in time is highly dependent on which local time zone your computer is set to.
Moment objects are always compared as moments - that is, instantaneous values based on UTC.
I see false when I run your code pen because I am in a time zone that is behind UTC.  If you see true, it's because you are in a local time zone that is ahead of UTC (by over an hour, given the time of the other value).


text:
Q: Reference request: Category of finite dimensional representations of loop algebra is not semisimple For $\mathfrak{g}$ a semisimple Lie algebra, we may define its (untwisted) loop algebra as $L(\mathfrak{g}) = \mathfrak{g} \otimes \mathbb{C}\lbrack t,t^{-1} \rbrack$. Let $\mathcal{F}$ be the category of finite-dimensional $L(\mathfrak{g})$-modules.
It is stated throughout the literature (e.g. [1]) that $\mathcal{F}$ is not semisimple. While it is straightforward to find an object in $\mathcal{F}$ that is reducible but not decomposable, I would like to know whether a purely categorical/algebraic (i.e. abstract) proof of this fact is known?
[1] Senesi, P. 2009. Finite-dimensional Representation Theory of Loop Algebras: A Survey. (https://arxiv.org/abs/0906.0099).


text:
Q: How do use Firebase Cloud Messaging in the Firebase Functions? How do use Firebase Cloud Messaging in the Firebase Functions?
I did try using getMessaging() to send the message but it also gave me issues so I will appreciate a quick workaround

*

*I get the error below when I use the function attached

i  functions: Beginning execution of "Return"
>  {"structuredData":true,"severity":"INFO","message":"Hello logs!"}
>  { state: 'BwcRCA4UBAMTGRgNDxkHHBoBAAQMBw0CGBEaEAYNEh4' }
i  functions: Finished "Return" in 4.336959ms
>  {
>    dt: 'dScq50VpRQSl27s-ZPBB_Y:APA91bHM0VNORw1q_VndMQbKS_NTjk3Z2cCTwwrkrEAlpSjpS-5cvraUcj_Q3UV_Pqdtvwg-3BZGE--ShyR3pEr-4jwgPRwHZ4f5JD7Y4ZVkYIg0Rh4JpxEfjqIhCUujrEqCncoJU09Q'
>  }
>  /Users/thapeloradebe/functions/node_modules/firebase-admin/lib/app/firebase-namespace.js:131
>                  return _this.ensureApp(app).messaging();
>                                              ^
>
>  TypeError: _this.ensureApp(...).messaging is not a function
>      at Proxy.fn (/Users/thapeloradebe/functions/node_modules/firebase-admin/lib/app/firebase-namespace.js:131:45)
>      at /Users/thapeloradebe/functions/lib/index.js:25:21
>      at processTicksAndRejections (node:internal/process/task_queues:96:5)

This below is my function
export const Return = functions.https.onRequest(async (request, response) =>{
  functions.logger.info("Hello logs!", { structuredData: true });

    console.log({state: request.query.state});
    db.ref(`states/${request.query.state}`).get().then(async (snapshot) => {
      const device_token = snapshot.val();
      console.log({'dt': device_token.token})
      const payload = {
        data: {
          state: request.query.state,
          bank_code: request.query.code
        },
      } as MessagingPayload;

      await admin.messaging(app).sendToDevice(device_token.token, payload)
        .then((response) => {
          console.log('Successfully sent message:', response.results);
        }).catch((error: Error) => {
          console.log('Error sending message:', error);
          throw new Error(error.message);
      });
    })

    response.send(request.query.code);
 });


text:
Q: HTML content filtered on blog page On my blog page where my all post are listed all formating is filtered and the post text is in a paragraph tag with all other formatting HTML tags removed. It works fine on the posts single page.
How can I fix it and allow my posts to be visible till "more break" with all formatting.

A: Go to Admin area -> Appearance -> Editor
and open Archive.php template from right side and change the following line from
the_excerpt();

to
the_content();

Thanks to @kraftner
Reference


text:
Q: Dynamically filter Series in Excel I have an excel sheet in which the chart is dynamically generated each time it runs based on a data table within the sheet. However, due the Excel Series 255 limitation, the chart stopped generating.
Is there a way I can define a subset of Series so the chart can dynamically pull its related data from the table?
For example if I have:
   Product    Q1  Q2  Q3  Q4
   Apples     1   2   3   4
   Bananas    3   4   5   6
   Oranges    4   5   6   7
   Strawberries 1  2  3   5

Within excel, how can I define only Apples, Oranges and Strawberries for the line chart so it will display its related Q-values?
TIA

A: If I understand you correctly, you can use a simple filter.  For example, here is your data plotted originally.

And here is the data after having

*

*applied a filter (Data Ribbon / Sort & Filter Tab / Filter)

*Select the table area

*execute GoTo Special / Visible Cells Only

*Insert a new graph

If this is something that needs to be done frequently, you could write a VBA macro to better automate the process.

If you change a value in a visible series, the chart will change.  But if you change the filter, you will need to go through the process again.


text:
Q: display: table-cell same space for all cells i've got a problem with display: table-cell; and the space between the cells. I'd like to have dynamically the same width for all cells.
See JSFiddle
How you can see the "Ausstattung & Skizze" is much wider than the others. Is there a way to dynamically set the same width to all cells?

A: li {
  display: inline-block;
  width: 150px;
}

edit: no need for inline-block, with width:25%

A: You can use table-layout:fixed; on the parent element which holds display:table;
ul{
  display: table;
  width: 700px;
  table-layout: fixed;
}

This way, every cell will get the same width if you don't force their width, no matter how many cells you have in a row.
(Edit: see this JSfiddle http://jsfiddle.net/m8evqnv0/ )

A: if the width of the unordered list is fixed, then:-
li
{
    width: 25%;
}

best practice:- use classes for li and then style the class.
if you want the table to be responsive, use table markups then. it will work like a charm.
fiddle:- http://jsfiddle.net/4wsmx8t0/3/


text:
Q: MySQL table partial redundancy I am finding pair of roommates along with room information.
currently I can get a table like below
example:
- Id1 Id2 Dorm room
- 101 133  2a   1
- 121 154  1b   3
- 218 584  3a   2
- 133 101  2a   1
- 584 218  3a   2
- 154 121  1b   3

not sure how to clear the redundancy as I want a table like this
- Id1 Id2 Dorm  room
- 101 133  2a    1
- 154 121  1b    3
- 218 584  3a    2

I was starting with a table like this
- StuID Dorm  room
- 101    2a    1
- 154    1b    3
- 121    1b    3
- ...

Thanks!

A: Don't use an equals on the join for studentID, instead use < or >.
This will really only work if each room can have 1 or 2 roommates.  if a 3rd is present a different solution would have to be generated.
SELECT T1.StuID, T2.StuID, T1.Dorm, T1.Room
FROM table T1
LEFT JOIN Table T2
 on T1.Dorm = T2.Dorm
and T1.Room = T2.Room
and T1.StuID < T2.StuID

This forces the T1.StudentID to be less than the T2.StudentID, thus the lower ID student will always be first ensuring order and no duplication.
Left join was used as I was unsure if some rooms only had 1 person and I assumed you wanted those.


text:
Q: Get all information from each table Because of all products have different price of its different package, I have separated its table for each products.

Product One

    Id
    package
    price
    image

    1
    2kg
    $10
    p2.jpg

    2
    4kg
    $20
    p4.jpg

    3
    6kg
    $30
    p6.jpg

    4
    8kg
    $40
    p8.jpg

Product Two

    Id
    package
    price
    image

    1
    2kg
    $12
    p2.jpg

    2
    4kg
    $14
    p4.jpg

    3
    6kg
    $16
    p6.jpg

    4
    8kg
    $18
    p8.jpg

Now what I want is to create a new table to collect the all products name: product one, product two, product three and product four.

Product One

    Id
    Name

    1
    Product One

    2
    Product Two

    3
    Product 3

    4
    Product Four

My question now is how to get all information of all product by connecting the name of products.
I am going to create a drop-down selection for its package. when they select the package, the price will be changed.

A: i know this is in coldfusion but i am sure there must be something similar in php
   <cfquery name="gtmyinfo" datasource="mydb">
        SELECT *
        FROM mytable
    </cfquery>

Product ID

Product Name

Product Image

   <cfoutput query="gtmyinfo">

#ProductID#

#ProductName#

#ProductImage#

   </cfoutput>

the table will keep looping as long with as many rows of data their are in the query.
you can limit which data is called with the "where" tag in the query or with an if/else tag in the table.


text:
Q: C# Expression Tree: Using TypeAs My first foray into writing an expression tree in c# is not going too well :). Here's the c# code I'm trying to duplicate
public static object Test<S, D>(S source, Func<D, object> selector )
    where S : class
    where D : class
{
    D derived = source as D;

    object retVal = null;

    if( derived != null ) retVal = selector(derived);

    return retVal;
}

Conceptually, this is intended to take an object and apply a selector to it to return a property of a derived class if the supplied object is of the derived class.
Here's what I've got so far:
public static object OrderByDerivedProperty<S>( S source, Type derivedType, string fieldName )
{
    ParameterExpression parameter = Expression.Parameter(typeof(S), "source");
    UnaryExpression typeAs = Expression.TypeAs(parameter, derivedType);

    ConstantExpression nullConst = Expression.Constant(null);
    BinaryExpression isNotNull = Expression.NotEqual(typeAs, nullConst);

    ParameterExpression varDest = Expression.Variable(derivedType, "varDest");
    ParameterExpression retVal = Expression.Variable(typeof(object), "retVal");

    BlockExpression block = Expression.Block(
        new[] { varDest, retVal },
        Expression.Assign(varDest, typeAs),
        Expression.Condition(
            isNotNull,
            Expression.Assign(retVal, Expression.Property(varDest, fieldName)),
            Expression.Assign(retVal, nullConst)
            ),
        retVal
    );

    LambdaExpression lambda = Expression.Lambda(block, new[] { parameter });

    return lambda.Compile().DynamicInvoke(source);
}

I've used a somewhat different set of arguments here to simplify my expressions.
The code works when derivedType is, in fact, a Type derived from S. However, if it isn't -- when I'm expecting the code to return retVal = null -- it blows up at the following line:
Expression.Assign(retVal, Expression.Property(varDest, fieldName)),

complaining that fieldName is not a property of varDest. Which is correct in that case...but I was expecting the "if true" arm of the Condtional expression to not be evaluated if the test expression was false. That's clearly not the case.
What I don't know about expression trees would fill (more than) a book. But if someone can point out where I'm going off the rails I'd appreciate it.

A: Not sure if you ever got this answered but here's what you need
        public static object OrderByDerivedProperty<TSource>(TSource source, Type derivedType, string propertyOrFieldName)
        {
            if (!derivedType.IsClass)
            {
                throw new Exception("Derived type must be a class.");
            }
            ParameterExpression sourceParameter = Expression.Parameter(typeof(object), "source");
            ParameterExpression typeAsVariable = Expression.Variable(derivedType);
            ParameterExpression returnVariable = Expression.Variable(typeof(object));
            BlockExpression block = Expression.Block(
                new[] { typeAsVariable,returnVariable },
                Expression.Assign(
                    typeAsVariable,
                    Expression.TypeAs(
                        sourceParameter,
                        derivedType
                    )
                ),
                Expression.Condition(
                    Expression.NotEqual(
                        typeAsVariable,
                        Expression.Constant(
                            null,
                            derivedType
                        )
                    ),
                    Expression.Assign(
                        returnVariable,
                        Expression.Convert(
                            Expression.PropertyOrField(
                                typeAsVariable,
                                propertyOrFieldName
                            ),
                            typeof(object)
                        )
                    ),
                    Expression.Assign(
                        returnVariable,
                        Expression.Constant(
                            null,
                            typeof(object)
                        )
                    )
                ),
                returnVariable
            );
            var lambda = Expression.Lambda<Func<object,object>>(block, new[] { sourceParameter });
            return lambda.Compile().Invoke(source);
        }


text:
Q: Scatter Plot Matrices I have a matrix mat[n,m] and I'd like to use splom to plot the scatterplots of mat[,"col4"] as a function of all other column values. Also I'd like to add different colors to points of certain row numbers which are stored in rownID[]. I've seen examples using splom but they plot all variables against all variables and use group of columns to change the color of points. Is it possible to do what I want using splom (or other R function)?
Example:
set.seed(1)
mat <-  matrix(sample(0:100, 16), ncol=4)

dimnames(mat) <- list(rownames(mat, do.NULL = FALSE, prefix = "row"),
                          colnames(mat, do.NULL = FALSE, prefix = "col"))

mat
     col1 col2 col3 col4
row1   26   19   58   61
row2   37   86    5   33
row3   56   97   18   66
row4   89   62   15   42

rowID <- matrix(c(1,3), ncol=1, nrow=2)

Thanks to https://stackoverflow.com/a/16033003/1262767
I've been using featurePlot function of caret package but I don't know how to change color of some specific points (that's why I'm interested in splom):
featurePlot(mat, mat$col4, plot = "scatter",
            ## Add some space between the panels
            between = list(x = 1, y = 1), main = "testSet",
            ## Add a background grid ('g') and a smoother ('smooth')
            type = c("g", "p", "s"))

A: This doesn't really seem like a good fit for splom. I think you're be better off reshaping your data and using a standard xyplot. For example
library(reshape2)
mm<-melt(cbind(data.frame(mat), high=1:nrow(mat) %in% rowID), c("col4","high"))
xyplot(col4~value|variable, mm, groups=high)

which gives


text:
Q: Looking for something more efficient than setInterval I am using some collision code I found on stack overflow, it uses .setInterval which when lowered to something like in a game doesn't seem very efficient. I wish to reset #div1 upon a false result.
Would an EventListener be preferable?
What would be the best alternative for something with collisions possibly happening every second?
window.setInterval(function() {
  var bang = collision(collisionOne, collisionTwo);
  $('#result').text(bang);
   if (bang) === false){
     $('#div1').detach();
     }
  }, 20);

A: In some cases, the function might need longer than the interval time to finish execution. Consider using setInterval in every 5 seconds, variables might prevent the request from completing on time. What would happen is that you'll end up with a bunch of queued requests that may not necessarily return in order.
You can use instead...
function interval(){

    setTimeout(interval, wait);
};

where the wait is a time variable.


text:
Q: JButton only appears after I hover over it? I was wondering why my button does not show up on the panel until AFTER I hover my mouse over where it would be? It also disappears again if I resize the window. The MainMenuScreen is just an image I use as my background image.
    //MainMenu setup
    JPanel card2 = new JPanel();
    card2.setLayout(new GridBagLayout());
    GridBagConstraints gbc = new GridBagConstraints();
    gbc.gridx = 0;
    gbc.gridy = 0;
    gbc.insets = new Insets(2,2,2,2);
    gbc.anchor = GridBagConstraints.CENTER;
    MainMenuScreen mms = new MainMenuScreen();
    mms.setLayout(new FlowLayout());
    card2.add(mms);
    card2.add(menuButton1, gbc);

Here is how I setup by background image.
public class MainMenuScreen extends JPanel{
    private static final long serialVersionUID = 1L;

    private BufferedImage background;

    public MainMenuScreen() {
        try {
            background = ImageIO.read(new File("M&M Arcade.png"));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public Dimension getPreferredSize() {
        return new Dimension(800, 600);
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        if (background != null) {
            int x = (getWidth() - background.getWidth());
            int y = (getHeight() - background.getHeight());
            g.drawImage(background, x, y, this);
        }

        Graphics2D g2d = (Graphics2D) g;
        g2d.setPaint(Color.white);
    }
}

A: The JButton doesn't show up beacuse you are using the same GridBagConstraints values for your MainMenuScreen component and your JButton menuButton1, i.e. they exist at the same location. Once the values of gbc are adjusted, the button will appear. Also better to consistently use the correct overloaded method of add when adding to a container with GridBagLayout.
Edit:
There have been numerous discussions on how to implement background images on JPanel containers. A notable one is Background Panel.


text:
Q: auto-complete search options I'm trying to build a search feature on my php website that provides an auto complete feature.  I've noticed that a lot of people are recommending jquery UI autocomplete.  But I took a look at their example online and it seems to take a really long time to search their example "birds" database. I haven't taken the time to analyze the sampel code to see if there's a way to speed it up.  But I just thought I'd ask to see what other ways i should be exploring to accomplish the same thing.
Thank you in advance for your time!

A: jQuery UI's Autocomplete is rich and awesome. If your concerned about speed of getting items from a Database using AJAX, consider the approach of pre-populating a JSON array of the relavent information, embedded on the page. Then its pretty darn near instant (you'll just have a bunch of bloat on the page)
http://jqueryui.com/autocomplete/#default
<head>
    <link rel="stylesheet" href="http://code.jquery.com/ui/1.9.1/themes/base/jquery-ui.css" />
    <script src="http://code.jquery.com/jquery-1.8.2.js"></script>
    <script src="http://code.jquery.com/ui/1.9.1/jquery-ui.js"></script>
    <link rel="stylesheet" href="/resources/demos/style.css" />
    <script>
    $(function() {
        var availableTags = [
            "ActionScript",
            "AppleScript",
            "Asp",
            "BASIC",
            "C",
            "C++",
            "Clojure",
            "COBOL",
            "ColdFusion",
            "Erlang",
            "Fortran",
            "Groovy",
            "Haskell",
            "Java",
            "JavaScript",
            "Lisp",
            "Perl",
            "PHP",
            "Python",
            "Ruby",
            "Scala",
            "Scheme"
        ];
        $( "#tags" ).autocomplete({
            source: availableTags
        });
    });
    </script>
</head>

That being said, the speed at which AJAX can call the page, to query the database and return the data, is entirely dependant on your connection and the server its running on. jQueryUI's autocomplete is really fast, I can vouch for it
Take a look through their documentation, you'll be surprised at how flexible this library is. The remote datasource example looks like this:
<script>
$(function() {
    function log( message ) {
        $( "<div>" ).text( message ).prependTo( "#log" );
        $( "#log" ).scrollTop( 0 );
    }

    $( "#birds" ).autocomplete({
        source: "search.php",
        minLength: 2,
        select: function( event, ui ) {
            log( ui.item ?
                "Selected: " + ui.item.value + " aka " + ui.item.id :
                "Nothing selected, input was " + this.value );
        }
    });
});
</script>

A: While building autocomplete/realtime search features in your web site, you might as well consider using services like rockitsearch.com . It is free web service for building autocomplete/search frond ends.


text:
Q: A problem about finding the probability a random variable is bigger than another random variable I'm studying statistics through Khan Academy and it had this question:

"Yuki and Zana are on a swimming team. They often compete against each
  other in the 100 meter freestyle race. Yuki's times in this race are
  normally distributed with a mean of 80 seconds and a standard
  deviation of 4.2 seconds. Zana's times are also
  normally distributed with a mean of 85 seconds and a standard
  deviation of 5.6 seconds. We can assume that their
  times are independent.
Suppose we choose a random 100-meter freestyle race and calculate the
  difference between their times.
Find the probability that Yuki's time is faster than Zana's."

Khan Academy's answer to the question is 0.7611 or approximately 0.76. I've spent hours working on this problem and I frustratingly keep on ending up with an answer of 0.2389. Can someone please help me on what I'm doing wrong?

A: I had the very same issue. As @mihaild mentions in the comment, your solution is the inverse of the true one. The real reason for this is in the text though.
What you (and I) calculated was the probability that Yuki's time is greater than Zana's. However, the question is about the probability that Yuki's time is faster, not greater. Because, of course, she is faster when her time is lower.


text:
Q: C++ Determine if binary is writable and updatable (it's not running) How can I check if a file(binary) is writable and "updatable" (meaning that the binary is not running and I can modify it since in Windows you can't modify a running binary).
Of course I can list the running processes and look it up in there but I would like to use a more direct approach if possible.
How can I distinguish between a fail because I have no write rights or fail because the binary is currently running?
Can AccessCheck provide that info?
Thank you


text:
Q: Regex for addresses in sparse/bad data I have a long file which was mangled by OCR/conversion and looks like this in general...
-------------JOE-LTO-N   ------TN---370-80 -----------------------
"00900006202                 26808      NAME, IDA BELLE &  BILLY               7621 RIDGEWOOD RD GOODLETTSVILLE 37072               $298.07"
"NAME, IDA BELLE 7621RIDGEWOOD RD"
GOODLITTSVILLE
"NAME, BILLY"
7621RIDGEWOOD RD
TN            37072 ....

...and I am trying to extract names/addresses using regex.
I need to extract all data matching the form LASTNAME, FIRSTNAME and also data matching the form STREETNUMBER TEXT ZIPCODE.
So far I have:
import re
import csv
exA = "ex-a.csv"
namelist = []
addlist = []
with open(exA, 'r') as exhibitA:
    lines = csv.reader(exhibitA, delimiter=",")
    namesearch = re.compile('([A-Z]+\w+, (\w*)')
    addsearch = re.compile('\d+(.*)\d{5}')
    for l in lines:
        names = namesearch.findall(str(l))
        namelist.append(names)
        adds = addsearch.findall(str(l))
        addlist.append(adds)
print(addlist)

But I'm having no success extracting this information. At best it's partial and inaccurate. It doesn't need to be perfect, but I'd like to get most of the data into a better form. Can anyone help?

A: Name Regex: (?<=NAME,\s)([A-Za-z&\s]*?)(?=\"|\s+\d)Demo
Address Regex: \d+\s?[A-Za-z][\w\s]+[\w]+(?:\d{5})? Demo


text:
Q: Matrix indexes with ejml (or other Java libraries) I'm using ejml library for writing mathematical algorithms in java. I think it is pretty useful, but I need to know if there is a fast mode (like print()) to print a matrix with indexes. Example:
    1    2
1  0.00 0.01
2  0.03 0.54
3  3.45 7.88
4  2.24 5.66

Otherwise, do you know other libraries aimed at the purpose?

A: Take a look at MatrixIO class. It has over 10 different print(...) methods, for all kinds of matrices. Altough there are no indices will be printed you can override needed methods at your wish.
On the other hand, custom implementation should be fairly simple algorithm. Some generic method which accepts all kinds of matrices should be sufficient.
Here's a working example with comments:
Code
public class MatrixWithIndices {

    public static void main(String[] args) {
        SimpleMatrix simpleMatrix = SimpleMatrix.random_DDRM(5, 5, 1, 9, new Random());

        printMatrixWithIndices(simpleMatrix.getDDRM(), 5, 5);
    }

    public static void printMatrixWithIndices(DMatrix matrix, int numChar, int precision) {
        String format = "%" + numChar + "." + precision + "f "; // default format

        StringBuilder columnIndexes = new StringBuilder();
        columnIndexes.append("    "); //skips first 4 chars

        // Append column indices
        for (int i = 0; i < matrix.getNumCols(); i++) {
            columnIndexes.append(i + 1);

            // Print spaces till next column
            for (int j = 0; j < String.format(format, matrix.get(0, i)).length() - 1; j++) {
                columnIndexes.append(" ");
            }
        }

        // Print column indices
        System.out.println(columnIndexes.toString());

        // Print horizontal dotted line
        System.out.println("  " + columnIndexes.toString().replaceAll(".", "-").substring(3));

        // Print rows
        for (int y = 0; y < matrix.getNumRows(); ++y) {

            // Prints row's index with 'border' (vertical line)
            System.out.print((y + 1) + " | ");

            // Print matrix values
            for (int x = 0; x < matrix.getNumCols(); ++x) {
                System.out.printf(format, matrix.get(y, x));
            }

            // Breaks line
            System.out.println();
        }
    }
}

Output
    1       2       3       4       5
  -----------------------------------------
1 | 7.16880 6.12461 3.67458 8.26479 2.07274
2 | 1.73381 6.81084 7.52687 3.40099 4.50719
3 | 2.56602 8.93279 3.83817 7.26837 2.54689
4 | 6.17946 2.56854 6.42016 3.85734 5.58872
5 | 5.89330 4.50916 1.15128 8.49580 6.02326

It's far from being perfect. Formatting will break for large values, but it should give you a good start.
GitHub Gist: https://gist.github.com/MSBlastt/7c4f3e25b8bed74fac90b6e0ef2f8e7a


text:
Q: Constant current power supply and 2 LED - series or parellel? I have a very limited understanding of how current works in parallel or in series.  I am trying to connect a pair of LEDs to a constant current power supply (1200ma) in which the power supply automatically adjusts the output voltage according to the current draw.
Which (if any) will result in a brighter output?  Series or parallel configuration?
The LEDs are Cree XP-G2 1A R5 that can handle 1.5A of current.  Of course I don't want to max this out because it will create too much heat.  I have tried both setups and measured the amp draw maxed at 1200ma but I can't tell which is brighter.  Does it even matter in my case?
Any help would be greatly appreciated.

A: You should connect them in series because:

*

*if diodes are connected in series - exactly the same current is flowing

*current will be 1200mA, because it does not split like in parallel

In series - circuit will need higher voltage to reach 1200mA on these leds, because in series voltage (not current) splits.

A: Series connected since power supply voltage is adjustable but current source has 1200 mA limit. To draw current required by two series connected LED voltage needs to be increased.


text:
Q: Check if two columns are equal for all rows per group Assuming a DB like this:
Date | Attribute1 | Attribute2 | ... | AttributeN
-------------------------------------------------
1    | A          | C          | ... | ...
1    | B          | C          | ... | ...
2    | A          | A          | ... | ...
2    | B          | B          | ... | ...
2    | A          | A          | ... | ...
3    | B          | B          | ... | ...
3    | A          | A          | ... | ...
4    | B          | C          | ... | ...
4    | A          | A          | ... | ...

I am trying to find for which unique dates (they are actual dates in the real case but I don't think that matters), ALL elements of Attribute1 are equal to their corresponding elements in Attribute2. The result for the example data above would be
Date
----
2
3

Because for each record that has date equal to 2 (and the same for 3) , Attribute1 is equal to Attribute2. 4 is not returned because although the last record in the sample does meet the criterion (since A equals A), the second last record does not (since B does not equal C).
I could not work out how to write this query, I was hoping for some aggregate function (shown as ALL(...) in the code below) that would allow me to write something like:
SELECT Date
FROM myTable
GROUP BY Date
HAVING ALL(Attribute1 = Attribute2)

Is there such a function? Otherwise is there a clever way to this using COUNT maybe?

A: You can use HAVING and CASE:
SELECT [Date]
FROM #tab
GROUP BY [Date]
HAVING SUM(CASE WHEN Attribute1 = Attribute2 THEN 0 ELSE 1 END) = 0

LiveDemo

Otherwise is there a clever way to this using COUNT maybe?

Why not :) Version with COUNT:
SELECT [Date]
FROM #tab
GROUP BY [Date]
HAVING COUNT(CASE WHEN Attribute1 <> Attribute2 THEN 1 END) = 0

LiveDemo2

A: Perhaps this:
select Date from Test
Except
Select Date from Test where Attribute1 <> Attribute2

A: The logic is easier if you turn it around. You want all unique DATE values where there isn't a row where Attribute1 is different to Attribute2:
SELECT DISTINCT [Date] FROM myTable
WHERE [Date] NOT IN (
   SELECT [Date] FROM myTable
   WHERE Attribute1 != Attribute2)