text:
from __future__ import with_statement, print_function
from datetime import datetime, timedelta
import unittest
import os
from trello import TrelloClient, Unauthorized, ResourceUnavailable

class TrelloBoardTestCase(unittest.TestCase):
    """
    Tests for TrelloClient API. Note these test are in order to
    preserve dependencies, as an API integration cannot be tested
    independently.
    """

    @classmethod
    def setUpClass(cls):
        cls._trello = TrelloClient(os.environ['TRELLO_API_KEY'],
                                   token=os.environ['TRELLO_TOKEN'])
        for b in cls._trello.list_boards():
            if b.name == os.environ['TRELLO_TEST_BOARD_NAME']:
                cls._board = b
                break
        if not cls._board:
            cls.fail("Couldn't find test board")
        cls._list = cls._board.add_list(str(datetime.now()))

    def _add_card(self, name, description=None):
        try:
            card = self._list.add_card(name, description)
            self.assertIsNotNone(card, msg="card is None")
            self.assertIsNotNone(card.id, msg="id not provided")
            self.assertEquals(card.name, name)
            return card
        except Exception as e:
            print(str(e))
            self.fail("Caught Exception adding card")

    def test40_add_card(self):
        name = "Testing from Python - no desc"
        card = self._add_card(name)

        self.assertIsNotNone(card.closed, msg="closed not provided")
        self.assertIsNotNone(card.url, msg="url not provided")

        card2 = self._trello.get_card(card.id)
        self.assertEqual(card.name, card2.name)

    def test41_add_card(self):
        name = "Testing from Python"
        description = "Description goes here"
        card = self._add_card(name, description)

        self.assertEquals(card.description, description)
        self.assertIsNotNone(card.closed, msg="closed not provided")
        self.assertIsNotNone(card.url, msg="url not provided")
        card.fetch()
        self.assertIsNotNone(card.member_id)
        self.assertIsNotNone(card.short_id)
        self.assertIsNotNone(card.list_id)
        self.assertIsNotNone(card.comments)
        self.assertIsNotNone(card.checklists)
        self.assertIsInstance(card.create_date, datetime)

    def test42_add_card_with_comments(self):
        name = "Card with comments"
        comment = "Hello World!"
        card = self._add_card(name)
        card.comment(comment)
        card.fetch(True)

        self.assertEquals(card.description, '')
        self.assertIsNotNone(card.closed, msg="closed not provided")
        self.assertIsNotNone(card.url, msg="url not provided")
        self.assertEquals(len(card.comments), 1)
        self.assertEquals(card.comments[0]['data']['text'], comment)

    def test43_delete_checklist(self):
        name = "Card with comments"
        card = self._list.add_card(name)
        card.fetch(True)

        name = 'Checklists'
        checklist = card.add_checklist(name,
                                       ['item1', 'item2'])
        self.assertIsNotNone(checklist, msg="checklist is None")
        self.assertIsNotNone(checklist.id, msg="id not provided")
        self.assertEquals(checklist.name, name)
        checklist.delete()
        card.delete()

    def test44_attach_url_to_card(self):
        name = "Testing from Python - url"
        card = self._add_card(name)

        card.attach(name='lwn', url='http://lwn.net/')
        card.fetch()
        self.assertEquals(card.badges['attachments'], 1)
        card.delete()

    def test52_get_cards(self):
        cards = self._board.get_cards()
        self.assertEquals(len(cards), 4)

        for card in cards:
            if card.name == 'Testing from Python':
                self.assertEqual(card.description, 'Description goes here')
            elif card.name == 'Testing from Python - no desc':
                self.assertEqual(card.description, '')
            elif card.name == 'Card with comments':
                self.assertEqual(card.description, '')
            else:
                self.fail(msg='Unexpected card found')

        self.assertIsInstance(self._board.all_cards(), list)
        self.assertIsInstance(self._board.open_cards(), list)
        self.assertIsInstance(self._board.closed_cards(), list)

    def test52_add_card_set_due(self):
        name = "Testing from Python"
        description = "Description goes here"
        card = self._list.add_card(name, description)

        # Set the due date to be 3 days from now
        today = datetime.today()
        day_detla = timedelta(3)
        due_date = today + day_detla
        card.set_due(due_date)
        expected_due_date = card.due
        # Refresh the due date from cloud
        card.fetch()
        actual_due_date = card.due
        self.assertEquals(expected_due_date, actual_due_date)

    def test53_checklist(self):
        name = "Testing from Python"
        description = "Description goes here"
        card = self._list.add_card(name, description)

        name = 'Checklists'
        checklist = card.add_checklist(name,
                                       ['item1', 'item2'])
        self.assertIsNotNone(checklist, msg="checklist is None")
        self.assertIsNotNone(checklist.id, msg="id not provided")
        self.assertEquals(checklist.name, name)
        checklist.rename('Renamed')
        self.assertEquals(checklist.name, 'Renamed')

    def test54_set(self):
        name = "Testing from Python"
        description = "Description goes here"
        card = self._list.add_card('noname')
        card.set_name(name)
        card.set_description(description)
        self.assertEquals(card.name, name)
        self.assertEquals(card.description, description)

    def test60_delete_cards(self):
        cards = self._board.get_cards()
        for card in cards:
            card.delete()

    def test70_all_members(self):
        self.assertTrue(len(self._board.all_members()) > 0)

    def test71_normal_members(self):
        self.assertTrue(len(self._board.normal_members()) >= 0)

    def test72_admin_members(self):
        self.assertTrue(len(self._board.admin_members()) > 0)

    def test73_owner_members(self):
        members = self._board.owner_members()
        self.assertTrue(len(members) > 0)
        member = members[0].fetch()
        self.assertNotEqual(member.status, None)
        self.assertNotEqual(member.id, None)
        self.assertNotEqual(member.bio, None)
        self.assertNotEqual(member.url, None)
        self.assertNotEqual(member.username, None)
        self.assertNotEqual(member.full_name, None)
        self.assertNotEqual(member.initials, None)
        member2 = self._trello.get_member(member.id)
        self.assertEqual(member.username, member2.username)

    def test80_unauthorized(self):
        client = TrelloClient('a')
        self.assertRaises(Unauthorized,
                          client.list_boards)

    def test81_resource_unavailable(self):
        self.assertRaises(ResourceUnavailable,
                          self._trello.get_card, '0')

    def test90_get_board(self):
        board = self._trello.get_board(self._board.id)
        self.assertEqual(self._board.name, board.name)

def suite():
    # tests = ['test01_list_boards', 'test10_board_attrs', 'test20_add_card']
    # return unittest.TestSuite(map(TrelloBoardTestCase, tests))
    return unittest.TestLoader().loadTestsFromTestCase(TrelloBoardTestCase)

if __name__ == "__main__":
    unittest.main()


text:
"""Tests for oryx.bijectors.bijectors_extensions."""

from absl.testing import absltest
from absl.testing import parameterized
import jax
import numpy as onp

from oryx import bijectors as bb
from oryx import core
from oryx.internal import test_util

BIJECTORS = [
    ('exp', lambda: bb.Exp(), 1., []),  # pylint: disable=unnecessary-lambda
    ('shift', lambda: bb.Shift(3.), 1., [3.]),
    ('Scale', lambda: bb.Scale(2.), 1., [2.]),
    ('transform_diagonal', lambda: bb.TransformDiagonal(bb.Exp()),
     onp.eye(2).astype(onp.float32), []),
    ('invert', lambda: bb.Invert(bb.Exp()), 1., []),
]

class BijectorsExtensionsTest(test_util.TestCase):

  @parameterized.named_parameters(BIJECTORS)
  def test_forward(self, bij, inp, flat):
    del flat
    b = bij()
    b.forward(inp)

  @parameterized.named_parameters(BIJECTORS)
  def test_inverse(self, bij, inp, flat):
    del flat
    b = bij()
    b.inverse(inp)

  @parameterized.named_parameters(BIJECTORS)
  def test_flatten(self, bij, inp, flat):
    del inp
    b = bij()
    flat_p, _ = jax.tree_util.tree_flatten(b)
    for e1, e2 in zip(flat_p, flat):
      onp.testing.assert_allclose(e1, e2)

  @parameterized.named_parameters(BIJECTORS)
  def test_inverse_transformation(self, bij, inp, flat):
    del flat
    b = bij()
    onp.testing.assert_allclose(core.inverse(b, inp)(inp), b.inverse(inp))

  @parameterized.named_parameters(BIJECTORS)
  def test_ildj_transformation(self, bij, inp, flat):
    del flat
    b = bij()
    onp.testing.assert_allclose(
        core.ildj(b, inp)(inp), b.inverse_log_det_jacobian(inp, onp.ndim(inp)))

if __name__ == '__main__':
  absltest.main()

redpajama_set_name: RedPajamaGithub


text:
package net.apexes.wsonrpc.core;

import java.io.IOException;

/**
 *
 * @author HeDYn
 *
 */
public interface Transport {

    /**
     *
     * @param bytes
     * @throws IOException
     */
    void sendBinary(byte[] bytes) throws IOException;

}


text:
require 'bundler'
Bundler.require
Bundler.require :test


