Why does my applet blink when i repaint using multiple threads?

Question: Summary: I'm currently doing an applet laboratory exercise that simulates a taxi cab, it has to have a display of the speed, fuel, fare and distance traveled, also a marquee whether the cab is occupied or vacant. it has buttons that gives interaction to the user.
Problem: I used a thread for the fare, distance and fuel and another thread for the marquee, but why is it that my marquee blinks continuously?
Answer: Without code, it's really anyone's guess, but regardless I'll take a stab. My guess is that you're drawing directly in the JApplet's paint(...) method and thereby losing all possible gain from Swing's double buffering. If so, then change this and draw in the paintComponent(...) method of a JPanel that the JApplet is displaying.
If this doesn't help, then consider giving us enough information so that we don't have to guess.  You may want to fill us in on how you're doing your threading and assure us that you're careful to obey Swing threading rules and update Swing components on the event thread only.
Edit
Your code:
import java.awt.*;
import java.awt.event.ActionEvent;
import javax.swing.JApplet;
import javax.swing.*;
import java.awt.event.ActionListener;
import java.io.*;
import javax.swing.border.Border;
/**
 *
 * @author IC
 */
public class taxiCab extends JApplet implements ActionListener {
    private JTextField speed, distance, fare, fuel, ov, full, tf, tf_fuel, tf_speed;
    private JButton butt, start, butt_pass, butt_sUp, butt_sDown, butt_refuel;
    private JLabel label;
    private JPanel main, north, south, south_left, south_right, center, center_content, north_speed, north_distance, north_fuel, north_fare;
    private Container contain;
    private int speedVal, distanceVal, passval, thread_sleep, status_width, fuel_width;
    private float fuelVal, fareVal;
    private Graphics g;
    private String status;
    private Font font2 = new Font("Kozuka Gothic Pro B", Font.BOLD, 60);
    private Border border2 = BorderFactory.createLineBorder(Color.black, 3);
    private Border border1 = BorderFactory.createLineBorder(Color.black, 1);
    private final int width_ = 500;
    private final int height_ = 300;
    Thread thread1 = new trd1();
    Thread thread2 = new trd2();
    /**
     * Initialization method that will be called after the applet is loaded into
     * the browser.
     */
    public void init() {
        setSize(width_,height_);
        status = new String();
        status = "VACANT";
        status_width = -330;
        Border border3 = BorderFactory.createLineBorder(Color.black, 5);
                thread1 = new trd1();
                thread2.start();
                thread2.suspend();
        contain = new Container();
        contain = getContentPane();
        main = new JPanel(new BorderLayout());
            north = new JPanel(new GridLayout(2,2));
            north.setBackground(Color.blue);
                north_speed = new JPanel();
                    tf_speed = new JTextField(10);
                    tf_speed.setBorder(border1);
                    tf_speed.setText("Speed");
                    tf_speed.setHorizontalAlignment(JTextField.CENTER);
                    tf_speed.setBackground(Color.CYAN);
                    tf_speed.setEditable(false);
                    speed = new JTextField(10);
                    speed.setBorder(border1);
                    speed.setEditable(false);
                    speed.setText("-");
                    speed.setHorizontalAlignment(JTextField.CENTER);
                    north_speed.add(tf_speed);
                    north_speed.add(speed);
                north_distance = new JPanel();
                    tf = new JTextField(10);
                    tf.setBorder(border1);
                    tf.setText("Distance");
                    tf.setHorizontalAlignment(JTextField.CENTER);
                    tf.setBackground(Color.CYAN);
                    tf.setEditable(false);
                    distance = new JTextField(10);
                    distance.setBorder(border1);
                    distance.setEditable(false);
                    distance.setText("-");//<----------------------------------distance
                    distance.setHorizontalAlignment(JTextField.CENTER);
                    north_distance.add(tf);
                    north_distance.add(distance);
                north_fuel = new JPanel();
                    tf_fuel = new JTextField(10);
                    tf_fuel.setBorder(border1);
                    tf_fuel.setText("Fuel");
                    tf_fuel.setHorizontalAlignment(JTextField.CENTER);
                    tf_fuel.setBackground(Color.CYAN);
                    tf_fuel.setEditable(false);
                    fuel = new JTextField(10);
                    fuel.setBorder(border1);
                    fuel.setEditable(false);
                    fuel.setText("-");
                    fuel.setHorizontalAlignment(JTextField.CENTER);
                    north_fuel.add(tf_fuel);
                    north_fuel.add(fuel);
                north_fare = new JPanel();
                    tf = new JTextField(10);
                    tf.setBorder(border1);
                    tf.setText("Fare");
                    tf.setHorizontalAlignment(JTextField.CENTER);
                    tf.setBackground(Color.CYAN);
                    tf.setEditable(false);
                    fare = new JTextField(10);
                    fare.setBorder(border1);
                    fare.setEditable(false);
                    fare.setText("-");
                    fare.setHorizontalAlignment(JTextField.CENTER);
                    north_fare.add(tf);
                    north_fare.add(fare);
                north.add(north_speed);
                north.add(north_distance);
                north.add(north_fuel);
                north.add(north_fare);
            center = new JPanel(new BorderLayout(3,3));
                center_content = new JPanel(new GridLayout(2,1,0,15));
                    ov = new JTextField(20);
                    ov.setText("");
                    ov.setBackground(Color.yellow);
                    ov.setEditable(false);
                    ov.setBorder(border2);
                    full = new JTextField(20);
                    full.setHorizontalAlignment(JTextField.CENTER);
                    full.setText("FUELMeter");
                    full.setIgnoreRepaint(true);
                    full.setFont(font2);
                    full.setBorder(border2);
                    center_content.add(ov);
                    center_content.add(full);
                center.add(center_content, "Center");
                center_content.setBackground(Color.yellow);
                label = new JLabel("   ");
                center.add(label, "North");
                label = new JLabel("   ");
                center.add(label, "West");
                label = new JLabel("   ");
                center.add(label, "South");
                label = new JLabel("   ");
                center.add(label, "East");
            south = new JPanel(new BorderLayout());
                south_left = new JPanel(new GridLayout(2,1));
                    butt_sUp = new JButton("Speed Up");
                    butt_sUp.setBorder(border1);
                    butt_sUp.addActionListener(this);
                    butt_sUp.setEnabled(false);
                    south_left.add(butt_sUp);
                    butt_sDown = new JButton("Speed Down");
                    butt_sDown.setBorder(border1);
                    butt_sDown.addActionListener(this);
                    butt_sDown.setEnabled(false);
                    south_left.add(butt_sDown);
                south_right = new JPanel(new GridLayout(2,1));
                    butt_pass = new JButton("Passenger In");
                    butt_pass.setBorder(border1);
                    butt_pass.addActionListener(this);
                    butt_pass.setEnabled(false);
                    south_right.add(butt_pass);
                    butt_refuel = new JButton("Refuel");
                    butt_refuel.setBorder(border1);
                    butt_refuel.addActionListener(this);
                    butt_refuel.setEnabled(false);
                    south_right.add(butt_refuel);
                butt = new JButton("Start");
                butt.setBorder(border1);
                    butt.addActionListener(this);
                south.add(butt, "Center");
                south.add(south_left, "West");
                south.add(south_right, "East");
        north.setBorder(border1);
        center.setBorder(border1);
        south.setBorder(border1);
        center.setBackground(Color.yellow);
        main.add(north, "North");
        main.add(center, "Center");
        main.add(south, "South");
        main.setBorder(border1);
        //main.setIgnoreRepaint(true);
        contain.add(main);
        contain.setVisible(true);
        //contain.setIgnoreRepaint(true);

    }
    public void paint(Graphics g){
        super.paint(g);
        g.setColor(Color.black);
        g.setFont(font2);
        g.drawString(status, status_width, 140);
        g.setColor(Color.yellow);
        g.fillRect(2,82,12,70);
        g.fillRect(getWidth()-14,82,12,70);
        g.setColor(Color.black);
        g.fillRect(0,82,2,70);
        g.setColor(Color.GREEN);
        g.fillRect(17,(getHeight()/2)+20,fuel_width,getHeight()-(83+(getHeight()/2)));
        main.setBorder(border1);
    }

    public void actionPerformed(ActionEvent e) {
        if(e.getActionCommand() == "Start"){
            butt.setLabel("Stop");
            butt_pass.setEnabled(true);
            fuelVal =  50.00f;
            distanceVal = 0;
            fareVal = 40.00f;
            speedVal = 0;
            fuel.setText(String.valueOf(fuelVal) + " L");
            distance.setText(String.valueOf(distanceVal) + " km");
            fare.setText("Php " + String.valueOf(fareVal));
            speed.setText(String.valueOf(speedVal) + " kph");
                thread1 = new trd1();
                thread1.start();
                thread2 = new trd2();
                thread2.start();
            //BufferedWriter bw;<-----------------------------------------------
            }
        else if(e.getActionCommand() == "Stop"){
            butt.setLabel("Start");
            butt_pass.setEnabled(false);
            butt_sUp.setEnabled(false);
            butt_sDown.setEnabled(false);
            butt_refuel.setEnabled(false);
            butt_pass.setLabel("Passenger In");

            thread1.stop();
        }
        else if(e.getActionCommand() == "Speed Up"){
            if(speedVal == 0){
                speedVal+=25;
                speed.setText(String.valueOf(speedVal) + " kph");
                butt_sDown.setEnabled(true);
                tf_speed.setText("Speed");
                thread1 = new trd1();
                thread1.start();
            }
            else if(speedVal == 275){
                speedVal+=25;
                speed.setText(String.valueOf(speedVal) + " kph");
                //butt_sUp.setEnabled(false);
                tf_speed.setText("MAX SPEED");
            }
            else{
                speedVal+=25;
                speed.setText(String.valueOf(speedVal) + " kph");
                }
        }
        else if(e.getActionCommand() == "Speed Down"){
            repaint();
            if(speedVal==25){
                speedVal-=25;
                speed.setText(String.valueOf(speedVal) + " kph");
                tf_speed.setText("S T O P P E D");
                butt_sDown.setEnabled(false);
            }
            else if(speedVal == 300){
                speedVal-=25;
                speed.setText(String.valueOf(speedVal) + " kph");
                tf_speed.setText("Speed");
                butt_sUp.setEnabled(true);
            }
            else{
                speedVal-=25;
                speed.setText(String.valueOf(speedVal) + " kph");
            }
        }
        else if(e.getActionCommand() == "Passenger In"){
            butt_pass.setLabel("Passenger Out");
            fareVal = 40.0f;
            fare.setText("Php " + String.valueOf(fareVal));
            butt_sUp.setEnabled(true);
            butt_sDown.setEnabled(true);
            butt_refuel.setEnabled(true);
            speedVal = 25;
            speed.setText(String.valueOf(speedVal) + " kph");
            status = "OCCUPIED";
                thread1 = new trd1();
                thread1.start();

        }
        else if(e.getActionCommand() == "Passenger Out"){
            status = "VACANT";
            butt_pass.setLabel("Passenger In");
            thread1.stop();
        }
        else if(e.getActionCommand() == "Refuel"){
            if(fuelVal == 0.0f){
                fuelVal = 50.00f;
                fuel.setText(String.valueOf(fuelVal));
                tf_fuel.setBackground(Color.cyan);
                tf_fuel.setText("Fuel");
                        fuel_width = (int)((getWidth()-34)*fuelVal/50f);
                thread1 = new trd1();
                thread1.start();
            }
            else{
                fuelVal = 50.00f;
                fuel.setText(String.valueOf(fuelVal) + " L");
            }
        }
    }

