text:
using namespace chrono;
using namespace chrono::vehicle;
using namespace chrono::vehicle::generic;

// =============================================================================

// Initial front_side position
ChVector<> initLoc(0, 0, 0.5);

// Initial front_side orientation
ChQuaternion<> initRot = Q_from_AngZ(CH_C_PI / 10);

// Type of tire model (RIGID or FIALA)
TireModelType tire_model = TireModelType::FIALA;

// Rigid terrain dimensions
double terrainHeight = 0;
double terrainLength = 100.0;  // size in X direction
double terrainWidth = 100.0;   // size in Y direction

// Simulation step size
double step_size = 0.001;

// Time interval between two render frames
double render_step_size = 1.0 / 50;  // FPS = 50

// Point on chassis tracked by the camera
ChVector<> trackPoint(0.0, 0.0, 1.75);

// =============================================================================

int main(int argc, char* argv[]) {
    GetLog() << "Copyright (c) 2017 projectchrono.org\nChrono version: " << CHRONO_VERSION << "\n\n";

    // --------------------------
    // Create the various modules
    // --------------------------

    // Create the front side
    Articulated_Front front_side(false);
    front_side.Initialize(ChCoordsys<>(initLoc, initRot));
    front_side.SetChassisVisualizationType(VisualizationType::PRIMITIVES);
    front_side.SetSuspensionVisualizationType(VisualizationType::PRIMITIVES);
    front_side.SetSteeringVisualizationType(VisualizationType::PRIMITIVES);
    front_side.SetWheelVisualizationType(VisualizationType::NONE);

    // Create the rear side
    Articulated_Rear rear_side(std::static_pointer_cast<Articulated_Chassis>(front_side.GetChassis()));
    rear_side.Initialize();
    rear_side.SetSuspensionVisualizationType(VisualizationType::PRIMITIVES);
    rear_side.SetWheelVisualizationType(VisualizationType::NONE);

    // Create the terrain
    RigidTerrain terrain(front_side.GetSystem());
    auto patch = terrain.AddPatch(ChCoordsys<>(ChVector<>(0, 0, terrainHeight - 5), QUNIT),
                                  ChVector<>(terrainLength, terrainWidth, 10));
    patch->SetContactFrictionCoefficient(0.9f);
    patch->SetContactRestitutionCoefficient(0.01f);
    patch->SetContactMaterialProperties(2e7f, 0.3f);
    patch->SetColor(ChColor(0.5f, 0.5f, 1));
    patch->SetTexture(vehicle::GetDataFile("terrain/textures/tile4.jpg"), 200, 200);
    terrain.Initialize();

    // Create and initialize the powertrain system
    Generic_SimplePowertrain powertrain("Powertrain");
    powertrain.Initialize(front_side.GetChassisBody(), front_side.GetDriveshaft());

    // Create the front tires
    std::unique_ptr<ChTire> tire_FL;
    std::unique_ptr<ChTire> tire_FR;
    switch (tire_model) {
        case TireModelType::RIGID:
            tire_FL = std::unique_ptr<ChTire>(new Generic_RigidTire("FL"));
            tire_FR = std::unique_ptr<ChTire>(new Generic_RigidTire("FR"));
            break;
        case TireModelType::FIALA:
            tire_FL = std::unique_ptr<ChTire>(new Generic_FialaTire("FL"));
            tire_FR = std::unique_ptr<ChTire>(new Generic_FialaTire("FR"));
            break;
        default:
            std::cout << "Tire type not supported!" << std::endl;
            return 1;
    }

    tire_FL->Initialize(front_side.GetWheelBody(FRONT_LEFT), LEFT);
    tire_FR->Initialize(front_side.GetWheelBody(FRONT_RIGHT), RIGHT);
    tire_FL->SetVisualizationType(VisualizationType::PRIMITIVES);
    tire_FR->SetVisualizationType(VisualizationType::PRIMITIVES);

    // Create the rear tires
    std::unique_ptr<ChTire> tire_RL;
    std::unique_ptr<ChTire> tire_RR;
    switch (tire_model) {
        case TireModelType::RIGID:
            tire_RL = std::unique_ptr<ChTire>(new Generic_RigidTire("RL"));
            tire_RR = std::unique_ptr<ChTire>(new Generic_RigidTire("RR"));
            break;
        case TireModelType::FIALA:
            tire_RL = std::unique_ptr<ChTire>(new Generic_FialaTire("RL"));
            tire_RR = std::unique_ptr<ChTire>(new Generic_FialaTire("RR"));
            break;
        default:
            std::cout << "Tire type not supported!" << std::endl;
            return 1;
    }

    tire_RL->Initialize(rear_side.GetWheelBody(FRONT_LEFT), LEFT);
    tire_RR->Initialize(rear_side.GetWheelBody(FRONT_RIGHT), RIGHT);
    tire_RL->SetVisualizationType(VisualizationType::PRIMITIVES);
    tire_RR->SetVisualizationType(VisualizationType::PRIMITIVES);

    // Initialize Irrlicht app
    ChWheeledVehicleIrrApp app(&front_side, &powertrain, L"Articulated Vehicle Demo");
    app.SetSkyBox();
    app.AddTypicalLights(irr::core::vector3df(30.f, -30.f, 100.f), irr::core::vector3df(30.f, 50.f, 100.f), 250, 130);
    app.SetChaseCamera(trackPoint, 6.0, 0.5);

    app.SetTimestep(step_size);

    app.AssetBindAll();
    app.AssetUpdateAll();

    // Initialize interactive driver
    ChIrrGuiDriver driver(app);

    // Set the time response for steering and throttle keyboard inputs.
    // NOTE: this is not exact, since we do not render quite at the specified FPS.
    double steering_time = 1.0;  // time to go from 0 to +1 (or from 0 to -1)
    double throttle_time = 1.0;  // time to go from 0 to +1
    double braking_time = 0.3;   // time to go from 0 to +1
    driver.SetSteeringDelta(render_step_size / steering_time);
    driver.SetThrottleDelta(render_step_size / throttle_time);
    driver.SetBrakingDelta(render_step_size / braking_time);

    driver.Initialize();

    // ---------------
    // Simulation loop
    // ---------------

    // Inter-module communication data
    TerrainForces tire_front_forces(2);
    TerrainForces tire_rear_forces(2);
    double driveshaft_speed;
    double powertrain_torque;
    double throttle_input;
    double steering_input;
    double braking_input;

    // Number of simulation steps between two 3D view render frames
    int render_steps = (int)std::ceil(render_step_size / step_size);

    // Initialize simulation frame counter and simulation time
    int step_number = 0;
    double time = 0;

    while (app.GetDevice()->run()) {
        // Render scene
        if (step_number % render_steps == 0) {
            app.BeginScene(true, true, irr::video::SColor(255, 140, 161, 192));
            app.DrawAll();
            app.EndScene();
        }

        // Collect output data from modules (for inter-module communication)
        throttle_input = driver.GetThrottle();
        steering_input = driver.GetSteering();
        braking_input = driver.GetBraking();

        powertrain_torque = powertrain.GetOutputTorque();

        tire_front_forces[0] = tire_FL->GetTireForce();
        tire_front_forces[1] = tire_FR->GetTireForce();
        tire_rear_forces[0] = tire_RL->GetTireForce();
        tire_rear_forces[1] = tire_RR->GetTireForce();

        driveshaft_speed = front_side.GetDriveshaftSpeed();

        WheelState wheel_FL = front_side.GetWheelState(FRONT_LEFT);
        WheelState wheel_FR = front_side.GetWheelState(FRONT_RIGHT);

        WheelState wheel_RL = rear_side.GetWheelState(FRONT_LEFT);
        WheelState wheel_RR = rear_side.GetWheelState(FRONT_RIGHT);

        // Update modules (process inputs from other modules)
        time = front_side.GetSystem()->GetChTime();

        driver.Synchronize(time);

        terrain.Synchronize(time);

        tire_FL->Synchronize(time, wheel_FL, terrain);
        tire_FR->Synchronize(time, wheel_FR, terrain);
        tire_RL->Synchronize(time, wheel_RL, terrain);
        tire_RR->Synchronize(time, wheel_RR, terrain);

        powertrain.Synchronize(time, throttle_input, driveshaft_speed);

        front_side.Synchronize(time, steering_input, braking_input, powertrain_torque, tire_front_forces);
        rear_side.Synchronize(time, steering_input, braking_input, tire_rear_forces);

        app.Synchronize(driver.GetInputModeAsString(), steering_input, throttle_input, braking_input);

        // Advance simulation for one timestep for all modules
        driver.Advance(step_size);

        terrain.Advance(step_size);

        tire_FL->Advance(step_size);
        tire_FR->Advance(step_size);
        tire_RL->Advance(step_size);
        tire_RR->Advance(step_size);

        powertrain.Advance(step_size);

        front_side.Advance(step_size);

        app.Advance(step_size);

        // Increment frame number
        step_number++;
    }

    return 0;
}


text:
require 'ruremai/mean'

class Object
  def mean?(*args)
    if args.empty?
      return Ruremai::Mean.new(self)
    else
      args.each do |method|
        self.method(method.to_sym).rurema!
      end
    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
from __future__ import (absolute_import, division, print_function,
                        unicode_literals)

import re
import glob
import os
import shutil
import sys
import datetime
import json

import six
import pytest

from os.path import abspath, dirname, join, isfile, relpath

from asv import config, environment, util
from asv.results import iter_results_for_machine
from asv.util import check_output, which

from . import tools
from .tools import dummy_packages, get_default_environment_type

dummy_values = (
    (6, 1),
    (6, 6),
    (6, 6),
)

def generate_basic_conf(tmpdir, repo_subdir='', values=dummy_values, dummy_packages=True):
    tmpdir = six.text_type(tmpdir)
    local = abspath(dirname(__file__))
    os.chdir(tmpdir)

    # Use relative paths on purpose since this is what will be in
    # actual config files

    shutil.copytree(os.path.join(local, 'benchmark'), 'benchmark')

    machine_file = join(tmpdir, 'asv-machine.json')

    shutil.copyfile(join(local, 'asv-machine.json'),
                    machine_file)

    repo_path = tools.generate_test_repo(tmpdir, values,
                                         subdir=repo_subdir).path

    if dummy_packages:
        matrix = {
            "asv_dummy_test_package_1": [""],
            "asv_dummy_test_package_2": tools.DUMMY2_VERSIONS,
        }
    else:
        matrix = {}

    conf_dict = {
        'env_dir': 'env',
        'benchmark_dir': 'benchmark',
        'results_dir': 'results_workflow',
        'html_dir': 'html',
        'repo': relpath(repo_path),
        'dvcs': 'git',
        'project': 'asv',
        'matrix': matrix,
    }
    if repo_subdir:
        conf_dict['repo_subdir'] = repo_subdir

    conf = config.Config.from_json(conf_dict)

    if hasattr(sys, 'pypy_version_info'):
        conf.pythons = ["pypy{0[0]}.{0[1]}".format(sys.version_info)]

    return tmpdir, local, conf, machine_file

@pytest.fixture
def basic_conf(tmpdir, dummy_packages):
    return generate_basic_conf(tmpdir)

