fix missing 'PR |' episodes

fix missing 'PR |' episodes

# Generate a separate file with a line for each episode containing
# seriesNumber, episodeURL, seriesTitle, seasonNumber, episodeNumber,
# episodeTitle, episodeDuration, & episodeDescription with the same columns
# as the primary spreadsheet so they can be combined into one.
# Add to the number of episodes but with no terminating newline
#
# INVOCATION:
#       curl -s https://watch.mhzchoice.com/a-french-village/season:1 \
#           | awk -v EPISODE_INFO_FILE=$EPISODE_INFO_FILE -v SERIES_NUMBER=$lastRow \
#           -v NUM_EPISODES_FILE=$NUM_EPISODES_FILE -v ERROR_FILE=$ERROR_FILE \
#           -f getMHzFrom-episodePages.awk
#
# INPUT:
#        <title>A French Village - MHz Choice</title>
#  ---
#        <meta name="apple-itunes-app" content="app-id=1096194231, \
#        app-argument=https://watch.mhzchoice.com/detective-montalbano?page=2">
#  ---
#

#          18 Episodes
#

#  ---
#
47:58

#  ---
#        The Landing (June 12, 1940)\
#
#  ---
#
Episode 1

#

#
A doctor oversees the birth of a child. Directed by Phillipe Triboit, 2009.

#
#
This episode will be made available on August 8.

#

# OUTPUT:
#       $EPISODE_INFO_FILE & the number of episodes
#

# Extract whether this is a page 2
/<meta name="apple-itunes-app" content=".*?page=2">/ {
    page2 = "yes"
}

# Extract only the number of episodes, print them with no terminating newline
# but if this is page 2 skip to avoid double counting
/
> NUM_EPISODES_FILE
        next
    }
}

# Extract the series title
/<title>/ {
    sub (/.*<title>/,"")
    sub (/ - MHz Choice<.*/,"")
    gsub (/'/,"'")
    gsub (/"/,"\"\"")
    gsub (/&/,"\\&")
    if (match ($0, /^The /)) {
        $0 = substr($0, 5) ", The"
    }
    seriesTitle = $0
    next
}

# Extract the duration
/<div class="duration-container/ {
    split ($0,fld,"[<>]")
    episodeDuration = fld[3]
    gsub (/ /,"",episodeDuration)
    # Spreadsheets decipher 2 part durations as time-of-day so make sure they're 3 parts
    if (split (episodeDuration, tm, ":") == 2)
        episodeDuration = "00:" episodeDuration
    next
}

# Extract the episode URL, the episode type, the episode title, and the seasonNumber
/<strong title="/ {
    gsub (/'/,"'")
    split ($0,fld,"\"")
    episodeURL = fld[2]
    if (episodeURL ~ /-c-.[[:digit:]]{3,4}$/)
        episodeNumberFromURL = substr (episodeURL, length(episodeURL)-1, 2) + 0
    shortURL = episodeURL
    sub (/.*watch/,"watch",shortURL)
    # Default episodeType to "E"
    episodeType = "E"
    # If episode is a Trailer or Finale (i.e. First look), set episodeType to "T"
    if (episodeURL ~ /-trailer-|-finale-/)
        episodeType = "T"
    # If episode is a BONUS:, set episodeType to "X"
    if (episodeURL ~ /-c-x[[:digit:]]{3,4}$|montme-c-01001|richard-sammel-inetrview/)
        episodeType = "X"
    # Take care of extra fields introduced in February 2020
    titleString = substr ($0, match ($0, /strong title/))
    split (titleString,fld,"\"")
    episodeTitle = fld[2]
    if (episodeTitle ~ /^PR \|/) {
        print episodeTitle "\t" shortURL >> ERROR_FILE
        printf ("-1") >> NUM_EPISODES_FILE
    }
    #
    # If start of episodeTitle == seriesTitle ": ", remove the redundant part.
    if ((match (episodeTitle, seriesTitle ": ")) == 1) {
        episodeTitle = substr(episodeTitle, RLENGTH + 1)
    }
    gsub (/"/,"\"\"",episodeTitle)
    gsub (/&/,"\\&",episodeTitle)
    sub (/.*season:/,"")
    sub (/\/.*/,"")
    seasonNumber = $0
    next
}