text:
function Connect-SfBOnline {

    [CmdletBinding()]
    param(

        [Parameter(
            ValueFromPipeline = $true,
            Mandatory = $true,
            HelpMessage = 'Credentials in Azure AD to access Office 365.'
        )]
        [System.Management.Automation.Credential()]
        [PSCredential]$Credential
    )

    $Module = Get-Module -Name 'SkypeOnlineConnector' -ListAvailable

    if ($null -eq $Module) {

        Write-Warning -Message "Requires the module 'SkypeOnlineConnector'"
        Write-Verbose -Message 'Download from: https://www.microsoft.com/en-us/download/details.aspx?id=39366' -Verbose
        return
    }
    else {

        if ($null -ne (Get-SfBOnlineSession)) {

            Write-Verbose -Message 'Skype for Business Online PowerShell PSSession already existis.'
            Write-Verbose -Message 'Disconnect from the current session to start a new one.'
            return
        }
        try {

            Import-Module -Name 'SkypeOnlineConnector' -DisableNameChecking -ErrorAction Stop -WarningAction SilentlyContinue -Verbose:$false
        }
        catch {

            Write-Warning -Message ('Unable to Import-Module "LyncOnlineConnector" - {0}' -f $_.Exception.Message)
            return
        }

        try {

            $null = New-CsOnlineSession -Credential $Credential -ErrorAction Stop -WarningAction SilentlyContinue -Verbose:$false
        }
        catch {

            Write-Warning -Message ('Unable to create PSSession for Skype for Business Online - {0}' -f $_.Exception.Message)
            return
        }
        try {

            $null = Import-PSSession -Session (Get-SfBOnlineSession) -DisableNameChecking -AllowClobber -ErrorAction Stop -WarningAction SilentlyContinue -Verbose:$false
        }
        catch {

            Write-Warning -Message ('Unable to load PSSession for Skype for Business Online - {0}' -f $_.Exception.Message)
            return
        }
    }
}


text:
package de.kit.sensorlibrary.permissions;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;

import de.kit.sensorlibrary.sensor.PermissionInterface;

/**
 * Created by Robert Zetzsche on 16.03.2017.
 */

public class PermissionHandler extends Handler {
    PermissionInterface permissionInterface;

    public PermissionHandler(PermissionInterface permissionInterface) {
        this.permissionInterface = permissionInterface;
    }

    @Override
    public void handleMessage(Message msg) {
        super.handleMessage(msg);
        Bundle bundle = msg.getData();
        permissionInterface.permissionGranted(bundle.getBoolean("isGranted"));
    }
}


text:
/* imonomy.js v3.1.0
Updated : 2017-03-15 */

var utils = require('src/utils.js');
var adloader = require('src/adloader.js');
var bidmanager = require('src/bidmanager.js');
var bidfactory = require('src/bidfactory.js');
const adaptermanager = require('src/adaptermanager');
var STATUSCODES = require('src/constants.json').STATUS;

function ImonomyAdapter() {
  return {
    callBids: _callBids
  };

  function _callBids(params) {
    var request = [];
    var siteRef = '';
    var screen_w = '';
    var screen_h = '';
    var language = '';
    var pxr = '';
    var keywords = '';
    var connectiontype = '';
    var domain = '';
    var page = '';
    var bid, i, l;
    var bids = params.bids;
    var imonomy_domain = 'b.imonomy.com';
    var callbackName = '_hb_' + utils.getUniqueIdentifierStr();

    try { siteRef = document.referrer } catch (e) { }
    try { domain = window.location.host } catch (e) { }
    try { pxr = window.devicePixelRatio } catch (e) { }
    try { screen_w = screen.width || document.body.clientWidth || 0 } catch (e) { }
    try { screen_h = screen.height || document.body.clientHeight || 0 } catch (e) { }
    try { page = window.location.pathname + location.search + location.hash } catch (e) { }

    try {
      var meta = document.getElementsByTagName('meta') || {};
      keywords = ('keywords' in meta) ? meta['keywords'].content : ''
    } catch (e) {}

    try {
      var connection = navigator.connection || navigator.mozConnection || navigator.webkitConnection;
      connectiontype = (connection != undefined) ? connection.type : '';
    } catch (e) {}

    try {
      var language_tmp = document.documentElement.lang || navigator.language || navigator.userLanguage || '';
      language = language_tmp.split('-')[0]
    } catch (e) {}

    try {
      var data = {
        pxr: pxr,
        page: page,
        domain: domain,
        siteRef: siteRef,
        screen_w: screen_w,
        screen_h: screen_h,
        language: language,
        keywords: keywords,
        connectiontype: connectiontype,
        requestId: params['requestId'],
        bidderRequestId: params['bidderRequestId'],
        callback: '$$PREBID_GLOBAL$$.' + callbackName,
        publisher_id: params['bids'][0]['params']['publisher_id'],
        bids: encodeURIComponent(JSON.stringify(params['bids']))
      };

      var protocol = (document.location.protocol === 'https:') ? 'https' : 'http';
      request.unshift(protocol + '://' + imonomy_domain + '/openrtb/hb/' + params['bids'][0]['params']['publisher_id'] + '?id=' + utils.getUniqueIdentifierStr());

      for (var key in data) {
        if (data.hasOwnProperty(key)) {
          request.push(key + '=' + encodeURIComponent(data[key]));
        }
      }

      for (i = 0, l = bids.length; i < l; i++) {
        bid = bids[i];
        request.push(formRequestUrl(bid.params));
      }

      $$PREBID_GLOBAL$$[callbackName] = handleCallback(bids);

      adloader.loadScript(request.join('&'));
    } catch (e) {
    }
  }

  function formRequestUrl(reqData) {
    var key;
    var url = [];

    for (key in reqData) {
      if (reqData.hasOwnProperty(key) && reqData[key]) {
        url.push(key, '=', reqData[key], '&');
      }
    }

    return btoa(url.join('').slice(0, -1));
  }

  function handleCallback(bids) {
    return function handleResponse(adItems) {
      try {
        var bidObject;
        var bidder = 'imonomy';
        var adItem;
        var bid;

        try {
          if (adItems.um_list) {
            _processUserMatchings(adItems.um_list);
          }
        } catch (e) { }

        adItems = adItems.ads;

        for (var i = 0, l = bids.length; i < l; i++) {
          bid = bids[i];
          adItem = getAdItem(adItems, bids[i].bidId);

          if (adItem) {
            bidObject = bidfactory.createBid(STATUSCODES.GOOD, bid);
            bidObject.bidderCode = bidder;
            bidObject.ad = adItem.ad;
            bidObject.cpm = adItem.cpm;
            bidObject.cur = adItem.cur;
            bidObject.width = adItem.width;
            bidObject.height = adItem.height;
            bidmanager.addBidResponse(bid.placementCode, bidObject);
          } else {
            bidObject = bidfactory.createBid(STATUSCODES.NO_BID, bid);
            bidObject.bidderCode = bidder;
            bidmanager.addBidResponse(bid.placementCode, bidObject);
          }
        }
      } catch (e) {
      }
    };
  }

  function _processUserMatchings(userMatchings) {
    var headElem = document.getElementsByTagName('head')[0];
    var createdElem;

    utils._each(userMatchings, function (userMatching) {
      createdElem = undefined;
      switch (userMatching.type) {
        case 'redirect':
          createdElem = document.createElement('img');
          break;
        case 'iframe':
          createdElem = utils.createInvisibleIframe();
          break;
        case 'js':
          createdElem = document.createElement('script');
          createdElem.type = 'text/javascript';
          createdElem.async = true;
          break;
      }
      if (createdElem) {
        createdElem.src = decodeURIComponent(userMatching.Url);
        headElem.insertBefore(createdElem, headElem.firstChild);
      }
    });
  }

  function getAdItem(adItems, imp) {
    adItems = adItems || []
    for (var i = 0, l = adItems.length; i < l; i++) {
      if (adItems[i].impression_id == imp) {
        return adItems[i];
      }
    }

    return null;
  }
}

adaptermanager.registerBidAdapter(new ImonomyAdapter(), 'imonomy');
module.exports = ImonomyAdapter;


text:
CUR_DIR=`pwd`

MY_HADOOP_HOME=/usr/local/hadoop
MY_CLASSPATH=$MY_HADOOP_HOME/share/hadoop/common/hadoop-common-2.6.0.jar:$MY_HADOOP_HOME/share/hadoop/common/lib/hadoop-annotations-2.6.0.jar:$MY_HADOOP_HOME/share/hadoop/mapreduce/hadoop-mapreduce-client-core-2.6.0.jar:$MY_HADOOP_HOME/share/hadoop/common/lib/commons-cli-1.2.jar

mkdir -p $CUR_DIR/classes
javac -Xlint -classpath $MY_CLASSPATH -d $CUR_DIR/classes $CUR_DIR/GaussianBlur.java
jar -cvf gaussian_blur.jar -C $CUR_DIR/classes .


text:
package org.thingsboard.server.dao.util;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface SqlDao {
}


text:
import datetime
import json
import os
import traceback

from dateutil.parser import parse

from great_expectations import DataContext
from great_expectations.cli.v012.upgrade_helpers.base_upgrade_helper import (
    BaseUpgradeHelper,
)
from great_expectations.data_context.store import (
    DatabaseStoreBackend,
    HtmlSiteStore,
    InMemoryStoreBackend,
    MetricStore,
    TupleFilesystemStoreBackend,
    TupleGCSStoreBackend,
    TupleS3StoreBackend,
    ValidationsStore,
)
from great_expectations.data_context.types.resource_identifiers import (
    ValidationResultIdentifier,
)

"""
NOTE (Shinnnyshinshin): This is not the UpgradeHelperV11 that is normally used by the CLI.

As of 2022-01, it is only triggered by running the CLI-command:

great_expectations --v2-api upgrade project

on a great_expectations/ directory, and cannot be used to fully migrate a v1.0 or v2.0 configuration to a v3.0 config. A
task for the full deprecation of this path has been placed in the backlog.
"""