def test_run_publish(capfd, basic_conf):
    tmpdir, local, conf, machine_file = basic_conf
    tmpdir = util.long_path(tmpdir)

    conf.matrix = {
        "req": dict(conf.matrix),
        "env":{"SOME_TEST_VAR": ["1"]},
    }

    # Tests a typical complete run/publish workflow
    tools.run_asv_with_conf(conf, 'run', "master", '--steps=2',
                            '--quick', '--show-stderr', '--profile',
                            '-a', 'warmup_time=0',
                            '--durations=5',
                            _machine_file=machine_file)
    text, err = capfd.readouterr()

    assert len(os.listdir(join(tmpdir, 'results_workflow', 'orangutan'))) == 5
    assert len(os.listdir(join(tmpdir, 'results_workflow'))) == 2
    assert 'asv: benchmark timed out (timeout 0.1s)' in text
    assert 'total duration' in text

    tools.run_asv_with_conf(conf, 'publish')

    assert isfile(join(tmpdir, 'html', 'index.html'))
    assert isfile(join(tmpdir, 'html', 'index.json'))
    assert isfile(join(tmpdir, 'html', 'asv.js'))
    assert isfile(join(tmpdir, 'html', 'asv.css'))

    # Check parameterized test json data format
    filename = glob.glob(join(tmpdir, 'html', 'graphs', 'arch-x86_64',
                              'asv_dummy_test_package_1',
                              'asv_dummy_test_package_2-' + tools.DUMMY2_VERSIONS[1],
                              'branch-master',
                              'cpu-Blazingly fast',
                              'env-SOME_TEST_VAR-1',
                              'machine-orangutan',
                              'os-GNU_Linux', 'python-*', 'ram-128GB',
                              'params_examples.time_skip.json'))[0]
    with open(filename, 'r') as fp:
        data = json.load(fp)
        assert len(data) == 2
        assert isinstance(data[0][0], six.integer_types)  # revision
        assert len(data[0][1]) == 3
        assert len(data[1][1]) == 3
        assert isinstance(data[0][1][0], float)
        assert isinstance(data[0][1][1], float)
        assert data[0][1][2] is None

    # Check that the skip options work
    capfd.readouterr()
    tools.run_asv_with_conf(conf, 'run', "master", '--steps=2',
                            '--quick', '--skip-existing-successful',
                            '--bench=time_secondary.track_value',
                            '--skip-existing-failed',
                            _machine_file=join(tmpdir, 'asv-machine.json'))
    tools.run_asv_with_conf(conf, 'run', "master", '--steps=2',
                            '--bench=time_secondary.track_value',
                            '--quick', '--skip-existing-commits',
                            _machine_file=join(tmpdir, 'asv-machine.json'))
    text, err = capfd.readouterr()
    assert 'Running benchmarks.' not in text

    # Check EXISTING and --environment work
    python = "{0[0]}.{0[1]}".format(sys.version_info)
    env_type = get_default_environment_type(conf, python)
    env_spec = ("-E", env_type + ":" + python)
    tools.run_asv_with_conf(conf, 'run', "EXISTING", '--quick',
                            '--bench=time_secondary.track_value',
                            *env_spec,
                            _machine_file=machine_file)

    # Remove the benchmarks.json file and check publish fails

    os.remove(join(tmpdir, "results_workflow", "benchmarks.json"))

    with pytest.raises(util.UserError):
        tools.run_asv_with_conf(conf, 'publish')


text:
namespace v8 {
namespace internal {
namespace interpreter {

class BytecodeGenerator final : public AstVisitor {
 public:
  BytecodeGenerator(Isolate* isolate, Zone* zone);

  Handle<BytecodeArray> MakeBytecode(CompilationInfo* info);

#define DECLARE_VISIT(type) void Visit##type(type* node) override;
  AST_NODE_LIST(DECLARE_VISIT)
#undef DECLARE_VISIT

  // Visiting function for declarations list and statements are overridden.
  void VisitDeclarations(ZoneList<Declaration*>* declarations) override;
  void VisitStatements(ZoneList<Statement*>* statments) override;

 private:
  class ContextScope;
  class ControlScope;
  class ControlScopeForBreakable;
  class ControlScopeForIteration;
  class ExpressionResultScope;
  class EffectResultScope;
  class AccumulatorResultScope;
  class RegisterResultScope;
  class RegisterAllocationScope;

  void MakeBytecodeBody();
  Register NextContextRegister() const;

  DEFINE_AST_VISITOR_SUBCLASS_MEMBERS();

  // Dispatched from VisitBinaryOperation.
  void VisitArithmeticExpression(BinaryOperation* binop);
  void VisitCommaExpression(BinaryOperation* binop);
  void VisitLogicalOrExpression(BinaryOperation* binop);
  void VisitLogicalAndExpression(BinaryOperation* binop);

  // Dispatched from VisitUnaryOperation.
  void VisitVoid(UnaryOperation* expr);
  void VisitTypeOf(UnaryOperation* expr);
  void VisitNot(UnaryOperation* expr);
  void VisitDelete(UnaryOperation* expr);

  // Used by flow control routines to evaluate loop condition.
  void VisitCondition(Expression* expr);

  // Helper visitors which perform common operations.
  Register VisitArguments(ZoneList<Expression*>* arguments);

  void VisitPropertyLoad(Register obj, Property* expr);
  void VisitPropertyLoadForAccumulator(Register obj, Property* expr);

  void VisitVariableLoad(Variable* variable, FeedbackVectorSlot slot,
                         TypeofMode typeof_mode = NOT_INSIDE_TYPEOF);
  void VisitVariableLoadForAccumulatorValue(
      Variable* variable, FeedbackVectorSlot slot,
      TypeofMode typeof_mode = NOT_INSIDE_TYPEOF);
  MUST_USE_RESULT Register
  VisitVariableLoadForRegisterValue(Variable* variable, FeedbackVectorSlot slot,
                                    TypeofMode typeof_mode = NOT_INSIDE_TYPEOF);
  void VisitVariableAssignment(Variable* variable, FeedbackVectorSlot slot);

  void VisitArgumentsObject(Variable* variable);
  void VisitThisFunctionVariable(Variable* variable);
  void VisitNewTargetVariable(Variable* variable);
  void VisitNewLocalFunctionContext();
  void VisitBuildLocalActivationContext();
  void VisitNewLocalBlockContext(Scope* scope);
  void VisitFunctionClosureForContext();
  void VisitSetHomeObject(Register value, Register home_object,
                          ObjectLiteralProperty* property, int slot_number = 0);
  void VisitObjectLiteralAccessor(Register home_object,
                                  ObjectLiteralProperty* property,
                                  Register value_out);
  void VisitForInAssignment(Expression* expr, FeedbackVectorSlot slot);

  // Visitors for obtaining expression result in the accumulator, in a
  // register, or just getting the effect.
  void VisitForAccumulatorValue(Expression* expression);
  MUST_USE_RESULT Register VisitForRegisterValue(Expression* expression);
  void VisitForEffect(Expression* node);

  // Methods for tracking and remapping register.
  void RecordStoreToRegister(Register reg);
  Register LoadFromAliasedRegister(Register reg);

  inline BytecodeArrayBuilder* builder() { return &builder_; }

  inline Isolate* isolate() const { return isolate_; }
  inline Zone* zone() const { return zone_; }

  inline Scope* scope() const { return scope_; }
  inline void set_scope(Scope* scope) { scope_ = scope; }
  inline CompilationInfo* info() const { return info_; }
  inline void set_info(CompilationInfo* info) { info_ = info; }

  inline ControlScope* execution_control() const { return execution_control_; }
  inline void set_execution_control(ControlScope* scope) {
    execution_control_ = scope;
  }
  inline ContextScope* execution_context() const { return execution_context_; }
  inline void set_execution_context(ContextScope* context) {
    execution_context_ = context;
  }
  inline void set_execution_result(ExpressionResultScope* execution_result) {
    execution_result_ = execution_result;
  }
  ExpressionResultScope* execution_result() const { return execution_result_; }
  inline void set_register_allocator(
      RegisterAllocationScope* register_allocator) {
    register_allocator_ = register_allocator;
  }
  RegisterAllocationScope* register_allocator() const {
    return register_allocator_;
  }

  ZoneVector<Handle<Object>>* globals() { return &globals_; }
  inline LanguageMode language_mode() const;
  Strength language_mode_strength() const;
  int feedback_index(FeedbackVectorSlot slot) const;

  Isolate* isolate_;
  Zone* zone_;
  BytecodeArrayBuilder builder_;
  CompilationInfo* info_;
  Scope* scope_;
  ZoneVector<Handle<Object>> globals_;
  ControlScope* execution_control_;
  ContextScope* execution_context_;
  ExpressionResultScope* execution_result_;
  RegisterAllocationScope* register_allocator_;
};

}  // namespace interpreter
}  // namespace internal
}  // namespace v8

#endif  // V8_INTERPRETER_BYTECODE_GENERATOR_H_


text:
var expect = require("expect.js")
,   w3c = require("..")
;

if (!process.env.W3CAPIKEY) {
    console.error("No API key has been set, make sure you defined the W3CAPIKEY environment variable.");
    process.exit(1);
}
w3c.apiKey = process.env.W3CAPIKEY;

function listChecker (done, title, field = 'title') {
    return function (err, data) {
        expect(err).to.not.be.ok();
        expect(data).to.be.an("array");
        if (title) expect(data.some(function (it) { return it[field] === title; })).to.be.ok();
        done();
    };
}

function embedChecker (done, field, value) {
    return function (err, data) {
        expect(err).to.not.be.ok();
        expect(data).to.be.an("array");
        expect(data.some(function (it) { return it[field] === value; })).to.be.ok();
        done();
    };
}

function itemChecker (done, field, value) {
    return function (err, data) {
        expect(err).to.not.be.ok();
        expect(data[field]).to.equal(value);
        done();
    };
}

describe('Functions', function () {
    it('can be listed', function (done) {
        w3c.functions().fetch(listChecker(done, 'Systems'));
    });
    it('can be fetched', function (done) {
        w3c.function(122803).fetch(itemChecker(done, 'name', 'Systems'));
    });
    it('have services', function (done) {
        w3c.function(122803).services().fetch(listChecker(done, 'Issue Tracking'));
    });
    it('have users', function (done) {
        w3c.function(122803).users().fetch(listChecker(done, 'Laurent Carcone'));
    });
});

describe("Groups", function () {
    it("can be listed", function (done) {
        w3c.groups().fetch(listChecker(done, "Cascading Style Sheets (CSS) Working Group"));
    });
    it("can be fetched", function (done) {
        w3c.group(32061).fetch(itemChecker(done, "name", "Cascading Style Sheets (CSS) Working Group"));
    });
    it("can be fetched with string", function (done) {
        w3c.group("32061").fetch(itemChecker(done, "name", "Cascading Style Sheets (CSS) Working Group"));
    });
    it("can be fetched with type/shortname", function (done) {
        w3c.group({type: "wg", shortname: "css"}).fetch(itemChecker(done, "name", "Cascading Style Sheets (CSS) Working Group"));
    });
    it("have chairs", function (done) {
        w3c.group(32061).chairs().fetch(listChecker(done, "Rossen Atanassov"));
    });
    it("have chairs with type/shortname", function (done) {
        w3c.group({type: "wg", shortname: "css"}).chairs().fetch(listChecker(done, "Rossen Atanassov"));
    });
    it("have services", function (done) {
        w3c.group(32061).services().fetch(listChecker(done, "Wiki"));
    });
    it("have services with type/shortname", function (done) {
        w3c.group({type: "wg", shortname: "css"}).services().fetch(listChecker(done, "Wiki"));
    });
    it("have specifications", function (done) {
        w3c.group(32061).specifications().fetch(listChecker(done, "Selectors Level 3"));
    });
    it("have specifications with type/shortname", function (done) {
        w3c.group({type: "wg", shortname: "css"}).specifications().fetch(listChecker(done, "Selectors Level 3"));
    });
    it("have teamcontacts", function (done) {
        w3c.group(32061).teamcontacts().fetch(listChecker(done, "Chris Lilley"));
    });
    it("have teamcontacts with type/shortname", function (done) {
        w3c.group({type: "wg", shortname: "css"}).teamcontacts().fetch(listChecker(done, "Chris Lilley"));
    });
    it("have users", function (done) {
        w3c.group(32061).users().fetch(listChecker(done, "Tab Atkins Jr."));
    });
    it("have users with type/shortname", function (done) {
        w3c.group({type: "wg", shortname: "css"}).users().fetch(listChecker(done, "Tab Atkins Jr."));
    });
    it("have charters", function (done) {
        w3c.group(32061).charters().fetch(listChecker(done));
    });
    it("have charters with type/shortname", function (done) {
        w3c.group({type: "wg", shortname: "css"}).charters().fetch(listChecker(done));
    });
    it("have charters that can be fetched", function (done) {
        w3c.group(32061).charter(102).fetch(itemChecker(done, "end", "1999-02-28"));
    });
    it("have charters that can be fetched with type/shortname", function (done) {
        w3c.group({type: "wg", shortname: "css"}).charter(102).fetch(itemChecker(done, "end", "1999-02-28"));
    });
    it("have participations", function (done) {
        w3c.group(32061).participations().fetch(listChecker(done));
    });
    it("have participations with type/shortname", function (done) {
        w3c.group({type: "wg", shortname: "css"}).participations().fetch(listChecker(done));
    });
});

