text:
package org.apache.flink.test.state;

import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.changelog.fs.FsStateChangelogStorageFactory;
import org.apache.flink.client.program.ClusterClient;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.core.execution.SavepointFormatType;
import org.apache.flink.runtime.jobgraph.JobGraph;
import org.apache.flink.runtime.testutils.CommonTestUtils;
import org.apache.flink.runtime.testutils.MiniClusterResourceConfiguration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.sink.DiscardingSink;
import org.apache.flink.test.util.MiniClusterWithClientResource;

import org.junit.After;
import org.junit.Before;
import org.junit.ClassRule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;

import java.io.File;
import java.time.Duration;
import java.util.Arrays;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Optional;

import static org.apache.flink.configuration.CheckpointingOptions.CHECKPOINTS_DIRECTORY;
import static org.apache.flink.configuration.CheckpointingOptions.SAVEPOINT_DIRECTORY;
import static org.apache.flink.runtime.jobgraph.SavepointRestoreSettings.forPath;
import static org.apache.flink.runtime.testutils.CommonTestUtils.waitForAllTaskRunning;
import static org.apache.flink.runtime.testutils.CommonTestUtils.waitForCheckpoint;
import static org.apache.flink.streaming.api.environment.CheckpointConfig.ExternalizedCheckpointCleanup.RETAIN_ON_CANCELLATION;
import static org.apache.flink.util.ExceptionUtils.findThrowableSerializedAware;
import static org.junit.Assert.fail;

/**
 * A test suite to check that restrictions on recovery with changelog enabled are enforced; and that
 * non-restricted scenarios are not blocked. In particular, recovery from non-changelog checkpoints
 * should not be allowed (see <a
 * href="https://issues.apache.org/jira/browse/FLINK-26079">FLINK-26079</a>).
 */
@RunWith(Parameterized.class)
public class ChangelogCompatibilityITCase {

    private final TestCase testCase;

    @Parameterized.Parameters(name = "{0}")
    public static List<TestCase> parameters() {
        return Arrays.asList(
                // disable changelog - allow restore from CANONICAL_SAVEPOINT
                TestCase.startWithChangelog(true)
                        .restoreWithChangelog(false)
                        .from(RestoreSource.CANONICAL_SAVEPOINT)
                        .allowRestore(true),
                // disable changelog - allow restore from CHECKPOINT
                TestCase.startWithChangelog(true)
                        .restoreWithChangelog(false)
                        .from(RestoreSource.CHECKPOINT)
                        .allowRestore(true),
                // enable changelog - allow restore only from CANONICAL_SAVEPOINT
                TestCase.startWithChangelog(false)
                        .restoreWithChangelog(true)
                        .from(RestoreSource.CANONICAL_SAVEPOINT)
                        .allowRestore(true),
                // explicitly disallow recovery from  non-changelog checkpoints
                // https://issues.apache.org/jira/browse/FLINK-26079
                TestCase.startWithChangelog(false)
                        .restoreWithChangelog(true)
                        .from(RestoreSource.CHECKPOINT)
                        .allowRestore(false),
                // normal cases: changelog enabled before and after recovery
                TestCase.startWithChangelog(true)
                        .restoreWithChangelog(true)
                        .from(RestoreSource.CANONICAL_SAVEPOINT)
                        .allowRestore(true),
                // taking native savepoints is not supported with changelog
                TestCase.startWithChangelog(true)
                        .restoreWithChangelog(true)
                        .from(RestoreSource.NATIVE_SAVEPOINT)
                        .allowSave(false)
                        .allowRestore(false),
                TestCase.startWithChangelog(true)
                        .restoreWithChangelog(true)
                        .from(RestoreSource.CHECKPOINT)
                        .allowRestore(true));
    }

    @Test
    public void testRestore() throws Exception {
        runAndStoreIfAllowed().ifPresent(this::restoreAndValidate);
    }

    private Optional<String> runAndStoreIfAllowed() throws Exception {
        JobGraph initialGraph = addGraph(initEnvironment());
        try {
            String location = tryCheckpointAndStop(initialGraph);
            if (!testCase.allowStore) {
                fail(testCase.describeStore());
            }
            return Optional.of(location);
        } catch (Exception e) {
            if (testCase.allowStore) {
                throw e;
            } else {
                return Optional.empty();
            }
        }
    }

    private StreamExecutionEnvironment initEnvironment() {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.enableChangelogStateBackend(testCase.startWithChangelog);
        if (testCase.restoreSource == RestoreSource.CHECKPOINT) {
            env.enableCheckpointing(50);
            env.getCheckpointConfig().setExternalizedCheckpointCleanup(RETAIN_ON_CANCELLATION);
        }
        return env;
    }

    private JobGraph addGraph(StreamExecutionEnvironment env) {
        env.fromSequence(Long.MIN_VALUE, Long.MAX_VALUE)
                .countWindowAll(37) // any stateful transformation suffices
                .reduce((ReduceFunction<Long>) Long::sum) // overflow is fine, result is discarded
                .addSink(new DiscardingSink<>());
        return env.getStreamGraph().getJobGraph();
    }

    private String tryCheckpointAndStop(JobGraph jobGraph) throws Exception {
        ClusterClient<?> client = miniClusterResource.getClusterClient();
        submit(jobGraph, client);
        if (testCase.restoreSource == RestoreSource.CHECKPOINT) {
            waitForCheckpoint(jobGraph.getJobID(), miniClusterResource.getMiniCluster(), 1);
            client.cancel(jobGraph.getJobID()).get();
            // obtain the latest checkpoint *after* cancellation - that one won't be subsumed
            return CommonTestUtils.getLatestCompletedCheckpointPath(
                            jobGraph.getJobID(), miniClusterResource.getMiniCluster())
                    .<NoSuchElementException>orElseThrow(
                            () -> {
                                throw new NoSuchElementException("No checkpoint was created yet");
                            });
        } else {
            return client.stopWithSavepoint(
                            jobGraph.getJobID(),
                            false,
                            pathToString(savepointDir),
                            testCase.restoreSource == RestoreSource.CANONICAL_SAVEPOINT
                                    ? SavepointFormatType.CANONICAL
                                    : SavepointFormatType.NATIVE)
                    .get();
        }
    }

    private void restoreAndValidate(String location) {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.enableChangelogStateBackend(testCase.restoreWithChangelog);
        JobGraph jobGraph = addGraph(env);
        jobGraph.setSavepointRestoreSettings(forPath(location));

        if (tryRun(jobGraph) != testCase.allowRestore) {
            fail(testCase.describeRestore());
        }
    }

    private boolean tryRun(JobGraph jobGraph) {
        try {
            submit(jobGraph, miniClusterResource.getClusterClient());
            miniClusterResource.getClusterClient().cancel(jobGraph.getJobID()).get();
            return true;
        } catch (AssertionError | Exception e) { // AssertionError is thrown by CommonTestUtils
            if (isValidationError(e)) {
                return false;
            } else {
                throw new RuntimeException(e);
            }
        }
    }

    private boolean isValidationError(Throwable e) {
        return findThrowableSerializedAware(
                        e, IllegalStateException.class, this.getClass().getClassLoader())
                .filter(i -> i.getMessage().toLowerCase().contains("recovery not supported"))
                .isPresent();
    }

    private static final class TestCase {
        boolean startWithChangelog;
        boolean restoreWithChangelog;
        RestoreSource restoreSource;
        boolean allowStore = true;
        boolean allowRestore = false;

        public static TestCase startWithChangelog(boolean changelogEnabled) {
            TestCase testCase = new TestCase();
            testCase.startWithChangelog = changelogEnabled;
            return testCase;
        }

        public TestCase restoreWithChangelog(boolean restoreWithChangelog) {
            this.restoreWithChangelog = restoreWithChangelog;
            return this;
        }

        public TestCase from(RestoreSource restoreSource) {
            this.restoreSource = restoreSource;
            return this;
        }

        public TestCase allowRestore(boolean allowRestore) {
            this.allowRestore = allowRestore;
            return this;
        }

        public TestCase allowSave(boolean allowSave) {
            this.allowStore = allowSave;
            return this;
        }

        @Override
        public String toString() {
            return String.format(
                    "startWithChangelog=%s, restoreWithChangelog=%s, restoreFrom=%s, allowStore=%s, allowRestore=%s",
                    startWithChangelog,
                    restoreWithChangelog,
                    restoreSource,
                    allowStore,
                    allowRestore);
        }

        private String describeStore() {
            return String.format(
                    "taking %s with changelog.enabled=%b should be %s",
                    restoreSource, startWithChangelog, allowStore ? "allowed" : "disallowed");
        }

        private String describeRestore() {
            return String.format(
                    "restoring from %s taken with changelog.enabled=%b should be %s with changelog.enabled=%b",
                    restoreSource,
                    allowRestore ? "allowed" : "disallowed",
                    startWithChangelog,
                    restoreWithChangelog);
        }
    }

    private enum RestoreSource {
        CANONICAL_SAVEPOINT,
        NATIVE_SAVEPOINT,
        CHECKPOINT
    }

    private void submit(JobGraph jobGraph, ClusterClient<?> client) throws Exception {
        client.submitJob(jobGraph).get();
        waitForAllTaskRunning(miniClusterResource.getMiniCluster(), jobGraph.getJobID(), true);
    }

    private static String pathToString(File path) {
        return path.toURI().toString();
    }

    @ClassRule public static final TemporaryFolder TEMPORARY_FOLDER = new TemporaryFolder();
    private File checkpointDir;
    private File savepointDir;
    private MiniClusterWithClientResource miniClusterResource;

    public ChangelogCompatibilityITCase(TestCase testCase) {
        this.testCase = testCase;
    }

    @Before
    public void before() throws Exception {
        checkpointDir = TEMPORARY_FOLDER.newFolder();
        savepointDir = TEMPORARY_FOLDER.newFolder();
        Configuration config = new Configuration();
        config.setString(CHECKPOINTS_DIRECTORY, pathToString(checkpointDir));
        config.setString(SAVEPOINT_DIRECTORY, pathToString(savepointDir));
        FsStateChangelogStorageFactory.configure(
                config, TEMPORARY_FOLDER.newFolder(), Duration.ofMinutes(1), 10);
        miniClusterResource =
                new MiniClusterWithClientResource(
                        new MiniClusterResourceConfiguration.Builder()
                                .setConfiguration(config)
                                .setNumberTaskManagers(11)
                                .setNumberSlotsPerTaskManager(1)
                                .build());
        miniClusterResource.before();
    }

    @After
    public void after() {
        if (miniClusterResource != null) {
            miniClusterResource.after();
        }
    }
}


text:
import fs from 'node:fs'
import path from 'node:path'
import test from 'tape'
import {remark} from 'remark'
import remarkHtml from 'remark-html'
import remarkHighlightjs from '../index.js'

