text:
#include "InfoKernel.hpp"

#include <algorithm>

#include <pdal/KDIndex.hpp>
#include <pdal/PipelineWriter.hpp>
#include <pdal/PDALUtils.hpp>
#include <pdal/pdal_config.hpp>
#ifdef PDAL_HAVE_LIBXML2
#include <pdal/XMLSchema.hpp>
#endif

#include <boost/program_options.hpp>

namespace pdal
{

static PluginInfo const s_info = PluginInfo(
    "kernels.info",
    "Info Kernel",
    "http://pdal.io/kernels/kernels.info.html" );

CREATE_STATIC_PLUGIN(1, 0, InfoKernel, Kernel, s_info)

std::string InfoKernel::getName() const { return s_info.name; }

InfoKernel::InfoKernel()
    : m_showStats(false)
    , m_showSchema(false)
    , m_showAll(false)
    , m_showMetadata(false)
    , m_boundary(false)
    , m_showSummary(false)
    , m_needPoints(false)
    , m_statsStage(NULL)
{}

void InfoKernel::validateSwitches()
{
    int functions = 0;

    if (!m_usestdin && m_inputFile.empty())
        throw pdal_error("No input file specified.");

    // All isn't really all.
    if (m_showAll)
    {
        m_showStats = true;
        m_showMetadata = true;
        m_showSchema = true;
    }

    if (m_boundary)
    {
        functions++;
        m_needPoints = true;
    }
    if (m_queryPoint.size())
    {
        functions++;
        m_needPoints = true;
    }
    if (m_pointIndexes.size())
    {
        functions++;
        m_needPoints = true;
    }
    if (m_showSchema)
        functions++;
    if (m_showMetadata)
        functions++;
    if (m_showSummary)
        functions++;
    if (m_showStats || functions == 0 )
    {
        functions++;
        m_showStats = true;
        m_needPoints = true;
    }

    if (m_pointIndexes.size() && m_queryPoint.size())
        throw pdal_error("--point option incompatible with --query option.");

    if (m_showSummary && functions > 1)
        throw pdal_error("--summary option incompatible with other "
            "specified options.");
}

void InfoKernel::addSwitches()
{
    namespace po = boost::program_options;

    po::options_description* file_options =
        new po::options_description("file options");

    file_options->add_options()
        ("input,i", po::value<std::string>(&m_inputFile)->default_value(""),
         "input file name")
        ;

    addSwitchSet(file_options);

    po::options_description* processing_options =
        new po::options_description("processing options");

    processing_options->add_options()
        ("all",
         po::value<bool>(&m_showAll)->zero_tokens()->implicit_value(true),
         "dump statistics, schema and metadata")
        ("point,p", po::value<std::string >(&m_pointIndexes), "point to dump")
        ("query", po::value< std::string>(&m_queryPoint),
         "Return points in order of distance from the specified "
         "location (2D or 3D)\n"
         "--query Xcoord,Ycoord[,Zcoord][/count]")
        ("stats",
         po::value<bool>(&m_showStats)->zero_tokens()->implicit_value(true),
         "dump stats on all points (reads entire dataset)")
        ("boundary",
         po::value<bool>(&m_boundary)->zero_tokens()->implicit_value(true),
         "compute a hexagonal hull/boundary of dataset")
        ("dimensions", po::value<std::string >(&m_dimensions),
         "dimensions on which to compute statistics")
        ("schema",
         po::value<bool>(&m_showSchema)->zero_tokens()->implicit_value(true),
         "dump the schema")
        ("pipeline-serialization",
         po::value<std::string>(&m_pipelineFile)->default_value(""), "")
        ("summary",
         po::value<bool>(&m_showSummary)->zero_tokens()->implicit_value(true),
        "dump summary of the info")
        ("metadata",
         po::value<bool>(&m_showMetadata)->zero_tokens()->implicit_value(true),
        "dump file metadata info")
        ;

    po::options_description* hidden =
        new po::options_description("Hidden options");
    hidden->add_options()
        ("pointcloudschema",
         po::value<std::string>(&m_PointCloudSchemaOutput),
        "dump PointCloudSchema XML output")
            ;

    addSwitchSet(processing_options);
    addHiddenSwitchSet(hidden);
    addPositionalSwitch("input", 1);
}

// Support for parsing point numbers.  Points can be specified singly or as
// dash-separated ranges.  i.e. 6-7,8,19-20
namespace {

using namespace std;

uint32_t parseInt(const string& s)
{
    try
    {
        return boost::lexical_cast<uint32_t>(s);
    }
    catch (boost::bad_lexical_cast)
    {
        throw app_runtime_error(string("Invalid integer: ") + s);
    }
}

void addRange(const string& begin, const string& end, vector<PointId>& points)
{
    PointId low = parseInt(begin);
    PointId high = parseInt(end);
    if (low > high)
        throw app_runtime_error(string("Range invalid: ") + begin + "-" + end);
    while (low <= high)
        points.push_back(low++);
}

vector<PointId> getListOfPoints(std::string p)
{
    vector<PointId> output;

    //Remove whitespace from string with awful remove/erase idiom.
    p.erase(remove_if(p.begin(), p.end(), ::isspace), p.end());

    vector<string> ranges = Utils::split2(p, ',');
    for (string s : ranges)
    {
        vector<string> limits = Utils::split(s, '-');
        if (limits.size() == 1)
            output.push_back(parseInt(limits[0]));
        else if (limits.size() == 2)
            addRange(limits[0], limits[1], output);
        else
            throw app_runtime_error(string("Invalid point range: ") + s);
    }
    return output;
}

} //namespace

MetadataNode InfoKernel::dumpPoints(PointViewPtr inView) const
{
    MetadataNode root;
    PointViewPtr outView = inView->makeNew();

    // Stick points in a inViewfer.
    std::vector<PointId> points = getListOfPoints(m_pointIndexes);
    for (size_t i = 0; i < points.size(); ++i)
    {
        PointId id = (PointId)points[i];
        if (id < inView->size())
            outView->appendPoint(*inView.get(), id);
    }

    MetadataNode tree = Utils::toMetadata(outView);
    std::string prefix("point ");
    for (size_t i = 0; i < outView->size(); ++i)
    {
        MetadataNode n = tree.findChild(std::to_string(i));
        n.add("PointId", points[i]);
        root.add(n.clone("point"));
    }
    return root;
}

MetadataNode InfoKernel::dumpSummary(const QuickInfo& qi)
{
    MetadataNode summary;
    summary.add("num_points", qi.m_pointCount);
    summary.add("spatial_reference", qi.m_srs.getWKT());
    MetadataNode bounds = summary.add("bounds");
    MetadataNode x = bounds.add("X");
    x.add("min", qi.m_bounds.minx);
    x.add("max", qi.m_bounds.maxx);
    MetadataNode y = bounds.add("Y");
    y.add("min", qi.m_bounds.miny);
    y.add("max", qi.m_bounds.maxy);
    MetadataNode z = bounds.add("Z");
    z.add("min", qi.m_bounds.minz);
    z.add("max", qi.m_bounds.maxz);

    std::string dims;
    auto di = qi.m_dimNames.begin();
    while (di != qi.m_dimNames.end())
    {
        dims += *di;
        ++di;
        if (di != qi.m_dimNames.end())
           dims += ", ";
    }
    summary.add("dimensions", dims);
    return summary;
}

void InfoKernel::setup(const std::string& filename)
{
    Options readerOptions;

    readerOptions.add("filename", filename);
    if (!m_needPoints)
        readerOptions.add("count", 0);

    m_manager = KernelSupport::makePipeline(filename);
    m_reader = m_manager->getStage();
    Stage *stage = m_reader;

    if (m_dimensions.size())
        m_options.add("dimensions", m_dimensions, "List of dimensions");

    Options options = m_options + readerOptions;
    m_reader->setOptions(options);

    if (m_showStats)
    {
        m_statsStage = &(m_manager->addFilter("filters.stats"));
        m_statsStage->setOptions(options);
        m_statsStage->setInput(*stage);
        stage = m_statsStage;
    }
    if (m_boundary)
    {
        m_hexbinStage = &(m_manager->addFilter("filters.hexbin"));
        m_hexbinStage->setOptions(options);
        m_hexbinStage->setInput(*stage);
        stage = m_hexbinStage;
        Options readerOptions;
    }
}

MetadataNode InfoKernel::run(const std::string& filename)
{
    MetadataNode root;

    root.add("filename", filename);
    if (m_showSummary)
    {
        QuickInfo qi = m_reader->preview();
        MetadataNode summary = dumpSummary(qi).clone("summary");
        root.add(summary);
    }
    else
    {
        applyExtraStageOptionsRecursive(m_manager->getStage());
        if (m_needPoints || m_showMetadata)
            m_manager->execute();
        else
            m_manager->prepare();
        dump(root);
    }
    root.add("pdal_version", pdal::GetFullVersionString());
    return root;
}

void InfoKernel::dump(MetadataNode& root)
{
    if (m_showSchema)
        root.add(Utils::toMetadata(m_manager->pointTable()).clone("schema"));

    if (m_PointCloudSchemaOutput.size() > 0)
    {
#ifdef PDAL_HAVE_LIBXML2
        XMLSchema schema(m_manager->pointTable().layout());

        std::ostream *out = FileUtils::createFile(m_PointCloudSchemaOutput);
        std::string xml(schema.xml());
        out->write(xml.c_str(), xml.size());
        FileUtils::closeFile(out);
#else
        std::cerr << "libxml2 support not enabled, no schema is produced" <<
            std::endl;
#endif

    }
    if (m_showStats)
        root.add(m_statsStage->getMetadata().clone("stats"));

    if (m_pipelineFile.size() > 0)
        PipelineWriter(*m_manager).writePipeline(m_pipelineFile);

    if (m_pointIndexes.size())
    {
        PointViewSet viewSet = m_manager->views();
        assert(viewSet.size() == 1);
        root.add(dumpPoints(*viewSet.begin()).clone("points"));
    }
    if (m_queryPoint.size())
    {
        PointViewSet viewSet = m_manager->views();
        assert(viewSet.size() == 1);
        root.add(dumpQuery(*viewSet.begin()));
    }
    if (m_showMetadata)
        root.add(m_reader->getMetadata().clone("metadata"));
    if (m_boundary)
    {
        PointViewSet viewSet = m_manager->views();
        assert(viewSet.size() == 1);
        root.add(m_hexbinStage->getMetadata().clone("boundary"));
    }
}

MetadataNode InfoKernel::dumpQuery(PointViewPtr inView) const
{
    int count;
    std::string location;

    // See if there's a provided point count.
    StringList parts = Utils::split2(m_queryPoint, '/');
    if (parts.size() == 2)
    {
        location = parts[0];
        count = atoi(parts[1].c_str());
    }
    else if (parts.size() == 1)
    {
        location = parts[0];
        count = inView->size();
    }
    else
        count = 0;
    if (count == 0)
        throw pdal_error("Invalid location specificiation. "
            "--query=\"X,Y[/count]\"");

    auto seps = [](char c){ return (c == ',' || c == '|' || c == ' '); };

    std::vector<std::string> tokens = Utils::split2(location, seps);
    std::vector<double> values;
    for (auto ti = tokens.begin(); ti != tokens.end(); ++ti)
        values.push_back(boost::lexical_cast<double>(*ti));

    if (values.size() != 2 && values.size() != 3)
        throw app_runtime_error("--points must be two or three values");

    PointViewPtr outView = inView->makeNew();

    std::vector<PointId> ids;
    if (values.size() >= 3)
    {
        KD3Index kdi(*inView);
        kdi.build();
        ids = kdi.neighbors(values[0], values[1], values[2], count);
    }
    else
    {
        KD2Index kdi(*inView);
        kdi.build();
        ids = kdi.neighbors(values[0], values[1], count);
    }

    for (auto i = ids.begin(); i != ids.end(); ++i)
        outView->appendPoint(*inView.get(), *i);

    return Utils::toMetadata(outView);
}

int InfoKernel::execute()
{
    std::string filename = m_usestdin ? std::string("STDIN") : m_inputFile;
    setup(filename);
    MetadataNode root = run(filename);
    Utils::toJSON(root, std::cout);

    return 0;
}

} // namespace pdal


