Q:

android shell commands getting the result

I work on an application that can make ping or traceroute requests from the android shell and my application reads the result and post it to the user. My problem is that I can not get the whole result (message) from the command. For example, the traceroute displays  the initial message just before showing the HOPS and ping only works for 1 packet properly. Otherwise (for many packets) I get the initial part of ping request and not the results.
I have a rooted device and installed busybox in order to have traceroute command.
The code is the following
    package com.example.commandshelltest;

import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.TextView;

public class MainActivity extends Activity {

    TextView tv1;
    String out = new String();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);
    String result=execute_reboot();
    TextView tv1=(TextView)findViewById(R.id.textView1);
    //tv1.setText(Integer.toString(result.length())); // i can see that while increasing the number of icmp packets in ping the length stays the same
    tv1.setText(result);

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    String execute_reboot()
    {
        Process process1;
        try {
            int BUFF_LEN =1024;
            process1=Runtime.getRuntime().exec("su");
              DataOutputStream os =
                  new DataOutputStream(process1.getOutputStream());
                //os.writeBytes("traceroute 8.8.8.8\n");
                os.writeBytes("ping -c 1 8.8.8.8\n");
                os.flush();
                InputStream stdout = process1.getInputStream();
                byte[] buffer = new byte[BUFF_LEN];
                int read;

                while((read=stdout.read(buffer))>0)
                while(true){
                    read = stdout.read(buffer);
                    out += new String(buffer, 0, read);
                    if(read<BUFF_LEN){
                        //we have read everything
                        break;
                    }
                }

                  os.writeBytes("exit\n");
                  os.flush();

                process1.waitFor();

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return out;

    }

}

A:

For everyone having the same problem.... I used as a code the example from Run shell commands from android program
The use of threads and sleep time solved the problem for me
public void runAsRoot(String[] cmds) throws Exception {
        Process p = Runtime.getRuntime().exec("su");
        DataOutputStream os = new DataOutputStream(p.getOutputStream());
        InputStream is = p.getInputStream();
        for (String tmpCmd : cmds) {
            os.writeBytes(tmpCmd+"\n");
            int readed = 0;
            byte[] buff = new byte[4096];
            boolean cmdRequiresAnOutput = true;
            if (cmdRequiresAnOutput) {
                while( is.available() <= 0) {
                    try { Thread.sleep(5000); } catch(Exception ex) {}
                }

                while( is.available() > 0) {
                    readed = is.read(buff);
                    if ( readed <= 0 ) break;
                    String seg = new String(buff,0,readed);
                    result=seg; //result is a string to show in textview
                }
            }
        }
        os.writeBytes("exit\n");
        os.flush();

the important part is the Thread.sleep(5000);
For "ls" the sleep time is not important. But for commands like ping or traceroute you need time and you have to wait for the results, hence 5000ms=5seconds is enough to get a response for a ping HOP.


Q:

Horizontally align rows in multiple tables using web user control

I need to align rows in different tables that are layed out horizontally.  I'd prefer to put the html code in a single web user control so I can create as many instances of that control as I want and lay them out horizontally.  The problem is, the text in the rows needs to wrap.  So some rows may expand vertically and some may not (see the example below).  When that happens, the rows in the other tables aren't aligned horizontally.  I know I can accomplish all this by using a single table, but that would mean I'd have to duplicate the name, address and phone html code instead of dynamically creating new instances of my user control (in reality there are many more fields than this, but I'm keeping it simple).  Is there any way to do this whether with div's, tables or something else?
Here's the problem:  Mary Jane's address field expands 2 lines, causing her phone field to not align properly with John's and Bob's.
Name:  John Doe           Name: Mary Jane                   Name: Bob Smith
Address: 123 broadway     Address: Some really long address Address: Short address
Phone: 123-456            that takes up multiple lines      Phone: 111-2222
                          Phone: 456-789