/**
 * @param {string} name
 */
const base = (name) =>
  String(fs.readFileSync(path.join('test', 'fixtures', name)))

test('remark-highlight.js', (t) => {
  t.is(
    remark()
      .use(remarkHighlightjs)
      .use(remarkHtml)
      .processSync(base('input.md'))
      .toString(),
    base('output.html'),
    'should highlight css & js'
  )

  t.is(
    remark()
      .use(remarkHtml)
      .use(remarkHighlightjs)
      .processSync('# Hello!\n\n```\nconsole.log(1)\n```')
      .toString(),
    '
Hello!
\n
console.log(1)\n
\n',
    'should not auto highlight'
  )

  t.is(
    remark()
      .use(remarkHtml)
      .use(remarkHighlightjs, {include: ['html']})
      .processSync('# Hello!\n\n```css\nh1{}\n```')
      .toString(),
    '
Hello!
\n
h1{}\n
\n',
    'should not highlight when the language is not specified (include)'
  )

  t.is(
    remark()
      .use(remarkHtml)
      .use(remarkHighlightjs, {exclude: ['css']})
      .processSync('# Hello!\n\n```css\nh1{}\n```')
      .toString(),
    '
Hello!
\n
h1{}\n
\n',
    'should not highlight when the language is not specified (exclude)'
  )

  t.ok(
    remark()
      .use(remarkHtml)
      .use(remarkHighlightjs, {prefix: 'code_'})
      .processSync('# Hello!\n\n```css\nh1{}\n```')
      .toString()
      .includes('class="code_selector-tag'),
    'should allow to change prefix'
  )

  t.deepEqual(
    remark()
      .use(() => (tree) => {
        tree.children[0].data = {
          hProperties: {dataFoo: 'bar', className: ['quux']}
        }
      })
      .use(remarkHighlightjs)
      .runSync(remark().parse('```css\n```')).children[0].data,
    {
      hProperties: {
        dataFoo: 'bar',
        className: ['hljs', 'quux', 'language-css']
      },
      hChildren: []
    },
    'should not modify existing hProperties and classes'
  )

  t.is(
    remark()
      .use(remarkHtml)
      .use(remarkHighlightjs)
      .processSync('# Hello!\n\n```console\n$ webpack\n```')
      .toString(),
    '
Hello!
\n
$ webpack
\n',
    'should not throw on console syntax'
  )

  t.end()
})

redpajama_set_name: RedPajamaGithub


text:
/******************************************************************************
 *                    _   _____   __________                                  *
 *                   | | / / _ | / __/_  __/     Visibility                   *
 *                   | |/ / __ |_\ \  / /          Across                     *
 *                   |___/_/ |_/___/ /_/       Space and Time                 *
 *                                                                            *
 * This file is part of VAST. It is subject to the license terms in the       *
 * LICENSE file found in the top-level directory of this distribution and at  *
 * http://vast.io/license. No part of VAST, including this file, may be       *
 * copied, modified, propagated, or distributed except according to the terms *
 * contained in the LICENSE file.                                             *
 ******************************************************************************/

#include "vast/format/pcap.hpp"

#include "vast/byte.hpp"
#include "vast/community_id.hpp"
#include "vast/defaults.hpp"
#include "vast/detail/assert.hpp"
#include "vast/detail/byte_swap.hpp"
#include "vast/error.hpp"
#include "vast/ether_type.hpp"
#include "vast/event.hpp"
#include "vast/filesystem.hpp"
#include "vast/logger.hpp"
#include "vast/span.hpp"
#include "vast/table_slice.hpp"
#include "vast/table_slice_builder.hpp"

#include <caf/config_value.hpp>
#include <caf/settings.hpp>

#include <thread>
#include <utility>

#include <netinet/in.h>