text:
import { Component } from '@angular/core';
import { SkyModalInstance } from '@skyux/modals';

import { FilterDemoModalContext } from './filter-demo-modal-context';

@Component({
  selector: 'app-filter-demo-modal',
  templateUrl: './filter-demo-modal.component.html',
})
export class FilterDemoModalComponent {
  public hideOrange: boolean;

  public fruitType = 'any';

  constructor(
    public context: FilterDemoModalContext,
    public instance: SkyModalInstance
  ) {
    if (
      this.context &&
      this.context.appliedFilters &&
      this.context.appliedFilters.length > 0
    ) {
      this.setFormFilters(this.context.appliedFilters);
    } else {
      this.clearAllFilters();
    }
  }

  public applyFilters(): void {
    const result = this.getAppliedFiltersArray();
    this.instance.save(result);
  }

  public cancel(): void {
    this.instance.cancel();
  }

  public clearAllFilters(): void {
    this.hideOrange = false;
    this.fruitType = 'any';
  }

  private getAppliedFiltersArray(): any[] {
    const appliedFilters: any[] = [];
    if (this.fruitType !== 'any') {
      appliedFilters.push({
        name: 'fruitType',
        value: this.fruitType,
        label: this.fruitType,
      });
    }

    if (this.hideOrange) {
      appliedFilters.push({
        name: 'hideOrange',
        value: true,
        label: 'hide orange fruits',
      });
    }

    return appliedFilters;
  }

  private setFormFilters(appliedFilters: any[]): void {
    for (let i = 0; i < appliedFilters.length; i++) {
      if (appliedFilters[i].name === 'fruitType') {
        this.fruitType = appliedFilters[i].value;
      }

      if (appliedFilters[i].name === 'hideOrange') {
        this.hideOrange = appliedFilters[i].value;
      }
    }
  }
}

redpajama_set_name: RedPajamaGithub


text:
import sqlite3
from sqlite3 import Error
import csv
import json

def main():
    conn = sqlite3.connect("greenhouse.db")
    create_table(conn)

    # with open('greenhouse_log.txt', 'r') as the_file:
    #     for line in the_file:
    #         it = iter(map(lambda s: s.strip(), line.split(";")))
    #         t_data = dict(zip(it, it))
    #         t_data['temperature'] = float(t_data['temperature'])
    #         t_data['humidity'] = int(t_data['humidity'])
    #         values = (t_data['date'], t_data['temperature'])
    #         insert_value(conn, values)
    # conn.commit()

    print_no_of_rows(conn)
    print_last_values(conn)

def print_no_of_rows(conn):
    cur = conn.cursor()
    cur.execute("SELECT count(*) FROM greenhouse")
    print("No of lines: {}".format(cur.fetchone()[0]))

def print_last_values(conn):
    cur = conn.cursor()
    cur.execute("SELECT * FROM greenhouse WHERE time = (SELECT MAX(time) FROM greenhouse)")
    print("Last row: {}".format(cur.fetchone()))

def insert_value(conn, temperature):
    sql = """ INSERT INTO greenhouse(time, temperature) values(?, ?) """
    cur = conn.cursor()
    cur.execute(sql, temperature)

def wef():
    temp_values = []
    with open('./green.log', 'r') as the_file:
        for line in the_file:
            it = iter(map(lambda s: s.strip(), line.split(";")))
            temperature_data = dict(zip(it, it))
            temperature_data['temp'] = float(temperature_data['temp'])
            temperature_data['humidity'] = int(temperature_data['humidity'])
            temp_values.append(temperature_data)
        json_str = json.dumps(temp_values)

def create_table(conn):
    c = conn.cursor()
    c.execute(
        """CREATE TABLE IF NOT EXISTS greenhouse (
              time text NOT NULL,
              temperature real
        );"""
    )

if __name__ == '__main__':
    main()


text:
namespace syncer {
class P2PInvalidator;
}

class Profile;

namespace invalidation {

class InvalidationLogger;

// This service is a wrapper around P2PInvalidator.  Unlike other
// InvalidationServices, it can both send and receive invalidations.  It is used
// only in tests, where we're unable to connect to a real invalidations server.
class P2PInvalidationService
    : public base::NonThreadSafe,
      public InvalidationService {
 public:
  explicit P2PInvalidationService(Profile* profile);
  virtual ~P2PInvalidationService();

  // Overrides KeyedService method.
  virtual void Shutdown() OVERRIDE;

  // InvalidationService implementation.
  // It is an error to have registered handlers when Shutdown() is called.
  virtual void RegisterInvalidationHandler(
      syncer::InvalidationHandler* handler) OVERRIDE;
  virtual void UpdateRegisteredInvalidationIds(
      syncer::InvalidationHandler* handler,
      const syncer::ObjectIdSet& ids) OVERRIDE;
  virtual void UnregisterInvalidationHandler(
      syncer::InvalidationHandler* handler) OVERRIDE;
  virtual syncer::InvalidatorState GetInvalidatorState() const OVERRIDE;
  virtual std::string GetInvalidatorClientId() const OVERRIDE;
  virtual InvalidationLogger* GetInvalidationLogger() OVERRIDE;

  void UpdateCredentials(const std::string& username,
                         const std::string& password);

  void SendInvalidation(const syncer::ObjectIdSet& ids);

 private:
  scoped_ptr<syncer::P2PInvalidator> invalidator_;
  std::string invalidator_id_;

  DISALLOW_COPY_AND_ASSIGN(P2PInvalidationService);
};

}  // namespace invalidation

#endif  // CHROME_BROWSER_INVALIDATION_P2P_INVALIDATION_SERVICE_H_


text:
using System;

using NUnit.Framework;

namespace ZXing.PDF417.Internal.Test
{
   /// <summary>
   /// @author Sean Owen
   /// </summary>
   public abstract class AbstractErrorCorrectionTestCase
   {
      public static void corrupt(int[] received, int howMany, Random random)
      {
         var corrupted = new System.Collections.BitArray(received.Length);
         // BitSet corrupted = new BitSet(received.Length);
         for (int j = 0; j < howMany; j++)
         {
            int location = random.Next(received.Length);
            if (corrupted[location])
            {
               j--;
            }
            else
            {
               corrupted[location] = true;
               received[location] = random.Next(929);
            }
         }
      }
      /*
      public static int[] erase(int[] received, int howMany, Random random)
      {
         var erased = new System.Collections.BitArray(received.Length);
         // BitSet erased = new BitSet(received.Length);
         int[] erasures = new int[howMany];
         int erasureOffset = 0;
         for (int j = 0; j < howMany; j++)
         {
            int location = random.Next(received.Length);
            if (erased[location])
            {
               j--;
            }
            else
            {
               erased[location] = true;
               received[location] = 0;
               erasures[erasureOffset++] = location;
            }
         }
         return erasures;
      }
      */
      public static Random getRandom()
      {
         return new Random((int)DateTime.Now.Ticks);
         // return new SecureRandom(new byte[] { (byte)0xDE, (byte)0xAD, (byte)0xBE, (byte)0xEF });
      }
      /*
      public static void assertArraysEqual(int[] expected,
                                    int expectedOffset,
                                    int[] actual,
                                    int actualOffset,
                                    int length)
      {
         for (int i = 0; i < length; i++)
         {
            Assert.AreEqual(expected[expectedOffset + i], actual[actualOffset + i]);
         }
      }
      */
   }
}


text:
package org.keycloak.it.utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.*;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import io.quarkus.deployment.util.FileUtil;
import io.quarkus.fs.util.ZipUtils;