# Extract the episode number, and correct if necessary
# Detective Montalbano requires special processing for page 2 episodeNumber
/<h4 class="/ {
    episodeNumber = $0
    sub (/.*Episode /,"",episodeNumber)
    sub (/<\/span>.*/,"",episodeNumber)
    episodeNumber = episodeNumber + 0
    if (seriesTitle == "Detective Montalbano" && page2 == "yes") {
        oldEpisodeNumber = episodeNumber
        episodeNumber += 24
        printf ("==> Changed E%02d to %s%02d: %s\n", oldEpisodeNumber, episodeType, \
                episodeNumber, shortURL) >> ERROR_FILE
    }
}

# WARNING - other scripts depend on the number and order of the fields below
# Extract the episode description and print the composed info
/
<span class=/,/<\/div>/ {
    if ($0 ~ /
 Changed %s00 to %s%02d: %s\n", episodeType, episodeType,
                        episodeNumberFromURL, shortURL) >> ERROR_FILE
                episodeNumber = episodeNumberFromURL
            } else {
                printf ("==> Episode number is 00: %s\n", shortURL) >> ERROR_FILE
            }
        }
        printf ("%d\t=HYPERLINK(\"%s\";\"%s, S%02d%s%02d, %s\"\)\t\t\t%s\t\t\t\t\t", \
                SERIES_NUMBER, episodeURL, seriesTitle, seasonNumber, episodeType, episodeNumber, \
                episodeTitle, episodeDuration) >> EPISODE_INFO_FILE
        # Need to account for multiple lines of description
        descriptionLinesFound = 0
        episodeDescription = ""
        # make sure there is no carryforward
        episodeNumber = ""
        episodeNumberFromURL = ""
    }
    if ($0 ~ /
/) {
        split ($0,fld,"[<>]")
        paragraph = fld[3]
        gsub (/"/,"\"",paragraph)
        gsub (/&/,"\\&",paragraph)
        # Could be in multiple paragraphs
        descriptionLinesFound += 1
        episodeDescription = episodeDescription (descriptionLinesFound == 1 ? "" : " ") paragraph
    }
    if ($0 ~ /<\/div>/) {
        if (episodeDescription == "")
            print "==> No description: " shortURL >> ERROR_FILE
        print episodeDescription >> EPISODE_INFO_FILE
    }
}

# Generate a separate file with a line for each episode containing
# seriesNumber, episodeURL, seriesTitle, seasonNumber, episodeNumber,
# episodeTitle, episodeDuration, & episodeDescription with the same columns
# as the primary spreadsheet so they can be combined into one.
# Add to the number of episodes but with no terminating newline
#
# INVOCATION:
#       curl -s https://watch.mhzchoice.com/a-french-village/season:1 \
#           | awk -v EPISODE_INFO_FILE=$EPISODE_INFO_FILE -v SERIES_NUMBER=$lastRow \
#           -v NUM_EPISODES_FILE=$NUM_EPISODES_FILE -v ERROR_FILE=$ERROR_FILE \
#           -f getMHzFrom-episodePages.awk
#
# INPUT:
#        <title>A French Village - MHz Choice</title>
#  ---
#        <meta name="apple-itunes-app" content="app-id=1096194231, \
#        app-argument=https://watch.mhzchoice.com/detective-montalbano?page=2">
#  ---
#

#          18 Episodes
#

#  ---
#
47:58

#  ---
#        The Landing (June 12, 1940)\
#
#  ---
#
Episode 1

#

#
A doctor oversees the birth of a child. Directed by Phillipe Triboit, 2009.

#
#
This episode will be made available on August 8.

#

# OUTPUT:
#       $EPISODE_INFO_FILE & the number of episodes
#

# Extract whether this is a page 2
/<meta name="apple-itunes-app" content=".*?page=2">/ {
    page2 = "yes"
}

# Extract only the number of episodes, print them with no terminating newline
# but if this is page 2 skip to avoid double counting
/
> NUM_EPISODES_FILE
        next
    }
}