describe("Services", function () {
    it("can be fetched", function (done) {
        w3c.service(2).fetch(itemChecker(done, "type", "tracker"));
    });
    it("have groups", function (done) {
        w3c.service(2).groups().fetch(listChecker(done, "Systems"));
    });
});

describe("Specifications", function () {
    it("can be listed", function (done) {
        w3c.specifications().fetch(listChecker(done, "SVG Paths"));
    });
    it("can be fetched", function (done) {
        w3c.specification("rex").fetch(itemChecker(done, "shortname", "rex"));
    });
    it("have superseded", function (done) {
        w3c.specification("SVG").superseded().fetch(listChecker(done, "Scalable Vector Graphics (SVG) 1.1 (Second Edition)"));
    });
    it("have supersedes", function (done) {
        w3c.specification("SVG11").supersedes().fetch(listChecker(done, "Scalable Vector Graphics (SVG) 1.0 Specification"));
    });
    it("have latest", function (done) {
        w3c.specification("SVG11").latest().fetch(itemChecker(done, "date", "2011-08-16"));
    });
});

describe("Specifications Version", function () {
    it("can be listed", function (done) {
        w3c.specification("SVG11").versions().fetch(listChecker(done, "Scalable Vector Graphics (SVG) 1.1 Specification"));
    });
    it("can be fetched", function (done) {
        w3c.specification("SVG11").version("20030114").fetch(itemChecker(done, "date", "2003-01-14"));
    });
    it("have deliverers", function (done) {
        w3c.specification("SVG11").version("20030114").deliverers().fetch(listChecker(done, "SVG Working Group"));
    });
    it("have editors", function (done) {
        w3c.specification("SVG11").version("20030114").editors().fetch(listChecker(done, "Dean Jackson"));
    });
    it("have successors", function (done) {
        w3c.specification("CSS21").version("20070719").successors().fetch(listChecker(done, "Candidate Recommendation Snapshot"));
    });
    it("have predecessors", function (done) {
        w3c.specification("CSS21").version("20090423").predecessors().fetch(listChecker(done, "Candidate Recommendation Snapshot"));
    });
});

describe("Users", function () {
    var ian = "ggdj8tciu9kwwc4o4ww888ggkwok0c8";
    it("can be fetched", function (done) {
        w3c.user(ian).fetch(itemChecker(done, "given", "Ian"));
    });
    it("can be retrieved by github account id", function (done) {
        // this is jean-gui
        w3c.user({type: 'github', id: '1479073'}).fetch(itemChecker(done, "given", "Jean-Guilhem"));
    });
    it("have affiliations", function (done) {
        w3c.user(ian).affiliations().fetch(listChecker(done));
    });
    it("have groups", function (done) {
        w3c.user(ian).groups().fetch(listChecker(done, "Community Groups Development Lead"));
    });
    it("have participations", function (done) {
        w3c.user(ian).participations().fetch(listChecker(done, "Web Payment Security Interest Group"));
    });
    it("have specifications", function (done) {
        w3c.user(ian).specifications().fetch(listChecker(done, "Accessibility Features of CSS"));
    });
    it("is team contact of", function (done) {
        w3c.user(ian).teamcontactofgroups().fetch(listChecker(done, "Web Payment Security Interest Group"));
    });
});

describe('Affiliations', function () {
    const STAFF = 52794;
    it('can be listed', function (done) {
        w3c.affiliations().fetch(listChecker(done, 'Framkom (Forskningsaktiebolaget Medie-och Kommunikationsteknik)'));
    });
    it('can be fetched', function (done) {
        w3c.affiliation(STAFF).fetch(itemChecker(done, 'name', 'W3C'));
    });
    it('have participants', function (done) {
        w3c.affiliation(STAFF).participants().fetch(listChecker(done, 'Kazuyuki Ashimura'));
    });
    it('have participations', function (done) {
        w3c.affiliation(STAFF).participations().fetch(listChecker(done, 'Accessibility Guidelines Working Group'));
    });
});

describe('Participations', function () {
    const PARTICIPATION = 656;
    it('can be fetched', function (done) {
        w3c.participation(PARTICIPATION).fetch(itemChecker(done, 'created', '2011-10-24 08:50:51'));
    });
});

describe('Translations', function () {
     const XHTMLBASIC_CA = 24;
    it("can be listed", function (done) {
        w3c.translations().fetch(listChecker(done, "XHTML™ Basic"));
    });
    it('can be fetched', function (done) {
        w3c.translation(XHTMLBASIC_CA).fetch(itemChecker(done, 'language', 'ca'));
    });
});

describe('Call for translations', function () {
     const XHTMLBASIC = 13;
    it("can be listed", function (done) {
        w3c.callsfortranslation().fetch(listChecker(done, "XHTML™ Basic"));
    });
    it('can be fetched', function (done) {
        w3c.callfortranslation(XHTMLBASIC).fetch(itemChecker(done, 'title', 'XHTML™ Basic'));
    });
});

describe('Non-participant licensing commitments', function () {
   it("can be fetched", function (done) {
       w3c.nplcs().fetch(listChecker(done, 9252268, 'repoId'));
   });
   it('can be fetched', function (done) {
       w3c.nplc({repoId: 9252268, pr: 4575}).fetch(itemChecker(done, 'repository-id', 9252268));
   });
});

describe('Specifications by status', function () {
    it("can be listed", function (done) {
        w3c.specificationsByStatus("Recommendation").fetch(listChecker(done, "Webmention"));
    });
});

describe("Embeds", function () {
    it('apply to functions', function (done) {
        w3c.functions().fetch({ embed: true }, embedChecker(done, 'name', 'Management'));
    });
    it("apply to groups", function (done) {
        w3c.groups().fetch({ embed: true }, embedChecker(done, "type", "community group"));
    });
    it("apply to specifications", function (done) {
        w3c.specifications().fetch({ embed: true }, embedChecker(done, "shortname", "wbxml"));
    });
});

describe("Specification Series", function() {
    const CSSCOLOR = 'css-color';
    it('can be fetched', function (done) {
        w3c.specificationseries(CSSCOLOR).fetch(itemChecker(done, 'shortname', CSSCOLOR));
    });
    it("have specifications", function (done) {
        w3c.specificationseries(CSSCOLOR).specifications().fetch(listChecker(done, "CSS Color Module Level 3"));
    });
});

describe("Promises API", function() {
    it('returns a promise if no callback is set', async function() {
        const groups = await w3c.groups().fetch();
        expect(groups).to.be.an("array");
        expect(groups.some(function (it) { return it.title === "Cascading Style Sheets (CSS) Working Group"; })).to.be.ok();
    });
});


text:
from __future__ import unicode_literals

from django.db import migrations, models

class Migration(migrations.Migration):

    initial = True

    dependencies = [
    ]

    operations = [
        migrations.CreateModel(
            name='CookieCutterLocationToStepMapping',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('location', models.CharField(max_length=100)),
                ('main_module', models.CharField(max_length=100)),
            ],
        ),
        migrations.CreateModel(
            name='CookieCutterTemplate',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('location', models.CharField(max_length=255)),
                ('name', models.CharField(max_length=100)),
                ('meant_for', models.CharField(choices=[('e', 'Experiment'), ('p', 'Package')], default='e', max_length=10)),
                ('folder_file_locations', models.ManyToManyField(to='cookiecutter_manager.CookieCutterLocationToStepMapping')),
            ],
        ),
    ]


text:
define([
  "$J",
  "sinon",
  "cali-calcu/interpreter/mBasic/For",
  "cali-calcu/CommandParser",
  "../../dev/Matchers"
], function ($J, sinon, For, CommandParser, Matchers) {

  $J.describe("cali.calcu.interpreter.mBasic.For", function () {

    // setup the environment
    var parser = null; // the parser
    $J.beforeEach(function () {
      parser = new CommandParser();
      // this gives the toBeMatrixCloseTo function
      $J.jasmine.Expectation.addMatchers(Matchers);
      epsilon = 1e-9;
    });

    // it("should exist in the namespace", function() {
    // 	expect(typeof For).toEqual("function");
    // });

    $J.describe("new For(input, position, parent, operators)", function () {
      $J.describe("creates an new expression for the test arg", function () {
        $J.it("should have arg[0] as an expression without parens", function () {
          var input = "for x = 1:10 \n y = y + 1; \n end\n";
          var args = parser.preprocess(input);
          var exp = new For(args, 0, null, parser.operators);
          $J.expect(exp.args[0].type).toEqual("EXPRESSION");
          $J.expect(exp.args[0].output).toEqual("x");
        });

        $J.it("should have arg[0] as an expression with parens", function () {
          var input = "for( x = 1:10 )\n y = y + 1; \n end\n";
          var args = parser.preprocess(input);
          var exp = new For(args, 0, null, parser.operators);
          $J.expect(exp.args[0].type).toEqual("EXPRESSION");
          $J.expect(exp.args[0].output).toEqual("x");
        });

        $J.it("should throw an error if there is no equal sign in test argument", function () {
          var input = "for 1:10\n y = y + 1; \n end\n";
          var args = parser.preprocess(input);
          $J.expect(function () {
            exp = new For(args, 0, null, parser.operators);
          }).toThrow("Operation Error :: FOR : unbalanced test expression.");
        });
      });

      $J.describe("repeat lines are placed in exec", function () {
        $J.it("should have exec as array of expressions", function () {
          var input = "for x = 1:10\n y = y + x; \n z = y + 2; \n end\n";
          var args = parser.preprocess(input);
          var exp = new For(args, 0, null, parser.operators);
          $J.expect(exp.exec.length).toEqual(2);
          $J.expect(exp.pos).toEqual(22);
        });
      });
    });

    $J.describe("#interpret(variables, outputCallback)", function () {

      var opts = {};
      $J.beforeEach(function () {
        opts.variables = {};
        opts.outputCallback = function () {
        }
      });

      $J.describe("interprets exex[] once for every column in the test array", function () {

        $J.describe("interprets the test once", function () {

          var exp = null;

          function callback(output) {

          }

          $J.beforeEach(function () {
            var input = "for x = 1:3\n y = 2 + x; \n z = y + 2; \n end\n";
            var args = parser.preprocess(input);
            exp = new For(args, 0, null, parser.operators);
            opts.variables = {};
            opts.outputCallback = callback;
          });

          $J.it("should interpret the test once", function (done) {
            var spy = sinon.spy(exp.args[0].args[0], "interpret");
            exp.interpret(opts, function (err, ans) {
              $J.expect(spy.callCount).toEqual(1);
              spy.restore();
              done();
            });
          });
        });

        $J.describe("calls exec array once for each column in test with updated variables", function () {
          $J.describe("with 1xN exec array", function () {
            var exp = null;
            $J.beforeEach(function () {
              var input = "for x = 1:3\n y = 2 + x; \n z = y + 2; \n end\n";
              var args = parser.preprocess(input);
              exp = new For(args, 0, null, parser.operators);
            });

            $J.it("should call exec N times", function (done) {
              var spy0 = sinon.spy(exp.exec[0], "interpret");
              var spy1 = sinon.spy(exp.exec[1], "interpret");
              exp.interpret(opts, function (err, ans) {
                $J.expect(spy0.callCount).toEqual(3);
                $J.expect(spy1.callCount).toEqual(3);
                $J.expect(opts.variables.y).toEqual([
                  [ 5 ]
                ]);
                spy0.restore();
                spy1.restore();
                done();
              });

            });
          });

          $J.describe("with MxN exec array", function () {
            var exp = null;
            var variables = {};

            function callback(output) {

            }

            $J.beforeEach(function () {
              var input = "for x = ones(2,3) \n y = 2 + x; \n z = y + 2; \n end\n";
              var args = parser.preprocess(input);
              exp = new For(args, 0, null, parser.operators);
            });

            $J.it("should call exec m*n times", function (done) {
              var spy0 = sinon.spy(exp.exec[0], "interpret");
              var spy1 = sinon.spy(exp.exec[1], "interpret");
              exp.interpret(opts, function (err, ans) {
                $J.expect(spy0.callCount).toEqual(6);
                $J.expect(spy1.callCount).toEqual(6);
                $J.expect(opts.variables.y).toEqual([
                  [ 3 ]
                ]);
                spy0.restore();
                spy1.restore();
                done();
              });
            });
          });
        });
      });
    });

    $J.describe("break", function () {

      $J.describe("breaks out of the loop", function () {

        var exp = null;
        var opts = {};
        $J.beforeEach(function () {
          var input = "for x = 1:10\n y = 2 + x; \n if(y == 5) \n break \n end \n end\n";
          var args = parser.preprocess(input);
          exp = new For(args, 0, null, parser.operators);
          opts.variables = {};
          opts.outputCallback = function () {
          }
        });

        $J.it("should not call it the full number of times", function (done) {
          var spy0 = sinon.spy(exp.exec[0], "interpret");
          exp.interpret(opts, function (err, ans) {
            $J.expect(spy0.callCount).toEqual(3);
            $J.expect(opts.variables.y).toEqual([
              [ 5 ]
            ]);
            spy0.restore();
            done();
          });
        });
      });
    });

    $J.describe("continue", function () {
      var opts = {};
      $J.beforeEach(function () {
        opts.variables = {};
        opts.outputCallback = function () {
        }
      });

      $J.describe("imedieatly contines to next loop", function () {

        var exp = null;
        $J.beforeEach(function () {
          var input = "for x = 1:5\n y = 2 + x; \n if(y > 4) \n continue \n end \n z = 3 + y; \n end\n";
          var args = parser.preprocess(input);
          exp = new For(args, 0, null, parser.operators);
        });

        $J.it("should not call it the full number of times", function (done) {
          var spy0 = sinon.spy(exp.exec[0], "interpret");
          var spy2 = sinon.spy(exp.exec[2], "interpret");
          var callcount = 0;
          exp.interpret(opts, function (err, ans) {
            callcount++;
            console.log("#### callcount:", callcount);
            $J.expect(spy0.callCount).toEqual(5);
            $J.expect(spy2.callCount).toEqual(2);
            spy0.restore();
            spy2.restore();
            done()
          });

        });
      });
    });

    $J.describe("integrates with the parser", function () {
      $J.it("should be in the script", function (done) {
        var input = "z = 0; \n y = 0; \n for x = 1:3\n y = 2 + y; \n z = 1 + z; \n end\n";
        parser.evaluate(input, function (err, ans) {
          $J.expect(err).toBeFalsy()
          $J.expect(parser.variables.z[0][0]).toEqual(3);
          $J.expect(parser.variables.y[0][0]).toEqual(6);
          done();
        });

      });

      $J.it("should nest fine", function (done) {
        var input = "z = 0; \n p = 0; \n" + "for x = 1:3\n z = z + 1; \n for y = 1:10\n p = p + 1;\n end\n end\n";
        parser.evaluate(input, function (err, ans) {
          $J.expect(err).toBeFalsy();
          $J.expect(parser.variables.z[0][0]).toEqual(3);
          $J.expect(parser.variables.p[0][0]).toEqual(30);
          done();
        });
      });
    });

  });

});


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package org.redkale.convert.json;