class UpgradeHelperV11(BaseUpgradeHelper):
    def __init__(self, data_context=None, context_root_dir=None) -> None:
        assert (
            data_context or context_root_dir
        ), "Please provide a data_context object or a context_root_dir."

        self.data_context = data_context or DataContext(
            context_root_dir=context_root_dir
        )

        self.upgrade_log = {
            "skipped_validations_stores": {
                "database_store_backends": [],
                "unsupported": [],
            },
            "skipped_docs_validations_stores": {"unsupported": []},
            "skipped_metrics_stores": {
                "database_store_backends": [],
                "unsupported": [],
            },
            "exceptions": [
                # {
                #     "validation_store_name": store_name
                #     "src": src_url,
                #     "dest": dest_url,
                #     "exception_message": exception_message,
                # },
                # {
                #     "site_name": site_name,
                #     "src": src_url,
                #     "dest": dest_url,
                #     "exception_message": exception_message,
                # }
            ],
            "upgraded_validations_stores": {
                # STORE_NAME: {
                #     "validations_updated": [{
                #         "src": src_url,
                #         "dest": dest_url
                #     }],
                #     "exceptions": BOOL
                # }
            },
            "upgraded_docs_site_validations_stores": {
                # SITE_NAME: {
                #     "validation_result_pages_updated": [{
                #         src: src_url,
                #         dest: dest_url
                #     }],
                #     "exceptions": BOOL
                # }
            },
        }

        self.upgrade_checklist = {
            "validations_store_backends": {},
            "docs_validations_store_backends": {},
        }

        self.validation_run_times = {}

        self.run_time_setters_by_backend_type = {
            TupleFilesystemStoreBackend: self._get_tuple_filesystem_store_backend_run_time,
            TupleS3StoreBackend: self._get_tuple_s3_store_backend_run_time,
            TupleGCSStoreBackend: self._get_tuple_gcs_store_backend_run_time,
        }

        self._generate_upgrade_checklist()

    def _generate_upgrade_checklist(self) -> None:
        for (store_name, store) in self.data_context.stores.items():
            if not isinstance(store, (ValidationsStore, MetricStore)):
                continue
            elif isinstance(store, ValidationsStore):
                self._process_validations_store_for_checklist(store_name, store)
            elif isinstance(store, MetricStore):
                self._process_metrics_store_for_checklist(store_name, store)

        sites = (
            self.data_context.project_config_with_variables_substituted.data_docs_sites
        )

        if sites:
            for site_name, site_config in sites.items():
                self._process_docs_site_for_checklist(site_name, site_config)

    def _process_docs_site_for_checklist(self, site_name, site_config) -> None:
        site_html_store = HtmlSiteStore(
            store_backend=site_config.get("store_backend"),
            runtime_environment={
                "data_context": self.data_context,
                "root_directory": self.data_context.root_directory,
                "site_name": site_name,
            },
        )
        site_validations_store_backend = site_html_store.store_backends[
            ValidationResultIdentifier
        ]

        if isinstance(
            site_validations_store_backend,
            tuple(list(self.run_time_setters_by_backend_type.keys())),
        ):
            self.upgrade_checklist["docs_validations_store_backends"][
                site_name
            ] = site_validations_store_backend
        else:
            self.upgrade_log["skipped_docs_validations_stores"]["unsupported"].append(
                {
                    "site_name": site_name,
                    "validations_store_backend_class": type(
                        site_validations_store_backend
                    ).__name__,
                }
            )

    def _process_validations_store_for_checklist(self, store_name, store) -> None:
        store_backend = store.store_backend
        if isinstance(store_backend, DatabaseStoreBackend):
            self.upgrade_log["skipped_validations_stores"][
                "database_store_backends"
            ].append(
                {
                    "store_name": store_name,
                    "store_backend_class": type(store_backend).__name__,
                }
            )
        elif isinstance(
            store_backend, tuple(list(self.run_time_setters_by_backend_type.keys()))
        ):
            self.upgrade_checklist["validations_store_backends"][
                store_name
            ] = store_backend
        else:
            self.upgrade_log["skipped_validations_stores"]["unsupported"].append(
                {
                    "store_name": store_name,
                    "store_backend_class": type(store_backend).__name__,
                }
            )

    def _process_metrics_store_for_checklist(self, store_name, store) -> None:
        store_backend = store.store_backend
        if isinstance(store_backend, DatabaseStoreBackend):
            self.upgrade_log["skipped_metrics_stores"][
                "database_store_backends"
            ].append(
                {
                    "store_name": store_name,
                    "store_backend_class": type(store_backend).__name__,
                }
            )
        elif isinstance(store_backend, InMemoryStoreBackend):
            pass
        else:
            self.upgrade_log["skipped_metrics_stores"]["unsupported"].append(
                {
                    "store_name": store_name,
                    "store_backend_class": type(store_backend).__name__,
                }
            )

    def _upgrade_store_backend(
        self, store_backend, store_name=None, site_name=None
    ) -> None:
        assert store_name or site_name, "Must pass either store_name or site_name."
        assert not (
            store_name and site_name
        ), "Must pass either store_name or site_name, not both."

        try:
            validation_source_keys = store_backend.list_keys()
        except Exception as e:
            exception_traceback = traceback.format_exc()
            exception_message = (
                f'{type(e).__name__}: "{str(e)}".  '
                f'Traceback: "{exception_traceback}".'
            )
            self._update_upgrade_log(
                store_backend=store_backend,
                store_name=store_name,
                site_name=site_name,
                exception_message=exception_message,
            )

        for source_key in validation_source_keys:
            try:
                run_name = source_key[-2]
                dest_key = None
                if run_name not in self.validation_run_times:
                    self.run_time_setters_by_backend_type.get(type(store_backend))(
                        source_key, store_backend
                    )
                dest_key_list = list(source_key)
                dest_key_list.insert(-1, self.validation_run_times[run_name])
                dest_key = tuple(dest_key_list)
            except Exception as e:
                exception_traceback = traceback.format_exc()
                exception_message = (
                    f'{type(e).__name__}: "{str(e)}".  '
                    f'Traceback: "{exception_traceback}".'
                )
                self._update_upgrade_log(
                    store_backend=store_backend,
                    source_key=source_key,
                    dest_key=dest_key,
                    store_name=store_name,
                    site_name=site_name,
                    exception_message=exception_message,
                )

            try:
                if store_name:
                    self._update_validation_result_json(
                        source_key=source_key,
                        dest_key=dest_key,
                        run_name=run_name,
                        store_backend=store_backend,
                    )
                else:
                    store_backend.move(source_key, dest_key)
                self._update_upgrade_log(
                    store_backend=store_backend,
                    source_key=source_key,
                    dest_key=dest_key,
                    store_name=store_name,
                    site_name=site_name,
                )
            except Exception as e:
                exception_traceback = traceback.format_exc()
                exception_message = (
                    f'{type(e).__name__}: "{str(e)}".  '
                    f'Traceback: "{exception_traceback}".'
                )
                self._update_upgrade_log(
                    store_backend=store_backend,
                    source_key=source_key,
                    dest_key=dest_key,
                    store_name=store_name,
                    site_name=site_name,
                    exception_message=exception_message,
                )

    def _update_upgrade_log(
        self,
        store_backend,
        source_key=None,
        dest_key=None,
        store_name=None,
        site_name=None,
        exception_message=None,
    ) -> None:
        assert store_name or site_name, "Must pass either store_name or site_name."
        assert not (
            store_name and site_name
        ), "Must pass either store_name or site_name, not both."

        try:
            src_url = store_backend.get_url_for_key(source_key) if source_key else "N/A"
        except Exception:
            src_url = f"Unable to generate URL for key: {source_key}"
        try:
            dest_url = store_backend.get_url_for_key(dest_key) if dest_key else "N/A"
        except Exception:
            dest_url = f"Unable to generate URL for key: {dest_key}"

        if not exception_message:
            log_dict = {"src": src_url, "dest": dest_url}
        else:
            key_name = "validation_store_name" if store_name else "site_name"
            log_dict = {
                key_name: store_name if store_name else site_name,
                "src": src_url,
                "dest": dest_url,
                "exception_message": exception_message,
            }
            self.upgrade_log["exceptions"].append(log_dict)

        if store_name:
            if exception_message:
                self.upgrade_log["upgraded_validations_stores"][store_name][
                    "exceptions"
                ] = True
            else:
                self.upgrade_log["upgraded_validations_stores"][store_name][
                    "validations_updated"
                ].append(log_dict)
        else:
            if exception_message:
                self.upgrade_log["upgraded_docs_site_validations_stores"][site_name][
                    "exceptions"
                ] = True
            else:
                self.upgrade_log["upgraded_docs_site_validations_stores"][site_name][
                    "validation_result_pages_updated"
                ].append(log_dict)

    def _update_validation_result_json(
        self, source_key, dest_key, run_name, store_backend
    ) -> None:
        new_run_id_dict = {
            "run_name": run_name,
            "run_time": self.validation_run_times[run_name],
        }
        validation_json_dict = json.loads(store_backend.get(source_key))
        validation_json_dict["meta"]["run_id"] = new_run_id_dict
        store_backend.set(dest_key, json.dumps(validation_json_dict))
        store_backend.remove_key(source_key)

    def _get_tuple_filesystem_store_backend_run_time(
        self, source_key, store_backend
    ) -> None:
        run_name = source_key[-2]
        try:
            self.validation_run_times[run_name] = parse(run_name).strftime(
                "%Y%m%dT%H%M%S.%fZ"
            )
        except (ValueError, TypeError):
            source_path = os.path.join(
                store_backend.full_base_directory,
                store_backend._convert_key_to_filepath(source_key),
            )
            path_mod_timestamp = os.path.getmtime(source_path)
            path_mod_iso_str = datetime.datetime.fromtimestamp(
                path_mod_timestamp
            ).strftime("%Y%m%dT%H%M%S.%fZ")
            self.validation_run_times[run_name] = path_mod_iso_str

    def _get_tuple_s3_store_backend_run_time(self, source_key, store_backend) -> None:
        import boto3

        s3 = boto3.resource("s3")
        run_name = source_key[-2]

        try:
            self.validation_run_times[run_name] = parse(run_name).strftime(
                "%Y%m%dT%H%M%S.%fZ"
            )
        except (ValueError, TypeError):
            source_path = store_backend._convert_key_to_filepath(source_key)
            if not source_path.startswith(store_backend.prefix):
                source_path = os.path.join(store_backend.prefix, source_path)
            source_object = s3.Object(store_backend.bucket, source_path)
            source_object_last_mod = source_object.last_modified.strftime(
                "%Y%m%dT%H%M%S.%fZ"
            )

            self.validation_run_times[run_name] = source_object_last_mod

    def _get_tuple_gcs_store_backend_run_time(self, source_key, store_backend) -> None:
        from google.cloud import storage

        gcs = storage.Client(project=store_backend.project)
        bucket = gcs.get_bucket(store_backend.bucket)
        run_name = source_key[-2]

        try:
            self.validation_run_times[run_name] = parse(run_name).strftime(
                "%Y%m%dT%H%M%S.%fZ"
            )
        except (ValueError, TypeError):
            source_path = store_backend._convert_key_to_filepath(source_key)
            if not source_path.startswith(store_backend.prefix):
                source_path = os.path.join(store_backend.prefix, source_path)
            source_blob_created_time = bucket.get_blob(
                source_path
            ).time_created.strftime("%Y%m%dT%H%M%S.%fZ")

            self.validation_run_times[run_name] = source_blob_created_time

    def _get_skipped_store_and_site_names(self):
        validations_stores_with_database_backends = [
            store_dict.get("store_name")
            for store_dict in self.upgrade_log["skipped_validations_stores"][
                "database_store_backends"
            ]
        ]
        metrics_stores_with_database_backends = [
            store_dict.get("store_name")
            for store_dict in self.upgrade_log["skipped_metrics_stores"][
                "database_store_backends"
            ]
        ]

        unsupported_validations_stores = [
            store_dict.get("store_name")
            for store_dict in self.upgrade_log["skipped_validations_stores"][
                "unsupported"
            ]
        ]
        unsupported_metrics_stores = [
            store_dict.get("store_name")
            for store_dict in self.upgrade_log["skipped_metrics_stores"]["unsupported"]
        ]

        stores_with_database_backends = (
            validations_stores_with_database_backends
            + metrics_stores_with_database_backends
        )
        stores_with_unsupported_backends = (
            unsupported_validations_stores + unsupported_metrics_stores
        )
        doc_sites_with_unsupported_backends = [
            doc_site_dict.get("site_name")
            for doc_site_dict in self.upgrade_log["skipped_docs_validations_stores"][
                "unsupported"
            ]
        ]
        return (
            stores_with_database_backends,
            stores_with_unsupported_backends,
            doc_sites_with_unsupported_backends,
        )

    def get_upgrade_overview(self):
        (
            skip_with_database_backends,
            skip_with_unsupported_backends,
            skip_doc_sites_with_unsupported_backends,
        ) = self._get_skipped_store_and_site_names()
        validations_store_name_checklist = [
            store_name
            for store_name in self.upgrade_checklist[
                "validations_store_backends"
            ].keys()
        ]
        site_name_checklist = [
            site_name
            for site_name in self.upgrade_checklist[
                "docs_validations_store_backends"
            ].keys()
        ]

        upgrade_overview = """\
<cyan>\
++=====================================================++
|| UpgradeHelperV11: Upgrade Overview (V2-API Version) ||
++=====================================================++\
</cyan>

**WARNING**
You have run the 'great_expectations project upgrade' command using the --v2-api flag, which is not able to perform the full upgrade to the configuration (3.0) that is fully compatible with the V3-API

Please re-run the 'great_expectations project upgrade' command without the --v2-api flag.

UpgradeHelperV11 will upgrade your project to be compatible with Great Expectations 0.11.x.
"""
        if not any(
            [
                validations_store_name_checklist,
                site_name_checklist,
                skip_with_database_backends,
                skip_with_unsupported_backends,
                skip_doc_sites_with_unsupported_backends,
            ]
        ):
            upgrade_overview += """
<green>\
Good news! No special upgrade steps are required to bring your project up to date.
The Upgrade Helper will simply increment the config_version of your great_expectations.yml for you.
</green>
Would you like to proceed?
"""
        else:
            upgrade_overview += """
<red>**WARNING**: Before proceeding, please make sure you have appropriate backups of your project.</red>
"""
            if validations_store_name_checklist or site_name_checklist:
                upgrade_overview += """
<cyan>\
Automated Steps
================
</cyan>
The following Stores and/or Data Docs sites will be upgraded:

"""
                upgrade_overview += (
                    f"""\
    - Validation Stores: {", ".join(validations_store_name_checklist)}
"""
                    if validations_store_name_checklist
                    else ""
                )
                upgrade_overview += (
                    f"""\
    - Data Docs Sites: {", ".join(site_name_checklist)}
"""
                    if site_name_checklist
                    else ""
                )

            if any(
                [
                    skip_with_database_backends,
                    skip_with_unsupported_backends,
                    skip_doc_sites_with_unsupported_backends,
                ]
            ):
                upgrade_overview += """
<cyan>\
Manual Steps
=============
</cyan>
The following Stores and/or Data Docs sites must be upgraded manually, due to having a database backend, or backend
type that is unsupported or unrecognized:

"""
                upgrade_overview += (
                    f"""\
    - Stores with database backends: {", ".join(skip_with_database_backends)}
"""
                    if skip_with_database_backends
                    else ""
                )
                upgrade_overview += (
                    f"""\
    - Stores with unsupported/unrecognized backends: {", ".join(skip_with_unsupported_backends)}
"""
                    if skip_with_unsupported_backends
                    else ""
                )
                upgrade_overview += (
                    f"""\
    - Data Docs sites with unsupported/unrecognized backends: {", ".join(skip_doc_sites_with_unsupported_backends)}
"""
                    if skip_doc_sites_with_unsupported_backends
                    else ""
                )
            else:
                upgrade_overview += """
<cyan>\
Manual Steps
=============
</cyan>
No manual upgrade steps are required.
"""

            upgrade_overview += """
<cyan>\
Upgrade Confirmation
=====================
</cyan>
Please consult the 0.11.x migration guide for instructions on how to complete any required manual steps or
to learn more about the automated upgrade process:

    <cyan>https://docs.greatexpectations.io/en/latest/how_to_guides/migrating_versions.html#id1</cyan>

Would you like to proceed with the project upgrade?\
"""
        return upgrade_overview, True

    def _save_upgrade_log(self):
        current_time = datetime.datetime.now(datetime.timezone.utc).strftime(
            "%Y%m%dT%H%M%S.%fZ"
        )
        dest_path = os.path.join(
            self.data_context._context_root_directory,
            "uncommitted",
            "logs",
            "project_upgrades",
            f"UpgradeHelperV11_{current_time}.json",
        )
        dest_dir, dest_filename = os.path.split(dest_path)
        os.makedirs(dest_dir, exist_ok=True)

        with open(dest_path, "w") as outfile:
            json.dump(self.upgrade_log, outfile, indent=2)

        return dest_path

    def _generate_upgrade_report(self):
        upgrade_log_path = self._save_upgrade_log()
        skipped_stores_or_sites = any(self._get_skipped_store_and_site_names())
        exception_occurred = False
        exceptions = self.upgrade_log.get("exceptions")
        if skipped_stores_or_sites or exceptions:
            increment_version = False
        else:
            increment_version = True
        upgrade_report = """\
<cyan>\
++================++
|| Upgrade Report ||
++================++\
</cyan>
"""
        if increment_version:
            upgrade_report += f"""
<green>\
Your project was successfully upgraded to be compatible with Great Expectations 0.11.x.
The config_version of your great_expectations.yml has been automatically incremented to 2.0.

A log detailing the upgrade can be found here:

    - {upgrade_log_path}\
</green>\
"""
        else:
            if exceptions:
                exception_occurred = True
                upgrade_report += f"""
<red>\
The Upgrade Helper encountered some exceptions during the upgrade process.
Please review the exceptions section of the upgrade log and migrate the affected files manually,
as detailed in the 0.11.x migration guide.

The upgrade log can be found here:

    - {upgrade_log_path}\
</red>\
"""
            else:
                upgrade_report += f"""
<yellow>\
The Upgrade Helper has completed the automated upgrade steps.
A log detailing the upgrade can be found here:

    - {upgrade_log_path}\
</yellow>\
"""
        return upgrade_report, increment_version, exception_occurred

    def upgrade_project(self):
        try:
            for (store_name, store_backend) in self.upgrade_checklist[
                "validations_store_backends"
            ].items():
                self.upgrade_log["upgraded_validations_stores"][store_name] = {
                    "validations_updated": [],
                    "exceptions": False,
                }
                self._upgrade_store_backend(store_backend, store_name=store_name)
        except Exception:
            pass

        try:
            for (site_name, store_backend) in self.upgrade_checklist[
                "docs_validations_store_backends"
            ].items():
                self.upgrade_log["upgraded_docs_site_validations_stores"][site_name] = {
                    "validation_result_pages_updated": [],
                    "exceptions": False,
                }
                self._upgrade_store_backend(store_backend, site_name=site_name)
        except Exception:
            pass

        # return a report of what happened, boolean indicating whether version should be incremented
        # if the version should not be incremented, the report should include instructions for steps to
        # be performed manually
        (
            upgrade_report,
            increment_version,
            exception_occurred,
        ) = self._generate_upgrade_report()
        return upgrade_report, increment_version, exception_occurred


