StackOverflowException Error

Question: I'm having an issue where I have put in my first array to a public method called DisplayArray1(), I have compiled it and when I got to open up the executable file is says "Process is terminated due to StackOverflowException"? Has anyone else had this problem?
This is my code so far:
using System;

namespace FlexibleArrayMethod
{
    class Program
    {
        static void Main()
        {
            Console.Clear();

            // Call intDisplayArray1() to output on screen
            intDisplayArray1();
            Console.Write("Array 1:  ");
        }
        public static int intDisplayArray1()
        {
            // first array declaration
            int[] Array1 = {5, 10, 15, 20};

            return intDisplayArray1[];
        }
    }
}

Any help is appreciated!
Comment: how did you compile this? `return intDisplayArray1[];` is not valid.
Comment: I imagine your real code is `return intDisplayArray1();` but it looks like you meant `return Array1;`.
Comment: I compiled everything through Command line. No errors came up while compiling either so I'm honestly not sure if you're saying it isn't valid. I trying to create a console-based application that declares 3 arrays of different sizes. Then passes each array to a method that displays all the integers in each array and their sum.
Comment: also can you explain what do you want to achieve?
Comment: @AlyBee i liked your comment because you honestly said what you want. :-)
Comment: @M.kazemAkhgary thank you xD I'm honestly struggling right now in my Programming 1 class and I can explain what I need it to do, I'm just unsure of how to get the outcome correctly.
Answer: assuming that return intDisplayArray1[]; (which doesn't compile) is really return intDisplayArray1(); in your code, you are in a recursive loop.
You are calling your method repeatedly without an exit condition.  Looks like you really just want to return your array:
 public static int[] intDisplayArray1()
 {
    int[] Array1 = { 5, 10, 15, 20 };

    return Array1;
 }

though there are a profound amount of logical errors still.
Here's what I'm led to believe you are trying to do:
static void Main()
{
    Console.Clear();

    // Call intDisplayArray1() to output on screen
    int[] array1 = intDisplayArray1();
    Console.Write("Array 1: " + string.Join(",", array1));
    Console.Read();
}

public static int[] intDisplayArray1()
{
   // first array declaration
   int[] Array1 = { 5, 10, 15, 20 };

   return Array1;
}

Comment: I edited the code and it shows the `Console.Write("Array 1:  ");` in the command line, but my array itself doesn't show
Comment: @AlyBee dont expect when you compile `Console.Write("Give me coffee: ");` actually do what you want.
Comment: you certainly could try it and find out what it does.  Best way to learn.
Comment: I'll go ahead and post the entirety of what I believe you are wanting
Comment: So then I should just put `Console.Write(intDisplayArray());`?
Comment: @Jonesopolis Honestly, I'm not advanced enough to understand the `Console.Write("Array 1: " + string.Join(",", array1));` part. I get declaring `intDisplayArray1()` as `int[] array1`, though.
Comment: Microsoft puts out documentation for us -> [string.Join](https://msdn.microsoft.com/en-us/library/57a79xd0(v=vs.110).aspx)
Comment: Oh, okay, I get it now! So, with the other arrays I have to implement and adding them together is the other issue. Now knowing how to display each one on the screen should resolve displaying the sum as well. Adding them will be the next hurtle to get over.
Comment: i think first you have to learn more about arrays. the way you just wanted to try `Console.Write(intDisplayArray());` will just print `System.Int32[]`. Thats right. the type of `int[]`. but in order to print elements of array you have to write  `Console.Write(array[0]);` and it will print first element. then `Console.Write(array[1]);` will print second element. this can be done inside loop though. @AlyBee
Comment: I appreciate all the help, guys :) You're angels! <3
Comment: So, update: The code works and I have all my arrays listed in their own methods and displayed in the Main method. Now I'm trying to calculate the sum of all of them. Any tips?
Comment: the sum of every number in every array?
Comment: Yes, exactly. Like, I've displayed array1 and now I need to display the sum of that array and so on. It's not requesting to add all the arrays together.
Comment: `Console.WriteLine("Array 1 Total: " + array1.Sum());`, you might need to add a using  statement for`System.Linq`
Comment: This may sound like a stupid question, but what exactly does that mean?

StackOverflowException Error


When using the ternary conditional operator, why does the compiler care if TypeA is convertable to TypeB and vice versa?

Question:
Possible Duplicate:
Type result with conditional operator in C#

Basically I have some code like this:
IEnumerable<Effect> effects = ( ( activeOnly ) ? this.ActiveEffects : this.AllEffects ).Select ( e => e );

where:
this.ActiveEffects is:
class ActiveEffectList : IEnumerable<Effect>

this.AllEffects is:
class EffectList : IEnumerable<Effect>

which is why I expected the above statement to work, but it returns this compile error:

Type of conditional expression cannot
  be determined because there is no
  implicit conversion between
  'ImageEditor.ActiveEffectList' and
  'ImageEditor.EffectList'
Comment: this is a common question, check the above duplicate. Short short version is type must be able to be determined from the expression on the right, the type on the left is not part of that logic.
Comment: I answered this by linking to another similar question, but Anthony's got it right - the proposed duplicate answers this handily.
Answer: You can solve this problem by casting the first value to IEnumerable<Effect>:
var effects = activeOnly ?
              (IEnumerable<Effect>) this.ActiveEffects :
              this.AllEffects;

The problem is that even though you're assigning to IEnumerable, the compiler needs to evaluate the conditional expression before the cast happens and since the conditional statement needs both paths to return the same type, you are getting an error that AllEffects can't be cast to ActiveEffects.
By casting the first value in the statement to IEnumerable<Effect>, you are forcing the conditional statement to return IEnumerable<Effect> rather than one of the more specific types.
Comment: @Joan, you can cast either. The idea is that at least one must be convertible to the other, you can generally cast either side. It will evaluate if X can go to Y or if Y can go to X.
Comment: @Joan - By casting the first, you are setting the type for the expression. .NET will automatically try to convert the second value to the type of the expression...so it will handle that second cast for you.
Comment: Thanks but why cast only the first one? I would think you need need to cast both? What's the difference?
Answer: Because it does not look at base types or the left side type when resolving the types.
You solve this by changing your statement into:
IEnumerable<Effect> effects = ( ( activeOnly ) ? (IEnumerable<Effect>)this.ActiveEffects : this.AllEffects ).Select ( e => e );

Answer: Because a ternary expression is an expression, and expressions have a type. The compiler doesn't try to find the closest common assignment-compatible type (as such a search could potentially be very complicated and would usually be of little value). In your case, you have two completely different types. All types (outside of unsafe blocks, in general) have a common ancestor at object, but the compiler doesn't look up the chain; if the two types don't have assignment compatibility in at least one direction, then you have to tell it what you want.
The easy solution is to cast one of the operands to the desired type. This will direct the compiler to compare the other operand to that type, which it will immediately see as compatible. So, in other words, cast one operand to IEnumerable<T>.
Answer: Your classes have both inherited from the same base (IEnumerable), but could have different implementations.  Before the assignment operator, the ternary operator first has to return a common type between the two values, and cannot convert b to a.
According to the reference:
http://msdn.microsoft.com/en-us/library/ty67wk28.aspx

Either the type of first_expression and second_expression must be the same, or an implicit conversion must exist from one type to the other.

Either do this:
IEnumerable<Effect> effects = ( ( activeOnly ) ? (IEnumerable<Effect>)this.ActiveEffects : this.AllEffects ).Select ( e => e );

Or add a implicit conversion operator to your classes:
http://msdn.microsoft.com/en-us/library/z5z9kes2(VS.71).aspx


Stop tests execution after first error/failure with maven surefire

Question: I'm using maven surefire plugin to execute the junit tests of my application.
I want to stop the execution after the first failure or error. In my case, these are integration tests that modify the application state, so I need to know the exact system state after the failure (we're having a strange issue that a test passes if executed isolated, but not if executed with the whole suite).
Is it possible? I couldn't find a option in the plugin docs here.
Answer: Actually, it turns out that this is not possible to do with maven-surefire-plugin.
I found the answer here.
I actually end up using the solution proposed there by @mhaller
So I implemented a junit listener like this:
package br.com.xpto;

import org.junit.runner.Description;
import org.junit.runner.notification.Failure;
import org.junit.runner.notification.RunListener;

import br.com.caelum.brutal.integration.scene.AcceptanceTestBase;

public class FailFastListener extends RunListener {

    public void testFailure(Failure failure) throws Exception {
        System.err.println("FAILURE: " + failure);
        AcceptanceTestBase.close();
        System.exit(-1);
    }

    @Override
    public void testFinished(Description description) throws Exception {
        AcceptanceTestBase.close();
        System.exit(-1);
    }
}

And configure maven-surefire like this:
<plugin>
    <artifactId>maven-surefire-plugin</artifactId>
    <version>2.10</version>
    <executions>
        <execution>
            <id>surefire-integration</id>
            <phase>integration-test</phase>
            <goals>
                <goal>test</goal>
            </goals>
            <configuration>
                <excludes>
                    <exclude>none</exclude>
                </excludes>
                <includes>
                    <include>**/scene/**/*Test.java</include>
                </includes>
                <forkMode>once</forkMode>
                <properties>
                    <property>
                        <name>listener</name>
                        <value>br.com.caelum.brutal.integration.util.FailFastListener</value>
                    </property>
                </properties>
            </configuration>
        </execution>
    </executions>
    <configuration>
        <excludes>
            <exclude>**/*</exclude>
        </excludes>
    </configuration>
</plugin>

Answer: First for integration tests you should use the maven-failsafe-plugin and not the maven-surefire-plugin.
Furthermore if you have integration tests which fail which is usually done on a CI environment. Afterwards you can run your failing integration test via
mvn -Dit.test=NameOfTheFailedIntegrationTest verify

separately.
Comment: actually it is a maven-surefire-plugin issure, since maven failsafe does not execute the tests, it just verify the results. Also its not of interest to execute only the failing tests, since the tests are passing when executed isolated (see my answer and update)


Countably many isolated points implies that any disjoint union of open sets is countable.

Question: I have a problem in general topology that I am not able to solve.
Let $X$ be a topological space with denumerably infinite many isolated points. Then show that any collection of pairwise disjoint open sets is denumerably infinite.
Any help would be much appreciated.
Comment: Is the question about showing that a ***collection*** of open sets is countable (as in the body of your post) or is it about showing that the ***union*** is countable (as in the title)?
Comment: I don't think there is any condition on a topological space $X$ which implies that any collection of pairwise disjoint open sets is ***infinite***, much less ***denumerably infinite***. There seem to be multiple problems with the question as you have stated it in English. Could you post the assignment in the original French?
Comment: **Counterexample.** Let $X=(-\infty,0)\cup\mathbb N,$ topologized as a subspace of $\mathbb R.$ Then $X$ is a topological space with denumerably many isolated points, namely, the points $1,2,3,\dots.$ Yet $\{(-4,-3),(-2,-1)\}$ is a collection of pairwise disjoint open sets which fails to be denumerably infinite, as it has only two members.
Comment: $X$ can have an uncountable family of pair-wise disjoint open sets even if the set of isolated points of $X$ is empty or finite or countably infinite.
Answer: Unless I'm missing something, the claim is false.

Let $B$ be any uncountable collection of pairwise disjoint sets, each containing at least two points, and let $X$ be the union of the members of $B$.

Let $T$ be the set of all unions of any number of members of $B.\;\,$Then

$T$ is a topology on $X$.
There are no isolated points.
There is an uncountable collection of pairwise disjoint open sets, namely, the members of $B$.

For a concrete example, let $X = \mathbb{R}-\{0\}$, and let $B = \{\{x,-x\} \mid x > 0\}$. Thus, the topology $T$ will be comprised of all subsets $U$ of $X$ such that whenever $x$ in $U,\;-x$ is also in $U$.

Edit:

The original version of the question specified countably many isolated points, so my counterexample qualifies, since it has no isolated points.

But in the OP's new edit, the requirement is now a countably infinite number of isolated points, not just countable.

But it's easy to satisfy this new requirement . . .

Just take any countably infinite set $S$, where $S$ is disjoint from $X$, and let $Y = X \cup S$.

Then define a topology on $Y$ by declaring a subset of $Y$ as open if it's the union of a (possibly empty) subset of $S$ with an open (possibly empty) subset of $X$, where "open" means open in the topology previously defined on $X$.

Then $Y$ is a topological space with a countably infinite number of isolated points, namely the points of $S$, and there is an uncountable collection of pairwise disjoint open subsets of $Y$, namely, the members of $B$.

Alternatively, here's a concrete example, similar to the old one, which satisfies the new requirements . . .

Let $X=\mathbb{R}$, and declare a set open if it's the union of a (possibly empty) subset of $\mathbb{Z}$ with a (possibly empty) subset $U$ of $\mathbb{R}-\mathbb{Z}$ such that whenever $x$ is in $U,\;-x$ is also in $U$.

Then the set of isolated points of $X$ is the set $\mathbb{Z}$, which is countably infinite, and the set
$$B = \{\{x,-x\} \mid x\in \mathbb{R}-\mathbb{Z}\;\text{and}\;x > 0\}$$
is an uncountable collection of pairwise disjoint open subsets of $X$.
Comment: Countable does not mean countably infinite. Finite sets are also countable. But it doesn't matter. For any space $X$, we can adjoin a countably infinite set, and declare all the new singletons as open.
Comment: Thank you.  I've been sitting here trying to figure out what was wrong with my counterexample, and the answer is -- nothing.
Comment: I might be wrong, but I think this is not the point of the exercise. To disprove the statement, you would need to show the existence of a topology X with 1. a collection B of uncountably (infinitely) many pairwise disjoint open sets 2. countably (infinitely) many isolated points.
Comment: The exercise is formulated in French and perhaps my translation of "dénombrable" into countable was not the most accurate. Sorry about that. I guess denumerable would be the right terminology in this case.


Fundamental theorem Galois Theory

Question: From time to time, I try to give my non-mathematician scientist friends descriptions of important theorems that I come across.
One friend, watched a video on Galois and now I'm at a loss on how to state to her the Fundamental Theorem of Galois Theory in an intuitive yet mathematically correct manner.
Comment: Boy, are you in problems or what. I highly doubt there's an "intuitive" basic way to describe this theorem without having to use some slightly powerful mathematical terminology, beginning from the most basic notion: fields extension.
Comment: Did the friend *ask* you to state the fund. thm. of Galois theory, or is it your idea to try to describe this theorem just from the friend having watched a video on Galois?
Comment: The friend asked me to describe the theorem, not exactly state it.
Answer: A very powerful idea in mathematics is to reduce a problem in one setting to a problem in another setting. What at first might seem like a difficult problem in one setting can suddenly be revealed to be a relatively straightforward problem in another. These sorts of reductions pervade mathematics.
The fundamental theorem of Galois theory performs a reduction of this type. The problem it reduces concerns the study of algebraic field extensions; roughly speaking, the idea here is to study nice collections of roots of polynomials, and the way in which the roots of some polynomials can be expressed in terms of the roots of other polynomials. If you've ever tried to work with polynomials that are not quadratic, you might have some appreciation for how difficult a problem this could have been.
Galois theory reduces this problem, in an appropriate sense, to the problem of studying the symmetries of the roots. In mathematics, we talk formally about symmetry using group theory. Galois theory associates to a polynomial the collection of all permutations of its roots which, roughly speaking, preserve all algebraic identities those roots satisfy. Roughly speaking again, this Galois group encodes in some appropriate sense the way in which roots of other polynomials relate to the roots of our polynomial, and because we know a lot about group theory it is often easier to study Galois groups than to study field extensions directly.
A remarkable result that can be proven using the fundamental theorem is the Abel-Ruffini theorem. Now, as it turns out, the quadratic formula that everyone is familiar with generalizes to a more complicated cubic formula and an even more complicated quartic formula. The Abel-Ruffini theorem states that these formulas do not generalize any further; there is no quintic formula expressing the roots of a quintic polynomial in terms of algebraic operations, including taking roots.
The proof that proceeds via Galois theory reduces this problem to showing that the group of symmetries of $5$ things is more complicated, in a certain precise sense (it is not solvable), than the group of symmetries of $2, 3$, or $4$ things, and roughly speaking an analogue of the quadratic formula can only exist if the Galois group is not complicated in this particular way.

Fundamental theorem Galois Theory


java:classname.java uses unchecked or unsafe operations

Question: I have a java project, and after compiling it I get 2 warnings:
java: filepath\filename.java uses unchecked or unsafe operations.
java: Recompile with -Xlint:unchecked for details.

And here is the code of the class:
public class GuiMain extends javax.swing.JFrame {

/**
 * Don't use parameters because of windows 7.
 */
public static final boolean USE_PARAMETERS = false;

/**
 * The refresh rate of the traffic screen capturing.
 */
private static int TRAFFIC_REFRESH_RATE = 0;

private static final long serialVersionUID = -2417685564943832874L;

private static final String CLIENT_NAME = "Traffic Analysis";

private static final String OUTPUT_FILE = "last_session_results.txt";

private JPanel pMainMenu = null;
private JPanel pInput = null;

private JButton btCreate = null;
private JTextField tfInput = null;
private JTextField tfCoordinates = null;

private JPanel pObserve = null;
private JScrollPane spObserve = null;
private JTable tblObserve = null;
private TrafficObserveModel modelObserve = null;
private JButton btAddObserver = null;
private JButton btDelObserver = null;
private JButton btObserving = null;

private JPanel pPaint = null;
private ImagePanel imagePanel = null;
private JButton btTrafficObserver = null;
private JComboBox cobSections = null;
private JButton btNewSection = null;
private JButton btDelSection = null;
private JButton btUndo = null;
private JButton btSave = null;
private JLabel lTimeInterval=null;//moe
private JTextField tfInputTinter=null;//moe
private JPanel pInputTime=null; //moe
private KeyListener keyListener ; //moe

private boolean observeTrafficView = false;
private boolean currentlyObserving = false;

private String curFileName = "";
private MapSection mapSection = null;
private ScreenCaptureController screenCapturing = null;

private Vector
 observeTraffic = new Vector
();
private BufferedImage lineImage = null;

public GuiMain() {
    super();

    try {
        // Create or delete content from the output file.
        BufferedWriter bw = new BufferedWriter(new FileWriter("." + ToolKit.fileSeparator() + OUTPUT_FILE));
        bw.close();

        // Create the "maps" directory if it doesn't exist.
        File mapsFile = new File("maps");

        if(!mapsFile.exists()) {
            if(!mapsFile.mkdir()) {
                System.out.println("Couldn't create maps directory.");
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

    screenCapturing = new ScreenCaptureController(this);
    screenCapturing.addScreenCaptureListener(new ScreenCaptureController.ScreenCaptureListener() {
        public void capturedScreen() {
            if(currentlyObserving) {
                ImageAnalysis analysis = new ImageAnalysis();
                int traffic[] = analysis.colorShare(screenCapturing.getMapTrafficOnly(), lineImage);

                try {
                    // Write the results to the file.
                    PrintWriter out = new PrintWriter(new BufferedWriter(
                        new FileWriter("." + ToolKit.fileSeparator() + OUTPUT_FILE, true)));
                    out.println(traffic[0] + " - " + traffic[1] + " - " + traffic[2] + " - " + traffic[3]);
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } else {
                showImage(screenCapturing.getMapTraffic());
            }
        }
    });

    initMainMenu();

    initGUI();
}

private void initGUI() {
    try {
        BorderLayout thisLayout = new BorderLayout();

        this.addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                shutDown(e);
            }
        });

        getContentPane().setLayout(thisLayout);
        {
            pPaint = new JPanel();
            //getContentPane().add(pPaint, BorderLayout.NORTH);

            GridBagLayout pPaintLayout = new GridBagLayout();
            pPaintLayout.columnWidths = new int[] {7, 7, 7, 7, 7};
            pPaintLayout.rowHeights = new int[] {25};
            pPaintLayout.columnWeights = new double[] {100.0, 0.1, 0.1, 0.1, 0.1};
            pPaintLayout.rowWeights = new double[] {0.1};
            pPaint.setLayout(pPaintLayout);
            {
                cobSections = new JComboBox();
                cobSections.setRenderer(new MapSectionItemRenderer());
                pPaint.add(cobSections, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0,
                    GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL,
                    new Insets(0, 0, 0, 0), 0, 0));
                cobSections.addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent evt) {
                        cobSectionsActionPerformed(evt);
                    }
                });
            }
            {

                btUndo = new JButton();
                pPaint.add(btUndo, new GridBagConstraints(1, 0, 1, 1, 0.0, 0.0,
                    GridBagConstraints.CENTER, GridBagConstraints.NONE,
                    new Insets(0, 5, 0, 0), 0, 0));
                btUndo.setText("Undo");
                btUndo.addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent evt) {
                        btUndoActionPerformed(evt);
                    }
                });
            }
            {

                btSave = new JButton();
                pPaint.add(btSave, new GridBagConstraints(2, 0, 1, 1, 0.0, 0.0,
                    GridBagConstraints.CENTER, GridBagConstraints.NONE,
                    new Insets(0, 5, 0, 0), 0, 0));
                btSave.setText("Save");
                btSave.addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent evt) {
                        btSaveActionPerformed(evt);
                    }
                });
            }

            {
                btNewSection = new JButton();
                pPaint.add(btNewSection, new GridBagConstraints(3, 0, 1, 1, 0.0, 0.0,
                    GridBagConstraints.CENTER, GridBagConstraints.NONE,
                    new Insets(0, 10, 0, 0), 0, 0));
                btNewSection.setText("+ Section");
                btNewSection.addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent evt) {
                        btNewSectionActionPerformed(evt);
                    }
                });
            }

            {
                lTimeInterval = new JLabel("T_interval (ms)");
                lTimeInterval.setVisible(false);
                pPaint.add(lTimeInterval, new GridBagConstraints(1, 0, 1, 1, 0.0, 0.0,
                        GridBagConstraints.CENTER, GridBagConstraints.NONE,
                        new Insets(0, 5, 0, 0), 0, 0));
            }
            {
                btDelSection = new JButton();
                pPaint.add(btDelSection, new GridBagConstraints(4, 0, 1, 1, 0.0, 0.0,
                    GridBagConstraints.CENTER, GridBagConstraints.NONE,
                    new Insets(0, 5, 0, 0), 0, 0));
                btDelSection.setText("- Section");
                btDelSection.addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent evt) {
                        btDelSectionActionPerformed(evt);
                    }
                });
            }
            {

                tfInputTinter = new JTextField(3);
                tfInputTinter.setVisible(false);
                pPaint.add(tfInputTinter, new GridBagConstraints(2, 0, 1, 1, 0.0, 0.0,
                        GridBagConstraints.CENTER, GridBagConstraints.NONE,
                        new Insets(0, 5, 0, 0), 0, 0));
            }

            imagePanel = new ImagePanel(mapSection);

            getContentPane().add(pMainMenu, BorderLayout.CENTER);

            btTrafficObserver = new JButton("Traffic Observation");
            btTrafficObserver.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    onTrafficObserverClicked(e);
                }
            });

            //getContentPane().add(btTrafficObserver, BorderLayout.SOUTH);

            pObserve = new JPanel();
            BorderLayout pObserveLayout = new BorderLayout();
            pObserve.setLayout(pObserveLayout);
            {
                JPanel pObserverButtons = new JPanel(new BorderLayout());
                {
                    btAddObserver = new JButton("Add");
                    pObserverButtons.add(btAddObserver, BorderLayout.WEST);
                    btAddObserver.addActionListener(new ActionListener() {
                        public void actionPerformed(ActionEvent evt) {
                            btAddObserverActionPerformed(evt);
                        }
                    });
                }
                {
                    btDelObserver = new JButton("Remove");
                    pObserverButtons.add(btDelObserver, BorderLayout.EAST);
                    btDelObserver.addActionListener(new ActionListener() {
                        public void actionPerformed(ActionEvent evt) {
                            btDelObserverActionPerformed(evt);
                        }
                    });
                }
                pObserve.add(pObserverButtons, BorderLayout.NORTH);

                spObserve = new JScrollPane();
                spObserve.setPreferredSize(new Dimension(150, 100));
                modelObserve = new TrafficObserveModel();
                tblObserve = new JTable(modelObserve);
                tblObserve.setDefaultRenderer(Section.class, new TrafficObserveRenderer());
                tblObserve.getColumnModel().getColumn(0).setPreferredWidth(100);
                tblObserve.setIntercellSpacing(new Dimension(0, 0));
                tblObserve.setRowSelectionAllowed(true);
                tblObserve.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); // moe bese sigle- selection
                spObserve.setViewportView(tblObserve);

                pObserve.add(spObserve, BorderLayout.CENTER);

                btObserving = new JButton("Observe Traffic");
                pObserve.add(btObserving, BorderLayout.SOUTH);
                btObserving.addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent evt) {
                        btObservingActionPerformed(evt);
                    }
                });
            }

            //getContentPane().add(pObserve, BorderLayout.EAST);
        }

        pack();
        setSize(320, 130);
        setTitle(CLIENT_NAME);
        setLocationRelativeTo(null);
        setVisible(false);
    } catch (Exception e) {
        //add your error handling code here
        e.printStackTrace();
    }
}