import java.nio.*;
import java.nio.charset.*;
import java.util.*;
import java.util.function.*;
import org.redkale.convert.*;
import org.redkale.util.*;

/**
 * 以ByteBuffer为数据载体的JsonWriter
 *
 *

 * 详情见: https://redkale.org
 *
 * @author zhangjx
 */
public class JsonByteBufferWriter extends JsonWriter {

    protected Charset charset;

    private final Supplier<ByteBuffer> supplier;

    private ByteBuffer[] buffers;

    private int index;

    protected JsonByteBufferWriter(boolean tiny, Supplier<ByteBuffer> supplier) {
        this(tiny, null, supplier);
    }

    protected JsonByteBufferWriter(boolean tiny, Charset charset, Supplier<ByteBuffer> supplier) {
        this.tiny = tiny;
        this.charset = StandardCharsets.UTF_8.equals(charset) ? null : charset;
        this.supplier = supplier;
    }

    @Override
    public JsonByteBufferWriter tiny(boolean tiny) {
        this.tiny = tiny;
        return this;
    }

    @Override
    protected boolean recycle() {
        super.recycle();
        this.index = 0;
        this.specify = null;
        this.charset = null;
        this.buffers = null;
        return false;
    }

    @Override
    public ByteBuffer[] toBuffers() {
        if (buffers == null) return new ByteBuffer[0];
        for (int i = index; i < this.buffers.length; i++) {
            ByteBuffer buf = this.buffers[i];
            if (buf.position() != 0) buf.flip();
        }
        return this.buffers;
    }

    @Override
    public int count() {
        if (this.buffers == null) return 0;
        int len = 0;
        for (ByteBuffer buffer : buffers) {
            len += buffer.remaining();
        }
        return len;
    }

    private int expand(final int byteLength) {
        if (this.buffers == null) {
            this.index = 0;
            this.buffers = new ByteBuffer[]{supplier.get()};
        }
        ByteBuffer buffer = this.buffers[index];
        if (!buffer.hasRemaining()) {
            buffer.flip();
            buffer = supplier.get();
            this.buffers = Utility.append(this.buffers, buffer);
            this.index++;
        }
        int len = buffer.remaining();
        int size = 0;
        while (len < byteLength) {
            buffer = supplier.get();
            this.buffers = Utility.append(this.buffers, buffer);
            len += buffer.remaining();
            size++;
        }
        return size;
    }

    @Override
    public void writeTo(final char ch) {
        if (ch > Byte.MAX_VALUE) throw new ConvertException("writeTo char(int.value = " + (int) ch + ") must be less 127");
        expand(1);
        this.buffers[index].put((byte) ch);
    }

    @Override
    public void writeTo(final char[] chs, final int start, final int len) {
        writeTo(-1, false, chs, start, len);
    }

    private void writeTo(int expandsize, final boolean quote, final char[] chs, final int start, final int len) {
        int byteLength = quote ? 2 : 0;
        ByteBuffer bb = null;
        if (charset == null) {
            byteLength += Utility.encodeUTF8Length(chs, start, len);
        } else {
            bb = charset.encode(CharBuffer.wrap(chs, start, len));
            byteLength += bb.remaining();
        }
        if (expandsize < 0) expandsize = expand(byteLength);
        if (expandsize == 0) { // 只需要一个buffer
            final ByteBuffer buffer = this.buffers[index];
            if (quote) buffer.put((byte) '"');

            if (charset == null) { //UTF-8
                final int limit = start + len;
                for (int i = start; i < limit; i++) {
                    char c = chs[i];
                    if (c < 0x80) {
                        buffer.put((byte) c);
                    } else if (c < 0x800) {
                        buffer.put((byte) (0xc0 | (c >> 6)));
                        buffer.put((byte) (0x80 | (c & 0x3f)));
                    } else if (Character.isSurrogate(c)) { //连取两个
                        int uc = Character.toCodePoint(c, chs[i + 1]);
                        buffer.put((byte) (0xf0 | ((uc >> 18))));
                        buffer.put((byte) (0x80 | ((uc >> 12) & 0x3f)));
                        buffer.put((byte) (0x80 | ((uc >> 6) & 0x3f)));
                        buffer.put((byte) (0x80 | (uc & 0x3f)));
                        i++;
                    } else {
                        buffer.put((byte) (0xe0 | ((c >> 12))));
                        buffer.put((byte) (0x80 | ((c >> 6) & 0x3f)));
                        buffer.put((byte) (0x80 | (c & 0x3f)));
                    }
                }
            } else {
                buffer.put(bb);
            }

            if (quote) buffer.put((byte) '"');
            return;
        }
        ByteBuffer buffer = this.buffers[index];
        if (quote) {
            if (!buffer.hasRemaining()) buffer = nextByteBuffer();
            buffer.put((byte) '"');
        }
        if (charset == null) { //UTF-8
            final int limit = start + len;
            for (int i = start; i < limit; i++) {
                char c = chs[i];
                if (c < 0x80) {
                    if (!buffer.hasRemaining()) buffer = nextByteBuffer();
                    buffer.put((byte) c);
                } else if (c < 0x800) {
                    if (!buffer.hasRemaining()) buffer = nextByteBuffer();
                    buffer.put((byte) (0xc0 | (c >> 6)));
                    if (!buffer.hasRemaining()) buffer = nextByteBuffer();
                    buffer.put((byte) (0x80 | (c & 0x3f)));
                } else if (Character.isSurrogate(c)) { //连取两个
                    int uc = Character.toCodePoint(c, chs[i + 1]);
                    if (!buffer.hasRemaining()) buffer = nextByteBuffer();
                    buffer.put((byte) (0xf0 | ((uc >> 18))));
                    if (!buffer.hasRemaining()) buffer = nextByteBuffer();
                    buffer.put((byte) (0x80 | ((uc >> 12) & 0x3f)));
                    if (!buffer.hasRemaining()) buffer = nextByteBuffer();
                    buffer.put((byte) (0x80 | ((uc >> 6) & 0x3f)));
                    if (!buffer.hasRemaining()) buffer = nextByteBuffer();
                    buffer.put((byte) (0x80 | (uc & 0x3f)));
                    i++;
                } else {
                    if (!buffer.hasRemaining()) buffer = nextByteBuffer();
                    buffer.put((byte) (0xe0 | ((c >> 12))));
                    if (!buffer.hasRemaining()) buffer = nextByteBuffer();
                    buffer.put((byte) (0x80 | ((c >> 6) & 0x3f)));
                    if (!buffer.hasRemaining()) buffer = nextByteBuffer();
                    buffer.put((byte) (0x80 | (c & 0x3f)));
                }
            }
        } else {
            while (bb.hasRemaining()) {
                if (!buffer.hasRemaining()) buffer = nextByteBuffer();
                buffer.put(bb.get());
            }
        }
        if (quote) {
            if (!buffer.hasRemaining()) buffer = nextByteBuffer();
            buffer.put((byte) '"');
        }
    }

    private ByteBuffer nextByteBuffer() {
        this.buffers[this.index].flip();
        return this.buffers[++this.index];
    }

    protected static int encodeEscapeUTF8Length(final char[] text, final int start, final int len) {
        char c;
        int size = 0;
        final char[] chs = text;
        final int limit = start + len;
        for (int i = start; i < limit; i++) {
            c = chs[i];
            switch (c) {
                case '\n': size += 2;
                    break;
                case '\r': size += 2;
                    break;
                case '\t': size += 2;
                    break;
                case '\\': size += 2;
                    break;
                case '"': size += 2;
                    break;
                default:
                    size += (c < 0x80 ? 1 : (c < 0x800 || Character.isSurrogate(c) ? 2 : 3));
                    break;
            }
        }
        return size;
    }

    /**
     * 注意: 该String值不能为null且不会进行转义, 只用于不含需要转义字符的字符串,例如enum、double、BigInteger转换的String
     *
     * @param quote 是否写入双引号
     * @param value String值
     */
    @Override
    public void writeLatin1To(final boolean quote, final String value) {
        byte[] bs = Utility.byteArray(value);
        int expandsize = expand(bs.length + (quote ? 2 : 0));
        if (expandsize == 0) {// 只需要一个buffer
            final ByteBuffer buffer = this.buffers[index];
            if (quote) buffer.put((byte) '"');
            buffer.put(bs);
            if (quote) buffer.put((byte) '"');
        } else {
            ByteBuffer buffer = this.buffers[index];
            if (quote) {
                if (!buffer.hasRemaining()) buffer = nextByteBuffer();
                buffer.put((byte) '"');
            }
            for (byte b : bs) {
                if (!buffer.hasRemaining()) buffer = nextByteBuffer();
                buffer.put(b);
            }
            if (quote) {
                if (!buffer.hasRemaining()) buffer = nextByteBuffer();
                buffer.put((byte) '"');
            }
        }
    }