# Extract the series title
/<title>/ {
    sub (/.*<title>/,"")
    sub (/ - MHz Choice<.*/,"")
    gsub (/'/,"'")
    gsub (/"/,"\"\"")
    gsub (/&/,"\\&")
    if (match ($0, /^The /)) {
        $0 = substr($0, 5) ", The"
    }
    seriesTitle = $0
    next
}

# Extract the duration
/<div class="duration-container/ {
    split ($0,fld,"[<>]")
    episodeDuration = fld[3]
    gsub (/ /,"",episodeDuration)
    # Spreadsheets decipher 2 part durations as time-of-day so make sure they're 3 parts
    if (split (episodeDuration, tm, ":") == 2)
        episodeDuration = "00:" episodeDuration
    next
}

# Extract the episode URL, the episode type, the episode title, and the seasonNumber
/<strong title="/ {
    gsub (/'/,"'")
    split ($0,fld,"\"")
    episodeURL = fld[2]
    if (episodeURL ~ /-c-.[[:digit:]]{3,4}$/)
        episodeNumberFromURL = substr (episodeURL, length(episodeURL)-1, 2) + 0
    shortURL = episodeURL
    sub (/.*watch/,"watch",shortURL)
    # Default episodeType to "E"
    episodeType = "E"
    # If episode is a Trailer or Finale (i.e. First look), set episodeType to "T"
    if (episodeURL ~ /-trailer-|-finale-/)
        episodeType = "T"
    # If episode is a BONUS:, set episodeType to "X"
    if (episodeURL ~ /-c-x[[:digit:]]{3,4}$|montme-c-01001|richard-sammel-inetrview/)
        episodeType = "X"
    # Take care of extra fields introduced in February 2020
    titleString = substr ($0, match ($0, /strong title/))
    split (titleString,fld,"\"")
    episodeTitle = fld[2]
    if (episodeTitle ~ /^PR \|/) {
        print episodeTitle "\t" shortURL >> ERROR_FILE
        printf ("-1") >> NUM_EPISODES_FILE
    }
    #
    # If start of episodeTitle == seriesTitle ": ", remove the redundant part.
    if ((match (episodeTitle, seriesTitle ": ")) == 1) {
        episodeTitle = substr(episodeTitle, RLENGTH + 1)
    }
    gsub (/"/,"\"\"",episodeTitle)
    gsub (/&/,"\\&",episodeTitle)
    sub (/.*season:/,"")
    sub (/\/.*/,"")
    seasonNumber = $0
    next
}

# Extract the episode number, and correct if necessary
# Detective Montalbano requires special processing for page 2 episodeNumber
/<h4 class="/ {
    sub (/.*Episode /,"")
    sub (/<\/span>.*/,"")
    episodeNumber = $0 + 0
    if (seriesTitle == "Detective Montalbano" && page2 == "yes") {
        oldEpisodeNumber = episodeNumber
        episodeNumber += 24
        printf ("==> Changed E%02d to %s%02d: %s\n", oldEpisodeNumber, episodeType, \
                episodeNumber, shortURL) >> ERROR_FILE
    }
    next
}

# WARNING - other scripts depend on the number and order of the fields below
# Extract the episode description and print the composed info
/<div class="transparent padding-top-medium"/,/<\/div>/ {
    if ($0 ~ /
 Changed %s00 to %s%02d: %s\n", episodeType, episodeType,
                        episodeNumberFromURL, shortURL) >> ERROR_FILE
                episodeNumber = episodeNumberFromURL
            } else {
                printf ("==> Episode number is 00: %s\n", shortURL) >> ERROR_FILE
            }
        }
        printf ("%d\t=HYPERLINK(\"%s\";\"%s, S%02d%s%02d, %s\"\)\t\t\t%s\t\t\t\t\t", \
                SERIES_NUMBER, episodeURL, seriesTitle, seasonNumber, episodeType, episodeNumber, \
                episodeTitle, episodeDuration) >> EPISODE_INFO_FILE
        # Need to account for multiple lines of description
        descriptionLinesFound = 0
        episodeDescription = ""
        # make sure there is no carryforward
        episodeNumber = ""
        episodeNumberFromURL = ""
    }
    if ($0 ~ /
/) {
        split ($0,fld,"[<>]")
        paragraph = fld[3]
        gsub (/"/,"\"",paragraph)
        gsub (/&/,"\\&",paragraph)
        # Could be in multiple paragraphs
        descriptionLinesFound += 1
        episodeDescription = episodeDescription (descriptionLinesFound == 1 ? "" : " ") paragraph
    }
    if ($0 ~ /<\/div>/) {
        if (episodeDescription == "")
            print "==> No description: " shortURL >> ERROR_FILE
        print episodeDescription >> EPISODE_INFO_FILE
    }
}