private void initMainMenu() {
    try {
        BorderLayout thisLayout = new BorderLayout();

        pMainMenu = new JPanel();

        pMainMenu.setLayout(thisLayout);
        {
            JPanel pButtons = new JPanel();
            pMainMenu.add(pButtons, BorderLayout.NORTH);

            GridBagLayout pButtonsLayout = new GridBagLayout();
            pButtonsLayout.columnWidths = new int[] {7, 7, 7};
            pButtonsLayout.rowHeights = new int[] {25};
            pButtonsLayout.columnWeights = new double[] {0.1, 0.1, 0.1};
            pButtonsLayout.rowWeights = new double[] {0.1};
            pButtons.setLayout(pButtonsLayout);
            {
                JButton btLoad = new JButton();
                pButtons.add(btLoad, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0,
                    GridBagConstraints.CENTER, GridBagConstraints.NONE,
                    new Insets(0, 5, 0, 0), 0, 0));
                btLoad.setText("Load");
                btLoad.addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent evt) {
                        btLoadActionPerformed(evt);
                    }
                });
            }
            {

                JButton btView = new JButton();
                pButtons.add(btView, new GridBagConstraints(1, 0, 1, 1, 0.0, 0.0,
                    GridBagConstraints.CENTER, GridBagConstraints.NONE,
                    new Insets(0, 5, 0, 0), 0, 0));
                btView.setText("View");
                btView.addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent evt) {
                        btViewActionPerformed(evt);
                    }
                });
            }
            {
                JButton btNew = new JButton();
                pButtons.add(btNew, new GridBagConstraints(2, 0, 1, 1, 0.0, 0.0,
                    GridBagConstraints.CENTER, GridBagConstraints.NONE,
                    new Insets(0, 5, 0, 0), 0, 0));
                btNew.setText("New");
                btNew.addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent evt) {
                        btNewActionPerformed(evt);
                    }
                });
            }

            pInput = new JPanel();
            pInput.setVisible(false);
            pMainMenu.add(pInput, BorderLayout.CENTER);

            GridBagLayout pInputLayout = new GridBagLayout();
            pInputLayout.columnWidths = new int[] {7, 7};
            pInputLayout.rowHeights = new int[] {25};
            pInputLayout.columnWeights = new double[] {0.1, 100.0};
            pInputLayout.rowWeights = new double[] {0.1, 100.0};
            pInput.setLayout(pInputLayout);
            {
                JLabel lName = new JLabel("Name");
                pInput.add(lName, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0,
                    GridBagConstraints.EAST, GridBagConstraints.NONE,
                    new Insets(0, 5, 0, 0), 0, 0));
            }
            {

                tfInput = new JTextField();
                pInput.add(tfInput, new GridBagConstraints(1, 0, 1, 1, 0.0, 0.0,
                    GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL,
                    new Insets(0, 5, 0, 0), 0, 0));
            }
            {
                JLabel lCoordinates = new JLabel("Coordinates");
                pInput.add(lCoordinates, new GridBagConstraints(0, 1, 1, 1, 0.0, 0.0,
                    GridBagConstraints.EAST, GridBagConstraints.NONE,
                    new Insets(0, 5, 0, 0), 0, 0));
            }
            {

                tfCoordinates = new JTextField();
                pInput.add(tfCoordinates, new GridBagConstraints(1, 1, 1, 1, 0.0, 0.0,
                    GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL,
                    new Insets(0, 5, 0, 0), 0, 0));
            }

            btCreate = new JButton("Create");
            btCreate.setVisible(false);
            btCreate.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent evt) {
                    btCreateActionPerformed(evt);
                }
            });

            pMainMenu.add(btCreate, BorderLayout.SOUTH);
        }
    } catch (Exception e) {
        //add your error handling code here
        e.printStackTrace();
    }
}