namespace vast {
namespace format {
namespace pcap {
namespace {

template <class... RecordFields>
inline type make_packet_type(RecordFields&&... record_fields) {
  return record_type{{"time", time_type{}.attributes({{"timestamp"}})},
                     {"src", address_type{}},
                     {"dst", address_type{}},
                     {"sport", port_type{}},
                     {"dport", port_type{}},
                     std::forward<RecordFields>(record_fields)...,
                     {"payload", string_type{}.attributes({{"skip"}})}}
    .name("pcap.packet");
}

inline const auto pcap_packet_type = make_packet_type();
inline const auto pcap_packet_type_community_id = make_packet_type(
  record_field{"community_id", string_type{}.attributes({{"index", "hash"}})});

} // namespace <anonymous>

reader::reader(caf::atom_value id, const caf::settings& options,
               std::unique_ptr<std::istream>)
  : super(id) {
  using defaults_t = vast::defaults::import::pcap;
  using caf::get_if;
  std::string category = defaults_t::category;
  if (auto interface = get_if<std::string>(&options, category + ".interface"))
    interface_ = *interface;
  input_ = get_or(options, category + ".read", defaults_t::read);
  cutoff_ = get_or(options, category + ".cutoff", defaults_t::cutoff);
  max_flows_ = get_or(options, category + ".max-flows", defaults_t::max_flows);
  max_age_
    = get_or(options, category + ".max-flow-age", defaults_t::max_flow_age);
  expire_interval_
    = get_or(options, category + ".flow-expiry", defaults_t::flow_expiry);
  pseudo_realtime_ = get_or(options, category + ".pseudo-realtime-factor",
                            defaults_t::pseudo_realtime_factor);
  snaplen_ = get_or(options, category + ".snaplen", defaults_t::snaplen);
  community_id_ = !get_or(options, category + ".disable-community-id", false);
  packet_type_
    = community_id_ ? pcap_packet_type_community_id : pcap_packet_type;
}

void reader::reset(std::unique_ptr<std::istream>) {
  // This function intentionally does nothing, as libpcap expects a filename
  // instead of an input stream. It only exists for compatibility with our
  // reader abstraction.
}

reader::~reader() {
  if (pcap_)
    ::pcap_close(pcap_);
}

caf::error reader::schema(vast::schema sch) {
  return replace_if_congruent({&packet_type_}, sch);
}

schema reader::schema() const {
  vast::schema result;
  result.add(packet_type_);
  return result;
}

const char* reader::name() const {
  return "pcap-reader";
}

namespace {

enum class frame_type : char {
  chap_none = '\x00',
  chap_challenge = '\x01',
  chap_response = '\x02',
  chap_both = '\x03',
  ethernet = '\x01',
  vlan = '\x02',
  mpls = '\x03',
  pppoe = '\x04',
  ppp = '\x05',
  chap = '\x06',
  ipv4 = '\x07',
  udp = '\x08',
  radius = '\x09',
  radavp = '\x0a',
  l2tp = '\x0b',
  l2avp = '\x0c',
  ospfv2 = '\x0d',
  ospf_md5 = '\x0e',
  tcp = '\x0f',
  ip_md5 = '\x10',
  unknown = '\x11',
  gre = '\x12',
  gtp = '\x13',
  vxlan = '\x14'
};

// Strips all data from a frame until the IP layer is reached. The frame type
// distinguisher exists for future recursive stripping.
span<const byte> decapsulate(span<const byte> frame, frame_type type) {
  switch (type) {
    default:
      return {};
    case frame_type::ethernet: {
      constexpr size_t ethernet_header_size = 14;
      if (frame.size() < ethernet_header_size)
        return {}; // need at least 2 MAC addresses and the 2-byte EtherType.
      switch (as_ether_type(frame.subspan<12, 2>())) {
        default:
          return frame;
        case ether_type::ieee_802_1aq:
          return frame.subspan<4>(); // One 32-bit VLAN tag
        case ether_type::ieee_802_1q_db:
          return frame.subspan<2 * 4>(); // Two 32-bit VLAN tags
      }
    }
  }
}

} // namespace

caf::error reader::read_impl(size_t max_events, size_t max_slice_size,
                             consumer& f) {
  // Sanity checks.
  VAST_ASSERT(max_events > 0);
  VAST_ASSERT(max_slice_size > 0);
  if (builder_ == nullptr) {
    if (!caf::holds_alternative<record_type>(packet_type_))
      return make_error(ec::parse_error, "illegal packet type");
    if (!reset_builder(caf::get<record_type>(packet_type_)))
      return make_error(ec::parse_error,
                        "unable to create builder for packet type");
  }
  // Local buffer for storing error messages.
  char buf[PCAP_ERRBUF_SIZE];
  // Initialize PCAP if needed.
  if (!pcap_) {
    // Determine interfaces.
    if (interface_) {
      pcap_ = ::pcap_open_live(interface_->c_str(), snaplen_, 1, 1000, buf);
      if (!pcap_) {
        return make_error(ec::format_error, "failed to open interface",
                          *interface_, ":", buf);
      }
      if (pseudo_realtime_ > 0) {
        pseudo_realtime_ = 0;
        VAST_WARNING(this, "ignores pseudo-realtime in live mode");
      }
      VAST_DEBUG(this, "listens on interface", *interface_);
    } else if (input_ != "-" && !exists(input_)) {
      return make_error(ec::format_error, "no such file: ", input_);
    } else {
#ifdef PCAP_TSTAMP_PRECISION_NANO
      pcap_ = ::
        pcap_open_offline_with_tstamp_precision(input_.c_str(),
                                                PCAP_TSTAMP_PRECISION_NANO,
                                                buf);
#else
      pcap_ = ::pcap_open_offline(input_.c_str(), buf);
#endif
      if (!pcap_) {
        flows_.clear();
        return make_error(ec::format_error, "failed to open pcap file ", input_,
                          ": ", std::string{buf});
      }
      VAST_DEBUG(this, "reads trace from", input_);
      if (pseudo_realtime_ > 0)
        VAST_DEBUG(this, "uses pseudo-realtime factor 1/" << pseudo_realtime_);
    }
    VAST_DEBUG(this, "cuts off flows after", cutoff_,
               "bytes in each direction");
    VAST_DEBUG(this, "keeps at most", max_flows_, "concurrent flows");
    VAST_DEBUG(this, "evicts flows after", max_age_ << "s of inactivity");
    VAST_DEBUG(this, "expires flow table every", expire_interval_ << "s");
  }
  for (size_t produced = 0; produced < max_events; ++produced) {
    // Attempt to fetch next packet.
    const u_char* data;
    pcap_pkthdr* header;
    auto r = ::pcap_next_ex(pcap_, &header, &data);
    if (r == 0)
      return finish(f, caf::none); // timed out
    if (r == -2)
      return finish(f, make_error(ec::end_of_input, "reached end of trace"));
    if (r == -1) {
      auto err = std::string{::pcap_geterr(pcap_)};
      ::pcap_close(pcap_);
      pcap_ = nullptr;
      return finish(f, make_error(ec::format_error,
                                  "failed to get next packet: ", err));
    }
    // Parse frame.
    span<const byte> frame{reinterpret_cast<const byte*>(data), header->len};
    frame = decapsulate(frame, frame_type::ethernet);
    if (frame.empty())
      return make_error(ec::format_error, "failed to decapsulate frame");
    constexpr size_t ethernet_header_size = 14;
    auto layer3 = frame.subspan<ethernet_header_size>();
    span<const byte> layer4;
    uint8_t layer4_proto = 0;
    flow conn;
    // Parse layer 3.
    switch (as_ether_type(frame.subspan<12, 2>())) {
      default: {
        VAST_DEBUG(this, "skips non-IP packet");
        continue;
      }
      case ether_type::ipv4: {
        constexpr size_t ipv4_header_size = 20;
        if (header->len < ethernet_header_size + ipv4_header_size)
          return make_error(ec::format_error, "IPv4 header too short");
        size_t header_size = (to_integer<uint8_t>(layer3[0]) & 0x0f) * 4;
        if (header_size < ipv4_header_size)
          return make_error(ec::format_error,
                            "IPv4 header too short: ", header_size, " bytes");
        auto orig_h
          = reinterpret_cast<const uint32_t*>(std::launder(layer3.data() + 12));
        auto resp_h
          = reinterpret_cast<const uint32_t*>(std::launder(layer3.data() + 16));
        conn.src_addr = {orig_h, address::ipv4, address::network};
        conn.dst_addr = {resp_h, address::ipv4, address::network};
        layer4_proto = to_integer<uint8_t>(layer3[9]);
        layer4 = layer3.subspan(header_size);
        break;
      }
      case ether_type::ipv6: {
        if (header->len < ethernet_header_size + 40)
          return make_error(ec::format_error, "IPv6 header too short");
        auto orig_h
          = reinterpret_cast<const uint32_t*>(std::launder(layer3.data() + 8));
        auto resp_h
          = reinterpret_cast<const uint32_t*>(std::launder(layer3.data() + 24));
        conn.src_addr = {orig_h, address::ipv4, address::network};
        conn.dst_addr = {resp_h, address::ipv4, address::network};
        layer4_proto = to_integer<uint8_t>(layer3[6]);
        layer4 = layer3.subspan(40);
        break;
      }
    }
    // Parse layer 4.
    auto payload_size = layer4.size();
    if (layer4_proto == IPPROTO_TCP) {
      VAST_ASSERT(!layer4.empty());
      auto orig_p
        = *reinterpret_cast<const uint16_t*>(std::launder(layer4.data()));
      auto resp_p
        = *reinterpret_cast<const uint16_t*>(std::launder(layer4.data() + 2));
      orig_p = detail::to_host_order(orig_p);
      resp_p = detail::to_host_order(resp_p);
      conn.src_port = {orig_p, port::tcp};
      conn.dst_port = {resp_p, port::tcp};
      auto data_offset
        = *reinterpret_cast<const uint8_t*>(std::launder(layer4.data() + 12))
          >> 4;
      payload_size -= data_offset * 4;
    } else if (layer4_proto == IPPROTO_UDP) {
      VAST_ASSERT(!layer4.empty());
      auto orig_p
        = *reinterpret_cast<const uint16_t*>(std::launder(layer4.data()));
      auto resp_p
        = *reinterpret_cast<const uint16_t*>(std::launder(layer4.data() + 2));
      orig_p = detail::to_host_order(orig_p);
      resp_p = detail::to_host_order(resp_p);
      conn.src_port = {orig_p, port::udp};
      conn.dst_port = {resp_p, port::udp};
      payload_size -= 8;
    } else if (layer4_proto == IPPROTO_ICMP) {
      VAST_ASSERT(!layer4.empty());
      auto message_type = to_integer<uint8_t>(layer4[0]);
      auto message_code = to_integer<uint8_t>(layer4[1]);
      conn.src_port = {message_type, port::icmp};
      conn.dst_port = {message_code, port::icmp};
      payload_size -= 8; // TODO: account for variable-size data.
    }
    // Parse packet timestamp
    uint64_t packet_time = header->ts.tv_sec;
    if (last_expire_ == 0)
      last_expire_ = packet_time;
    if (!update_flow(conn, packet_time, payload_size)) {
      // Skip cut off packets.
      continue;
    }
    evict_inactive(packet_time);
    shrink_to_max_size();
    // Extract timestamp.
    using namespace std::chrono;
    auto secs = seconds(header->ts.tv_sec);
    auto ts = time{duration_cast<duration>(secs)};
#ifdef PCAP_TSTAMP_PRECISION_NANO
    ts += nanoseconds(header->ts.tv_usec);
#else
    ts += microseconds(header->ts.tv_usec);
#endif
    // Assemble packet.
    auto layer3_ptr = reinterpret_cast<const char*>(layer3.data());
    auto packet = std::string_view{std::launder(layer3_ptr), layer3.size()};
    auto& cid = state(conn).community_id;
    if (!(builder_->add(ts) && builder_->add(conn.src_addr)
          && builder_->add(conn.dst_addr) && builder_->add(conn.src_port)
          && builder_->add(conn.dst_port)
          && (!community_id_ || builder_->add(std::string_view{cid}))
          && builder_->add(packet))) {
      return make_error(ec::parse_error, "unable to fill row");
    }
    if (pseudo_realtime_ > 0) {
      if (ts < last_timestamp_) {
        VAST_WARNING(this, "encountered non-monotonic packet timestamps:",
                     ts.time_since_epoch().count(), '<',
                     last_timestamp_.time_since_epoch().count());
      }
      if (last_timestamp_ != time::min()) {
        auto delta = ts - last_timestamp_;
        std::this_thread::sleep_for(delta / pseudo_realtime_);
      }
      last_timestamp_ = ts;
    }
    if (builder_->rows() == max_slice_size)
      if (auto err = finish(f, caf::none))
        return err;
  }
  return finish(f, caf::none);
}

reader::flow_state& reader::state(const flow& x) {
  auto i = flows_.find(x);
  if (i == flows_.end()) {
    auto cf = flow{x.src_addr, x.dst_addr, x.src_port, x.dst_port};
    auto id = community_id::compute<policy::base64>(cf);
    i = flows_.emplace(x, flow_state{0, 0, std::move(id)}).first;
  }
  return i->second;
}

bool reader::update_flow(const flow& x, uint64_t packet_time,
                         uint64_t payload_size) {
  auto& st = state(x);
  st.last = packet_time;
  auto& flow_size = st.bytes;
  if (flow_size == cutoff_)
    return false;
  VAST_ASSERT(flow_size < cutoff_);
  // Trim the packet if needed.
  flow_size += std::min(payload_size, cutoff_ - flow_size);
  return true;
}

void reader::evict_inactive(uint64_t packet_time) {
  if (packet_time - last_expire_ <= expire_interval_)
    return;
  last_expire_ = packet_time;
  auto i = flows_.begin();
  while (i != flows_.end())
    if (packet_time - i->second.last > max_age_)
      i = flows_.erase(i);
    else
      ++i;
}

void reader::shrink_to_max_size() {
  while (flows_.size() >= max_flows_) {
    auto buckets = flows_.bucket_count();
    auto unif1 = std::uniform_int_distribution<size_t>{0, buckets - 1};
    auto bucket = unif1(generator_);
    auto bucket_size = flows_.bucket_size(bucket);
    while (bucket_size == 0) {
      ++bucket;
      bucket %= buckets;
      bucket_size = flows_.bucket_size(bucket);
    }
    auto unif2 = std::uniform_int_distribution<size_t>{0, bucket_size - 1};
    auto offset = unif2(generator_);
    VAST_ASSERT(offset < bucket_size);
    auto begin = flows_.begin(bucket);
    std::advance(begin, offset);
    flows_.erase(begin->first);
  }
}

writer::writer(std::string trace, size_t flush_interval, size_t snaplen)
  : flush_interval_{flush_interval}, snaplen_{snaplen}, trace_{std::move(trace)} {
}

writer::~writer() {
  if (dumper_)
    ::pcap_dump_close(dumper_);
  if (pcap_)
    ::pcap_close(pcap_);
}

caf::error writer::write(const table_slice& slice) {
  if (!pcap_) {
#ifdef PCAP_TSTAMP_PRECISION_NANO
    pcap_ = ::pcap_open_dead_with_tstamp_precision(DLT_RAW, snaplen_,
                                                   PCAP_TSTAMP_PRECISION_NANO);
#else
    pcap_ = ::pcap_open_dead(DLT_RAW, snaplen_);
#endif
    if (!pcap_)
      return make_error(ec::format_error, "failed to open pcap handle");
    dumper_ = ::pcap_dump_open(pcap_, trace_.c_str());
    if (!dumper_)
      return make_error(ec::format_error, "failed to open pcap dumper");
  }
  if (!congruent(slice.layout(), pcap_packet_type)
      && !congruent(slice.layout(), pcap_packet_type_community_id))
    return make_error(ec::format_error, "invalid pcap packet type");
  // TODO: consider iterating in natural order for the slice.
  for (size_t row = 0; row < slice.rows(); ++row) {
    auto payload_field = slice.at(row, 6);
    auto& payload = caf::get<view<std::string>>(payload_field);
    // Make PCAP header.
    ::pcap_pkthdr header;
    auto ns_field = slice.at(row, 0);
    auto ns = caf::get<view<time>>(ns_field).time_since_epoch().count();
    header.ts.tv_sec = ns / 1000000000;
#ifdef PCAP_TSTAMP_PRECISION_NANO
    header.ts.tv_usec = ns % 1000000000;
#else
    ns /= 1000;
    header.ts.tv_usec = ns % 1000000;
#endif
    header.caplen = payload.size();
    header.len = payload.size();
    // Dump packet.
    ::pcap_dump(reinterpret_cast<uint8_t*>(dumper_), &header,
                reinterpret_cast<const uint8_t*>(std::launder(payload.data())));
  }
  if (++total_packets_ % flush_interval_ == 0)
    if (auto r = flush(); !r)
      return r.error();
  return caf::none;
}

caf::expected<void> writer::flush() {
  if (!dumper_)
    return make_error(ec::format_error, "pcap dumper not open");
  VAST_DEBUG(this, "flushes at packet", total_packets_);
  if (::pcap_dump_flush(dumper_) == -1)
    return make_error(ec::format_error, "failed to flush");
  return caf::no_error;
}

const char* writer::name() const {
  return "pcap-writer";
}

} // namespace pcap
} // namespace format
} // namespace vast


text:
<?php

/**
 *      [Discuz!] (C)2001-2099 Comsenz Inc.
 *      This is NOT a freeware, use is subject to license terms
 *
 *      $Id: table_home_feed.php 28335 2012-02-28 04:37:47Z zhangguosheng $
 */

if(!defined('IN_DISCUZ')) {
	exit('Access Denied');
}