Fixed the decode script

Fixed the decode script

BEGIN {
	RS = ""
	FS = ""
	convert = "\nABCDEFGHIJKLMNOPQRSTUVWXYZ"

	# For character to number conversion
	for (n=0; n<256; n++) {
		ord[sprintf("%c", n)] = n
	}

	shift = 0
	lastNum = 0
}

function fiveBitDecode(char) {
	currentNum = ord[char]

	if (shift >= 8) {
		shift = shift - 8
	}

	while (shift < 8) {
		if (shift > 0 && shift < 5) {
			lastNum = or(lastNum, and(lshift(currentNum, 5 - shift), 0x1F))
			printf "%c", substr(convert, lastNum + 1, 1)
		}

		lastNum = and(rshift(currentNum, shift), 0x1F)
		if (shift <= 3) {
			printf "%c", substr(convert, lastNum + 1, 1)
			lastNum = 0
		}

		shift = shift + 5
	}
}

{
	for (i = 1; i <= NF; i++) {
		fiveBitDecode($i)
	}
}

BEGIN {
	RS = ""
	FS = ""
	convert = "\nABCDEFGHIJKLMNOPQRSTUVWXYZ"

	# For character to number conversion
	for (n=0; n<256; n++) {
		ord[sprintf("%c", n)] = n
	}

	shift = 0
	lastNum = 0
}

function fiveBitDecode(char) {
	currentNum = ord[char]

	if (shift >= 8) {
		shift = shift - 8
	}

	while (shift <= 8) {
		if (shift > 0 && shift < 5) {
			lastNum = or(lastNum, and(lshift(currentNum, 5 - shift), 0x1F))
			printf "%c", substr(convert, lastNum + 1, 1)
		}

		lastNum = and(rshift(currentNum, shift), 0x1F)
		if (shift <= 3) {
			printf "%c", substr(convert, lastNum + 1, 1)
			lastNum = 0
		}

		shift = shift + 5
	}
}

{
	for (i = 1; i <= NF; i++) {
		fiveBitDecode($i)
	}
}


rudimentary documentation for the includebloat script

Change-Id: I52209b70b3d93e488e6c9d16fefd179f2ac06afb


update

update

###########################################################
## generate proto payload struct
##
@include "client/header.awk"
BEGIN { RS = "==="; FS ="\n"
print ""
}
{

	pack_code = ""
	unpack_code = ""
	for (i=1;i<=NF;i++)
	{
		if ($i ~ /[A-Za-z_]+=/) {
			name = substr($i,1, match($i,/=/)-1)
			print "\npublic class " name " {"
			typeok = "true"
		} else {
			if ($i!="" && typeok) {
				print(_field($i))
				pack_code = pack_code "\t\t" _writer($i)
				unpack_code = unpack_code  _reader($i)
			}
		}

	}

	if (typeok) {
		#writer
		print "\n\tpublic void Pack(ByteArray w) {"
		print pack_code
		print "\t}"
		#reader
		print "\tpublic  static "name" UnPack(ByteArray reader){"
		print "\t\t"name " tbl = new " name "();"
		print unpack_code
		print "\t\treturn tbl;\n\t}"

		print "}"
	}

	typeok=false
}
END { }

function _field(line) {
	split(line, a, " ")

	if (a[2] in TYPES) {
		return "\tpublic " TYPES[a[2]] " " a[1] ";"
	} else if (a[2] == "array") {
		if (a[3] in TYPES) {
			return "\tpublic " TYPES[a[3]] "[] " a[1] ";"
		} else {
			return "\tpublic " a[3] "[] " a[1] ";"
		}
	} else {
		return "\tpublic " a[2]" " a[1] ";"
	}
}