    @Override
    public void writeInt(int value) {
        writeLatin1To(false, String.valueOf(value));
    }

    @Override
    public void writeLong(long value) {
        writeLatin1To(false, String.valueOf(value));
    }

    @Override
    public void writeString(String value) {
        if (value == null) {
            writeNull();
            return;
        }
        final char[] chs = Utility.charArray(value);
        int len = 0;
        for (char ch : chs) {
            switch (ch) {
                case '\n': len += 2;
                    break;
                case '\r': len += 2;
                    break;
                case '\t': len += 2;
                    break;
                case '\\': len += 2;
                    break;
                case '"': len += 2;
                    break;
                default: len++;
                    break;
            }
        }
        if (len == chs.length) {
            writeTo(-1, true, chs, 0, len);
            return;
        }
        int expandsize = -1;
        if (this.charset == null) { //UTF-8
            final int byteLength = 2 + encodeEscapeUTF8Length(chs, 0, chs.length);
            expandsize = expand(byteLength);
            if (expandsize == 0) { // 只需要一个buffer
                final ByteBuffer buffer = this.buffers[index];
                buffer.put((byte) '"');
                for (int i = 0; i < chs.length; i++) {
                    char c = chs[i];
                    switch (c) {
                        case '\n': buffer.put((byte) '\\').put((byte) 'n');
                            break;
                        case '\r': buffer.put((byte) '\\').put((byte) 'r');
                            break;
                        case '\t': buffer.put((byte) '\\').put((byte) 't');
                            break;
                        case '\\': buffer.put((byte) '\\').put((byte) '\\');
                            break;
                        case '"': buffer.put((byte) '\\').put((byte) '"');
                            break;
                        default:
                            if (c < 0x80) {
                                buffer.put((byte) c);
                            } else if (c < 0x800) {
                                buffer.put((byte) (0xc0 | (c >> 6)));
                                buffer.put((byte) (0x80 | (c & 0x3f)));
                            } else if (Character.isSurrogate(c)) { //连取两个
                                int uc = Character.toCodePoint(c, chs[i + 1]);
                                buffer.put((byte) (0xf0 | ((uc >> 18))));
                                buffer.put((byte) (0x80 | ((uc >> 12) & 0x3f)));
                                buffer.put((byte) (0x80 | ((uc >> 6) & 0x3f)));
                                buffer.put((byte) (0x80 | (uc & 0x3f)));
                                i++;
                            } else {
                                buffer.put((byte) (0xe0 | ((c >> 12))));
                                buffer.put((byte) (0x80 | ((c >> 6) & 0x3f)));
                                buffer.put((byte) (0x80 | (c & 0x3f)));
                            }
                            break;
                    }
                }
                buffer.put((byte) '"');
                return;
            }
        }
        StringBuilder sb = new StringBuilder(len);
        for (char ch : chs) {
            switch (ch) {
                case '\n': sb.append("\\n");
                    break;
                case '\r': sb.append("\\r");
                    break;
                case '\t': sb.append("\\t");
                    break;
                case '\\': sb.append("\\\\");
                    break;
                case '"': sb.append("\\\"");
                    break;
                default: sb.append(ch);
                    break;
            }
        }
        char[] cs = Utility.charArray(sb);
        writeTo(expandsize, true, cs, 0, sb.length());
    }

    @Override
    public String toString() {
        return Objects.toString(this);
    }
}


text:
package org.jkiss.dbeaver.ext.postgresql.model.impls.redshift;

import org.jkiss.code.NotNull;
import org.jkiss.dbeaver.DBException;
import org.jkiss.dbeaver.Log;
import org.jkiss.dbeaver.ext.postgresql.model.PostgreSchema;
import org.jkiss.dbeaver.ext.postgresql.model.PostgreTableRegular;
import org.jkiss.dbeaver.ext.postgresql.model.PostgreTablespace;
import org.jkiss.dbeaver.model.DBUtils;
import org.jkiss.dbeaver.model.exec.DBCSession;
import org.jkiss.dbeaver.model.exec.jdbc.JDBCPreparedStatement;
import org.jkiss.dbeaver.model.exec.jdbc.JDBCResultSet;
import org.jkiss.dbeaver.model.exec.jdbc.JDBCSession;
import org.jkiss.dbeaver.model.runtime.DBRProgressMonitor;
import org.jkiss.dbeaver.model.struct.DBSObject;

import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * RedshiftTable base
 */
public class RedshiftTable extends PostgreTableRegular
{
    private static final Log log = Log.getLog(RedshiftTable.class);

    @Override
    public boolean isRefreshSchemaStatisticsOnTableRefresh() {
        return false;
    }

    public RedshiftTable(PostgreSchema catalog) {
        super(catalog);
    }

    public RedshiftTable(PostgreSchema catalog, ResultSet dbResult) {
        super(catalog, dbResult);
    }

    protected void readTableStatistics(JDBCSession session) throws SQLException {
        try (JDBCPreparedStatement dbStat = session.prepareStatement(
            "SELECT size, tbl_rows FROM SVV_TABLE_INFO WHERE \"schema\"=? AND table_id=?"))
        {
            dbStat.setString(1, getSchema().getName());
            dbStat.setLong(2, getObjectId());
            try (JDBCResultSet dbResult = dbStat.executeQuery()) {
                if (dbResult.next()) {
                    fetchStatistics(dbResult);
                }
            }
        }
    }

    @Override
    public DBSObject refreshObject(@NotNull DBRProgressMonitor monitor) throws DBException {
        if (hasStatistics()) {
            diskSpace = null;
            try (DBCSession session = DBUtils.openMetaSession(monitor, this, "Calculate relation size on disk")) {
                readTableStatistics((JDBCSession) session);
            } catch (Exception e) {
                log.debug("Can't fetch disk space", e);
            }
        }
        return super.refreshObject(monitor);
    }

    protected void fetchStatistics(JDBCResultSet dbResult) throws SQLException {
        diskSpace = dbResult.getLong("size") * 1024 * 1024;
        rowCountEstimate = rowCount = dbResult.getLong("tbl_rows");
    }

    // Not supported
    @Override
    public PostgreTablespace getTablespace(DBRProgressMonitor monitor) throws DBException {
        return super.getTablespace(monitor);
    }

    // Not supported
    @Override
    public String getPartitionKey() {
        return super.getPartitionKey();
    }

    // Not supported
    @Override
    public boolean hasPartitions() {
        return super.hasPartitions();
    }

    // Not supported
    @Override
    public boolean isHasOids() {
        return super.isHasOids();
    }
}


text:
// Boost.Geometry Index
//
// Spatial query predicates
//
// Copyright (c) 2011-2013 Adam Wulkiewicz, Lodz, Poland.
//
// Use, modification and distribution is subject to the Boost Software License,
// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)

#ifndef BOOST_GEOMETRY_INDEX_PREDICATES_HPP
#define BOOST_GEOMETRY_INDEX_PREDICATES_HPP

#include <utility>
#include <boost/tuple/tuple.hpp>
#include <boost/mpl/assert.hpp>

#include <boost/geometry/index/detail/predicates.hpp>
#include <boost/geometry/index/detail/tuples.hpp>

/*!
\defgroup predicates Predicates (boost::geometry::index::)
*/

