Monday, November 28, 2016

c++ Pause Hack

A Snippet to use to make something pause until a debugger can attach to it.

void pauseForTest()
{
FILE *fin = 0;
do {
if (fin)
fclose(fin);
::Sleep(2000);
fin = fopen("C:\\delme\\pause.txt", "r");
} while (fin);
}

Wednesday, October 12, 2016

c++ Diagnostic Logging Hack

Here is a quick and dirty c++ logging hack.
I got tired of recreating something like it.


LoggingHack.h


#ifdef LOGGING_HACK

class JLogStream
{
public:
virtual ~JLogStream() {
}
};

extern JLogStream* jlogs;

extern JLogStream& operator<< (JLogStream& rlog, const std::string& val);
extern JLogStream& operator<< (JLogStream& rlog, const std::wstring& val);
extern JLogStream& operator<< (JLogStream& rlog, const char* zStr);
extern JLogStream& operator<< (JLogStream& rlog, const wchar_t* zStr);
extern JLogStream& operator<< (JLogStream& rlog, int val);
extern JLogStream& operator<< (JLogStream& rlog, std::stringstream &val);
extern JLogStream& operator<< (JLogStream& rlog, std::wstringstream &val);

#define JLOG( x ) { (*jlogs) << x << "\n"; }

#else
#define JLOG( x ) ;
#endif



LoggingHack.cpp




#ifdef LOGGING_HACK

#include <sstream>

#include "LoggingHack.h"

class JLogStreamImpl : public JLogStream
{
private:
FILE* jlog_fout1;
FILE* jlog_fout2;
FILE* jlog_fout3;

public:
JLogStreamImpl()
{
std::stringstream ss1;
ss1 << "c:\\delme\\" << LOGGING_HACK_FILE_BASE_NAME << ".log";
std::stringstream ss2;
ss2 << "c:\\delme\\" << LOGGING_HACK_FILE_BASE_NAME << " - " << ::GetTickCount() << ".log";
std::stringstream ss3;
ss3 << "c:\\delme\\" << LOGGING_HACK_FILE_BASE_NAME << "-rolling.log";

fopen_s(&jlog_fout1, ss1.str().c_str(), "wt");
fopen_s(&jlog_fout2, ss2.str().c_str(), "wt");
fopen_s(&jlog_fout3, ss3.str().c_str(), "at");

log(ss1.str().c_str());
}

void log(const char* zStr)
{
fwrite(zStr, strlen(zStr), 1, jlog_fout1);
fwrite(zStr, strlen(zStr), 1, jlog_fout2);
fwrite(zStr, strlen(zStr), 1, jlog_fout3);

fflush(jlog_fout1);
fflush(jlog_fout2);
fflush(jlog_fout3);
}

void log(const wchar_t* zStr)
{
int ncharLen;
ncharLen = WideCharToMultiByte(CP_UTF8, 0, zStr, -1, NULL, 0, NULL, NULL);
char* zstr = new char[ncharLen];
WideCharToMultiByte(CP_UTF8, 0, zStr, -1, zstr, ncharLen, NULL, NULL);
log("UNICODE:");
log(zstr);
}

void log(int val)
{
std::stringstream ss;
ss << val;
log(ss);
}

void log(std::stringstream &val)
{
log(val.str().c_str());
}

void log(std::wstringstream &val)
{
log(val.str().c_str());
}

};

extern JLogStream& operator<< (JLogStream& rlog, const std::string& val)
{
dynamic_cast<JLogStreamImpl*>(&rlog)->log(val.c_str());
return rlog;
}

extern JLogStream& operator<< (JLogStream& rlog, const std::wstring& val)
{
dynamic_cast<JLogStreamImpl*>(&rlog)->log(val.c_str());
return rlog;
}

extern JLogStream& operator<< (JLogStream& rlog, const char* zStr)
{
dynamic_cast<JLogStreamImpl*>(&rlog)->log(zStr);
return rlog;
}

extern JLogStream& operator<< (JLogStream& rlog, const wchar_t* zStr)
{
dynamic_cast<JLogStreamImpl*>(&rlog)->log(zStr);
return rlog;
}

extern JLogStream& operator<< (JLogStream& rlog, int val)
{
dynamic_cast<JLogStreamImpl*>(&rlog)->log(val);
return rlog;
}

extern JLogStream& operator<< (JLogStream& rlog, std::stringstream &val)
{
dynamic_cast<JLogStreamImpl*>(&rlog)->log(val);
return rlog;
}

extern JLogStream& operator<< (JLogStream& rlog, std::wstringstream &val)
{
dynamic_cast<JLogStreamImpl*>(&rlog)->log(val);
return rlog;
}


JLogStreamImpl theLogStream;

JLogStream* jlogs = &theLogStream;


#else
#define jlog(s) ;
#define jlog(s1, s2) ;
#endif



Include this in one cpp file of the dll or exe: Replacing LogBaseName with the desired name