import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.EmptyAsset;
import org.jboss.shrinkwrap.api.exporter.ZipExporter;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.keycloak.common.Version;
import org.keycloak.it.TestProvider;
import org.keycloak.it.junit5.extension.CLIResult;
import org.keycloak.quarkus.runtime.cli.command.Build;
import org.keycloak.quarkus.runtime.configuration.mappers.PropertyMapper;
import org.keycloak.quarkus.runtime.configuration.mappers.PropertyMappers;

import static org.keycloak.quarkus.runtime.Environment.LAUNCH_MODE;
import static org.keycloak.quarkus.runtime.Environment.isWindows;

public final class RawKeycloakDistribution implements KeycloakDistribution {

    private static final int DEFAULT_SHUTDOWN_TIMEOUT_SECONDS = 10;

    private Process keycloak;
    private int exitCode = -1;
    private final Path distPath;
    private final List<String> outputStream = new ArrayList<>();
    private final List<String> errorStream = new ArrayList<>();
    private boolean manualStop;
    private String relativePath;
    private int httpPort;
    private boolean debug;
    private boolean reCreate;
    private boolean removeBuildOptionsAfterBuild;
    private ExecutorService outputExecutor;
    private boolean inited = false;
    private Map<String, String> envVars = new HashMap<>();

    public RawKeycloakDistribution(boolean debug, boolean manualStop, boolean reCreate, boolean removeBuildOptionsAfterBuild) {
        this.debug = debug;
        this.manualStop = manualStop;
        this.reCreate = reCreate;
        this.removeBuildOptionsAfterBuild = removeBuildOptionsAfterBuild;
        this.distPath = prepareDistribution();
    }

    @Override
    public CLIResult run(List<String> arguments) {
        reset();
        if (manualStop && isRunning()) {
            throw new IllegalStateException("Server already running. You should manually stop the server before starting it again.");
        }
        stop();
        try {
            startServer(arguments);
            if (manualStop) {
                asyncReadOutput();
                waitForReadiness();
            } else {
                readOutput();
            }
        } catch (Exception cause) {
            stop();
            throw new RuntimeException("Failed to start the server", cause);
        } finally {
            if (arguments.contains(Build.NAME) && removeBuildOptionsAfterBuild) {
                for (List<PropertyMapper> mappers : PropertyMappers.getBuildTimeMappers().values()) {
                    for (PropertyMapper mapper : mappers) {
                        removeProperty(mapper.getFrom().substring(3));
                    }
                }
            }
            if (!manualStop) {
                stop();
                envVars.clear();
            }
        }

        return CLIResult.create(getOutputStream(), getErrorStream(), getExitCode());
    }

    @Override
    public void stop() {
        if (isRunning()) {
            try {
                // On Windows, we need to make sure sub-processes are terminated first
                destroyDescendantsOnWindows(keycloak, false);

                keycloak.destroy();
                keycloak.waitFor(DEFAULT_SHUTDOWN_TIMEOUT_SECONDS, TimeUnit.SECONDS);
                exitCode = keycloak.exitValue();
            } catch (Exception cause) {
                destroyDescendantsOnWindows(keycloak, true);
                keycloak.destroyForcibly();
                throw new RuntimeException("Failed to stop the server", cause);
            }
        }

        shutdownOutputExecutor();
    }

    private void destroyDescendantsOnWindows(Process parent, boolean force) {
        if (!isWindows()) {
            return;
        }

        CompletableFuture allProcesses = CompletableFuture.completedFuture(null);

        for (ProcessHandle process : parent.descendants().collect(Collectors.toList())) {
            if (force) {
                process.destroyForcibly();
            } else {
                process.destroy();
            }

            allProcesses = CompletableFuture.allOf(allProcesses, process.onExit());
        }

        try {
            allProcesses.get(DEFAULT_SHUTDOWN_TIMEOUT_SECONDS, TimeUnit.SECONDS);
        } catch (Exception cause) {
            throw new RuntimeException("Failed to terminate descendants processes", cause);
        }

        try {
            // TODO: remove this. do not ask why, but on Windows we are here even though the process was previously terminated
            // without this pause, tests re-installing dist before tests should fail
            // looks like pausing the current thread let windows to cleanup processes?
            // more likely it is env dependent
            Thread.sleep(500);
        } catch (InterruptedException e) {
        }
    }

    @Override
    public List<String> getOutputStream() {
        return outputStream;
    }

    @Override
    public List<String> getErrorStream() {
        return errorStream;
    }

    @Override
    public int getExitCode() {
        return exitCode;
    }

    @Override
    public boolean isDebug() { return this.debug; }

    @Override
    public boolean isManualStop() { return this.manualStop; }

    @Override
    public String[] getCliArgs(List<String> arguments) {
        List<String> allArgs = new ArrayList<>();

        if (isWindows()) {
            allArgs.add(distPath.resolve("bin") + File.separator + SCRIPT_CMD_INVOKABLE);
        } else {
            allArgs.add(SCRIPT_CMD_INVOKABLE);
        }

        if (this.isDebug()) {
            allArgs.add("--debug");
        }

        if (!this.isManualStop()) {
            allArgs.add("-D" + LAUNCH_MODE + "=test");
        }

        this.relativePath = arguments.stream().filter(arg -> arg.startsWith("--http-relative-path")).map(arg -> arg.substring(arg.indexOf('=') + 1)).findAny().orElse("/");
        this.httpPort = Integer.parseInt(arguments.stream().filter(arg -> arg.startsWith("--http-port")).map(arg -> arg.substring(arg.indexOf('=') + 1)).findAny().orElse("8080"));

        allArgs.add("-Dkc.home.dir=" + distPath + File.separator);
        allArgs.addAll(arguments);

        return allArgs.toArray(String[]::new);
    }

    private void waitForReadiness() throws MalformedURLException {
        URL contextRoot = new URL("http://localhost:" + httpPort + ("/" + relativePath + "/realms/master/").replace("//", "/"));
        HttpURLConnection connection = null;
        long startTime = System.currentTimeMillis();

        while (true) {
            if (System.currentTimeMillis() - startTime > getStartTimeout()) {
                throw new IllegalStateException(
                        "Timeout [" + getStartTimeout() + "] while waiting for Quarkus server");
            }

            try {
                // wait before checking for opening a new connection
                Thread.sleep(1000);
                if ("https".equals(contextRoot.getProtocol())) {
                    HttpsURLConnection httpsConnection = (HttpsURLConnection) (connection = (HttpURLConnection) contextRoot.openConnection());
                    httpsConnection.setSSLSocketFactory(createInsecureSslSocketFactory());
                    httpsConnection.setHostnameVerifier(createInsecureHostnameVerifier());
                } else {
                    connection = (HttpURLConnection) contextRoot.openConnection();
                }

                connection.setReadTimeout((int) getStartTimeout());
                connection.setConnectTimeout((int) getStartTimeout());
                connection.connect();

                if (connection.getResponseCode() == 200) {
                    break;
                }
            } catch (Exception ignore) {
            } finally {
                if (connection != null) {
                    connection.disconnect();
                }
            }
        }
    }

    private long getStartTimeout() {
        return TimeUnit.SECONDS.toMillis(120);
    }

    private HostnameVerifier createInsecureHostnameVerifier() {
        return new HostnameVerifier() {
            @Override
            public boolean verify(String s, SSLSession sslSession) {
                return true;
            }
        };
    }

    private SSLSocketFactory createInsecureSslSocketFactory() throws IOException {
        TrustManager[] trustAllCerts = new TrustManager[] {new X509TrustManager() {
            public void checkClientTrusted(final X509Certificate[] chain, final String authType) {
            }

            public void checkServerTrusted(final X509Certificate[] chain, final String authType) {
            }

            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        }};

        SSLContext sslContext;
        SSLSocketFactory socketFactory;

        try {
            sslContext = SSLContext.getInstance("TLS");
            sslContext.init(null, trustAllCerts, new SecureRandom());
            socketFactory = sslContext.getSocketFactory();
        } catch (NoSuchAlgorithmException | KeyManagementException e) {
            throw new IOException("Can't create unsecure trust manager");
        }
        return socketFactory;
    }

    private boolean isRunning() {
        return keycloak != null && keycloak.isAlive();
    }

    private void asyncReadOutput() {
        shutdownOutputExecutor();
        outputExecutor = Executors.newSingleThreadExecutor();
        outputExecutor.execute(this::readOutput);
    }

    private void shutdownOutputExecutor() {
        if (outputExecutor != null) {
            outputExecutor.shutdown();
            try {
                outputExecutor.awaitTermination(30, TimeUnit.SECONDS);
            } catch (InterruptedException cause) {
                throw new RuntimeException("Failed to terminate output executor", cause);
            } finally {
                outputExecutor = null;
            }
        }
    }

    private void reset() {
        outputStream.clear();
        errorStream.clear();
        exitCode = -1;
        shutdownOutputExecutor();
        keycloak = null;
    }

    private Path prepareDistribution() {
        try {
            Path distRootPath = Paths.get(System.getProperty("java.io.tmpdir")).resolve("kc-tests");
            distRootPath.toFile().mkdirs();

            File distFile = new File("../../dist/" + File.separator + "target" + File.separator + "keycloak-" + Version.VERSION + ".zip");
            if (!distFile.exists()) {
                throw new RuntimeException("Distribution archive " + distFile.getAbsolutePath() +" doesn't exist");
            }
            distRootPath.toFile().mkdirs();
            String distDirName = distFile.getName();
            Path dPath = distRootPath.resolve(distDirName.substring(0, distDirName.lastIndexOf('.')));

            if (!inited || (reCreate || !dPath.toFile().exists())) {
                FileUtil.deleteDirectory(dPath);
                ZipUtils.unzip(distFile.toPath(), distRootPath);
            }

            // make sure script is executable
            if (!dPath.resolve("bin").resolve(SCRIPT_CMD).toFile().setExecutable(true)) {
                throw new RuntimeException("Cannot set " + SCRIPT_CMD + " executable");
            }

            inited = true;

            return dPath;
        } catch (Exception cause) {
            throw new RuntimeException("Failed to prepare distribution", cause);
        }
    }