namespace boost { namespace geometry { namespace index {

#ifdef BOOST_GEOMETRY_INDEX_DETAIL_EXPERIMENTAL

/*!
\brief Generate \c contains() predicate.

Generate a predicate defining Value and Geometry relationship.
Value will be returned by the query if <tt>bg::within(Geometry, Indexable)</tt>
returns true.

\par Example
\verbatim
bgi::query(spatial_index, bgi::contains(box), std::back_inserter(result));
\endverbatim

\ingroup predicates

\tparam Geometry    The Geometry type.

\param g            The Geometry object.
*/
template <typename Geometry> inline
detail::spatial_predicate<Geometry, detail::contains_tag, false>
contains(Geometry const& g)
{
    return detail::spatial_predicate<Geometry, detail::contains_tag, false>(g);
}

#endif // BOOST_GEOMETRY_INDEX_DETAIL_EXPERIMENTAL

/*!
\brief Generate \c covered_by() predicate.

Generate a predicate defining Value and Geometry relationship.
Value will be returned by the query if <tt>bg::covered_by(Indexable, Geometry)</tt>
returns true.

\par Example
\verbatim
bgi::query(spatial_index, bgi::covered_by(box), std::back_inserter(result));
\endverbatim

\ingroup predicates

\tparam Geometry    The Geometry type.

\param g            The Geometry object.
*/
template <typename Geometry> inline
detail::spatial_predicate<Geometry, detail::covered_by_tag, false>
covered_by(Geometry const& g)
{
    return detail::spatial_predicate<Geometry, detail::covered_by_tag, false>(g);
}

#ifdef BOOST_GEOMETRY_INDEX_DETAIL_EXPERIMENTAL

/*!
\brief Generate \c covers() predicate.

Generate a predicate defining Value and Geometry relationship.
Value will be returned by the query if <tt>bg::covered_by(Geometry, Indexable)</tt>
returns true.

\par Example
\verbatim
bgi::query(spatial_index, bgi::covers(box), std::back_inserter(result));
\endverbatim

\ingroup predicates

\tparam Geometry    The Geometry type.

\param g            The Geometry object.
*/
template <typename Geometry> inline
detail::spatial_predicate<Geometry, detail::covers_tag, false>
covers(Geometry const& g)
{
    return detail::spatial_predicate<Geometry, detail::covers_tag, false>(g);
}

#endif // BOOST_GEOMETRY_INDEX_DETAIL_EXPERIMENTAL

/*!
\brief Generate \c disjoint() predicate.

Generate a predicate defining Value and Geometry relationship.
Value will be returned by the query if <tt>bg::disjoint(Indexable, Geometry)</tt>
returns true.

\par Example
\verbatim
bgi::query(spatial_index, bgi::disjoint(box), std::back_inserter(result));
\endverbatim

\ingroup predicates

\tparam Geometry    The Geometry type.

\param g            The Geometry object.
*/
template <typename Geometry> inline
detail::spatial_predicate<Geometry, detail::disjoint_tag, false>
disjoint(Geometry const& g)
{
    return detail::spatial_predicate<Geometry, detail::disjoint_tag, false>(g);
}

/*!
\brief Generate \c intersects() predicate.

Generate a predicate defining Value and Geometry relationship.
Value will be returned by the query if <tt>bg::intersects(Indexable, Geometry)</tt>
returns true.

\par Example
\verbatim
bgi::query(spatial_index, bgi::intersects(box), std::back_inserter(result));
bgi::query(spatial_index, bgi::intersects(ring), std::back_inserter(result));
bgi::query(spatial_index, bgi::intersects(polygon), std::back_inserter(result));
\endverbatim

\ingroup predicates

\tparam Geometry    The Geometry type.

\param g            The Geometry object.
*/
template <typename Geometry> inline
detail::spatial_predicate<Geometry, detail::intersects_tag, false>
intersects(Geometry const& g)
{
    return detail::spatial_predicate<Geometry, detail::intersects_tag, false>(g);
}

/*!
\brief Generate \c overlaps() predicate.

Generate a predicate defining Value and Geometry relationship.
Value will be returned by the query if <tt>bg::overlaps(Indexable, Geometry)</tt>
returns true.

\par Example
\verbatim
bgi::query(spatial_index, bgi::overlaps(box), std::back_inserter(result));
\endverbatim

\ingroup predicates

\tparam Geometry    The Geometry type.

\param g            The Geometry object.
*/
template <typename Geometry> inline
detail::spatial_predicate<Geometry, detail::overlaps_tag, false>
overlaps(Geometry const& g)
{
    return detail::spatial_predicate<Geometry, detail::overlaps_tag, false>(g);
}

#ifdef BOOST_GEOMETRY_INDEX_DETAIL_EXPERIMENTAL

/*!
\brief Generate \c touches() predicate.

Generate a predicate defining Value and Geometry relationship.
Value will be returned by the query if <tt>bg::touches(Indexable, Geometry)</tt>
returns true.

\ingroup predicates

\tparam Geometry    The Geometry type.

\param g            The Geometry object.
*/
template <typename Geometry> inline
detail::spatial_predicate<Geometry, detail::touches_tag, false>
touches(Geometry const& g)
{
    return detail::spatial_predicate<Geometry, detail::touches_tag, false>(g);
}

#endif // BOOST_GEOMETRY_INDEX_DETAIL_EXPERIMENTAL

/*!
\brief Generate \c within() predicate.

Generate a predicate defining Value and Geometry relationship.
Value will be returned by the query if <tt>bg::within(Indexable, Geometry)</tt>
returns true.

\par Example
\verbatim
bgi::query(spatial_index, bgi::within(box), std::back_inserter(result));
\endverbatim

\ingroup predicates

\tparam Geometry    The Geometry type.

\param g            The Geometry object.
*/
template <typename Geometry> inline
detail::spatial_predicate<Geometry, detail::within_tag, false>
within(Geometry const& g)
{
    return detail::spatial_predicate<Geometry, detail::within_tag, false>(g);
}

/*!
\brief Generate satisfies() predicate.

A wrapper around user-defined UnaryPredicate checking if Value should be returned by spatial query.

\par Example
\verbatim
bool is_red(Value const& v) { return v.is_red(); }

struct is_red_o {
template <typename Value> bool operator()(Value const& v) { return v.is_red(); }
}

// ...

rt.query(index::intersects(box) && index::satisfies(is_red),
std::back_inserter(result));

rt.query(index::intersects(box) && index::satisfies(is_red_o()),
std::back_inserter(result));

#ifndef BOOST_NO_CXX11_LAMBDAS
rt.query(index::intersects(box) && index::satisfies([](Value const& v) { return v.is_red(); }),
std::back_inserter(result));
#endif
\endverbatim

\ingroup predicates

\tparam UnaryPredicate  A type of unary predicate function or function object.

\param pred             The unary predicate function or function object.
*/
template <typename UnaryPredicate> inline
detail::satisfies<UnaryPredicate, false>
satisfies(UnaryPredicate const& pred)
{
    return detail::satisfies<UnaryPredicate, false>(pred);
}

/*!
\brief Generate nearest() predicate.

When nearest predicate is passed to the query, k-nearest neighbour search will be performed.
\c nearest() predicate takes a \c Point from which distance to \c Values is calculated
and the maximum number of \c Values that should be returned.

\par Example
\verbatim
bgi::query(spatial_index, bgi::nearest(pt, 5), std::back_inserter(result));
bgi::query(spatial_index, bgi::nearest(pt, 5) && bgi::intersects(box), std::back_inserter(result));
\endverbatim

\warning
Only one \c nearest() predicate may be used in a query.

\ingroup predicates

\param point        The point from which distance is calculated.
\param k            The maximum number of values to return.
*/
template <typename Point> inline
detail::nearest<Point>
nearest(Point const& point, unsigned k)
{
    return detail::nearest<Point>(point, k);
}

#ifdef BOOST_GEOMETRY_INDEX_DETAIL_EXPERIMENTAL

/*!
\brief Generate path() predicate.

When path predicate is passed to the query, the returned values are k values along the path closest to
its begin. \c path() predicate takes a \c Segment or a \c Linestring defining the path and the maximum
number of \c Values that should be returned.

\par Example
\verbatim
bgi::query(spatial_index, bgi::path(segment, 5), std::back_inserter(result));
bgi::query(spatial_index, bgi::path(linestring, 5) && bgi::intersects(box), std::back_inserter(result));
\endverbatim

\warning
Only one distance predicate (\c nearest() or \c path()) may be used in a query.

\ingroup predicates

\param linestring   The path along which distance is calculated.
\param k            The maximum number of values to return.
*/
template <typename SegmentOrLinestring> inline
detail::path<SegmentOrLinestring>
path(SegmentOrLinestring const& linestring, unsigned k)
{
    return detail::path<SegmentOrLinestring>(linestring, k);
}

#endif // BOOST_GEOMETRY_INDEX_DETAIL_EXPERIMENTAL

namespace detail {

// operator! generators

template <typename Fun, bool Negated> inline
satisfies<Fun, !Negated>
operator!(satisfies<Fun, Negated> const& p)
{
    return satisfies<Fun, !Negated>(p);
}

template <typename Geometry, typename Tag, bool Negated> inline
spatial_predicate<Geometry, Tag, !Negated>
operator!(spatial_predicate<Geometry, Tag, Negated> const& p)
{
    return spatial_predicate<Geometry, Tag, !Negated>(p.geometry);
}

// operator&& generators

template <typename Pred1, typename Pred2> inline
boost::tuples::cons<
    Pred1,
    boost::tuples::cons<Pred2, boost::tuples::null_type>
>
operator&&(Pred1 const& p1, Pred2 const& p2)
{
    /*typedef typename boost::mpl::if_c<is_predicate<Pred1>::value, Pred1, Pred1 const&>::type stored1;
    typedef typename boost::mpl::if_c<is_predicate<Pred2>::value, Pred2, Pred2 const&>::type stored2;*/
    namespace bt = boost::tuples;

    return
    bt::cons< Pred1, bt::cons<Pred2, bt::null_type> >
        ( p1, bt::cons<Pred2, bt::null_type>(p2, bt::null_type()) );
}

template <typename Head, typename Tail, typename Pred> inline
typename tuples::push_back_impl<
    boost::tuples::cons<Head, Tail>,
    Pred,
    0,
    boost::tuples::length<boost::tuples::cons<Head, Tail> >::value
>::type
operator&&(boost::tuples::cons<Head, Tail> const& t, Pred const& p)
{
    //typedef typename boost::mpl::if_c<is_predicate<Pred>::value, Pred, Pred const&>::type stored;
    namespace bt = boost::tuples;

    return
    tuples::push_back_impl<
        bt::cons<Head, Tail>, Pred, 0, bt::length< bt::cons<Head, Tail> >::value
    >::apply(t, p);
}

} // namespace detail

}}} // namespace boost::geometry::index

#endif // BOOST_GEOMETRY_INDEX_PREDICATES_HPP


text:
===========
Expressions
===========

.. contents::
   :local:
   :depth: 2

Object Identifiers
==================

Since there is no complete HLSL grammar specification I know of,
the overall structure of the AST comes from many trials and erros (and might still change).

Here is a brief overview how one of the most complex constructs, the **object identifiers**, are structured:
These object identifiers consist of several AST classes and are part of the expressions,
specifically ``ObjectExpr``, ``ArrayExpr``, ``AssignExpr``, and ``CallExpr``.

An ``ObjectExpr`` (for "object expression") holds a reference to an object, which can be
either a **variable** (also parameter), **buffer** (also texture), **sampler** (also sampler state),
**structure**, or **type alias**.

Specification
-------------

::

 ObjectExpr : Expr {
     Expr              prefixExpression [Optional]
     Boolean           isStatic         [Optional]
     String            identifier

     Ref<Decl>         symbolRef        [Optional]  --> VarDecl, BufferDecl, SamplerDecl, StructDecl
 }

 AssignExpr : Expr {
     Expr              lvalueExpression
     AssinOp           assignOperator
     Expr              rvalueExpression
 }

 ArrayExpr : Expr {
     Expr              prefixExpression
     List<Expr>        arrayIndices
 }

 CallExpr : Expr {
     Expr              prefixExpression [Optional]
     Boolean           isStatic         [Optional]
     String            identifier
     Ref<FunctionDecl> funcDeclRef      [Optional]
 }

 BracketExpr : Expr {
     Expr              subExpression
 }

Example: ``( Scene::getMain().getLights() )[1].material.getShininess()``

::

 expression (CallExpr)
  |-prefixExpression (ObjectExpr)
  |  |-prefixExpression (ArrayExpr)
  |  |  |-prefixExpression (BracketExpr)
  |  |  |  `-subExpression (CallExpr)
  |  |  |     |-prefixExpression (CallExpr)
  |  |  |     |  |-prefixExpression (ObjectExpr)
  |  |  |     |  |  `-identifier = "Scene"
  |  |  |     |  |-isStatic = true
  |  |  |     |  `-identifier = "getMain"
  |  |  |     `-identifier = "getLights"
  |  |  `-arrayIndices[0] (LiteralExpr)
  |  |     `-literal = "1"
  |  `-identifier = "material"
  `-identifier = "getShininess"

Cast Expressions
================

Parsing
-------

Cast expressions are the only part that can *not* be parsed with a **context free grammar**.
Consider the following example::

 int X = 0;
 (X) - (1);

In this example ``X`` specifies a local variable from type ``int``, and the expression ``(X) - (1)`` is a **binary expression**
with the minus operator. Now consider the next example::

 typedef int X;
 (X) - (1);

In this example ``X`` specifies a type alias that refers to the type ``int``, and the expression ``(X) - (1)`` is
equivalent to ``(int)-1`` which is a **cast expression**. This means the parser needs to know all type names
for the respective scopes, which in turn means the parser needs to be context aware.

Entry-Point Return
------------------

When the entry point function return type is a structure (e.g. ``Output``), and a return statement uses a cast expression
(e.g. ``return (Output)1;``) then this cast expression must be transformed for GLSL in different ways.
In the following the structure ``Output`` is assumed to be declared as::

 struct Output {
     float4 position;
     float3 normal;
 };

Return ``ObjectExpr``
---------------------

When an **object expression** is returned, it must be translated to a constructor of the respective function return type::

 return (Output)object;

Must translate to this in GLSL::

 return Output(vec4(object), vec3(object));

Return ``CallExpr``
-------------------

When a **call expression** is returned, a temporary variable must be written out, to avoid multiple calls to the function,
because it might have side affects::

 return (Output)f();

Must translate to this in GLSL::

 f_ReturnType xst_temp = f();
 return Output(vec4(xst_temp), vec3(xst_temp));

Transforming System Value Semantics
===================================

Especially for geometry shaders a system value semantic must be transformed from an array expression like this:

* ``output[0].position`` to ``gl_Position`` (for geometry shader output)
* ``input[0].position`` to ``gl_in[0].gl_Position`` (for geometry shader input)
* ``input[0].normal`` to ``xsv_NORMAL[0]`` (for geometry shader input)

This transformation is currently implemented in the ``GLSLGenerator`` instead of the ``GLSLConverter``.


text:
package com.themangoproject.ui.moviepopup;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JTable;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import com.themangoproject.model.MangoController;
import com.themangoproject.model.Movie;
import com.themangoproject.ui.UIController;
import com.themangoproject.ui.model.EditableMovieTableModel;

/**
 * Menu item for adding items to a list.
 *
 * @author Paul Osborne
 */