public void showImage(BufferedImage curImage) {
    imagePanel.setImage(curImage, mapSection);

    setSize(curImage.getWidth(), curImage.getHeight() + 80);
    setLocationRelativeTo(null);
}

private void showTrafficMap() {
    if(mapSection != null) {
        screenCapturing.setMapSection(mapSection);

        if(screenCapturing.captureBaseMap()) {
            try {
                getContentPane().remove(pMainMenu);
                getContentPane().add(pPaint, BorderLayout.NORTH);
                getContentPane().add(imagePanel, BorderLayout.CENTER);
                getContentPane().add(btTrafficObserver, BorderLayout.SOUTH);

                cobSections.setModel(new DefaultComboBoxModel(mapSection.getModel()));

                if(mapSection.getModel().size() > 0) {
                    cobSections.setSelectedIndex(0);
                }

                validate();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

private void shutDown(WindowEvent e) {
    if(mapSection != null && curFileName != "") {
        XMLManager.writeFile(curFileName, mapSection);
    }

    System.exit(0);
}

private void btSaveActionPerformed(ActionEvent evt) {
    if(mapSection != null && curFileName != "") {
        XMLManager.writeFile(curFileName, mapSection);
    }
}

private void btLoadActionPerformed(ActionEvent evt) {
    JFileChooser chooser = new JFileChooser();

    chooser.setCurrentDirectory(new java.io.File("maps"));
    chooser.setDialogTitle("Select Map");
    chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);

    // disable the "All files" option.
    chooser.setAcceptAllFileFilterUsed(false);
    //
    if(chooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
        curFileName = chooser.getSelectedFile().toString();

        mapSection = XMLManager.parseFile(curFileName);

        showTrafficMap();
    } else {
        System.out.println("No Selection ");
    }
}

private void btViewActionPerformed(ActionEvent evt) {
    if(USE_PARAMETERS) {
        String htmlFilePath = "html" + ToolKit.fileSeparator() + "trafficPrototype.html";
        File htmlFile = new File(htmlFilePath);

        String[] params = {"coord=(26.370628,-80.104281),11", "view=1"};
        ToolKit.openBrowser(htmlFile.toURI(), params);
    } else {
        String htmlFilePath = "html" + ToolKit.fileSeparator() + "trafficPrototype2.html";
        File htmlFile = new File(htmlFilePath);

        HtmlController.writeParameterScript(26.370628, -80.104281, 11, 1);
        ToolKit.openBrowser(htmlFile.toURI());
    }
}

private void btNewActionPerformed(ActionEvent evt) {
    pInput.setVisible(true);
    btCreate.setVisible(true);
}

private void btCreateActionPerformed(ActionEvent evt) {
    String fileName = tfInput.getText();
    String coords = tfCoordinates.getText();

    String coord = coords.replace("(", "").replace(")", "");
    String[] params = coord.split(",");

    boolean invalidCoord = false;
    double lat = 0.0;
    double lng = 0.0;
    int zoom = 0;

    try {
        lat = Double.parseDouble(params[0].trim());
        lng = Double.parseDouble(params[1].trim());
        zoom = Integer.parseInt(params[2].trim());
    } catch(Exception e) {
        invalidCoord = true;
    }

    if(!invalidCoord) {
        mapSection = new MapSection(fileName, lat, lng, zoom);

        fileName = fileName.replace(" ", "_");

        curFileName = "." + ToolKit.fileSeparator() + "maps" + ToolKit.fileSeparator() + fileName + ".xml";
        XMLManager.writeFile(curFileName, mapSection);

        showTrafficMap();
    } else {
        JOptionPane.showMessageDialog(this, "Invalid Coordinates!", "Coordinates", JOptionPane.ERROR_MESSAGE);
    }
}

private void cobSectionsActionPerformed(ActionEvent evt) {
    imagePanel.setCurrentSection((Section)cobSections.getSelectedItem());

    imagePanel.repaint();
}

private void btUndoActionPerformed(ActionEvent evt) {
    if(cobSections.getSelectedIndex() != -1) {
        Section selectedSection = (Section)cobSections.getSelectedItem();

        if(selectedSection.removeLastAddedItem()) {
            imagePanel.repaint();
        }
    }
}

private void btNewSectionActionPerformed(ActionEvent evt) {
    String newSectionName = "";

    newSectionName = JOptionPane.showInputDialog(this, "Input your new section name.",
        "New Section", JOptionPane.QUESTION_MESSAGE);

    if(newSectionName != null && !newSectionName.equals("")) {
        Section section = new Section(newSectionName);

        if(mapSection.addSection(section)) {
            cobSections.setSelectedIndex(cobSections.getItemCount() - 1);
        } else {
            JOptionPane.showMessageDialog(this, "Section " + newSectionName + " already exists!",
                "New Section", JOptionPane.INFORMATION_MESSAGE);
        }
    }
}

private void btDelSectionActionPerformed(ActionEvent evt) {
    if(cobSections.getSelectedIndex() != -1) {
        int selectedOption = JOptionPane.showConfirmDialog(this, "Delete " +
            ((Section)cobSections.getSelectedItem()).getId() + " section?",
            "Delete Section", JOptionPane.YES_NO_CANCEL_OPTION);

        if(selectedOption == JOptionPane.YES_OPTION) {
            mapSection.getSections().remove(cobSections.getSelectedIndex());
            cobSections.setSelectedIndex(0);
        }
    }
}

private void btAddObserverActionPerformed(ActionEvent evt) {
    if(cobSections.getSelectedIndex() != -1) {
        Section sectionToAdd = (Section)cobSections.getSelectedItem();
        boolean duplicate = false;

        for(Section section : observeTraffic) {
            if(section.getId().equals(sectionToAdd.getId())) {
                duplicate = true;
            }
        }

        if(!duplicate) {
            observeTraffic.add(sectionToAdd);

            modelObserve.setData(observeTraffic);

            imagePanel.repaint();
        }
    }
}

private void btDelObserverActionPerformed(ActionEvent evt) {
    if(tblObserve.getSelectedRow() != -1) {
        observeTraffic.remove(tblObserve.getSelectedRow());

        modelObserve.setData(observeTraffic);

        imagePanel.repaint();
    }
}

private void btObservingActionPerformed(ActionEvent evt) {

    String timeInterval = tfInputTinter.getText();//moe

    if(modelObserve.getRowCount() > 0) {
        if(currentlyObserving) {
            currentlyObserving = false;

            btObserving.setText("Observe Traffic");

            screenCapturing.stopCapturing();
        } else {
            currentlyObserving = true;

            btObserving.setText("Stop Observing");

            lineImage = imagePanel.getLineImage();

            if(!timeInterval.trim().isEmpty()) //moe
            {
                tfInputTinter.addActionListener(new ActionListener() {

                    @Override
                    public void actionPerformed(ActionEvent e) {
                        //btObserving.setText("Stop Observing");
                    }
                });

                 TRAFFIC_REFRESH_RATE=Integer.parseInt(timeInterval);//moe
                 screenCapturing.captureAutomatically(TRAFFIC_REFRESH_RATE);
            }

        }
    } else {
        JOptionPane.showMessageDialog(this, "There are no sections selected.",
            "Observe Traffic", JOptionPane.INFORMATION_MESSAGE);
    }

}

private void onTrafficObserverClicked(ActionEvent e) {
    if(observeTrafficView) {
        observeTrafficView = false;

        btTrafficObserver.setText("Traffic Observation");

        btUndo.setVisible(true);
        btSave.setVisible(true);
        btNewSection.setVisible(true);
        btDelSection.setVisible(true);

        lTimeInterval.setVisible(false);
        tfInputTinter.setVisible(false);

        getContentPane().remove(pObserve);
    } else {
        observeTrafficView = true;

        btTrafficObserver.setText("Traffic Manipulation");

        btUndo.setVisible(false);
        btSave.setVisible(false);
        btNewSection.setVisible(false);
        btDelSection.setVisible(false);

        lTimeInterval.setVisible(true);
         tfInputTinter.setVisible(true);

        getContentPane().add(pObserve, BorderLayout.EAST);
    }

    imagePanel.setObserveTraffic(observeTraffic, observeTrafficView);
    validate();
    }
}

Can anybody help me how to resolve this? I would like to make a new jar file, but I suppose I should rebuild the project without warnings first.
Thanks in advance.
Comment: Did you do as the compiler suggests: "Recompile with -Xlint:unchecked for details"?  What additional info did you see?
Answer: Can anybody help me how to resolve this? I would like to make a new jar file, but I suppose I should rebuild the project without warnings first.
Of course that you can compile with warnings if you haven't errors, but you must be careful with the logic of your app more than "0 warnings".
See this question, it could be helpful for you.
Comment: Or alternatively, OP could just try recompiling with `-Xlint:unchecked`.
Comment: Maybe in a future release of Java, Oracle will change that message to `Post a question on Stack Overflow for details`.
Comment: Of course, it's a bad way to ignore the compiler suggestions :)
Comment: @DavidWallace That's actually what Google did with their Android Google Group.
Answer: JComboBox is a generic type that needs a type parameter to indicate the type of the items the JComboBox presents.  You have not provided this type parameter, so the compiler issues the warning you see.  In your case, you'll want to declare it as JComboBox
, and make a similar change to the DefaultComboBoxModel, since it too needs this type parameter.  Once you've done that, you can also remove those casts you're currently doing when you get items from the combo box.
Comment: Thanks, but still I get the same the warnings


mod_rewrite for iframe pointed to mediaurl & retain GET params

Question: I have an iframe to embed audio which points to a src like this...
http://domain.com/embed/mediaID

At the embed level I have an index.php listening to GET requests but it will of course never get the requests unless I do some sort of redirect in my .htaccess like so...
RewriteEngine On
RewriteRule ^([^/]*)$ index.php?var1=$1 [L]

That accounts for the path schema so I can point to a mediaID like that but this is unscalable in that I can't easily add more GET params.
I'm seeing that YouTube & Vimeo point to a mediaID but then also allow GET params thereafter.
My understanding is that a rewrite is the way to go for this but perhaps I'm mistaken. I definitely would rather pass the mediaID as a GET param and skip writing each param I'll ever use in the .htaccess but that is not the way YouTube & Vimeo have gone, they seem to have found a scalable way to do it.
Why is their approach of pointing to the mediaID better than passing the url as a GET?  I take it their approach is good practice, perhaps I'm assuming to much.
What is the best way to accomplish a direct link to a media ID and retain the GET params in a scalable way.
Answer: If you want to retain the existing query string after your rewrite, just use the QSA flag on your rule:
RewriteRule ^([^/]*)$ index.php?var1=$1 [QSA,L]

Then, in addition to var1, you'll receive whichever parameters were passed in as part of the original request.


Onde colocar a anotação @Produces e @Consumes? No método ou na classe?

Question: Estive estudando o funcionamento de APIs REST em Java e me deparei com duas didáticas diferentes. Em uma delas o professor colocava as anotações na definição da classe, desta maneira:
<code>@Path("imoveis")
@Consumes(MediaType.APPLICATION_JSON + ";charset=utf-8")
@Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
public class .....
</code>
e em outra didática o professor colocava as anotações especificamente em cima de cada método, desta maneira:
<code>@GET
@Consumes(MediaType.APPLICATION_JSON + ";charset=utf-8")
@Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
public ......
</code>
Gostaria de saber qual a maneira mais correta de se declarar essas anotações, quais as vantagens e desvantagens de cada uma delas.
Answer: No exemplo que você mostrou, os dois vão acabar resultando na mesma configuração.
A diferença de adoção deve ser relacionada exclusivamente à sua necessidade.

Meu controller irá sempre consumir e retornar JSON

Neste caso não faz sentido você colocar as anotações em cada método (lembre-se sempre do DRY!)

Meu controller irá consumir e retornar múltiplos formatos

Nesta situação, você pode anotar os métodos, porque provavelmente você terá métodos específicos consumindo XML ou outro formato, métodos consumindo apenas JSON, e métodos consumindo vários formatos.

Hoje você não possui uma necessidade de retornar ou consumir vários/diferentes formatos, então faz sentido deixar apenas na classe. Amanhã caso você tenha XML como retorno e consumo (e a classe estiver anotada), você pode anotar apenas o método que irá tratar esta situação com XML e o resto da classe ainda irá tratar JSON (conforme anotado na classe).
De forma prática, o resultado é o mesmo, você deve considerar  a melhor estrutura do seu código e evitar repetições.
Complemento:
Conforme apontei no comentário para melhor entendimento, a idéia seria deixar as coisas comuns a maioria dos controladores nas anotações da classe, e então ir especializando nos métodos conforme a necessidade (devemos sempre considerar o DRY, deixando coisas comuns em apenas um lugar se possível)
Comment: No meu caso eu tinha alguns métodos que não consumiam nem retornavam dados, alguns métodos que apenas retornavam, e também tinha uns que consumiam e retornavam, por isso eu fiquei confuso.
Comment: @Eduardo Essa é a idéia mesmo, geralmente configurações que são mais utilizadas por todos os métodos costumam a ficar na classe, e os métodos especializam conforme a necessidade
Comment: aa sim, agora eu entendi.


Proving uniform convergence of this series

Question: I'm trying to prove that the following series
$$\sum_{n=1}^{\infty}(-1)^n \dfrac{x^2 + n}{n^2}$$
converges uniformly on every finite interval $I$ in $\mathbb{R}$.
In the previous exercice I've shown that the series is not absolute convergent for any $x \in \mathbb{R}$, so this might be of use, but I'm not sure how.
I've attempted to use the Weierstrass M-test and tried to find some $M_n \geq \dfrac{x^2 + n}{n^2} \; \forall x \in I$ such that $\sum M_n$ converges. But I realised that this would imply that $M_n \geq \frac{1}{n}$ and thus $\sum M_n$ cannot converge.
I also tried finding the partial sums for the series, but this also turned out to be pretty tough.
How would I go about showing uniform convergence on $I$?
Answer: First given $x \in \mathbb{R}$:
$$\sum_{n=1}^{\infty}(-1)^n \dfrac{x^2 + n}{n^2}=\sum_{n=1}^{\infty}(-1)^n \dfrac{x^2}{n^2}+\sum_{n=1}^{\infty}(-1)^n \dfrac{1}{n}$$
So if you prove $\sum_{n=1}^{\infty}(-1)^n \dfrac{x^2}{n^2}$ is absolutly convergent you are ready (since the second sum converges and is constant and not depends on $x$).
$x^2$ is bounded for every finite interval on $I$ by $M_I$:
$$\left|(-1)^n\frac{x^2}{n^2}\right|\leq \frac{M_I}{n^2} $$
So $\sum_{n=1}^{\infty}(-1)^n \dfrac{x^2}{n^2}$ is absolutly convergent.
Uniformity: pointwise $f_m(x)$ converges to:
$$f(x)=x^2 \sum_{n=1}^{\infty}(-1)^n \dfrac{1}{n^2}+\sum_{n=1}^{\infty}(-1)^n \dfrac{1}{n}$$
So:
$$|f(x)-f_m(x)|=$$
$$\left|x^2 \sum_{n=1}^{\infty}(-1)^n \dfrac{1}{n^2}+\sum_{n=1}^{\infty}(-1)^n \dfrac{1}{n}-x^2 \sum_{n=1}^{m}(-1)^n \dfrac{1}{n^2}-\sum_{n=1}^{m}(-1)^n \dfrac{1}{n}\right|$$
$$\leq\left|x^2 \sum_{n=1}^{\infty}(-1)^n \dfrac{1}{n^2}-x^2 \sum_{n=1}^{m}(-1)^n \dfrac{1}{n^2}\right|+\left|\sum_{n=1}^{\infty}(-1)^n \dfrac{1}{n}-\sum_{n=1}^{m}(-1)^n \dfrac{1}{n}\right|$$
$$\leq|x^2|\left| \sum_{n=1}^{\infty}(-1)^n \dfrac{1}{n^2}- \sum_{n=1}^{m}(-1)^n \dfrac{1}{n^2}\right|+\left|\sum_{n=1}^{\infty}(-1)^n \dfrac{1}{n}-\sum_{n=1}^{m}(-1)^n \dfrac{1}{n}\right|$$
$$\leq M_I\left| \sum_{n=1}^{\infty}(-1)^n \dfrac{1}{n^2}- \sum_{n=1}^{m}(-1)^n \dfrac{1}{n^2}\right|+\left|\sum_{n=1}^{\infty}(-1)^n \dfrac{1}{n}-\sum_{n=1}^{m}(-1)^n \dfrac{1}{n}\right|$$
At that point you can complete the demostration (because the convergence is not given by the point $x$ you take)
Answer: Let $M>0$ such that $I \subset [-M,M]$
Let $$\begin{array}{ccccc}
f & : & I & \to & \mathbb R \\
 & & x & \mapsto & \sum_{n=1}^{\infty}(-1)^n \dfrac{x^2 + n}{n^2} \\
\end{array}$$
For $m\in \mathbb N$, let  $$\begin{array}{ccccc}
f_m & : & I & \to & \mathbb R \\
 & & x & \mapsto & \sum_{n=1}^{m}(-1)^n \dfrac{x^2 + n}{n^2} \\
\end{array}$$
Now for $x \in I$, because the series is alternate,
$$|f(x)-f_m(x)|\leq \dfrac{x^2 + n+1}{(n+1)^2} \leq \dfrac{M^2 + n+1}{(n+1)^2}$$
Because $\frac{M^2 + n+1}{(n+1)^2} \to 0$ and is independent on $x$, uniform convergence is granted.


How to have full command on time in Laravel

Question: I have use carbon, but it's not working according to my needs.
What I want is to apply check on time in minutes, like after every 15 min check, to work and then minute reset to zero.
Like:
if(time > 15 ) {
  do this...
  reset to zero
} else {
  do this
}

Comment: why not you do that on your frontend probably using javascript?
Comment: Are you running a timer, or just checking to see if the minute is 0, 15, 30, or 45?
Answer: You need task schedule or command make:
The simple form is call your controller every15min, go to app/console/Kernel.php
protected function schedule(Schedule $schedule)
{
    $schedule->call('yourcontroller@youtfunction')->everyFifteenMinutes();
}

And you run this: php artisan schedule:run
You can make command, but this ius more complex
Here is oficial documentation: https://laravel.com/docs/7.x/scheduling
Comment: Can use sessions and apply condition like session expires and run my condition. But question is how to set condition on sessions as i am trying but still not working. Like config/session.php setting my lifetime and then on env but its not working. I think it will be helpful if someone let me know sessions help me out or not.


Lowest career WAR for a 2-time+ all-star?

Question: Of all MLB players who have made the all-star team at least twice, who has the lowest career WAR?
Is there a way to answer this question with baseball-reference or mlb savant? Or do you have to write some SQL?
Comment: Certainly possible with Stathead (baseball reference stats search), but requires an account nowadays to get useful results (they hide the first 10).  One batter has *negative* WAR who fits your criteria, amusingly (but they hide the result, so don't know who it is).
Answer: Worst hitters with at least two All-Star appearances

Rk
Player
AS
Career WAR
From
To

1
Hal Smith
2
1.9
1956
1965

2
Hal Wagner
2
2.5
1937
1949

3
Dave Ferriss
2
2.9
1945
1950

4
Blue Moon Odom
2
3.2
1964
1976

5
Jim Finigan
2
3.4
1954
1959

6
Harvey Haddix
3
3.4
1952
1965

7
Birdie Tebbetts
4
3.7
1936
1952

8
Rollie Hemsley
5
3.8
1928
1947

9
Don Mueller
2
4.2
1948
1959

10
Leo Durocher
3
4.3
1925
1945

Full list at: https://stathead.com/tiny/T6CHr
I'm assuming you don't want the pitcher's WAR for hitting included in this list. I excluded pitchers from the batting war by setting a requirement of 15% in any non-pitching position. Blue Moon Odom (a pitcher) still sneaks into this list, because he was frequently used a pinch runner. I didn't want to filter out any other legit hitters who were used as a pinch runner in their career.
Worst pitchers with at least two All-Star appearances

Rk
Player
Career WAR
IP
From
To

1
Gregory Soto
1.9
254.1
2019
2023

2
Blue Moon Odom
2.2
1509
1964
1976

3
Luis Arroyo
3.3
531.1
1955
1963

4
Mike Williams
3.6
768.1
1992
2003

5
Kazuhiro Sasaki
3.7
223.1
2000
2003

6
Joel Hanrahan
4.3
404.2
2007
2013

7
Chris Pérez
4.7
379.1
2008
2014

8
David Bednar
5.2
183.2
2019
2023

9
Al Javery
5.6
1142.2
1940
1946

10
Ryne Duren
5.7
589.1
1954
1965

I don't know why stathead is not including the All-Star appearance in their final table.
For the pitchers, I had to set a minimum innings pitched of 150 innings. Otherwise, you'd get guys like Jose Canseco in there who pitched a couple innnigs. Why 150 innings? There's a Yankee outfielder, Ben Chapman, who was a 3x All-Star in the 1930s. In his career he pitched 141 innings.
Full list at: https://stathead.com/tiny/jwARF
Comment: Cool list. Harvey Haddix from the first list is also a pitcher who did a lot of PR. Rollie Hemsley and Leo Durocher were even all stars in years where they had negative war.


Summing ordered samples

Question: Let's pick a random number between 0 and 1 uniformly 1000 times and put the results in an array for example : [0.176,0.765,0.879,0.234,0.152,0.765,0.645,0.897,0.762,0.087...] and sort this sample from smallest to largest.
Then repeat the experience n times and keep the n arrays. Finally make the sum of all the arrays and we have a big array for example : [3.7636,4.7362,8,87...].
Can someone help me and give me a mathematical explanation of why the CLT does not apply and why the distribution of the sum seems to be uniform between 0 and n and not normal the more n and the size of my samples increase ?
Here the histogram when I order my samples :

Histogram when I do not order my samples :

My python code :
import numpy as np
import matplotlib.pyplot as plt

sum1= np.asarray([0. for k in range(1000)])
for i in range(1000):
    sum1 = np.add(sum1, np.sort(np.asarray([np.random.random() for j in range (1000)])))

plt.hist(sum1,range(int(min(sum1)), int(max(sum1))))
plt.show()

Many thanks in advance !
Answer: The CLT makes a statement about what happens if you sum up many independent draws of one random variable: if you do this many times, the distribution of the sum will converge to normality.
What you are doing here is summing 1000 different variables. Each separate one is an order statistic from the uniform distribution, and each separate one has a different expectation: essentially, the $i$-th entry in each of your vectors of length 1000 has an expectation of about $\frac{i}{1000}$. And then, you are not repeating this experiment many times, but just a single time. The result is a single vector of length 1000, which is (almost, because of boundary issues) uniformly distributed.
Here is something where the CLT does give you what you expect. Do your experiment many times (I chose 200 replicates, and changed your 1000 to 100 to shorten runtimes), and in each case, only record the first entry of sum1. The result looks much more normal, and would look more so with more than 200 replicates:

first_entry = [0 for _ in range(200)]
for ii in range(len(first_entry)):
    sum1 = np.asarray([0. for k in range(100)])
    for i in range(100):
        sum1 = np.add(sum1, np.sort(np.asarray([np.random.random() for j in range(100)])))
    first_entry[ii] = sum1[0]
plt.hist(first_entry)
plt.show()

Comment: Thank you ! I understand now why the CLT doesn't work. But I precisely want a uniform distribution from a sum of samples from uniform distributions and I do not exactly understand why "the i-th entry in each of your vectors of length 1000 has an expectation of about i/1000" and why it also works with an exponential distribution etc
Many thanks in advance
Comment: Since you pick 1000 points from the uniform distribution *and then order them*, the $i$-th data point will be at around $\frac{i}{1000}$. What do you mean by "**it** works with an exponential distribution"? What are you referring to?
Comment: If i replace the uniform distribution by an exponential distribution the sum looks like an exponential distribution too
Comment: That is not surprising to me. If you sample from any distribution and then order, the ordered samples will have separate expectations that look like the original distribution. If you then sum or average entry-wise, you recover the original distribution. This should work with any distribution. What other distribution of the averages would you expect?
Comment: I don't know what I was expected, sorry, but I wanted to be sure that I was recovering the original distribution and not just something similar. I didn't find a lot of things about the sum of ordered samples on the internet, maybe I don't have the right keywords. Thanks for your time I can't vote up your answers since I'm a recent user but it was useful for a statistic beginner like me.
Comment: Don't think of it as *summing ordered samples*. Look at each entry separately, like I did for the first one. This is an *order statistic*, and you can find information about the distribution of order statistics, e.g., from the uniform distribution. And then, in a second step, you take sums or averages of such order statistics, which is where the CLT kicks in again.

Summing ordered samples


Should the 'f' be sustained or replayed in Rachmaninoff op. 43, variation XVIII (piano)?

Question: In Rachmaninoff's well known variation 18 of opus 43, Rhapsody on a Theme of Paganini, the first few measures of the piano part show an 'f' that's somehow repeated during the length of the first note:

How should this be played? Should the 'f' be replayed? Or should the 'f' remain sustained during the length of the first instance? Is this just to show the that conceptually it's all still triplets?
Answer: The F should be replayed, but in a way that shows it's in a different voice than the initial F. Here, most likely the second F would be played a bit more quietly than the first, since the first is attached to the melody, while the second is clearly accompaniment.
Answer: Yes, replay the F and pretend you didn't. :) This is only half kidding. You need to keep both voices in mind at the same time: the F that is part of the chord and the F that is part of the accompaniment.


What does the shifting of graded modules mean here?

Question:
For any graded module $M$ we denote $M(a)$ the module $M$ "shifted by $a$" so that $M(a)_d=M_{a+d}$. Thus for example the free $S$-module of rank $1$ generated by an element of degree $a$ is $S(-a)$.

Here $S=k[x_1,x_2,\dots,x_n]$, where $k$ is a field.
I don't understand the statement in bold font. We know that $S=M_0\oplus M_1\oplus\dots\oplus M_n$ where $M_d$ is the group of homogeneous polynomials of degree $d$. Hence $S(-a)=M_{-a}\oplus M_{-a+1}\oplus \dots\oplus M_{n-a}$
What does this even mean?
Answer: That's almost right.  But, note that
$$
S = \bigoplus_{d=0}^{\infty}M_d = M_0 \oplus M_1 \oplus \ldots
$$
not the finite direct sum that you wrote.
But the next thing you wrote is a little more wrong.  The point is that after shifting, the $d$ degree part of $S(-a)$ is whatever the $d-a$ graded part of $S$ is, ie. $M_{d-a}$ if $a\leq d$ or $0$ otherwise.   But don't forget, at this point, we're talking about $S(-a)$ as a module over $S$, not as a ring.  It IS in fact a ring, but we're thinking of it as the free module with generator in degree $a$ in this case.
Comment: Sorry, shouldn't it read "the $d$ degree part of $S(-a)$ is whatever the $d$ graded part of $S$ is"?
Comment: Also, is this module equal to $S$? I feel it should be a subset of $S$. Sorry this is an irrelevant question. I am just clarifying
Comment: Also, what does degree of an element mean here? Let us suppose an element $b$ has degree $a$. Does it mean $b$ is a monomial of degree $a$? Or does it mean $b^a=1$?
Comment: Hi Ayush.  Let's take this to chat.  The answer to your questions is all no, but will take longer than a comment to explain. http://chat.stackexchange.com/rooms/info/35119/discussion-between-ayush-and-callus?tab=general
Comment: Thanks! Sounds like a good idea. However, how do I take this conversation to chat?
Comment: Click on the link in my comment.  That should take you to the room


Is $\frac{1}{x}$ continuosly differentiable on the set $E = (- \infty, 0) \cup (0, \infty)$?

Question: Just to explain the motivation behind some other thing, I shall ask first this question:

Is $\frac{1}{x}$ continuosly differentiable (or we can examine
  $\frac{1}{x^3}$ also) on the set  $$E = (- \infty, 0) \cup (0,
> \infty)$$

The reason why I'm asking this is that when we consider a solution to a given initial value problem, we define the definition of interval of that solution as a single connected set (or just an interval), and the reason for this is explained to me as that we are trying to find solutions $y(x) \in C^1$, but when I discard the problematic points from my domain, why should I get any problem about the condition that $y \in C^1$ ?
Edit:
For example, let say that we solve an ODE, and the general solution is of the form
$$y(x) = c / x.$$
Then if the initial condition is given as $y(1) = 1$, we see that $c = 1$, and the domain of definition is $1 \in (0,\infty)$. However, I do not understand the motivation behind the reason why the interval of definition is not $(-\infty, 0) \cup (0, \infty)$ .
Comment: My answer address your edit exactly. The issue is uniqueness.
Comment: @symplectomorphic see my comments please.
Answer: Yes, $1/x$ and $1/x^3$ are continuously differentiable (in fact, infinitely differentiable) on your domain (the set of all nonzero reals).
The reason we typically assume that the domain of a solution to an IVP is connected is to ensure uniqueness. If you try to solve the IVP $f'(x)=-1/x^2$ with $f(1)=1$ on your domain, the solution isn't unique: the values of the function aren't determined in the left half-plane.
Comment: Yes, there is a general theorem: https://en.m.wikipedia.org/wiki/Picard–Lindelöf_theorem
Comment: The point is that the solution is only uniquely determined *locally*. The initial condition may not determine the solution *globally*, as in your example: knowing $f(1)=1$ is not enough to determine the values when $x<0$.
Comment: how does the connectedness related with the uniqueness ? I mean is there any theorem about this ?
Comment: I have only seen existance and uniqueness for the first order linear ODEs.
Comment: I see, thank for the answer.
Answer: The funciton $f(x)=\frac1x$ is an element of $C^1(\mathbb R\setminus\{0\})$.
To comment on your question about the initial value problems, I would need more information about what is unclear to you.
Comment: see my edit please.
Answer: Your notation is inadequate. The function is in $C^1(E)$. It is also in $C^1(U)$ for every interval $U\subset E$. You must specify the domain in this notation if it isn't implicit, especially when you are considering several of them.
In other words, $C^1$ without a specified domain is ambiguous.


Need to enable UITextField in row of UITableView when cell is selected in iOS

Question: I have created a custom cell that places a UITextField in each row of a UITableView.  What I would like to do is enable the UITextField for a particular row (i.e. activate the cursor in that textfield), when the user presses on anywhere inside the cell.
I have the following method where I try to do this:
- (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

     [_cell.textField setUserInteractionEnabled:TRUE];

}

However, this is not working.  Can anyone see what I'm doing wrong?
Answer: Try this code:
- (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

     [_cell.textField becomeFirstResponder];
}

Answer: You're on the right track placing this inside didSelectRowAtIndexPath:. However, setting user interaction enabled on the textfield just means that the user would be allowed to interact with the object if they tried. You're looking for becomeFirstResponder.
- (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
    [cell.textField becomeFirstResponder];
}

Comment: What if I have multiple text fields in a row and want to detect which one was closest to the user touch?
Answer: What is this _cell iVar? Are you setting it somewhere?
I think what you are trying to accomplish is this:
- (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

     UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
     [cell.textField becomeFirstResponder];
}

Notice that in this way you are getting the cell for the tapped indexPath.
And also, just for information, it's a pattern in objective-C to use booleans as YES or NO, instead of true or false.


How to estimate amplitude of a sinusoid from two samples

Question: Given a sinusoid $x(t)=A\cos(t+\theta)$, I can estimate the amplitude $A$ if I take two samples separated by $\frac{\pi}{2}$. If $X_1=x(0+\theta)$ and $X_2=x(\pi/2+\theta)$. Then, $A$ can be estimated from $X_1^2+X_2^2$.
However, I am taking samples separated by a different (but known) angle $\phi$. The samples are
$X_1=x(0+\theta)$
and
$X_2=x(\phi+\theta)$
Can I estimate $A$ from these two sample?
Answer: $$X_1=A\cos{\theta}$$
$$X_2=A\cos{(\theta+\phi)}=A\cos\theta cos\phi-A\sin{\theta}\sin{\phi}$$
Therefore:
$$X_2=X_1\cos{\phi}-A\sin{\phi}\sqrt{1-\frac{X_1^2}{A^2}}$$
$$\sqrt{A^2-X_1^2}=\frac{X_1\cos{\phi}-X_2}{\sin{\phi}}$$
$$A^2=X_1^2+\left(\frac{X_1\cos{\phi}-X_2}{\sin{\phi}}\right)^2$$


Ant run command with pipes

Question: I must to implement command : java -jar test.jar page.xml | mysql -u user -p base
in ant. So i Have tried with this task:
<java jar="test.jar" fork="true">
  <arg line="page.xml | mysql -u user -p base"/>
</java>

But i have got en exception with pipe - "|" :
 java.lang.IllegalArgumentException: Input already set; can't set to |

So, that's the problem:)
Answer: The pipe (|) can only be used in a shell script. You're passing it as an argument to the java process.
So you need to execute a shell script. You can do this by executing (say) bash -c and passing the above as a shell statement (albeit inline - you could write a separate script file but it seems a bit of an overhead here)
  <exec executable="bash">
    <arg value="-c"/>
    <arg line="java -jar test.jar page.xml | mysql -u user -p base"/>
  </exec>

Comment: Porblem was in , it should be
But now it writes: /usr/bin/java: /usr/bin/java: cannot execute binary file
Comment: wow, i just thought that it works, but not...
I have got:
No such file or directory
Comment: From what ? You may need to set your classpath (or similar - don't forget you're now spawning off a separate process)
Comment: Yeah,  doesn't work for me, but  does. Of course, I'm executing a binary other than java, but still using the pipe.
Answer: I don't know if this was ever resolved, but I was having a similar problem which I solved by using the following:
<exec executable="bash">
    <arg value="-c"/>
    <arg line='"java -jar test.jar page.xml | mysql -u user -p base"'/>
</exec>

Just thought I would share.
Answer: Another solution would be to wrap the java -jar test.jar page.xml | mysql -u user -p base into a separate script and call it with simple <exec> task.
Answer: When you run a java program from Ant, the input and out from the program are captured by the Ant runtime - you can't try and redirect them elsewhere using that pipe.
If you want to do that, you might have better luck with the exec task, although that might suffer from the same problem.
Answer: There you are actually running a java command.
You need to use Exec task http://ant.apache.org/manual/Tasks/exec.html but not sure if there also you can run piped commands or not. Give it a try.
Answer: Explaining why Amelie's answer is the correct solution:
The difference between Amelie's correct solution compared to Brain Agnew's solution is the subtle difference between them.  Brian had the second arg as a "value" while Amelie is using "line".
Here's why Amelie's is correct, per Apache Ant Documentation:

"value | a single command-line argument; can contain space characters."

"line | a space-delimited list of command-line arguments."

<exec executable="bash">
    <arg value="-c"/>
    <arg line='"java -jar test.jar page.xml | mysql -u user -p base"'/>
</exec>

Ant run command with pipes


Visual Studio 2015 Docker Integration wont attach for debuging

Question: I created a Default .net Core RC2 MVC app using VS 2015.  I added Docker Support so I could run and debug it in docker.
When I run the project it builds the docker container and starts it.  Running the command "docker ps" shows the container running with the correct ports mapped.  However I get the following error:
The target process exited without raising a CoreCLR started event.  Ensure that the target process is configured to use NETStandard [version ...] or newer.  This might be expected if the target process did not run.

Also trying to access the web page returns the following error:
[Fiddler] The connection to '10.0.75.2' failed.
Error: ConnectionRefused (0x274d).
System.Net.Sockets.SocketException No connection could be made because the target machine actively refused it 10.0.75.2:80
Answer: Turns out the problem is related to the docker for windows beta I am running.  By default it does not let you map volumes.
To enable open the docker for window settings:

And select Manage shared drives.
Select the C drive or drive you have the .Net code stored on and rebuild and deploy the project:


Is SCCM overkill for medium-sized organizations?

Question: I am an IT technician in a high school with around 1600 students 250 staff and 800+ client computers mostly running Windows 7. Our team is composed of three members. My boss seems content with a network that works (just about) not necessarily a productive well maintained network that is easy to run and maintain. I'm still fairly early on in my I.T. career so I'm not up to speed on all the different endpoint management solutions that are available.
I'm looking for a better way to manage clients (deploy software, track changes, inventory etc) I like the look of SCCM 2012's features but the case studies seem to be aimed at large multi-site infrastructural rather than a single mid sized site.
Is SCCM suitable for a mid sized single site or is it aimed at much larger corporations? How can I determine whether or not an endpoint management solution like SCCM is a good fit for our organization?
EDIT: Thanks for all the help I'll take a look at SCE and SCCM and get some proposals drawn up to take to my boss/deputy head
Comment: @dunxd Actually, Microsoft usually has pretty deep discounts for education.
Comment: You might want to look at System Center Essentials.  Although as an educational establishment, the full SCCM is probably not out of reach financially, the Essentials package, and documentation, may be more manageable.
Answer: Background:
I have been the primary administrator/user of a SCCM 2012 SP1 implementation in our organization which is composed of about 500 workstations (Windows 7) and 120 servers (Windows Server 2008 R2). I am also early on in my career and primarily have a background in and a passion for networking and Linux so Windows endpoint management is something new and slightly distasteful to me. I only have experience with SCCM 2012 so I can't speak to the older versions. Our organization is at the bottom of the economy of scale curve and our (more or less) successful implementation of SCCM is largely due the fact we are far enough ahead of our requirements that we can be proactive, a lot of standard duties are handled by other groups (Active Directory, Email, Networking, Security).

The Price of Features: Complexity
SCCM 2012 has alot of moving parts and when they break they break for reasons that are not always immediately obvious or intuitive. SCCM 2012 kind of acts like an overseer, managing and leveraging a bunch of existing underlying technologies through a single framework. This is not simple and it occasionally breaks. To get an idea of how many different underlying pieces are involved go look at the number of logfiles, I think at a rough count there are something like ~240 logfiles. Again, it is hard (at least my perspective) to overstate the complexity of SCCM (or really any endpoint management system).

Managing Endpoints Like a Boss
You know what is really annoying? Walking (or RDPing) to each individual machine to perform the same task over and over again. That's boring and a waste of time. If you really commit to using this tool it can be an incredible force-multipler. Here's the features that let you do that:

Software Updates - This is basically just WSUS on steroids. You get great reporting, granularity and compliance checking over the standard WSUS offerings. If you can do WSUS you can do Software Updates with SCCM.
Compliance Settings - I was about really excited to see this feature coming from the land of things like Puppet. Configuration Items are composed of a Setting to evaluate and then a Compliance Rule which determines whether or not to remediate it. As example, we pushed an organization-wide Application that removed one compression utility and replaced it with another. This had the unfortunate consequence of not correctly setting the file association for ZIP files. One Registry Key based Configuration Item later we had set the file association across the entire fleet. You can assess a pretty wide degree of Settings - Registry Keys/Values, Active Directory queries, WQL and SQL queries, and PowerShell scripts. Think of Compliance Settings like a very flexible, granular version of GPOs with revision control (finally) and reporting. The downside is that for anything even slightly complex you will be writing scripts and we still don't escape the difficulty of doing configuration management of an API oriented management model.
Applications - This is for deploying and managing 3rd party software. All of the logic is supposed to be contained in the "Application" - the detection logic (how do I know if $APPLICATION is installed), the requirement logic (does the client meet the prerequisites), in installation logic and the uninstallation logic. With properly built Applications this works really, really well for managing 3rd party software. The newer version is deployed, it automatically supersedes the older version, uninstalls it and then installs the newer version. As I mentioned above - we replaced one utility with another across our entire fleet overnight. You can take this model even further and use the "AppStore" functionality to let users install their own software that is outside of the base image. You will want to manage things like Adobe Flash, Acrobat/Reader and Java JRE since they are so often the target of malware but do not attempt to do this yourself. Just buy a subscription service that provides them through SCUP. The installation process for these products is such a moving target that it seems like every version does things differently (see here, here, here and here). At best I find that I can turn out a new Application of something like the Java JRE or Flash in about five hours. If you do Reader, Acrobat, Flash, and Java JRE you can expect 20 hours worth of work a month at a minimum. That's almost entire week of a FTE for packaging - save those hours and effort for in house or specialty applications. (Why Adobe and Oracle go to such depths to make my life harder, I have no idea.)
Reporting / Software Metering - Just about everything in Windows is either in WMI or in the Registry. The Registry is easy to reach into with Configuration Items and just about everything in WMI gets sucked up in the Inventory Cycle. You can then use the builtin or custom Reports to turn this into nice fancy Manager-Approved (TM) information. As an example, we have a custom report that get us the Serial Number of all our workstations, we send it to our Dell rep and we get back a list of machines whose warranty expires that quarter. Neat.
I mentioned user-centric Application installation from an "AppStore" earlier - so if users are installing Acrobat on their own how do you manage licenses? You can run a report at true up time to see who has the software in question and then look at Software Metering which will tell you how often that particular piece of software is used on a particular workstation. We're using this to roll-up each department's licenses for Acrobat into a single agreement so we can get a better per-license cost and then for extra measure remove it from workstations where it is rarely used.
Operating System Deployment - This is basically MDT, WAIK and DISM. The value add that SCCM gets you is Task Sequences and Build and Capture. You essentially automate the process of building your reference machine. To refresh your base image, you update your Task Sequence and re-run it. This greatly reduces the time it takes to build a new base image.

Right-sizing - Or How I Became an SCCM Administrator
All that stuff sounds good huh? Here's the problem. It's not simple to do. Our tier-1 guy spent almost six weeks figuring out the Build and Capture for base images. It took me at least a month to get a laundry list of break/fix issues resolved. I still can't manage to build, test and deploy Java JRE before a new version is released. Our DBA had to write our custom reports since I couldn't figure out SSRS. I find that I write a lot of PowerShell scripts to glue certain things together or to perform some kind of "logic". I still can't write WQL queries for application logic. After six months of spending almost all day, every day with SCCM, I feel like I'm just beginning to start getting over the learning curve. Our tier-1 and tier-2 folks end up pushing the majority of SCCM issues (which are really endpoint/desktop support stuff) to me since they don't (yet!) have the skill set to resolve them. By skill set - I mean, things like familiarity with WMI/WQL, WSUS, ProcMon, Windows Installer, PowerShell, and the Registry. To do things like the ZIP association file Configuration Item fix, you need to know that kind of configuration data is stored in the Registry and where to find it. If you make SCCM your organization's tool for managing endpoints you need to be prepared for 1) a lot of desktop support stuff to be handled by people further up the support chain since it requires such a diverse skill set, 2) a brutal learning curve for your tier-1 staff, 3) resistance and a tendency for staff to do stuff the "old school manual way" because it is "so much easier".