    private void readOutput() {
        try (
                BufferedReader outStream = new BufferedReader(new InputStreamReader(keycloak.getInputStream()));
                BufferedReader errStream = new BufferedReader(new InputStreamReader(keycloak.getErrorStream()));
        ) {
            while (keycloak.isAlive()) {
                readStream(outStream, outputStream);
                readStream(errStream, errorStream);
            }
        } catch (Throwable cause) {
            throw new RuntimeException("Failed to read server output", cause);
        }
    }

    private void readStream(BufferedReader reader, List<String> stream) throws IOException {
        String line;

        while (reader.ready() && (line = reader.readLine()) != null) {
            stream.add(line);
            System.out.println(line);
        }
    }

    /**
     * The server is configured to redirect errors to output stream. This adds a limitation when checking whether a
     * message arrived via error stream.
     *
     * @param arguments the list of arguments to run the server
     * @throws Exception if something bad happens
     */
    private void startServer(List<String> arguments) throws Exception {
        ProcessBuilder pb = new ProcessBuilder(getCliArgs(arguments));
        ProcessBuilder builder = pb.directory(distPath.resolve("bin").toFile());

        builder.environment().put("KEYCLOAK_ADMIN", "admin");
        builder.environment().put("KEYCLOAK_ADMIN_PASSWORD", "admin");

        if (debug) {
            builder.environment().put("DEBUG_SUSPEND", "y");
        }

        builder.environment().putAll(envVars);

        keycloak = builder.start();
    }

    @Override
    public void setManualStop(boolean manualStop) {
        this.manualStop = manualStop;
    }

    @Override
    public void setProperty(String key, String value) {
        updateProperties(properties -> properties.put(key, value), distPath.resolve("conf").resolve("keycloak.conf").toFile());
    }

    @Override
    public void setEnvVar(String key, String value) {
        this.envVars.put(key, value);
    }

    @Override
    public void removeProperty(String name) {
        updateProperties(new Consumer<Properties>() {
            @Override
            public void accept(Properties properties) {
                properties.remove(name);
            }
        }, distPath.resolve("conf").resolve("keycloak.conf").toFile());
    }

    @Override
    public void setQuarkusProperty(String key, String value) {
        updateProperties(new Consumer<Properties>() {
            @Override
            public void accept(Properties properties) {
                properties.put(key, value);
            }
        }, getQuarkusPropertiesFile());
    }

    @Override
    public void deleteQuarkusProperties() {
        File file = getQuarkusPropertiesFile();

        if (file.exists()) {
            file.delete();
        }
    }

    @Override
    public void copyOrReplaceFileFromClasspath(String file, Path targetFile) {
        File targetDir = distPath.resolve(targetFile).toFile();

        targetDir.mkdirs();

        try {
            Files.copy(getClass().getResourceAsStream(file), targetDir.toPath(), StandardCopyOption.REPLACE_EXISTING);
        } catch (IOException cause) {
            throw new RuntimeException("Failed to copy file", cause);
        }
    }

    @Override
    public void copyOrReplaceFile(Path file, Path targetFile) {
        if (!file.toFile().exists()) {
            return;
        }

        File targetDir = distPath.resolve(targetFile).toFile();

        targetDir.mkdirs();

        try {
            Files.copy(file, targetDir.toPath(), StandardCopyOption.REPLACE_EXISTING);
        } catch (IOException cause) {
            throw new RuntimeException("Failed to copy file", cause);
        }
    }

    public void copyProvider(String groupId, String artifactId) {
        try {
            Files.copy(Maven.resolveArtifact(groupId, artifactId), getDistPath().resolve("providers").resolve(artifactId + ".jar"));
        } catch (IOException cause) {
            throw new RuntimeException("Failed to copy JAR file to 'providers' directory", cause);
        }
    }

    private void updateProperties(Consumer<Properties> propertiesConsumer, File propertiesFile) {
        Properties properties = new Properties();

        if (propertiesFile.exists()) {
            try (
                FileInputStream in = new FileInputStream(propertiesFile);
            ) {

                properties.load(in);
            } catch (Exception e) {
                throw new RuntimeException("Failed to update " + propertiesFile, e);
            }
        }

        try (
            FileOutputStream out = new FileOutputStream(propertiesFile)
        ) {
            propertiesConsumer.accept(properties);
            properties.store(out, "");
        } catch (Exception e) {
            throw new RuntimeException("Failed to update " + propertiesFile, e);
        }
    }

    private File getQuarkusPropertiesFile() {
        return distPath.resolve("conf").resolve("quarkus.properties").toFile();
    }

    public Path getDistPath() {
        return distPath;
    }

    public void copyProvider(TestProvider provider) {
        Path providerPackagePath = Paths.get(provider.getClass().getResource(".").getPath());
        JavaArchive providerJar = ShrinkWrap.create(JavaArchive.class, provider.getName() + ".jar")
                .addClasses(provider.getClasses())
                .addAsManifestResource(EmptyAsset.INSTANCE, "beans.xml");
        Map<String, String> manifestResources = provider.getManifestResources();

        for (Map.Entry<String, String> resource : manifestResources.entrySet()) {
            try {
                providerJar.addAsManifestResource(providerPackagePath.resolve(resource.getKey()).toFile(), resource.getValue());
            } catch (Exception cause) {
                throw new RuntimeException("Failed to add manifest resource: " + resource.getKey(), cause);
            }
        }

        copyOrReplaceFile(providerPackagePath.resolve("quarkus.properties"), Path.of("conf", "quarkus.properties"));

        providerJar.as(ZipExporter.class).exportTo(getDistPath().resolve("providers").resolve(providerJar.getName()).toFile());
    }
}


text:
package ru.eltech.csa.siths.form.entity;

import static org.junit.Assert.*;

import java.lang.annotation.AnnotationTypeMismatchException;
import java.lang.reflect.Method;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import javax.validation.constraints.Size;

public class FeaturedAccountTest {
	FeaturedAccount b;

	  public void printType(byte x) {
	        System.out.println(x + " is an byte");
	    }
	    public void printType(int x) {
	   fail("fdafds");
	    }
	    public void printType(float x) {
	        System.out.println(x + " is an float");
	    }
	    public void printType(double x) {
	        System.out.println(x + " is an double");
	    }
	    public void printType(String x) {
	        System.out.println(x + " is an double");
	    }

 @Before
 public void start()
    {
	 FeaturedAccount b = new FeaturedAccount("zxfdsfdsf","test@mail.ru","abcdefgh","abcdefgh");
	}

	@Test(expected = Exception.class)
	public void test() {

System.out.println(b.name);

	}

	@Test(expected = AnnotationTypeMismatchException.class)
	public void testSetName() {
		FeaturedAccount m = new FeaturedAccount();
		m.setName(123);
		System.out.println(m.name);

	}
	@Test(expected = AnnotationTypeMismatchException.class)
	public void testSetName_2() {
		FeaturedAccount m = new FeaturedAccount();
		m.setName("testing");
		System.out.println(m.name);

	}
	@Test(expected = AnnotationTypeMismatchException.class)
	public void testSetName_3() {
		FeaturedAccount m = new FeaturedAccount();
		m.setName("vc");
		System.out.println(m.name);

	}
	@Test(expected = Exception.class)
	public void testSetName_4() {
		FeaturedAccount m = new FeaturedAccount();
		m.setName("vc");
		System.out.println(m.name);

	}

	@Test(expected = Exception.class)
	public void testGetName() {
		System.out.println(b.getName());

	}

	@Test(expected = Exception.class)
	public void testSetEmail() {
		FeaturedAccount b = new FeaturedAccount();

		b.setEmail("sdfsdf@mail.ru");
	}

	@Test(expected = Exception.class)
	public void testGetEmail() {
		FeaturedAccount b = new FeaturedAccount();

		System.out.println(b.getEmail());

	}

	@Test
	public void testSetPassword() {
		FeaturedAccount b = new FeaturedAccount();
		b.setPassword("example_password");
	}

	@Test(expected = Exception.class)
	public void testSetPassword_1() {
		FeaturedAccount b = new FeaturedAccount();
		b.setPassword("example_password");
	}
	@Test
	public void testGetPassword() {
		FeaturedAccount b = new FeaturedAccount();
		b.getPassword();
	}
	@Test(expected = Exception.class)
	public void testGetPassword_1() {
		FeaturedAccount b = new FeaturedAccount();
		b.getPassword();
	}

	@Test
	public void testSetPasswordConfirmation() {
		FeaturedAccount b = new FeaturedAccount();
		b.setPasswordConfirmation("confirm_password");
	}

	@Test(expected = Exception.class)
	public void testGetPasswordConfirmation_1() {
		FeaturedAccount b = new FeaturedAccount();
		b.getPasswordConfirmation();
	}

}


text:
React fundamentals class for BU's CS department

## Lesson 1

The obligatory `Hello, World!` program.

### Get Started
1. git clone https://github.com/mikechabot/react-fundamentals.git
2. `npm install`
3. Launch environment:
  * `npm start`


text:
require 'spec_helper'

RSpec.feature 'User searching topics' do
  title = 'Rando thread'

  # On MySQL, a transaction has to complete before the full text search index is updated
  before :all do
    @messageboard = create(:messageboard)
    create(:topic, title: title, messageboard: @messageboard)
    create_list(:topic, 2, messageboard: @messageboard)
    @topics = PageObject::Topics.new(@messageboard)
  end

  after :all do
    DatabaseCleaner.clean_with(:truncation)
  end

  it 'in a messageboard' do
    @topics.visit_style_guide
    @topics.search_for(title)
    expect(page.source).to(
      include(I18n.t('thredded.topics.search.results_in_messageboard_message_html',
                     query: title, messageboard: @messageboard.name))
    )
    expect(@topics.normal_topics.size).to eq(1)
    expect(@topics).to have_topic_titled(title)
  end

  it 'globally' do
    visit thredded.root_path
    @topics.search_for(title)
    expect(page.source).to include(I18n.t('thredded.topics.search.results_message_html', query: title))
    expect(@topics.normal_topics.size).to eq(1)
    expect(@topics).to have_topic_titled(title)
  end