public class AddToListMenuItem extends JMenu implements
        ChangeListener {

    /** Generated serial UID */
    private static final long serialVersionUID = -2087640290190972545L;

    /**
     * Constructor for AddToListMenuItem. Set the title and add the
     * lists. Also add change listener.
     */
    public AddToListMenuItem() {
        super("Add to List");
        addLists();
        MangoController.getInstance().addListsChangeListener(this);
    }

    /**
     * ActionListener for handling the action of having a list with a
     * specific label clicked on... That is, add the movie to the
     * list.
     */
    public class AddToListActionListener implements ActionListener {
        private String label;

        /**
         * Construct a list action listener for list with given label
         *
         * @param listLabel
         */
        public AddToListActionListener(String listLabel) {
            this.label = listLabel;
        }

        /**
         * Get the currently selected movie and add it to the list.
         *
         * @param e
         *            the triggering action event.
         */
        public void actionPerformed(ActionEvent e) {
            // Get the selected movie
            JTable table = UIController.getInstance().getViewTable();

            int[] selectedRows = table.getSelectedRows();
            int selectedRow2;
            for(int i =0; i < selectedRows.length; i++){
                selectedRow2 = table.getRowSorter().
                    convertRowIndexToModel(selectedRows[i]);
                Movie m = ((EditableMovieTableModel) table
                    .getModel()).getMovieForRow(selectedRow2);
                MangoController.getInstance().addMovieToList(this.label,
                    m);
            }

//            int selectedRow = table.getRowSorter()
//                    .convertRowIndexToModel(table.getSelectedRow());
//            Movie m = ((EditableMovieTableModel) table.getModel())
//                    .getMovieForRow(selectedRow);
//
//            // add the movie
//            MangoController.getInstance().addMovieToList(this.label,
//                    m);
        }
    }

    /**
     * All all lists to the menu as action items that add the selected
     * movie to the end of the list.
     */
    private void addLists() {
        List<String> lists = MangoController.getInstance()
                .getAllLists();
        for (String list : lists) {
            JMenuItem item = new JMenuItem(list);
            item.addActionListener(new AddToListActionListener(list));
            this.add(item);
        }
    }

    /**
     * ChangeListener event listening to changes to the set of lists.
     * When a change is detected, remove and add again all from the
     * database.
     *
     * @param e
     *            The change event
     */
    @Override
    public void stateChanged(ChangeEvent e) {
        this.removeAll();
        this.addLists();
    }

}


text:
@interface AdColony (Specs)

+ (void)mp_swizzleStartMethod;
+ (void)mp_swizzleZoneStatusMethod;

+ (NSString *)mp_getAppId;
+ (NSArray *)mp_getZoneIds;
+ (void)mp_onAdColonyAdAvailabilityChange:(BOOL)available inZone:(NSString *)zoneID;
+ (void)mp_setAdColonyDelegate:(id)delegate;
+ (void)mp_setZoneStatus:(NSInteger)status;

@end


text:
/* nano_ctx_switch.c - measure context switch time between fibers */

/*
 * Copyright (c) 2012-2014 Wind River Systems, Inc.
 *
 * SPDX-License-Identifier: Apache-2.0
 */

/*
 * DESCRIPTION
 * This file contains fiber context switch time measurement.
 * The task starts two fibers. One fiber waits on a semaphore. The other,
 * after starting, releases a semaphore which enable the first fiber to run.
 * Each fiber increases a common global counter and context switch back and
 * forth by yielding the cpu. When counter reaches the maximal value, fibers
 * stop and the average time of context switch is displayed.
 */

#include "timestamp.h"
#include "utils.h"

#include <arch/cpu.h>

/* number of context switches */
#define NCTXSWITCH   10000
#ifndef STACKSIZE
#define STACKSIZE    512
#endif

/* stack used by the fibers */
static char __stack fiberOneStack[STACKSIZE];
static char __stack fiberTwoStack[STACKSIZE];

/* semaphore used for fibers synchronization */
static struct nano_sem syncSema;

static uint32_t timestamp;

/* context switches counter */
static volatile uint32_t ctxSwitchCounter;

/* context switch balancer. Incremented by one fiber, decremented by another*/
static volatile int ctxSwitchBalancer;

/**
 *
 * fiberOne
 *
 * Fiber makes all the test preparations: registers the interrupt handler,
 * gets the first timestamp and invokes the software interrupt.
 *
 * @return N/A
 */
static void fiberOne(void)
{
	nano_fiber_sem_take(&syncSema, TICKS_UNLIMITED);
	timestamp = TIME_STAMP_DELTA_GET(0);
	while (ctxSwitchCounter < NCTXSWITCH) {
		fiber_yield();
		ctxSwitchCounter++;
		ctxSwitchBalancer--;
	}
	timestamp = TIME_STAMP_DELTA_GET(timestamp);
}

/**
 *
 * @brief Check the time when it gets executed after the semaphore
 *
 * Fiber starts, waits on semaphore. When the interrupt handler releases
 * the semaphore, fiber measures the time.
 *
 * @return 0 on success
 */
static void fiberTwo(void)
{
	nano_fiber_sem_give(&syncSema);
	while (ctxSwitchCounter < NCTXSWITCH) {
		fiber_yield();
		ctxSwitchCounter++;
		ctxSwitchBalancer++;
	}
}

/**
 *
 * @brief The test main function
 *
 * @return 0 on success
 */
int nanoCtxSwitch(void)
{
	PRINT_FORMAT(" 4- Measure average context switch time between fibers");
	nano_sem_init(&syncSema);
	ctxSwitchCounter = 0;
	ctxSwitchBalancer = 0;

	bench_test_start();
	task_fiber_start(&fiberOneStack[0], STACKSIZE,
			 (nano_fiber_entry_t) fiberOne, 0, 0, 6, 0);
	task_fiber_start(&fiberTwoStack[0], STACKSIZE,
			 (nano_fiber_entry_t) fiberTwo, 0, 0, 6, 0);
	if (ctxSwitchBalancer > 3 || ctxSwitchBalancer < -3) {
		PRINT_FORMAT(" Balance is %d. FAILED", ctxSwitchBalancer);
	} else if (bench_test_end() != 0) {
		errorCount++;
		PRINT_OVERFLOW_ERROR();
	} else {
		PRINT_FORMAT(" Average context switch time is %u tcs = %u"
			     " nsec",
			     timestamp / ctxSwitchCounter,
			     SYS_CLOCK_HW_CYCLES_TO_NS_AVG(timestamp,
							   ctxSwitchCounter));
	}
	return 0;
}


text:
<?php

function search($query, $database, $cache, $format = 'json') {
	$data = $cache->load($query);

	if($data) {
        $json = json_decode($data);
        $json->meta->time = 0;
		return $json;
    }

    $espacedQuery = escapeshellarg($query);
    $command = PYTHON3 . FCASEARCH . "-d $database -q $espacedQuery -f $format";
    $data = shell_exec("LANG=cs_CZ.utf-8; " . $command);
    $decodedJson = json_decode($data);
    if ($decodedJson) {
        $cache->save($query, $data);
        return $decodedJson;
    } else {
        throw new SearchException($data);
    }
}

function getFcaExtension($results) {
   	$fca = new Fca($results);
   	$specStr = $fca->getSpecialization();
    $siblStr = $fca->getSimilar();

    return array('spec' => $specStr, 'sib' => $siblStr);
}

function getLink($href, $text, $wrapper = '') {
    $html = "$text";
    if($wrapper) {
        $html = "<$wrapper>$html</$wrapper>";
    }
    return $html;
}

function getGETValue($name, $default = '') {
    if(isset ($_GET[$name])) {
        return $_GET[$name];
    } else {
        return $default;
    }
}

function getHTTPQuery($parameters = false) {
	if (!$parameters)
		$parameters = $_GET;
    $httpQuery = '?' . http_build_query($parameters);
    $httpQuery = str_replace('&', '&', $httpQuery);
    return $httpQuery;
}

class SearchException extends Exception { }


text:
package com.gentics.mesh.core.db;

import com.gentics.mesh.core.data.dao.PersistingBranchDao;
import com.gentics.mesh.core.data.dao.PersistingContentDao;
import com.gentics.mesh.core.data.dao.PersistingGroupDao;
import com.gentics.mesh.core.data.dao.PersistingJobDao;
import com.gentics.mesh.core.data.dao.PersistingLanguageDao;
import com.gentics.mesh.core.data.dao.PersistingMicroschemaDao;
import com.gentics.mesh.core.data.dao.PersistingNodeDao;
import com.gentics.mesh.core.data.dao.PersistingProjectDao;
import com.gentics.mesh.core.data.dao.PersistingRoleDao;
import com.gentics.mesh.core.data.dao.PersistingSchemaDao;
import com.gentics.mesh.core.data.dao.PersistingTagDao;
import com.gentics.mesh.core.data.dao.PersistingTagFamilyDao;
import com.gentics.mesh.core.data.dao.PersistingUserDao;

/**
 * A developer API of {@link Tx}.
 *
 * @author plyhun
 *
 */
public interface CommonTx extends Tx, TxEntityPersistenceManager {

	/**
	 * Return the current active common transaction.
	 *
	 * @return Currently active transaction
	 */
	static CommonTx get() {
		return (CommonTx) Tx.get();
	}

	@Override
	default int txId() {
		return hashCode();
	}

	@Override
	PersistingNodeDao nodeDao();

	@Override
	PersistingUserDao userDao();

	@Override
	PersistingGroupDao groupDao();

	@Override
	PersistingRoleDao roleDao();

	@Override
	PersistingProjectDao projectDao();

	@Override
	PersistingLanguageDao languageDao();

	@Override
	PersistingJobDao jobDao();

	@Override
	PersistingTagFamilyDao tagFamilyDao();

	@Override
	PersistingTagDao tagDao();

	@Override
	PersistingBranchDao branchDao();

	@Override
	PersistingMicroschemaDao microschemaDao();

	@Override
	PersistingSchemaDao schemaDao();

	@Override
	PersistingContentDao contentDao();

	@Override
	CommonTxData data();
}


text:
import { includes, without, pick } from 'lodash';
import { createSelector } from 'reselect';
import { scaleThreshold } from 'd3-scale';
import { fromJS, Set as makeSet, List as makeList } from 'immutable';

import { NODE_BASE_SIZE } from '../../constants/styles';
import { graphNodesSelector, graphEdgesSelector } from './graph';
import { graphZoomStateSelector } from './zoom';
import {
  canvasCircularExpanseSelector,
  canvasDetailsHorizontalCenterSelector,
  canvasDetailsVerticalCenterSelector,
} from '../canvas';

const circularOffsetAngle = Math.PI / 4;

// make sure circular layouts a bit denser with 3-6 nodes
const radiusDensity = scaleThreshold()
  .domain([3, 6])
  .range([2.5, 3, 2.5]);

const translationToViewportCenterSelector = createSelector(
  [
    canvasDetailsHorizontalCenterSelector,
    canvasDetailsVerticalCenterSelector,
    graphZoomStateSelector,
  ],
  (centerX, centerY, zoomState) => {
    const {
      scaleX, scaleY, translateX, translateY
    } = zoomState.toJS();
    return {
      x: (-translateX + centerX) / scaleX,
      y: (-translateY + centerY) / scaleY,
    };
  }
);

const selectedNodeIdSelector = createSelector(
  [
    graphNodesSelector,
    state => state.get('selectedNodeId'),
  ],
  (graphNodes, selectedNodeId) => (graphNodes.has(selectedNodeId) ? selectedNodeId : null)
);

// TODO: Combine this with the corresponding nodes decorator.
const focusedNodesIdsSelector = createSelector(
  [
    selectedNodeIdSelector,
    state => state.get('nodes'),
  ],
  (selectedNodeId, nodes) => {
    if (!selectedNodeId || nodes.isEmpty()) {
      return [];
    }

    // The selected node always goes in focus.
    let focusedNodes = makeSet([selectedNodeId]);

    // Add all the nodes the selected node is connected to...
    focusedNodes = focusedNodes.merge(nodes.getIn([selectedNodeId, 'adjacency']) || makeList());

    // ... and also all the nodes that connect to the selected one.
    nodes.forEach((node, nodeId) => {
      const adjacency = node.get('adjacency') || makeList();
      if (adjacency.includes(selectedNodeId)) {
        focusedNodes = focusedNodes.add(nodeId);
      }
    });

    return focusedNodes.toArray();
  }
);

const circularLayoutScalarsSelector = createSelector(
  [
    state => graphZoomStateSelector(state).get('scaleX'),
    state => focusedNodesIdsSelector(state).length - 1,
    canvasCircularExpanseSelector,
  ],
  (scale, circularNodesCount, viewportExpanse) => {
    // Here we calculate the zoom factor of the nodes that get selected into focus.
    // The factor is a somewhat arbitrary function (based on what looks good) of the
    // viewport dimensions and the number of nodes in the circular layout. The idea
    // is that the node should never be zoomed more than to cover 1/2 of the viewport
    // (`maxScale`) and then the factor gets decresed asymptotically to the inverse
    // square of the number of circular nodes, with a little constant push to make
    // the layout more stable for a small number of nodes. Finally, the zoom factor is
    // divided by the zoom factor applied to the whole topology layout to cancel it out.
    const maxScale = viewportExpanse / NODE_BASE_SIZE / 2;
    const shrinkFactor = Math.sqrt(circularNodesCount + 10);
    const selectedScale = maxScale / shrinkFactor / scale;

    // Following a similar logic as above, we set the radius of the circular
    // layout based on the viewport dimensions and the number of circular nodes.
    const circularRadius = viewportExpanse / radiusDensity(circularNodesCount) / scale;
    const circularInnerAngle = (2 * Math.PI) / circularNodesCount;

    return { selectedScale, circularRadius, circularInnerAngle };
  }
);