Is SCCM a good fit for your organization? Here's some questions to consider.

Are you in a reactive mode or a proactive mode?
How diverse is your staff's job duties already? Do they just do endpoint management or are you doing everything?
How deep and diverse is your staff's skill set?
Is there a desire and willing-ness to among your staff to climb that learning curve?
How diverse is your fleet and your end user's requirements?
Is senior staff willing handle desktop support issues and mentor your tier-1 and tier-2 folks until they become more comfortable with SCCM?
Will your management provide training (hint: If you have a Microsoft Premier contract, they have some great PFEs that can do on-site seminars).
Is your management willing to run interference for you, while you spend a week or two figuring out something the "SCCM-way" instead of just doing it the "old school manual way"?
Comment: @MDMoore313 - After we got our Premier contract settled we had a PFE do a four day tailored training that was awesome. The guys that really had/have a hard time are our Tier-1/Tier-2 folks. Doing things like installing software w/ SCCM versus manually going to each computer and installing requires a huge skill set change.
Comment: My heart goes out to you. I'm assuming it's not in the budget to get some sccm training? I got it before taking over desktop configuration management, and it actually helped. I did have experience with sql queries and the Windows GUI and of course scripting, but other than that I was an sccm noob. It was only a couple grand, just fyi.
Comment: I agree, it's both an art and a science.
Answer: I would not call 800+ computers "mid sized". I was successfully deploying the successor of SCCM in a bank with 850 employees. In your case it is a lot more likely nowt knowing your tools that will be the problem - somehow I have a problem imagining the team of 3 people in a school being the highly competent people that companies employ for a lot more money. The learning curve WILL be brutal for you.
But once you are over it, it will help a lot - the whole System Center suite. 800+ machines is WAY too big to run around to install stuff.
Comment: @TomTom What is the 'successor of SCCM'?
Comment: Agree, I'm an admin in a company that until recently was about 900 seats across two sites, and couldn't imagine doing it without SCCM. Using it well will save you a lot of time and effort, and you really aren't that small in SCCM terms. (We now have 35 sites in 20 countries, though only a couple hundred more users, and it really is invaluable).
Comment: I hear you, I would describe my skill set as average at best but at the same time I probably know more about correct systems administration and have a better insight that the 2 people I work with. I'm willing to learn everything I can about the software prior to deployment but I didn't want to spend hours reading SCCM guides and books only to work out it wasn't a suitable system. any advised further reading?
Comment: Documentation, pretty much - that is how  I get into pretty much everything. Set up a small virtual environment and play with it.
Answer: Forget you're a school and look at your numbers critically. You have 800 computers and nearly 2000 users. That's not a small company and I wouldn't really say "midsize" either. Schools IT is often neglected, but the truth is you should be using good quality enterprise hardware and software.
And, indeed, that includes SCCM. It's hard for any of us to say what will definitely work in your environment, but you could certainly pick worse places to start.
Of course, this is all easier said than done, but trust me when I say I've nearly every 'level' of educational IT.
There's very little that's truly overkill for a network of this size - plenty that are too expensive, though!
Answer: I'd use redo and backup, and wpkg, simple (with a bit of research and organization), and best of all it works. You can image a machine, and then WPKG will (surprise, surprise), install the software.
That's the system we used to use with 2000+ machines, over multiple campuses, until we were taken over by another college.
We use SCCM now. It's great in all respects except speed, reliability, simplicity, installing software, installing the os, reporting, and giving you accurate data.
Apart from that, it's ok.