class table_home_feed extends discuz_table
{
	public function __construct() {

		$this->_table = 'home_feed';
		$this->_pk    = 'feedid';

		parent::__construct();
	}

	public function optimize_table() {
		return DB::query("OPTIMIZE TABLE %t", array($this->_table), true);
	}

	public function fetch($id, $idtype = '', $uid = '', $feedid = '') {
		$wherearr = array();
		if($feedid) {
			$wherearr[] = DB::field('feedid', $feedid);
		}
		if($id) {
			$wherearr[] = DB::field('id', $id);
			$wherearr[] = DB::field('idtype', $idtype);
		}
		if($uid) {
			$wherearr[] = DB::field('uid', $uid);
		}
		$wheresql = !empty($wherearr) && is_array($wherearr) ? ' WHERE '.implode(' AND ', $wherearr) : '';

		if(empty($wheresql)) {
			return null;
		}

		return DB::fetch_first('SELECT * FROM '.DB::table($this->_table).' '.$wheresql);
	}

	public function fetch_all_by_uid_dateline($uids, $findex = true, $start = 0, $limit = 5) {
		if(!($uids = dintval($uids, true))) {
			return null;
		}
		return DB::fetch_all('SELECT * FROM %t '.(($findex) ? 'USE INDEX(dateline)' : '').' WHERE uid IN (%n) ORDER BY dateline desc %i', array($this->_table, $uids, DB::limit($start, $limit)));
	}

	public function fetch_all_by_hot($hotstarttime) {
		return DB::fetch_all('SELECT * FROM %t USE INDEX(hot) WHERE dateline>=%d ORDER BY hot DESC LIMIT 0,10', array($this->_table, $hotstarttime));
	}

	public function update($id, $data, $idtype = '', $uid = '', $feedid = '') {
		$condition = array();
		if($feedid) {
			$condition[] = DB::field('feedid', $feedid);
		}
		if($id) {
			$condition[] = DB::field('id', $id);
			$condition[] = DB::field('idtype', $idtype);
		}
		if($uid) {
			$condition[] = DB::field('uid', $uid);
		}

		if(empty($data) || !is_array($data) || !count($condition)) {
			return null;
		}
		DB::update($this->_table, $data, implode(' AND ', $condition));
	}

	public function update_hot_by_id($id, $idtype, $uid, $inchot) {
		DB::query('UPDATE %t SET hot = hot+\'%d\' WHERE id = %d AND idtype = %s AND uid = %d', array($this->_table, $inchot, $id, $idtype, $uid));
	}

	public function update_hot_by_feedid($feedid, $inchot) {
		DB::query('UPDATE %t SET hot = hot+\'%d\' WHERE feedid = %d', array($this->_table, $inchot, $feedid));
	}

	public function delete_by_dateline($dateline, $hot = 0) {
		if(!is_numeric($dateline) || !is_numeric($hot)) {
			return false;
		}
		$condition = array();

		$condition[] = DB::field('dateline', $dateline, '<');
		$condition[] = DB::field('hot', $hot);

		DB::delete($this->_table, implode(' AND ', $condition));
	}

	public function delete_by_id_idtype($ids, $idtype) {
		if(!$ids || !$idtype) {
			return null;
		}
		$condition = array();

		$condition[] = DB::field('id', $ids);
		$condition[] = DB::field('idtype', $idtype);

		DB::delete($this->_table, implode(' AND ', $condition));
	}

	public function delete_by_uid_idtype($uid, $idtype) {
		if(!$uid || !$idtype) {
			return null;
		}
		$condition = array();
		$condition[] = DB::field('uid', $uid);
		$condition[] = DB::field('idtype', $idtype);

		DB::delete($this->_table, implode(' AND ', $condition));
	}

	public function delete_by_icon($icon) {
		if(!$icon) {
			return null;
		}
		DB::delete($this->_table, DB::field('icon', $icon));
	}

	public function delete($feedid, $uid = '') {
		$condition = array();

		if($feedid) {
			$condition[] = DB::field('feedid', $feedid);
		}

		if($uid) {
			$condition[] = DB::field('uid', $uid);
		}

		if(!count($condition)) {
			return null;
		}

		DB::delete($this->_table, implode(' AND ', $condition));
	}

	public function delete_by_uid($uids) {
		if(!$uids) {
			return null;
		}
		DB::delete($this->_table, DB::field('uid', $uids).' OR ('.DB::field('id', $uids).' AND idtype=\'uid\')');
	}

	public function fetch_uid_by_username($users) {
		if(!$users) {
			return null;
		}
		return DB::fetch_all('SELECT uid FROM %t WHERE username IN (%n)', array($this->_table, $users), 'uid');
	}

	public function fetch_icon_by_icon($icon) {
		return DB::fetch_first('SELECT icon FROM %t WHERE icon=%s', array($this->_table, $icon));
	}

	public function fetch_feedid_by_hashdata($uid, $hash_data) {
		return DB::fetch_first('SELECT feedid FROM %t WHERE uid=%d AND hash_data=%s LIMIT 0,1', array($this->_table, $uid, $hash_data));
	}

	public function fetch_feedid_by_feedid($feedid) {
		if(!$feedid) {
			return null;
		}
		return DB::fetch_all('SELECT feedid FROM %t WHERE feedid IN (%n)', array($this->_table, $feedid), 'feedid');
	}

	public function fetch_uid_by_uid($uid) {
		if(!$uid) {
			return null;
		}
		return DB::fetch_all('SELECT uid FROM %t WHERE uid IN (%n)', array($this->_table, $uid), 'uid');
	}

	public function fetch_all_by_search($fetchtype, $uids, $icon, $starttime, $endtime, $feedids, $hot1, $hot2, $start = 0, $limit = 0, $findex = '', $appid = '') {
		$parameter = array($this->_table);
		$wherearr = array();
		if(is_array($uids) && count($uids)) {
			$parameter[] = $uids;
			$wherearr[] = 'uid IN(%n)';
		}

		if($appid) {
			$parameter[] = $appid;
			$wherearr[] = 'appid=%d';
		}

		if($icon) {
			$parameter[] = $icon;
			$wherearr[] = 'icon=%s';
		}

		if($starttime) {
			$parameter[] = is_numeric($starttime) ? $starttime : strtotime($starttime);
			$wherearr[] = 'dateline>%d';
		}

		if($endtime) {
			$parameter[] = is_numeric($endtime) ? $endtime : strtotime($endtime);
			$wherearr[] = 'dateline<%d';
		}

		if(is_array($feedids) && count($feedids)) {
			$parameter[] = $feedids;
			$wherearr[] = 'feedid IN(%n)';
		}

		if($hot1) {
			$parameter[] = $hot1;
			$wherearr[] = 'hot>=%d';
		}

		if($hot2) {
			$parameter[] = $hot2;
			$wherearr[] = 'hot<=%d';
		}

		if($fetchtype == 3) {
			$selectfield = "count(*)";
		} elseif ($fetchtype == 2) {
			$selectfield = "feedid";
		} else {
			$selectfield = "*";
			$parameter[] = DB::limit($start, $limit);
			$ordersql = ' ORDER BY dateline DESC %i';
		}

		if($findex) {
			$findex = 'USE INDEX(dateline)';
		}

		$wheresql = !empty($wherearr) && is_array($wherearr) ? ' WHERE '.implode(' AND ', $wherearr) : '';

		if($fetchtype == 3) {
			return DB::result_first("SELECT $selectfield FROM %t $wheresql", $parameter);
		} else {
			return DB::fetch_all("SELECT $selectfield FROM %t {$findex} $wheresql $ordersql", $parameter);
		}
	}
}

?>


text:
import os
import sys
import shutil
import tempfile

from django.conf import settings
import django

TMPDIR = tempfile.mkdtemp(prefix='spillway_')

DEFAULT_SETTINGS = {
    'INSTALLED_APPS': (
        'django.contrib.gis',
        'spillway',
        'tests',
    ),
    'DATABASES': {
        'default': {
            'ENGINE': 'django.contrib.gis.db.backends.spatialite',
            'NAME': ':memory:'
        }
    },
    'MEDIA_ROOT': TMPDIR,
    'MIDDLEWARE_CLASSES': (
        'django.middleware.common.CommonMiddleware',
        'django.middleware.csrf.CsrfViewMiddleware',
    ),
    'ROOT_URLCONF': 'tests.urls'
}

def teardown():
    try:
        shutil.rmtree(TMPDIR)
    except OSError:
        print('Failed to remove {}'.format(TMPDIR))

def runtests():
    if not settings.configured:
        settings.configure(**DEFAULT_SETTINGS)
    # Compatibility with Django 1.7's stricter initialization
    if hasattr(django, 'setup'):
        django.setup()
    parent = os.path.dirname(os.path.abspath(__file__))
    sys.path.insert(0, parent)
    try:
        from django.test.runner import DiscoverRunner
        runner_class = DiscoverRunner
    except ImportError:
        from django.test.simple import DjangoTestSuiteRunner
        runner_class = DjangoTestSuiteRunner
    try:
        status = runner_class(
            verbosity=1, interactive=True, failfast=False).run_tests(['tests'])
    except:
        status = 1
    finally:
        teardown()
    sys.exit(status)

if __name__ == '__main__':
    runtests()


text:
package server

import (
	"context"
	"errors"
	"github.com/GoogleCloudPlatform/declarative-resource-client-library/dcl"
	alphapb "github.com/GoogleCloudPlatform/declarative-resource-client-library/python/proto/binaryauthorization/alpha/binaryauthorization_alpha_go_proto"
	emptypb "github.com/GoogleCloudPlatform/declarative-resource-client-library/python/proto/empty_go_proto"
	"github.com/GoogleCloudPlatform/declarative-resource-client-library/services/google/binaryauthorization/alpha"
)

// PolicyServer implements the gRPC interface for Policy.
type PolicyServer struct{}

// ProtoToPolicyClusterAdmissionRulesEvaluationModeEnum converts a PolicyClusterAdmissionRulesEvaluationModeEnum enum from its proto representation.
func ProtoToBinaryauthorizationAlphaPolicyClusterAdmissionRulesEvaluationModeEnum(e alphapb.BinaryauthorizationAlphaPolicyClusterAdmissionRulesEvaluationModeEnum) *alpha.PolicyClusterAdmissionRulesEvaluationModeEnum {
	if e == 0 {
		return nil
	}
	if n, ok := alphapb.BinaryauthorizationAlphaPolicyClusterAdmissionRulesEvaluationModeEnum_name[int32(e)]; ok {
		e := alpha.PolicyClusterAdmissionRulesEvaluationModeEnum(n[len("BinaryauthorizationAlphaPolicyClusterAdmissionRulesEvaluationModeEnum"):])
		return &e
	}
	return nil
}