text:
#include "tensorflow_quantum/core/ops/parse_context.h"

#include <google/protobuf/text_format.h>

#include <string>
#include <vector>

#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/lib/core/error_codes.pb.h"
#include "tensorflow/core/lib/core/status.h"
#include "tensorflow/core/lib/core/threadpool.h"
#include "tensorflow_quantum/core/ops/tfq_simulate_utils.h"
#include "tensorflow_quantum/core/proto/pauli_sum.pb.h"
#include "tensorflow_quantum/core/proto/program.pb.h"
#include "tensorflow_quantum/core/src/program_resolution.h"

namespace tfq {
namespace {

using ::tensorflow::OpKernelContext;
using ::tensorflow::Status;
using ::tensorflow::Tensor;
using ::tfq::proto::PauliSum;
using ::tfq::proto::Program;

template <typename T>
Status ParseProto(const std::string& text, T* proto) {
  // First attempt to parse from the binary representation.
  if (proto->ParseFromString(text)) {
    return Status::OK();
  }

  // If that fails, then try to parse from the human readable representation.
  if (google::protobuf::TextFormat::ParseFromString(text, proto)) {
    return Status::OK();
  }

  return Status(tensorflow::error::INVALID_ARGUMENT,
                "Unparseable proto: " + text);
}

}  // namespace

Status ParsePrograms(OpKernelContext* context, const std::string& input_name,
                     std::vector<Program>* programs) {
  const tensorflow::Tensor* input;
  Status status = context->input(input_name, &input);
  if (!status.ok()) {
    return status;
  }

  if (input->dims() != 1) {
    // Never parse anything other than a 1d list of circuits.
    return Status(
        tensorflow::error::INVALID_ARGUMENT,
        absl::StrCat("programs must be rank 1. Got rank ", input->dims(), "."));
  }

  const auto program_strings = input->vec<tensorflow::tstring>();
  const int num_programs = program_strings.dimension(0);
  programs->assign(num_programs, Program());

  auto DoWork = [&](int start, int end) {
    for (int i = start; i < end; i++) {
      OP_REQUIRES_OK(context, ParseProto(program_strings(i), &programs->at(i)));
    }
  };

  // TODO(mbbrough): Determine if this is a good cycle estimate.
  const int cycle_estimate = 1000;
  context->device()->tensorflow_cpu_worker_threads()->workers->ParallelFor(
      num_programs, cycle_estimate, DoWork);

  return Status::OK();
}

Status ParsePrograms2D(OpKernelContext* context, const std::string& input_name,
                       std::vector<std::vector<Program>>* programs) {
  const tensorflow::Tensor* input;
  Status status = context->input(input_name, &input);
  if (!status.ok()) {
    return status;
  }

  if (input->dims() != 2) {
    // Never parse anything other than a 1d list of circuits.
    return Status(tensorflow::error::INVALID_ARGUMENT,
                  absl::StrCat("other_programs must be rank 2. Got rank ",
                               input->dims(), "."));
  }

  const auto program_strings = input->matrix<tensorflow::tstring>();
  const int num_programs = program_strings.dimension(0);
  const int num_entries = program_strings.dimension(1);
  programs->assign(num_programs, std::vector<Program>(num_entries, Program()));

  auto DoWork = [&](int start, int end) {
    for (int i = start; i < end; i++) {
      OP_REQUIRES_OK(
          context,
          ParseProto(program_strings(i / num_entries, i % num_entries),
                     &programs->at(i / num_entries).at(i % num_entries)));
    }
  };

  // TODO(mbbrough): Determine if this is a good cycle estimate.
  const int cycle_estimate = 1000;
  context->device()->tensorflow_cpu_worker_threads()->workers->ParallelFor(
      num_programs * num_entries, cycle_estimate, DoWork);

  return Status::OK();
}

Status GetProgramsAndProgramsToAppend(
    OpKernelContext* context, std::vector<Program>* programs,
    std::vector<Program>* programs_to_append) {
  Status status = ParsePrograms(context, "programs", programs);
  if (!status.ok()) {
    return status;
  }

  status = ParsePrograms(context, "programs_to_append", programs_to_append);
  if (!status.ok()) {
    return status;
  }

  if (programs->size() != programs_to_append->size()) {
    return Status(tensorflow::error::INVALID_ARGUMENT,
                  "programs and programs_to_append must have matching sizes.");
  }

  return Status::OK();
}

Status GetProgramsAndNumQubits(
    OpKernelContext* context, std::vector<Program>* programs,
    std::vector<int>* num_qubits,
    std::vector<std::vector<PauliSum>>* p_sums /*=nullptr*/,
    bool swap_endianness /*=false*/) {
  // 1. Parse input programs
  // 2. (Optional) Parse input PauliSums
  // 3. Convert GridQubit locations to integers.
  Status status = ParsePrograms(context, "programs", programs);
  if (!status.ok()) {
    return status;
  }

  if (p_sums) {
    status = GetPauliSums(context, p_sums);
    if (!status.ok()) {
      return status;
    }
    if (programs->size() != p_sums->size()) {
      return Status(
          tensorflow::error::INVALID_ARGUMENT,
          absl::StrCat("Number of circuits and PauliSums do not match. Got ",
                       programs->size(), " circuits and ", p_sums->size(),
                       " paulisums."));
    }
  }

  // Resolve qubit ID's in parallel.
  num_qubits->assign(programs->size(), -1);
  auto DoWork = [&](int start, int end) {
    for (int i = start; i < end; i++) {
      Program& program = (*programs)[i];
      unsigned int this_num_qubits;
      if (p_sums) {
        OP_REQUIRES_OK(context,
                       ResolveQubitIds(&program, &this_num_qubits,
                                       &(p_sums->at(i)), swap_endianness));
      } else {
        OP_REQUIRES_OK(context, ResolveQubitIds(&program, &this_num_qubits,
                                                nullptr, swap_endianness));
      }
      (*num_qubits)[i] = this_num_qubits;
    }
  };

  // TODO(mbbrough): Determine if this is a good cycle estimate.
  const int cycle_estimate = 1000;
  context->device()->tensorflow_cpu_worker_threads()->workers->ParallelFor(
      num_qubits->size(), cycle_estimate, DoWork);

  return Status::OK();
}

tensorflow::Status GetProgramsAndNumQubits(
    OpKernelContext* context, std::vector<Program>* programs,
    std::vector<int>* num_qubits,
    std::vector<std::vector<Program>>* other_programs) {
  // 1. Parse input programs
  // 2. Parse other_programs
  // 3. Convert GridQubit locations to integers and ensure exact matching.
  Status status = ParsePrograms(context, "programs", programs);
  if (!status.ok()) {
    return status;
  }

  status = ParsePrograms2D(context, "other_programs", other_programs);
  if (!status.ok()) {
    return status;
  }

  if (programs->size() != other_programs->size()) {
    return Status(tensorflow::error::INVALID_ARGUMENT,
                  absl::StrCat("programs and other_programs batch dimension",
                               " do not match. Foud: ", programs->size(),
                               " and ", other_programs->size()));
  }

  // Resolve qubit ID's in parallel.
  num_qubits->assign(programs->size(), -1);
  auto DoWork = [&](int start, int end) {
    for (int i = start; i < end; i++) {
      Program& program = (*programs)[i];
      unsigned int this_num_qubits;
      OP_REQUIRES_OK(context, ResolveQubitIds(&program, &this_num_qubits,
                                              &(*other_programs)[i]));
      (*num_qubits)[i] = this_num_qubits;
    }
  };

  // TODO(mbbrough): Determine if this is a good cycle estimate.
  const int cycle_estimate = 1000;
  context->device()->tensorflow_cpu_worker_threads()->workers->ParallelFor(
      num_qubits->size(), cycle_estimate, DoWork);

  return Status::OK();
}

Status GetPauliSums(OpKernelContext* context,
                    std::vector<std::vector<PauliSum>>* p_sums) {
  // 1. Parses PauliSum proto.
  const Tensor* input;
  Status status = context->input("pauli_sums", &input);
  if (!status.ok()) {
    return status;
  }

  if (input->dims() != 2) {
    return Status(tensorflow::error::INVALID_ARGUMENT,
                  absl::StrCat("pauli_sums must be rank 2. Got rank ",
                               input->dims(), "."));
  }

  const auto sum_specs = input->matrix<tensorflow::tstring>();
  p_sums->assign(sum_specs.dimension(0),
                 std::vector<PauliSum>(sum_specs.dimension(1), PauliSum()));
  const int op_dim = sum_specs.dimension(1);
  auto DoWork = [&](int start, int end) {
    for (int ii = start; ii < end; ii++) {
      const int i = ii / op_dim;
      const int j = ii % op_dim;
      PauliSum p;
      OP_REQUIRES_OK(context, ParseProto(sum_specs(i, j), &p));
      (*p_sums)[i][j] = p;
    }
  };

  // TODO(mbbrough): Determine if this is a good cycle estimate.
  const int cycle_estimate = 1000;
  context->device()->tensorflow_cpu_worker_threads()->workers->ParallelFor(
      sum_specs.dimension(0) * sum_specs.dimension(1), cycle_estimate, DoWork);

  return Status::OK();
}

Status GetSymbolMaps(OpKernelContext* context, std::vector<SymbolMap>* maps) {
  // 1. Convert to dictionary representation for param resolution.
  const Tensor* input_names;
  Status status = context->input("symbol_names", &input_names);
  if (!status.ok()) {
    return status;
  }

  if (input_names->dims() != 1) {
    return Status(tensorflow::error::INVALID_ARGUMENT,
                  absl::StrCat("symbol_names must be rank 1. Got rank ",
                               input_names->dims(), "."));
  }

  const Tensor* input_values;
  status = context->input("symbol_values", &input_values);
  if (!status.ok()) {
    return status;
  }

  if (input_values->dims() != 2) {
    return Status(tensorflow::error::INVALID_ARGUMENT,
                  absl::StrCat("symbol_values must be rank 2. Got rank ",
                               input_values->dims(), "."));
  }

  const auto symbol_names = input_names->vec<tensorflow::tstring>();
  const auto symbol_values = input_values->matrix<float>();

  if (symbol_names.dimension(0) != symbol_values.dimension(1)) {
    return Status(tensorflow::error::INVALID_ARGUMENT,
                  "Input symbol names and value sizes do not match.");
  }

  maps->assign(symbol_values.dimension(0), SymbolMap());

  const int symbol_dim = symbol_values.dimension(1);
  auto DoWork = [&](int start, int end) {
    for (int i = start; i < end; i++) {
      for (int j = 0; j < symbol_dim; j++) {
        const std::string& name = symbol_names(j);
        const float value = symbol_values(i, j);
        (*maps)[i][name] = {j, value};
      }
    }
  };

  // TODO(mbbrough): Determine if this is a good cycle estimate.
  const int cycle_estimate = 1000;
  context->device()->tensorflow_cpu_worker_threads()->workers->ParallelFor(
      symbol_values.dimension(0), cycle_estimate, DoWork);

  return Status::OK();
}

tensorflow::Status GetNumSamples(
    tensorflow::OpKernelContext* context,
    std::vector<std::vector<int>>* parsed_num_samples) {
  const Tensor* input_num_samples;
  Status status = context->input("num_samples", &input_num_samples);
  if (!status.ok()) {
    return status;
  }

  if (input_num_samples->dims() != 2) {
    return Status(tensorflow::error::INVALID_ARGUMENT,
                  absl::StrCat("num_samples must be rank 2. Got rank ",
                               input_num_samples->dims(), "."));
  }

  const auto matrix_num_samples = input_num_samples->matrix<int>();
  parsed_num_samples->reserve(matrix_num_samples.dimension(0));
  for (unsigned int i = 0; i < matrix_num_samples.dimension(0); i++) {
    std::vector<int> sub_parsed_num_samples;
    sub_parsed_num_samples.reserve(matrix_num_samples.dimension(1));
    for (unsigned int j = 0; j < matrix_num_samples.dimension(1); j++) {
      const int num_samples = matrix_num_samples(i, j);
      if (num_samples < 1) {
        return Status(tensorflow::error::INVALID_ARGUMENT,
                      "Each element of num_samples must be greater than 0.");
      }
      sub_parsed_num_samples.push_back(num_samples);
    }
    parsed_num_samples->push_back(sub_parsed_num_samples);
  }

  return Status::OK();
}

// used by tfq_simulate_samples.
Status GetIndividualSample(tensorflow::OpKernelContext* context,
                           int* n_samples) {
  const Tensor* input_num_samples;
  Status status = context->input("num_samples", &input_num_samples);
  if (!status.ok()) {
    return status;
  }

  if (input_num_samples->dims() != 1) {
    return Status(tensorflow::error::INVALID_ARGUMENT,
                  absl::StrCat("num_samples must be rank 1. Got rank ",
                               input_num_samples->dims(), "."));
  }

  const auto vector_num_samples = input_num_samples->vec<int>();

  if (vector_num_samples.dimension(0) != 1) {
    return Status(tensorflow::error::INVALID_ARGUMENT,
                  absl::StrCat("num_samples must contain 1 element. Got ",
                               vector_num_samples.dimension(0), "."));
  }

  (*n_samples) = vector_num_samples(0);
  return Status::OK();
}

// used by adj_grad_op.
tensorflow::Status GetPrevGrads(
    tensorflow::OpKernelContext* context,
    std::vector<std::vector<float>>* parsed_prev_grads) {
  const Tensor* input_grads;
  Status status = context->input("downstream_grads", &input_grads);
  if (!status.ok()) {
    return status;
  }

  if (input_grads->dims() != 2) {
    return Status(tensorflow::error::INVALID_ARGUMENT,
                  absl::StrCat("downstream_grads must be rank 2. Got rank ",
                               input_grads->dims(), "."));
  }

  const auto matrix_grads = input_grads->matrix<float>();
  parsed_prev_grads->reserve(matrix_grads.dimension(0));
  for (unsigned int i = 0; i < matrix_grads.dimension(0); i++) {
    std::vector<float> sub_parsed_grads;
    sub_parsed_grads.reserve(matrix_grads.dimension(1));
    for (unsigned int j = 0; j < matrix_grads.dimension(1); j++) {
      const float grad_v = matrix_grads(i, j);
      sub_parsed_grads.push_back(grad_v);
    }
    parsed_prev_grads->push_back(sub_parsed_grads);
  }

  return Status::OK();
}

}  // namespace tfq