function _writer(line) {
	split(line, a, " ")

	if (a[2] in WRITERS) {
		return "w." WRITERS[a[2]] "(this." a[1] ");\n"
	} else if (a[2] == "array") {
		ret = "w.WriteUnsignedInt16((UInt16)this." a[1] ".Length);\n"
		if (a[3] == "byte") {
			ret = ret "w.WriteRawBytes(this."a[1]");\n"
			return ret
		} else if (a[3] in TYPES) {
			ret = ret "\tforeach (int k in this." a[1] ") {\n"
				ret = ret "\t\tw." WRITERS[a[3]] "(this." a[1] "[k]);\n"
			return ret "\t}\n"
		} else {
			ret = ret "\tforeach ("a[3]" k in this." a[1] ") {\n"
				ret = ret "\t\tk.Pack(w);\n"
			return ret "\t}\n"
		}
	} else {
		return "this." a[1] ".Pack(w);\n"
	}
}

function _reader(line){
	if (line ~ /^#.*/ || line ~ /^===/) {
		return ""
	}
	ret =  "\t"
	split(line, a, " ")
	if (a[2] ==  "array") {
		if (a[3] == "byte") { 		## bytes
			ret = ret "\ttbl."a[1]" = reader.ReadBytes();"

		} else if (a[3] in READERS) {	## primitives

			ret = ret "\tUInt16 narr = reader.ReadUnsignedInt16();\n"
			ret = ret "\t\tfor (int i = 0; i < narr; i++) {\n"
			ret = ret "\t\t\ttbl."a[1]"[i] =reader."READERS[a[3]]"();\n"
			#ret = ret "\t\t\ttbl."a[1]"[i] =  v;\n"
			ret = ret "\t\t}"

		} else {	## struct

			ret = ret "\tUInt16 narr = reader.ReadUnsignedInt16();\n"
			ret = ret "\t\ttbl."a[1]" = new "a[3]"[narr];\n"
			ret = ret "\t\tfor (int i = 0; i < narr; i++){\n"
			ret = ret "\t\t\ttbl."a[1]"[i] = "a[3]".UnPack(reader);\n"
			ret = ret "\t\t}"

		}
	} else if (!(a[2] in READERS)) {
		ret = ret "\ttbl."a[1]"  = "a[2]".UnPack(reader);"
	} else {
		ret = ret "\ttbl."a[1]"  = reader." READERS[a[2]] "();"
	}
	return ret "\n";
}

###########################################################
## generate proto payload struct
##
@include "client/header.awk"
BEGIN { RS = "==="; FS ="\n"
print ""
}
{

	pack_code = ""
	unpack_code = ""
	for (i=1;i<=NF;i++)
	{
		if ($i ~ /[A-Za-z_]+=/) {
			name = substr($i,1, match($i,/=/)-1)
			print "\npublic class " name " {"
			typeok = "true"
		} else {
			if ($i!="" && typeok) {
				print(_field($i))
				pack_code = pack_code "\t\t" _writer($i)
				unpack_code = unpack_code  _reader($i)
			}
		}

	}

	if (typeok) {
		#writer
		print "\n\tpublic void Pack(ByteArray w) {"
		print pack_code
		print "\t}"
		#reader
		print "\tpublic  static "name" UnPack(ByteArray reader){"
		print "\t\t"name " tbl = new " name "();"
		print unpack_code
		print "\t\treturn tbl;\n\t}"

		print "}"
	}

	typeok=false
}
END { }

function _field(line) {
	split(line, a, " ")

	if (a[2] in TYPES) {
		return "\tpublic " TYPES[a[2]] " " a[1] ";"
	} else if (a[2] == "array") {
		if (a[3] in TYPES) {
			return "\tpublic " TYPES[a[3]] "[] " a[1] ";"
		} else {
			return "\tpublic " a[3] "[] " a[1] ";"
		}
	} else {
		return "\tpublic " a[2]" " a[1] ";"
	}
}

function _writer(line) {
	split(line, a, " ")

	if (a[2] in WRITERS) {
		return "w." WRITERS[a[2]] "(this." a[1] ");\n"
	} else if (a[2] == "array") {
		ret = "w.WriteU16(uint16(len(this." a[1] ")));\n"
		if (a[3] == "byte") {
			ret = ret "w.WriteRawBytes(this."a[1]");\n"
			return ret
		} else if (a[3] in TYPES) {
			ret = ret "\tforeach (int k in this." a[1] ") {\n"
				ret = ret "\t\tw." WRITERS[a[3]] "(this." a[1] "[k]);\n"
			return ret "\t}\n"
		} else {
			ret = ret "\tforeach (int k in this." a[1] ") {\n"
				ret = ret "\t\tthis."a[1]"[k].Pack(w);\n"
			return ret "\t}\n"
		}
	} else {
		return "this." a[1] ".Pack(w);\n"
	}
}