#define LOGGING_HACK
#define LOGGING_HACK_FILE_BASE_NAME "LogBaseName"
#include "..\..\..\..\LoggingHack.cpp"


Include this in the other cpp files of the module:

#define LOGGING_HACK
#include "..\..\..\..\LoggingHack.h"


Use it like this:

JLOG(__FILE__ << "@" << __LINE__);





Friday, May 27, 2016

Virtualbox crashing VMs on startup

FYI:

*WARNING* Almost *all* of my VM's stopped working today.  I got some error on startup - but before they could really even start to start up.
*In case you have this problem* here is the work around I figured out, it is strange:
1. In virtual box there are some alternate ways to start a VM, one is called "Detachable Start"
2. Start your failing VM using "Detachable Start", you may have to start it twice
3. When it starts is will have crashed Windows and rebooted Windows ( so you will not have the state you saved the VM in )
4. Once it starts, snapshot it and that new snapshot will start up normally.

Friday, May 6, 2016

PostgreSQL database backup and restore

I needed to backup a DB then reset a VM and then put the backup on it.
This is what I did ( I think )

To dump it to a file of sql commands:

pg_dump -U [user-name] [source db name] -f [name of file to dump it to]

One nice thing is that it is human readable.

To reinstall it:

  1. I had to drop the existing DB with the same name ( I used pgAdmin III to do so)
  2. I recreated an empty DB with the same name, and since I needed extensions, I added the 2 extensions I needed.
  3. Then I loaded it in ( which could have been to a different DB name, but in my case I used the same one ):
pgsl -U [user-name] -d [db name to restore to] -f [name of the dump file]

Also note that the commands are found in PostgreSQL's bin directory.

Wednesday, April 13, 2016

Maven maven-antrun-plugin run executions in various phases

Maven maven-antrun-plugin run executions in various phases.
This is an example of that:


<plugin>
    <artifactId>maven-antrun-plugin</artifactId>
    <version>1.8</version>
    <executions>
        <execution>
            <id>1</id>
            <phase>generate-test-resources</phase>
            <configuration>
                <target>
                    <echo message="%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%"/>
                    <echo message="run - generate-test-resources"/>
                    <echo message="%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%"/>
                </target>
            </configuration>
            <goals>
                <goal>run</goal>
            </goals>
        </execution>
        <execution>
            <id>2</id>
            <phase>generate-resources</phase>
            <configuration>
                <target>
                    <echo message="%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%"/>
                    <echo message="run - generate-resources"/>
                    <echo message="%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%"/>
                </target>
            </configuration>
            <goals>
                <goal>run</goal>
            </goals>
        </execution>
        <execution>
            <id>443-4</id>
            <phase>process-test-classes</phase>
            <configuration>
                <target>
                    <echo message="%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%"/>
                    <echo message="process-test-classes"/>
                    <echo message="%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%"/>
                    <fail/>
                </target>
            </configuration>
            <goals>
                <goal>run</goal>
            </goals>
        </execution>
        <execution>
            <id>3</id>
            <phase>test</phase>
            <configuration>
                <target>
                    <echo message="%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%"/>
                    <echo message="DOES NOT RUN ! test"/>
                    <echo message="%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%"/>
                </target>
            </configuration>
            <goals>
                <goal>run</goal>
            </goals>
        </execution>
    </executions>
</plugin>

Tuesday, April 12, 2016

Disable Windows Maintenance on in a VM

Seems like it isn't worth it to let Windows do Maintenance on in a VM.
Turn it off like this:

Start -> Task Scheduler
Task Scheduler Library -> Microsoft -> Windows -> Task Scheduler

Turn it off in 2 places:

Regular Maintenance -> Context Menu -> Disable
Idle Maintenance -> Context Menu -> Disable


Thursday, April 7, 2016

Postgres getting the description of a table, specifically column names

Do this:

SELECT column_name, data_type FROM INFORMATION_SCHEMA.COLUMNS WHERE table_name = 'table_name_goes_here';

Tuesday, March 22, 2016

Am I running as Administrator in a Windows batch file

Am I running as Administrator in a Windows batch file

This is a great way to test:

whoami /groups | findstr /b BUILTIN\Administrators | findstr /c:"Enabled group" && GOTO RunningAsAdmin
ECHO This must be run as AdministratorGOTO NotRunningAsAdmin
:RunningAsAdmin


Monday, March 14, 2016

Maven antrun java.io.IOException: "Cannot run program" because "The filename or extension is too long"

There is an issue on where the command that maven antrun fails to run a java because the command line is too long.
In my case the classpath was way too long.

To fix it the classpath needs to be written to a manifest in a jar file and that needs to be used by java to get the classpath.

Here is an example of how to do it:


<manifestclasspath property="manifest.classpath"
                   jarfile="target/classpathSupplier.jar"
                   maxParentLevels="99">
    <classpath refid="maven.compile.classpath" />