// ProtoToPolicyClusterAdmissionRulesEnforcementModeEnum converts a PolicyClusterAdmissionRulesEnforcementModeEnum enum from its proto representation.
func ProtoToBinaryauthorizationAlphaPolicyClusterAdmissionRulesEnforcementModeEnum(e alphapb.BinaryauthorizationAlphaPolicyClusterAdmissionRulesEnforcementModeEnum) *alpha.PolicyClusterAdmissionRulesEnforcementModeEnum {
	if e == 0 {
		return nil
	}
	if n, ok := alphapb.BinaryauthorizationAlphaPolicyClusterAdmissionRulesEnforcementModeEnum_name[int32(e)]; ok {
		e := alpha.PolicyClusterAdmissionRulesEnforcementModeEnum(n[len("BinaryauthorizationAlphaPolicyClusterAdmissionRulesEnforcementModeEnum"):])
		return &e
	}
	return nil
}

// ProtoToPolicyKubernetesNamespaceAdmissionRulesEvaluationModeEnum converts a PolicyKubernetesNamespaceAdmissionRulesEvaluationModeEnum enum from its proto representation.
func ProtoToBinaryauthorizationAlphaPolicyKubernetesNamespaceAdmissionRulesEvaluationModeEnum(e alphapb.BinaryauthorizationAlphaPolicyKubernetesNamespaceAdmissionRulesEvaluationModeEnum) *alpha.PolicyKubernetesNamespaceAdmissionRulesEvaluationModeEnum {
	if e == 0 {
		return nil
	}
	if n, ok := alphapb.BinaryauthorizationAlphaPolicyKubernetesNamespaceAdmissionRulesEvaluationModeEnum_name[int32(e)]; ok {
		e := alpha.PolicyKubernetesNamespaceAdmissionRulesEvaluationModeEnum(n[len("BinaryauthorizationAlphaPolicyKubernetesNamespaceAdmissionRulesEvaluationModeEnum"):])
		return &e
	}
	return nil
}

// ProtoToPolicyKubernetesNamespaceAdmissionRulesEnforcementModeEnum converts a PolicyKubernetesNamespaceAdmissionRulesEnforcementModeEnum enum from its proto representation.
func ProtoToBinaryauthorizationAlphaPolicyKubernetesNamespaceAdmissionRulesEnforcementModeEnum(e alphapb.BinaryauthorizationAlphaPolicyKubernetesNamespaceAdmissionRulesEnforcementModeEnum) *alpha.PolicyKubernetesNamespaceAdmissionRulesEnforcementModeEnum {
	if e == 0 {
		return nil
	}
	if n, ok := alphapb.BinaryauthorizationAlphaPolicyKubernetesNamespaceAdmissionRulesEnforcementModeEnum_name[int32(e)]; ok {
		e := alpha.PolicyKubernetesNamespaceAdmissionRulesEnforcementModeEnum(n[len("BinaryauthorizationAlphaPolicyKubernetesNamespaceAdmissionRulesEnforcementModeEnum"):])
		return &e
	}
	return nil
}

// ProtoToPolicyKubernetesServiceAccountAdmissionRulesEvaluationModeEnum converts a PolicyKubernetesServiceAccountAdmissionRulesEvaluationModeEnum enum from its proto representation.
func ProtoToBinaryauthorizationAlphaPolicyKubernetesServiceAccountAdmissionRulesEvaluationModeEnum(e alphapb.BinaryauthorizationAlphaPolicyKubernetesServiceAccountAdmissionRulesEvaluationModeEnum) *alpha.PolicyKubernetesServiceAccountAdmissionRulesEvaluationModeEnum {
	if e == 0 {
		return nil
	}
	if n, ok := alphapb.BinaryauthorizationAlphaPolicyKubernetesServiceAccountAdmissionRulesEvaluationModeEnum_name[int32(e)]; ok {
		e := alpha.PolicyKubernetesServiceAccountAdmissionRulesEvaluationModeEnum(n[len("BinaryauthorizationAlphaPolicyKubernetesServiceAccountAdmissionRulesEvaluationModeEnum"):])
		return &e
	}
	return nil
}

// ProtoToPolicyKubernetesServiceAccountAdmissionRulesEnforcementModeEnum converts a PolicyKubernetesServiceAccountAdmissionRulesEnforcementModeEnum enum from its proto representation.
func ProtoToBinaryauthorizationAlphaPolicyKubernetesServiceAccountAdmissionRulesEnforcementModeEnum(e alphapb.BinaryauthorizationAlphaPolicyKubernetesServiceAccountAdmissionRulesEnforcementModeEnum) *alpha.PolicyKubernetesServiceAccountAdmissionRulesEnforcementModeEnum {
	if e == 0 {
		return nil
	}
	if n, ok := alphapb.BinaryauthorizationAlphaPolicyKubernetesServiceAccountAdmissionRulesEnforcementModeEnum_name[int32(e)]; ok {
		e := alpha.PolicyKubernetesServiceAccountAdmissionRulesEnforcementModeEnum(n[len("BinaryauthorizationAlphaPolicyKubernetesServiceAccountAdmissionRulesEnforcementModeEnum"):])
		return &e
	}
	return nil
}

// ProtoToPolicyIstioServiceIdentityAdmissionRulesEvaluationModeEnum converts a PolicyIstioServiceIdentityAdmissionRulesEvaluationModeEnum enum from its proto representation.
func ProtoToBinaryauthorizationAlphaPolicyIstioServiceIdentityAdmissionRulesEvaluationModeEnum(e alphapb.BinaryauthorizationAlphaPolicyIstioServiceIdentityAdmissionRulesEvaluationModeEnum) *alpha.PolicyIstioServiceIdentityAdmissionRulesEvaluationModeEnum {
	if e == 0 {
		return nil
	}
	if n, ok := alphapb.BinaryauthorizationAlphaPolicyIstioServiceIdentityAdmissionRulesEvaluationModeEnum_name[int32(e)]; ok {
		e := alpha.PolicyIstioServiceIdentityAdmissionRulesEvaluationModeEnum(n[len("BinaryauthorizationAlphaPolicyIstioServiceIdentityAdmissionRulesEvaluationModeEnum"):])
		return &e
	}
	return nil
}

// ProtoToPolicyIstioServiceIdentityAdmissionRulesEnforcementModeEnum converts a PolicyIstioServiceIdentityAdmissionRulesEnforcementModeEnum enum from its proto representation.
func ProtoToBinaryauthorizationAlphaPolicyIstioServiceIdentityAdmissionRulesEnforcementModeEnum(e alphapb.BinaryauthorizationAlphaPolicyIstioServiceIdentityAdmissionRulesEnforcementModeEnum) *alpha.PolicyIstioServiceIdentityAdmissionRulesEnforcementModeEnum {
	if e == 0 {
		return nil
	}
	if n, ok := alphapb.BinaryauthorizationAlphaPolicyIstioServiceIdentityAdmissionRulesEnforcementModeEnum_name[int32(e)]; ok {
		e := alpha.PolicyIstioServiceIdentityAdmissionRulesEnforcementModeEnum(n[len("BinaryauthorizationAlphaPolicyIstioServiceIdentityAdmissionRulesEnforcementModeEnum"):])
		return &e
	}
	return nil
}

// ProtoToPolicyDefaultAdmissionRuleEvaluationModeEnum converts a PolicyDefaultAdmissionRuleEvaluationModeEnum enum from its proto representation.
func ProtoToBinaryauthorizationAlphaPolicyDefaultAdmissionRuleEvaluationModeEnum(e alphapb.BinaryauthorizationAlphaPolicyDefaultAdmissionRuleEvaluationModeEnum) *alpha.PolicyDefaultAdmissionRuleEvaluationModeEnum {
	if e == 0 {
		return nil
	}
	if n, ok := alphapb.BinaryauthorizationAlphaPolicyDefaultAdmissionRuleEvaluationModeEnum_name[int32(e)]; ok {
		e := alpha.PolicyDefaultAdmissionRuleEvaluationModeEnum(n[len("BinaryauthorizationAlphaPolicyDefaultAdmissionRuleEvaluationModeEnum"):])
		return &e
	}
	return nil
}

// ProtoToPolicyDefaultAdmissionRuleEnforcementModeEnum converts a PolicyDefaultAdmissionRuleEnforcementModeEnum enum from its proto representation.
func ProtoToBinaryauthorizationAlphaPolicyDefaultAdmissionRuleEnforcementModeEnum(e alphapb.BinaryauthorizationAlphaPolicyDefaultAdmissionRuleEnforcementModeEnum) *alpha.PolicyDefaultAdmissionRuleEnforcementModeEnum {
	if e == 0 {
		return nil
	}
	if n, ok := alphapb.BinaryauthorizationAlphaPolicyDefaultAdmissionRuleEnforcementModeEnum_name[int32(e)]; ok {
		e := alpha.PolicyDefaultAdmissionRuleEnforcementModeEnum(n[len("BinaryauthorizationAlphaPolicyDefaultAdmissionRuleEnforcementModeEnum"):])
		return &e
	}
	return nil
}

// ProtoToPolicyGlobalPolicyEvaluationModeEnum converts a PolicyGlobalPolicyEvaluationModeEnum enum from its proto representation.
func ProtoToBinaryauthorizationAlphaPolicyGlobalPolicyEvaluationModeEnum(e alphapb.BinaryauthorizationAlphaPolicyGlobalPolicyEvaluationModeEnum) *alpha.PolicyGlobalPolicyEvaluationModeEnum {
	if e == 0 {
		return nil
	}
	if n, ok := alphapb.BinaryauthorizationAlphaPolicyGlobalPolicyEvaluationModeEnum_name[int32(e)]; ok {
		e := alpha.PolicyGlobalPolicyEvaluationModeEnum(n[len("BinaryauthorizationAlphaPolicyGlobalPolicyEvaluationModeEnum"):])
		return &e
	}
	return nil
}

// ProtoToPolicyAdmissionWhitelistPatterns converts a PolicyAdmissionWhitelistPatterns object from its proto representation.
func ProtoToBinaryauthorizationAlphaPolicyAdmissionWhitelistPatterns(p *alphapb.BinaryauthorizationAlphaPolicyAdmissionWhitelistPatterns) *alpha.PolicyAdmissionWhitelistPatterns {
	if p == nil {
		return nil
	}
	obj := &alpha.PolicyAdmissionWhitelistPatterns{
		NamePattern: dcl.StringOrNil(p.GetNamePattern()),
	}
	return obj
}