function _reader(line){
	if (line ~ /^#.*/ || line ~ /^===/) {
		return ""
	}
	ret =  "\t"
	split(line, a, " ")
	if (a[2] ==  "array") {
		if (a[3] == "byte") { 		## bytes
			ret = ret "\ttbl."a[1]" = reader.ReadBytes();"

		} else if (a[3] in READERS) {	## primitives

			ret = ret "\tshort narr = reader.ReadU16();\n"
			ret = ret "\t\tfor (int i = 0; i < narr; i++) {\n"
			ret = ret "\t\t\ttbl."a[1]"[i] =reader."READERS[a[3]]"();\n"
			#ret = ret "\t\t\ttbl."a[1]"[i] =  v;\n"
			ret = ret "\t\t}"

		} else {	## struct

			ret = ret "\tshort narr = reader.ReadU16();\n"
			ret = ret "\t\ttbl."a[1]" = new "a[3]"[narr];\n"
			ret = ret "\t\tfor (int i = 0; i < narr; i++){\n"
			ret = ret "\t\t\ttbl."a[1]"[i] = "a[3]".Unpack(reader);\n"
			ret = ret "\t\t}"

		}
	} else if (!(a[2] in READERS)) {
		ret = ret "\ttbl."a[1]"  = "a[2]".UnPack(reader);"
	} else {
		ret = ret "\ttbl."a[1]"  = reader." READERS[a[2]] "();"
	}
	return ret "\n";
}


Add a close command to avoid too many files opened problems (encountered with large libpcap file)

git-svn-id: 392d0e5ce652024192c571322d40dcc23d6d83b0@118 8a65f31f-a56f-4bd6-98e8-2755f64920ec

BEGIN {
  session_count = 0;
  FS="|"
  OFS="|"
}

{
  if ($3 ~ "[0-9]+") {
    # See if the current line is already in the table
    frame_file = destDir "/frames/Frame"$3".html"
    session_line = ""
    "grep -i \"" session_token "\" " frame_file | getline session_line
    close(grep)

    if (session_line == "" ) {
      $6 = "{0}"
      print $0

    } else {
      found = 0;
      split(session_line, array, " ")
      session = array[2]
      for (i=0; i < session_count; i++) {
        if (sessions[i] == session) {
          found = 1
          $6 = "{" i+1 "}"
          print $0
          break
        }
      }

      if (found == 0) {
        $6 = "{" session_count+1 "}"
        sessions[session_count++] = session
        print $0
        s = sprintf("echo '%2d: new session in frame %4s: %s' >&2", session_count, $3, session)
        system(s)
      }
    }

  } else {
    # Comment line, line starting with "#".
    # Requires no processing, just print it
    print $0
  }
}

BEGIN {
  session_count = 0;
  FS="|"
  OFS="|"
}

{
  if ($3 ~ "[0-9]+") {
    # See if the current line is already in the table
    frame_file = destDir "/frames/Frame"$3".html"
    session_line = ""
    "grep -i \"" session_token "\" " frame_file | getline session_line

    if (session_line == "" ) {
      $6 = "{0}"
      print $0

    } else {
      found = 0;
      split(session_line, array, " ")
      session = array[2]
      for (i=0; i < session_count; i++) {
        if (sessions[i] == session) {
          found = 1
          $6 = "{" i+1 "}"
          print $0
          break
        }
      }

      if (found == 0) {
        $6 = "{" session_count+1 "}"
        sessions[session_count++] = session
        print $0
        s = sprintf("echo '%2d: new session in frame %4s: %s' >&2", session_count, $3, session)
        system(s)
      }
    }

  } else {
    # Comment line, line starting with "#".
    # Requires no processing, just print it
    print $0
  }
}


removed debug output from nvidia plugin

removed debug output from nvidia plugin