    public class trd1 extends Thread implements Runnable {

        public void run(){
            if(fuelVal>0.00f || speedVal>0){
                for(;;){
                    try {
                        Thread.sleep(50000/speedVal);
                        if(fuelVal == 0.00f || speedVal == 0)
                            thread1.stop();
                        distanceVal++;
                        fareVal += 1.00;
                        fuelVal -=.25f;
                        fuel_width = (int)((getWidth()-34)*fuelVal/50f);
                        repaint();
                        distance.setText(String.valueOf(distanceVal)+" km");
                        fuel.setText(String.valueOf(fuelVal)+" L");
                        fare.setText("P " + String.valueOf(fareVal));
                    } catch (InterruptedException e) {
                    }
                }
            }
            }
        }
    public class trd2 extends Thread implements Runnable {
        //tf_fuel = new JTextField(15);

        public void run(){
                for(int b = 0;;b++){
                    try {
                        Thread.sleep(10);
                        status_width +=1;
                        if(status_width == getWidth())
                            status_width = -330;
                        repaint();
                        if(fuelVal == 0.0f){
                            if(b%2==0){
                                tf_fuel.setBackground(Color.red);
                                tf_fuel.setText("R E F U E L");
                                }
                            else{
                                tf_fuel.setBackground(Color.cyan);
                                tf_fuel.setText("R E F U E L");
                                }
                        }
                    } catch (InterruptedException e) {
                    }
                }

        }
    }
}

Yep, I guessed correctly: you're painting directly in the JApplet. As I stated initially, don't do that. In fact your best bet at learning to do this correctly is to read the tutorials:

Lesson: Performing Custom Painting (the basics)
Painting in AWT and Swing (for more advanced concepts)