// ProtoToPolicyClusterAdmissionRules converts a PolicyClusterAdmissionRules object from its proto representation.
func ProtoToBinaryauthorizationAlphaPolicyClusterAdmissionRules(p *alphapb.BinaryauthorizationAlphaPolicyClusterAdmissionRules) *alpha.PolicyClusterAdmissionRules {
	if p == nil {
		return nil
	}
	obj := &alpha.PolicyClusterAdmissionRules{
		EvaluationMode:  ProtoToBinaryauthorizationAlphaPolicyClusterAdmissionRulesEvaluationModeEnum(p.GetEvaluationMode()),
		EnforcementMode: ProtoToBinaryauthorizationAlphaPolicyClusterAdmissionRulesEnforcementModeEnum(p.GetEnforcementMode()),
	}
	for _, r := range p.GetRequireAttestationsBy() {
		obj.RequireAttestationsBy = append(obj.RequireAttestationsBy, r)
	}
	return obj
}

// ProtoToPolicyKubernetesNamespaceAdmissionRules converts a PolicyKubernetesNamespaceAdmissionRules object from its proto representation.
func ProtoToBinaryauthorizationAlphaPolicyKubernetesNamespaceAdmissionRules(p *alphapb.BinaryauthorizationAlphaPolicyKubernetesNamespaceAdmissionRules) *alpha.PolicyKubernetesNamespaceAdmissionRules {
	if p == nil {
		return nil
	}
	obj := &alpha.PolicyKubernetesNamespaceAdmissionRules{
		EvaluationMode:  ProtoToBinaryauthorizationAlphaPolicyKubernetesNamespaceAdmissionRulesEvaluationModeEnum(p.GetEvaluationMode()),
		EnforcementMode: ProtoToBinaryauthorizationAlphaPolicyKubernetesNamespaceAdmissionRulesEnforcementModeEnum(p.GetEnforcementMode()),
	}
	for _, r := range p.GetRequireAttestationsBy() {
		obj.RequireAttestationsBy = append(obj.RequireAttestationsBy, r)
	}
	return obj
}

// ProtoToPolicyKubernetesServiceAccountAdmissionRules converts a PolicyKubernetesServiceAccountAdmissionRules object from its proto representation.
func ProtoToBinaryauthorizationAlphaPolicyKubernetesServiceAccountAdmissionRules(p *alphapb.BinaryauthorizationAlphaPolicyKubernetesServiceAccountAdmissionRules) *alpha.PolicyKubernetesServiceAccountAdmissionRules {
	if p == nil {
		return nil
	}
	obj := &alpha.PolicyKubernetesServiceAccountAdmissionRules{
		EvaluationMode:  ProtoToBinaryauthorizationAlphaPolicyKubernetesServiceAccountAdmissionRulesEvaluationModeEnum(p.GetEvaluationMode()),
		EnforcementMode: ProtoToBinaryauthorizationAlphaPolicyKubernetesServiceAccountAdmissionRulesEnforcementModeEnum(p.GetEnforcementMode()),
	}
	for _, r := range p.GetRequireAttestationsBy() {
		obj.RequireAttestationsBy = append(obj.RequireAttestationsBy, r)
	}
	return obj
}

// ProtoToPolicyIstioServiceIdentityAdmissionRules converts a PolicyIstioServiceIdentityAdmissionRules object from its proto representation.
func ProtoToBinaryauthorizationAlphaPolicyIstioServiceIdentityAdmissionRules(p *alphapb.BinaryauthorizationAlphaPolicyIstioServiceIdentityAdmissionRules) *alpha.PolicyIstioServiceIdentityAdmissionRules {
	if p == nil {
		return nil
	}
	obj := &alpha.PolicyIstioServiceIdentityAdmissionRules{
		EvaluationMode:  ProtoToBinaryauthorizationAlphaPolicyIstioServiceIdentityAdmissionRulesEvaluationModeEnum(p.GetEvaluationMode()),
		EnforcementMode: ProtoToBinaryauthorizationAlphaPolicyIstioServiceIdentityAdmissionRulesEnforcementModeEnum(p.GetEnforcementMode()),
	}
	for _, r := range p.GetRequireAttestationsBy() {
		obj.RequireAttestationsBy = append(obj.RequireAttestationsBy, r)
	}
	return obj
}

// ProtoToPolicyDefaultAdmissionRule converts a PolicyDefaultAdmissionRule object from its proto representation.
func ProtoToBinaryauthorizationAlphaPolicyDefaultAdmissionRule(p *alphapb.BinaryauthorizationAlphaPolicyDefaultAdmissionRule) *alpha.PolicyDefaultAdmissionRule {
	if p == nil {
		return nil
	}
	obj := &alpha.PolicyDefaultAdmissionRule{
		EvaluationMode:  ProtoToBinaryauthorizationAlphaPolicyDefaultAdmissionRuleEvaluationModeEnum(p.GetEvaluationMode()),
		EnforcementMode: ProtoToBinaryauthorizationAlphaPolicyDefaultAdmissionRuleEnforcementModeEnum(p.GetEnforcementMode()),
	}
	for _, r := range p.GetRequireAttestationsBy() {
		obj.RequireAttestationsBy = append(obj.RequireAttestationsBy, r)
	}
	return obj
}

// ProtoToPolicy converts a Policy resource from its proto representation.
func ProtoToPolicy(p *alphapb.BinaryauthorizationAlphaPolicy) *alpha.Policy {
	obj := &alpha.Policy{
		DefaultAdmissionRule:       ProtoToBinaryauthorizationAlphaPolicyDefaultAdmissionRule(p.GetDefaultAdmissionRule()),
		Description:                dcl.StringOrNil(p.GetDescription()),
		GlobalPolicyEvaluationMode: ProtoToBinaryauthorizationAlphaPolicyGlobalPolicyEvaluationModeEnum(p.GetGlobalPolicyEvaluationMode()),
		SelfLink:                   dcl.StringOrNil(p.GetSelfLink()),
		Project:                    dcl.StringOrNil(p.GetProject()),
		UpdateTime:                 dcl.StringOrNil(p.GetUpdateTime()),
	}
	for _, r := range p.GetAdmissionWhitelistPatterns() {
		obj.AdmissionWhitelistPatterns = append(obj.AdmissionWhitelistPatterns, *ProtoToBinaryauthorizationAlphaPolicyAdmissionWhitelistPatterns(r))
	}
	return obj
}

// PolicyClusterAdmissionRulesEvaluationModeEnumToProto converts a PolicyClusterAdmissionRulesEvaluationModeEnum enum to its proto representation.
func BinaryauthorizationAlphaPolicyClusterAdmissionRulesEvaluationModeEnumToProto(e *alpha.PolicyClusterAdmissionRulesEvaluationModeEnum) alphapb.BinaryauthorizationAlphaPolicyClusterAdmissionRulesEvaluationModeEnum {
	if e == nil {
		return alphapb.BinaryauthorizationAlphaPolicyClusterAdmissionRulesEvaluationModeEnum(0)
	}
	if v, ok := alphapb.BinaryauthorizationAlphaPolicyClusterAdmissionRulesEvaluationModeEnum_value["PolicyClusterAdmissionRulesEvaluationModeEnum"+string(*e)]; ok {
		return alphapb.BinaryauthorizationAlphaPolicyClusterAdmissionRulesEvaluationModeEnum(v)
	}
	return alphapb.BinaryauthorizationAlphaPolicyClusterAdmissionRulesEvaluationModeEnum(0)
}

// PolicyClusterAdmissionRulesEnforcementModeEnumToProto converts a PolicyClusterAdmissionRulesEnforcementModeEnum enum to its proto representation.
func BinaryauthorizationAlphaPolicyClusterAdmissionRulesEnforcementModeEnumToProto(e *alpha.PolicyClusterAdmissionRulesEnforcementModeEnum) alphapb.BinaryauthorizationAlphaPolicyClusterAdmissionRulesEnforcementModeEnum {
	if e == nil {
		return alphapb.BinaryauthorizationAlphaPolicyClusterAdmissionRulesEnforcementModeEnum(0)
	}
	if v, ok := alphapb.BinaryauthorizationAlphaPolicyClusterAdmissionRulesEnforcementModeEnum_value["PolicyClusterAdmissionRulesEnforcementModeEnum"+string(*e)]; ok {
		return alphapb.BinaryauthorizationAlphaPolicyClusterAdmissionRulesEnforcementModeEnum(v)
	}
	return alphapb.BinaryauthorizationAlphaPolicyClusterAdmissionRulesEnforcementModeEnum(0)
}

// PolicyKubernetesNamespaceAdmissionRulesEvaluationModeEnumToProto converts a PolicyKubernetesNamespaceAdmissionRulesEvaluationModeEnum enum to its proto representation.
func BinaryauthorizationAlphaPolicyKubernetesNamespaceAdmissionRulesEvaluationModeEnumToProto(e *alpha.PolicyKubernetesNamespaceAdmissionRulesEvaluationModeEnum) alphapb.BinaryauthorizationAlphaPolicyKubernetesNamespaceAdmissionRulesEvaluationModeEnum {
	if e == nil {
		return alphapb.BinaryauthorizationAlphaPolicyKubernetesNamespaceAdmissionRulesEvaluationModeEnum(0)
	}
	if v, ok := alphapb.BinaryauthorizationAlphaPolicyKubernetesNamespaceAdmissionRulesEvaluationModeEnum_value["PolicyKubernetesNamespaceAdmissionRulesEvaluationModeEnum"+string(*e)]; ok {
		return alphapb.BinaryauthorizationAlphaPolicyKubernetesNamespaceAdmissionRulesEvaluationModeEnum(v)
	}
	return alphapb.BinaryauthorizationAlphaPolicyKubernetesNamespaceAdmissionRulesEvaluationModeEnum(0)
}

// PolicyKubernetesNamespaceAdmissionRulesEnforcementModeEnumToProto converts a PolicyKubernetesNamespaceAdmissionRulesEnforcementModeEnum enum to its proto representation.
func BinaryauthorizationAlphaPolicyKubernetesNamespaceAdmissionRulesEnforcementModeEnumToProto(e *alpha.PolicyKubernetesNamespaceAdmissionRulesEnforcementModeEnum) alphapb.BinaryauthorizationAlphaPolicyKubernetesNamespaceAdmissionRulesEnforcementModeEnum {
	if e == nil {
		return alphapb.BinaryauthorizationAlphaPolicyKubernetesNamespaceAdmissionRulesEnforcementModeEnum(0)
	}
	if v, ok := alphapb.BinaryauthorizationAlphaPolicyKubernetesNamespaceAdmissionRulesEnforcementModeEnum_value["PolicyKubernetesNamespaceAdmissionRulesEnforcementModeEnum"+string(*e)]; ok {
		return alphapb.BinaryauthorizationAlphaPolicyKubernetesNamespaceAdmissionRulesEnforcementModeEnum(v)
	}
	return alphapb.BinaryauthorizationAlphaPolicyKubernetesNamespaceAdmissionRulesEnforcementModeEnum(0)
}