text:
/*****************************************
 *  Enrico Fucile
 ****************************************/

#include "grib_api_internal.h"
#include <ctype.h>

#if GRIB_PTHREADS
static pthread_once_t once  = PTHREAD_ONCE_INIT;
static pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER;

static void thread_init() {
    pthread_mutexattr_t attr;
    pthread_mutexattr_init(&attr);
    pthread_mutexattr_settype(&attr,PTHREAD_MUTEX_RECURSIVE);
    pthread_mutex_init(&mutex1,&attr);
    pthread_mutexattr_destroy(&attr);
}
#elif GRIB_OMP_THREADS
static int once = 0;
static omp_nest_lock_t mutex1;

static void thread_init()
{
    GRIB_OMP_CRITICAL(lock_grib_accessor_class_codetable_c)
    {
        if (once == 0)
        {
            omp_init_nest_lock(&mutex1);
            once = 1;
        }
    }
}
#endif

/*
   This is used by make_class.pl

   START_CLASS_DEF
   CLASS      = accessor
   SUPER      = grib_accessor_class_unsigned
   IMPLEMENTS = init;dump;unpack_string;pack_expression;unpack_long
   IMPLEMENTS = value_count;pack_string; destroy; get_native_type;
   MEMBERS    =  const char* tablename
   MEMBERS    =  const char* masterDir
   MEMBERS    =  const char* localDir
   MEMBERS    =  grib_codetable* table
   END_CLASS_DEF

 */