Perspective Drawing Height at a Distance

Question: sorry if my formatting is a bit off, this is my first post using MathJax.
I am trying to render a perfectly vertical line in a 3d plane at a 10 meter distance from a camera, and am having trouble using my trig/calc knowledge to solve the diminishing height that can actually be seen for each meter of height added/stacked. In short, how tall will a 10m tall line appear in perspective when it is 10m away from the origin or camera. This is what I have so far:

In a 2D world, I have right triangle. The shape is 10m horizontal from the origin and then vertical rise from the right angle. Both the adjacent (horizontal) line and the opposite (vertical) are in meters, which I used to give me a hypotenuse. The hypotenuse is now the actual distance away the top of each segment of the line is from the viewer or perspective.

$$\sqrt{1(o)^2+10(a)^2} = 10.0499$$
$$\sqrt{2(o)^2+10(a)^2} = 10.1980$$
$$\sqrt{3(o)^2+10(a)^2} = 10.4403$$
$$\sqrt{4(o)^2+10(a)^2} = 10.7703$$
$$\sqrt{5(o)^2+10(a)^2} = 11.1803$$
$$\sqrt{10(o)^2+10(a)^2} = 14.1421$$

I then tried calculating the amount the line would need shrink to accommodate real world 3D perspective. I figured that, as the line is perfectly straight and vertical, it should shrink linearly. But, I could not figure out how to do this. I know that the base line is 10m, and the next hypotenuse us 10.4999m, for a 1 meter tall triangle. I tried reducing the line by the exact percent the hypotenuse changes: $$\frac{1(o)}{1+\frac{10.0499-10}{10}(\Delta{h})}$$ I also tried averaging, as half of the line in views behind the half way point, and half of it is in front of the half way point: $$\frac{1(o)}{1+\frac{\frac{10.0499+10}{2}-10}{10}(average\Delta{h})}$$ But then I got stuck. I though either of these may work, but, as the change in hypotenuse is not linear, it meant that the 1 meter lines were not going to decrease linearly in size.
As a side note, I will ultimately have precise vanishing point (x, y) locations, but, I feel as though these will only help me once I start troubling my way through 5 point perspectives, and know the exact size of display I will be using, like a camera, eyes, or monitor. I am trying to develop my own 3D game/video rendering engine, but want to figure out the math behind real world perspectives before attempting to code it.
I have a feeling that there is an actual formula for this out there somewhere, but I have searched and can not find it. When using excel, to 200m in the opposite, I get a curve and can calculate a polynomial trend line that almost fits with 6 orders, but it still does not fit as good as it should. I have also considered limits, but can not seem to remember how they work.