// PolicyKubernetesServiceAccountAdmissionRulesEvaluationModeEnumToProto converts a PolicyKubernetesServiceAccountAdmissionRulesEvaluationModeEnum enum to its proto representation.
func BinaryauthorizationAlphaPolicyKubernetesServiceAccountAdmissionRulesEvaluationModeEnumToProto(e *alpha.PolicyKubernetesServiceAccountAdmissionRulesEvaluationModeEnum) alphapb.BinaryauthorizationAlphaPolicyKubernetesServiceAccountAdmissionRulesEvaluationModeEnum {
	if e == nil {
		return alphapb.BinaryauthorizationAlphaPolicyKubernetesServiceAccountAdmissionRulesEvaluationModeEnum(0)
	}
	if v, ok := alphapb.BinaryauthorizationAlphaPolicyKubernetesServiceAccountAdmissionRulesEvaluationModeEnum_value["PolicyKubernetesServiceAccountAdmissionRulesEvaluationModeEnum"+string(*e)]; ok {
		return alphapb.BinaryauthorizationAlphaPolicyKubernetesServiceAccountAdmissionRulesEvaluationModeEnum(v)
	}
	return alphapb.BinaryauthorizationAlphaPolicyKubernetesServiceAccountAdmissionRulesEvaluationModeEnum(0)
}

// PolicyKubernetesServiceAccountAdmissionRulesEnforcementModeEnumToProto converts a PolicyKubernetesServiceAccountAdmissionRulesEnforcementModeEnum enum to its proto representation.
func BinaryauthorizationAlphaPolicyKubernetesServiceAccountAdmissionRulesEnforcementModeEnumToProto(e *alpha.PolicyKubernetesServiceAccountAdmissionRulesEnforcementModeEnum) alphapb.BinaryauthorizationAlphaPolicyKubernetesServiceAccountAdmissionRulesEnforcementModeEnum {
	if e == nil {
		return alphapb.BinaryauthorizationAlphaPolicyKubernetesServiceAccountAdmissionRulesEnforcementModeEnum(0)
	}
	if v, ok := alphapb.BinaryauthorizationAlphaPolicyKubernetesServiceAccountAdmissionRulesEnforcementModeEnum_value["PolicyKubernetesServiceAccountAdmissionRulesEnforcementModeEnum"+string(*e)]; ok {
		return alphapb.BinaryauthorizationAlphaPolicyKubernetesServiceAccountAdmissionRulesEnforcementModeEnum(v)
	}
	return alphapb.BinaryauthorizationAlphaPolicyKubernetesServiceAccountAdmissionRulesEnforcementModeEnum(0)
}

// PolicyIstioServiceIdentityAdmissionRulesEvaluationModeEnumToProto converts a PolicyIstioServiceIdentityAdmissionRulesEvaluationModeEnum enum to its proto representation.
func BinaryauthorizationAlphaPolicyIstioServiceIdentityAdmissionRulesEvaluationModeEnumToProto(e *alpha.PolicyIstioServiceIdentityAdmissionRulesEvaluationModeEnum) alphapb.BinaryauthorizationAlphaPolicyIstioServiceIdentityAdmissionRulesEvaluationModeEnum {
	if e == nil {
		return alphapb.BinaryauthorizationAlphaPolicyIstioServiceIdentityAdmissionRulesEvaluationModeEnum(0)
	}
	if v, ok := alphapb.BinaryauthorizationAlphaPolicyIstioServiceIdentityAdmissionRulesEvaluationModeEnum_value["PolicyIstioServiceIdentityAdmissionRulesEvaluationModeEnum"+string(*e)]; ok {
		return alphapb.BinaryauthorizationAlphaPolicyIstioServiceIdentityAdmissionRulesEvaluationModeEnum(v)
	}
	return alphapb.BinaryauthorizationAlphaPolicyIstioServiceIdentityAdmissionRulesEvaluationModeEnum(0)
}

// PolicyIstioServiceIdentityAdmissionRulesEnforcementModeEnumToProto converts a PolicyIstioServiceIdentityAdmissionRulesEnforcementModeEnum enum to its proto representation.
func BinaryauthorizationAlphaPolicyIstioServiceIdentityAdmissionRulesEnforcementModeEnumToProto(e *alpha.PolicyIstioServiceIdentityAdmissionRulesEnforcementModeEnum) alphapb.BinaryauthorizationAlphaPolicyIstioServiceIdentityAdmissionRulesEnforcementModeEnum {
	if e == nil {
		return alphapb.BinaryauthorizationAlphaPolicyIstioServiceIdentityAdmissionRulesEnforcementModeEnum(0)
	}
	if v, ok := alphapb.BinaryauthorizationAlphaPolicyIstioServiceIdentityAdmissionRulesEnforcementModeEnum_value["PolicyIstioServiceIdentityAdmissionRulesEnforcementModeEnum"+string(*e)]; ok {
		return alphapb.BinaryauthorizationAlphaPolicyIstioServiceIdentityAdmissionRulesEnforcementModeEnum(v)
	}
	return alphapb.BinaryauthorizationAlphaPolicyIstioServiceIdentityAdmissionRulesEnforcementModeEnum(0)
}

// PolicyDefaultAdmissionRuleEvaluationModeEnumToProto converts a PolicyDefaultAdmissionRuleEvaluationModeEnum enum to its proto representation.
func BinaryauthorizationAlphaPolicyDefaultAdmissionRuleEvaluationModeEnumToProto(e *alpha.PolicyDefaultAdmissionRuleEvaluationModeEnum) alphapb.BinaryauthorizationAlphaPolicyDefaultAdmissionRuleEvaluationModeEnum {
	if e == nil {
		return alphapb.BinaryauthorizationAlphaPolicyDefaultAdmissionRuleEvaluationModeEnum(0)
	}
	if v, ok := alphapb.BinaryauthorizationAlphaPolicyDefaultAdmissionRuleEvaluationModeEnum_value["PolicyDefaultAdmissionRuleEvaluationModeEnum"+string(*e)]; ok {
		return alphapb.BinaryauthorizationAlphaPolicyDefaultAdmissionRuleEvaluationModeEnum(v)
	}
	return alphapb.BinaryauthorizationAlphaPolicyDefaultAdmissionRuleEvaluationModeEnum(0)
}

// PolicyDefaultAdmissionRuleEnforcementModeEnumToProto converts a PolicyDefaultAdmissionRuleEnforcementModeEnum enum to its proto representation.
func BinaryauthorizationAlphaPolicyDefaultAdmissionRuleEnforcementModeEnumToProto(e *alpha.PolicyDefaultAdmissionRuleEnforcementModeEnum) alphapb.BinaryauthorizationAlphaPolicyDefaultAdmissionRuleEnforcementModeEnum {
	if e == nil {
		return alphapb.BinaryauthorizationAlphaPolicyDefaultAdmissionRuleEnforcementModeEnum(0)
	}
	if v, ok := alphapb.BinaryauthorizationAlphaPolicyDefaultAdmissionRuleEnforcementModeEnum_value["PolicyDefaultAdmissionRuleEnforcementModeEnum"+string(*e)]; ok {
		return alphapb.BinaryauthorizationAlphaPolicyDefaultAdmissionRuleEnforcementModeEnum(v)
	}
	return alphapb.BinaryauthorizationAlphaPolicyDefaultAdmissionRuleEnforcementModeEnum(0)
}

// PolicyGlobalPolicyEvaluationModeEnumToProto converts a PolicyGlobalPolicyEvaluationModeEnum enum to its proto representation.
func BinaryauthorizationAlphaPolicyGlobalPolicyEvaluationModeEnumToProto(e *alpha.PolicyGlobalPolicyEvaluationModeEnum) alphapb.BinaryauthorizationAlphaPolicyGlobalPolicyEvaluationModeEnum {
	if e == nil {
		return alphapb.BinaryauthorizationAlphaPolicyGlobalPolicyEvaluationModeEnum(0)
	}
	if v, ok := alphapb.BinaryauthorizationAlphaPolicyGlobalPolicyEvaluationModeEnum_value["PolicyGlobalPolicyEvaluationModeEnum"+string(*e)]; ok {
		return alphapb.BinaryauthorizationAlphaPolicyGlobalPolicyEvaluationModeEnum(v)
	}
	return alphapb.BinaryauthorizationAlphaPolicyGlobalPolicyEvaluationModeEnum(0)
}

// PolicyAdmissionWhitelistPatternsToProto converts a PolicyAdmissionWhitelistPatterns object to its proto representation.
func BinaryauthorizationAlphaPolicyAdmissionWhitelistPatternsToProto(o *alpha.PolicyAdmissionWhitelistPatterns) *alphapb.BinaryauthorizationAlphaPolicyAdmissionWhitelistPatterns {
	if o == nil {
		return nil
	}
	p := &alphapb.BinaryauthorizationAlphaPolicyAdmissionWhitelistPatterns{}
	p.SetNamePattern(dcl.ValueOrEmptyString(o.NamePattern))
	return p
}

// PolicyClusterAdmissionRulesToProto converts a PolicyClusterAdmissionRules object to its proto representation.
func BinaryauthorizationAlphaPolicyClusterAdmissionRulesToProto(o *alpha.PolicyClusterAdmissionRules) *alphapb.BinaryauthorizationAlphaPolicyClusterAdmissionRules {
	if o == nil {
		return nil
	}
	p := &alphapb.BinaryauthorizationAlphaPolicyClusterAdmissionRules{}
	p.SetEvaluationMode(BinaryauthorizationAlphaPolicyClusterAdmissionRulesEvaluationModeEnumToProto(o.EvaluationMode))
	p.SetEnforcementMode(BinaryauthorizationAlphaPolicyClusterAdmissionRulesEnforcementModeEnumToProto(o.EnforcementMode))
	sRequireAttestationsBy := make([]string, len(o.RequireAttestationsBy))
	for i, r := range o.RequireAttestationsBy {
		sRequireAttestationsBy[i] = r
	}
	p.SetRequireAttestationsBy(sRequireAttestationsBy)
	return p
}

// PolicyKubernetesNamespaceAdmissionRulesToProto converts a PolicyKubernetesNamespaceAdmissionRules object to its proto representation.
func BinaryauthorizationAlphaPolicyKubernetesNamespaceAdmissionRulesToProto(o *alpha.PolicyKubernetesNamespaceAdmissionRules) *alphapb.BinaryauthorizationAlphaPolicyKubernetesNamespaceAdmissionRules {
	if o == nil {
		return nil
	}
	p := &alphapb.BinaryauthorizationAlphaPolicyKubernetesNamespaceAdmissionRules{}
	p.SetEvaluationMode(BinaryauthorizationAlphaPolicyKubernetesNamespaceAdmissionRulesEvaluationModeEnumToProto(o.EvaluationMode))
	p.SetEnforcementMode(BinaryauthorizationAlphaPolicyKubernetesNamespaceAdmissionRulesEnforcementModeEnumToProto(o.EnforcementMode))
	sRequireAttestationsBy := make([]string, len(o.RequireAttestationsBy))
	for i, r := range o.RequireAttestationsBy {
		sRequireAttestationsBy[i] = r
	}
	p.SetRequireAttestationsBy(sRequireAttestationsBy)
	return p
}