/* START_CLASS_IMP */

/*

Don't edit anything between START_CLASS_IMP and END_CLASS_IMP
Instead edit values between START_CLASS_DEF and END_CLASS_DEF
or edit "accessor.class" and rerun ./make_class.pl

*/

static int  get_native_type(grib_accessor*);
static int pack_string(grib_accessor*, const char*, size_t *len);
static int pack_expression(grib_accessor*, grib_expression*);
static int unpack_long(grib_accessor*, long* val,size_t *len);
static int unpack_string (grib_accessor*, char*, size_t *len);
static int value_count(grib_accessor*,long*);
static void destroy(grib_context*,grib_accessor*);
static void dump(grib_accessor*, grib_dumper*);
static void init(grib_accessor*,const long, grib_arguments* );
static void init_class(grib_accessor_class*);

typedef struct grib_accessor_codetable {
    grib_accessor          att;
/* Members defined in gen */
/* Members defined in long */
/* Members defined in unsigned */
	long nbytes;
	grib_arguments* arg;
/* Members defined in codetable */
	const char* tablename;
	const char* masterDir;
	const char* localDir;
	grib_codetable* table;
} grib_accessor_codetable;

extern grib_accessor_class* grib_accessor_class_unsigned;

static grib_accessor_class _grib_accessor_class_codetable = {
    &grib_accessor_class_unsigned,                      /* super                     */
    "codetable",                      /* name                      */
    sizeof(grib_accessor_codetable),  /* size                      */
    0,                           /* inited */
    &init_class,                 /* init_class */
    &init,                       /* init                      */
    0,                  /* post_init                      */
    &destroy,                    /* free mem                       */
    &dump,                       /* describes himself         */
    0,                /* get length of section     */
    0,              /* get length of string      */
    &value_count,                /* get number of values      */
    0,                 /* get number of bytes      */
    0,                /* get offset to bytes           */
    &get_native_type,            /* get native type               */
    0,                /* get sub_section                */
    0,               /* grib_pack procedures long      */
    0,                 /* grib_pack procedures long      */
    0,                  /* grib_pack procedures long      */
    &unpack_long,                /* grib_unpack procedures long    */
    0,                /* grib_pack procedures double    */
    0,              /* grib_unpack procedures double  */
    &pack_string,                /* grib_pack procedures string    */
    &unpack_string,              /* grib_unpack procedures string  */
    0,          /* grib_pack array procedures string    */
    0,        /* grib_unpack array procedures string  */
    0,                 /* grib_pack procedures bytes     */
    0,               /* grib_unpack procedures bytes   */
    &pack_expression,            /* pack_expression */
    0,              /* notify_change   */
    0,                /* update_size   */
    0,            /* preferred_size   */
    0,                    /* resize   */
    0,      /* nearest_smaller_value */
    0,                       /* next accessor    */
    0,                    /* compare vs. another accessor   */
    0,     /* unpack only ith value          */
    0,     /* unpack a subarray         */
    0,              		/* clear          */
    0,               		/* clone accessor          */
};

grib_accessor_class* grib_accessor_class_codetable = &_grib_accessor_class_codetable;

static void init_class(grib_accessor_class* c)
{
	c->next_offset	=	(*(c->super))->next_offset;
	c->string_length	=	(*(c->super))->string_length;
	c->byte_count	=	(*(c->super))->byte_count;
	c->byte_offset	=	(*(c->super))->byte_offset;
	c->sub_section	=	(*(c->super))->sub_section;
	c->pack_missing	=	(*(c->super))->pack_missing;
	c->is_missing	=	(*(c->super))->is_missing;
	c->pack_long	=	(*(c->super))->pack_long;
	c->pack_double	=	(*(c->super))->pack_double;
	c->unpack_double	=	(*(c->super))->unpack_double;
	c->pack_string_array	=	(*(c->super))->pack_string_array;
	c->unpack_string_array	=	(*(c->super))->unpack_string_array;
	c->pack_bytes	=	(*(c->super))->pack_bytes;
	c->unpack_bytes	=	(*(c->super))->unpack_bytes;
	c->notify_change	=	(*(c->super))->notify_change;
	c->update_size	=	(*(c->super))->update_size;
	c->preferred_size	=	(*(c->super))->preferred_size;
	c->resize	=	(*(c->super))->resize;
	c->nearest_smaller_value	=	(*(c->super))->nearest_smaller_value;
	c->next	=	(*(c->super))->next;
	c->compare	=	(*(c->super))->compare;
	c->unpack_double_element	=	(*(c->super))->unpack_double_element;
	c->unpack_double_subarray	=	(*(c->super))->unpack_double_subarray;
	c->clear	=	(*(c->super))->clear;
	c->make_clone	=	(*(c->super))->make_clone;
}