export const selectedScaleSelector = createSelector(
  [
    circularLayoutScalarsSelector,
  ],
  layout => layout.selectedScale
);

// Nodes after the selection circular layout has been applied to dagre engine output.
export const layoutNodesSelector = createSelector(
  [
    selectedNodeIdSelector,
    focusedNodesIdsSelector,
    graphNodesSelector,
    translationToViewportCenterSelector,
    circularLayoutScalarsSelector,
  ],
  (selectedNodeId, focusedNodesIds, graphNodes, translationToCenter, layoutScalars) => {
    const { circularRadius, circularInnerAngle } = layoutScalars;

    // Do nothing if the layout doesn't contain the selected node anymore.
    if (!selectedNodeId) {
      return graphNodes;
    }

    // Fix the selected node in the viewport center.
    let layoutNodes = graphNodes.mergeIn([selectedNodeId], translationToCenter);

    // Put the nodes that are adjacent to the selected one in a circular layout around it.
    const circularNodesIds = without(focusedNodesIds, selectedNodeId);
    layoutNodes = layoutNodes.map((node, nodeId) => {
      const index = circularNodesIds.indexOf(nodeId);
      if (index > -1) {
        const angle = circularOffsetAngle + (index * circularInnerAngle);
        return node.merge({
          x: translationToCenter.x + (circularRadius * Math.sin(angle)),
          y: translationToCenter.y + (circularRadius * Math.cos(angle))
        });
      }
      return node;
    });

    return layoutNodes;
  }
);

// Edges after the selection circular layout has been applied to dagre engine output.
export const layoutEdgesSelector = createSelector(
  [
    graphEdgesSelector,
    layoutNodesSelector,
    focusedNodesIdsSelector,
  ],
  (graphEdges, layoutNodes, focusedNodesIds) => (
    // Update the edges in the circular layout to link the nodes in a straight line.
    graphEdges.map((edge) => {
      const source = edge.get('source');
      const target = edge.get('target');
      if (includes(focusedNodesIds, source) || includes(focusedNodesIds, target)) {
        return edge.set('points', fromJS([
          pick(layoutNodes.get(source).toJS(), ['x', 'y']),
          pick(layoutNodes.get(target).toJS(), ['x', 'y']),
        ]));
      }
      return edge;
    })
  )
);


text:
try:
    import uasyncio as asyncio
except ImportError:
    try:
        import asyncio
    except ImportError:
        print("SKIP")
        raise SystemExit

async def task1(id):
    for i in range(4):
        print("sleep", id)
        await asyncio.sleep(0)

async def task2(id, ev):
    for i in range(4):
        ev.set()
        ev.clear()
        print("wait", id)
        await ev.wait()

async def main():
    ev = asyncio.Event()
    tasks = [
        asyncio.create_task(task1(0)),
        asyncio.create_task(task2(2, ev)),
        asyncio.create_task(task1(1)),
        asyncio.create_task(task2(3, ev)),
    ]
    await tasks[1]
    ev.set()

asyncio.run(main())


text:
<!DOCTYPE HTML>

<title>ServerCacheManager (ebean api 13.6.0 API)</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="dc.created" content="2022-05-03">
<meta name="description" content="declaration: module: io.ebean.api, package: io.ebean.cache, interface: ServerCacheManager">
<meta name="generator" content="javadoc/ClassWriterImpl">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">
<link rel="stylesheet" type="text/css" href="../../../../script-dir/jquery-ui.min.css" title="Style">
<link rel="stylesheet" type="text/css" href="../../../../jquery-ui.overrides.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Module

Package

Class

Use

Tree

Deprecated

Index

Help

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

SEARCH:
<input type="text" id="search-input" value="search" disabled="disabled">
<input type="reset" id="reset-button" value="reset" disabled="disabled">

Module io.ebean.api

Package io.ebean.cache

Interface ServerCacheManager

public interface ServerCacheManager

The cache service for server side caching of beans and query results.

Method Summary

<button id="method-summary-table-tab0" role="tab" aria-selected="true" aria-controls="method-summary-table.tabpanel" tabindex="0" onkeydown="switchTab(event)" onclick="show('method-summary-table', 'method-summary-table', 3)" class="active-table-tab">All Methods</button><button id="method-summary-table-tab2" role="tab" aria-selected="false" aria-controls="method-summary-table.tabpanel" tabindex="-1" onkeydown="switchTab(event)" onclick="show('method-summary-table', 'method-summary-table-tab2', 3)" class="table-tab">Instance Methods</button><button id="method-summary-table-tab3" role="tab" aria-selected="false" aria-controls="method-summary-table.tabpanel" tabindex="-1" onkeydown="switchTab(event)" onclick="show('method-summary-table', 'method-summary-table-tab3', 3)" class="table-tab">Abstract Methods</button>

Modifier and Type

Method

Description

List<ServerCacheRegion>

allRegions()

Return all the cache regions.

void

allRegionsEnabled<wbr>(boolean enabled)

Enable or disable all the cache regions.

ServerCache

beanCache<wbr>(Class<?> beanType)

Return the cache for beans of a particular type.

void

clear<wbr>(Class<?> beanType)

This clears both the bean and query cache for a given type.

void

clearAll()

Clear all the caches.

void

clearAllLocal()

Clear all the local caches.

void

clearLocal<wbr>(Class<?> beanType)

Clear the local caches for this bean type.

ServerCache

collectionIdsCache<wbr>(Class<?> beanType,
 String propertyName)

Return the cache for associated many properties of a bean type.

void

enabledRegions<wbr>(String regions)

Set the regions that are enabled.

boolean

localL2Caching()

Return true if the L2 caching is local.

ServerCache

naturalKeyCache<wbr>(Class<?> beanType)

Return the cache for mapping natural keys to id values.

ServerCache

queryCache<wbr>(Class<?> beanType)

Return the cache for query results of a particular type of bean.

ServerCacheRegion

region<wbr>(String name)

Return the cache region by name.

void

visitMetrics<wbr>(MetricVisitor visitor)

Visit the metrics for all the server caches.

Method Details

visitMetrics

void visitMetrics<wbr>(MetricVisitor visitor)

Visit the metrics for all the server caches.

localL2Caching

boolean localL2Caching()

Return true if the L2 caching is local.

 Local L2 caching means that the cache updates should occur in foreground
 rather than background processing.

allRegions

List<ServerCacheRegion> allRegions()

Return all the cache regions.

enabledRegions

void enabledRegions<wbr>(String regions)

Set the regions that are enabled.

 Typically this is set on startup and at runtime (via dynamic configuration).

Parameters:

regions - A region name or comma delimited list of region names.

allRegionsEnabled

void allRegionsEnabled<wbr>(boolean enabled)

Enable or disable all the cache regions.

region

ServerCacheRegion region<wbr>(String name)

Return the cache region by name. Typically, to enable or disable the region.

naturalKeyCache

ServerCache naturalKeyCache<wbr>(Class<?> beanType)

Return the cache for mapping natural keys to id values.

beanCache

ServerCache beanCache<wbr>(Class<?> beanType)

Return the cache for beans of a particular type.

collectionIdsCache

ServerCache collectionIdsCache<wbr>(Class<?> beanType,
 String propertyName)

Return the cache for associated many properties of a bean type.

queryCache

ServerCache queryCache<wbr>(Class<?> beanType)

Return the cache for query results of a particular type of bean.

clear

void clear<wbr>(Class<?> beanType)

This clears both the bean and query cache for a given type.

clearAll

void clearAll()

Clear all the caches.

clearAllLocal

void clearAllLocal()

Clear all the local caches.

 This is used when the L2 Cache is based on clustered near-caches (Like Ebean-K8s-L2Cache).
 It is not used when the L2 cache is a distributed cache such as HazelCast or Ignite etc.

clearLocal

void clearLocal<wbr>(Class<?> beanType)

Clear the local caches for this bean type.

 This is used when the L2 Cache is based on clustered near-caches (Like Ebean-K8s-L2Cache).
 It is not used when the L2 cache is a distributed cache such as HazelCast or Ignite etc.

Copyright © 2022. All rights reserved.


text:
/*
 * Ory Hydra API
 *
 * Documentation for all of Ory Hydra's APIs.
 *
 * API version: 1.0.0
 * Contact: hi@ory.sh
 */

// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT.

package client

import (
	"encoding/json"
)

// HealthStatus struct for HealthStatus
type HealthStatus struct {
	// Status always contains \"ok\".
	Status *string `json:"status,omitempty"`
}

// NewHealthStatus instantiates a new HealthStatus object
// This constructor will assign default values to properties that have it defined,
// and makes sure properties required by API are set, but the set of arguments
// will change when the set of required properties is changed
func NewHealthStatus() *HealthStatus {
	this := HealthStatus{}
	return &this
}

// NewHealthStatusWithDefaults instantiates a new HealthStatus object
// This constructor will only assign default values to properties that have it defined,
// but it doesn't guarantee that properties required by API are set
func NewHealthStatusWithDefaults() *HealthStatus {
	this := HealthStatus{}
	return &this
}

// GetStatus returns the Status field value if set, zero value otherwise.
func (o *HealthStatus) GetStatus() string {
	if o == nil || o.Status == nil {
		var ret string
		return ret
	}
	return *o.Status
}

// GetStatusOk returns a tuple with the Status field value if set, nil otherwise
// and a boolean to check if the value has been set.
func (o *HealthStatus) GetStatusOk() (*string, bool) {
	if o == nil || o.Status == nil {
		return nil, false
	}
	return o.Status, true
}

// HasStatus returns a boolean if a field has been set.
func (o *HealthStatus) HasStatus() bool {
	if o != nil && o.Status != nil {
		return true
	}

	return false
}

// SetStatus gets a reference to the given string and assigns it to the Status field.
func (o *HealthStatus) SetStatus(v string) {
	o.Status = &v
}

func (o HealthStatus) MarshalJSON() ([]byte, error) {
	toSerialize := map[string]interface{}{}
	if o.Status != nil {
		toSerialize["status"] = o.Status
	}
	return json.Marshal(toSerialize)
}

type NullableHealthStatus struct {
	value *HealthStatus
	isSet bool
}

func (v NullableHealthStatus) Get() *HealthStatus {
	return v.value
}

func (v *NullableHealthStatus) Set(val *HealthStatus) {
	v.value = val
	v.isSet = true
}

func (v NullableHealthStatus) IsSet() bool {
	return v.isSet
}

func (v *NullableHealthStatus) Unset() {
	v.value = nil
	v.isSet = false
}

func NewNullableHealthStatus(val *HealthStatus) *NullableHealthStatus {
	return &NullableHealthStatus{value: val, isSet: true}
}

func (v NullableHealthStatus) MarshalJSON() ([]byte, error) {
	return json.Marshal(v.value)
}

func (v *NullableHealthStatus) UnmarshalJSON(src []byte) error {
	v.isSet = true
	return json.Unmarshal(src, &v.value)
}


text:
/**
 *
 */
package ngo.music.soundcloudplayer.boundary.fragment.real;

import ngo.music.soundcloudplayer.boundary.fragment.abstracts.SoundCloudExploreFragment;
import ngo.music.soundcloudplayer.general.Constants;

/**
 * @author LEBAO_000
 *
 */
public class DiscoFragment extends SoundCloudExploreFragment {

	@Override
	protected int getCategory() {
		// TODO Auto-generated method stub
		return DISCO;
	}

}