// PolicyKubernetesServiceAccountAdmissionRulesToProto converts a PolicyKubernetesServiceAccountAdmissionRules object to its proto representation.
func BinaryauthorizationAlphaPolicyKubernetesServiceAccountAdmissionRulesToProto(o *alpha.PolicyKubernetesServiceAccountAdmissionRules) *alphapb.BinaryauthorizationAlphaPolicyKubernetesServiceAccountAdmissionRules {
	if o == nil {
		return nil
	}
	p := &alphapb.BinaryauthorizationAlphaPolicyKubernetesServiceAccountAdmissionRules{}
	p.SetEvaluationMode(BinaryauthorizationAlphaPolicyKubernetesServiceAccountAdmissionRulesEvaluationModeEnumToProto(o.EvaluationMode))
	p.SetEnforcementMode(BinaryauthorizationAlphaPolicyKubernetesServiceAccountAdmissionRulesEnforcementModeEnumToProto(o.EnforcementMode))
	sRequireAttestationsBy := make([]string, len(o.RequireAttestationsBy))
	for i, r := range o.RequireAttestationsBy {
		sRequireAttestationsBy[i] = r
	}
	p.SetRequireAttestationsBy(sRequireAttestationsBy)
	return p
}

// PolicyIstioServiceIdentityAdmissionRulesToProto converts a PolicyIstioServiceIdentityAdmissionRules object to its proto representation.
func BinaryauthorizationAlphaPolicyIstioServiceIdentityAdmissionRulesToProto(o *alpha.PolicyIstioServiceIdentityAdmissionRules) *alphapb.BinaryauthorizationAlphaPolicyIstioServiceIdentityAdmissionRules {
	if o == nil {
		return nil
	}
	p := &alphapb.BinaryauthorizationAlphaPolicyIstioServiceIdentityAdmissionRules{}
	p.SetEvaluationMode(BinaryauthorizationAlphaPolicyIstioServiceIdentityAdmissionRulesEvaluationModeEnumToProto(o.EvaluationMode))
	p.SetEnforcementMode(BinaryauthorizationAlphaPolicyIstioServiceIdentityAdmissionRulesEnforcementModeEnumToProto(o.EnforcementMode))
	sRequireAttestationsBy := make([]string, len(o.RequireAttestationsBy))
	for i, r := range o.RequireAttestationsBy {
		sRequireAttestationsBy[i] = r
	}
	p.SetRequireAttestationsBy(sRequireAttestationsBy)
	return p
}

// PolicyDefaultAdmissionRuleToProto converts a PolicyDefaultAdmissionRule object to its proto representation.
func BinaryauthorizationAlphaPolicyDefaultAdmissionRuleToProto(o *alpha.PolicyDefaultAdmissionRule) *alphapb.BinaryauthorizationAlphaPolicyDefaultAdmissionRule {
	if o == nil {
		return nil
	}
	p := &alphapb.BinaryauthorizationAlphaPolicyDefaultAdmissionRule{}
	p.SetEvaluationMode(BinaryauthorizationAlphaPolicyDefaultAdmissionRuleEvaluationModeEnumToProto(o.EvaluationMode))
	p.SetEnforcementMode(BinaryauthorizationAlphaPolicyDefaultAdmissionRuleEnforcementModeEnumToProto(o.EnforcementMode))
	sRequireAttestationsBy := make([]string, len(o.RequireAttestationsBy))
	for i, r := range o.RequireAttestationsBy {
		sRequireAttestationsBy[i] = r
	}
	p.SetRequireAttestationsBy(sRequireAttestationsBy)
	return p
}

// PolicyToProto converts a Policy resource to its proto representation.
func PolicyToProto(resource *alpha.Policy) *alphapb.BinaryauthorizationAlphaPolicy {
	p := &alphapb.BinaryauthorizationAlphaPolicy{}
	p.SetDefaultAdmissionRule(BinaryauthorizationAlphaPolicyDefaultAdmissionRuleToProto(resource.DefaultAdmissionRule))
	p.SetDescription(dcl.ValueOrEmptyString(resource.Description))
	p.SetGlobalPolicyEvaluationMode(BinaryauthorizationAlphaPolicyGlobalPolicyEvaluationModeEnumToProto(resource.GlobalPolicyEvaluationMode))
	p.SetSelfLink(dcl.ValueOrEmptyString(resource.SelfLink))
	p.SetProject(dcl.ValueOrEmptyString(resource.Project))
	p.SetUpdateTime(dcl.ValueOrEmptyString(resource.UpdateTime))
	sAdmissionWhitelistPatterns := make([]*alphapb.BinaryauthorizationAlphaPolicyAdmissionWhitelistPatterns, len(resource.AdmissionWhitelistPatterns))
	for i, r := range resource.AdmissionWhitelistPatterns {
		sAdmissionWhitelistPatterns[i] = BinaryauthorizationAlphaPolicyAdmissionWhitelistPatternsToProto(&r)
	}
	p.SetAdmissionWhitelistPatterns(sAdmissionWhitelistPatterns)
	mClusterAdmissionRules := make(map[string]*alphapb.BinaryauthorizationAlphaPolicyClusterAdmissionRules, len(resource.ClusterAdmissionRules))
	for k, r := range resource.ClusterAdmissionRules {
		mClusterAdmissionRules[k] = BinaryauthorizationAlphaPolicyClusterAdmissionRulesToProto(&r)
	}
	p.SetClusterAdmissionRules(mClusterAdmissionRules)
	mKubernetesNamespaceAdmissionRules := make(map[string]*alphapb.BinaryauthorizationAlphaPolicyKubernetesNamespaceAdmissionRules, len(resource.KubernetesNamespaceAdmissionRules))
	for k, r := range resource.KubernetesNamespaceAdmissionRules {
		mKubernetesNamespaceAdmissionRules[k] = BinaryauthorizationAlphaPolicyKubernetesNamespaceAdmissionRulesToProto(&r)
	}
	p.SetKubernetesNamespaceAdmissionRules(mKubernetesNamespaceAdmissionRules)
	mKubernetesServiceAccountAdmissionRules := make(map[string]*alphapb.BinaryauthorizationAlphaPolicyKubernetesServiceAccountAdmissionRules, len(resource.KubernetesServiceAccountAdmissionRules))
	for k, r := range resource.KubernetesServiceAccountAdmissionRules {
		mKubernetesServiceAccountAdmissionRules[k] = BinaryauthorizationAlphaPolicyKubernetesServiceAccountAdmissionRulesToProto(&r)
	}
	p.SetKubernetesServiceAccountAdmissionRules(mKubernetesServiceAccountAdmissionRules)
	mIstioServiceIdentityAdmissionRules := make(map[string]*alphapb.BinaryauthorizationAlphaPolicyIstioServiceIdentityAdmissionRules, len(resource.IstioServiceIdentityAdmissionRules))
	for k, r := range resource.IstioServiceIdentityAdmissionRules {
		mIstioServiceIdentityAdmissionRules[k] = BinaryauthorizationAlphaPolicyIstioServiceIdentityAdmissionRulesToProto(&r)
	}
	p.SetIstioServiceIdentityAdmissionRules(mIstioServiceIdentityAdmissionRules)

	return p
}

// applyPolicy handles the gRPC request by passing it to the underlying Policy Apply() method.
func (s *PolicyServer) applyPolicy(ctx context.Context, c *alpha.Client, request *alphapb.ApplyBinaryauthorizationAlphaPolicyRequest) (*alphapb.BinaryauthorizationAlphaPolicy, error) {
	p := ProtoToPolicy(request.GetResource())
	res, err := c.ApplyPolicy(ctx, p)
	if err != nil {
		return nil, err
	}
	r := PolicyToProto(res)
	return r, nil
}

// applyBinaryauthorizationAlphaPolicy handles the gRPC request by passing it to the underlying Policy Apply() method.
func (s *PolicyServer) ApplyBinaryauthorizationAlphaPolicy(ctx context.Context, request *alphapb.ApplyBinaryauthorizationAlphaPolicyRequest) (*alphapb.BinaryauthorizationAlphaPolicy, error) {
	cl, err := createConfigPolicy(ctx, request.GetServiceAccountFile())
	if err != nil {
		return nil, err
	}
	return s.applyPolicy(ctx, cl, request)
}

// DeletePolicy handles the gRPC request by passing it to the underlying Policy Delete() method.
func (s *PolicyServer) DeleteBinaryauthorizationAlphaPolicy(ctx context.Context, request *alphapb.DeleteBinaryauthorizationAlphaPolicyRequest) (*emptypb.Empty, error) {

	return nil, errors.New("no delete endpoint for Policy")

}

// ListBinaryauthorizationAlphaPolicy is a no-op method because Policy has no list method.
func (s *PolicyServer) ListBinaryauthorizationAlphaPolicy(_ context.Context, _ *alphapb.ListBinaryauthorizationAlphaPolicyRequest) (*alphapb.ListBinaryauthorizationAlphaPolicyResponse, error) {
	return nil, nil
}

func createConfigPolicy(ctx context.Context, service_account_file string) (*alpha.Client, error) {

	conf := dcl.NewConfig(dcl.WithUserAgent("dcl-test"), dcl.WithCredentialsFile(service_account_file))
	return alpha.NewClient(conf), nil
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Messaging;
using MahApps.Metro.Controls.Dialogs;
using UFO.Commander.Views;

namespace UFO.Commander.Messages
{
    public class HideDialogMessage : MessageBase
    {
        public ViewModelBase ViewModel { get; set; }

        public HideDialogMessage(ViewModelBase viewModel)
        {
            ViewModel = viewModel;
        }
    }
}


text:
from yowsup.layers import YowLayer, YowLayerEvent, YowProtocolLayer
from .protocolentities import *
class YowIbProtocolLayer(YowProtocolLayer):

    def __init__(self):
        handleMap = {
            "ib": (self.recvIb, self.sendIb),
            "iq": (None, self.sendIb)
        }
        super(YowIbProtocolLayer, self).__init__(handleMap)

    def __str__(self):
        return "Ib Layer"

    def sendIb(self, entity):
        if entity.__class__ == CleanIqProtocolEntity:
            self.toLower(entity.toProtocolTreeNode())

    def recvIb(self, node):
        if node.getChild("dirty"):
            self.toUpper(DirtyIbProtocolEntity.fromProtocolTreeNode(node))
        elif node.getChild("offline"):
            self.toUpper(OfflineIbProtocolEntity.fromProtocolTreeNode(node))
        elif node.getChild("account"):
            self.toUpper(AccountIbProtocolEntity.fromProtocolTreeNode(node))
        else:
            raise ValueError("Unkown ib node %s" % node)