/* END_CLASS_IMP */

static int grib_load_codetable(grib_context* c,const char* filename,
        const char* recomposed_name,size_t size,grib_codetable* t);

static void init(grib_accessor* a, const long len, grib_arguments* params)
{
    int n=0;
    grib_accessor_codetable* self  = (grib_accessor_codetable*)a;
    grib_action* act=(grib_action*)(a->creator);

    self->tablename = grib_arguments_get_string(grib_handle_of_accessor(a),params,n++);
    self->masterDir = grib_arguments_get_name(grib_handle_of_accessor(a),params,n++);
    self->localDir = grib_arguments_get_name(grib_handle_of_accessor(a),params,n++);

    /*if (a->flags & GRIB_ACCESSOR_FLAG_STRING_TYPE)
    printf("-------- %s type string (%ld)\n",a->name,a->flags);*/

    if (a->flags & GRIB_ACCESSOR_FLAG_TRANSIENT) {
        a->length = 0;
        if (!a->vvalue)
            a->vvalue = (grib_virtual_value*)grib_context_malloc_clear(a->context,sizeof(grib_virtual_value));
        a->vvalue->type=grib_accessor_get_native_type(a);
        a->vvalue->length=len;
        if (act->default_value!=NULL) {
            const char* p = 0;
            size_t s_len = 1;
            long l;
            int ret=0;
            double d;
            char tmp[1024];
            grib_expression* expression=grib_arguments_get_expression(grib_handle_of_accessor(a),act->default_value,0);
            int type = grib_expression_native_type(grib_handle_of_accessor(a),expression);
            switch(type) {
            case GRIB_TYPE_DOUBLE:
                grib_expression_evaluate_double(grib_handle_of_accessor(a),expression,&d);
                grib_pack_double(a,&d,&s_len);
                break;

            case GRIB_TYPE_LONG:
                grib_expression_evaluate_long(grib_handle_of_accessor(a),expression,&l);
                grib_pack_long(a,&l,&s_len);
                break;

            default:
                s_len = sizeof(tmp);
                p = grib_expression_evaluate_string(grib_handle_of_accessor(a),expression,tmp,&s_len,&ret);
                if (ret != GRIB_SUCCESS) {
                    grib_context_log(a->context,GRIB_LOG_FATAL,
                            "unable to evaluate %s as string",a->name);
                }
                s_len = strlen(p)+1;
                pack_string(a,p,&s_len);
                break;
            }
        }
    } else {
        a->length = len;
    }
}

static int str_eq(const char* a, const char* b)
{
    if ( a && b && (strcmp(a,b)==0) )
        return 1;
    return 0;
}

#ifdef DEBUGGING
static void dump_codetable(grib_codetable* atable)
{
    grib_codetable* next = NULL;
    int count = 0;

    next=atable;
    while(next) {
        printf("[%.2d] CodeTable Dump: f0=%s f1=%s\n", count, next->filename[0], next->filename[1]);
        count++;
        next = next->next;
    }
}
#endif
static grib_codetable* load_table(grib_accessor_codetable* self)
{
    size_t size = 0;
    grib_handle*    h = ((grib_accessor*)self)->parent->h;
    grib_context*   c = h->context;
    grib_codetable* t = NULL;
    grib_codetable* next=NULL ;
    grib_accessor* a=(grib_accessor*)self;
    char *filename=0;
    char recomposed[1024]={0,};
    char localRecomposed[1024]={0,};
    char *localFilename=0;
    char masterDir[1024]={0,};
    char localDir[1024]={0,};
    size_t len=1024;

    if (self->masterDir != NULL)
        grib_get_string(h,self->masterDir,masterDir,&len);

    len=1024;
    if (self->localDir != NULL)
        grib_get_string(h,self->localDir,localDir,&len);

    if (*masterDir!=0) {
        char name[1024]={0,};
        sprintf(name,"%s/%s",masterDir,self->tablename);
        grib_recompose_name(h, NULL,name, recomposed,0);
        filename=grib_context_full_defs_path(c,recomposed);
    } else {
        grib_recompose_name(h, NULL,self->tablename, recomposed,0);
        filename=grib_context_full_defs_path(c,recomposed);
    }

    if (*localDir!=0) {
        char localName[1024]={0,};
        sprintf(localName,"%s/%s",localDir,self->tablename);
        grib_recompose_name(h, NULL,localName, localRecomposed,0);
        localFilename=grib_context_full_defs_path(c,localRecomposed);
    }

    GRIB_MUTEX_INIT_ONCE(&once,&thread_init);
    GRIB_MUTEX_LOCK(&mutex1); /* GRIB-930 */

    /*printf("%s: Looking in cache: f=%s lf=%s\n", self->att.name, filename, localFilename);*/
    next=c->codetable;
    while(next) {
        if ((filename && next->filename[0] && strcmp(filename,next->filename[0]) == 0) &&
                ((localFilename==0 && next->filename[1]==NULL) ||
                        ((localFilename!=0 && next->filename[1]!=NULL)
                                && strcmp(localFilename,next->filename[1]) ==0)) )
        {
            t = next;
            goto the_end;
        }
        /* Special case: see GRIB-735 */
        if (filename==NULL && localFilename!=NULL)
        {
            if ( str_eq(localFilename, next->filename[0]) ||
                 str_eq(localFilename, next->filename[1]) )
            {
                t = next;
                goto the_end;
            }
        }
        next = next->next;
    }

    if (a->flags & GRIB_ACCESSOR_FLAG_TRANSIENT) {
        Assert(a->vvalue!=NULL);
        size=a->vvalue->length*8;
    } else {
        size = grib_byte_count((grib_accessor*)self) * 8;
    }
    size = grib_power(size,2);

    t = (grib_codetable*)grib_context_malloc_clear_persistent(c,sizeof(grib_codetable) +
            (size-1)*sizeof(code_table_entry));

    if (filename!=0)
        grib_load_codetable(c,filename,recomposed,size,t);

    if (localFilename!=0)
        grib_load_codetable(c,localFilename,localRecomposed,size,t);

    /*dump_codetable(c->codetable);*/

    if (t->filename[0]==NULL && t->filename[1]==NULL) {
        grib_context_free_persistent(c,t);
        t = NULL;
        goto the_end;
    }

the_end:
    GRIB_MUTEX_UNLOCK(&mutex1);

    return t;
}

static int grib_load_codetable(grib_context* c,const char* filename,
        const char* recomposed_name,size_t size,grib_codetable* t)
{
    char line[1024];
    FILE *f = NULL;
    int lineNumber = 0;
    grib_context_log(c,GRIB_LOG_DEBUG,"Loading code table from %s",filename);

    f = codes_fopen(filename, "r");
    if (!f) return GRIB_IO_PROBLEM;

    Assert(t!=NULL);

    if (t->filename[0] == NULL ){
        t->filename[0]  = grib_context_strdup_persistent(c,filename);
        t->recomposed_name[0]  = grib_context_strdup_persistent(c,recomposed_name);
        t->next      = c->codetable;
        t->size      = size;
        c->codetable = t;
    } else {
        t->filename[1]  = grib_context_strdup_persistent(c,filename);
        t->recomposed_name[1]  = grib_context_strdup_persistent(c,recomposed_name);
    }

    while(fgets(line,sizeof(line)-1,f))
    {
        char* p = line;
        int code    = 0;
        char abbreviation[1024] = {0,};
        char title[1024]={0,};
        char* q = abbreviation;
        char* r = title;
        char* units=0;
        char unknown[]="unknown";
        ++lineNumber;

        line[strlen(line)-1] = 0;

        while(*p != '\0' && isspace(*p)) p++;

        if(*p == '#')
            continue;

        while(*p != '\0' && isspace(*p)) p++;

        if( *p =='\0' ) continue;

        if (!isdigit(*p))
        {
            grib_context_log(c,GRIB_LOG_ERROR, "Invalid entry in file %s: line %d", filename, lineNumber);
            continue; /* skip this line */
        }
        Assert(isdigit(*p));

        while(*p != '\0')
        {
            if(isspace(*p)) break;
            code *= 10;
            code += *p - '0';
            p++;
        }

        if(code <0 || code >= size)
        {
            grib_context_log(c,GRIB_LOG_WARNING,"code_table_entry: invalid code in %s: %d (table size=%d)",filename,code,size);
            continue;
        }

        while(*p != '\0' && isspace(*p)) p++;

        while(*p != '\0')
        {
            if(isspace(*p)) break;
            *q++ = *p++;
        }
        *q = 0;
        while(*p != '\0' && isspace(*p)) p++;

        while(*p != '\0')
        {
            if(*p == '(' ) break;
            *r++ = *p++;
        }
        *r = 0;

        while(*p != '\0' && isspace(*p)) p++;
        if (*p != '\0') {
            units=++p;
            while(*p != '\0' && *p != ')' ) p++;
            *p='\0';
        } else {
            units=unknown;
        }

        Assert(*abbreviation);
        Assert(*title);

        if(t->entries[code].abbreviation != NULL)
        {
            grib_context_log(c,GRIB_LOG_WARNING,"code_table_entry: duplicate code in %s: %d (table size=%d)",filename,code,size);
            continue;
        }

        Assert(t->entries[code].abbreviation == NULL);
        Assert(t->entries[code].title        == NULL);

        t->entries[code].abbreviation = grib_context_strdup_persistent(c,abbreviation);
        t->entries[code].title        = grib_context_strdup_persistent(c,title);
        t->entries[code].units        = grib_context_strdup_persistent(c,units);
    }

    fclose(f);

    return 0;
}