end


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
Pass: (900) names must be unique among FunctionDefinitions,
Compartments, Species, global Parameters, Reactions, and Events
(L2v1 Section 3.5).
-->
<sbml xmlns="http://www.sbml.org/sbml/level1" level="1" version="1">
  <model name="m">
        <listOfCompartments>
			<compartment name="c"/>
        </listOfCompartments>
        <listOfSpecies>
        		<specie name="s" compartment="c" initialAmount="0"/>
        </listOfSpecies>
        <listOfParameters>
          <parameter name="p" value="2"/>
        </listOfParameters>
        <listOfRules>
			<parameterRule name="p" formula="c*5"/>
        </listOfRules>
        <listOfReactions>
        		<reaction name="r">
        			<listOfProducts>
        				<specieReference specie="s"/>
        			</listOfProducts>
        		</reaction>
        </listOfReactions>
  </model>
</sbml>


text:
namespace mo
{
  extern void* (*alloc_func)(size_t n);
  extern void(*free_func)(void* p);
  extern void* (*realloc_func)(void* p, size_t n);

  void* default_alloc(size_t n);
  void default_free(void* p);
  void* default_realloc(void* p, size_t n);

  void register_default_alloc();
}

#endif

//--------------------------------------------------------------------------------------------------
namespace mo
{
  struct new_tag {};
}

inline void* operator new(size_t, void* p, mo::new_tag){ return p; }
inline void operator delete(void*, void*, mo::new_tag) {}

#define MO_PLACEMENT_NEW(p)   ::new_handler(p, mo::new_tag())

//--------------------------------------------------------------------------------------------------
namespace mo
{
  //------------------------------------------------------------------------------------------------
  template<class T>
  class allocator
  {
  public:

    //----------------------------------------------------------------------------------------------
    typedef T value_type;
    template<class U> struct rebind { typedef allocator<U> other; };

    //----------------------------------------------------------------------------------------------
    allocator() {}

    //----------------------------------------------------------------------------------------------
    allocator(const allocator&) {}

    //----------------------------------------------------------------------------------------------
    template<class U> allocator(const allocator<U>&) {}

    //----------------------------------------------------------------------------------------------
    T* allocate(size_t n)
    {
      return (T*)MO_ALLOC(n * sizeof(T), typeid(T).name());
    }

    //----------------------------------------------------------------------------------------------
    void deallocate(T* p)
    {
      MO_FREE(p, typeid(T).name());
    }

    //----------------------------------------------------------------------------------------------
    size_t max_size() const
    {
      return (size_t)-1 / sizeof(T);
    }
  };

  template<class T>
  bool operator==(const allocator<T>&, const allocator<T>&)
  {
    return true;
  }

  template<class T>
  bool operator!=(const allocator<T>&, const allocator<T>&)
  {
    return false;
  }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Epiclinium negerianum Sacc. & P. Syd.

### Remarks
null


text:
<?php

require_once('find_config.php');
$h->session->requireLoggedIn();

if (!isset($_GET['goto'])) {
    header('Location: index.php');
}

$tourl = $_GET['goto'];

// Start chat between two users
if (isset($_GET['otherid']) && is_numeric($_GET['otherid'])) {
    addSubscription(SUBSCRIPTION_USER_CHATREQ, $h->session->id, $_GET['otherid']);
}

//echo $tourl;
header('Location: '.$tourl);

?>


text:
.class Lcn/com/smartdevices/bracelet/ui/aH;
.super Ljava/lang/Object;

# interfaces
.implements Landroid/animation/ValueAnimator$AnimatorUpdateListener;

# instance fields
.field final synthetic a:Lcn/com/smartdevices/bracelet/ui/MainUIActivity;

# direct methods
.method constructor <init>(Lcn/com/smartdevices/bracelet/ui/MainUIActivity;)V
    .locals 0

    iput-object p1, p0, Lcn/com/smartdevices/bracelet/ui/aH;->a:Lcn/com/smartdevices/bracelet/ui/MainUIActivity;

    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    return-void
.end method

# virtual methods
.method public onAnimationUpdate(Landroid/animation/ValueAnimator;)V
    .locals 4

    const/high16 v1, 0x3f000000    # 0.5f

    invoke-virtual {p1}, Landroid/animation/ValueAnimator;->getAnimatedValue()Ljava/lang/Object;

    move-result-object v0

    check-cast v0, Ljava/lang/Float;

    invoke-virtual {v0}, Ljava/lang/Float;->floatValue()F

    move-result v0

    mul-float/2addr v0, v1

    add-float/2addr v1, v0

    invoke-virtual {p1}, Landroid/animation/ValueAnimator;->getAnimatedValue()Ljava/lang/Object;

    move-result-object v0

    check-cast v0, Ljava/lang/Float;

    invoke-virtual {v0}, Ljava/lang/Float;->floatValue()F

    move-result v0

    iget-object v2, p0, Lcn/com/smartdevices/bracelet/ui/aH;->a:Lcn/com/smartdevices/bracelet/ui/MainUIActivity;

    invoke-static {v2}, Lcn/com/smartdevices/bracelet/ui/MainUIActivity;->h(Lcn/com/smartdevices/bracelet/ui/MainUIActivity;)Landroid/widget/TextView;

    move-result-object v2

    invoke-virtual {v2, v1}, Landroid/widget/TextView;->setScaleX(F)V

    iget-object v2, p0, Lcn/com/smartdevices/bracelet/ui/aH;->a:Lcn/com/smartdevices/bracelet/ui/MainUIActivity;

    invoke-static {v2}, Lcn/com/smartdevices/bracelet/ui/MainUIActivity;->h(Lcn/com/smartdevices/bracelet/ui/MainUIActivity;)Landroid/widget/TextView;

    move-result-object v2

    invoke-virtual {v2, v1}, Landroid/widget/TextView;->setScaleY(F)V

    iget-object v2, p0, Lcn/com/smartdevices/bracelet/ui/aH;->a:Lcn/com/smartdevices/bracelet/ui/MainUIActivity;

    invoke-static {v2}, Lcn/com/smartdevices/bracelet/ui/MainUIActivity;->i(Lcn/com/smartdevices/bracelet/ui/MainUIActivity;)Landroid/widget/TextView;

    move-result-object v2

    invoke-virtual {v2, v1}, Landroid/widget/TextView;->setScaleX(F)V

    iget-object v2, p0, Lcn/com/smartdevices/bracelet/ui/aH;->a:Lcn/com/smartdevices/bracelet/ui/MainUIActivity;

    invoke-static {v2}, Lcn/com/smartdevices/bracelet/ui/MainUIActivity;->i(Lcn/com/smartdevices/bracelet/ui/MainUIActivity;)Landroid/widget/TextView;

    move-result-object v2

    invoke-virtual {v2, v1}, Landroid/widget/TextView;->setScaleY(F)V

    iget-object v2, p0, Lcn/com/smartdevices/bracelet/ui/aH;->a:Lcn/com/smartdevices/bracelet/ui/MainUIActivity;

    invoke-static {v2}, Lcn/com/smartdevices/bracelet/ui/MainUIActivity;->h(Lcn/com/smartdevices/bracelet/ui/MainUIActivity;)Landroid/widget/TextView;

    move-result-object v2

    invoke-virtual {v2, v1}, Landroid/widget/TextView;->setAlpha(F)V

    iget-object v2, p0, Lcn/com/smartdevices/bracelet/ui/aH;->a:Lcn/com/smartdevices/bracelet/ui/MainUIActivity;

    invoke-static {v2}, Lcn/com/smartdevices/bracelet/ui/MainUIActivity;->i(Lcn/com/smartdevices/bracelet/ui/MainUIActivity;)Landroid/widget/TextView;

    move-result-object v2

    invoke-virtual {v2, v1}, Landroid/widget/TextView;->setAlpha(F)V

    iget-object v1, p0, Lcn/com/smartdevices/bracelet/ui/aH;->a:Lcn/com/smartdevices/bracelet/ui/MainUIActivity;

    const/4 v2, 0x0

    invoke-static {v2}, Ljava/lang/Boolean;->valueOf(Z)Ljava/lang/Boolean;

    move-result-object v2

    invoke-static {v1, v2}, Lcn/com/smartdevices/bracelet/ui/MainUIActivity;->a(Lcn/com/smartdevices/bracelet/ui/MainUIActivity;Ljava/lang/Boolean;)Ljava/lang/Boolean;

    iget-object v1, p0, Lcn/com/smartdevices/bracelet/ui/aH;->a:Lcn/com/smartdevices/bracelet/ui/MainUIActivity;

    invoke-static {v1}, Lcn/com/smartdevices/bracelet/ui/MainUIActivity;->j(Lcn/com/smartdevices/bracelet/ui/MainUIActivity;)Landroid/widget/ImageView;

    move-result-object v1

    const/high16 v2, 0x43b40000    # 360.0f

    const/high16 v3, 0x43340000    # 180.0f

    mul-float/2addr v0, v3

    sub-float v0, v2, v0

    invoke-virtual {v1, v0}, Landroid/widget/ImageView;->setRotation(F)V