</manifestclasspath>
<!-- Create pathing Jar --><jar destfile="target/classpathSupplier.jar">
    <manifest>
        <attribute name="Class-Path" value="${manifest.classpath}"/>
    </manifest>
</jar>
<java classname="org.me.ClassToRun" fork="yes" failonerror="true">
    <arg value="-someArg" />
    <!--<jvmarg value="-Xdebug"/>-->
    <!--<jvmarg value="-Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=5005"/>-->
    <classpath>
        <pathelement location="target/classpathSupplier.jar"/>
    </classpath>
</java>

Thursday, March 3, 2016

Windows password expiry and complexity, disabling

To disable Windows Password expire date and lower complexity, go to:
( This is good to do on VMs used for testing, that only occasionally run )


  1. Control Panel
  2. Administrative Tools
  3. Local Security Policy
  4. Account Policies
  5. Password Policy
Set Maximum password age to 0
Set Password complexity to Disabled.


Wednesday, February 24, 2016

Windows Command line redirect stdout and stderr to the same file

I keep forgetting how to do this, so:
Windows Command line redirect stdout and stderr to the same file like this:

someprog.exe > log.txt 2>&1

Monday, February 22, 2016

maven run ant command only

Here is how to run only the ant command in maven:

mvn antrun:run compile

Assuming the pom.xml is like this:

<profiles>
  <profile>
    <id>x86-windows</id>
    <activation>
      <activeByDefault>true</activeByDefault>
    </activation>
    <build>
      <plugins>

        <plugin>
          <artifactId>maven-antrun-plugin</artifactId>
          <executions>
            <execution>
              <id>compile</id>
              <phase>compile</phase>
              <goals>
                <goal>run</goal>
              </goals>
              <configuration>
                <tasks>
                  <echo>It worked! only running this part!</echo>



Thursday, February 18, 2016

Look into jar files using Windows Explorer

I sometimes want to look inside of jar files, and have been copying then to .zip and then using windows explorer to look inside them.  I just found out you can do this in a Admin Console:

assoc .jar=CompressedFolder

After which you can double click on a jar file in explorer and it gives you the choice to run it or open it explorer which then lets you look inside.

Monday, February 1, 2016

Using fiddler to change the port of a request

Using fiddler to change the port of a request.
Look here for how to do it:
http://docs.telerik.com/fiddler/KnowledgeBase/FiddlerScript/ModifyRequestOrResponse

Here is how I did it, I put this in the fiddler script:

if (true && oSession.fullUrl.Contains("someUrlPath/thatNeedsNewPort"))
        {
            oSession.host="localhost:12300";
        }

Friday, January 29, 2016

Postgres - Seeing what connections exist and where they are to and from

Found this Postgres command to show all the connections, their sources, what dbs they are connected to.

SELECT * FROM pg_stat_activity


Wednesday, January 20, 2016

Windows command line aws dynamodb update-item example

Here is an example of using update-item on an AWS dynamoDB

aws --region us-east-1 dynamodb update-item ^
--table-name my-dynamo-table-name --key ^
"{""Id"":{""S"":""IdToMatch""}}" ^
--update-expression "SET #H = :h" ^
--expression-attribute-names "{""#H"":""ColumnName""}" ^
--expression-attribute-values "{"":h"":{""S"":""TestString""}}"

This was inspirational:
http://docs.aws.amazon.com/cli/latest/reference//dynamodb/update-item.html

Windows command line aws dynamodb get-item example

It was a pain in the butt figuring out how to do dynamodb get-item using the Windows command line version of aws.

Here is what ended up working for me:

aws --region us-east-1 dynamodb get-item --table-name my-dynamo-table-name --key "{""Id"":{""S"":""IdToMatch""}}"

In my case the table just had a Hash key only and the name of the key is "Id" and the value of Id for the row I wanted was "IdToMatch"

See this for what _MAY_ explain how to use keys of types that are not "S":
http://docs.aws.amazon.com/cli/latest/reference/dynamodb/get-item.html




Tuesday, January 19, 2016

bash ssh magic with heredoc

I don't yet understand this:


ssh user@server "$( cat <<'EOT'
echo "These commands will be run on: $( uname -a )"
EOT
)"

But it probably is a good way to send args to a program as a block.
Seems like the chars between the 'EOT' are piped as input into the program that is before the <<

See this as one of the answers to
http://stackoverflow.com/questions/7114990/pseudo-terminal-will-not-be-allocated-because-stdin-is-not-a-terminal


Friday, January 15, 2016

Python argparse is great at handling command lines

Python argparse is great at handling command lines.
Be sure to look at it if you need to handle parameters.

You can create it multiple times in the same program if need be.

Wednesday, January 6, 2016

When will my Domain Password Expire

I needed to know when my Domain Password would expire.
This command reports it.

! Type it exactly like this, you don't need to substitute any values for anything !

In a CMD shell run this:

net user %USERNAME% /DOMAIN

One of the results will be something like this:

Password expires             1/10/2016 9:52:20 AM