#!/bin/bash
#  Copyright 2015 High Performance Computing Center, Stuttgart
#  Adapted for nvidia-smi by Anders Gidenstam 2015.
#  Copyright 2015 Anders Gidenstam, Chalmers University of Technology.
#
#  Licensed under the Apache License, Version 2.0 (the "License");
#  you may not use this file except in compliance with the License.
#  You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
#  Unless required by applicable law or agreed to in writing, software
#  distributed under the License is distributed on an "AS IS" BASIS,
#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#  See the License for the specific language governing permissions and
#  limitations under the License.
#

BEGIN {
    gpu_id=-1
}
(NR==1) {
    epoch_time=$0
}
# Collect interesting information from the nvidia-smi output.
# NOTE: This is fragile as it is strongly dependent on the nvidia-smi output.
/^GPU/ {
    gpu_id+=1
}
/GPU UUID/ {
    GPU[gpu_id, "UUID"] = $4
}
/GPU Current Temp/ {
    GPU[gpu_id, "temperature"] = $5
}
/Power Draw/ {
    GPU[gpu_id, "power"] = $4
}
#   Utilization (NOTE: The key needs to be unique in the output.)
/Gpu/ {
    GPU[gpu_id, "GPUutilization"] = $3
}
END {
    "hostname" |& getline hostname

    JSON=""
    JSON=JSON"{\"Timestamp\":\""epoch_time"\", "
    JSON=JSON"\"type\":\"power\", "
    JSON=JSON"\"hostname\":\""hostname"\""

    for (i=0; i <= gpu_id; i++) {
        JSON=JSON", \"GPU"i":power\":"GPU[i, "power"]""
        JSON=JSON", \"GPU"i":temperature\":"GPU[i, "temperature"]""
        JSON=JSON", \"GPU"i":GPUutilization\":"GPU[i, "GPUutilization"]""
    }
    JSON=JSON"}"

    URL=server"/"id
    "curl -i -s -H 'Accept: application/json' -H 'Content-Type:application/json' -X POST "URL " --data '"JSON"'" |& getline results
}

#!/bin/bash
#  Copyright 2015 High Performance Computing Center, Stuttgart
#  Adapted for nvidia-smi by Anders Gidenstam 2015.
#  Copyright 2015 Anders Gidenstam, Chalmers University of Technology.
#
#  Licensed under the Apache License, Version 2.0 (the "License");
#  you may not use this file except in compliance with the License.
#  You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
#  Unless required by applicable law or agreed to in writing, software
#  distributed under the License is distributed on an "AS IS" BASIS,
#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#  See the License for the specific language governing permissions and
#  limitations under the License.
#

BEGIN {
    gpu_id=-1
}
(NR==1) {
    epoch_time=$0
}
# Collect interesting information from the nvidia-smi output.
# NOTE: This is fragile as it is strongly dependent on the nvidia-smi output.
/^GPU/ {
    gpu_id+=1
}
/GPU UUID/ {
    GPU[gpu_id, "UUID"] = $4
}
/GPU Current Temp/ {
    GPU[gpu_id, "temperature"] = $5
}
/Power Draw/ {
    GPU[gpu_id, "power"] = $4
}
#   Utilization (NOTE: The key needs to be unique in the output.)
/Gpu/ {
    GPU[gpu_id, "GPUutilization"] = $3
}
END {
    "hostname" |& getline hostname

    JSON=""
    JSON=JSON"{\"Timestamp\":\""epoch_time"\", "
    JSON=JSON"\"type\":\"power\", "
    JSON=JSON"\"hostname\":\""hostname"\""

    for (i=0; i <= gpu_id; i++) {
        #JSON=JSON", \"GPU"i":UUID\":\""GPU[i, "UUID"]"\""
        JSON=JSON", \"GPU"i":power\":"GPU[i, "power"]""
        JSON=JSON", \"GPU"i":temperature\":"GPU[i, "temperature"]""
        JSON=JSON", \"GPU"i":GPUutilization\":"GPU[i, "GPUutilization"]""
    }
    JSON=JSON"}"
    print JSON

    URL=server"/"id
    "curl -i -s -H 'Accept: application/json' -H 'Content-Type:application/json' -X POST "URL " --data '"JSON"'" |& getline results

    print "Done with result:" results
}