Do you have any suggestions, formulas or links to possible formulas or similar problems to figure out? The example would also work knocking my triangle on its side, still only seeing a line on the horizontal.
Thank you for any help!
Answer: As far as I know the height of the line should be inverse proportional to the distance ie. $h\approx 1/d$. Early 3D video games (e.g. Wolfenstein 3D) used this technique called raycasting (related but not to be confused with raytracing) to make a 2D world appear 3D, hence commonly called 2.5D. You may want to consult tutorials on raycasting like this one by Permadi.
Comment: I don't think there is a formula for this difference, which is easier than calculating it directly. Thinking of number of operations its hard to beat three (2 divisions one subtraction). And you have noticed that the relation between distance and height is not linear, so division by one constant won't help.
Comment: Thank you. h = 1/d is what I have, but but more simple. I was checking some functions: If an hypotenuse of an object rising doubles, does its size halve, and it does. I only thought this worked moving straight from the eye. I think that I way over complicated it. However, I still have a complication: if I add a meter, hypot changes from 10.0499 to 10.1980. The difference is 0.1481. If I want to calculate the difference in height between the top of the first and second meter, how could I do this without calculating each and subtracting? Because dividing by a decimal below 1 doesn't work.


24 hour expiration of first password

Question: EDIT**
I'm thinking of running a scheduled task at the end of every workday to retrieve all accounts who have never logged on and disabling their accounts.
Please excuse any syntax errors. I may very well be fumbling here. Can anyone say if this solution will work?
get-aduser -f {-not ( lastlogontimestamp -like "*")} | Disable-ADAccount