I'm not restricted in any way how to do this (other than using asp.net), but I'd prefer to use a single web control that I instantiate X times at design time (in this example, it's 3 times).  I'm using VS2008, and .Net 3.5

A:

Just so everyone knows, this is possible.  I finished the solution using jquery and it works pretty well.  I assigned each table a specific css class and used that to identify which tables need to be resized (don't want to use an id since each one must be unique).  It works in the 4 major browsers.  For IE7 make sure to add a space in the empty cells for this to work.  Here's the Javascript:
function ResizeTableRows() {
    // select tables by css class name using jquery
    var tables = $('.myCssClassName');

    // all tables should have the save number of rows, so just use the first one
    var totalRows = tables[0].rows.length;

    for (var rowNumber = 0; rowNumber < totalRows; rowNumber++) {
        var maxRowHeight = GetMaxRowHeight(tables, rowNumber);

        for (var i = 0; i < tables.length; i++) {
            if (maxRowHeight > 0) {
                tables[i].rows[rowNumber].height = maxRowHeight;
                SetCellHeight(tables[i].rows[rowNumber].cells, maxRowHeight);
            }
        }
    }
}

function GetMaxRowHeight(tables, rowNumber) {
    var maxRowHeight = 0;

    for (var i = 0; i < tables.length; i++) {
        var row1 = tables[i].rows[rowNumber];
        var cell1 = row1.cells[0];
        var rowHeight = row1.clientHeight;

        if (rowHeight <= 0) {
            rowHeight = row1.height;
        }
        if (rowHeight <= 0) {
            rowHeight = cell1.clientHeight;
        }

        if (rowHeight > maxRowHeight) {
            maxRowHeight = rowHeight;
        }
    }
    return maxRowHeight;
}

function SetCellHeight(cells, maxRowHeight) {
    for (var i = 0; i < cells.length; i++) {
        cells[i].height = maxRowHeight;
    }
}

Here's the code to start the process.  Add it to the main page and not the web control (if you're using .net)
<script type="text/javascript">
    // runs automatically after this page has been loaded and rendered
    $(document).ready(function() {
        ResizeTableRows();
    });
</script>


Q:

absolute positioning css with height 100% element?

I have elements positioned absolutely on a page, but within those elements I will have dynamic content nested. If the content grows, my elements outside are absolute positioned so they don't move and obstruct the content.
Is there any tricks around this?
Can I get jquery to add some pixels to 'top' of my positioned elements offsetting the #ContainerDiv?

A:

First off I don't suggest using Javascript to fix a layout bug, unless it's with dynamic content anyway.
Now, what kind of a layout are you trying to go for? If you're trying to do 100% height columns there are various layout tutorials on how to achieve this purely with CSS (and often with a repeating background for the column). You can find them simply by searching for 100% height. What you're going to end up doing is hacking your CSS for different browsers to get them to act like they support min-height: 100%;


Q:

Failed lock verification

I've been getting this error every time my app starts and someone told me that it has something to do with synchronized in java. However, I'm am not using that directly (though pretty much every library in my app does). I don't know where to start and what code I should be posting. Any ideas?
Here you can see some of my logs with a bunch of different libraries complaining:
08-06 20:04:52.287 14696-14696/com.supercilex.robotscouter.debug I/art: Late-enabling -Xcheck:jni
08-06 20:04:52.323 14696-14705/com.supercilex.robotscouter.debug E/art: Failed sending reply to debugger: Broken pipe
08-06 20:04:52.323 14696-14705/com.supercilex.robotscouter.debug I/art: Debugger is no longer active
08-06 20:04:52.323 14696-14705/com.supercilex.robotscouter.debug I/art: Starting a blocking GC Instrumentation
08-06 20:04:52.386 14696-14696/com.supercilex.robotscouter.debug W/System: ClassLoader referenced unknown path: /data/app/com.supercilex.robotscouter.debug-2/lib/arm64
08-06 20:04:55.309 14696-14696/com.supercilex.robotscouter.debug W/System: ClassLoader referenced unknown path: /data/app/com.supercilex.robotscouter.debug-2/lib/arm64
08-06 20:04:55.372 14696-14696/com.supercilex.robotscouter.debug W/art: Class com.google.firebase.FirebaseApp failed lock verification and will run slower.
08-06 20:04:55.372 14696-14696/com.supercilex.robotscouter.debug W/art: Common causes for lock verification issues are non-optimized dex code
08-06 20:04:55.372 14696-14696/com.supercilex.robotscouter.debug W/art: and incorrect proguard optimizations.
08-06 20:04:55.381 14696-14696/com.supercilex.robotscouter.debug W/art: Class android.support.v4.util.SimpleArrayMap failed lock verification and will run slower.
08-06 20:04:55.454 14696-14696/com.supercilex.robotscouter.debug W/art: Class com.google.android.gms.common.api.GoogleApiClient failed lock verification and will run slower.
08-06 20:04:55.474 14696-14696/com.supercilex.robotscouter.debug W/art: Class com.google.android.gms.internal.zzqc failed lock verification and will run slower.
08-06 20:04:55.507 14696-14965/com.supercilex.robotscouter.debug W/art: Class com.google.android.gms.internal.zzqc$zzc failed lock verification and will run slower.
08-06 20:04:55.519 14696-14965/com.supercilex.robotscouter.debug W/art: Class com.google.android.gms.common.api.GoogleApiClient$Builder failed lock verification and will run slower.
08-06 20:04:55.533 14696-14965/com.supercilex.robotscouter.debug W/art: Class com.google.android.gms.common.internal.zzd failed lock verification and will run slower.
08-06 20:04:55.540 14696-14965/com.supercilex.robotscouter.debug W/art: Class com.google.android.gms.common.internal.zzm failed lock verification and will run slower.
08-06 20:04:55.542 14696-14965/com.supercilex.robotscouter.debug W/art: Class com.google.android.gms.common.internal.zzn failed lock verification and will run slower.
08-06 20:04:55.548 14696-14965/com.supercilex.robotscouter.debug W/art: Class com.google.android.gms.common.stats.zzb failed lock verification and will run slower.
08-06 20:04:55.557 14696-14965/com.supercilex.robotscouter.debug W/art: Class com.google.android.gms.internal.zzsb failed lock verification and will run slower.
08-06 20:04:55.558 14696-14965/com.supercilex.robotscouter.debug W/DynamiteModule: Local module descriptor class for com.google.firebase.auth not found.
08-06 20:04:55.561 14696-14965/com.supercilex.robotscouter.debug W/art: Class com.google.android.gms.common.internal.zzz failed lock verification and will run slower.
08-06 20:04:55.566 14696-14965/com.supercilex.robotscouter.debug W/art: Class com.google.android.gms.common.zzf failed lock verification and will run slower.
08-06 20:04:55.567 14696-14965/com.supercilex.robotscouter.debug W/art: Class com.google.android.gms.common.zzd$zzc failed lock verification and will run slower.
08-06 20:04:55.571 14696-14965/com.supercilex.robotscouter.debug W/art: Class com.google.android.gms.common.internal.zzd$zzh failed lock verification and will run slower.

A:

It happens to me on a Nexus 6P and Android 7.0 final release. There is an opened bug for this issue: https://code.google.com/p/android/issues/detail?id=219490


Q:

Why isn't the CSS file showing up?

I've double checked my syntax for linking the CSS file in the  of my HTML file, and it all looks correct to me. And when I view the page source of my HTML page, it does indeed to be linking correctly to the CSS page. But none of the styling seems to be showing up. I'm fairly certain that the linking of the CSS file is fine, but I can't understand why none of the changes are appearing.
HTML FILE:
<!DOCTYPE html>

    <title>Midterm: Hangman</title>

    <link rel="stylesheet" type="type/css" href="hangman.css">

Hangman

    <input id="guessedLetter" type="text" maxlength="1" minlength="1" placeholder="Guess a letter" />

    <button type="button" onclick="javascript:compareLetter()">Guess!</button>

    <button type="button" onclick="javascript:hideWord()">Restart</button>

Instructions

Put some instructions here!

CSS FILE:
body {
    background: #2C2A30;
}

button[type=button] {
    background: #D94C47;
    font-family: Arial;
    padding: 5px 5px;
    font-size: 25px;
    border-radius: 5px;
    padding: 7px 12px;
    border: 1px solid #D94C47;
    color: white;
    font-weight: bold;
}

button[type=button]:hover {
    background: #FF7A61;
    border: 1px solid #FF7A61;
    color: #2C2A30;
}

SCREENSHOT OF CHROME DEVELOPER TOOL:

SCREENSHOT OF FOLDER STRUCTURE:

A:

You should be using <link rel="stylesheet" href="hangman.css">.

A:

You have a typo:
<link rel="stylesheet" type="type/css" href="hangman.css">

should be:
<link rel="stylesheet" type="text/css" href="hangman.css">

Note the type --> text.
Additionally, in HTML5 you don't need the type attribute at all, so you can just have:
<link rel="stylesheet" href="hangman.css">


Q:

*new title: JButton array scope (it was:change color of button with button name)

How can is alter the color of the correct button?
It is for a small application, this app has 5 buttons from a array.(the name's are a,b,c,d,e)
The appearence of the buttons have to alter (change color) when i type in a number in a Jtextfield.
I added a name to each button:
knop = new JButton(Titel[i]);
            knop.setName(tel[i]);

Here i get the text:
public void actionPerformed(ActionEvent e) {
        String invoer = antwoord.getText();

        try
        {
            int welke = Integer.parseInt(invoer);

            if  (welke-1 >0 && welke-1<5)
            {
                vraag.setText("Goeie keus!");
                if (welke == 1){

                    knop.setBackground(Color.BLUE);

                }
                knop.setBackground(Color.red);
            }

But now it only changes the last button to red which is created bij the array.
So the question can I select a button by its name?
So  if (input = 1) alter button 1 to green. in stead of only button 5.
I have tried de solution of gile, but i can't get it to work:
I get every time a: "AWT-EventQueue-0" java.lang.NullPointerException"
package kiesknop;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;

//public class Paneel extends JApplet
public class Paneel extends JFrame

{

private JPanel paneel;
private JButton knop;
public  JTextField antwoord;
private JLabel vraag;
public JButton[] knops;

public Paneel() {

    int [][] numButtons = new int [5][4];
    numButtons[0][0] = 50;
    numButtons[0][1] = 10;
    numButtons[0][2] = 10;
    numButtons[0][3] = 10;

    numButtons[1][0] = 100;
    numButtons[1][1] = 10;
    numButtons[1][2] = 30;
    numButtons[1][3] = 30;

    numButtons[2][0] = 200;
    numButtons[2][1] = 10;
    numButtons[2][2] = 50;
    numButtons[2][3] = 50;

    numButtons[3][0] = 300;
    numButtons[3][1] = 10;
    numButtons[3][2] = 100;
    numButtons[3][3] = 100;

    numButtons[4][0] = 500;
    numButtons[4][1] = 10;
    numButtons[4][2] = 200;
    numButtons[4][3] = 200;

    String [] Titel = new String [5];

    Titel [0] = "*";
    Titel [1] = "**";
    Titel [2] = "***";
    Titel [3] = "****";
    Titel [4] = "*****";

    String [] tel = new String [5];
    tel [0] = "a";
    tel [1] = "b";
    tel [2] = "c";
    tel [3] = "d";
    tel [4] = "e";

paneel = new JPanel();

JButton[] knops = new JButton[5];

for (int i = 0; i < 5; i++)
        {
            knops[i] = new JButton(Titel[i]);
            knops[i].setName (tel[i]);
            knops[i].setBounds(numButtons[i][0],numButtons[i][1], numButtons[i][2], numButtons[i][3]);
            knops[i].addActionListener(new KnopHandler());
        }

for (int i = 0; i < 5; i++)
{
    paneel.add(knops[i]);

}

vraag = new JLabel("Welke knop grootte vind je het mooist?");
vraag.setBounds(100, 400, 250, 20);

antwoord = new JTextField(20);
antwoord.setBounds(500, 400, 100, 20);
antwoord.setEditable(true);
antwoord.addActionListener(new AntwoordHandler());

paneel.add (vraag);
paneel.add (antwoord);

setContentPane (paneel);

    }
public class KnopHandler implements ActionListener  {

    public void actionPerformed(ActionEvent e) {

        JButton o = (JButton)e.getSource();
        String Text = o.getText();
        String name = o.getName();
        String Label =o.getLabel();

        System.out.println("knop gedrukt");
        System.out.println(Text);
        System.out.println(name);
        System.out.println(Label);
    }
}

class AntwoordHandler  implements ActionListener  {

    public void actionPerformed(ActionEvent e) {
        String invoer = antwoord.getText();

        try
        {
            int welke = Integer.parseInt(invoer);

            if  (welke >0 && welke<5)
            {
                vraag.setText("Goeie keus!");
                if(welke == 1)// knops[welke].setBackground(Color.BLUE);
                System.out.println(knops[1]);

                if(welke == 2) knops[welke].setBackground(Color.BLUE);

                if(welke == 3) knops[welke].setBackground(Color.BLUE);

                if(welke == 4) knops[welke].setBackground(Color.BLUE);

                if(welke == 5) knops[welke].setBackground(Color.BLUE);
                }

            else vraag.setText("Geen geldige invoer!");
            }

            catch( NumberFormatException nfe)
            {
                if( invoer.equals("")) vraag.setText("Niets ingevuld!");
                    else
                vraag.setText("Alleen nummers invoeren!");
            }

        }
    }

public static void main (String arg[])

{

JFrame frame = new Paneel();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(null);
frame.setVisible(true);
frame.setSize(900, 500);

}
}

What am i doing wrong ?

A:

You can put buttons in an array
JButton[] knops = new JButton[5];
...
knops[i] = new JButton(Titel[i]);
...

And then set the background after user entered a number:
if (welke == 1){
    knops[welke].setBackground(Color.GREEN);
}


Q:

What is the CMake equivalent of the GCC -c option?

For example, if I had a makefile that contains this:
dynArray.o: dynArray.c dynArray.h type.h
    gcc -Wall -ansi -c dynArray.c

How would I translate that into a CMakeLists.txt file?

A:

Probably CMake's object libraries would do that, that mean compile objects but not archive them like normal library would.
add_library(<name> OBJECT <src>...)


Q:

Change only method result and class loader NoSuchMethod

We started with one jar with one class with one method like:
boolean foo( int bar ) { ... }

However, the result of this method was useless (in fact, always true) and clients that used this result for anything fails in an error. For this reason, method was changed to:
void foo( int bar ) { ... }

and all items recompiled. Thus, we can assume all users of this jar calls the method as:
foo(14);

none uses the form (and is out of scope for this question if there are someone):
boolean x = foo(14);

Assume none client, new or older, uses the boolean result.
The problem was when, in target systems, the new jar is loaded without upgrading the clients. Not updated clients fails with an exception "NoSuchMethod" when looking for the "foo" method with result "boolean". That is:

client has an statment like "foo(14);" without usage of the method result
client is compiled using the jar with boolean method.
client and library is loaded in target system
library is updated with new jar with void method
client crashes with "NoSuchMethod"

The origin of the problem seems to be that both, Java and C/C++ doesn't allows two methods that differs only in result, but only Java "name mangling" includes the result type in the name that class loader (linker in C/C++) is looking for.
The question is: it is possible to trick in any way the library jar or the class loader to skip  "NoSuchMethod" exception in this scenario?

A:

This behaviour is fully expected. This is because client's compiled classes contain constant pool, which includes symbolic reference to a method.
Let's suppose we have class FooClass with two methods:
public boolean foo1(int bar) {
    return true;
}

public void foo2(int bar) {
    // ...
}

And let's suppose we have another class Main where we invoke both methods:
    FooClass fc = new FooClass();
    fc.foo1(1);
    fc.foo2(1);

If we will disassemble Main.class we will see that method references differ not only in their names, but in returned type (notice (I)Z and (I)V):
     7: astore_1
     8: aload_1
     9: iconst_1
    10: invokevirtual #4                  // Method q42340444/FooClass.foo1:(I)Z
    13: pop
    14: aload_1
    15: iconst_1
    16: invokevirtual #5                  // Method q42340444/FooClass.foo2:(I)V

Where constant pool contains:
   #4 = Methodref          #2.#25         // q42340444/FooClass.foo1:(I)Z
   #5 = Methodref          #2.#26         // q42340444/FooClass.foo2:(I)V

In other words, it preserves original method's return type and looks in linked libraries for exactly same method, which causes NoSuchMethod exception in your case.
More specifically, compiled user classes are linked to FooClass.foo:(I)Z method, while your new library doesn't contain method with such description, but only FooClass.foo:(I)V.
Conclusion: You can not solve this problem without keeping old method signature (may be it is better annotate that method with @Deprecated annotation), or by recompiling client's code.


Q:

How to read XHTML file tags using Objective-C?

I want to read XHTML tags and text separately using objective C.
what approach I have to follow?

A:

Use an XML parser like NSXMLParser.


Q:

Referencing (Using an alias) the value from nested MySQL query in an outer conditional statement

I'm using a nested query to get the value I need from a table that I then need to use in a conditional statement, however, every time I try this I keep on getting an error saying unknown column (format) in the field list
SELECT

(SELECT format FROM competition_stages WHERE comp_id = "5" AND rid = "24") AS format,

a.tie_id, b.name AS team_a, b.team_id AS team_a_id, c.name AS team_b, c.team_id AS team_b_id, SUM(e.bonus) AS team_a_bonus, SUM(f.bonus) AS team_b_bonus,

SUM(CASE
    WHEN (a.team_a = e.team_id AND format = "0") THEN e.score
END) as team_a_agg,

SUM(CASE
    WHEN (a.team_b = f.team_id AND format = "0") THEN f.score
END) as team_b_agg

FROM competition_tie a

INNER JOIN teams b ON (a.team_a = b.team_id)
INNER JOIN teams c ON (a.team_b = c.team_id)

LEFT JOIN fixtures d ON (a.tie_id = d.tie_id)
LEFT JOIN fixture_scores e ON (d.fx_id = e.fx_id AND a.team_a = e.team_id)
LEFT JOIN fixture_scores f ON (d.fx_id = f.fx_id AND a.team_b = f.team_id)

WHERE a.comp_id = "5" AND a.rid = "24" AND a.season_id = "5"

GROUP BY a.tie_id

ORDER BY a.tie_id ASC

I can get the value of the format column in my results when I go through them but it just seems I can't use it within my query to use in.
Thanks for your help!

A:

Instead of using a subquery, simply join the competition_stages table to your query so that you can reference the format column directly. Assuming there is no appearant relation between the competition_stages table and the other tables in the query (at least not from the information on hand), you can just join the table using the two conditions you specified if these conditions would only yield 1 result in the competition_stages table. Something like this:
SELECT cs.format, a.tie_id, ....
FROM competition_tie a ...
INNER JOIN competition_stages cs ON cs.comp_id = "5" AND cs.rid = "24"


Q:

why we can access memory from non paged pool at or above DISPATCH LEVEL

As I know that if IRQL level is dispatch then you can access memory from non paged pool. if we will try to access memory from paged pool.just wanted to know why ?

A:

"why we can access memory from non paged pool at or above DISPATCH LEVEL" is a statement, question is why we cannot access memory from paged pool IRQL >= DISPATCH_LEVEL?
Well...

"Any routine that is running at greater than IRQL APC_LEVEL can
  neither allocate memory from paged pool nor access memory in paged
  pool safely. If a routine running at IRQL greater than APC_LEVEL
  causes a page fault, it is a fatal error."

-- http://msdn.microsoft.com/en-us/library/windows/hardware/ff554368(v=vs.85).aspx
Why is this:
suppose your driver is servicing an interrupt, and while at it, it holds a spin lock. Now, you want to access some data structure that resides on the paged pool and as you are already out of luck, that data is on a page that has been paged-out by the memory manager.
Now, your driver has to wait until the memory manager page-in your data. You are blocking/waiting/sleeping, actually your driver is.
Now, another interrupt occurs, but since you are still waiting for the data to be paged-in, what do you think what will happen now?
Know this,

" Holding a spin lock for an unnecessarily long duration can hurt
  system-wide performance."

as your driver waits longer for something to happen, your kernel will go to freeze.
Also,

"Note that a thread may not block while holding a spinlock, because
  that could cause deadlock. Further, preemption is disabled on a given
  processor while a spinlock is held."

-- https://developer.apple.com/library/mac/documentation/Darwin/Conceptual/KernelProgramming/synchronization/synchronization.html
anyway, read this further:

"Driver code that runs at IRQL > PASSIVE_LEVEL should execute as
  quickly as possible. The higher the IRQL at which a routine runs, the
  more important it is for good overall performance to tune that routine
  to execute as quickly as possible. For example, any driver that calls
  KeRaiseIrql should make the reciprocal call to KeLowerIrql as soon as
  it can."

-- http://msdn.microsoft.com/en-us/library/windows/hardware/ff554368(v=vs.85).aspx
Page fault is an exception that needs to be serviced quickly by the memory manager. While your driver holds spinlock and holds that processor hostage, that processor is as good as dead right now.
MSDN says:

"While a driver routine holds a spin lock, it cannot cause a hardware
  exception or raise a software exception without bringing down the
  system. In other words, a driver's ISR and any SynchCritSection
  routine that the driver supplies in a call to KeSynchronizeExecution
  must not cause a fault or trap, such as a page fault or an arithmetic
  exception, and cannot raise a software exception. A routine that calls
  KeAcquireSpinLock or KeAcquireInStackQueuedSpinLock also cannot cause
  a hardware exception or raise a software exception until it has
  released its executive spin lock and is no longer running at IRQL =
  DISPATCH_LEVEL."

-- http://msdn.microsoft.com/en-us/library/windows/hardware/ff559854(v=vs.85).aspx
All this answers what will happen, or what can happen. As to answer Why we cannot use paged memory above or at DISPATCH_LEVEL:

It leads to deadlock most of the time, which in kernel world is kernel-crash.
It will induce latency in kernel, which is bad.
Refer to 1, that's kind of important.

I have tried to fetch as much relevant information as possible, if you are still not sold, try reading on spin-locks, re-entrant functions, interrupt handling, Paging. Try reading for Linux, Windows, and Apple's OS's kernel. They all say same things with varying details.


Q:

Iterating Through Cells in a Powershell [MATH] Function

I'm trying to calculate some basic statistics in PowerShell using [MATH], specifically the Standard Deviation of a group of values in a field named 'td'.
My code currently outputs a number that is much too high to be the standard deviation. For example, in a case where the values in the column have no range (all values were 15), where the Standard Deviation should be zero, the returned value was equal to 15.
which I think may have something to do with incorrect use of $Y in this section of code:
Foreach ($Y in $STDEVInputFile) {
$DevMath += [math]::pow(($STDEVInputFile[$Y].td - $STDEVAVG.Average), 2)

However, I'm not familiar enough with PowerShell to be sure. Would anyone out there be able to show me where I'm going wrong? Here is the full code:
##################################################
#Calculate statistics for TD column in each file

$i = 1

While ($i -le 211) {

#Set the variable to the filename with the iteration number
$filename = "c:\zMFM\z550Output\20dSummer\fixed20dSum550Output$i.csv"

#Check to see if that a file with $filename exists. If not, skip to the next iteration of $i. If so, run the code to collect the statistics for each variable and output them each to a different file
If (Test-Path $filename) {

#Calculate the Standard Deviation
#First get the average of the values in the column
$STDEVInputFile = Import-CSV $filename

#Find the average and count for column 'td'
$STDEVAVG = $STDEVInputFile | Measure-Object td -Average | Select Count, Average
$DevMath = 0

$Y =

# Sum the squares of the differences between each value in the field and the mean
Foreach ($Y in $STDEVInputFile) {
$DevMath += [math]::pow(($STDEVInputFile[$Y].td - $STDEVAVG.Average), 2)

#Divide by the number of samples minus one
$STDEV = [Math]::sqrt($DevMath / ($STDEVAVG.Count-1))

}

#Calculate the basic statistics for column 'td' with the MEASURE-OBJECT cmdlet
$STATS = Import-CSV $Filename |
Measure-Object td -ave -max -min |

#Export the statistics as a CSV
Export-CSV -notype "c:\zMFM\z550Output\20dSummer\tempstats$i.csv"

#Store the values that will go into the final table as variables
$GetColumns = Import-CSV $filename
$VZA = $GetColumns[0].VZA
$VAZ = $GetColumns[0].VAZ

#Import the temporary stats file, append columns and populate them with the declared variables

Import-Csv "c:\zMFM\z550Output\20dSummer\tempstats$i.csv" |
  Select-Object @{Name="VZA";Expression={$VZA}},
                @{Name="VAZ";Expression={$VAZ}},
                @{Name="STDDEV";Expression={$STDEV}},
                Count, Average, Maximum, Minimum, Property |

#Export the $STATS file containing everything you need in the correct folder

Export-CSV -notype "c:\zMFM\z550Output\20dSummer\Statistics_TD_20dSum550_$i.csv"

}
$i++
}

A:

I think:
$DevMath += [math]::pow(($STDEVInputFile[$Y].td - $STDEVAVG.Average), 2)

should be
$DevMath += [math]::pow(($Y.td - $STDEVAVG.Average), 2)

The original $STDEVInputFile[$Y].td part is going to return null/0, so for your example of all 15s in the input, instead of each step doing 15-15=0 squared, you are doing 0-15 = -15 squared.

You may also want to get rid of the $Y= empty line before the foreach loop, as it is(maybe) setting $Y to the output of the whole loop, and if nothing else using that while using $Y inside the loop is confusing.


Q:

ASP.NET DetailsVew rebind the dropdownlist after insert items

I am new to ASP.NET and have been trying to make the dropdownlist works correctly in DetailsView, but no luck so far.  I am getting every close to accomplish this, so much appreciated of someone can help me out here.
An error that I am getting is:

Databinding methods such as Eval(), XPath(), and Bind() can only be
  used in the context of a databound control.

I have this code in my DetailsView:
<EditItemTemplate>
    <asp:DropDownList id="VendorName"
        datasourceid="VendorSqlDataSource"
        AutoPostBack="true"
        datatextfield="VendorName"
        DataValueField="VendorID"
        SelectedValue='<%# Bind("VendorID") %>'
        runat="server"
        OnSelectedIndexChanged="ddlCategory_SelectedIndexChanged" />

    <asp:SqlDataSource ID="VendorSqlDataSource"
        ConnectionString="<%$Connectionstrings:ConnectionString%>"
        SelectCommand="SELECT VendorID, VendorName from MDF_Vendor"
        runat="server">
    </asp:SqlDataSource>
</EditItemTemplate>

<EditItemTemplate>
    <asp:DropDownList id="VendorBUName"
        datasourceid="VendorBUSqlDataSource"
        datatextfield="VendorBUName"
        DataValueField="VendorBUID"
        SelectedValue='<%# Bind("VendorBUID") %>'
        runat="server"/>

    <asp:SqlDataSource ID="VendorBUSqlDataSource"
        runat="server"
        ConnectionString="<%$Connectionstrings:ConnectionString%>"
        selectcommand="SELECT VendorBUID, VendorBUName
                       from MDF_VendorBU
                       Where VendorID = @VendorID"
        <SelectParameters>
            <asp:Parameter Name="VendorID" Type="Int32" />
        </SelectParameters>
    </asp:SqlDataSource>
</EditItemTemplate>

In my code behind list, I have this code to rebuild the list of VendorBUName dropdownlist when VendorName selected.
protected void ddlVendor_SelectedIndexChanged
               (object sender, EventArgs e)
{

    DropDownList ddlVendor =
        (DropDownList)DetailsView1.FindControl("VendorName");
    DropDownList ddlVendorBU =
        (DropDownList)DetailsView1.FindControl("VendorBUName");

    if (ddlVendorBU != null)
    {
        Response.Write("SelectChanged");
        int VendorID = Convert.ToInt32(ddlVendor.SelectedValue.ToString());
        Response.Write("VendorID: " + VendorID);

        ddlVendorBU.Items.Clear();

        string strConn = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
        SqlConnection con = new SqlConnection(strConn);
        SqlCommand cmd = new SqlCommand();
        cmd.Connection = con;
        cmd.CommandType = CommandType.Text;
        cmd.CommandText = "SELECT VendorBUID, VendorBUName FROM dbo.MDF_VendorBU WHERE VendorID = @VendorID";
        cmd.Parameters.AddWithValue("@VendorID", VendorID);
        DataSet objDs = new DataSet();
        SqlDataAdapter dAdapter = new SqlDataAdapter();
        dAdapter.SelectCommand = cmd;
        con.Open();
        dAdapter.Fill(objDs);

        con.Close();

        if (objDs.Tables[0].Rows.Count > 0)
        {
            foreach (DataRow dr in objDs.Tables[0].Rows)
            {
                ddlVendorBU.Items.Insert(0, new ListItem( (dr["VendorBUName"]).ToString(), "-1") );
            }
            ddlVendorBU.DataBind();  //<-- Problem HERE can not rebind it.
        }

    }
}

This is working so far in DetailsView.  I click Edit, these 2 dropdownlists selected the correct value.  When I select another Vendor in VendorName ddl, it refreshes the VendorBUName list.  Great! However, when I try to ddlVendorBU.DataBind(); to rebind the VendorBUName list, it gives the error above.  If removed that, it won't update the record for VendorBUName because is not bound to the field.
I am totally stuck, if someone can please help.  Thanks in advance!

A:

If you use  ddlVendorBU.DataBind(); you must define DataSource property.
If you wish insert Item, you don't need DataBind method.
So
You can try this code without DataBind
foreach (DataRow dr in objDs.Tables[0].Rows)
{
     ddlVendorBU.Items.Insert(0, new ListItem( (dr["VendorBUName"]).ToString(), "-1") );
}


Q:

jQuery - how to detect an option being selected in a select, when it doesn't change the selection

I have a bunch of selects listing PDF files.  When the user chooses a PDF from the select, I display the pdf in the screen.  This is triggered from an event listener on "change blur".
If they then close the div with the pdf in it, and want to open it again, they must select it again from the dropdown.
However, I'm finding that in order to show the pdf again, they need to select a different pdf, then open the select again and choose the one they do want:  in other words, if you open the select, then click "Done" (on mobile) or click on the already-selected option (desktop), then because it hasn't changed, it doesn't trigger showing the PDF.
I thought that adding "blur" to the events being listened for would do it - wouldn't the select closing trigger it's blur event?  But it doesn't seem to help.
This is my code:
$("body").on("change blur", ".pdf-file-select", function(e){
  //get the pdf uri from the selection and show the pdf
});

thanks.
EDIT - on investigation, blur only fires when I click outside the select - it doesn't fire when I close the select.

A:

use the click event instead
$("body").on("click", ".pdf-file-select", function(e){
  //get the pdf uri from the selection and show the pdf
});


Q:

android - MediaCodec record video with timestamp on each video frame

I need to record video with timestamp on each video frame. I see a example in cts which use InputSurace.java and OutputSurface.java to connect Decoder and Encoder to transcode video files. Is it possible to reuse these two android java class to implement a timestamp video recorder?
I try to use OutputSurface as Camera preview output and use InputSurface as MediaCodec Encoder input but sounds like only record 2 or 3 frames then it hang there forever!

A:

Take your time and explore this link to get an idea how to feed the Camera preview into a video file. Once you are confident about the mechanism, you should be able to feed the MediaCodec input surface with some kind of OpenGL magic to put extra graphics on the top of the Camera's preview. I would recommend to tweak the example code's drawExtra() as a start.


Q:

NServicebus Publisher/Distributor Unable to communicate with all subscribers/workers?

We have one distributor/publisher (NSB community version, which is on a domain but recently changed to workgroup mode due to some issues), which communicates to two workers on two different servers (on domain). All of a sudden it is not sending any work to one of the workers where as the worker has sent several acknowledgements which were unacknowledged by the publisher.
Please help - whether this is a bug in NSB host or am i missing something here?

A:

Finally found the issue, it is not related to Nservicebus, rather it is related to network.
The servers were unable to communicate each other due to some security/firewall problems.
Solution is: Adding the host entries of subscribers (worker servers) in the publisher (distributor) has solved the same.


Q:

How do I manage jenkins secret in kubernetes?

Hey I am new to kubernetes and playing around with jenkins deployment. I have deployed jenkins master pod through the deployment.yaml as well service and pvc.yaml.
I set the service as node port and but how do I secure and manage jenkins secret ? Do I need to create some sort of configmap for this ? I usually get jenkins secrets from kubectl logs . Any help or suggestion will be greatly appreciated to make this more secure :)

A:

First let's clear some concepts and background:
Since you are new to kubernetes, I'll help you understand the scenario better and give you suggestions to achieve your goal.

A ConfigMap stores configuration data as key-value pairs. ConfigMap is similar to Secrets, but provides a means of working with strings that don’t contain sensitive information.

I'm posting the description of Configmap to help you understand that it's powerful to handle data but it's not applicable for storing sensitive information, hence will not be mentioned below.

Kubernetes Secrets lets you store and manage sensitive information, such as passwords, OAuth tokens, and ssh keys. Storing confidential information in a Secret is safer and more flexible than putting it verbatim in a Pod definition or in a container image.

Natively, Kubernetes uses secrets to handle objects that store sensitive data and it's authenticated by kubernetes-api, keeping it safe from external access unless it have a valid credential to cluster administration.
By default Jenkins stores the password in Secrets.

Deployment:

This is the 101 guide to deploy Jenkins on Kubernetes

It will show you the best way to extract the admin password extracting from the secret
It will show you how to access Jenkins UI.
The deployment is automated with Helm which is a powerful tool on Kubernetes.

Addressing your Questions:

how do I secure and manage jenkins secret?

The Jenkins secret is secure by kubernetes credentials, only those who have access to the cluster can extract it, so it's relatively safe by default.

You can learn how Kubernetes manages authentication Here.
Using this approach you can manage your users and password from Jenkins UI. You can learn about Jenkins Credentials here.

Any help or suggestion will be greatly appreciated to make this more secure

After gaining some experience with Jenkins and Kubernetes and as your setup grows, you can start using several steps to enhance your overall security. Thus far we relied on the native security tools, but you can consider new approaches for distributed authentication. Here are some guides you can learn more:

Configuring and Securing Credentials in Jenkins
Official Jenkins Credentials Documentation
Using OAuth Credentials
Third-party SSO Login with KeyCloak

If I can help you further let me know in the comments!


Q:

replace two elements in a list with the sum of those two elements?

I have a list:
G[3] = {2, 4, 2, 4, 2, 4, 2, 4, 2, 4}   (there's a 3 in there for the 3rd Prime)
Recursively defined by:
G[2] = {2,4}

G[i_] := Nest[Join[#, G[i - 1]] &, G[i - 1], Prime[i] - 1]

And I would like to transform it into the list
Hsum[3]= {2, 6, 4, 2, 4, 2, 4, 6}

to get the ith element of the second list, I add up elements 1 to i of the original list and test if the sum is = 1 (mod 5) then I replace G[3][[i]] with G[3][[i]]+G[3][[i+1]] and delete element G[3][[i+1]]
So far, all I can get to work is the summing and testing mod some prime.
Hsum[i_] :=
 Table[If[Mod[Sum[G[i][[j]], {j, 1, k}], Prime[i]] == 1,
   G[i][[k]] + G[i][[k - 1]], G[i][[k]]], {k, 1, Length[G[i]]}]

but that doesn't get rid of the unwanted element that has been summed.
Any help would be appreciated!

A:

Try thinking of doing substitutions on a list. You want the beginning of the list and then a couple of elements and then the rest of the list. If the beginning of the list and the next element satisfies a condition then you want the substitution to give you a modified list.
G[2] = {2, 4};
G[i_] := Nest[Join[#, G[i - 1]] &, G[i - 1], Prime[i] - 1];
g3 = G[3];
g3 //. {h__, i_, j_, k___} /; (Mod[Total[{h}]+i, 5] == 1) -> {h, i+j, k}

and that gives you
{2, 6, 4, 2, 4, 2, 4, 6}

Study that until you can see what all the pieces are doing. Look up //. and /; in the help system until you can see why this works. Carefully count the number of _ used in each place and try to understand why that number was used in each position. Note: I assigned your list to g3 instead of trying to work on G[3] to have one less level of subscripting and hopefully make this slightly easier to understand. I always try to start as simply as possible and work up from there. Then test this carefully on larger examples until you are sure it works before trusting it. Pattern matching and substitution can be tricky and error prone at times.


Q:

How do you support PowerShell's -WhatIf & -Confirm parameters in a Cmdlet that calls other Cmdlets?

I have a PowerShell script cmdlet that supports the -WhatIf & -Confirm parameters.
It does this by calling the $PSCmdlet.ShouldProcess() method before performing the change.
This works as expected.
The problem I have is that my Cmdlet is implemented by calling other Cmdlets and the -WhatIf or -Confirm parameters are not passed along to the Cmdlets I invoke.
How can I pass along the values of -WhatIf and -Confirm to the Cmdlets I call from my Cmdlet?
For example, if my Cmdlet is Stop-CompanyXyzServices and it uses Stop-Service to implement its action.
If -WhatIf is passed to Stop-CompanyXyzServices I want it to also be passed to Stop-Service.
Is this possible?

A:

Passing parameters explicitly
You can pass the -WhatIf and -Confirm parameters with the $WhatIfPreference and $ConfirmPreference variables. The following example achieves this with parameter splatting:
if($ConfirmPreference -eq 'Low') {$conf = @{Confirm = $true}}

StopService MyService -WhatIf:([bool]$WhatIfPreference.IsPresent) @conf

$WhatIfPreference.IsPresent will be True if the -WhatIf switch is used on the containing function. Using the -Confirm switch on the containing function temporarily sets $ConfirmPreference to low.
Passing parameters implicitly
Since the -Confirm and -WhatIf temporarily set the $ConfirmPreference and $WhatIfPreference variables automatically, is it even necessary to pass them?
Consider the example:
function ShouldTestCallee {
    [cmdletBinding(SupportsShouldProcess=$true,ConfirmImpact='Medium')]
    param($test)

    $PSCmdlet.ShouldProcess($env:COMPUTERNAME,"Confirm?")
}

function ShouldTestCaller {
    [cmdletBinding(SupportsShouldProcess=$true)]
    param($test)

    ShouldTestCallee
}

$ConfirmPreference = 'High'
ShouldTestCaller
ShouldTestCaller -Confirm

ShouldTestCaller results in True from ShouldProcess()
ShouldTestCaller -Confirm results in an confirm prompt even though I didn't pass the switch.
Edit
@manojlds answer made me realize that my solution was always setting $ConfirmPreference to 'Low' or 'High'. I have updated my code to only set the -Confirm switch if the confirm preference is 'Low'.

A:

After some googling I came up with a good solution for passing common parameters along to called commands.  You can use the @ splatting operator to pass along all the parameters that were passed to your command.  For example, if
Start-Service -Name ServiceAbc @PSBoundParameters
is in the body of your script powershell will pass all the parameters that were passed to your script to the Start-Service command.  The only problem is that if your script contains say a -Name parameter it will be passed too and PowerShell will complain that you included the -Name parameter twice.  I wrote the following function to copy all the common parameters to a new dictionary and then I splat that.
function Select-BoundCommonParameters
{
    [CmdletBinding()]
    param(
        [Parameter(Mandatory=$true)]
        $BoundParameters
    )
    begin
    {
        $boundCommonParameters = New-Object -TypeName 'System.Collections.Generic.Dictionary[string, [Object]]'
    }
    process
    {
        $BoundParameters.GetEnumerator() |
            Where-Object { $_.Key -match 'Debug|ErrorAction|ErrorVariable|WarningAction|WarningVariable|Verbose' } |
            ForEach-Object { $boundCommonParameters.Add($_.Key, $_.Value) }

        $boundCommonParameters
    }
}

The end result is you pass parameters like -Verbose along to the commands called in your script and they honor the callers intention.

A:

Here is a complete solution based on @Rynant and @Shay Levy's answers:
function Stop-CompanyXyzServices
{
    [CmdletBinding(SupportsShouldProcess=$true,ConfirmImpact='Medium')]

    Param(
        [Parameter(
            Position=0,
            ValueFromPipeline=$true,
            ValueFromPipelineByPropertyName=$true
        )]
        [string]$Name
    )

    process
    {
        if($PSCmdlet.ShouldProcess($env:COMPUTERNAME,"Stop XYZ services '$Name'")){
            ActualCmdletProcess
        }
        if([bool]$WhatIfPreference.IsPresent){
            ActualCmdletProcess
        }
    }
}

function ActualCmdletProcess{
# add here the actual logic of your cmdlet, and any call to other cmdlets
Stop-Service $name -WhatIf:([bool]$WhatIfPreference.IsPresent) -Confirm:("Low","Medium" -contains $ConfirmPreference)
}

We have to see if -WhatIf is passed separately as well so that the whatif can be passed on to the individual cmdlets. ActualCmdletProcess is basically a refactoring so that you don't call the same set of commands again just for the WhatIf. Hope this helps someone.


Q:

Finding the value of an infinite trigonometric series

Find the sum $$\sum_{n=1}^\infty \cfrac{[[\cos(\frac {2\pi}{n})+1]]}{4^n}.$$
I honestly have no clue what to do except that I know that the sum for the $\cfrac {1}{4^n}$ component is $\cfrac 13$.
Can anyone help me in solving this problem? As much as possible, I need a solution that does not use calculus.

A:

Assuming $[[\cdot]]$ means the floor, consider what $\cos \frac{2\pi}{n}$ looks like - namely, for $n \ge 4$, that it'll always be the cosine of a positive angle less than or equal to $\frac{\pi}{2}$, which will always be a positive number strictly less than 1.  Therefore, all terms after the third will be the same, so it's just a matter of replacing the first three terms.  The first term will be doubled by adding one to the numerator, the second and third annihilated by the floor function after subtracting one and one-half respectively.  That is to say, $\frac{1}{4} + \frac{1}{16} + \frac{1}{64} = \frac{21}{64}$ is replaced by one-half, so the final sum is
$$\frac{1}{3} - \frac{21}{64} + \frac{1}{2} = \frac{97}{192}$$


Q:

Concat column values based on condition

This code :
import numpy as np
import pandas as pd

df = pd.DataFrame(['a1', 'a2', 'stop', 'a4', 'a4', 'a5', 'stop', 'a3'],
                  columns=['c'])

renders:
      c
0    a1
1    a2
2  stop
3    a4
4    a4
5    a5
6  stop
7    a3

I'm attempting to produce the following dataframe where values in a column are concatenated until 'stop' value is encountered :
columns = ['c1' , 'c2']
data = np.array([['a1, a2','stop'] , ['a4, a4, a5','stop']])
df = pd.DataFrame(data, columns=columns)
df

           c1    c2
0      a1, a2  stop
1  a4, a4, a5  stop

Is this a valid approach, filter the rows where column value is 'stop':
df[df['c'] == 'stop']

then access the previous rows ?

A:

First, create a boolean mask by testing the equality of c to "stop":
>>> df = pd.DataFrame(['a1', 'a2', 'stop', 'a3', 'a4', 'a5', 'stop', 'a6'],
                      columns=['c'])
>>> mask = df['c'].eq('stop')

You also specified you want to ignore values after the final stop.  Truncate both series with:
>>> stop = mask[::-1].idxmax()
>>> mask = mask[:stop]
>>> c = df['c'][:stop].copy()

Now groupby:
>>> c.groupby(mask.cumsum()).apply(lambda s: s[s!='stop'].tolist())
c
0        [a1, a2]
1    [a4, a4, a5]

With a cumulative sum, True maps to 1 and False maps to 0.  This serves as the grouping.
A footnote - this logic should work regardless of whether the final value in the Series ends in a stop or not.


Q:

Linux partition system

While installing Ubuntu, I only created two partitions for Ubuntu one for swap and I formatted the other as ext4 and set mount point as "/". The Operating System is working flawlessly.
I was just reading a few Ubuntu install guides and found that most of them suggest creating more partitions and mount them as "/root", "/home", etc, etc.
Is there a difference between the two sorts of install methods?   Is there a performance difference between the two methods?

A:

There is a difference not so much for performance but for the easier administration.
The layout I usually use for partitioning is:
/
/var
/home
/tmp
swap partition.

I setup /var and /tmp on different mount points in order to keep the root filesystem / clean because /var can get filled by downloaded updates and /tmp can get filled with temporary files and thus causing the system not to run properly.
Also i keep /home on a separate partition because in case of a reinstall I can keep all the personal settings there and after the system is reinstalled the applications can read the settings from there, otherwise you need to backup the data and restore it after reinstall


Q:

How do I write this script's results to a file?

Basic question as I'm learning powershell. At the moment I have a script that give me the output of a directory in a nice clean format. I want to write the results to file rather than to the console. I can't seem to figure out the correct use of Out-File. I've tried it in the script and tried it as an extension when running it. Any help would be appreciated.
get-childitem "A:\data\set1" -recurse | where {$_.extension -eq ".mp3"} | % {
 Write-Host $_.FullName}

A:

You do not need to use Write-Host:
get-childitem "A:\data\set1" -recurse |
  where {$_.extension -eq ".mp3"} |
  % {$_.FullName} |
  Out-File ./list.txt


Q:

How to write into a Log file from the batch file?

I have a batch file that triggers  process in Access database. I'd like to write into a log file (just some *.txt file saved in the same folder) time when before the process started and after it was finished.
Is there a command for that?
Thank you in advance

A:

Using > and >> outputs to a file.
eg
echo Hello World > hi.txt

Will result in a file called hi.txt containing the string "Hello World"
echo How are you >> hi.txt

Will add the line "How are you" to the end of hi.txt
This works on both Windows and Unix based OS. (Linux, Mac OS...)
On windows, using %TIME% or %DATE% in the echo string will output time/date as part of the string.


Q:

How to access the column name which contains dot . in select query

I have tried backticks `` aswell .
My Column name is complaintlgeo.lat while writing the query as
 select `complaintlgeo.lat` from mandapet.pgr_view

I'm getting the following Errors

ERROR:  missing FROM-clause entry for table "complaintlgeo" LINE 1:
  select `complaintlgeo.lat` from mandapet.pgr_view
            ^

********** Error **********
ERROR: missing FROM-clause entry for table "complaintlgeo" SQL state:
  42P01 Character: 9

A:

Do you try with [] ?
select [complaintlgeo].[lat] from mandapet.pgr_view

or
select [complaintlgeo.lat] from mandapet.pgr_view


Q:

Call a javascript function automatically without buttons

I developed a javascript function that shows me the current time. Until then I had no problems. The problem is that I can not call this function in the place I want ... how can I call it using this?

Location where I want to call the function

Hours here

A:

Place a  with an id where you want the time to be shown. Then query that  by id and set its textContent.
Use the setInterval function if you want to update the time at a regular interval:

function getTime() {
  const timeNow = new Date();
  const hours   = timeNow.getHours();
  const minutes = timeNow.getMinutes();
  const seconds = timeNow.getSeconds();
  let timeString = '' + ((hours > 24) ? hours - 12 : hours);
  timeString  += ((minutes < 10) ? ":0" : ":") + minutes;
  timeString  += ((seconds < 10) ? ":0" : ":") + seconds;
  timeString  += (hours >= 12) ? " P.M." : " A.M.";
  return timeString;
}

const hoursSpan = document.getElementById('hours');
hoursSpan.textContent = getTime();

setInterval(() => {
  hoursSpan.textContent = getTime();
}, 1000);


Q:

What does >... mean in vim and how to substitute a single whitespace for it?

I know that when :set list is used whitespace is shown as .. But what does it mean when a whitespace symbol is preceded by >, e.g. >., >.., or >...?
And how do I remove it and leave only one single whitespace . behind?
It's a bit hard to give a good example but the whitespace that is included with >.. feels like chewing gum; meaning if you add more whitespace it will crush other words closer together before moving the whole line to the right:
Long    long    time    ago it  began.

A:

It seems like if it's a tab. You can confirm this by placing your cursor on it and press ga in normal mode. If it displays
<^I>  9,  Hex 09,  Octal 011

then it's a tab. A space looks like this:
< >  32,  Hex 20,  Octal 040

To change each tab to a single space:
%s/\t/ /g


Q:

Explanation on CSS float overflow property

I am a newbie to CSS. I started exploring CSS float property. I have two
 elements inside a container. The two divs have equal width and height.

      Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu. In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo. Nullam dictum felis eu pede mollis pretium. Integer tincidunt. Cras dapibus. Vivamus elementum semper nisi. Aenean vulputate eleifend tellus. Aenean leo ligula, porttitor eu, consequat vitae, eleifend ac, enim. Aliquam lorem ante, dapibus in, viverra quis, feugiat a, tellus. Phasellus viverra nulla ut metus varius laoreet. Quisque rutrum. Aenean imperdiet. Etiam ultricies nisi vel augue. Curabitur ullamcorper ultricies nisi. Nam eget dui. Etiam rhoncus. Maecenas tempus, tellus eget condimentum rhoncus, sem quam semper libero, sit amet adipiscing sem neque sed ipsum. Nam quam nunc, blandit vel, luctus pulvinar, hendrerit id, lorem. Maecenas nec odio et ante tincidunt tempus. Donec vitae sapien ut libero venenatis faucibus. Nullam quis ante. Etiam sit amet orci eget eros faucibus tincidunt. Duis leo. Sed fringilla mauris sit amet nibh. Donec sodales sagittis magna. Sed consequat, leo eget bibendum sodales, augue velit cursus nunc,

And CSS for the above is :
.one{
  width: 200px;
  height: 200px;
  background-color: green;
  border: 1px solid blue;
  float: left;
}
.two{
  width: 200px;
  height: 200px;
  background-color: red;
  border: 1px solid black;
  overflow:visible;
}

.container{
  overflow:hidden;
}

From the above what I can understand is that since the div that is floated is removed from the normal flow and floated to left and the second div which contains the text inside
 elements merges underneath the .one div. And moreover  since both have the same width and height I cannot see the content.
But when I set the overflow property of the .two to scroll I see the second div being placed adjacent to first div. This is confusing. Why is such a behavior? Please explain me. Link to codepen attached below for more details.
Link to Codepen

A:

The float CSS property specifies that an element should be taken from the normal flow. However the non-float element still takes all the available width including the floating element. But if you set overflow: auto; or hidden to it, it will then align next to the floating element. See the demo following, it should explain it clearly.

.a1, .b1 {
    background: rgba(0,0,0,.5); /*pure black with alpha*/
    width: 50px;
    height: 50px;
    float: left;
}
.a2 {
    background: lime;
}
.b2 {
    background: lime;
    overflow: auto; /*let the browser decide whether to clip or not*/
}

hello

Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu.

hello

Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu.


Q:

Getting image to appear below text on mobile device

Hi guys i have an image side by sdie with some text and i am trying to get it to appear below the text on a mobile device but right now its appearing above it, I'm using bootstrap 3.
html:

Title

Bryggeriet är en restaurang, sportbar och nattklubb som ligger mitt på Avenyn i Göteborg. Sedan vi öppnade portarna 1993 har vi varit ett självklart val för alla som vill äta riktigt god mat, ta en trevlig lunch, följa sitt favoritlag i Sportbaren, komma förbi på en after work eller dansa helgnatten lång. Eller om man bara vill beställa någonting gott att dricka i en avslappnad och gemytlig miljö.

Hos oss kan och bör du förvänta dig mat som är en fröjd för både ögat och magen. Här står maten i fokus och vi tillagar alla våra rätter från grunden. Det betyder att du får fräsch mat som tillagas när du beställer den, gjord på råvaror av högsta kvalitet. Vi tar inga genvägar, utan serverar endast sådant som vi själva skulle uppskatta att få på tallriken..

CSS:
    @media only screen and (max-width: 768px) {

}

I have tried to float the element and then use clear:both but i cant seem to get anything to work to make the image appear at the bottom od the div below all the text.
Thanks

A:

You could use the following bootstrap push and pull classes on medium and up screens;
col-md-pull-6, col-md-push-6

This will reorganise the flow of content - for example:  https://jsfiddle.net/hfwr6n8z/2/
You should also restructure your HTML, and place the image wrapper div last in the DOM, so it is displayed last on small screens.


Q:

Access mmap memory from another process

I've started playing with mmap. I'm trying to create an example workspace that will be then extended to the real case.
This is what I want to achieve:
PROCESS 1:

mmap a file (actually a device, but it's okay to generate an example with a text file)

PROCESS 2: (not foked from process 1; just an independent process)

read the memory mapped by process 1
change some bits
write it to a new file

I've read several examples and documentations, but I still didn't find how to achieve this. What I'm missing is:

how can process 2 access the memory mapped by process 1, without knowing anything about the opened file?
how can I put the mmap content in a new file? I suppose I have to ftruncate a new file, mmap this file and memcpy the content of process 1 memory map to process 2 memory map (then msync)

Side info, I have a message queue opened between the two processes, so they can share some messages if needed (ex. the memory address/size, ...).
Any hints?
Thanks in advance!
MIX

A:

This answer considers you are trying to do this stuff on linux/unix.

how can process 2 access the memory mapped by process 1, without knowing anything about the opened file?

Process 1 passes to mmap[1] the flag MAP_SHARED.
You can:

A) Share the file descriptor using unix domain sockets[2].
B) Send
the name of the file using the queues you mentioned at the end of
your message.

Process 2 opens mmap with the flag MAP_SHARED. Modifications to the mmaped memory in Process 1 will be visible for Process 2. If you need fine control of when the changes from process 1 are shown to process 2 you should control it with msync[3]

how can I put the mmap content in a new file? I suppose I have to
  ftruncate a new file, mmap this file and memcpy the content of process
  1 memory map to process 2 memory map (then msync)

Why just don't write the mmaped memory as regular memory with write?
[1]http://man7.org/linux/man-pages/man2/mmap.2.html
[2]Portable way to pass file descriptor between different processes
[3]http://man7.org/linux/man-pages/man2/msync.2.html


Q:

Handlebars Template rendering template as text

I created a helper in Handlebars to help with logic, but my template parses the returned html as text rather than html.
I have a quiz results page that is rendered after the quiz is completed:

For each of the rounds, I use a helper to determine which template to render a round's result:
  Handlebars.registerHelper("round_end_result", function() {
    if (this.correct) {
      var source = '';
      if (this.guess == this.correct) {
        console.log("correct guess");
        var source = $("#round-end-correct").html();
      } else {
        var source = $("#round-end-wrong").html();
      }
      var template = Handlebars.compile(source);
      var context = this;
      var html = template(context);
      console.log(html);
      return html;
    } else {
      console.log("tie");
    }
  });

Here is a template that describes a correct round (let's take say it rendered the #round-end-correct template):

Here is what gets rendered:

Not as HTML, but as text. How do I get it to actually render the HTML as HTML, rather than text?

A:

I assume that unescaping in Handlebars works the same as in vanilla Mustache.
In that case use triple mustaches to unescape html, i,e: {{{unescapedhtml}}}, like:


Q:

Why does bundle exec puma fail with a Gemfile syntax error?

I'm trying to deploy a Rails 4 app with capistrano 3 to Ubuntu 12.04. I'm using the capistrano3-puma gem to handle configuring puma, but when it tries to bundle exec puma I get this error:
Gemfile syntax error: (Bundler::GemfileError)
/srv/photo_album/releases/20140607043918/Gemfile:41: syntax error, unexpected ':', expecting kEND
...sprockets_better_errors', git: 'git@github.com:RobinClowers/...

I'm able bundle exec rails just fine from this machine just fine, so I think there is something else going on. That error looks like ruby 1.8 trying to parse 1.9 hash syntax...

A:

I figured this out. I accidentally installed puma with the system ruby (which is 1.8.7), and I had not run bundle install yet, so there was no 2.1.1 version install for it to find.


Q:

Force iframe to scroll

I have an absolutely horrible webform that renders into the following:
body -> form -> table -> thousands of divs -> iframe -> body -> thousands of divs -> iframe -> body -> table
Eventually I find the table that contains the actual data, the user makes his view smaller and the data cannot be seen, so there needs to be a scrollbar. I have been applying overflow:auto, width:100%, height:100% on many elements but never seen the right scrollbar to appear. Initially, the page renders with a few of the parent elements having overflow:hidden, however after changing them as I was inspecting the page nothing happened. Is there any way to force the scrollbar?

A:

Please try this:

OR
Put your iframe inside a fixed height div and put css property as scroll-y:auto.

div.iframe_container{height:500px;scroll-y:auto}


Q:

Jquery tabs width next and prev links

the tabs are working fine but I need to trigger the NEXT and PREV buttons that currently don't make the tabs selected
cloud you help me with that?
http://jsfiddle.net/pmnzT/27/
thanks

A:

Take advantage of the existing click handler that you have.  When you click next, manually trigger the click handler on the next tab, by calling .trigger('click').  I also put the changeTab code in a common call, so you don't have to replicate code in the next and previous click handlers:
function changeTab(next){
    var tabs = $('.tabmenu a');  // Get tab links
    var curTab = tabs.index($('.selected'));  // What link # is selected?
    var num = tabs.size();  // How many do we have?
    if(next) {
       // If next, add 1 (mod total, allows wrapping)
       newTab = (curTab+1)%num;
    } else {
       // If prev, sub 1 (add total, mod total, allows wrapping)
       newTab = (curTab+num-1)%num;
    }
    // This manually "clicks" the next tab
    tabs.eq(newTab).trigger('click');
}

$('.next-tab').click(function(){
    // call changeTab(); 1 means next
    changeTab(1);
});

$('.prev-tab').click(function(){
    // call changeTab();  0 means previous
    changeTab(0);
});

Demo: http://jsfiddle.net/baKYK/
That being said, jQuery UI provides a lot of functionality automatically.  Is there a reason you aren't using it?


Q:

unexpected flowtype error with possibly null object

I am learning flow type, but I got a lot of problems that I do not understand.
One of them is as follows:
I initialize the bill state us null then I fetch it from the API and update the state with the fetched bill. I know that if this.state.bill is null I can't access any property on it so I only access properties of this.state.bill inside an if statement like that:
class BillPaymentPage extends Component<*, props, *> {
  state = {
    bill: null,
  };

  componentDidMount() {
    this.fetchBill(this.props.id);
  }

  fetchBill = async (id: string) => {
    const bill = await getBillById(id, this.props.token).catch(e =>
      console.log(e),
    );
    this.setState({ bill });
  };
  ....
  render() {
    if (this.state.bill) {
      const totalPayment = this.state.bill.payment
        .reduce((acc, curr) => acc + curr.amount, 0)
        .toFixed(3);
      return (
        <Card>
          <PaymentForm
            bill={this.state.bill}
            submitPayment={this.submitPayment}
            billStatus={this.state.bill.status}
          />

            <FormattedMessage id="label.total" /> :{' '}
            <FormattedNumber
              value={this.state.bill.total}
              type="currency"
              currency="tnd"
            />

            <FormattedMessage id="label.totalPayment" /> :{' '}
            <FormattedNumber
              value={totalPayment}
              type="currency"
              currency="tnd"
            />

          <PaymentList
            deletePayment={this.deletePayment}
            payment={this.state.bill.payment}
          />
        </Card>
      );
    }
    return <Loader />;
  }
}

Although I've used if(this.state.bill) flow still show me this error:
app/components/pages/bills/BillPaymentPage.js:99
 99:             billStatus={this.state.bill.status}
                                             ^^^^^^ property `status`. Property cannot be accessed on possibly null value
 99:             billStatus={this.state.bill.status}
                             ^^^^^^^^^^^^^^^ null

app/components/pages/bills/BillPaymentPage.js:104
104:               value={this.state.bill.total}
                                          ^^^^^ property `total`. Property cannot be accessed on possibly null value
104:               value={this.state.bill.total}
                          ^^^^^^^^^^^^^^^ null

app/components/pages/bills/BillPaymentPage.js:119
119:             payment={this.state.bill.payment}
                                          ^^^^^^^ property `payment`. Property cannot be accessed on possibly null value
119:             payment={this.state.bill.payment}
                          ^^^^^^^^^^^^^problem

How can I solve this probleme?

A:

Flow supports "refining" types, which means you can use control statements like if to make Flow realize that a certain option for a value is or is not available. This allows code like this to work fine:
var obj = {
  state: {
    bill: (null: null | { payment: Array<string> }),
  },
};

if (obj.state.bill) {
  let str: string = obj.state.bill.payment[0];
}

(On Flow Try)
because Flow can see that .bill can't be null because the if statement succeeded.
The reason that isn't happening in your case is that certain operations make Flow have to go back to being unsure. In your case it is
const totalPayment = this.state.bill.payment
    .reduce((acc, curr) => acc + curr.amount, 0)
    .toFixed(3);

generally complex statements like this could somehow modify bill so that it was null again. In this particular instance it's obvious to a person that it won't happen, but it is not obvious to Flow. You can see that behavior in this too:
var obj = {
  state: {
    bill: (null: null | { payment: Array<string> }),
  },
};

if (obj.state.bill) {
  obj.state.bill.payment.reduce((acc, v) => v);

  let str: string = obj.state.bill.payment[0];
}

(On Flow Try)
Generally the approach most people use for cases like this is that they pull the properties off of state entirely before using them, e.g.
var obj = {
  state: {
    bill: (null: null | { payment: Array<string> }),
  },
};

const { bill } = obj.state;

if (bill) {
  bill.payment.reduce((acc, v) => v);

  let str: string = bill.payment[0];
}

(On Flow Try)
which will work fine since there is not no way for the value of bill to change from non-null to null very obviously.


Q:

Efficiently backup many versions of a git repo with branch namespacing

At work, we use Perforce for version control.  There are problems with this: 1) with this centralized model, we can't check in changes until they are ready for regression.  This means that we have no revision control during the development process.  2) We don't back up our client view of the depot, so our work is unsafe until we can check it in. 3) We have problems sharing our code with each unless we beg to have an integration branch set up.  I am trying to set up an optional git workflow for developers who want to use git to beat these problems.
The plan is to use git-p4 to interface with the perforce server and create a private git repo.  This takes care of 1).  I plan to use the integration-manager workflow depicted in Git Pro (http://progit.org/book/ch5-1.html) to have our developers publish public repos, taking care of 3).

Finally, I want a place where developers can push their changes so that they will pulled into nightly backups / offsite backups.  The reason we don't backup our client views now is because doing nightly archival backups of everyone's client view is space inefficient.  We have a lot of developers, and they produce a lot of code.  We can't be redundantly backing up everyone's client view.  We only want to preserve the unique changes that they are making only.
My thinking was to have one bare git repo, call it omni-backup, that everyone can push all of their branches to (and feel free to suggest alternatives).  This would utilize git's space efficient sha-1 hashing and ensure that only unique versions of each file are backed up.  The trick is that all the backup repositories have to be part of the same repo to get the space efficiency.
The problem is when two people with completely different branches chose the same name for their branch.  E.G. Bob has a feature branch and Jane has a feature branch, but they're for different features.  If Bob pushes to omni-backup, Jane won't be able to, as it wouldn't be a fastforward merge.
Now what I would ideally want to have happen is that when Bob pushes his feature branch, the branch will be renamed to bob-feature on the omni-backup remote.  And when he pulls feature from omni-backup, he gets back bob-feature.
This doesn't seem terribly easy to accomplish in git.  It looks like I can use push hooks documented in http://www.kernel.org/pub/software/scm/git/docs/git-receive-pack.html post-receive hook to rewrite the name of the ref immediately after it written, and then something could be done to reverse the process on the way back, but it feels fragile.  Anyone have a better idea?

edit: for VonC (Because code sucks in comments)
Your way sounds promising, VonC, but I don't see how the fact that it's a fetch will beat the namespacing problems.  Are you suggesting a cronjob that knows how to rename the branch?
like (really dirty):
foreach my $user (@users) {
    my @branches = split(/s/,cat `$LDAPSERVER/$USER/$REPO/.git/refs/heads`);
    foreach my $branch (@branches) {
        system "git fetch $LDAPSERVER/$USER/$REPO/$BRANCH:+$USER$BRANCH"
    }
}

A:

Why would you need for developer to push to omni-backup repo?
For backup purposes, I would rather register the different developer's repository as remote, and do a git fetch every night (from the omni-backup server) on all the remote repos.
That way, no branch name collusion possible. And a more automated process (the developer doesn't have to explicitly push anything on a repo he/she doesn't directly work with, but would only consider for backup)
Then I would produce a nice little git archive out of omni-backup and store it away.


Q:

Show which field the term was found in?

In the search results, is there a way to show which custom field a search term was found in?

A:

No.
The search index is a big text field per entry, containing all searchable fields. This is what makes the keyword searches fast. However, that also means there is no info as to what specific field contained the keywords. It's totally possible that, for keywords that contain more than one word, the terms are found in multiple fields.


Q:

Play framework 2.0 does not compile when using java.utils.Stack

I have this strange problem where any call to said data structure will give a nullPointerException when instantiated as a Stack, but not when instantiated as a List.
Both unit tests and running the play web server give nullPointerException when I run it with the stack class
This works:
....

/*
 * comment belongs to post, and if post is deleted,
 * the deletion is relayed to all comments that post object
 * owns
 */
@OneToMany (mappedBy="post",cascade=CascadeType.ALL)
public List<Comment> comments;

....

public Post(SuperUser author,String content,String title){
    this.comments = new LinkedList<Comment>();
    this.author = author;
    this.content = content;
    this.title = title;
    this.postedAt = new Date();

}

...

public Post addComment(Comment newComment){
    this.comments.add(newComment);
    this.save();
    return this;
}

This does not work:
....

/*
 * comment belongs to post, and if post is deleted,
 * the deletion is relayed to all comments that post object
 * owns
 */
@OneToMany (mappedBy="post",cascade=CascadeType.ALL)
public Stack<Comment> comments;

....

public Post(SuperUser author,String content,String title){
    this.comments = new Stack<Comment>();
    this.author = author;
    this.content = content;
    this.title = title;
    this.postedAt = new Date();

}

...

public Post addComment(Comment newComment){
this.comments.push(newComment); // ERROR
    this.save();
    return this;
}

I tried writing a wrapper interface for the List interface and giving it the method:
public E push(E elem);

But that does also not work.
Any idea what this could be?

A:

You may not use concrete classes as the type of entity associations. Only interfaces: List, Set, Map. The ORM uses its own concrete implementations of these interfaces to implement dirty checking, lazy loading, etc.
Relevant quote from the spec:

Collection-valued persistent fields and properties must be defined in terms of one of the following collection-valued interfaces regardless of whether the entity class otherwise adheres to the JavaBeans method conventions noted above and whether field or property access is used: java.util.Collection, java.util.Set, java.util.List, java.util.Map. The collection implementation type may be used by the application to initialize fields or properties before the entity is made persistent. Once the entity becomes managed (or detached), subsequent access must be through the interface type.


Q:

Compiler Error When Calling Base Constructor when both Base and Derived are Templated With Derived Type Parameter

I am struggling to understand why the following code does not compile:
template <class T>
class Base {
    public:
        Base(int a){}
};
template <class T>
class Derived: public Base<T>  {
    public:
        Derived(int a): Base(a){}
};
int main(){}

On my compiler (gcc 5.4.0 with C++ 11) this outputs the error message
error: class 'Derived<T>' does not have any field named 'Base'
         Derived(int a): Base(a){}

I see that this is somewhat similar to Template base constructor call in member initialization list error, though that test case actually compiles for me while this one does not: The main difference seems to be that both Base and Derived use the same type parameter. Additionally, it compiles fine if I explicitly add the type parameters or I give an explicit scope for base, as in
template <class T>
class Base {
    public:
        Base(int a){}
};

template <class T>
class Derived: public Base<T>  {
    public:
        Derived(int a): Derived::Base(a){}
};

int main(){}

What's going on? Am I misunderstanding when injected class names may be used?

A:

The injected class name Base is a member of the class Base, and since the base class is dependent, its scope is not searched during unqualified name lookup. As such, using the name Base will only find the class template, not the injected class name of Base<T>. That is why you must write Base<T>.
Derived::Base works because it causes name lookup to be postponed until Derived is instantiated.


Q:

FFMPEG image sequence with longer durations after generated an output video

I'm using this library to create a deepfake video. The problem is the original duration video is shorter than the generated one. Original is 35 seconds but generated is 41 seconds. Image frames captured and converted are same, 1037 frames.
I'm using this command to generate the video.
ffmpeg -i video-frame-%0d.png -c:v libx264 -vf "fps=25,format=yuv420p" out.mp4

A:

1037 frames /25 fps = 41.48s
Your video appears to be 30 fps*.
ffmpeg -framerate 30 -i video-frame-%0d.png -c:v libx264 -vf "format=yuv420p" out.mp4
*It may be 29.97 i.e. exactly 30000/1001 fps.


Q:

error when using EC2 SNS with SSM (Systems Manager)

I'm trying to use AWS's SNS with SSM but getting an error about roles.
Here's the error:
botocore.errorfactory.InvalidRole: An error occurred (InvalidRole) when calling the SendCommand operation: ServiceRoleArn is not valid: arn:aws:iam::<account #>:role/FullSNS

Here's the relevant code:
response = client.send_command(
InstanceIds=[
    '<instance id>',
],
DocumentName='AWS-RunShellScript',
Parameters={
    'commands': [
        '<command>',
    ],
    'workingDirectory': [
        '<directory>'
    ]
},
OutputS3BucketName='<s3 bucket>',
ServiceRoleArn='arn:aws:iam::<account #>:role/FullSNS',
NotificationConfig={
    'NotificationArn': 'arn:aws:sns:us-east-1:<account #>:MyTestTopic',
    'NotificationEvents': [
        'All',
        ],
    'NotificationType': 'Command'
    }
)

And here's the policy on that role:
{
  "Version": "2012-10-17",
  "Statement": [
{
  "Action": [
    "sns:*"
  ],
  "Effect": "Allow",
  "Resource": "*"
}
]
}

The above is with boto3 but I get the same error if I try it within the console.

A:

I wish the AWS documentation was more clear on this point, but I also had to edit the trust relationship on that IAM role to look like this:
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": {
         "Service": "ssm.amazonaws.com"
      },
      "Action": "sts:AssumeRole"
    }
  ]
}


Q:

Email not being sent using gmail info

ok, so i have been trying to sort this for about 3 hours but to no avail. I have made a simple contact us form. All it needs to do is send the message to my gmail account. It's not sending anything and neither is it giving any error. I tried turning off the 2 step authentication but that hasn't helped either.
My aspx code:
<asp:Panel ID="Panel1" runat="server" DefaultButton="btnSubmit">

                            Please Fill the Following to Send us an E-Mail. We will get back to you ASAP!

                            Your name:
    <asp:RequiredFieldValidator ID="RequiredFieldValidator11" runat="server" ErrorMessage="*"
        ControlToValidate="YourName" ValidationGroup="save" />

                            <asp:TextBox ID="YourName" runat="server" Width="250px" />

                            Your email address:
    <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ErrorMessage="*"
        ControlToValidate="YourEmail" ValidationGroup="save" />

                            <asp:TextBox ID="YourEmail" runat="server" Width="250px" />
                            <asp:RegularExpressionValidator runat="server" ID="RegularExpressionValidator23"
                                SetFocusOnError="true" Text="Example: username@gmail.com" ControlToValidate="YourEmail"
                                ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*" Display="Dynamic"
                                ValidationGroup="save" ForeColor="Red" />

                            Subject:
    <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ErrorMessage="*"
        ControlToValidate="YourSubject" ValidationGroup="save" />

                            <asp:TextBox ID="YourSubject" runat="server" Width="400px" />

                            Your Question:
    <asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" ErrorMessage="*"
        ControlToValidate="Comments" ValidationGroup="save" />

                            <asp:TextBox ID="Comments" runat="server"
                                TextMode="MultiLine" Rows="10" Width="400px" />

                            <asp:Button ID="btnSubmit" runat="server" Text="Send" ValidationGroup="save" Height="36px" OnClick="btnSubmit_Click" Width="86px" />

                    </asp:Panel>

my C# code:
  try
{
    MailMessage Msg = new MailMessage();
    // Sender e-mail address.
    Msg.From = new MailAddress(YourEmail.Text);
    // Recipient e-mail address.
    Msg.To.Add("*****@gmail.com");
    Msg.Subject = YourSubject.Text;
    Msg.Body = Comments.Text;
    // your remote SMTP server IP.
    SmtpClient smtp = new SmtpClient();
    smtp.Host = "smtp.gmail.com";
    smtp.Port = 587;
    smtp.Credentials = new System.Net.NetworkCredential("****@gmail.com", "*********");
    smtp.EnableSsl = true;
    smtp.Send(Msg);
    //Msg = null;
    DisplayMessage.Text = "Thanks for Contacting us";
    // Clear the textbox valuess
    YourName.Text = "";
    YourSubject.Text = "";
    Comments.Text = "";
    YourEmail.Text = "";
}
catch (Exception ex)
{
Console.WriteLine("{0} Exception caught.", ex);
}

any help will be greatly appreciated

A:

You need to put proper credential from which you will be sending the mail.
See here
ASPX CODE
<asp:Panel ID="Panel1" runat="server" DefaultButton="btnSubmit">

            Please Fill the Following to Send us an E-Mail. We will get back to you ASAP!

            Your name:
<asp:RequiredFieldValidator ID="RequiredFieldValidator11" runat="server" ErrorMessage="*"
    ControlToValidate="YourName" ValidationGroup="save" />

            <asp:TextBox ID="YourName" runat="server" Width="250px" />

            Your email address:
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ErrorMessage="*"
    ControlToValidate="YourEmail" ValidationGroup="save" />

            <asp:TextBox ID="YourEmail" runat="server" Width="250px" />
            <asp:RegularExpressionValidator runat="server" ID="RegularExpressionValidator23"
                SetFocusOnError="true" Text="Example: username@gmail.com" ControlToValidate="YourEmail"
                ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*" Display="Dynamic"
                ValidationGroup="save" ForeColor="Red" />

            Subject:
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ErrorMessage="*"
    ControlToValidate="YourSubject" ValidationGroup="save" />

            <asp:TextBox ID="YourSubject" runat="server" Width="400px" />

            Your Question:
<asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" ErrorMessage="*"
    ControlToValidate="Comments" ValidationGroup="save" />

            <asp:TextBox ID="Comments" runat="server"
                TextMode="MultiLine" Rows="10" Width="400px" />

            <asp:Button ID="btnSubmit" runat="server" Text="Send" ValidationGroup="save" Height="36px" OnClick="btnSubmit_Click" Width="86px" />

    </asp:Panel>

CS CODE
protected void btnSubmit_Click(object sender, EventArgs e)
    {
        try
        {
            MailMessage Msg = new MailMessage();
            // Sender e-mail address.
            Msg.From = new MailAddress(YourEmail.Text);
            // Recipient e-mail address.
            Msg.To.Add("test@gmail.com");
            Msg.Subject = YourSubject.Text;
            Msg.Body = Comments.Text;
            // your remote SMTP server IP.
            SmtpClient smtp = new SmtpClient();
            smtp.Host = "smtp.gmail.com";
            smtp.Port = 587;
            smtp.Credentials = new System.Net.NetworkCredential("YOURGMAILID", "YOURGMAIL PASSWORD");  // IT SHOULD BE CORRECT TO WORK
            smtp.EnableSsl = true;
            smtp.Send(Msg);
            //Msg = null;
           // DisplayMessage.Text = "Thanks for Contacting us";
            // Clear the textbox valuess
            YourName.Text = "";
            YourSubject.Text = "";
            Comments.Text = "";
            YourEmail.Text = "";
        }
        catch (Exception ex)
        {
            Console.WriteLine("{0} Exception caught.", ex);
        }
    }

hope it helps. :)


Q:

What is the general rule to use accusatival pronouns to refer to nouns repeatedly?

I'm just a beginner of Spanish. An exercise of my Spanish text book asks the readers to ask questions about the bold part in the sentence:
Todo lo hacen muy rápido.
My answer is:
¿Cómo todo lo hacen?
The answer gives:
¿Cómo hacen todo?
I know that the "lo" in the original sentence refers to "todo", but why the "lo" is missing in the answer? I don't know when should we use assusatival pronouns to refer to the noun repeatedly. Is there a general rule?

A:

It's not easy for me (native speaker) to distill the general rule. But, as a matter of fact:

¿Cómo hacen todo?

and

¿Cómo lo hacen?

would be correct constructions, though they would be slightly different questions. In the later, "lo", of course alludes to the thing that is being done ("todo" - direct object -  you can try replacing it by "el trabajo"), which here is left tacit; hence, this would only make sense if the previous sentence or the context had mentioned that, eg: "-Siempre hacen todo de la misma manera. -¿Cómo lo hacen?"
So, your book/teacher is right.
To say

¿Cómo lo hacen todo?

would be a redundant construction (see that it's a merge of the two above). Incorrect, but it might happen in casual speaking, perhaps for some emphasis.

¿Como todo lo hacen?

would be definitely wrong, that's never the order.


Q:

Why is Chrome searching for my favicon.ico when I serve up a file from ASP.NET MVC?

I have a controller in MVC serving up images from a database.
EDIT: This still happens if I serve up a file over completely standard means in MVC.
Every time I request my image, Google Chrome also searches for my favicon.ico.
To avoid unnecessary discussions about other things "I should also care about" let us assume I do not care for caching whatsoever in this example and I shall always return HTTP response 200 with the file.
In my controller I return the following:
return File(fileBytes, contentType);

After inspecting Fiddler 2, the following response is generated:

HTTP/1.1 200 OK
  Cache-Control: public
  Content-Type: image/gif
  ETag: oYu19wKo+KEHkyxZQ2WXAA==
  Server: Microsoft-IIS/7.0
  X-AspNetMvc-Version: 1.0
  X-AspNet-Version: 2.0.50727
  X-Powered-By: ASP.NET
  Date: Tue, 16 Jun 2009 18:48:45 GMT
  Content-Length: 29344

By comparison, this is the response in Fiddler from Google when I request (for the first time) the Google logo:

HTTP/1.1 200 OK
  Content-Type: image/gif
  Last-Modified: Wed, 07 Jun 2006 19:42:34 GMT
  Date: Tue, 16 Jun 2009 18:50:54 GMT
  Expires: Wed, 16 Jun 2010 18:50:54 GMT
  Cache-Control: public, max-age=31536000
  Server: gws
  Content-Length: 8706
  Age: 2

However, in Chrome after getting my image Chrome attempts to find my favicon.ico. It does not try this after requesting the Google logo.
Any ideas why this might be happening? From my understanding on HTML, the answer must be in the response header because surely that is all the client has to go on? Please correct me!
EDIT 2: It seems a lot of people have completely misunderstood the problem. The problem is not the lack of a favicon and the erroring requests in MVC - it's the problem of requesting a favicon when only an image is being loaded, with a content type of "IMAGE/JPEG", as opposed to a webpage with a content type of "TEXT/HTML"!!

A:

This has nothing to do with MVC. I am using webforms with a custom built log service and I stumbled upon this post wondering why I had continuous 'File does not exist' errors in my logs. This is locally on my development machine, I have no favicon.ico files in my projects, and I have tried IE, Firefox and Google trying to see which browser is the guilty party.
Every request from Google Chrome to my apps makes a request for a favicon.ico. I had to start logging browser locally to determine that it was in fact googles browser that is the culprit. I'd contact google if it bothers you. I just wanted to make sure it wasn't some new trojan infecting my chrome.

A:

The actual answer: It's a known, verified bug. *(recently fixed!... maybe?)
Looks like a known, longstanding issue with Chrome:
http://crbug.com/39402
If you want it fixed sooner, star the issue. More people starring the issue will likely increase its priority and possibly get it fixed faster.

****UPDATE 1***: As of May 15 of this year (2013)--four years after this question was asked--it looks like the issue has been fixed in version 29:
http://crbug.com/39402#c47
Feel free to undo all your hacks and workarounds. :]
****UPDATE 2 (2015-01)***: This is apparently still an issue for some users, according to the same issue link. :/

A:

Do you have a favicon? If not, perhaps that's why Chrome is attempting to find it every time for your website. For google it already has the favicon cached.


Q:

Can multiple SELECT FOR UPDATES in a single transaction cause a race condition (Postgres)?

I'm using Postgres 9.1. I'm wondering if using multiple SELECT FOR UPDATES in the same transaction could potentially cause a race condition.
2 concurrent transactions:

transaction 1: select for update on table 1 -- successfully acquires lock
transaction 2: select for update on table 2 -- successfully acquires lock
transaction 2: select for update on table 1 -- waiting for lock release from transaction 1
transaction 1: select for update on table 2 -- waiting for lock release from transaction 2

What happens in this situation? Does one of the waiting transactions eventually time out? If so, is there a way to configure the timeout duration?
edit: is deadlock_timeout the configuration I am looking for?

A:

Yes, you should look for the deadlock_timeout in the docs.
But your scenario doesn't means that there will be a deadlock, 'cos PostgreSQL is using row-level locks and it is not clear whether your transactions are concurring for the same rows.
Another option is to use serialization level higher then default READ COMMITTED. But in this case your application should be ready to receive exceptions with SQLCODE=40001:
ERROR:  could not serialize access due to concurrent update

This is expected, you should just re-try transaction as is.
A very good overview of Serializable isolation level you can find on the wiki.