    return-void
.end method


text:
package upside_down

type termSummaryIncr struct{}

func newTermSummaryIncr() *termSummaryIncr {
	return &termSummaryIncr{}
}

func (t *termSummaryIncr) Merge(key, existing []byte) ([]byte, error) {
	if len(existing) > 0 {
		tfr, err := NewTermFrequencyRowKV(key, existing)
		if err != nil {
			return nil, err
		}
		tfr.freq++
		return tfr.Value(), nil
	} else {
		tfr, err := NewTermFrequencyRowK(key)
		if err != nil {
			return nil, err
		}
		tfr.freq = 1
		return tfr.Value(), nil
	}
}

type termSummaryDecr struct{}

func newTermSummaryDecr() *termSummaryDecr {
	return &termSummaryDecr{}
}

func (t *termSummaryDecr) Merge(key, existing []byte) ([]byte, error) {
	if len(existing) > 0 {
		tfr, err := NewTermFrequencyRowKV(key, existing)
		if err != nil {
			return nil, err
		}
		tfr.freq--
		if tfr.freq > 0 {
			return tfr.Value(), nil
		}
	}
	return nil, nil
}


text:
/*
 *	objc.h
 *	Copyright 1988-1996, NeXT Software, Inc.
 */

#ifndef _OBJC_OBJC_H_
#define _OBJC_OBJC_H_

#include <sys/types.h>      // for __DARWIN_NULL
#include <Availability.h>
#include <objc/objc-api.h>
#include <stdbool.h>

#if !OBJC_TYPES_DEFINED
/// An opaque type that represents an Objective-C class.
//一个不透明的类型代表一个objective - c类
typedef struct objc_class *Class;

/// Represents an instance of a class.
//代表一个类的实例
struct objc_object {
    Class isa  OBJC_ISA_AVAILABILITY;
};

/// A pointer to an instance of a class.
//一个类的实例的指针
typedef struct objc_object *id;
#endif

/// An opaque type that represents a method selector.
//一个不透明的类型代表一种选择方法
typedef struct objc_selector *SEL;

/// A pointer to the function of a method implementation.
//一个指向函数的方法实现
//IMP:Implementation,它是指向一个方法实现的指针
#if !OBJC_OLD_DISPATCH_PROTOTYPES
typedef void (*IMP)(void /* id, SEL, ... */ );
#else
typedef id (*IMP)(id, SEL, ...);
#endif

#define OBJC_BOOL_DEFINED

/// Type to represent a boolean value.
#if !defined(OBJC_HIDE_64) && TARGET_OS_IPHONE && __LP64__
typedef bool BOOL;
#else
typedef signed char BOOL;
// BOOL is explicitly signed so @encode(BOOL) == "c" rather than "C"
// even if -funsigned-char is used.
#endif

#if __has_feature(objc_bool)
#define YES __objc_yes
#define NO  __objc_no
#else
#define YES ((BOOL)1)
#define NO  ((BOOL)0)
#endif

#ifndef Nil
# if __has_feature(cxx_nullptr)
#   define Nil nullptr
# else
#   define Nil __DARWIN_NULL
# endif
#endif

#ifndef nil
# if __has_feature(cxx_nullptr)
#   define nil nullptr
# else
#   define nil __DARWIN_NULL
# endif
#endif

#if ! (defined(__OBJC_GC__)  ||  __has_feature(objc_arc))
#define __strong /* empty */
#endif

#if !__has_feature(objc_arc)
#define __unsafe_unretained /* empty */
#define __autoreleasing /* empty */
#endif

/**
 * Returns the name of the method specified by a given selector.
 *
 * @param sel A pointer of type \c SEL. Pass the selector whose name you wish to determine.
 *
 * @return A C string indicating the name of the selector.
 */
OBJC_EXPORT const char *sel_getName(SEL sel)
    __OSX_AVAILABLE_STARTING(__MAC_10_0, __IPHONE_2_0);

/**
 * Registers a method with the Objective-C runtime system, maps the method
 * name to a selector, and returns the selector value.
 *
 * @param str A pointer to a C string. Pass the name of the method you wish to register.
 *
 * @return A pointer of type SEL specifying the selector for the named method.
 *
 * @note You must register a method name with the Objective-C runtime system to obtain the
 *  method's selector before you can add the method to a class definition. If the method name
 *  has already been registered, this function simply returns the selector.
 */
OBJC_EXPORT SEL sel_registerName(const char *str)
    __OSX_AVAILABLE_STARTING(__MAC_10_0, __IPHONE_2_0);

/**
 * Returns the class name of a given object.
 *
 * @param obj An Objective-C object.
 *
 * @return The name of the class of which \e obj is an instance.
 */
OBJC_EXPORT const char *object_getClassName(id obj)
    __OSX_AVAILABLE_STARTING(__MAC_10_0, __IPHONE_2_0);

/**
 * Returns a pointer to any extra bytes allocated with an instance given object.
 *
 * @param obj An Objective-C object.
 *
 * @return A pointer to any extra bytes allocated with \e obj. If \e obj was
 *   not allocated with any extra bytes, then dereferencing the returned pointer is undefined.
 *
 * @note This function returns a pointer to any extra bytes allocated with the instance
 *  (as specified by \c class_createInstance with extraBytes>0). This memory follows the
 *  object's ordinary ivars, but may not be adjacent to the last ivar.
 * @note The returned pointer is guaranteed to be pointer-size aligned, even if the area following
 *  the object's last ivar is less aligned than that. Alignment greater than pointer-size is never
 *  guaranteed, even if the area following the object's last ivar is more aligned than that.
 * @note In a garbage-collected environment, the memory is scanned conservatively.
 */
OBJC_EXPORT void *object_getIndexedIvars(id obj)
    __OSX_AVAILABLE_STARTING(__MAC_10_0, __IPHONE_2_0);

/**
 * Identifies a selector as being valid or invalid.
 *
 * @param sel The selector you want to identify.
 *
 * @return YES if selector is valid and has a function implementation, NO otherwise.
 *
 * @warning On some platforms, an invalid reference (to invalid memory addresses) can cause
 *  a crash.
 */
OBJC_EXPORT BOOL sel_isMapped(SEL sel)
    __OSX_AVAILABLE_STARTING(__MAC_10_0, __IPHONE_2_0);

/**
 * Registers a method name with the Objective-C runtime system.
 *
 * @param str A pointer to a C string. Pass the name of the method you wish to register.
 *
 * @return A pointer of type SEL specifying the selector for the named method.
 *
 * @note The implementation of this method is identical to the implementation of \c sel_registerName.
 * @note Prior to OS X version 10.0, this method tried to find the selector mapped to the given name
 *  and returned \c NULL if the selector was not found. This was changed for safety, because it was
 *  observed that many of the callers of this function did not check the return value for \c NULL.
 */
OBJC_EXPORT SEL sel_getUid(const char *str)
    __OSX_AVAILABLE_STARTING(__MAC_10_0, __IPHONE_2_0);

// Obsolete ARC conversions. Deprecation forthcoming.
// Use CFBridgingRetain, CFBridgingRelease, and __bridge casts instead.

typedef const void* objc_objectptr_t;

#if __has_feature(objc_arc)
#   define objc_retainedObject(o) ((__bridge_transfer id)(objc_objectptr_t)(o))
#   define objc_unretainedObject(o) ((__bridge id)(objc_objectptr_t)(o))
#   define objc_unretainedPointer(o) ((__bridge objc_objectptr_t)(id)(o))
#else
#   define objc_retainedObject(o) ((id)(objc_objectptr_t)(o))
#   define objc_unretainedObject(o) ((id)(objc_objectptr_t)(o))
#   define objc_unretainedPointer(o) ((objc_objectptr_t)(id)(o))
#endif

#if !__OBJC2__

// The following declarations are provided here for source compatibility.

#if defined(__LP64__)
    typedef long arith_t;
    typedef unsigned long uarith_t;
#   define ARITH_SHIFT 32
#else
    typedef int arith_t;
    typedef unsigned uarith_t;
#   define ARITH_SHIFT 16
#endif

typedef char *STR;

#define ISSELECTOR(sel) sel_isMapped(sel)
#define SELNAME(sel)	sel_getName(sel)
#define SELUID(str)	sel_getUid(str)
#define NAMEOF(obj)     object_getClassName(obj)
#define IV(obj)         object_getIndexedIvars(obj)

#endif

#endif  /* _OBJC_OBJC_H_ */


text:
layout: post
status: publish
published: true
title: "Pentaho Data Integration: A Tool to Have on Your Toolbelt"
categories:
- Data
tags:
- data
- integration
---

Today I wanna share something nice I've been using: Pentaho Data Integration (aka Kettle).

As the name says, PDI is a powerful tool for manipulating and integrating data accross multiple souces (databases, files, APIs, CRMs etc).

This process of extracting, transforming and loading data is called ETL, and PDI is meant for that.

How it works

The building blocks of PDI are: job and transformation.

A transformation is where the magic happens and a job is a set of transformations.

Both can be stored locally or in a remote repository accessible to all your teammates.

You can also have a remote server responsible for running your jobs in a scheduler like crontab.

Setup

PDI is a paid product, but they provide a free community edition (CE), which is amazing by the way (I've been using just that so far).

There are many CE versions available, enter here and download the one you want (generally the last one).

PDI requires Java Runtime Environment (JRE), so make sure it's installed.

PDI does not require installation. Simply unpack the zip file into a folder of your choice and click Data Integration to open.

Check this link for more info.

Use case: crossing data

Imagine you have two applications with distinct databases: one PostgreSQL (A) and other SQL Server (B) with the following tables:

How can we cross customers from the two databases using the email attribute?

First, we need to create a transformation.

Open PDI and create a new transformation (File -> New -> Transformation).

This is how a blank transformation looks like.

In the sidebar we have all the available steps and in the big empty space, is where we drag and drop the steps we wanna use.

To join the tables, we need to input them first, so drag a Table input step to the transformation, double-click it and type the SQL query you wanna execute.

You will have to create a database connection first, just click New in front of Connection and enter the credentials.

We need to order by email because this field will be used to join the tables.

Drag another Table input for the SQL Server database and do the same.

Now we need to join them, under the Joins folder, drag the Merge Join and select the steps, join type and the keys to join (in our case, email).

Once you are done, run the transformation (click the play button or Action -> Run). It will ask for a name, fill and save.

In Execution Results you can see a bunch of details related to your run, in Preview data, we can check the merge was done as expected.

Note that we are not outputting the result of our transformation (to a .xlsx file for example), but you could do this by dragging a Output step and setting it as you wish.

Wrapping up

Pentaho Data Integration is a fantastic tool that will open you a million of possibilities.

This post is just to introduce it to you. Explore others steps and have fun.


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="ProjectModuleManager">
    <modules>
      <module fileurl="file://$PROJECT_DIR$/.idea/BuzzWordTrading.iml" filepath="$PROJECT_DIR$/.idea/BuzzWordTrading.iml" />
    </modules>
  </component>
</project>


text:
package com.model;
//°à¼¶id,רҵid,°à¼¶Ãû³Æ£¬°à¼¶ÈËÊý
public class Grade {

	private String gra_code;
	private String gra_majorName;
	private String gra_name;
	private int gra_num;
	public String getGra_code() {
		return gra_code;
	}
	public void setGra_code(String gra_code) {
		this.gra_code = gra_code;
	}

	public String getGra_majorName() {
		return gra_majorName;
	}
	public void setGra_majorName(String gra_majorName) {
		this.gra_majorName = gra_majorName;
	}
	public String getGra_name() {
		return gra_name;
	}
	public void setGra_name(String gra_name) {
		this.gra_name = gra_name;
	}
	public int getGra_num() {
		return gra_num;
	}
	public void setGra_num(int gra_num) {
		this.gra_num = gra_num;
	}

}


text:
package nng;

import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;

@Tag("fast")
public class BoolByReferenceTest {

    @Test
    public void testBool() {
        BoolByReference ref = new BoolByReference();
        assertFalse(ref.getValue());
        ref.setValue(true);
        assertTrue(ref.getValue());
        ref.setValue(false);
        assertFalse(ref.getValue());
    }
}


text:
package org.spongepowered.mod.mixin.core.world.gen;

import net.minecraft.world.World;
import net.minecraft.world.chunk.ChunkPrimer;
import net.minecraft.world.chunk.IChunkProvider;
import net.minecraft.world.gen.ChunkProviderEnd;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.event.terraingen.ChunkProviderEvent.ReplaceBiomeBlocks;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;

@Mixin(ChunkProviderEnd.class)
public abstract class MixinChunkProviderEnd implements IChunkProvider {

    @Shadow(remap = false) private int chunkX; // Forge added
    @Shadow(remap = false) private int chunkZ; // Forge added
    @Shadow private World endWorld;

    @Inject(method = "func_180519_a(Lnet/minecraft/world/chunk/ChunkPrimer;)V", at = @At("HEAD") , cancellable = true)
    public void cancelEndStone(ChunkPrimer chunk, CallbackInfo ci) {
        ReplaceBiomeBlocks event = new ReplaceBiomeBlocks(this, this.chunkX, this.chunkZ, chunk, this.endWorld);
        MinecraftForge.EVENT_BUS.post(event);
        ci.cancel();
    }
}


text:
using System;
using Xamarin.Forms.Platform.iOS;
using Foundation;
using UIKit;
using Xamarin.Forms;
using CoreGraphics;
using KeyboardOverlap.Forms.Plugin.iOSUnified;
using System.Diagnostics;

[assembly: ExportRenderer (typeof(Page), typeof(KeyboardOverlapRenderer))]
namespace KeyboardOverlap.Forms.Plugin.iOSUnified
{
	[Preserve (AllMembers = true)]
	public class KeyboardOverlapRenderer : PageRenderer
	{
		NSObject _keyboardShowObserver;
		NSObject _keyboardHideObserver;
		private bool _pageWasShiftedUp;
		private double _activeViewBottom;
		private bool _isKeyboardShown;

		public static void Init ()
		{
			var now = DateTime.Now;
			Debug.WriteLine ("Keyboard Overlap plugin initialized {0}", now);
		}

		public override void ViewWillAppear (bool animated)
		{
			base.ViewWillAppear (animated);

			var page = Element as ContentPage;

			if (page != null) {
				var contentScrollView = page.Content as ScrollView;

				if (contentScrollView != null)
					return;

				RegisterForKeyboardNotifications ();
			}
		}

		public override void ViewWillDisappear (bool animated)
		{
			base.ViewWillDisappear (animated);

			UnregisterForKeyboardNotifications ();
		}

		void RegisterForKeyboardNotifications ()
		{
			if (_keyboardShowObserver == null)
				_keyboardShowObserver = NSNotificationCenter.DefaultCenter.AddObserver (UIKeyboard.WillShowNotification, OnKeyboardShow);
			if (_keyboardHideObserver == null)
				_keyboardHideObserver = NSNotificationCenter.DefaultCenter.AddObserver (UIKeyboard.WillHideNotification, OnKeyboardHide);
		}

		void UnregisterForKeyboardNotifications ()
		{
			_isKeyboardShown = false;
			if (_keyboardShowObserver != null) {
				NSNotificationCenter.DefaultCenter.RemoveObserver (_keyboardShowObserver);
				_keyboardShowObserver.Dispose ();
				_keyboardShowObserver = null;
			}

			if (_keyboardHideObserver != null) {
				NSNotificationCenter.DefaultCenter.RemoveObserver (_keyboardHideObserver);
				_keyboardHideObserver.Dispose ();
				_keyboardHideObserver = null;
			}
		}

		protected virtual void OnKeyboardShow (NSNotification notification)
		{
			if (!IsViewLoaded || _isKeyboardShown)
				return;

			_isKeyboardShown = true;
			var activeView = View.FindFirstResponder ();

			if (activeView == null)
				return;

			var keyboardFrame = UIKeyboard.FrameEndFromNotification (notification);
			var isOverlapping = activeView.IsKeyboardOverlapping (View, keyboardFrame);

			if (!isOverlapping)
				return;

			if (isOverlapping) {
				_activeViewBottom = activeView.GetViewRelativeBottom (View);
				ShiftPageUp (keyboardFrame.Height, _activeViewBottom);
			}
		}

		private void OnKeyboardHide (NSNotification notification)
		{
			if (!IsViewLoaded)
				return;

			_isKeyboardShown = false;
			var keyboardFrame = UIKeyboard.FrameEndFromNotification (notification);

			if (_pageWasShiftedUp) {
				ShiftPageDown (keyboardFrame.Height, _activeViewBottom);
			}
		}

		private void ShiftPageUp (nfloat keyboardHeight, double activeViewBottom)
		{
			var pageFrame = Element.Bounds;

			var newY = pageFrame.Y + CalculateShiftByAmount (pageFrame.Height, keyboardHeight, activeViewBottom);

			Element.LayoutTo (new Rectangle (pageFrame.X, newY,
				pageFrame.Width, pageFrame.Height));

			_pageWasShiftedUp = true;
		}

		private void ShiftPageDown (nfloat keyboardHeight, double activeViewBottom)
		{
			var pageFrame = Element.Bounds;

			var newY = pageFrame.Y - CalculateShiftByAmount (pageFrame.Height, keyboardHeight, activeViewBottom);

			Element.LayoutTo (new Rectangle (pageFrame.X, newY,
				pageFrame.Width, pageFrame.Height));

			_pageWasShiftedUp = false;
		}

		private double CalculateShiftByAmount (double pageHeight, nfloat keyboardHeight, double activeViewBottom)
		{
			return (pageHeight - activeViewBottom) - keyboardHeight;
		}
	}
}


text:
ANSIBLE_METADATA = {'metadata_version': '1.1',
                    'status': ['preview'],
                    'supported_by': 'community'}

DOCUMENTATION = '''
---
module: avi_alertemailconfig
author: Gaurav Rastogi (@grastogi23) <grastogi@avinetworks.com>

short_description: Module for setup of AlertEmailConfig Avi RESTful Object
description:
    - This module is used to configure AlertEmailConfig object
    - more examples at U(https://github.com/avinetworks/devops)
requirements: [ avisdk ]
version_added: "2.4"
options:
    state:
        description:
            - The state that should be applied on the entity.
        default: present
        choices: ["absent", "present"]
    avi_api_update_method:
        description:
            - Default method for object update is HTTP PUT.
            - Setting to patch will override that behavior to use HTTP PATCH.
        version_added: "2.5"
        default: put
        choices: ["put", "patch"]
    avi_api_patch_op:
        description:
            - Patch operation to use when using avi_api_update_method as patch.
        version_added: "2.5"
        choices: ["add", "replace", "delete"]
    cc_emails:
        description:
            - Alerts are copied to the comma separated list of  email recipients.
    description:
        description:
            - User defined description for the object.
    name:
        description:
            - A user-friendly name of the email notification service.
        required: true
    tenant_ref:
        description:
            - It is a reference to an object of type tenant.
    to_emails:
        description:
            - Alerts are sent to the comma separated list of  email recipients.
        required: true
    url:
        description:
            - Avi controller URL of the object.
    uuid:
        description:
            - Unique object identifier of the object.
extends_documentation_fragment:
    - avi
'''

EXAMPLES = """
- name: Example to create AlertEmailConfig object
  avi_alertemailconfig:
    controller: 10.10.25.42
    username: admin
    password: something
    state: present
    name: sample_alertemailconfig
"""

RETURN = '''
obj:
    description: AlertEmailConfig (api/alertemailconfig) object
    returned: success, changed
    type: dict
'''

from ansible.module_utils.basic import AnsibleModule
try:
    from ansible.module_utils.network.avi.avi import (
        avi_common_argument_spec, avi_ansible_api, HAS_AVI)
except ImportError:
    HAS_AVI = False

def main():
    argument_specs = dict(
        state=dict(default='present',
                   choices=['absent', 'present']),
        avi_api_update_method=dict(default='put',
                                   choices=['put', 'patch']),
        avi_api_patch_op=dict(choices=['add', 'replace', 'delete']),
        cc_emails=dict(type='str',),
        description=dict(type='str',),
        name=dict(type='str', required=True),
        tenant_ref=dict(type='str',),
        to_emails=dict(type='str', required=True),
        url=dict(type='str',),
        uuid=dict(type='str',),
    )
    argument_specs.update(avi_common_argument_spec())
    module = AnsibleModule(
        argument_spec=argument_specs, supports_check_mode=True)
    if not HAS_AVI:
        return module.fail_json(msg=(
            'Avi python API SDK (avisdk>=17.1) or requests is not installed. '
            'For more details visit https://github.com/avinetworks/sdk.'))
    return avi_ansible_api(module, 'alertemailconfig',
                           set([]))

if __name__ == '__main__':
    main()


text:
import '../../api/accounts/server/publications.js';
import '../../api/accounts/account';
import '../../api/accounts/methods';
import '../../api/courses/server/publications';
import '../../api/courses/methods';
import '../../api/units/server/publications';
import '../../api/units/methods';
import '../../api/topics/server/publications';
import '../../api/topics/methods';
import '../../api/resources/server/publications';
import '../../api/resources/methods';
import '../../api/settings/server/publications';
import '../../api/settings/methods';
import './init';
import '../../api/bookmarks/methods';
import '../../api/bookmarks/server/publications';
import '../../api/notifications/server/publications';
import '../../api/notifications/methods';
import '../../api/notifications/notifications';
import '../../api/feedback/server/publications';
import '../../api/feedback/methods';
import '../../api/search/server/publications';
import '../../api/search/methods';
import '../../api/statistics/server/publications';
import '../../api/statistics/csvMethods';
import '../../api/sync/methods';
import '../../api/sync/syncFile';
import '../../api/Deleted/methods';
import '../../api/Deleted/server/publications';
import '../../api/externallink/methods';
import '../../api/externallink/server/publications';
import '../../api/sync/endpoint';
import '../../api/sync/server/sync';
import '../../api/crons';
import '../../api/languages/methods';
import '../../api/Log/logger';


text:
<?php

namespace Drupal\webform\Plugin\WebformElement;

use Drupal\webform\WebformSubmissionInterface;

/**
 * Provides a 'textfield' element.
 *
 * @WebformElement(
 *   id = "textfield",
 *   api = "https://api.drupal.org/api/drupal/core!lib!Drupal!Core!Render!Element!Textfield.php/class/Textfield",
 *   label = @Translation("Text field"),
 *   description = @Translation("Provides a form element for input of a single-line text."),
 *   category = @Translation("Basic elements"),
 * )
 */
class TextField extends TextBase {

  /**
   * {@inheritdoc}
   */
  public function getDefaultProperties() {
    return parent::getDefaultProperties() + [
      'multiple' => FALSE,
      'multiple__header_label' => '',
      // Form display.
      'input_mask' => '',
      // Form validation.
      'counter_type' => '',
      'counter_maximum' => '',
      'counter_message' => '',
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function prepare(array &$element, WebformSubmissionInterface $webform_submission = NULL) {
    $element['#maxlength'] = (!isset($element['#maxlength'])) ? 255 : $element['#maxlength'];
    parent::prepare($element, $webform_submission);
  }

}


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

#nullable disable

using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Test.Utilities;
using Xunit;

namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations
{
    public class ExternKeywordRecommenderTests : KeywordRecommenderTests
    {
        [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
        public async Task TestAtRoot()
        {
            await VerifyKeywordAsync(
@"$$");
        }

        [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
        public async Task TestAfterClass()
        {
            await VerifyKeywordAsync(
@"class C { }
$$");
        }

        [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
        public async Task TestAfterGlobalStatement()
        {
            await VerifyKeywordAsync(
@"System.Console.WriteLine();
$$");
        }

        [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
        public async Task TestAfterGlobalVariableDeclaration()
        {
            await VerifyKeywordAsync(
@"int i = 0;
$$");
        }

        [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
        public async Task TestNotInUsingAlias()
        {
            await VerifyAbsenceAsync(
@"using Goo = $$");
        }

        [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
        public async Task TestNotInGlobalUsingAlias()
        {
            await VerifyAbsenceAsync(
@"global using Goo = $$");
        }

        [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
        [CombinatorialData]
        public async Task TestInEmptyStatement(bool topLevelStatement)
        {
            await VerifyKeywordAsync(AddInsideMethod(
@"$$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
        }

        [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
        [CombinatorialData]
        public async Task TestAfterStaticInStatement(bool topLevelStatement)
        {
            await VerifyKeywordAsync(AddInsideMethod(
@"static $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
        }

        [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
        [CombinatorialData]
        public async Task TestAfterAttributesInStatement(bool topLevelStatement)
        {
            await VerifyKeywordAsync(AddInsideMethod(
@"[Attr] $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
        }

        [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
        [CombinatorialData]
        public async Task TestAfterAttributesInSwitchCase(bool topLevelStatement)
        {
            await VerifyKeywordAsync(AddInsideMethod(
@"switch (c)
{
    case 0:
         [Foo]
         $$
}", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
        }

        [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
        [CombinatorialData]
        public async Task TestAfterAttributesAndStaticInStatement(bool topLevelStatement)
        {
            await VerifyKeywordAsync(AddInsideMethod(
@"[Attr] static $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
        }

        [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
        [CombinatorialData]
        public async Task TestBetweenAttributesAndReturnStatement(bool topLevelStatement)
        {
            await VerifyKeywordAsync(AddInsideMethod(
@"[Attr]
$$
return x;", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
        }

        [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
        [CombinatorialData]
        public async Task TestBetweenAttributesAndLocalDeclarationStatement(bool topLevelStatement)
        {
            await VerifyKeywordAsync(AddInsideMethod(
@"[Attr]
$$
x y = bar();", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
        }

        [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
        [CombinatorialData]
        public async Task TestBetweenAttributesAndAwaitExpression(bool topLevelStatement)
        {
            await VerifyKeywordAsync(AddInsideMethod(
@"[Attr]
$$
await bar;", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
        }

        [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
        [CombinatorialData]
        public async Task TestBetweenAttributesAndAssignmentStatement(bool topLevelStatement)
        {
            await VerifyKeywordAsync(AddInsideMethod(
@"[Foo]
$$
y = bar();", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
        }

        [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
        [CombinatorialData]
        public async Task TestBetweenAttributesAndCallStatement(bool topLevelStatement)
        {
            await VerifyKeywordAsync(AddInsideMethod(
@"[Foo]
$$
bar();", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
        }

        [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
        [CombinatorialData]
        public async Task TestNotAfterExternInStatement(bool topLevelStatement)
        {
            await VerifyAbsenceAsync(AddInsideMethod(
@"extern $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
        }

        [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
        public async Task TestNotAfterExternKeyword()
            => await VerifyAbsenceAsync(@"extern $$");

        [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
        public async Task TestAfterPreviousExternAlias()
        {
            await VerifyKeywordAsync(
@"extern alias Goo;
$$");
        }

        [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
        public async Task TestAfterUsing()
        {
            await VerifyKeywordAsync(@"using Goo;
$$");
        }

        [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
        public async Task TestAfterGlobalUsing()
        {
            await VerifyKeywordAsync(
@"global using Goo;
$$");
        }

        [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
        public async Task TestAfterNamespace()
        {
            await VerifyKeywordAsync(@"namespace N {}
$$");
        }

        [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
        public async Task TestInsideNamespace()
        {
            await VerifyKeywordAsync(
@"namespace N {
    $$");
        }

        [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
        public async Task TestNotAfterExternKeyword_InsideNamespace()
        {
            await VerifyAbsenceAsync(@"namespace N {
    extern $$");
        }

        [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
        public async Task TestAfterPreviousExternAlias_InsideNamespace()
        {
            await VerifyKeywordAsync(
@"namespace N {
   extern alias Goo;
   $$");
        }

        [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
        public async Task TestNotAfterUsing_InsideNamespace()
        {
            await VerifyAbsenceAsync(@"namespace N {
    using Goo;
    $$");
        }

        [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
        public async Task TestNotAfterMember_InsideNamespace()
        {
            await VerifyAbsenceAsync(@"namespace N {
    class C {}
    $$");
        }

        [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
        public async Task TestNotAfterNamespace_InsideNamespace()
        {
            await VerifyAbsenceAsync(@"namespace N {
    namespace N {}
    $$");
        }

        [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
        public async Task TestInClass()
        {
            await VerifyKeywordAsync(
@"class C {
    $$");
        }

        [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
        public async Task TestInStruct()
        {
            await VerifyKeywordAsync(
@"struct S {
    $$");
        }

        [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
        public async Task TestInInterface()
        {
            await VerifyKeywordAsync(
@"interface I {
    $$");
        }

        [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
        public async Task TestNotAfterAbstract()
        {
            await VerifyAbsenceAsync(
@"class C {
    abstract $$");
        }

        [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
        public async Task TestNotAfterExtern()
        {
            await VerifyAbsenceAsync(
@"class C {
    extern $$");
        }

        [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
        public async Task TestAfterPublic()
        {
            await VerifyKeywordAsync(
@"class C {
    public $$");
        }
    }
}


text:
<?php

declare(strict_types=1);

namespace Doctrine\ORM\Mapping\Factory;

use Doctrine\ORM\Reflection\ReflectionService;
use Doctrine\ORM\Reflection\RuntimeReflectionService;

/**
 * RuntimeClassMetadataFactory is the ClassMetadata object creation factory that runs at
 * execution time, consuming pre-exising entity classes.
 */
class RuntimeClassMetadataFactory extends AbstractClassMetadataFactory
{
    /** @var RuntimeReflectionService */
    private $reflectionService;

    protected function getReflectionService() : ReflectionService
    {
        if (! $this->reflectionService) {
            $this->reflectionService = new RuntimeReflectionService();
        }

        return $this->reflectionService;
    }
}