Original Question **
I'm not a sysadmin persay, I'm more of a programmer, and new to active directory and powershell scripting. I've done scripting in bash and other languages so I can catch on quickly.
My current role(I'm new) has an industry standard to expire/ disable accounts if the first use password has not been utilized within 24 hours. I have done a search and found that AD does not support this feature, but learned that it may be possible through a script. There is a tight deadline from an audit and I must say we are a little desperate.
Any help would be appreciated, even just a background on possible ways to set the expiration time or identify accounts who have not changed the password yet.
Thank you very much
Comment: If you have a legal requirement to do that with a tight deadline, why aren't you hiring an external consultant to help you with that?
Comment: I wouldn't say its a 'legal' requirement, but an industry requirement. that said, it holds weight. We're not hiring an external consultant most likely for budget purposes and because of the industry we are in, which is high security, bringing an external consultant on would be cumbersome. Additional contracts, privacy agreements, bringing them up to speed, along with getting it approved through corporate would be an enormous hassle. It would be faster if I could implement it myself. That said, I don't make the rules, unfortunately. I understand your logic.
Answer: You can check the following properties to find whether or not the user account has logged in or changed password.
LastLogonDate
PasswordLastSet
get-aduser -identity ACCOUNTNAME -properties LastLogonDate,PasswordLastSet

Answer: Yes, your one-liner should work. I modified your original command to filter for enabled accounts only.
Get-ADuser -f {-not ( lastlogontimestamp -like "*") -and (enabled -eq $true)} | Disable-ADAccount

Comment: Oh, and if you aren't sure of the implications of that command, add a `-Whatif` to the end (after Disable-ADAccount)
Answer: Active Directory doesn't have a way to set the password expiry on individual accounts. When it goes to expire passwords, it checks the account's Pwd-Last-Set attribute against the global Max-Pwd-Age setting.
If you're using some sort of scripted process to create user accounts, I would do the following:

Alter user creation script to append to a list of usernames and Pwd-Last-Set timestamps.
Create a scheduled task which iterates along the list. If the Pwd-Last-Set timestamp on the account is the same as in the file (i.e. they have not changed passwords) and the timestamp in the file is older than 24 hours, set the Pwd-Last-Set attribute on the account to 0 and unset the don't expire flag if needed. This will immediately expire the password.
Comment: For simplicity's sake, Is there a way to simply check if the password has never been changed? That way, I could run a scheduled task at the end of the day disabling any account with this property?
Answer:
For simplicity's sake, Is there a way to simply check if the password has never been changed? That way, I could run a scheduled task at the end of the day disabling any account with this property? –  Jacksgrin

I see this question is quite old, however, comparing the values of the Created or CreatedTimeStamp properties, along with the PasswordLastSet property should be a start.
get-aduser -identity [accountname] -properties Created,CreatedTimeStamp,PasswordLastSet,LastLogonDate
This should show you if the account password was ever changed since the account's inception.
FYI, I'm unable to comment or I would have replied to his comment.

24 hour expiration of first password


Why the weight vector is a linear combination of the inputs and the outputs in the Perceptron

Question: I was studying Support Vector Machines and I've got stuck with this relation regarding the weight vector of the hyperplane.
$w=\sum\limits_{i\in I}^{} y_i x_i$
For reference, I'm studying from the Alex Smola slides and this relation is not justified.
Comment: can you tell the page please? I wonder where lagrange multipliers are.
Comment: @gunes https://alex.smola.org/teaching/cmu2013-10-701/slides/4_Perceptron.pdf slide 10/56
Answer: That particular slide is about Perceptron algorithm, where initially $w$ is $0$ and you update it for each misclassified sample with the following update rule (there are slightly changed versions of this, but sticking with the slides):
$$w\leftarrow w+y_ix_i$$
Because we start from $0$ and every update made is in terms of $y_ix_i$, the final version of the weights will be a linear combination of the input samples, i.e. something like $$w=\sum m_i y_i x_i$$
where $m_i$ is the number of times in the learning loop we updated for sample $i$. The concept of linear combination is correct, but the equation provided is wrong. If it were, we could have solved for $w$ directly, without the need of iterating until convergence: $$w=\sum y_i x_i=\sum_{y_i=1} x_i-\sum_{y_i=-1} x_i$$


How do you organise your MVC controller tests?

Question: I'm looking for tidy suggestions on how people organise their controller tests.
For example, take the "add" functionality of my "Address" controller,
[AcceptVerbs(HttpVerbs.Get)]
public ActionResult Add()
{
    var editAddress = new DTOEditAddress();
    editAddress.Address = new Address();
    editAddress.Countries = countryService.GetCountries();

    return View("Add", editAddress);
}

[RequireRole(Role = Role.Write)]
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Add(FormCollection form)
{
    // save code here
}

I might have a fixture called "when_adding_an_address", however there are two actions i need to test under this title...
I don't want to call both actions in my Act() method in my fixture, so I divide the fixture in half, but then how do I name it?
"When_adding_an_address_GET" and "When_adding_an_address_POST"?
things just seems to be getting messy, quickly.
Also, how do you deal with stateless/setupless assertions for controllers, and how do you arrange these wrt the above? for example:
[Test]
public void the_requesting_user_must_have_write_permissions_to_POST()
{
    Assert.IsTrue(this.SubjectUnderTest.ActionIsProtectedByRole(c => c.Add(null), Role.Write));
}

This is custom code i know, but you should get the idea, it simply checks that a filter attribute is present on the method. The point is it doesnt require any Arrange() or Act().
Any tips welcome!
Thanks
Answer: In my opinion you should forget about naming your tests after the methods you're testing. In fact testing a single method is a strange concept. You should be testing a single thing a client will do with your code. So for example if you can hit add with a POST and a GET you should write two tests like you suggested. If you want to see what happens in a certain exceptional case you should write another test.
I usually pick names that tell a maintainer what he needs to know in Java:
@Test public void shouldRedirectToGetWhenPostingToAdd(){
    //...
}

You can do this in any language and pick any *DD naming convention if you like, but the point is that the test name should convey the expectations and the scenario. You will get very small test this way and I consider this a good thing.
Answer: Here's what I do now:
/tests/controllers/address/add/get.cs
/tests/controllers/address/add/valid.cs
/tests/controllers/address/add/invalid.cs