You've also got a lot of other errors in your code, some significant, including using == to compare Strings rather than the equals(...) or equalsIgnoreCase(...) method, and trying to call Thread#stop() directly. Never do that. Also don't set a component's border within paint or paintComponent. Also you are setting a component's text and background color from within a background thread and off of the Swing event thread -- two potential causes of intermittent and hard to debug threading errors. You'll only want to do these things on the Swing event thread.
Comment: @cjBucketHead: good lord no -- ***never*** use those methods. A reading of the [Thread API](http://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html) will tell you why they are very dangerous to use.
Comment: the code is kind of messy at the moment, wait, i'll just select the ones that are possible to cause the problem. btw, i'm still at experimenting phase because the semester just started, is it all right for me to use depreciated methods like Thread.suspend() or Thread.resume()?
Comment: the lines "contain = new Container(); contain = getContentPane();" are doing nothing.  You can get rid of the first line


If I respawn a boss and kill him with Lucatiel again, does that count towards the 3 bossfight requirement to prevent her from disappearing?

Question: I've killed the Lost Sinner with Lucatiel more than 3 times by respawning with a bonfire ascetic.   Have I met the requirement to prevent Lucatiel of Mirrahh from disappearing after Aldia's Keep?
Answer: Yep - any boss kills in a single playthrough (ascetic or not) will count.
Comment: This counts for Benhart as well.


how to display an entire table as a "legend" on the access form

Question: I have an invoice form which pulls in multiple interrelated tables.  But separately from that, I want to display a "legend" at the bottom of the invoice.  The legend is contents of a separate table, but its not really related to anything on the form.  It is simply some "verbiage" the source for which originates out of a access table.
Answer: Insert a subform, bound to that separate table, in the form footer.
You may even get away with, in design view, to simply drag the table and drop it in the form footer.
Comment: I have tried that -- so what I get is a vertical table of codes and descriptions. Is it possible to get rid of headings? Is it possible to make data "flow" into 3 columns that occupy the entire width of the form?  It about 30 entries -- I cant simply display it vertically -- it needs to display lets say 3 columns, 10 entries each.  Thank you
Comment: Yes, that should be possible. Design a custom form using as source a custom query that concatenate rows and/or fields as you prefer. Bing/Google on that.


Using output parameter from SQL Server stored procedure in Access

Question: I am attempting to get an output variable (the new identity column) from a stored procedure in SQL Server 2008 after executing the procedure from Access 2013 VBA. I don't fully understand all the adodb stuff, and I've tried a number of things from different articles to no avail. Here's where I am with it now...
Stored procedure:
PROCEDURE [proc_NewClient]
    @Type INT,
    @PhoneIntakeID INT,
    @ClientID INT = NULL,
    @NewPSID INT = null OUTPUT (2 possible ways to call the proc, one does not produce an output variable)

   INSERT INTO tblClientDetails (ClientID, PhoneIntakeID, Client_Status)
   VALUES (@ClientID, @PhoneIntakeID, 'Applicant')

   DECLARE @NewClientDetailID int
   SELECT @NewClientDetailID = SCOPE_IDENTITY()

   INSERT INTO tblPS_Psychosocial (ClientDetailID, Client)
   VALUES (@NewClientDetailID, @ClientID)

   SELECT @NewPSID = SCOPE_IDENTITY()

   INSERT INTO tblPS_AbuseHistory (PsychosocialID)
   VALUES (@NewPSID)

   INSERT INTO tblPS_FamilyHistory(PsychosocialID) VALUES (@NewPSID)
   INSERT INTO tblPS_FinancialHistory (PsychosocialID) VALUES (@NewPSID)
   INSERT INTO tblPS_LegalHistory (PsychosocialID) VALUES (@NewPSID)
   INSERT INTO tblPS_MedicalHistory (PsychosocialID) VALUES (@NewPSID)
   INSERT INTO tblPS_PsychiatricHistory (PsychosocialID) VALUES (@NewPSID)
   INSERT INTO tblPS_SocialHistory (PsychosocialID)  VALUES (@NewPSID)
   INSERT INTO tblPS_SpiritualHistory (PsychosocialID) VALUES (@NewPSID)
   INSERT INTO tblPS_SubstanceHistory (PsychosocialID) VALUES (@NewPSID)

   INSERT INTO tblVocAssessment(ClientDetailID) VALUES (@NewClientDetailID)

And from the form I've got:
    Dim cnn As ADODB.Connection
            Dim cmd As New ADODB.Command, rs As New ADODB.Recordset, param1 As New ADODB.Parameter, param2 As New ADODB.Parameter, param3 As New ADODB.Parameter, param4 As New ADODB.Parameter
            Set cnn = New ADODB.Connection
            cnn.ConnectionString = "DRIVER=SQL Server;SERVER=SRV-DB01;DATABASE=TWHClientMgmt;Trusted_Connection=Yes"

            cnn.Open cnn.ConnectionString

            Set cmd = New ADODB.Command
            cmd.ActiveConnection = cnn
            cmd.CommandType = adCmdStoredProc
            cmd.CommandText = "[THEWOMENSHOME\jboyd].proc_NewClient"

            Set param1 = cmd.CreateParameter("@Type", adinteger, adparamInput, , 2)
            cmd.Parameters.Append param1
            Set param2 = cmd.CreateParameter("@PhoneIntakeID", adinteger, adparamInput, , Me.PhoneIntakeID)
            cmd.Parameters.Append param2
            Set param3 = cmd.CreateParameter("@ClientID", adinteger, adparamInput, , intNewID)
            cmd.Parameters.Append param3
            Set param4 = cmd.CreateParameter("@NewPSID", adinteger, adParamOutput)
            cmd.Parameters.Append param4

rs.open cmd

To this point the code works, the new records are generated, etc. When I run the stored procedure from SQL Server it returns the correct identity column number, but I've tried multiple ways to reference the output in VBA and always end up coming up with a null. How do I reference it here correctly?
Comment: Instead of `rs.Open` try `cmd.Execute` and then see if you can retrieve the value of the output parameter with `cmd.Parameters("@NewPSID").Value`.
Comment: You can also make SP returning recordset with one row/one column with new ID data and read this data using select clause in pass-through query
Comment: The trade-off in using a stored procedure that returns a result set and invoking it with a pass-through query is that pass-through queries cannot be *parameterized*, so you have to use *dynamic SQL* to "glue together" the EXEC statement each time. Therefore you need to escape ("sanitize") all of the inputs, quote them properly (including `''` or `N''`, depending on the type of string), and so on.
Comment: Yes, just use procedure with select at the end, in VBA code use regular OpenRecordset for querydef. Set the qurydef `sql` propery to `select   or pass-through query name first. And yes, you cannot parametryze such kind queries.
Comment: @GordThompson  thank you! I had tried that combination but WITHOUT the .value on the parameter, that was the ticket!! It works perfectly now!
Comment: @SergeyS. How would I script a passthrough query like that, that both executes the insert and returns the value? Would I just execute it with ReturnsRecords set to true, all the parameters supplied, and end the stored procedure with a select? How would you reference the value in vba? It seems like if that works it would be a much simpler solution than what I've been doing.
Answer: To retrieve the value of a stored procedure's OUTPUT parameter you simply .Execute the ADODB.Command and then retrieve the .Value of the corresponding ADODB.Parameter, like so:
cmd.Execute
' retrieve and display the returned OUTPUT parameter value
Debug.Print cmd.Parameters("@NewPSID").Value

Comment: It is possible to retrieve output parameter in `.CommandType = adCmdText` mode ?
Comment: After `Rs = cmd.Execute()` You can also use this to return output parameter value
`Debug.Print param4`
Answer: Simple DAO solution calling stored procedure:
Public Function RunSqlQuery(q As String) As Variant

Dim cdb As DAO.Database
Dim qdf As DAO.QueryDef
Dim rs As Recordset

Set cdb = CurrentDb
Set qdf = cdb.CreateQueryDef("")
qdf.Connect = cdb.TableDefs("dbo_Setup").Connect  ' your attached table
qdf.SQL = q
qdf.ReturnsRecords = True
Set rs = qdf.OpenRecordset()
RunSqlQuery = rs.Fields(0)  ' you also can output more than one parameter from a stored procedure as fields
rs.Close
Set rs = Nothing
Set qdf = Nothing
Set cdb = Nothing

End Function

Now, call the function, define a query the same way you would do at the SQL server:
? RunSQLQuery("DECLARE @param1 varchar(16);   exec proc_MyStoredProcedure @param1 OUTPUT;  SELECT @param1")


Getting a ray for raypicking in openGL ES

Question: OK, so I used this code for a ray for opengl ES but I'm getting an error with the
this.P0 = farCoOrds;
this.P1 = nearCoOrds;

at the very end of the code. It says,

Cannot Resolve Symbol

Here is the code:
public class Ray {
    public static float[] P0 = new float[3];
    public static float [] P1 = new float[3];
    public Ray(GL10 gl, int width, int height, float xTouch, float yTouch) {
        MatrixGrabber matrixGrabber = new MatrixGrabber();
        matrixGrabber.getCurrentState(gl);

        int[] viewport = {0, 0, width, height};

        float[] nearCoOrds = new float[3];
        float[] farCoOrds = new float[3];
        float[] temp = new float[4];
        float[] temp2 = new float[4];
        // get the near and far ords for the click
        float winx = xTouch, winy =(float)viewport[3] - yTouch;
    //        Log.d(TAG, "modelView is =" + Arrays.toString(matrixGrabber.mModelView));
    //        Log.d(TAG, "projection view is =" + Arrays.toString( matrixGrabber.mProjection ));

        int result = GLU.gluUnProject(winx, winy, 1.0f, matrixGrabber.mModelView, 0,
    matrixGrabber.mProjection, 0, viewport, 0, temp, 0);

        Matrix.multiplyMV(temp2, 0, matrixGrabber.mModelView, 0, temp, 0);
        if(result == GL10.GL_TRUE){
            nearCoOrds[0] = temp2[0] / temp2[3];
            nearCoOrds[1] = temp2[1] / temp2[3];
            nearCoOrds[2] = temp2[2] / temp2[3];

        }

        result = GLU.gluUnProject(winx, winy, 0, matrixGrabber.mModelView, 0,
    matrixGrabber.mProjection, 0, viewport, 0, temp, 0);
        Matrix.multiplyMV(temp2,0,matrixGrabber.mModelView, 0, temp, 0);
        if(result == GL10.GL_TRUE){
            farCoOrds[0] = temp2[0] / temp2[3];
            farCoOrds[1] = temp2[1] / temp2[3];
            farCoOrds[2] = temp2[2] / temp2[3];
        }
        this.P0 = farCoOrds;
        this.P1 = nearCoOrds;
    }
}

What is the problem?
Comment: Where are `P0` and `P1` defined?
Comment: It isn't I guess what I am asking is what are they suppose to be defined as.
Answer: The P0 [] and the P1 [] are not defined. I defined them as public static float[] P0 = new float[3], and public static float[] P1 = new float[3].


Android - generated layouts, is it possible?

Question: is it possible in Android create dynamic layouts and then use them? I mean insted of layouts defined in src use some dynamic generated layouts from database, which contains pieces of XML code and when put together it makes new layout...
It is real or unreal scenario?
Answer: you can create elements programatically. For instance you can do:
TextView myTextView = new TextView();

You may have to do something like this. Otherwise you will need to generate an XML file and use LayoutInflater I guess.
Answer: That is not supported. The built-in LayoutInflater requires resource files, not arbitrary XML. Quoting the documentation:

Therefore, it is not currently possible to use LayoutInflater with an XmlPullParser over a plain XML file at runtime; it only works with an XmlPullParser returned from a compiled resource (R.something file.)

You would have to write your own LayoutInflater equivalent.


Call a python script with a shebang

Question: I want to run a python script foo.py from the command line like this
$ foo

Using a shebang in foo.py, for example:
#!/usr/bin/env python
print('this is foo')

allows me to call it like this:
$ ./foo.py

How do I drop the leading ./ and the trailing .py?
Comment: @Cyrus Don't give that line without explaining the security implications!
Comment: The leading `./` is there for security reasons. And you can just rename the file.
Comment: To explain: if you include the current working directory in your `PATH` someone can put a script name like a standard command (for example `ls`) in some folder. When you enter that folder and run `ls` the script will be executed with your rights.
Comment: This might help: `PATH="$PATH:$PWD"`
Comment: Does this answer your question? [How do I run a shell script without using "sh" or "bash" commands?](https://stackoverflow.com/questions/8779951/how-do-i-run-a-shell-script-without-using-sh-or-bash-commands) I know it says "shell script", but it's the same process for any script.
Comment: Yes, move `foo.py` as `foo` to a directory that is in your PATH.
Comment: @KlausD. `bash` would only execute `ls` in `$PWD` if it did not find `ls` in one of the directories mentioned in `$PATH` before. I had not written `PATH="$PWD:$PATH"`.
Comment: Ah - I see. So an alternative would be to put `foo.py` in something that is on my PATH already?
Answer: First, rename the file from foo.py to foo.
Then, move the file to /usr/local/bin/ or /home/user/.local/bin if the script will only be executed by a single user. Instead, if your script is placed somewhere in the system for example "/path/to/foo", you could add your "/path/to/foo" to the $PATH variable.
After opening a new terminal session. You should be able to execute the script without the "./" and ".py".
By the way "./" means that you want to execute a file in the current working directory. It is always possible to execute a file using a full path of the file, for example "/usr/bin/something_to_run".
Please consider reading about PATH variable here.

Call a python script with a shebang


Closed convex set as the intersection of (tangent) half spaces

Question: Theorem 18.8 in the book by Rockafellar establishes that any $n$-dimensional closed convex set $C$ in $R^n$ can be expressed as the intersection of the closed half spaces tangent to $C$. See here for the book page.
I'm having trouble seeing why the statement is true. For example, consider the square in $R^2$ which is the convex hull of $(1,1), (1,-1), (-1,1)$ and $(-1,-1)$. This is a closed convex set, but it does not seem to have any tangent hyperplanes (a hyperplane is tangent if it is the unique supporting hyperplane at a certain point), so how can the square be expressed as its tangent half spaces?
Is there something I'm missing here?
Edit: I realize that I might have some misunderstanding here, but I'm still not sure. On the same page of the book, tangent hyperplanes are mentioned as duals to the exposed points, that's why I thought for a hyperplane to be tangent it must only passes through one of the exposed points, which now I realize might not be the case. Does this mean that in the above example, hyperplanes containing one of the sides of the square are its tangent hyperplanes? This will rationalize the theorem for me, but can someone explain in what sense the tangent hyperplanes are dual to exposed points?
Thanks a lot!
Comment: Is the horizontal line $\{(x,1): x\in\Bbb R\}$ a tangent hyperplane (for your square) by your lights?
Comment: @JohnDawkins Thanks for the comment! Now I realize that I probably misunderstood the notion of the tangent hyperplane. I just edited my question.
Comment: Regarding uniqueness: Rockafellar is defining a supporting hyperplane at $x$ to be a tangent hyperplane, if it is the only supporting hyperplane at $x$. So by definition, points that admit more than one supporting hyperplanes, do not admit tangent planes.
Answer: Tangent hyperplanes can touch a convex set at multiple points.  For the square, you have 4 half-spaces whose defining hyperplanes are tangent to the sides of the square, namely $\{(x,y):y\geq 1\}$, $\{(x,y):y\leq -1\}$, $\{(x,y):x\geq 1\}$ and $\{(x,y):x\leq -1\}$.  You also have 4 that touch the corners, at 45 degree angles (I won't write them down explicitly).  If you intersect these 8 half-spaces, you'll get the square.  It helps to draw a picture.
Comment: Thank you for the answer. Are those touching only the corners also considered tangent? It seems that they are not unique (i.e. you can tilt them to be touching at 30 and 60 degrees), which is a requirement for tangency?
Comment: Supporting hyperplanes aren't unique for arbitrary convex sets, I'm not sure where you've seen that.  They're unique for strictly convex sets.  The theorem about half-space intersection doesn't require uniqueness anyway.
Comment: Hmm I realize I may be seriously confused. In my example on the square, isn't the hyperplane $\{(x,y): y=1 \}$ a unique supporting hyperplane to the point, say, $(0,1)$? The uniqueness requirement is mentioned in Rockafellar, on the same page of the link in my question. It's mentioned in the 4th paragraph on that page, if you wouldn't mind taking a look? Thanks a lot!


How to align three images specifically?

Question: I'm having trouble aligning three images in the middle of the page.
Let's say image #1 is around 500px high by 500px wide. Image #2 and #3 are 250px high and 500x wide.
I want image #1 to be on the left and image #2 and #3 next to image #1.
There would be some margin between them so that they wouldn't be RIGHT next to each other, but for now, I need to figure out a way to align them.
------------------    -------------------
|                 |   |                 |
|                 |   |                 |
|                 |   |                 |
|                 |   |_________________|
|                 |
|                 |   |-----------------|
|                 |   |                 |
|                 |   |                 |
-------------------   -------------------

Does that make sense...?
Also, they're not buttons or anything. Just plan images.
Comment: forget an illustration. How about "what have you tried?"  - we who volunteer our lives on this site like to know we're not just doing your work for you. We're here to "help" not just work.
Comment: @KaiQing, if that's what he was asking for, then this question was even more poorly written than I first thought.
Comment: A graphical illustration would be helpful.
Comment: Define _"align them"_... vertically, horizontally, along their top/bottom edges, equal spacing, centered, what?
Comment: I shamelessly hijacked the question to illustrate the request. This is what I believe the OP wanted. If I'm wrong... shame on me for putting an ounce of interest in it
Comment: @sparky - true but I deduce this entirely based on the dimensions he listed. Because 2 and 3 are half the HEIGHT of 1 it makes some sense to believe this is his intention.
Answer: Like this? http://jsfiddle.net/chmHH/
Works in Chrome, haven't checked other browsers.
HTML (I recommend using class names)

CSS
div{
    text-align:center;
}
img{
    display:inline;
}

Updated: http://jsfiddle.net/chmHH/1/
HTML

CSS
div{
    text-align:center;
}
img{
    display:inline;
}
img.top{
    vertical-align:top;
}
img.bottom{
    vertical-align:baseline;
    margin-left:-204px;
}

Comment: zzz http://jsfiddle.net/chmHH/3/
Answer: First approach.
If you can change a little bit the markup, the easiest approach consists into adding an extra box for the images, which should be rendered in column. Then you would change the box display property so that it does not start on a new line.

.inline-block {
  display: inline-block;
}
.small {
  display: block;
}

Second approach.
Use CSS float property. All you may ever want to know about float is in this css-tricks' post.
And that's the final result.

#big {
    float:left;
    margin-right:2px;
}
.small {
  display: block;
}

Answer: if only 3 images, and using html, then try aligning left, middle, and right, like this:

you must also set the width and height to a small enough size so all will fit with a space, depending on your screen resolution.  Just try to shrink image size to a small size and will probably work.
Comment: I fear for the future of the internet if this answer has somehow been accepted by any living soul! - and sorry user185. it takes a lot to get me to downvote but you just kept soaring this into the abyss
Comment: -1 for using `align` attribute.
Comment: pretty sure align is not valid in html5.
Comment: I don't think it's valid in HTML4.01 either.  Correction:  **deprecated** in HTML4.01.
Comment: Probably true. This is the first google result I found on it: http://webdesign.about.com/od/htmltags/p/blatalignmultim.htm
Comment: Wow, this answer just keeps getting worse.  What a mess inside that third `img` tag.  **Proof-read what you post, man!**
Comment: Yeah, that works! Thanks so much, everyone!
I had an image sample but for some reason, my file isn't opening and I couldn't upload it. But that sample up there that someone so nicely put up for me was exactly what I was looking for (I didn't think about using characters to illustrate the image).
Thanks,s guys! You guys are the best!
Comment: You realize that there is no such `img` `attribute`'s called `position`, `left`, or `top`.
Comment: @user1772537, pay attention to the comments and edit history on your OP...  KaiQing is who fixed your question.  And this answer by user1851853 can't possibly work... it's full of syntax errors and deprecated HTML.
Comment: @KaiQing, me too... what a disaster... ten edits and he still couldn't find the syntax errors, even after I pointed to them.
Comment: @KaiQing, this code demonstrates how forgiving browsers can be.  It would be a better Internet if the browser rendered a blank page on syntax errors instead of a "best guess".  And this question/answer demonstrates that people don't read comments.

How to align three images specifically?


chrome.extension.getViews() and Extension Options page

Question: If I open a new tab and navigate to chrome-extension://{ext_id}/options.html by typing directly into the address bar the page shows up in the list when I do
chrome.extension.getViews({'tab'})

This is the expected behaviour.
If I [right click] on my extensions "browser_action" action and select "Options" this brings up a new tab with chrome-extension://{ext_id}/options.html as the URL and it shows up in the list when I do
chrome.extension.getViews({'tab'})

Again, this is the expected behavior.
If I click a link on my extensions popup, that navigates to the options page, this opens up a new tab and navigates me to chrome-extension://{ext_id}/options.html. This is the expected behavior.
BUT, there is always a but, for some reason this page does NOT show up in
chrome.extension.getViews({'tab'})

Even though it is obviously within the context and protocol of the extension. I just don't know what the difference between the FIRST and the LAST scenario is. If anything I would expect the first scenario to fail since the user is manually navigating there, rather than a extensions own popup navigating to the extensions own options page.
I have tried using both

/* and */

/* This correctly sets the href as chrome-extension://{ext_id}/options.html */

but again the same problem. The extension still runs all its Javascript correctly. I still am able to use chrome.extension functionality correctly. Just the page is not showing up within getViews. I suspect it is a Sandboxing issue, but I can't understand it working for all other situations expect one.
Does anyone know how to either get it to work correctly? or open up the page in a different manner so it will work?
PS: I do not wish to open up the options page within the popup window. I have tested this, and it STILL does not list the page within the getViews but I presume this is because it is no longer a 'tab' but a 'popup'.. But again, its not the behavior I wish.
Answer: If it looks like a bug and feels like a bug, then it is probably a bug. In the future, if you think that you're experiencing a bug, don't hesitate reporting it on Chromium's bug tracker at http://crbug.com/new.
I have reported your bug as https://code.google.com/p/chromium/issues/detail?id=341459.
A work-around to get your extension page opened from the popup window to show up in chrome.extensions.getView({type: 'tab'}) is to open the tab using chrome.tabs.create:
chrome.tabs.create({
    url: 'options.html'
});

Comment: I am just experimenting with this technique this very minute when i seen on the documentation you do **not** need the tabs permission to use most of the functionality.
Comment: This worked. Not quite as elegant as using href but I can live with it. Also, thank you for making the issue on chromium.


Saving String[] to a bundle to be used when activity is recreated

Question: When my activity is ran for the first time it downloads some url strings and sets them to.
a String list...
public   String [] myRemoteImages = {imageUrl,imageUrl2,imageUrl3,imageUrl4};

the imageUrl's inside are 4 url's that are downloaded and set to the variables..
When the activity is closed or destroyed, how can i save these url's to their variables so they wont be erased when the activity is destroyed?
Could i possible save it in a bundle and then onRestoreInstanceState pull them out?
Answer: If your activity is destroyed you would not be able to save data, but you can use SharedPreferences for example to save some datas like Strings:
http://developer.android.com/guide/topics/data/data-storage.html#pref
Answer: If you want to save these strings during activity re-creation use the following method.
public String [] myRemoteImages = /* ... */;
private static final String KEY_URLS = "urls";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (savedInstanceState != null) {
        myRemoteImages = savedInstanceState.getStringArray(KEY_URLS);
    }
 }

@Override
protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    outState.putStringArray(KEY_URLS, myRemoteImages);
}

If you want to keep these string alive when your application is closed by user you'd better use SharedPreferences.
onRestoreInstanceState() is called when the activity is restored. It means that this activity is recreating after configuration change or after a process containing this activity was killed and re-launched. So if you want to save a state before your app closes, use onPause()/onResume() methods to save and restore it.
Comment: SO should i do it the way you stated above? Becuase i tried it, once the app is killed, the methods above doesnt reload the strings[]
Comment: I want to be able to save the strings[] when the activity its killed.
Comment: You can save these strings to 'SharedPrefererences' when you get them or when they change. And in `onCreate()` for example you can try to load these strings. The main idea is not to wait until your app is killed because you won't be able to do anything in this case.


Optimizing for update only files of size 4-20kb on restricted NVMe AWS disks (Low bandwidth, low latency)

Question: Working on a problem statement where we can't use a DB, instead, we have to implement our own.
Problem statement:-

A request is made to the server with blob (4KB avg, 20KB max) with a UUID and store the blob on disk, sounds perfect use-case for key-pair blobfs, but the catch is, a request from the same UUID will be made again and we'll have to replace the previously written data with a new one, i.e at any point of time we're only concerned with the latest blob.

Request from the same UUID will be made every 10 seconds.

SIGKILL could be made to the server to check the integrity of files. It's okay to lose data of requests made in the last 3 seconds. However, we'd want to make this time as low as possible.

Number of writes is way more than the number of reads

We want to know the maximum number of UUIDs we can support on the given infrastructure.

Infrastructure:-

We have a c6gd.large AWS instance which comes with 4GB RAM, 2 CPUs, 120GB NVMe. But the problem with NVMe is that the bandwidth is restricted by AWS (source), however, we do get low latency (within 150 microseconds).

As shown below, we get more bandwidth while storing in bs of 5kb than 1GB. Also creating a new file is faster than overwriting an existing one.

What I've tried so far:-

Because of the above benchmarks, for each request, I create/update a file with each UUID and write the blob to it.

I've tried both xfs and ext4 filesystem and ext4 performs a bit better and is giving around 8.5k Requests/Second for a 2 hour test. Which means we can support 85k probes as each probe will send request only once every 10 seconds.

I've tested using wrk and noticed that CPU usage on average is around 70-80% and RAM usage is around 3GB (out of 4GB)

I've mounted the disk with ext4 with rw,seclabel,noatime,nodiratime,journal_async_commit,nobarrier these mount options.

NOTE: I've benchmarked the http server alone and it's supporting 100k Req/sec, hence it won't be a bottleneck.

I've used golang for it and this is how I'm writing to file.

I've read about RocksDB architecture, and LSM trees looks promising however I'm of the opinion that compaction process won't give us a huge benefit given that badwidth is just around 100MBps. Am I wrong to think that?
Another question that's in mind is when there are say 1000 writes in a batch to go on disk, I'm assuming that the fs (ext4) journaling will sort these operations. Is this assumpting correct? If not is there a way to enforce this? Also can I batch these write requests to be processed every say 100ms?
Are there any other ideas which I can try?
Comment: Yes, it is way better for everyone, you can use code formatting in editor, there are hints and help you can follow.
Comment: Please, don't use screenshots for code and error messages. It is hard to reproduce and search engines have problems finding data that are inserted as images as well.
Comment: @Ruli so rather just paste them as code blocks? I'll follow that from now on. Thanks.
Answer: ideas

buffer requests(go channel, unix datagram socket, redis, ...)
bulk upsert every 100ms

tried

badger db & go channel
rocks db  & unix datagram socket
sqlite3   & unix datagram socket

not tried

RabbitMQ
Kafka
Nats
PostgreSQL
Redis

front
communication
db
result

net/http(go)
go channel
badger(go)
killed(OOM)

net/http(go)
unix datagram socket
rocksdb(rust)
many timeouts

net/http(go)
unix datagram socket
sqlite3(rust)
18,000 rps

benchmark result
latency distribution(ms) and requests per second

50%
75%
90%
99%
rps
description

0.6
0.7
1.2
9.9
176k
1. create files(direct)

2.4
4.5
7.1
14
54k
2. create files(indirect)

6.9
13
19
71
18k
3. sqlite3

10
18
24
46
13k
4. upsert files(dirty)

339
350
667
1320
0.4k
5. upsret files(fdatasync)

connections: 128
threads: 128
duration: 60 seconds

1. create files(direct)

wrk -> GET request
GET request -> actix web server
create empty files

2. create files(indirect)

wrk -> GET request
GET request -> net/http server
data(4k) -> unix datagram socket
unix datagram socket -> create empty files

3. sqlite3

wrk -> GET request
GET request -> net/http server
data(4k) -> unix datagram socket
unix datagram socket -> channel(buffer=128)
channel -> sqlite3(bulk upserts, every 100 ms)

4. upsert files(dirty)

wrk -> GET request
GET request -> net/http server
data(4k) -> unix datagram socket
unix datagram socket -> ext4(without fdatasync)

5. upsret files(fdatasync)

wrk -> GET request
GET request -> net/http server
data(4k) -> unix datagram socket
unix datagram socket -> ext4(temp file)
fdatasync
rename

local pc info
storage
cat /etc/fstab
LABEL=cloudimg-rootfs   /        ext4   defaults        0 1

cpuinfo
fgrep 'model name' /proc/cpuinfo|cat -n
     1  model name      : Intel(R) Core(TM) i7-9750H CPU @ 2.60GHz
     2  model name      : Intel(R) Core(TM) i7-9750H CPU @ 2.60GHz
     3  model name      : Intel(R) Core(TM) i7-9750H CPU @ 2.60GHz
     4  model name      : Intel(R) Core(TM) i7-9750H CPU @ 2.60GHz
     5  model name      : Intel(R) Core(TM) i7-9750H CPU @ 2.60GHz
     6  model name      : Intel(R) Core(TM) i7-9750H CPU @ 2.60GHz
     7  model name      : Intel(R) Core(TM) i7-9750H CPU @ 2.60GHz
     8  model name      : Intel(R) Core(TM) i7-9750H CPU @ 2.60GHz
     9  model name      : Intel(R) Core(TM) i7-9750H CPU @ 2.60GHz
    10  model name      : Intel(R) Core(TM) i7-9750H CPU @ 2.60GHz
    11  model name      : Intel(R) Core(TM) i7-9750H CPU @ 2.60GHz
    12  model name      : Intel(R) Core(TM) i7-9750H CPU @ 2.60GHz

dd
% dd if=/dev/zero of=./zeros.dat bs=4096 count=262144
262144+0 records in
262144+0 records out
1073741824 bytes (1.1 GB, 1.0 GiB) copied, 2.67881 s, 401 MB/s

% dd if=/dev/zero of=./zeros.dat bs=4096 count=262144 conv=fdatasync
262144+0 records in
262144+0 records out
1073741824 bytes (1.1 GB, 1.0 GiB) copied, 1.02852 s, 1.0 GB/s

% dd if=/dev/zero of=./zeros.dat bs=4096 count=262144 conv=fsync
262144+0 records in
262144+0 records out
1073741824 bytes (1.1 GB, 1.0 GiB) copied, 0.875749 s, 1.2 GB/s


File path is not supported

Question: string fil = @"D:\\vish1_vish.txt";
FileStream fs = new FileStream(File, FileMode.Create,FileAccess.Write);

In this line I'm getting file path name is unsupported. Please help me how to rectify this error.
Comment: You pass "File" not "fil" to the FileStream ctor
Answer: You are not passing your path to the method:
string fil = @"D:\vish1_vish.txt";
FileStream fs = new FileStream(File, FileMode.Create,FileAccess.Write);

I guess it should be something like this(your question is quite unclear):
string fil = @"D:\vish1_vish.txt";
FileStream fs = new FileStream(fil, FileMode.Create,FileAccess.Write);

Comment: string fil = @"D:\vish1_vish.txt";                                                    FileStream fs=newFileStream(fil,FileMode.Create,FileAccess.Write);I'm getting error as unsupported file format

File path is not supported


How to find depth of property?

Question: public class CategoryInModel
{
 public int Id { get; set; }
 public CategoryInModel Parent { get; set; }
}

I have a class like above. I want to get depth of the Parent object.
Parent object can have various depths.
Like:
Parent.Parent.Parent
or
Parent.Parent
How can I find the depth of the parent object?
Answer: Based on the logic that a model's depth will be 1 + the parent depth:
public class CategoryInModel
{
    public int Id { get; set; }
    public CategoryInModel Parent { get; set; }

    public int Depth => 1 + ParentDepth;
    public int ParentDepth => Parent?.Depth ?? 0;
}

Answer: static int GetDepth (CategoryInModel cat, int depth = -1)
{
    if (cat == null)
        return depth;
    else
        return GetDepth(cat.Parent, depth + 1);
}

And then to use:
var mod = new CategoryInModel { Parent = new CategoryInModel { Parent = new CategoryInModel { Parent = new CategoryInModel() } } };

Console.WriteLine(GetDepth(mod));

How to find depth of property?


Checking the numbers in an array and then comparing their values

Question: Where do i fix the code in a way so that, i can check if the numbers in any row has equal values (e.g : if the matrix is 3*3 then for instance for the first row every number is 1)
#include <iostream>

using namespace std;

int main ()

{
    int n;
    cout<< "Kvadrat husnegtiin iremb:" <<endl ;
    cin>> n;
    int A[n][n];
    for (int i = 0 ; i < n ; ++i )
    {
        for (int j = 0 ; j < n; ++j )
        {
            cout<< "["<< i<< "]"<< "["<< j<< "]"<< " Element"<< endl;
            cin>> A[i][j] ;
        }
    }
    for ( int i = 0 ; i < n ; ++i )
    {
        int B1 = A [i] [0] ;
        for ( int j = 0 ; j < n; ++j )
        {
            if (B1 == A [i] [j] )
            {
                cout<< i<< "Baina"<< endl;
            }
        }
    }
}

Answer: You can use a flag to check if there's a different value in your loop.
In example :
for (int i = 0; i < n; ++i)
{
    int B1 = A[i][0];
    bool IsDifferent = false;
    for (int j = 0; !IsDifferent && j < n; ++j)
    {
        if (B1 != A[i][j]) //Notice the inverted condition
        {
            IsDifferent = true;
        }
    }
    if (!IsDifferent)
        cout << "Line " << i << " has equal values." << endl;
}

Answer: for ( int i = 0 ; i < n ; ++i ) {
  bool all_equal = true;

  for ( int j = 1 ; all_equal && j < n; ++j ) {
    all_equal = A[i][j] == A[i][0];
  }

  if ( all_equal )
    cout << "row " << i << " has equal values" << endl;
}


Can I change date to Monday if date equals Saturday or Sunday in Excel VBA Macro

Question: When I run my excel VBA macro it automatically copies a sheet called temp into a new sheet formatted "day of week-month-day-year" "ddd-MMM-dd-yyyy"
It will name this new tab with tomorrows date.
But when I run this on Friday or Saturday it will use Saturday or Sunday for the Date.
When ran on Sunday it will use Monday which is good.
I have tried using code from this StackOverflow post and mix it into my code without any luck.
Move next Dateadd to Monday if it falls on Saturday or Sunday
Not exactly sure how to make it work with my code.
ThisWorkbook.Sheets("temp").Copy After:=Sheets(Sheets.Count)
ThisWorkbook.Sheets(Sheets.Count).Name = Format(Date + 1, "ddd-MMM-dd-yyyy")

I need it to always use Monday if ran on a Friday or Saturday.
Comment: *I have tried using code...without any luck*  <-- what does this mean, exactly? Do you get an error?
Comment: IOW, show us what you have tried, and explain what you mean by "without any luck"
Answer: ThisWorkbook.Sheets(Sheets.Count).Name = format(Application.WorksheetFunction.WorkDay(date, 1), "ddd-MMM-dd-yyyy")

Answer: You could try:
Sub CopySheet()

    Dim strName As String

    If Format(Date, "dddd") = "Saturday" Then
        strName = Format(Date + 2, "ddd-MMM-dd-yyyy")
    ElseIf Format(Date, "dddd") = "Sunday" Then
        strName = Format(Date + 1, "ddd-MMM-dd-yyyy")
    End If

    ThisWorkbook.Sheets(Sheets.Count).name = strName

End Sub

Answer: Sub Weekend_Dates()

    Dim k As Integer

    For k = 1 To k + 1

        If Weekday(Cells(k, 1).Value, vbMonday) = 1 Then
             Cells(k, 2).Value = Cells(k, 1)
        ElseIf Weekday(Cells(k, 1).Value, vbMonday) = 2 Then
             Cells(k, 2).Value = Cells(k, 1)
        ElseIf Weekday(Cells(k, 1).Value, vbMonday) = 3 Then
             Cells(k, 2).Value = Cells(k, 1)
        ElseIf Weekday(Cells(k, 1).Value, vbMonday) = 4 Then
             Cells(k, 2).Value = Cells(k, 1)
        ElseIf Weekday(Cells(k, 1).Value, vbMonday) = 5 Then
             Cells(k, 2).Value = Cells(k, 1)
        ElseIf Weekday(Cells(k, 1).Value, vbMonday) = 6 Then
             Cells(k, 2).Value = Cells(k, 1) + 2
                Else
                Cells(k, 2).Value = Cells(k, 1) + 1

        End If

    Next k

End Sub


How should I drain fuel from my mower?

Question: I have a Honda lawn mower (HRX217K2VKA) and I want to drain the fuel for winter. How should I do this? Three options spring to mind:

Run the engine until the fuel is gone.
Tip the mower to pour the fuel out.
Siphon the fuel.

The manufacturer's manual (see page 13) recommends option 1, but I was wondering if anyone could recommend an alternative that didn't waste the gas.
Comment: @Brian - the trouble (from what I've always heard) comes from a few different spots, and a main one these days is that without stabilizers, in blended gasolines (which more and more are these days), you run the risk of [phase separation](http://www.fuel-testers.com/ethanol_engine_precautions.html).  That site claims a shelf life of only 3 months - definitely shorter than a lawnmower's winter downtime.  Then you have the problem that some gas stations dilute their gas - also leading to separation (often leading to a ruined engine).  Evaporation is usually not the primary problem.
Comment: Some people just leave it in and use Sta-bil. Others don't do anything. According to an engineer at Marathon that I talked to a few years ago, gasoline should be stable for 3-5 years unless left in an open container where it will evaporate quickly. Not sure I want to test that length, but I routinely leave half a tank of gas in my racecar that may not be driven for up to 6 months and so far have not had any issues.  I guess it comes down to how fast it might evaporate from the mower as to if it's necessary (obviously you'll follow the owner's manual if it tells you what you need to do).
Comment: @Nate good info.  I hadn't run across that before.  Best to try and avoid any ethanol when possible I guess.  I know that my older car (1991) hates ethanol (10% MPG loss and had to go from 87 to 94 octane to control spark knock ever since our local stations switched).
Comment: Ethanol cannot be avoided in many US states, including mine. Gas with ethanol will begin to deteriorate within months, and it will damage carburetors in older cars and non-automotive engines if not drained.
Comment: One thing to think about with that wasted gas - what were you going to do with it?  You shouldn't keep it until next spring.
Answer: I have always just had a "last mow of the year", where when I run the mower dry, and I've never had a problem.  Then you're not really "wasting" the gas.
Depending on your model (and it looks like the one you specified ought to manage this), you may be able to do option 2 if you have a really full gas tank.  Then, after emptying, you still ought to run it dry for what little remains.
I personally would not recommend siphoning it.  Unless you wanted to go to the trouble of buying extra equipment to do it (and think about that - how often are you going to be siphoning gasoline?  Enough to justify a special purchase?), that means a distinct risk of drinking a little bit of gasoline... not exactly a pleasant experience, nor good for you.
from this site:

Many adverse health effects of gasoline are due to individual chemicals in gasoline, mainly BTEX, that are present in small amounts. Breathing small amounts of gasoline vapors can lead to nose and throat irritation, headaches, dizziness, nausea, vomiting, confusion and breathing difficulties. Symptoms from swallowing small amounts of gasoline include mouth, throat and stomach irritation, nausea, vomiting, dizziness and headaches. Some effects of skin contact with gasoline include rashes, redness and swelling. Being exposed to large amounts of gasoline can lead to coma or death.

So, siphoning probably won't kill you, but I certainly wouldn't endorse it.
Comment: There are handheld siphons that work on gasoline. The problem is, no siphon will get out the last of the gas. I siphon out what I can in these cases, then run it dry.
Comment: Yeah, I don't like siphoning as a first option. It's nasty. I figured the "running dry" was my best option. Thanks! I think I'll mulch the last leaves with it this weekend. :)
Comment: Regarding siphonioning not getting all the gas out: Does it matter? When you go to start the mower in the spring there will be a few ounces of old gas and you'll add a 1/4 gallon or so on top of it. Might be a little hard to start or run rough, but it should be fine.
Answer: IMO run it dry, most of my neighbors and I do this by mowing our leaves. Either bagging or mulching actually helps.
Alternately look for the line that runs from the bottom of the fuel tank to the carburettor. If this is easy to get to and remove you may be able to remove the line and use that to drain it.
Comment: The problem with siphoning the gas is that you probably won't be able to get it out of the fuel line and carburetor, which is honestly where stale gas is going to cause the most problems. Running it dry seems like the safest bet. Drive it down to the corner store next time instead of your car maybe to use up the gas.
Comment: JohnFx - Thats why I'm suggesting using the fuel pickup tube. It should be at the bottom of the tank and it should just drain out so there isn't a need to siphon.
Answer: I bought a little gas siphon with a squeeze bulb from home depot for $5.  I use that to empty the tank.  I then run the mower to pull the remaining gas out of the system (runs for like a minute).
Oh, and +1 for using Sta-bil.  Even if you don't leave gas in the mower, you should put a fuel stabilizer in your gas can.  Unless you use up the fuel in your gas can every 2-3 weeks, it needs some kind of stabilizer or the gasoline will start to break down.
Answer: Either run it until it's dry or put sta-bil in it. Definitely don't just leave gas sitting in it.
Depending on how yours is setup, you might be able to unhook the hose that goes from the tank into the carb.  They usually have those spring clamps you can pinch with pliers to get off, but really, that is more work than you need to do. And you can't reliably save the gas, and letting it run off on to the ground isn't a great idea.
I usually mulch down my leaves until it runs out of gas and then put it up for the year.
Answer: There is a drain valve to drain the fuel in my Honda mower.
See page 56 of http://cdn.powerequipment.honda.com/pe/pdf/manuals/31VH7H20.pdf .

How should I drain fuel from my mower?


I get the "unable to locate package" message when trying to install php-xml-rss, even though I have the universe repo added

Question: I'm currently configuring a Wordpress hosting platform, and one of the packages that I need to install is php-xml-rss.  It's in the universe repo, which I have added, and I ran apt-get update and upgrade, so I know it's up to date.  When I run the command to download php-xml-rss, I just get a "unable to locate package" message.  I was able to get the rest of my packages with no issues.  Any clue what might be causing this?
Answer: On my research I found that php-xml-rss package is only available in trusty (14.04LTS), you can verify it here.
A solution could be to download the .DEB files from here or here, depending on which version of Ubuntu you're using.
Hope it helps.
Comment: Thanks.  That's too bad, because I'm using Ubuntu 16.04.3 so I'll probably have to restart from scratch with 14.04
Comment: You can download the .DEB files and install them using `sudo dpkg -i `
Comment: I might be missing something since I'm fairly new to ubuntu and to Linux in general, but when I run `sudo dpkg -i` after downloading the package, it says ` is not a debian format archive>.  However it says .deb on the download page.  If it helps at all I can't use a GUI for this project.


Debug/Run Applet in NetBeans

Question: How can I debug or run a class that extends java.applet.Applet? I am able to run the applet from the command line with appletviewer.
appletviewer runapp.html

Here is what class looks like:
import java.awt.Graphics;
import java.applet.Applet;

public class FancyApplet extends Applet {
    @Override
    public void paint(Graphics g) {
        g.drawString("Hello World!", 20, 20);
    }
}

Here is what the HTML file looks like
<!doctype html>

    <meta charset="utf-8">
    <title>A Fancy Applet</title>

<object type="application/java" width="200" height="300">
    <param name="code" value="FancyApplet.class">
</object>

How do I have to organize those files within my project and what settings do I have to use to debug the Applet in NetBeans? The thread Running a java applet from netbeans? did not help unfortunately. I did what was suggested, but get a message telling me that the main class was not found. What I took from it though was that in my case the HTML file is not even needed? But just because I am curious is it still possible or recommended to use it?
Comment: You've broken the paint chain, you really should call `super.paint`. Do you really need to use `java.awt.Applet`?  The API was replaced with Swing some 15+ years ago.  In fact, do you really need to use applets?  They have a lot of issues and difficulties that might be best avoided if you are just learning...
Comment: I know that it is recommended to use Swing or JavaFX instead. I am just learning all that stuff and was told that Swing is build on AWT, so it is useful to have an understanding of it.
Comment: Yes and no.  You don't really need a "deep" understanding of AWT to learn Swing, as it's use/interaction is semi-transparent. If you're just learning, then I suggest you stay away from applets (personally) and focus on desktop applications, as they are less restrictive and present a more gential learning curve - IMHO
Comment: You also might find [Painting in AWT and Swing](http://www.oracle.com/technetwork/java/painting-140037.html) and [Performing Custom Painting](http://docs.oracle.com/javase/tutorial/uiswing/painting/) useful
Answer: As you don't have public static void main(String[] args) in your FancyApplet class, so the above error is produced.
You can run your java applet in the NetBeans IDE by pressing Shift + F6 key from your main class(keeping cursor inside FancyApplet class here). It'll run the applet program without searching for the main method.
This is an alternate shortcut method of running individual classes in NetBeans IDE.
Comment: All that time I did not think about that I can run individual files. When doing this the HTML file to run the Applet will be automatically created in the build folder of the project. A bit too late I found this useful link explaining it all: https://netbeans.org/kb/docs/web/applets.html

Debug/Run Applet in NetBeans


Async with WPF properties

Question: I have a bound property like this:
public string MyPath
{
    get { return _mypath; }
    set
    {
        _mypath = value;
        NotifyPropertyChanged(() => MyPath);
        LoadSomeStuffFromMyPath(mypath)
    }
}

I'd like the make LoadSomeStuffFromMyPath async but I cannot await from a property. Is there a simple way to do this?
EDIT: More than one person has said not to use a property so I want to call this out. I am using WPF and this property is bound to the UI. I have to use a property.
Comment: @Servy Both get and set are bound to the UI.
Comment: Is it important for code setting a value to not continue execution until `LoadSomeStuffFromMyPath` finishes?  If no, fire and forget, if yes, don't use a property, use a method to set the value.
Comment: @Servy Yes it is important that it not continue. Unfortunately I'm using WPF so I don't have the option to not use a property.
Comment: @Justin984 If it can't continue, why do you want it to be asynchronous?
Comment: @ReedCopsey I want to show a progress bar
Comment: @Justin984 Is the property *setter* called from UI data binding, or just the getter?  If it's only the getter then have a read only property and a method that sets the underlying value.
Comment: @Justin984 While this doesn't provide you the exact requested functionality, my new edit should get you the proper behavior (with some other functionality added)
Comment: possible duplicate of [How do I make this run asynchronously?](http://stackoverflow.com/questions/19501952/how-do-i-make-this-run-asynchronously)
Comment: @Servy I'd say that's actually a different issue (since it's somewhat specific to `IEnumerable` bindings, and purely a "get" issue)
Comment: @ReedCopsey What about it is specific to `IEnumerable`?  The answer would apply equally to any other type of data.  Whether it's a get/set issue shouldn't affect the solution, again, it should apply to both, I would think.
Comment: @Servy That's more "how do I bind to data being asynchronously loaded" - this is more "How do I asychronously change my data".  The mechanisms vary quite a bit.
Answer: Since you want to force the operation to not continue until this is complete, I would suggest making a method to handle loading and displaying your progress.
You could use a separate property to disable the UI while this loads, which could effectively "block" your user until the operation completes:
public string MyPath
{
    get { return _mypath; }
    set
    {
        _myPath = value;
        NotifyPropertyChanged(() => MyPath);
        UpdateMyPathAsync();
    }
}

public async Task UpdateMyPathAsync()
{
    this.EnableUI = false; // Stop user from setting path again....
    await LoadSomeStuffFromMyPathAsync(MyPath);
    this.EnableUI = true;
}

This allows you to still bind, as normal, with WPF, but have your UI reflect that the operation is running (asynchronously) and display progress, etc.
Comment: @Justin984 Then wrap that in a separate method call that is async, so you can control the order of operations (which is what I did to disable/enable the UI)
Comment: Be aware that with this solution, exceptions raised from `UpdateMyPathAsync` are ignored.
Comment: Won't this cause execution to continue since UpdateMyPathAsync() is not awaited?
Comment: @Justin984 Yes, but disabling the UI will prevent hte user from doing anything - you *can't stop executing from continuing* if you want to allow the UI to update...
Comment: Well I meant anything that comes after UpdateMyPathAsync() will execute immediately. I didn't submit full source, but I have some things after UpdateMyPathAsync that I do not want to execute until the file is loaded.
Comment: @StephenCleary Very true - I didn't add any exception handling in here.  You could easily make a FireAndForget method that wraps the exceptions and logs them or does something else if required, and use that on the resulting Task.
Answer: Perhaps you should move that kind of logic to a method. You're going against the guidelines for using properties:

The operation is orders of magnitude slower than a field set would be.
  If you are even considering providing an asynchronous version of an
  operation to avoid blocking the thread, it is very likely that the
  operation is too expensive to be a property. In particular, operations
  that access the network or the file system (other than once for
  initialization) should most likely be methods, not properties.

http://msdn.microsoft.com/en-us/library/vstudio/ms229054(v=vs.100).aspx
EDIT:
I'm not very experienced with WPF, but I think this might be a way to bind to a method instead of a property:
Binding a method to a column in datagrid WPF
Comment: Personally, no.  If it's clearly not an answer that applies to the question, I find it distracting to have it as an answer.  No, you need to have a property to do the binding, you won't be able to use a method.
Comment: It's hard to say without context, but given that it's WPF there's good odds that it's used in databinding, which would require it to be a property.  This has been [confirmed by the op](http://stackoverflow.com/questions/19550402/async-with-wpf-properties#comment29009531_19550402)
Comment: You're right. Even so, I think it's better I leave this here since this is a pretty common misuse of properties, do you agree?

Async with WPF properties


Determine the image of the unit circle $S^1$ by the action of the matrix $e^A$.

Question: We have:
$$e^{ \begin{pmatrix}
-5 & 9\\
-4 & 7
\end{pmatrix} }$$
I need to determine the image of the unit circle $S^1$ by the action of the matrix $e^A$.
I think that I know how to calculate $e^A$:
I get the Jordan decomposition:
$$A = \begin{pmatrix}
  -5 & 9\\
  -4 & 7
 \end{pmatrix}  =
 \begin{pmatrix}
  -6 & 1\\
  -4 & 0
 \end{pmatrix}
 \cdot
 \begin{pmatrix}
  1 & 1\\
  0 & 1
 \end{pmatrix}
 \cdot
 \frac{1}{4}
 \begin{pmatrix}
  0 & -1\\
  1 & -6
 \end{pmatrix}
 $$
With eigenvalues: $\lambda$ = 1, algebraic multiplicity = 2, eigenvecotrs: $\left\{ \begin{pmatrix}
  1\\
  0
 \end{pmatrix}, \begin{pmatrix}
 0\\
 1
 \end{pmatrix} \right\}$
$$ \displaystyle e^A = \sum^{\infty}_{i = 0} \frac{A^i}{i!}$$
$$e^A =
 \begin{pmatrix}
  -6 & 1\\
  -4 & 0
 \end{pmatrix}
 \cdot
 \left(
 \begin{pmatrix}
  1 & 0\\
  0 & 1
 \end{pmatrix}
 +
 \displaystyle \sum^{\infty}_{i = 1} \frac{ \begin{pmatrix}
  1 & 1\\
  0 & 1
 \end{pmatrix}}{i!}
 \right)
 \cdot
 \frac{1}{4}
 \begin{pmatrix}
  0 & -1\\
  1 & -6
 \end{pmatrix}$$
$$e^A = \begin{pmatrix}
  -5 & 9\\
  -4 & 7
 \end{pmatrix}  =
 \begin{pmatrix}
  -6 & 1\\
  -4 & 0
 \end{pmatrix}
 \cdot
 \begin{pmatrix}
  \displaystyle \sum^{\infty}_{i = 1} \frac{1}{i!}& \displaystyle \sum^{\infty}_{i = 1} \frac{2^{i-1}}{i!}\\
  0 & \displaystyle \sum^{\infty}_{i = 1} \frac{1}{i!}
 \end{pmatrix}
 \cdot
 \frac{1}{4}
 \begin{pmatrix}
  0 & -1\\
  1 & -6
 \end{pmatrix}$$
Where: $$\displaystyle \sum^{\infty}_{i = 1} \frac{2^{i-1}}{i!} = \frac{1}{2} \sum^{\infty}_{i = 1} \frac{2^{i}}{i!} = \frac{1}{2}(e^2 - 1)
 $$
So:
$$e^A =
 \begin{pmatrix}
  -6 & 1\\
  -4 & 0
 \end{pmatrix}
 \cdot
 \begin{pmatrix}
  e & \displaystyle \frac{e^2}{2} - \displaystyle \frac{1}{2}\\
  0 & e
 \end{pmatrix}
 \cdot
 \frac{1}{4}
 \begin{pmatrix}
  0 & -1\\
  1 & -6
 \end{pmatrix} =
 \begin{pmatrix}
  \displaystyle \frac{-3e^2 + e + 3}{4} & \displaystyle \frac{9e^2 - 9}{2}\\
  \displaystyle \frac{-e^2 + 1}{2} & 3e^2 + e - 3
 \end{pmatrix}
 $$
Now, I don't know if I did it correctly up to this point and what I should do next - to operate on my unit circle.

Solution:
Because of @Oscar Lanzi we know that:
$$e^{\begin{pmatrix}-5 & 9\\-4 & 7\end{pmatrix}}=e\begin{pmatrix}-5 & 9\\-4 & 7\end{pmatrix}$$
Then because of that:
Equation of unit circle under linear transformation - can't understand role of inverse matrix
(answer by @Prototank)
We know that the image of unit circle in action of the matrix $A$ is given by: $$65x^{2}-166xy+106y^{2}=1$$
Now we need to scale by $e$ and we get the image of unit circle in action of the matrix $e^A$:
$$65x^{2}-166xy+106y^{2}=e^2$$
Comment: There may be a more sophisticated way to do this, but have you tried a few key points on the unit circle and see if there's any obvious behavior?
Comment: No, I'm not sure I I would know how to do that.
Comment: For example, find the images of $(0,1), (1,0)$ etc. It also seems a mistake has been made somewhere, it seems like for your matrxi $A$, $\exp(A)=eA$, according to software: [link](https://www.wolframalpha.com/input?i=matrix+exponential+%7B%7B-5%2C9%7D%2C%7B-4%2C7%7D%7D).
Comment: Ohh, I see. So having that exp(A) I should find the images of some points and look for a pattern?
Comment: Notice $\exp(A)=eA$ means that the action of $\exp(A)$ on any vector $v$ is basically the same as the action of $A$ on $v$, so what would $A$ do to a vector on the unit circle? Then scale it by factor of $e$.
Comment: As @just a user's answer points out, it is an ellipse. Here is the graph: https://www.desmos.com/calculator/umzmpcil68
Answer: This address the general question of shape of image of an unit circle under the action of $e^A$. We can think of a linear dynamic system $\dot x=Ax$, the solution of which will be $x=e^{tA}$. Then what you are seeking is the ending position of points starting from the unit circle, after following linear dynamics for $t=1$.

This animation has credit to Ella Batty. I TAed her class last semester and used this as a demo for 2d dynamic systems.
https://twitter.com/i/status/1319061743679799297
Answer: The matrix exponentiation is much simpler than it looks. When you find that $1$ is the only eigenvalue, render
$\begin{pmatrix}-5 & 9\\-4 & 7\end{pmatrix}=\begin{pmatrix}1 & 0\\
0 & 1
\end{pmatrix}+\begin{pmatrix}-6 & 9\\-4 & 6\end{pmatrix}.$
The first matrix on the right just gives a factor of $e$ to the overall exponential. The second matrix is nilpotent and the series for its exponential is just
$\begin{pmatrix}1 & 0\\
0 & 1
\end{pmatrix}+\begin{pmatrix}-6 & 9\\-4 & 6\end{pmatrix}=\begin{pmatrix}-5 & 9\\-4 & 7\end{pmatrix}.$
So
$e^{\begin{pmatrix}-5 & 9\\-4 & 7\end{pmatrix}}=e\begin{pmatrix}-5 & 9\\-4 & 7\end{pmatrix}.$
Continue from there.
Comment: I think I know what to do next. I will edit my original post soon.
Comment: I got it, I will post full answer.
Answer: The calculation won't be easy, but standard.
To understand the image of any invertible matrix $T$ acting on the unit circle, first do the SVD decomposition $$T=U\Sigma V = U\begin{pmatrix} \sigma_1 & \\ & \sigma_2\end{pmatrix}V$$ Note that $V$ send the circle back to itself, as it keeps norms. Now it should be clear that the image is just an ellipse with two principal axes being $\sigma_1, \sigma_2$ along the directions of the two column vectors of $U$.
Also to find $U$ and $\sigma_i$, we only have to diagonalize $TT^*$.


Oledb on wcf has some issues with large excel files?

Question: Here is the story:
I want to import an excel sheet into a database.
I do some preparations on the client, like selecting the file, the correct sheet and the configuration of the sheet.
When that's all done I send the file to my local wcf server.
Then wcf writes the file to the temp folder (C:\Windows\Temp).
I create an oledb connection and execute a count(*) command on the sheet, and that is where it goes wrong.
The code:
            _connection = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + FileName + ";Extended Properties=\"Excel 12.0 Xml;HDR=YES\"");
            OleDbCommand command = new OleDbCommand("SELECT COUNT(*) FROM [" + .SheetName + "]", _connection);
            if (_connection.State == ConnectionState.Closed)
                _connection.Open();
            TotalRows = (int)command.ExecuteScalar();

Yes, I'm not using a using here, don't mind that please...
When (int)command.ExecuteScalar(); is executed it goes wrong.
I receive the error: System resource exceeded.. This is an OleDBException.
The memory of my computer ain't being filled and it looks like it doesn't even try to read the file. It instantly crashes.
Some information about the file I try to read:

It has 154k rows
It has 114 columns
The size is 90mb

If I take a subset of 50k rows of this, it doesn't crash.
Though it says that TotalRows is 2536.
At first I though the file was corrupt, but thats not the case since this exact same code works on the client with the exact same file.
If I take a subset of 2500 rows all goes well and there are now problems.
If I take a subset of 2600 rows (doesn't matter which rows) the row count is still 2536.
My questions:

What is going wrong?
Who is responsible for the error and the incorrect results?
Why does it work on the client, but not on my server (same machine!)
Why doesn't it crash with a smaller file?

Need more information? Please leave a comment.
Update 1:
Both the client and the server run as 32 bit applications.
Comment: Quick question; does the server run in 32 bit mode; while the client runs in 64 bit mode?
Answer: Have the same problem. I am trying to read excel file with 30k rows via web site.
But I only take a subset of 8007 rows.
I found that if I change Application Pool Identity to Administrator instead of Network service then all is ok. Also if I converted my excel file to .xls Jet Provider can read 30k rows too.
Then I look through the forums and found that and try my code with ExtendedProperties parameter IMEX=1 and all 30k rows was read.
Comment: That is indeed the same problem I have. I will try your suggestion in a few days.
Comment: Then I look through the forums and found that and try my code with ExtendedProperties parameter IMEX=1 and all 30k rows was read.


Rotten eggs smell in house

Question: We bought a 3rd floor apartment in Italy (highest floor) a few years ago and use it as a holiday home. We've had no issues for about 3 years and suddenly we started getting the smell of rotten eggs at the entrance to the apartment. We've got someone coming in regularly and ensuring the water traps are full every week. The smell just doesn't seem to go and peaks at about 4am in the morning. I can't localise it to any bathroom or the kitchen or the HVAC system. we've had an army of plumbers come and go and no one seems to have a solution. As mentioned the smell is at it's worst at the entrance to the apartment and maybe this is because we detect it coming in from outside the house. Any help is appreciated.
Comment: Something hidden and rotting?
Answer: Some people describe the smell of the additive that they put in natural gas as a "rotten eggs smell". I am not sure if they use such additive in natural gas in Italy but if so then you may want to consider that this smell is the accumulated gas from a gas leak someplace.

Rotten eggs smell in house


Using a Variable as a Property in PowerShell

Question: A bit of a PowerShell neophyte here, so please be kind. I am creating a PS script which is helping me to document my environment. What I am trying to do is get the names of all of an object's properties and populate an XML document with the property names and corresponding values. For example:
PS C:\> $stuff = Get-SomeStuff
PS C:\> $stuff
Name: foo
Version: 1.0

The output XML would look like this:
<rootNode>
    <stuff>
        <Name>foo</Name>
        <Version>1.0</Version>
    </stuff>
</rootNode>

Essentially I want to use the $stuff property names to substitute for the properties when retrieving the object properties. Essentially I need to dynamically substitute the property name with the extracted name. My code looks like this:
$stuff = Get-SomeStuff
CreateXML $rootnode,"stuff",$stuff

Function CreateXML ($rootNode, $nodeName, $category){
    $subRootNode = $xml.CreateElement($nodeName)
    $catProps = $stuff | Get-Member -MemberType Property | Select -ExpandProperty Name
    foreach ($prop in $catProps){
        $newNode = $xml.CreateElement($prop)
        $newNode.Text = $category.{$prop} #--- THIS IS THE LINE CAUSING PROBLEMS
        $subRootNode.AppendChild($newNode)
    }
$rootNode.AppendChild($subRootNode)
}

Any help is greatly appreciated, as there are thousands of properties I have to capture across multiple nodes.
Comment: What is `Get-SomeStuff`? And what problems exactly does `$category.{$prop}` cause?
Comment: Maybe I'm just missing it, but where does $category come from?
Comment: Actually, it's easier than you're trying.  $category.$prop should work.
Comment: Get-SomeStuff was just a dummy cmdlet to simplify the explanation. In terms of the problem it causes, it doesn't work. I was able to establish that the output of doing it that way would dump property typing, not the property itself.
Comment: Mike, I tried that originally but nothing gets sent through the output.
Answer: Try this way:
[xml]$xml = '<rootNode></rootNode>'

$stuff | foreach {

    $node = $xml.CreateElement('stuff')

    $_.psobject.properties | foreach{
        $prop = $xml.CreateElement($_.Name)
        $prop.InnerText = $_.value
        $node.AppendChild($prop)
    }

    $xml.DocumentElement.AppendChild($node)

}

$xml


openAI gym save data as times series

Question: The openAI gym environments have the capability to print results to the screen and also render video. Is there a existing command or a wrapper/monitor that will save the time series data for the state and the actions? I would like to analyze the performance in the time-frequency domain.
I guess I could write the data to a file each time the animation is updated, but curious how others do this.
Answer: What I found is this:
Gym wrapper which saves video and episode summary here
Code for how to use the wrapper here
If you also need to save all actions and information from each episode, I think you will have to create your own script.

openAI gym save data as times series


What is the definition of "high-capacity cnn" or "high-capacity architecture"?

Question: I found the phrase "high-capacity cnn" in these two papers:
1.Rich feature hierarchies for accurate object detection and semantic segmentation
2.Region-based Convolutional Networks for Accurate Object Detection and Segmentation
I've searched it up on google but I can't seem to find a good one.
Comment: See also: ['What is the "capacity" of a machine learning model?'](https://stats.stackexchange.com/q/312424) on Cross Validated.
Answer: This usually refers to the complexity of the underlying pattern that the neural network is able to learn. Usually going deep increases the capacity of the neural network by increasing the number of model parameters which means it can fit more complex functions. However, increasing  capacity by going deep also increases your chance of over-fitting and issues such as regularisation becomes important. It usually also means you need to increase the number of training samples.
Comment: I suppose that Residual Nets is the way how one should go deeper with increasing performance.
Comment: This term is abused and used quite loosely but typically the capacity refers to the capacity to explore the function space. This is usually correlated with the depth of the NN. So usually `deep` neural networks are high capacity. If by `large`, you mean a large number of layers, than yes.
Comment: So, is this has the same meaning as "large cnn model"?


Vega-lite reference line label for today's date

Question: I have a timeline bubble chart (shown with dummy data) with a reference line for the current date.
I want to add a label for the reference line that just says "today's date". When I try to add one it adds a label with today's date to every bubble. I would like a label for the reference line on top where it would be readable.
Here is my code:
<code>{
  "$schema": "https://vega.github.io/schema/vega-lite/v5.json",
  "data": {"name": "dataset"},
  "width": 950,
  "height": 400,
  "transform": [
    {
      "calculate": "now()",
      "as": "today"
    }
  ],
  "encoding": {
    "x": {
      "field": "Date",
      "type": "temporal",
      "axis": {
        "grid": false,
        "format": "Q%q %Y"
      }
    },
    "y": {
      "field": "Prob",
      "type": "quantitative"
    }
  },
  "layer": [
    {
      "mark": {
        "type": "circle",
        "opacity": 0.8,
        "stroke": "black",
        "strokeWidth": 1
      },
      "encoding": {
        "size": {
          "field": "Amount",
          "type": "quantitative"
        },
        "color": {
          "field": "Group",
          "type": "nominal"
        }
      }
    },
    {
      "mark": {
        "type": "circle",
        "opacity": 0.8,
        "stroke": "black",
        "strokeWidth": 1
      },
      "encoding": {
        "size": {
          "field": "Amount",
          "type": "quantitative",
          "scale": {"rangeMax": 1000}
        },
        "color": {
          "field": "Group",
          "type": "nominal"
        }
      }
    },
    {
      "mark": {
        "type": "rule",
        "opacity": 0.6
      },
      "encoding": {
        "x": {
          "field": "today",
          "type": "temporal"
        },
        "size": {"value": 1},
        "color": {"value": "grey"}
      }
    }
  ]
}
</code>
I tried adding this to the layer and of course it added todays date to each bubble instead of the reference line:
<code>{
          "mark": "text",
          "encoding": {
            "text": {
              "field": "today",
              "type": "temporal"
            }
          }
        }
</code>
Thanks!!
Answer: I was able to figure it out. I had to put this in a layer within a layer that contained just the rule for todays date and the text for todays date.
<code>   {
          "mark": {
            "type": "text",
            "align": "left",
            "baseline": "bottom",
            "dx":-15
          },
          "encoding": {
            "text": {"value": "Today"},
            "x": {
              "field": "today",
              "type": "temporal"
            },
            "y": {"value": 0}
          }
        }
</code>


C# get data from database

Question: I need to enhance a function of C# code. I am new to C# but I have strong java background.
My job is to write a new query, like JDBC,  to get data from database.
In the method below, I didn't see any SQL query.
what does this line mean ? is this similar to Hibernate hql ?
from p in Session.Query<MyObject>() select p

Thanks
code:
 public IPagingList<MyObject> ReadMyObjectItems(int start, int limit, IList<Filter> filters)
        {

            var criteria = Session.CreateCriteria<MyObject>();

            if (limit != -1)
            {
                criteria.SetMaxResults(limit);
                criteria.SetFirstResult(start);
            }

            if (filters != null)
            {
                foreach (var filter in filters)
                {
                    criteria.Add(Restrictions.InsensitiveLike(filter.Field, "%" + filter.Value + "%"));
                }
            }

            IList<MyObject> report = criteria.List<MyObject>();

            int total = (from p in Session.Query<MyObject>() select p).Count();

            var pagedResults = new PagingList<MyObject> { List = report, Total = total };

            return pagedResults;

        }

Comment: It's similar in concept to hql, to find more information on this, you'll want to look up linq to nhibernate or nhibernate linq provider.
Answer: It seems that project is using an ORM like NHibernate. You can get more details here : http://nhibernate.info
Answer: (from p in Session.Query<MyObject>() select p).Count();
We are simply getting a count of all the objects.
Refactor this to
Session.Query<MyObject>().Count().  It's easier to read and in this case LINQ is unnecessary.
Answer: It's Linq syntax. A powerful form of querying incorporated into .Net and different .Net frameworks.
In your case it seems you are using NHibernate and that line is using NHibernate Linq. (But the surrounding code is using Criteria.)
For composing queries in NHibernate you have the options of using

Linq
HQL
Criteria

which all have different pros and cons.
Either will be translated into SQL by NHibernate. The actual result will be fetched when you try to access it such as for instance reading an item in the result or converting the result to a List etc.

C# get data from database


Lemma about direct sum, missing step

Question: Lemma
If $V=V_1\oplus V_2$, and $W$ subspace of $V$, then $W=(W\cap V_1)\oplus(W\cap V_2)$ if and only if there is a subset $S\subset W$ such that $W=\text{span}(S)$ and $S=(S\cap V_1)\cup(S\cap V_2)$.
Proof
$\implies$: $W=(W\cap V_1)\oplus(W\cap V_2)$, thus any vector $w\in W$ can be expressed as $w=w_1+w_2$, where $w_1\in W\cap V_1$ and $w_2\in W\cap V_2$. Consider any spanning set of $W$, $R=\{w_k\mid k\in K\}$. Again, $w_k=w_{k,1}+w_{k,2}$. We define $S=\{w_{k,1}\mid k\in K\}\cup \{w_{k,2}\mid k\in K\}$. Clearly $\langle S\rangle=W$. Additionally, $(S\cap V_1)\cup(S\cap V_2)=\{w_{k,1}\mid k\in K\}\cup \{w_{k,2}\mid k\in K\}=S$.
$\impliedby$: From $S=(S\cap V_1)\cup(S\cap V_2)$ follows that, if $0\neq w\in S$, then either $w\in V_1$ or $w\in V_2$ ($V=V_1\oplus V_2$ implies $V_1\cap V_2=\{0\}$). We define $S_1:=S\cap V_1$ and $S_2:=S\cap V_2$. Any vector $w\in W$ can be expressed as $w=w_1+\cdots+w_m+w'_1+\cdots+w'_n$, where $w_i\in S_1$ and $w'_i\in S_2$. $w_1+\cdots+w_m\in\langle S_1\rangle$ and $w'_1+\cdots+w'_n\in\langle S_2\rangle$. Now $\langle S_1\rangle=W\cap V_1$ and $\langle S_2\rangle=W\cap V_2$ ($\color{red}{why?}$), therefore $(W\cap V_1)\oplus(W\cap V_2)=W$. $\tag*{$\square$}$

$\color{red}{why?}$ Clearly $\langle S_1\rangle\subset W\cap V_1$
Answer: That is because $V_1$ and $V_2$ are in direct sum, and the elements of $S$ which are not in $V_1$ are all in $V_2$.

Edit: pick $v\in W\cap V_1$. Since $W=$ Span $S$, and since $S=S_1\cup S_2$, $v$ can be written $v_1+v_2$ with $v_1\in \left\langle S_1\right\rangle\subset V_1$ and $v_2\in \left\langle S_2\right\rangle\subset V_2$.
Now $v-v_1\in V_1\cap V_2$, therefore $v=v_1$.
Comment: Thank you for your reply. I used the fact that the elements of $S$ are either in $V_1$ or in $V_2$ previously in the proof. Now the question is why $\langle S_1\rangle=W\cap V_1$ and particularly why $v\in W\cap V_1$ implies $v\in\langle S_1\rangle$. I'm not able to get the connection so directly.
Comment: @LiPo I understood your question. What is not clear in my answer?
Comment: you speak about $S$, I'm speaking about $\langle S_1 \rangle$. I honestly do not see how your answer is connected with my question (the connection with the rest is clear).
Comment: @LiPo I elaborated a bit, is it clearer now?
Comment: Thank you! I needed some time... now it is very clear

Lemma about direct sum, missing step


What is this white bar on my door?

Question: My door has this odd looking bar with two movable parts to it and I'm trying to figure out what it is and what purpose it serves.
Comment: It looks like ventilation, but what is on the other side
Comment: @crip659 My first thought as well, but I'd expect any kind of curtain mount to be at least as wide as the window if not wider.  This one is considerably shorter, and would leave big gaps on both sides.
Comment: The position would seem to be for a curtain/blind/shade, but was removed from the holder/rod.
Comment: Are there any features on the outside of the door in this location? Holes? Hardware? A grille or a slot?
Comment: the bottom picture shows ventilation holes
Comment: What parts are moveable?
Answer: It's a trickle vent. In the UK it is mandatory to have the capability to provide continuous room ventilation without having to open a window or door. The standard way of doing this is with trickle vents such as this installed in windows and doors (or their frames)
Your additional picture clearly shows two independent shutters to control the air flow. Probably a bit over-elaborate - I would suggest a single control flap is adequate.
There will almost certainly be a similar component on the outside of the door, with a grill or screen to reduce insect ingress.
Comment: One of their main purposes is to prevent the build-up of condensation inside the home, which is often a side-effect of a well-insulated building in the UK.
Comment: It certainly can occur in a well-insulated but poorly ventilated building, but in the UK the most common cause is poor insulation (causing cold spots) coupled with poor ventilation (causing high humidity)
Comment: One of my doors has a pair of flaps.  I'm not sure if it's coincidence but the trickle is more of a draught on this one compared to the ones over my windows.  Perhaps they did intend you to be able to turn it down. I think about the airflow paths and my extractors so don't open all of mine

What is this white bar on my door?


Asynchronous API

Question: Given that OpenCL is meant to be an API for heterogeneous programming, it by almost definition has a huge latency penalty associated with it. Therefore there MUST be an asynchronous API for it.
I am however finding it difficult to find the asynchronous API in OpenCL.net. I have found the OpenCl.Net.Event struct, which seems to be an out parameter in most API calls. However I can't find anyway to associate a callback on the event, as it seems clSetEventCallback is missing from opencl.net.
Does anyone know how to await an asynchronous operation in opencl.net?
Comment: For example in OpenCL you will need to load your data into memory of the target `device`. This is done by enqueuing a load memory operation. The sample code shows how to do this synchronously (by setting async false, and ignoring the `out` `Event` `object`). From an implementation point of view, loading data onto the GPU is "slow" in that latency is high (even if we are just taking into account GDDR5 latencies). When we have hundreds of round trips to the GPU via the PCI-E bus, we lose all performance gains. Thus I want to be able to enqueue operations and be notified of completion.
Comment: Could this be because OpenCl.Net is a wrapper for OpenCl 1.0? The method `clSetEventCallback` only appeared in OpenCl 1.1 I believe.
Comment: What do you mean by latency? Is it about the time the function calls block while waiting for results?
Comment: I'm not very familiar with openCl but isn't the batch processing of openCl we are talkingn about? What you want is to spend as much time as possible queuing data and as little time as possible waiting for results (or anything else) right?
Comment: @Eric Batch processing is certainly something worth doing. But given that there are several operations (loading the data/loading the kernal (compuation)/flushing the operation/waiting for completion/exporting the data back to RAM) that need to be done to get computation to happen async is still important.
Comment: @Eric Just so that you know. I want to extend [GpuLinq](https://github.com/nessos/GpuLinq/blob/gpu/tests/GpuLinq.Tests.CSharp/packages.config) to both support batch processing and asynchronous processing. At the moment async seems easier.
Answer: I don't know much about OpenCL.net, but isn't the CommandQueue what you are looking for? You can enqueue all your aynch tasks a fait with the Finish command until all tasks are finished?
For example here: GPGPU image processing basics using OpenCL.NET under The image processing part
For clSetEventCallback i only found clFinish or clWaitForEvents.
Refering to your statement:

as it seems clSetEventCallback is missing from opencl.net

I could not find any way to do what you want, sorry.
EDIT:
This seems to be very intestring: Google-Code / GPUTracer. You should take a look at OpenCL.cs and Event.cs. I think they solved your problem.
Comment: @Aron ok, now i understand and updated my post, but could not found any solution with the curren OPenCL.Net version, sorry.
Comment: Unfortunately this is not what I am looking for. I am looking for how to use those command with `Blocking` set to `false` which is the opposite of every tutorial I found so far. This tutorial is for doing blocking/synchronous API.
Comment: What is with this: https://www.khronos.org/registry/cl/sdk/1.1/docs/man/xhtml/clFinish.html (clFinish)? Sorry if i'm completly wrong, just trying to help :)
Comment: "Blocks until all previously queued OpenCL commands in a command-queue are issued to the associated device and have completed." Which by definition is the OPPOSITE of asynchronous.
Comment: Ok, but then i do not understand this part of your question: `Does anyone know how to await an asynchronous operation in opencl.net?`
Comment: Ah you are correct. I should have clarified, but I was using the C#5 definition of the `await` keyword, which is a non-blocking call. I was hoping to convert the API to work with C#5 async/await.
Comment: @Aron i found something else, hope it helps.

Asynchronous API