void grib_codetable_delete(grib_context* c)
{
    grib_codetable* t = c->codetable;

    while(t)
    {
        grib_codetable* s = t->next;
        int i;

        for(i = 0; i < t->size; i++)
        {
            grib_context_free_persistent(c,t->entries[i].abbreviation);
            grib_context_free_persistent(c,t->entries[i].title);
        }
        grib_context_free_persistent(c,t->filename[0]);
        if(t->filename[1])
            grib_context_free_persistent(c,t->filename[1]);
        grib_context_free_persistent(c,t->recomposed_name[0]);
        if (t->recomposed_name[1])
            grib_context_free_persistent(c,t->recomposed_name[1]);
        grib_context_free_persistent(c,t);
        t = s;
    }
}

static void dump(grib_accessor* a, grib_dumper* dumper)
{
    grib_accessor_codetable* self  = (grib_accessor_codetable*)a;
    char comment[2048];
    grib_codetable* table;

    size_t llen = 1;
    long value;

    if(!self->table) self->table = load_table(self);
    table=self->table;

    grib_unpack_long(a, &value,&llen);

    if(value == GRIB_MISSING_LONG)
    {
        if(a->length < 4)
        {
            value = (1L << a->length) - 1;
        }
    }

    if(table && value >= 0 && value < table->size)
    {
        if(table->entries[value].abbreviation)
        {
            int b = atol(table->entries[value].abbreviation);
            if(b == value)
                strcpy(comment,table->entries[value].title);
            else
                sprintf(comment,"%s", table->entries[value].title);

            if (table->entries[value].units!=NULL && strcmp(table->entries[value].units,"unknown")) {
                strcat(comment," (");
                strcat(comment,table->entries[value].units);
                strcat(comment,") ");
            }
        }
        else
        {
            strcpy(comment,"Unknown code table entry");
        }

    }
    else
    {
        strcpy(comment,"Unknown code table entry");
    }

    strcat(comment," (");
    if (table) {
        strcat(comment,table->recomposed_name[0]);
        if (table->recomposed_name[1]!=NULL) {
            strcat(comment," , ");
            strcat(comment,table->recomposed_name[1]);
        }
    }
    strcat(comment,") ");

    grib_dump_long(dumper,a,comment);
}

static int unpack_string (grib_accessor* a, char* buffer, size_t *len)
{
    grib_accessor_codetable* self = (grib_accessor_codetable*)a;
    grib_codetable*          table = NULL;

    size_t size = 1;
    long   value;
    int err = GRIB_SUCCESS;
    char tmp[1024];
    size_t l = 0;

    if( (err = grib_unpack_long(a,&value,&size)) != GRIB_SUCCESS)
        return err;

    if(!self->table) self->table = load_table(self);
    table=self->table;

    if(table && (value >= 0) && (value < table->size) && table->entries[value].abbreviation)
    {
        strcpy(tmp,table->entries[value].abbreviation);
    }
    else
    {

#if 1
        sprintf(tmp,"%d",(int)value);
#else
        return GRIB_DECODING_ERROR;
#endif
    }

    l = strlen(tmp) + 1;

    if(*len < l)
    {
        *len = l;
        return GRIB_BUFFER_TOO_SMALL;
    }

    strcpy(buffer,tmp);
    *len = l;

    return GRIB_SUCCESS;
}

static int value_count(grib_accessor* a,long* count)
{
    *count=1;
    return 0;
}

static int pack_string(grib_accessor* a, const char* buffer, size_t *len)
{
    grib_accessor_codetable* self = (grib_accessor_codetable*)a;
    grib_codetable*          table ;

    long i;
    size_t size = 1;

    typedef int (*cmpproc)(const char*, const char*);
#ifndef ECCODES_ON_WINDOWS
    cmpproc cmp = (a->flags & GRIB_ACCESSOR_FLAG_LOWERCASE) ? strcmp_nocase : strcmp;
#else
    /* Microsoft Windows Visual Studio support */
    cmpproc cmp = (a->flags & GRIB_ACCESSOR_FLAG_LOWERCASE) ? stricmp : strcmp;
#endif

    if(!self->table) self->table = load_table(self);
    table=self->table;

    if(!table)
        return GRIB_ENCODING_ERROR;

    if (a->set) {
        int err=grib_set_string(grib_handle_of_accessor(a),a->set,buffer,len);
        if (err!=0) return err;
    }

    for(i = 0 ; i < table->size; i++)
        if(table->entries[i].abbreviation)
            if(cmp(table->entries[i].abbreviation,buffer) == 0)
                return grib_pack_long(a,&i,&size);

    if (a->flags & GRIB_ACCESSOR_FLAG_NO_FAIL) {
        grib_action* act=(grib_action*)(a->creator);
        if (act->default_value!=NULL) {
            const char* p = 0;
            size_t s_len = 1;
            long l;
            int ret=0;
            double d;
            char tmp[1024];
            grib_expression* expression=grib_arguments_get_expression(grib_handle_of_accessor(a),act->default_value,0);
            int type = grib_expression_native_type(grib_handle_of_accessor(a),expression);
            switch(type) {
            case GRIB_TYPE_DOUBLE:
                grib_expression_evaluate_double(grib_handle_of_accessor(a),expression,&d);
                grib_pack_double(a,&d,&s_len);
                break;

            case GRIB_TYPE_LONG:
                grib_expression_evaluate_long(grib_handle_of_accessor(a),expression,&l);
                grib_pack_long(a,&l,&s_len);
                break;

            default:
                s_len = sizeof(tmp);
                p = grib_expression_evaluate_string(grib_handle_of_accessor(a),expression,tmp,&s_len,&ret);
                if (ret != GRIB_SUCCESS) {
                    grib_context_log(a->context,GRIB_LOG_FATAL,
                            "unable to evaluate %s as string",a->name);
                    return ret;
                }
                s_len = strlen(p)+1;
                pack_string(a,p,&s_len);
                break;
            }
            return GRIB_SUCCESS;
        }

    }
    return GRIB_ENCODING_ERROR;
}

static int pack_expression(grib_accessor* a, grib_expression *e)
{
    const char* cval=NULL;
    int ret=0;
    long lval=0;
    size_t len = 1;
    grib_handle* hand = grib_handle_of_accessor(a);

    if (strcmp(e->cclass->name,"long")==0) {
        ret=grib_expression_evaluate_long(hand,e,&lval);
        /*if (hand->context->debug)
            printf("ECCODES DEBUG grib_accessor_class_codetable::pack_expression %s %ld\n", a->name,lval);*/

        ret = grib_pack_long(a,&lval,&len);
    } else {
        char tmp[1024];
        len = sizeof(tmp);
        cval = grib_expression_evaluate_string(hand,e,tmp,&len,&ret);
        if (ret!=GRIB_SUCCESS) {
            grib_context_log(a->context,GRIB_LOG_ERROR,"grib_accessor_codetable.pack_expression: unable to evaluate string %s to be set in %s\n",grib_expression_get_name(e),a->name);
            return ret;
        }
        len = strlen(cval) + 1;
        /*if (hand->context->debug)
            printf("ECCODES DEBUG grib_accessor_class_codetable::pack_expression %s %s\n", a->name, cval);*/
        ret = grib_pack_string(a,cval,&len);
    }
    return ret;
}

static void destroy(grib_context* context,grib_accessor* a)
{
    if (a->vvalue != NULL) {
        grib_context_free(context, a->vvalue);
        a->vvalue=NULL;
    }
}

static int get_native_type(grib_accessor* a)
{
    int type=GRIB_TYPE_LONG;
    /*printf("---------- %s flags=%ld GRIB_ACCESSOR_FLAG_STRING_TYPE=%d\n",
         a->name,a->flags,GRIB_ACCESSOR_FLAG_STRING_TYPE);*/
    if (a->flags & GRIB_ACCESSOR_FLAG_STRING_TYPE)
        type=GRIB_TYPE_STRING;
    return type;
}

static int unpack_long(grib_accessor* a, long* val, size_t *len)
{
    grib_accessor_codetable* self = (grib_accessor_codetable*)a;
    long rlen = 0;
    int err=0;
    unsigned long i = 0;
    long pos = a->offset*8;
    grib_handle* hand = NULL;

#ifdef DEBUG
    err=grib_value_count(a,&rlen);
    Assert(!err);
    Assert(rlen == 1);
#endif
    rlen = 1; /* ECC-480 Performance: avoid func call overhead of grib_value_count */

    if(!self->table) self->table = load_table(self);

    if(*len < rlen)
    {
        grib_context_log(a->context, GRIB_LOG_ERROR, " wrong size (%ld) for %s it contains %d values ",*len, a->name , rlen);
        *len = 0;
        return GRIB_ARRAY_TOO_SMALL;
    }

    if (a->flags & GRIB_ACCESSOR_FLAG_TRANSIENT) {
        *val=a->vvalue->lval;
        *len=1;
        return GRIB_SUCCESS;
    }

    /* ECC-480 Performance: inline the grib_handle_of_accessor here to reduce func call overhead */
    if (a->parent==NULL) hand = a->h;
    else                 hand = a->parent->h;

    for(i=0; i< rlen;i++){
        val[i] = (long)grib_decode_unsigned_long(hand->buffer->data , &pos, self->nbytes*8);
    }

    *len = rlen;
    return GRIB_SUCCESS;
}


text: A selection of data structures made lovingly in C.