answer
stringlengths
15
1.25M
#include "PubSubClient.h" #include "ShimClient.h" #include "Buffer.h" #include "BDDTest.h" #include "trace.h" byte server[] = { 172, 16, 0, 2 }; bool callback_called = false; char lastTopic[1024]; char lastPayload[1024]; unsigned int lastLength; void reset_callback() { callback_called = false; lastTopic[0] = '\0'; lastPayload[0] = '\0'; lastLength = 0; } void callback(char* topic, byte* payload, unsigned int length) { callback_called = true; strcpy(lastTopic,topic); memcpy(lastPayload,payload,length); lastLength = length; } int <API key>() { IT("receives a callback message"); reset_callback(); ShimClient shimClient; shimClient.setAllowConnect(true); byte connack[] = { 0x20, 0x02, 0x00, 0x00 }; shimClient.respond(connack,4); PubSubClient client(server, 1883, callback, shimClient); int rc = client.connect((char*)"client_test1"); IS_TRUE(rc); byte publish[] = {0x30,0xe,0x0,0x5,0x74,0x6f,0x70,0x69,0x63,0x70,0x61,0x79,0x6c,0x6f,0x61,0x64}; shimClient.respond(publish,16); rc = client.loop(); IS_TRUE(rc); IS_TRUE(callback_called); IS_TRUE(strcmp(lastTopic,"topic")==0); IS_TRUE(memcmp(lastPayload,"payload",7)==0); IS_TRUE(lastLength == 7); IS_FALSE(shimClient.error()); END_IT } int test_receive_stream() { IT("receives a streamed callback message"); reset_callback(); Stream stream; stream.expect((uint8_t*)"payload",7); ShimClient shimClient; shimClient.setAllowConnect(true); byte connack[] = { 0x20, 0x02, 0x00, 0x00 }; shimClient.respond(connack,4); PubSubClient client(server, 1883, callback, shimClient, stream); int rc = client.connect((char*)"client_test1"); IS_TRUE(rc); byte publish[] = {0x30,0xe,0x0,0x5,0x74,0x6f,0x70,0x69,0x63,0x70,0x61,0x79,0x6c,0x6f,0x61,0x64}; shimClient.respond(publish,16); rc = client.loop(); IS_TRUE(rc); IS_TRUE(callback_called); IS_TRUE(strcmp(lastTopic,"topic")==0); IS_TRUE(lastLength == 7); IS_FALSE(stream.error()); IS_FALSE(shimClient.error()); END_IT } int <API key>() { IT("receives an max-sized message"); reset_callback(); ShimClient shimClient; shimClient.setAllowConnect(true); byte connack[] = { 0x20, 0x02, 0x00, 0x00 }; shimClient.respond(connack,4); PubSubClient client(server, 1883, callback, shimClient); int rc = client.connect((char*)"client_test1"); IS_TRUE(rc); byte length = <API key>; byte publish[] = {0x30,length-2,0x0,0x5,0x74,0x6f,0x70,0x69,0x63,0x70,0x61,0x79,0x6c,0x6f,0x61,0x64}; byte bigPublish[length]; memset(bigPublish,'A',length); bigPublish[length] = 'B'; memcpy(bigPublish,publish,16); shimClient.respond(bigPublish,length); rc = client.loop(); IS_TRUE(rc); IS_TRUE(callback_called); IS_TRUE(strcmp(lastTopic,"topic")==0); IS_TRUE(lastLength == length-9); IS_TRUE(memcmp(lastPayload,bigPublish+9,lastLength)==0); IS_FALSE(shimClient.error()); END_IT } int <API key>() { IT("drops an oversized message"); reset_callback(); ShimClient shimClient; shimClient.setAllowConnect(true); byte connack[] = { 0x20, 0x02, 0x00, 0x00 }; shimClient.respond(connack,4); PubSubClient client(server, 1883, callback, shimClient); int rc = client.connect((char*)"client_test1"); IS_TRUE(rc); byte length = <API key>+1; byte publish[] = {0x30,length-2,0x0,0x5,0x74,0x6f,0x70,0x69,0x63,0x70,0x61,0x79,0x6c,0x6f,0x61,0x64}; byte bigPublish[length]; memset(bigPublish,'A',length); bigPublish[length] = 'B'; memcpy(bigPublish,publish,16); shimClient.respond(bigPublish,length); rc = client.loop(); IS_TRUE(rc); IS_FALSE(callback_called); IS_FALSE(shimClient.error()); END_IT } int <API key>() { IT("drops an oversized message"); reset_callback(); Stream stream; ShimClient shimClient; shimClient.setAllowConnect(true); byte connack[] = { 0x20, 0x02, 0x00, 0x00 }; shimClient.respond(connack,4); PubSubClient client(server, 1883, callback, shimClient, stream); int rc = client.connect((char*)"client_test1"); IS_TRUE(rc); byte length = <API key>+1; byte publish[] = {0x30,length-2,0x0,0x5,0x74,0x6f,0x70,0x69,0x63,0x70,0x61,0x79,0x6c,0x6f,0x61,0x64}; byte bigPublish[length]; memset(bigPublish,'A',length); bigPublish[length] = 'B'; memcpy(bigPublish,publish,16); shimClient.respond(bigPublish,length); stream.expect(bigPublish+9,length-9); rc = client.loop(); IS_TRUE(rc); IS_TRUE(callback_called); IS_TRUE(strcmp(lastTopic,"topic")==0); IS_TRUE(lastLength == length-9); IS_FALSE(stream.error()); IS_FALSE(shimClient.error()); END_IT } int test_receive_qos1() { IT("receives a qos1 message"); reset_callback(); ShimClient shimClient; shimClient.setAllowConnect(true); byte connack[] = { 0x20, 0x02, 0x00, 0x00 }; shimClient.respond(connack,4); PubSubClient client(server, 1883, callback, shimClient); int rc = client.connect((char*)"client_test1"); IS_TRUE(rc); byte publish[] = {0x32,0x10,0x0,0x5,0x74,0x6f,0x70,0x69,0x63,0x12,0x34,0x70,0x61,0x79,0x6c,0x6f,0x61,0x64}; shimClient.respond(publish,18); byte puback[] = {0x40,0x2,0x12,0x34}; shimClient.expect(puback,4); rc = client.loop(); IS_TRUE(rc); IS_TRUE(callback_called); IS_TRUE(strcmp(lastTopic,"topic")==0); IS_TRUE(memcmp(lastPayload,"payload",7)==0); IS_TRUE(lastLength == 7); IS_FALSE(shimClient.error()); END_IT } int main() { <API key>(); test_receive_stream(); <API key>(); <API key>(); <API key>(); test_receive_qos1(); FINISH }
# Written by Ryan Kereliuk <ryker@ryker.org>. This file may be # distributed under the same terms as Perl itself. # The RFC 3261 sip URI is <scheme>:<authority>;<params>?<query>. package URI::sip; use strict; use warnings; use parent qw(URI::_server URI::_userpass); use URI::Escape qw(uri_unescape); our $VERSION = '1.71'; $VERSION = eval $VERSION; sub default_port { 5060 } sub authority { my $self = shift; $$self =~ m,^($URI::scheme_re:)?([^;?]*)(.*)$,os or die; my $old = $2; if (@_) { my $auth = shift; $$self = defined($1) ? $1 : ""; my $rest = $3; if (defined $auth) { $auth =~ s/([^$URI::uric])/ URI::Escape::escape_char($1)/ego; $$self .= "$auth"; } $$self .= $rest; } $old; } sub params_form { my $self = shift; $$self =~ m,^((?:$URI::scheme_re:)?)(?:([^;?]*))?(;[^?]*)?(.*)$,os or die; my $paramstr = $3; if (@_) { my @args = @_; $$self = $1 . $2; my $rest = $4; my @new; for (my $i=0; $i < @args; $i += 2) { push(@new, "$args[$i]=$args[$i+1]"); } $paramstr = join(";", @new); $$self .= ";" . $paramstr . $rest; } $paramstr =~ s/^; return split(/[;=]/, $paramstr); } sub params { my $self = shift; $$self =~ m,^((?:$URI::scheme_re:)?)(?:([^;?]*))?(;[^?]*)?(.*)$,os or die; my $paramstr = $3; if (@_) { my $new = shift; $$self = $1 . $2; my $rest = $4; $$self .= $paramstr . $rest; } $paramstr =~ s/^; return $paramstr; } # Inherited methods that make no sense for a SIP URI. sub path {} sub path_query {} sub path_segments {} sub abs { shift } sub rel { shift } sub query_keywords {} 1;
<?php namespace Oro\Bundle\InstallerBundle\Command; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\HttpKernel\Bundle\BundleInterface; use Oro\Bundle\MigrationBundle\Command\<API key>; use Oro\Bundle\MigrationBundle\Migration\Loader\DataFixturesLoader; class <API key> extends <API key> { /** * @inheritdoc */ protected function configure() { $this->setName('oro:package:demo:load') ->setDescription('Load demo data from specified package(s) to your database.') ->addArgument( 'package', InputArgument::IS_ARRAY | InputArgument::REQUIRED, 'Package directories' ) ->addOption('dry-run', null, InputOption::VALUE_NONE, 'Outputs list of fixtures without apply them'); } /** * @inheritdoc */ protected function getFixtures(InputInterface $input, OutputInterface $output) { $<API key> = $input->getArgument('package'); $packageDirectories = []; foreach ($<API key> as $package) { $path = realpath($package); if (!$path) { $output->writeln(sprintf('<error>Path "%s" is invalid</error>', $package)); continue; } $packageDirectories[] = $path . DIRECTORY_SEPARATOR; } if (!$packageDirectories) { throw new \RuntimeException("No valid paths specified", 1); } // a function which allows filter fixtures by the given packages $filterByPackage = function ($path) use ($packageDirectories) { foreach ($packageDirectories as $packageDir) { if (stripos($path, $packageDir) === 0) { return true; } } return false; }; // prepare data fixture loader // we should load only fixtures from the specified packages /** @var DataFixturesLoader $loader */ $loader = $this->getContainer()->get('oro_migration.data_fixtures.loader'); $fixtureRelativePath = $this-><API key>($input); /** @var BundleInterface $bundle */ foreach ($this->getApplication()->getKernel()->getBundles() as $bundle) { $bundleDir = $bundle->getPath(); if (is_dir($bundleDir) && $filterByPackage($bundleDir)) { $path = $bundleDir . $fixtureRelativePath; if (is_dir($path)) { $loader->loadFromDirectory($path); } } } return $loader->getFixtures(); } /** * @inheritdoc */ protected function getTypeOfFixtures(InputInterface $input) { return <API key>::DEMO_FIXTURES_TYPE; } }
var utils = require('keystone-utils'); module.exports = function initDatabase () { if (!this.get('mongo')) { var dbName = this.get('db name') || utils.slug(this.get('name')); var dbUrl = process.env.MONGO_URI || process.env.MONGO_URL || process.env.MONGODB_URL || process.env.MONGOLAB_URI || process.env.MONGOLAB_URL || (process.env.<API key> || 'mongodb://localhost/') + dbName; this.set('mongo', dbUrl); } return this; };
#include "renderer/CCGLProgram.h" #ifndef WIN32 #include <alloca.h> #endif #include "base/CCDirector.h" #include "base/uthash.h" #include "renderer/ccGLStateCache.h" #include "platform/CCFileUtils.h" #include "deprecated/CCString.h" // helper functions static void replaceDefines(const std::string& compileTimeDefines, std::string& out) { // Replace semicolons with '#define ... \n' if (compileTimeDefines.size() > 0) { size_t pos; out = compileTimeDefines; out.insert(0, "#define "); while ((pos = out.find(';')) != std::string::npos) { out.replace(pos, 1, "\n#define "); } out += "\n"; } } NS_CC_BEGIN const char* GLProgram::<API key> = "<API key>"; const char* GLProgram::<API key> = "<API key>"; const char* GLProgram::<API key> = "<API key>"; const char* GLProgram::<API key> = "<API key>"; const char* GLProgram::<API key> = "ShaderPositionColor"; const char* GLProgram::<API key> = "<API key>"; const char* GLProgram::<API key> = "<API key>"; const char* GLProgram::<API key> = "<API key>"; const char* GLProgram::<API key> = "<API key>"; const char* GLProgram::<API key> = "<API key>"; const char* GLProgram::<API key> = "<API key>"; const char* GLProgram::<API key> = "<API key>"; const char* GLProgram::<API key> = "ShaderUIGrayScale"; const char* GLProgram::<API key> = "ShaderLabelDFNormal"; const char* GLProgram::<API key> = "ShaderLabelDFGlow"; const char* GLProgram::<API key> = "ShaderLabelNormal"; const char* GLProgram::<API key> = "ShaderLabelOutline"; const char* GLProgram::SHADER_3D_POSITION = "Shader3DPosition"; const char* GLProgram::<API key> = "<API key>"; const char* GLProgram::<API key> = "<API key>"; const char* GLProgram::<API key> = "<API key>"; const char* GLProgram::<API key> = "<API key>"; const char* GLProgram::<API key> = "<API key>"; const char* GLProgram::<API key> = "<API key>"; const char* GLProgram::<API key> = "<API key>"; const char* GLProgram::<API key> = "<API key>"; const char* GLProgram::<API key> = "<API key>"; const char* GLProgram::SHADER_3D_SKYBOX = "Shader3DSkybox"; const char* GLProgram::SHADER_3D_TERRAIN = "Shader3DTerrain"; const char* GLProgram::SHADER_CAMERA_CLEAR = "ShaderCameraClear"; // uniform names const char* GLProgram::<API key> = "CC_AmbientColor"; const char* GLProgram::<API key> = "CC_PMatrix"; const char* GLProgram::<API key> = "CC_MVMatrix"; const char* GLProgram::<API key> = "CC_MVPMatrix"; const char* GLProgram::<API key> = "CC_NormalMatrix"; const char* GLProgram::UNIFORM_NAME_TIME = "CC_Time"; const char* GLProgram::<API key> = "CC_SinTime"; const char* GLProgram::<API key> = "CC_CosTime"; const char* GLProgram::<API key> = "CC_Random01"; const char* GLProgram::<API key> = "CC_Texture0"; const char* GLProgram::<API key> = "CC_Texture1"; const char* GLProgram::<API key> = "CC_Texture2"; const char* GLProgram::<API key> = "CC_Texture3"; const char* GLProgram::<API key> = "CC_alpha_value"; // Attribute names const char* GLProgram::<API key> = "a_color"; const char* GLProgram::<API key> = "a_position"; const char* GLProgram::<API key> = "a_texCoord"; const char* GLProgram::<API key> = "a_texCoord1"; const char* GLProgram::<API key> = "a_texCoord2"; const char* GLProgram::<API key> = "a_texCoord3"; const char* GLProgram::<API key> = "a_normal"; const char* GLProgram::<API key> = "a_blendWeight"; const char* GLProgram::<API key> = "a_blendIndex"; const char* GLProgram::<API key> = "a_tangent"; const char* GLProgram::<API key> = "a_binormal"; static const char * <API key> = "uniform mat4 CC_PMatrix;\n" "uniform mat4 CC_MVMatrix;\n" "uniform mat4 CC_MVPMatrix;\n" "uniform mat3 CC_NormalMatrix;\n" "uniform vec4 CC_Time;\n" "uniform vec4 CC_SinTime;\n" "uniform vec4 CC_CosTime;\n" "uniform vec4 CC_Random01;\n" "uniform sampler2D CC_Texture0;\n" "uniform sampler2D CC_Texture1;\n" "uniform sampler2D CC_Texture2;\n" "uniform sampler2D CC_Texture3;\n" "//CC INCLUDES END\n\n"; static const std::string EMPTY_DEFINE; GLProgram* GLProgram::<API key>(const GLchar* vShaderByteArray, const GLchar* fShaderByteArray) { return <API key>(vShaderByteArray, fShaderByteArray, EMPTY_DEFINE); } GLProgram* GLProgram::<API key>(const GLchar* vShaderByteArray, const GLchar* fShaderByteArray, const std::string& compileTimeDefines) { auto ret = new (std::nothrow) GLProgram(); if(ret && ret->initWithByteArrays(vShaderByteArray, fShaderByteArray, compileTimeDefines)) { ret->link(); ret->updateUniforms(); ret->autorelease(); return ret; } CC_SAFE_DELETE(ret); return nullptr; } GLProgram* GLProgram::createWithFilenames(const std::string& vShaderFilename, const std::string& fShaderFilename) { return createWithFilenames(vShaderFilename, fShaderFilename, EMPTY_DEFINE); } GLProgram* GLProgram::createWithFilenames(const std::string& vShaderFilename, const std::string& fShaderFilename, const std::string& compileTimeDefines) { auto ret = new (std::nothrow) GLProgram(); if(ret && ret->initWithFilenames(vShaderFilename, fShaderFilename, compileTimeDefines)) { ret->link(); ret->updateUniforms(); ret->autorelease(); return ret; } CC_SAFE_DELETE(ret); return nullptr; } GLProgram::GLProgram() : _program(0) , _vertShader(0) , _fragShader(0) , _flags() { _director = Director::getInstance(); CCASSERT(nullptr != _director, "Director is null when init a GLProgram"); memset(_builtInUniforms, 0, sizeof(_builtInUniforms)); } GLProgram::~GLProgram() { CCLOGINFO("%s %d deallocing GLProgram: %p", __FUNCTION__, __LINE__, this); clearShader(); if (_program) { GL::deleteProgram(_program); } for (auto e : _hashForUniforms) { free(e.second.first); } _hashForUniforms.clear(); } bool GLProgram::initWithByteArrays(const GLchar* vShaderByteArray, const GLchar* fShaderByteArray) { return initWithByteArrays(vShaderByteArray, fShaderByteArray, EMPTY_DEFINE); } bool GLProgram::initWithByteArrays(const GLchar* vShaderByteArray, const GLchar* fShaderByteArray, const std::string& compileTimeDefines) { _program = glCreateProgram(); <API key>(); // convert defines here. If we do it in "compileShader" we will do it it twice. // a cache for the defines could be useful, but seems like overkill at this point std::string replacedDefines = ""; replaceDefines(compileTimeDefines, replacedDefines); _vertShader = _fragShader = 0; if (vShaderByteArray) { if (!compileShader(&_vertShader, GL_VERTEX_SHADER, vShaderByteArray, replacedDefines)) { CCLOG("cocos2d: ERROR: Failed to compile vertex shader"); return false; } } // Create and compile fragment shader if (fShaderByteArray) { if (!compileShader(&_fragShader, GL_FRAGMENT_SHADER, fShaderByteArray, replacedDefines)) { CCLOG("cocos2d: ERROR: Failed to compile fragment shader"); return false; } } if (_vertShader) { glAttachShader(_program, _vertShader); } <API key>(); if (_fragShader) { glAttachShader(_program, _fragShader); } _hashForUniforms.clear(); <API key>(); return true; } bool GLProgram::initWithFilenames(const std::string& vShaderFilename, const std::string& fShaderFilename) { return initWithFilenames(vShaderFilename, fShaderFilename, EMPTY_DEFINE); } bool GLProgram::initWithFilenames(const std::string& vShaderFilename, const std::string& fShaderFilename, const std::string& compileTimeDefines) { auto fileUtils = FileUtils::getInstance(); std::string vertexSource = fileUtils->getStringFromFile(FileUtils::getInstance()->fullPathForFilename(vShaderFilename)); std::string fragmentSource = fileUtils->getStringFromFile(FileUtils::getInstance()->fullPathForFilename(fShaderFilename)); return initWithByteArrays(vertexSource.c_str(), fragmentSource.c_str(), compileTimeDefines); } void GLProgram::<API key>() { static const struct { const char *attributeName; int location; } attribute_locations[] = { {GLProgram::<API key>, GLProgram::<API key>}, {GLProgram::<API key>, GLProgram::VERTEX_ATTRIB_COLOR}, {GLProgram::<API key>, GLProgram::<API key>}, {GLProgram::<API key>, GLProgram::<API key>}, {GLProgram::<API key>, GLProgram::<API key>}, {GLProgram::<API key>, GLProgram::<API key>}, {GLProgram::<API key>, GLProgram::<API key>}, }; const int size = sizeof(attribute_locations) / sizeof(attribute_locations[0]); for(int i=0; i<size;i++) { <API key>(_program, attribute_locations[i].location, attribute_locations[i].attributeName); } } void GLProgram::parseVertexAttribs() { //_vertexAttribs.clear(); // Query and store vertex attribute meta-data from the program. GLint activeAttributes; GLint length; glGetProgramiv(_program, <API key>, &activeAttributes); if(activeAttributes > 0) { VertexAttrib attribute; glGetProgramiv(_program, <API key>, &length); if(length > 0) { GLchar* attribName = (GLchar*) alloca(length + 1); for(int i = 0; i < activeAttributes; ++i) { // Query attribute info. glGetActiveAttrib(_program, i, length, nullptr, &attribute.size, &attribute.type, attribName); attribName[length] = '\0'; attribute.name = std::string(attribName); // Query the pre-assigned attribute location attribute.index = glGetAttribLocation(_program, attribName); _vertexAttribs[attribute.name] = attribute; } } } else { GLchar ErrorLog[1024]; glGetProgramInfoLog(_program, sizeof(ErrorLog), NULL, ErrorLog); CCLOG("Error linking shader program: '%s'\n", ErrorLog); } } void GLProgram::parseUniforms() { //_userUniforms.clear(); // Query and store uniforms from the program. GLint activeUniforms; glGetProgramiv(_program, GL_ACTIVE_UNIFORMS, &activeUniforms); if(activeUniforms > 0) { GLint length; glGetProgramiv(_program, <API key>, &length); if(length > 0) { Uniform uniform; GLchar* uniformName = (GLchar*)alloca(length + 1); for(int i = 0; i < activeUniforms; ++i) { // Query uniform info. glGetActiveUniform(_program, i, length, nullptr, &uniform.size, &uniform.type, uniformName); uniformName[length] = '\0'; // Only add uniforms that are not built-in. // The ones that start with 'CC_' are built-ins if(strncmp("CC_", uniformName, 3) != 0) { // remove possible array '[]' from uniform name if(length > 3) { char* c = strrchr(uniformName, '['); if(c) { *c = '\0'; } } uniform.name = std::string(uniformName); uniform.location = <API key>(_program, uniformName); GLenum __gl_error_code = glGetError(); if (__gl_error_code != GL_NO_ERROR) { CCLOG("error: 0x%x", (int)__gl_error_code); } assert(__gl_error_code == GL_NO_ERROR); _userUniforms[uniform.name] = uniform; } } } } else { GLchar ErrorLog[1024]; glGetProgramInfoLog(_program, sizeof(ErrorLog), NULL, ErrorLog); CCLOG("Error linking shader program: '%s'\n", ErrorLog); } } Uniform* GLProgram::getUniform(const std::string &name) { const auto itr = _userUniforms.find(name); if( itr != _userUniforms.end()) return &itr->second; return nullptr; } VertexAttrib* GLProgram::getVertexAttrib(const std::string &name) { const auto itr = _vertexAttribs.find(name); if( itr != _vertexAttribs.end()) return &itr->second; return nullptr; } std::string GLProgram::getDescription() const { return StringUtils::format("<GLProgram = " <API key> " | Program = %i, VertexShader = %i, FragmentShader = %i>", (size_t)this, _program, _vertShader, _fragShader); } bool GLProgram::compileShader(GLuint * shader, GLenum type, const GLchar* source) { return compileShader(shader, type, source, ""); } bool GLProgram::compileShader(GLuint* shader, GLenum type, const GLchar* source, const std::string& convertedDefines) { GLint status; if (!source) { return false; } const GLchar *sources[] = { #if CC_TARGET_PLATFORM == CC_PLATFORM_WINRT (type == GL_VERTEX_SHADER ? "precision mediump float;\n precision mediump int;\n" : "precision mediump float;\n precision mediump int;\n"), #elif (CC_TARGET_PLATFORM != CC_PLATFORM_WIN32 && CC_TARGET_PLATFORM != CC_PLATFORM_LINUX && CC_TARGET_PLATFORM != CC_PLATFORM_MAC) (type == GL_VERTEX_SHADER ? "precision highp float;\n precision highp int;\n" : "precision mediump float;\n precision mediump int;\n"), #endif <API key>, convertedDefines.c_str(), source}; *shader = glCreateShader(type); glShaderSource(*shader, sizeof(sources)/sizeof(*sources), sources, nullptr); glCompileShader(*shader); glGetShaderiv(*shader, GL_COMPILE_STATUS, &status); if (! status) { GLsizei length; glGetShaderiv(*shader, <API key>, &length); GLchar* src = (GLchar *)malloc(sizeof(GLchar) * length); glGetShaderSource(*shader, length, nullptr, src); CCLOG("cocos2d: ERROR: Failed to compile shader:\n%s", src); if (type == GL_VERTEX_SHADER) { CCLOG("cocos2d: %s", getVertexShaderLog().c_str()); } else { CCLOG("cocos2d: %s", <API key>().c_str()); } free(src); return false;; } return (status == GL_TRUE); } GLint GLProgram::getAttribLocation(const std::string &attributeName) const { return glGetAttribLocation(_program, attributeName.c_str()); } GLint GLProgram::getUniformLocation(const std::string &attributeName) const { return <API key>(_program, attributeName.c_str()); } void GLProgram::bindAttribLocation(const std::string &attributeName, GLuint index) const { <API key>(_program, index, attributeName.c_str()); } void GLProgram::updateUniforms() { _builtInUniforms[<API key>] = <API key>(_program, <API key>); _builtInUniforms[UNIFORM_P_MATRIX] = <API key>(_program, <API key>); _builtInUniforms[UNIFORM_MV_MATRIX] = <API key>(_program, <API key>); _builtInUniforms[UNIFORM_MVP_MATRIX] = <API key>(_program, <API key>); _builtInUniforms[<API key>] = <API key>(_program, <API key>); _builtInUniforms[UNIFORM_TIME] = <API key>(_program, UNIFORM_NAME_TIME); _builtInUniforms[UNIFORM_SIN_TIME] = <API key>(_program, <API key>); _builtInUniforms[UNIFORM_COS_TIME] = <API key>(_program, <API key>); _builtInUniforms[UNIFORM_RANDOM01] = <API key>(_program, <API key>); _builtInUniforms[UNIFORM_SAMPLER0] = <API key>(_program, <API key>); _builtInUniforms[UNIFORM_SAMPLER1] = <API key>(_program, <API key>); _builtInUniforms[UNIFORM_SAMPLER2] = <API key>(_program, <API key>); _builtInUniforms[UNIFORM_SAMPLER3] = <API key>(_program, <API key>); _flags.usesP = _builtInUniforms[UNIFORM_P_MATRIX] != -1; _flags.usesMV = _builtInUniforms[UNIFORM_MV_MATRIX] != -1; _flags.usesMVP = _builtInUniforms[UNIFORM_MVP_MATRIX] != -1; _flags.usesNormal = _builtInUniforms[<API key>] != -1; _flags.usesTime = ( _builtInUniforms[UNIFORM_TIME] != -1 || _builtInUniforms[UNIFORM_SIN_TIME] != -1 || _builtInUniforms[UNIFORM_COS_TIME] != -1 ); _flags.usesRandom = _builtInUniforms[UNIFORM_RANDOM01] != -1; this->use(); // Since sample most probably won't change, set it to 0,1,2,3 now. if(_builtInUniforms[UNIFORM_SAMPLER0] != -1) <API key>(_builtInUniforms[UNIFORM_SAMPLER0], 0); if(_builtInUniforms[UNIFORM_SAMPLER1] != -1) <API key>(_builtInUniforms[UNIFORM_SAMPLER1], 1); if(_builtInUniforms[UNIFORM_SAMPLER2] != -1) <API key>(_builtInUniforms[UNIFORM_SAMPLER2], 2); if(_builtInUniforms[UNIFORM_SAMPLER3] != -1) <API key>(_builtInUniforms[UNIFORM_SAMPLER3], 3); } bool GLProgram::link() { CCASSERT(_program != 0, "Cannot link invalid program"); GLint status = GL_TRUE; <API key>(); glLinkProgram(_program); parseVertexAttribs(); parseUniforms(); clearShader(); #if DEBUG || (CC_TARGET_PLATFORM == CC_PLATFORM_WINRT) glGetProgramiv(_program, GL_LINK_STATUS, &status); if (status == GL_FALSE) { CCLOG("cocos2d: ERROR: Failed to link program: %i", _program); GL::deleteProgram(_program); _program = 0; } #endif return (status == GL_TRUE); } void GLProgram::use() { GL::useProgram(_program); } static std::string logForOpenGLShader(GLuint shader) { std::string ret; GLint logLength = 0, charsWritten = 0; glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &logLength); if (logLength < 1) return ""; char *logBytes = (char*)malloc(logLength + 1); glGetShaderInfoLog(shader, logLength, &charsWritten, logBytes); logBytes[logLength] = '\0'; ret = logBytes; free(logBytes); return ret; } static std::string logForOpenGLProgram(GLuint program) { std::string ret; GLint logLength = 0, charsWritten = 0; glGetProgramiv(program, GL_INFO_LOG_LENGTH, &logLength); if (logLength < 1) return ""; char *logBytes = (char*)malloc(logLength + 1); glGetProgramInfoLog(program, logLength, &charsWritten, logBytes); logBytes[logLength] = '\0'; ret = logBytes; free(logBytes); return ret; } std::string GLProgram::getVertexShaderLog() const { return cocos2d::logForOpenGLShader(_vertShader); } std::string GLProgram::<API key>() const { return cocos2d::logForOpenGLShader(_fragShader); } std::string GLProgram::getProgramLog() const { return logForOpenGLProgram(_program); } // Uniform cache bool GLProgram::<API key>(GLint location, const GLvoid* data, unsigned int bytes) { if (location < 0) { return false; } bool updated = true; auto element = _hashForUniforms.find(location); if (element == _hashForUniforms.end()) { GLvoid* value = malloc(bytes); memcpy(value, data, bytes ); _hashForUniforms.insert(std::make_pair(location, std::make_pair(value, bytes))); } else { if (memcmp(element->second.first, data, bytes) == 0) { updated = false; } else { if (element->second.second < bytes) { GLvoid* value = realloc(element->second.first, bytes); memcpy(value, data, bytes ); _hashForUniforms[location] = std::make_pair(value, bytes); } else memcpy(element->second.first, data, bytes); } } return updated; } GLint GLProgram::<API key>(const char* name) const { CCASSERT(name != nullptr, "Invalid uniform name" ); CCASSERT(_program != 0, "Invalid operation. Cannot get uniform location when program is not initialized"); return <API key>(_program, name); } void GLProgram::<API key>(GLint location, GLint i1) { bool updated = <API key>(location, &i1, sizeof(i1)*1); if (updated) { glUniform1i( (GLint)location, i1); } } void GLProgram::<API key>(GLint location, GLint i1, GLint i2) { GLint ints[2] = {i1,i2}; bool updated = <API key>(location, ints, sizeof(ints)); if (updated) { glUniform2i( (GLint)location, i1, i2); } } void GLProgram::<API key>(GLint location, GLint i1, GLint i2, GLint i3) { GLint ints[3] = {i1,i2,i3}; bool updated = <API key>(location, ints, sizeof(ints)); if (updated) { glUniform3i( (GLint)location, i1, i2, i3); } } void GLProgram::<API key>(GLint location, GLint i1, GLint i2, GLint i3, GLint i4) { GLint ints[4] = {i1,i2,i3,i4}; bool updated = <API key>(location, ints, sizeof(ints)); if (updated) { glUniform4i( (GLint)location, i1, i2, i3, i4); } } void GLProgram::<API key>(GLint location, GLint* ints, unsigned int numberOfArrays) { bool updated = <API key>(location, ints, sizeof(int)*2*numberOfArrays); if (updated) { glUniform2iv( (GLint)location, (GLsizei)numberOfArrays, ints ); } } void GLProgram::<API key>(GLint location, GLint* ints, unsigned int numberOfArrays) { bool updated = <API key>(location, ints, sizeof(int)*3*numberOfArrays); if (updated) { glUniform3iv( (GLint)location, (GLsizei)numberOfArrays, ints ); } } void GLProgram::<API key>(GLint location, GLint* ints, unsigned int numberOfArrays) { bool updated = <API key>(location, ints, sizeof(int)*4*numberOfArrays); if (updated) { glUniform4iv( (GLint)location, (GLsizei)numberOfArrays, ints ); } } void GLProgram::<API key>(GLint location, GLfloat f1) { bool updated = <API key>(location, &f1, sizeof(f1)*1); if (updated) { glUniform1f( (GLint)location, f1); } } void GLProgram::<API key>(GLint location, GLfloat f1, GLfloat f2) { GLfloat floats[2] = {f1,f2}; bool updated = <API key>(location, floats, sizeof(floats)); if (updated) { glUniform2f( (GLint)location, f1, f2); } } void GLProgram::<API key>(GLint location, GLfloat f1, GLfloat f2, GLfloat f3) { GLfloat floats[3] = {f1,f2,f3}; bool updated = <API key>(location, floats, sizeof(floats)); if (updated) { glUniform3f( (GLint)location, f1, f2, f3); } } void GLProgram::<API key>(GLint location, GLfloat f1, GLfloat f2, GLfloat f3, GLfloat f4) { GLfloat floats[4] = {f1,f2,f3,f4}; bool updated = <API key>(location, floats, sizeof(floats)); if (updated) { glUniform4f( (GLint)location, f1, f2, f3,f4); } } void GLProgram::<API key>( GLint location, const GLfloat* floats, unsigned int numberOfArrays ) { bool updated = <API key>(location, floats, sizeof(float)*numberOfArrays); if (updated) { glUniform1fv( (GLint)location, (GLsizei)numberOfArrays, floats ); } } void GLProgram::<API key>(GLint location, const GLfloat* floats, unsigned int numberOfArrays) { bool updated = <API key>(location, floats, sizeof(float)*2*numberOfArrays); if (updated) { glUniform2fv( (GLint)location, (GLsizei)numberOfArrays, floats ); } } void GLProgram::<API key>(GLint location, const GLfloat* floats, unsigned int numberOfArrays) { bool updated = <API key>(location, floats, sizeof(float)*3*numberOfArrays); if (updated) { glUniform3fv( (GLint)location, (GLsizei)numberOfArrays, floats ); } } void GLProgram::<API key>(GLint location, const GLfloat* floats, unsigned int numberOfArrays) { bool updated = <API key>(location, floats, sizeof(float)*4*numberOfArrays); if (updated) { glUniform4fv( (GLint)location, (GLsizei)numberOfArrays, floats ); } } void GLProgram::<API key>(GLint location, const GLfloat* matrixArray, unsigned int numberOfMatrices) { bool updated = <API key>(location, matrixArray, sizeof(float)*4*numberOfMatrices); if (updated) { glUniformMatrix2fv( (GLint)location, (GLsizei)numberOfMatrices, GL_FALSE, matrixArray); } } void GLProgram::<API key>(GLint location, const GLfloat* matrixArray, unsigned int numberOfMatrices) { bool updated = <API key>(location, matrixArray, sizeof(float)*9*numberOfMatrices); if (updated) { glUniformMatrix3fv( (GLint)location, (GLsizei)numberOfMatrices, GL_FALSE, matrixArray); } } void GLProgram::<API key>(GLint location, const GLfloat* matrixArray, unsigned int numberOfMatrices) { bool updated = <API key>(location, matrixArray, sizeof(float)*16*numberOfMatrices); if (updated) { glUniformMatrix4fv( (GLint)location, (GLsizei)numberOfMatrices, GL_FALSE, matrixArray); } } void GLProgram::<API key>() { <API key>(_director->getMatrix(MATRIX_STACK_TYPE::<API key>)); } void GLProgram::<API key>(const Mat4 &matrixMV) { auto& matrixP = _director->getMatrix(MATRIX_STACK_TYPE::<API key>); if (_flags.usesP) <API key>(_builtInUniforms[UNIFORM_P_MATRIX], matrixP.m, 1); if (_flags.usesMV) <API key>(_builtInUniforms[UNIFORM_MV_MATRIX], matrixMV.m, 1); if (_flags.usesMVP) { Mat4 matrixMVP = matrixP * matrixMV; <API key>(_builtInUniforms[UNIFORM_MVP_MATRIX], matrixMVP.m, 1); } if (_flags.usesNormal) { Mat4 mvInverse = matrixMV; mvInverse.m[12] = mvInverse.m[13] = mvInverse.m[14] = 0.0f; mvInverse.inverse(); mvInverse.transpose(); GLfloat normalMat[9]; normalMat[0] = mvInverse.m[0];normalMat[1] = mvInverse.m[1];normalMat[2] = mvInverse.m[2]; normalMat[3] = mvInverse.m[4];normalMat[4] = mvInverse.m[5];normalMat[5] = mvInverse.m[6]; normalMat[6] = mvInverse.m[8];normalMat[7] = mvInverse.m[9];normalMat[8] = mvInverse.m[10]; <API key>(_builtInUniforms[<API key>], normalMat, 1); } if (_flags.usesTime) { // This doesn't give the most accurate global time value. // Cocos2D doesn't store a high precision time value, so this will have to do. // Getting Mach time per frame per shader using time could be extremely expensive. float time = _director->getTotalFrames() * _director-><API key>(); <API key>(_builtInUniforms[GLProgram::UNIFORM_TIME], time/10.0, time, time*2, time*4); <API key>(_builtInUniforms[GLProgram::UNIFORM_SIN_TIME], time/8.0, time/4.0, time/2.0, sinf(time)); <API key>(_builtInUniforms[GLProgram::UNIFORM_COS_TIME], time/8.0, time/4.0, time/2.0, cosf(time)); } if (_flags.usesRandom) <API key>(_builtInUniforms[GLProgram::UNIFORM_RANDOM01], CCRANDOM_0_1(), CCRANDOM_0_1(), CCRANDOM_0_1(), CCRANDOM_0_1()); } void GLProgram::reset() { _vertShader = _fragShader = 0; memset(_builtInUniforms, 0, sizeof(_builtInUniforms)); // it is already deallocated by android //GL::deleteProgram(_program); _program = 0; for (auto e: _hashForUniforms) { free(e.second.first); } _hashForUniforms.clear(); } inline void GLProgram::clearShader() { if (_vertShader) { glDeleteShader(_vertShader); } if (_fragShader) { glDeleteShader(_fragShader); } _vertShader = _fragShader = 0; } NS_CC_END
author: jeffatwood comments: true date: 2009-04-17 06:24:44+00:00 layout: post redirect_from: /2009/04/<API key> slug: <API key> title: The Stack Overflow Question Lifecycle wordpress_id: 1074 tags: - company - community - design Apparently some users [who really should know better](http: Stack Overflow is, at its heart, a Question and Answer site. So the **lifecycle of any given question** is, by definition, how the site works. I've documented it in a series of blog posts over the last few months, but let's put it all together in Reader's Digest form right here: ## Stack Overflow is a community of programmers Right off the bat, [if your question is not programming related](http://blog.stackoverflow.com/2008/10/<API key>/), it shouldn't be on Stack Overflow. What is a programming related question? Here's a solid set of guidelines generated by the SO community itself: * Questions intended to resolve a specific programming problem that have multiple possible answers. The "correct" response is subjective. * Questions intended to resolve a specific programming problem that have only one correct answer. A "specific programming problem" can be defined as a problem that exists in code and that can be resolved with correct code (or cannot be resolved at all). These questions are normally language-specific. * Questions about language-agnostic algorithms for hypothetical problems that have potential real-world applications. For example, traveling salesman or BSP. * Questions about best practices and other aspects of programming, including use of software tools used in the development process, standards for maintenance and readability of code, advice to avoid potential coding pitfalls, etc. * Questions about software tools that, while not directly related to software development, involve some scripting or programming themselves, for example, Excel or Matlab. Look at the above guidelines, and ask yourself: **Does my question fit?** If you believe it does, awesome! Ask away! If it doesn't fit, it doesn't mean that you're a bad person for wanting to ask that question. It just means that you should probably ask it elsewhere. If, however, you ask a question that is not a good fit for Stack Overflow, then.. ## Who decides what questions don't fit? Trusted members of the Stack Overflow community decide which questions belong on Stack Overflow. Every question goes through a community vetting process: 1. You see a question that is inappropriate for Stack Overflow because it's [not programming related](http://blog.stackoverflow.com/2008/10/<API key>/). 2. You have 3,000 reputation, the minimum required to cast close or open votes. 3. You vote to close this question. 4. Four (4) other users also vote to close this question, reaching a total of five (5) closure votes (or, a moderator votes to close -- moderator votes are binding.) 5. Once closed, the question can be reopened by voting to open in the same manner. If the question garners five (5) votes to reopen, the process starts over at step 6. If question **remains closed for 48 full hours**, it is now eligible for deletion. 7. You have 10,000 reputation, the minimum required to cast deletion votes. 8. If the question gets three (3) deletion votes (or a moderator vote), the question is deleted. 9. Note that deleted questions are invisible to typical users -- but can be seen by moderators and users with 10,000+ reputation. 10. The question can be undeleted at any time by voting for undeletion in the same manner. If the question garners three votes for undeletion, the process starts over at step No, it is not a perfect process, because not everyone agrees all the time. If this surprises or shocks you in any way, I'd like to gently remind you that the earth you're currently living on is populated by these things we call "human beings". And disagreement is, believe it or not, _normal_. Expected, even. As one Stack Overflow user said: <blockquote> Congratulations...you've found an inconsistency in the world. If only there were some way for you to reconcile it. </blockquote> If you're looking for a perfectly consistent system, you'll need to invent robots to implement that system, first. As long as people are involved, the only constant is this: **there will always be inconsistency**. (And just for the record, it is OK to have fun <API key> questions that the community likes every now and then -- as long as the system isn't overrun with the things.) ## Why do you allow content to be deleted? Just like death is an unfortunate but normal part of life, [I believe deletion is also an unfortunate but normal part of living websites](http://blog.stackoverflow.com/2009/01/<API key>/). Who can delete posts? * **Post authors** can delete their answers. But they can only delete their questions when there are no significantly upvoted answers to the question. * **Users with 10,000+ reputation** can delete questions that have been closed for 48 hours, if they cast three (3) votes for deletion. Questions can be undeleted through the same process in reverse. * **Moderators** can delete anything. Why would you _delete_ a question? Isn't closing it enough? * Some questions are of such poor quality that they _cannot_ be salvaged. They're literally nonsense. Not every byte of data that is created in the world is infinite and sacred. * Some questions are so incredibly off topic that they add no value to a programming community. * The mental cost of processing these closed questions is _not_ zero, particularly for users who are actively engaged and scanning questions to find things they can help answer. * If users see a lot of closed questions, they'll note that we don't enforce the guidelines, so why should they? Without any final resolution, asking questions that get closed becomes something we are implicitly encouraging -- a [broken windows problem](http://en.wikipedia.org/wiki/<API key>). If this goes on for long enough, we're no longer a community of programmers who ask and answer programming questions, we're a community of random people discussing.. whatever. That's toxic. * If enough of these closed questions are allowed to hang around, they become clutter that reduces the overall signal to noise ratio -- which further reduces confidence in the system. Let me be clear: we do not _seek out_ deletion, by any means. But we believe not **having the guts to cull some of your worst content** is much, much more dangerous to your community than letting it sit around forever in the vague hope that it will magically get better over time. Hopefully this clears up the bulk of any confusion about the lifecycle of a question on Stack Overflow. As I said, I'll try to get the essential parts of this in the faq.
// CodeContracts using System.Diagnostics.Contracts; using System; namespace System.Reflection.Emit { public class UnmanagedMarshal { public System.Runtime.InteropServices.UnmanagedType BaseType { get; } public int ElementCount { get; } public System.Runtime.InteropServices.UnmanagedType GetUnmanagedType { get; } public Guid IIDGuid { get; } public static UnmanagedMarshal DefineLPArray (System.Runtime.InteropServices.UnmanagedType elemType) { return default(UnmanagedMarshal); } public static UnmanagedMarshal DefineByValArray (int elemCount) { return default(UnmanagedMarshal); } public static UnmanagedMarshal DefineSafeArray (System.Runtime.InteropServices.UnmanagedType elemType) { return default(UnmanagedMarshal); } public static UnmanagedMarshal DefineByValTStr (int elemCount) { return default(UnmanagedMarshal); } public static UnmanagedMarshal <API key> (System.Runtime.InteropServices.UnmanagedType unmanagedType) { CodeContract.Requires((int)unmanagedType != 23); CodeContract.Requires((int)unmanagedType != 29); CodeContract.Requires((int)unmanagedType != 30); CodeContract.Requires((int)unmanagedType != 42); CodeContract.Requires((int)unmanagedType != 44); return default(UnmanagedMarshal); } } }
var express = require('../') , request = require('./support/http') , assert = require('assert'); describe('HEAD', function(){ it('should default to GET', function(done){ var app = express(); app.get('/tobi', function(req, res){ // send() detects HEAD res.send('tobi'); }); request(app) .head('/tobi') .expect(200, done); }) }) describe('app.head()', function(){ it('should override', function(done){ var app = express() , called; app.head('/tobi', function(req, res){ called = true; res.end(''); }); app.get('/tobi', function(req, res){ assert(0, 'should not call GET'); res.send('tobi'); }); request(app) .head('/tobi') .expect(200, function(){ assert(called); done(); }); }) })
CKEDITOR.plugins.setLang( 'uicolor', 'fr-ca', { title: 'Sélecteur de couleur', preview: 'Aperçu', config: 'Insérez cette ligne dans votre fichier config.js', predefined: 'Ensemble de couleur prédéfinies' } );
// CodeContracts // File System.ServiceModel.Configuration.<API key>.cs // Automatically generated contract file. using System.Collections.Generic; using System.IO; using System.Text; using System.Diagnostics.Contracts; using System; // Disable the "this variable is not used" warning as every field would imply it. #pragma warning disable 0414 // Disable the "this variable is never assigned to". #pragma warning disable 0067 // Disable the "this event is never assigned to". #pragma warning disable 0649 // Disable the "this variable is never used". #pragma warning disable 0169 // Disable the "new keyword not required" warning. #pragma warning disable 0109 // Disable the "extern without DllImport" warning. #pragma warning disable 0626 // Disable the "could hide other member" warning, can happen on certain properties. #pragma warning disable 0108 namespace System.ServiceModel.Configuration { public partial class <API key> : <API key> { #region Methods and constructors protected internal override void InitializeFrom(System.ServiceModel.Channels.Binding binding) { } protected override void <API key>(System.ServiceModel.Channels.Binding binding) { } public <API key>(string name) { } public <API key>() { } #endregion #region Properties and indexers protected override Type BindingElementType { get { return default(Type); } } public Uri PrivacyNoticeAt { get { return default(Uri); } set { } } public int <API key> { get { return default(int); } set { } } protected override System.Configuration.<API key> Properties { get { return default(System.Configuration.<API key>); } } public <API key> Security { get { return default(<API key>); } } #endregion } }
// CodeContracts using System.Diagnostics.Contracts; using System; namespace System.Net.Sockets { public class IPv6MulticastOption { public System.Net.IPAddress! Group { get; set Contract.Requires(value != null); } public Int64 InterfaceIndex { get; set Contract.Requires(value >= 0); Contract.Requires(value <= -1); } public IPv6MulticastOption (System.Net.IPAddress! group) { Contract.Requires(group != null); return default(IPv6MulticastOption); } public IPv6MulticastOption (System.Net.IPAddress! group, Int64 ifindex) { Contract.Requires(group != null); Contract.Requires(ifindex >= 0); Contract.Requires(ifindex <= -1); return default(IPv6MulticastOption); } } }
#include "crypto_aead.h" #include "pi-cipher.h" #include "api.h" /* void PI_ENCRYPT_SIMPLE( void *cipher, uint16_t *cipher_len_B, void *tag, uint16_t *tag_length_B, const void *msg, uint16_t msg_len_B, const void *ad, uint16_t ad_len_B, const void *nonce_secret, const void *nonce_public, uint16_t nonce_public_len_B, const void *key, uint16_t key_len_B ); */ int crypto_aead_encrypt( unsigned char *c,unsigned long long *clen, const unsigned char *m,unsigned long long mlen, const unsigned char *ad,unsigned long long adlen, const unsigned char *nsec, const unsigned char *npub, const unsigned char *k ) { /* the code for the cipher implementation goes here, generating a ciphertext c[0],c[1],...,c[*clen-1] from a plaintext m[0],m[1],...,m[mlen-1] and associated data ad[0],ad[1],...,ad[adlen-1] and secret message number nsec[0],nsec[1],... and public message number npub[0],npub[1],... and secret key k[0],k[1],... */ size_t x; PI_ENCRYPT_SIMPLE( c, &x, m, mlen, ad, adlen, nsec, npub, CRYPTO_NPUBBYTES, k, CRYPTO_KEYBYTES ); *clen = x; return 0; } /* int PI_DECRYPT_SIMPLE( void *msg, uint16_t *msg_len_B, void *nonce_secret, const void *cipher, uint16_t cipher_len_B, const void *ad, uint16_t ad_len_B, const void *nonce_public, uint16_t nonce_public_len_B, const void *key, uint16_t key_len_B ); */ int crypto_aead_decrypt( unsigned char *m,unsigned long long *mlen, unsigned char *nsec, const unsigned char *c,unsigned long long clen, const unsigned char *ad,unsigned long long adlen, const unsigned char *npub, const unsigned char *k ) { /* the code for the cipher implementation goes here, generating a plaintext m[0],m[1],...,m[*mlen-1] and secret message number nsec[0],nsec[1],... from a ciphertext c[0],c[1],...,c[clen-1] and associated data ad[0],ad[1],...,ad[adlen-1] and public message number npub[0],npub[1],... and secret key k[0],k[1],... */ int r; size_t ml; r = PI_DECRYPT_SIMPLE( m, &ml, nsec, c, clen, ad, adlen, npub, CRYPTO_NPUBBYTES, k, CRYPTO_KEYBYTES ); *mlen = ml; return r; }
<?php defined('C5_EXECUTE') or die("Access Denied."); class <API key> extends BlockController { public $btTable = 'btForm'; public $<API key> = 'btFormQuestions'; public $<API key> = 'btFormAnswerSet'; public $btAnswersTablename = 'btFormAnswers'; public $btInterfaceWidth = '420'; public $btInterfaceHeight = '430'; public $thankyouMsg=''; public $<API key>=0; protected $btExportTables = array('btForm', 'btFormQuestions'); protected $btExportPageColumns = array('redirectCID'); protected $lastAnswerSetId=0; /** * Used for localization. If we want to localize the name/description we have to include this */ public function <API key>() { return t("Build simple forms and surveys."); } public function getBlockTypeName() { return t("Form"); } public function <API key>() { return array( 'delete-question' => t('Are you sure you want to delete this question?'), 'form-name' => t('Your form must have a name.'), 'complete-required' => t('Please complete all required fields.'), 'ajax-error' => t('AJAX Error.'), 'form-min-1' => t('Please add at least one question to your form.') ); } protected function <API key>($b, $blockNode) { if (isset($blockNode->data)) { foreach($blockNode->data as $data) { if ($data['table'] != $this-><API key>()) { $table = (string) $data['table']; if (isset($data->record)) { foreach($data->record as $record) { $aar = new ADODB_Active_Record($table); $aar->bID = $b->getBlockID(); foreach($record->children() as $node) { $nodeName = $node->getName(); $aar->{$nodeName} = (string) $node; } if ($table == 'btFormQuestions') { $db = Loader::db(); $aar->questionSetId = $db->GetOne('select questionSetId from btForm where bID = ?', array($b->getBlockID())); } $aar->Save(); } } } } } } public function __construct($b = null){ parent::__construct($b); //$this->bID = intval($this->_bID); if(is_string($this->thankyouMsg) && !strlen($this->thankyouMsg)){ $this->thankyouMsg = $this-><API key>(); } } public function on_page_view() { if ($this-><API key>()) { $this->addHeaderItem(Loader::helper('html')->css('jquery.ui.css')); $this->addFooterItem(Loader::helper('html')->javascript('jquery.ui.js')); } } //Internal helper function private function <API key>() { $whereInputTypes = "inputType = 'date' OR inputType = 'datetime'"; $sql = "SELECT COUNT(*) FROM {$this-><API key>} WHERE questionSetID = ? AND bID = ? AND ({$whereInputTypes})"; $vals = array(intval($this->questionSetId), intval($this->bID)); $JQUIFieldCount = Loader::db()->GetOne($sql, $vals); return (bool)$JQUIFieldCount; } public function <API key>() { return t("Thanks!"); } //form add or edit submit //(run after the duplicate method on first block edit of new page version) function save( $data=array() ) { if( !$data || count($data)==0 ) $data=$_POST; $b=$this->getBlockObject(); $c=$b-><API key>(); $db = Loader::db(); if(intval($this->bID)>0){ $q = "select count(*) as total from {$this->btTable} where bID = ".intval($this->bID); $total = $db->getOne($q); }else $total = 0; if($_POST['qsID']) $data['qsID']=$_POST['qsID']; if( !$data['qsID'] ) $data['qsID']=time(); if(!$data['oldQsID']) $data['oldQsID']=$data['qsID']; $data['bID']=intval($this->bID); if(!empty($data['redirectCID'])) { $data['redirect'] = 1; } else { $data['redirect'] = 0; $data['redirectCID'] = 0; } if(empty($data['addFilesToSet'])) { $data['addFilesToSet'] = 0; } $v = array( $data['qsID'], $data['surveyName'], intval($data['<API key>']), $data['recipientEmail'], $data['thankyouMsg'], intval($data['displayCaptcha']), intval($data['redirectCID']), intval($data['addFilesToSet']), intval($this->bID) ); //is it new? if( intval($total)==0 ){ $q = "insert into {$this->btTable} (questionSetId, surveyName, <API key>, recipientEmail, thankyouMsg, displayCaptcha, redirectCID, addFilesToSet, bID) values (?, ?, ?, ?, ?, ?, ?, ?, ?)"; }else{ $q = "update {$this->btTable} set questionSetId = ?, surveyName=?, <API key>=?, recipientEmail=?, thankyouMsg=?, displayCaptcha=?, redirectCID=?, addFilesToSet=? where bID = ? AND questionSetId=".$data['qsID']; } $rs = $db->query($q,$v); //Add Questions (for programmatically creating forms, such as during the site install) if( count($data['questions'])>0 ){ $miniSurvey = new MiniSurvey(); foreach( $data['questions'] as $questionData ) $miniSurvey->addEditQuestion($questionData,0); } $this->questionVersioning($data); return true; } //Ties the new or edited questions to the new block number //New and edited questions are temporarily given bID=0, until the block is saved... painfully complicated protected function questionVersioning( $data=array() ){ $db = Loader::db(); $oldBID = intval($data['bID']); //if this block is being edited a second time, remove edited questions with the current bID that are pending replacement //if( intval($oldBID) == intval($this->bID) ){ $vals=array( intval($data['oldQsID']) ); $pendingQuestions=$db->getAll('SELECT msqID FROM btFormQuestions WHERE bID=0 && questionSetId=?',$vals); foreach($pendingQuestions as $pendingQuestion){ $vals=array( intval($this->bID), intval($pendingQuestion['msqID']) ); $db->query('DELETE FROM btFormQuestions WHERE bID=? AND msqID=?',$vals); } //assign any new questions the new block id $vals=array( intval($data['bID']), intval($data['qsID']), intval($data['oldQsID']) ); $rs=$db->query('UPDATE btFormQuestions SET bID=?, questionSetId=? WHERE bID=0 && questionSetId=?',$vals); //These are deleted or edited questions. (edited questions have already been created with the new bID). $<API key>=explode( ',', $data['ignoreQuestionIDs'] ); $ignoreQuestionIDs=array(0); foreach($<API key> as $msqID) $ignoreQuestionIDs[]=intval($msqID); $ignoreQuestionIDstr=join(',',$ignoreQuestionIDs); //remove any questions that are pending deletion, that already have this current bID $<API key>=explode( ',', $data['pendingDeleteIDs'] ); $pendingDeleteQIDs=array(); foreach($<API key> as $msqID) $pendingDeleteQIDs[]=intval($msqID); $vals=array( $this->bID, intval($data['qsID']), join(',',$pendingDeleteQIDs) ); $unchangedQuestions=$db->query('DELETE FROM btFormQuestions WHERE bID=? AND questionSetId=? AND msqID IN (?)',$vals); } //Duplicate will run when copying a page with a block, or editing a block for the first time within a page version (before the save). function duplicate($newBID) { $b=$this->getBlockObject(); $c=$b-><API key>(); $db = Loader::db(); $v = array($this->bID); $q = "select * from {$this->btTable} where bID = ? LIMIT 1"; $r = $db->query($q, $v); $row = $r->fetchRow(); //if the same block exists in multiple collections with the same questionSetID if(count($row)>0){ $oldQuestionSetId=$row['questionSetId']; //It should only generate a new question set id if the block is copied to a new page, //otherwise it will loose all of its answer sets (from all the people who've used the form on this page) $questionSetCIDs=$db->getCol("SELECT distinct cID FROM {$this->btTable} AS f, <API key> AS cvb ". "WHERE f.bID=cvb.bID AND questionSetId=".intval($row['questionSetId']) ); //this question set id is used on other pages, so make a new one for this page block if( count( $questionSetCIDs ) >1 || !in_array( $c->cID, $questionSetCIDs ) ){ $newQuestionSetId=time(); $_POST['qsID']=$newQuestionSetId; }else{ //otherwise the question set id stays the same $newQuestionSetId=$row['questionSetId']; } //duplicate survey block record //with a new Block ID and a new Question $v = array($newQuestionSetId,$row['surveyName'],$newBID,$row['thankyouMsg'],intval($row['<API key>']),$row['recipientEmail'],$row['displayCaptcha'], $row['addFilesToSet']); $q = "insert into {$this->btTable} ( questionSetId, surveyName, bID,thankyouMsg,<API key>,recipientEmail,displayCaptcha,addFilesToSet) values (?, ?, ?, ?, ?, ?, ?,?)"; $result=$db->Execute($q, $v); $rs=$db->query("SELECT * FROM {$this-><API key>} WHERE questionSetId=$oldQuestionSetId AND bID=".intval($this->bID) ); while( $row=$rs->fetchRow() ){ $v=array($newQuestionSetId,intval($row['msqID']), intval($newBID), $row['question'],$row['inputType'],$row['options'],$row['position'],$row['width'],$row['height'],$row['required']); $sql= "INSERT INTO {$this-><API key>} (questionSetId,msqID,bID,question,inputType,options,position,width,height,required) VALUES (?,?,?,?,?,?,?,?,?,?)"; $db->Execute($sql, $v); } return $newQuestionSetId; } return 0; } //users submits the completed survey function action_submit_form() { $ip = Loader::helper('validation/ip'); Loader::library("file/importer"); if (!$ip->check()) { $this->set('invalidIP', $ip->getErrorMessage()); return; } $txt = Loader::helper('text'); $db = Loader::db(); //question set id $qsID=intval($_POST['qsID']); if($qsID==0) throw new Exception(t("Oops, something is wrong with the form you posted (it doesn't have a question set id).")); //get all questions for this question set $rows=$db->GetArray("SELECT * FROM {$this-><API key>} WHERE questionSetId=? AND bID=? order by position asc, msqID", array( $qsID, intval($this->bID))); // check captcha if activated if ($this->displayCaptcha) { $captcha = Loader::helper('validation/captcha'); if (!$captcha->check()) { $errors['captcha'] = t("Incorrect captcha code"); $_REQUEST['ccmCaptchaCode']=''; } } //checked required fields foreach($rows as $row){ if ($row['inputType']=='datetime'){ if (!isset($datetime)) { $datetime = Loader::helper("form/date_time"); } $translated = $datetime->translate('Question'.$row['msqID']); if ($translated) { $_POST['Question'.$row['msqID']] = $translated; } } if( intval($row['required'])==1 ){ $notCompleted=0; if ($row['inputType'] == 'email') { if (!Loader::helper('validation/strings')->email($_POST['Question' . $row['msqID']])) { $errors['emails'] = t('You must enter a valid email address.'); } } if($row['inputType']=='checkboxlist'){ $answerFound=0; foreach($_POST as $key=>$val){ if( strstr($key,'Question'.$row['msqID'].'_') && strlen($val) ){ $answerFound=1; } } if(!$answerFound) $notCompleted=1; }elseif($row['inputType']=='fileupload'){ if( !isset($_FILES['Question'.$row['msqID']]) || !is_uploaded_file($_FILES['Question'.$row['msqID']]['tmp_name']) ) $notCompleted=1; }elseif( !strlen(trim($_POST['Question'.$row['msqID']])) ){ $notCompleted=1; } if($notCompleted) $errors['CompleteRequired'] = t("Complete required fields *") ; } } //try importing the file if everything else went ok $tmpFileIds=array(); if(!count($errors)) foreach($rows as $row){ if( $row['inputType']!='fileupload' ) continue; $questionName='Question'.$row['msqID']; if ( !intval($row['required']) && ( !isset($_FILES[$questionName]['tmp_name']) || !is_uploaded_file($_FILES[$questionName]['tmp_name']) ) ){ continue; } $fi = new FileImporter(); $resp = $fi->import($_FILES[$questionName]['tmp_name'], $_FILES[$questionName]['name']); if (!($resp instanceof FileVersion)) { switch($resp) { case FileImporter::<API key>: $errors['fileupload'] = t('Invalid file extension.'); break; case FileImporter::E_FILE_INVALID: $errors['fileupload'] = t('Invalid file.'); break; } }else{ $tmpFileIds[intval($row['msqID'])] = $resp->getFileID(); if(intval($this->addFilesToSet)) { Loader::model('file_set'); $fs = new FileSet(); $fs = $fs->getByID($this->addFilesToSet); if($fs->getFileSetID()) { $fs->addFileToSet($resp); } } } } if(count($errors)){ $this->set('formResponse', t('Please correct the following errors:') ); $this->set('errors',$errors); $this->set('Entry',$E); }else{ //no form errors //save main survey record $u = new User(); $uID = 0; if ($u->isRegistered()) { $uID = $u->getUserID(); } $q="insert into {$this-><API key>} (questionSetId, uID) values (?,?)"; $db->query($q,array($qsID, $uID)); $answerSetID=$db->Insert_ID(); $this->lastAnswerSetId=$answerSetID; $questionAnswerPairs=array(); if( strlen(<API key>)>1 && strstr(<API key>,'@') ){ $<API key> = <API key>; }else{ $adminUserInfo=UserInfo::getByID(USER_SUPER_ID); $<API key> = $adminUserInfo->getUserEmail(); } $replyToEmailAddress = $<API key>; //loop through each question and get the answers foreach( $rows as $row ){ //save each answer if($row['inputType']=='checkboxlist'){ $answer = Array(); $answerLong=""; $keys = array_keys($_POST); foreach ($keys as $key){ if (strpos($key, 'Question'.$row['msqID'].'_') === 0){ $answer[]=$txt->sanitize($_POST[$key]); } } }elseif($row['inputType']=='text'){ $answerLong=$txt->sanitize($_POST['Question'.$row['msqID']]); $answer=''; }elseif($row['inputType']=='fileupload'){ $answer=intval( $tmpFileIds[intval($row['msqID'])] ); }elseif($row['inputType']=='url'){ $answerLong=""; $answer=$txt->sanitize($_POST['Question'.$row['msqID']]); }elseif($row['inputType']=='email'){ $answerLong=""; $answer=$txt->sanitize($_POST['Question'.$row['msqID']]); if(!empty($row['options'])) { $settings = unserialize($row['options']); if(is_array($settings) && array_key_exists('<API key>', $settings) && $settings['<API key>'] == 1) { $email = $txt->email($answer); if(!empty($email)) { $replyToEmailAddress = $email; } } } }elseif($row['inputType']=='telephone'){ $answerLong=""; $answer=$txt->sanitize($_POST['Question'.$row['msqID']]); }else{ $answerLong=""; $answer=$txt->sanitize($_POST['Question'.$row['msqID']]); } if( is_array($answer) ) $answer=join(',',$answer); $questionAnswerPairs[$row['msqID']]['question']=$row['question']; $questionAnswerPairs[$row['msqID']]['answer']=$txt->sanitize( $answer.$answerLong ); $v=array($row['msqID'],$answerSetID,$answer,$answerLong); $q="insert into {$this->btAnswersTablename} (msqID,asID,answer,answerLong) values (?,?,?,?)"; $db->query($q,$v); } $foundSpam = false; $submittedData = ''; foreach($questionAnswerPairs as $questionAnswerPair){ $submittedData .= $questionAnswerPair['question']."\r\n".$questionAnswerPair['answer']."\r\n"."\r\n"; } $antispam = Loader::helper('validation/antispam'); if (!$antispam->check($submittedData, 'form_block')) { // found to be spam. We remove it $foundSpam = true; $q="delete from {$this-><API key>} where asID = ?"; $v = array($this->lastAnswerSetId); $db->Execute($q, $v); $db->Execute('delete from {$this->btAnswersTablename} where asID = ?', array($this->lastAnswerSetId)); } if(intval($this-><API key>)>0 && !$foundSpam){ if ($this->sendEmailFrom !== false) { $<API key> = $this->sendEmailFrom; } else if( strlen(<API key>)>1 && strstr(<API key>,'@') ){ $<API key> = <API key>; }else{ $adminUserInfo=UserInfo::getByID(USER_SUPER_ID); $<API key> = $adminUserInfo->getUserEmail(); } $mh = Loader::helper('mail'); $mh->to( $this->recipientEmail ); $mh->from( $<API key> ); $mh->replyto( $replyToEmailAddress ); $mh->addParameter('formName', $this->surveyName); $mh->addParameter('questionSetId', $this->questionSetId); $mh->addParameter('questionAnswerPairs', $questionAnswerPairs); $mh->load('<API key>'); $mh->setSubject(t('%s Form Submission', $this->surveyName)); //echo $mh->body.'<br>'; @$mh->sendMail(); } if (!$this-><API key>) { if ($this->redirectCID > 0) { $pg = Page::getByID($this->redirectCID); if (is_object($pg) && $pg->cID) { $this->redirect($pg->getCollectionPath()); } } $c = Page::getCurrentPage(); header("Location: ".Loader::helper('navigation')->getLinkToCollection($c, true)."?surveySuccess=1&qsid=".$this->questionSetId."#".$this->questionSetId); exit; } } } function delete() { $db = Loader::db(); $deleteData['questionsIDs']=array(); $deleteData['<API key>']=array(); $miniSurvey=new MiniSurvey(); $info=$miniSurvey-><API key>($this->bID); //get all answer sets $q = "SELECT asID FROM {$this-><API key>} WHERE questionSetId = ".intval($info['questionSetId']); $answerSetsRS = $db->query($q); //delete the questions $deleteData['questionsIDs']=$db->getAll( "SELECT qID FROM {$this-><API key>} WHERE questionSetId = ".intval($info['questionSetId']).' AND bID='.intval($this->bID) ); foreach($deleteData['questionsIDs'] as $questionData) $db->query("DELETE FROM {$this-><API key>} WHERE qID=".intval($questionData['qID'])); //delete left over answers $strandedAnswerIDs = $db->getAll('SELECT fa.aID FROM `btFormAnswers` AS fa LEFT JOIN btFormQuestions as fq ON fq.msqID=fa.msqID WHERE fq.msqID IS NULL'); foreach($strandedAnswerIDs as $strandedAnswerIDs) $db->query('DELETE FROM `btFormAnswers` WHERE aID='.intval($strandedAnswer['aID'])); //delete the left over answer sets $deleteData['<API key>'] = $db->getAll('SELECT aset.asID FROM btFormAnswerSet AS aset LEFT JOIN btFormAnswers AS fa ON aset.asID=fa.asID WHERE fa.asID IS NULL'); foreach($deleteData['<API key>'] as $<API key>) $db->query('DELETE FROM btFormAnswerSet WHERE asID='.intval($<API key>['asID'])); //delete the form block $q = "delete from {$this->btTable} where bID = '{$this->bID}'"; $r = $db->query($q); parent::delete(); return $deleteData; } }
(function( window, angular, undefined ){ "use strict"; /* * @ngdoc module * @name material.components.backdrop * @description Backdrop */ /** * @ngdoc directive * @name mdBackdrop * @module material.components.backdrop * * @restrict E * * @description * `<md-backdrop>` is a backdrop element used by other components, such as dialog and bottom sheet. * Apply class `opaque` to make the backdrop use the theme backdrop color. * */ angular .module('material.components.backdrop', ['material.core']) .directive('mdBackdrop', ["$mdTheming", "$animate", "$rootElement", "$window", "$log", "$$rAF", "$document", function BackdropDirective($mdTheming, $animate, $rootElement, $window, $log, $$rAF, $document) { var ERROR_CSS_POSITION = "<md-backdrop> may not work properly in a scrolled, static-positioned parent container."; return { restrict: 'E', link: postLink }; function postLink(scope, element, attrs) { // If body scrolling has been disabled using mdUtil.disableBodyScroll(), // adjust the 'backdrop' height to account for the fixed 'body' top offset var body = $window.getComputedStyle($document[0].body); if (body.position == 'fixed') { var hViewport = parseInt(body.height, 10) + Math.abs(parseInt(body.top, 10)); element.css({ height: hViewport + 'px' }); } // backdrop may be outside the $rootElement, tell ngAnimate to animate regardless if ($animate.pin) $animate.pin(element, $rootElement); $$rAF(function () { // Often $animate.enter() is used to append the backDrop element // so let's wait until $animate is done... var parent = element.parent()[0]; if (parent) { var styles = $window.getComputedStyle(parent); if (styles.position == 'static') { // backdrop uses position:absolute and will not work properly with parent position:static (default) $log.warn(ERROR_CSS_POSITION); } } $mdTheming.inherit(element, element.parent()); }); } }]); })(window, window.angular);
"""The tests for the weblink component.""" import unittest from homeassistant.components import weblink from tests.common import <API key> class <API key>(unittest.TestCase): """Test the Weblink component.""" def setUp(self): """Setup things to be run when tests are started.""" self.hass = <API key>() def tearDown(self): """Stop everything that was started.""" self.hass.stop() def <API key>(self): """Test if new entity is created.""" self.assertTrue(weblink.setup(self.hass, { weblink.DOMAIN: { 'entities': [ { weblink.ATTR_NAME: 'My router', weblink.ATTR_URL: 'http://127.0.0.1/' }, {} ] } })) state = self.hass.states.get('weblink.my_router') assert state is not None assert state.state == 'http://127.0.0.1/'
// Name: archive.h // Purpose: topic overview // RCS-ID: $Id$ // Licence: wxWindows licence /** @page overview_archive Archive Formats The archive classes handle archive formats such as zip, tar, rar and cab. Currently wxZip and wxTar classes are included. For each archive type, there are the following classes (using zip here as an example): @li wxZipInputStream: Input stream @li wxZipOutputStream: Output stream @li wxZipEntry: Holds meta-data for an entry (e.g. filename, timestamp, etc.) There are also abstract wxArchive classes that can be used to write code that can handle any of the archive types, see @ref <API key>. Also see wxFileSystem for a higher level interface that can handle archive files in a generic way. The classes are designed to handle archives on both seekable streams such as disk files, or non-seekable streams such as pipes and sockets (see @ref <API key>). See also wxFileSystem. @li @ref <API key> @li @ref <API key> @li @ref <API key> @li @ref <API key> @li @ref <API key> @li @ref <API key> <hr> @section <API key> Creating an Archive Call <API key>::PutNextEntry() to create each new entry in the archive, then write the entry's data. Another call to PutNextEntry() closes the current entry and begins the next. For example: @code wxFFileOutputStream out(wxT("test.zip")); wxZipOutputStream zip(out); wxTextOutputStream txt(zip); wxString sep(wxFileName::GetPathSeparator()); zip.PutNextEntry(wxT("entry1.txt")); txt << wxT("Some text for entry1.txt\n"); zip.PutNextEntry(wxT("subdir") + sep + wxT("entry2.txt")); txt << wxT("Some text for subdir/entry2.txt\n"); @endcode The name of each entry can be a full path, which makes it possible to store entries in subdirectories. @section <API key> Extracting an Archive <API key>::GetNextEntry() returns a pointer to entry object containing the meta-data for the next entry in the archive (and gives away ownership). Reading from the input stream then returns the entry's data. Eof() becomes @true after an attempt has been made to read past the end of the entry's data. When there are no more entries, GetNextEntry() returns @NULL and sets Eof(). @code auto_ptr<wxZipEntry> entry; wxFFileInputStream in(wxT("test.zip")); wxZipInputStream zip(in); while (entry.reset(zip.GetNextEntry()), entry.get() != NULL) { // access meta-data wxString name = entry->GetName(); // read 'zip' to access the entry's data } @endcode @section <API key> Modifying an Archive To modify an existing archive, write a new copy of the archive to a new file, making any necessary changes along the way and transferring any unchanged entries using <API key>::CopyEntry(). For archive types which compress entry data, CopyEntry() is likely to be much more efficient than transferring the data using Read() and Write() since it will copy them without decompressing and recompressing them. In general modifications are not possible without rewriting the archive, though it may be possible in some limited cases. Even then, rewriting the archive is usually a better choice since a failure can be handled without losing the whole archive. <API key> can be helpful to do this. For example to delete all entries matching the pattern "*.txt": @code auto_ptr<wxFFileInputStream> in(new wxFFileInputStream(wxT("test.zip"))); <API key> out(wxT("test.zip")); wxZipInputStream inzip(*in); wxZipOutputStream outzip(out); auto_ptr<wxZipEntry> entry; // transfer any meta-data for the archive as a whole (the zip comment // in the case of zip) outzip.CopyArchiveMetaData(inzip); // call CopyEntry for each entry except those matching the pattern while (entry.reset(inzip.GetNextEntry()), entry.get() != NULL) if (!entry->GetName().Matches(wxT("*.txt"))) if (!outzip.CopyEntry(entry.release(), inzip)) break; // close the input stream by releasing the pointer to it, do this // before closing the output stream so that the file can be replaced in.reset(); // you can check for success as follows bool success = inzip.Eof() && outzip.Close() && out.Commit(); @endcode @section <API key> Looking Up an Archive Entry by Name Also see wxFileSystem for a higher level interface that is more convenient for accessing archive entries by name. To open just one entry in an archive, the most efficient way is to simply search for it linearly by calling <API key>::GetNextEntry() until the required entry is found. This works both for archives on seekable and non-seekable streams. The format of filenames in the archive is likely to be different from the local filename format. For example zips and tars use unix style names, with forward slashes as the path separator, and absolute paths are not allowed. So if on Windows the file "C:\MYDIR\MYFILE.TXT" is stored, then when reading the entry back wxArchiveEntry::GetName() will return "MYDIR\MYFILE.TXT". The conversion into the internal format and back has lost some information. So to avoid ambiguity when searching for an entry matching a local name, it is better to convert the local name to the archive's internal format and search for that: @code auto_ptr<wxZipEntry> entry; // convert the local name we are looking for into the internal format wxString name = wxZipEntry::GetInternalName(localname); // open the zip wxFFileInputStream in(wxT("test.zip")); wxZipInputStream zip(in); // call GetNextEntry() until the required internal name is found do { entry.reset(zip.GetNextEntry()); } while (entry.get() != NULL && entry->GetInternalName() != name); if (entry.get() != NULL) { // read the entry's data... } @endcode To access several entries randomly, it is most efficient to transfer the entire catalogue of entries to a container such as a std::map or a wxHashMap then entries looked up by name can be opened using the <API key>::OpenEntry() method. @code <API key>(wxZipEntry*, ZipCatalog); ZipCatalog::iterator it; wxZipEntry *entry; ZipCatalog cat; // open the zip wxFFileInputStream in(wxT("test.zip")); wxZipInputStream zip(in); // load the zip catalog while ((entry = zip.GetNextEntry()) != NULL) { wxZipEntry*& current = cat[entry->GetInternalName()]; // some archive formats can have multiple entries with the same name // (e.g. tar) though it is an error in the case of zip delete current; current = entry; } // open an entry by name if ((it = cat.find(wxZipEntry::GetInternalName(localname))) != cat.end()) { zip.OpenEntry(*it->second); // ... now read entry's data } @endcode To open more than one entry simultaneously you need more than one underlying stream on the same archive: @code // opening another entry without closing the first requires another // input stream for the same file wxFFileInputStream in2(wxT("test.zip")); wxZipInputStream zip2(in2); if ((it = cat.find(wxZipEntry::GetInternalName(local2))) != cat.end()) zip2.OpenEntry(*it->second); @endcode @section <API key> Generic Archive Programming Also see wxFileSystem for a higher level interface that can handle archive files in a generic way. The specific archive classes, such as the wxZip classes, inherit from the following abstract classes which can be used to write code that can handle any of the archive types: @li <API key>: Input stream @li <API key>: Output stream @li wxArchiveEntry: Holds the meta-data for an entry (e.g. filename) In order to able to write generic code it's necessary to be able to create instances of the classes without knowing which archive type is being used. To allow this there is a class factory for each archive type, derived from <API key>, that can create the other classes. For example, given <API key>* factory, streams and entries can be created like this: @code // create streams without knowing their type auto_ptr<<API key>> inarc(factory->NewStream(in)); auto_ptr<<API key>> outarc(factory->NewStream(out)); // create an empty entry object auto_ptr<wxArchiveEntry> entry(factory->NewEntry()); @endcode For the factory itself, the static member <API key>::Find() can be used to find a class factory that can handle a given file extension or mime type. For example, given @e filename: @code const <API key> *factory; factory = <API key>::Find(filename, wxSTREAM_FILEEXT); if (factory) stream = factory->NewStream(new wxFFileInputStream(filename)); @endcode @e Find() does not give away ownership of the returned pointer, so it does not need to be deleted. There are similar class factories for the filter streams that handle the compression and decompression of a single stream, such as wxGzipInputStream. These can be found using <API key>::Find(). For example, to list the contents of archive @e filename: @code auto_ptr<wxInputStream> in(new wxFFileInputStream(filename)); if (in->IsOk()) { // look for a filter handler, e.g. for '.gz' const <API key> *fcf; fcf = <API key>::Find(filename, wxSTREAM_FILEEXT); if (fcf) { in.reset(fcf->NewStream(in.release())); // pop the extension, so if it was '.tar.gz' it is now just '.tar' filename = fcf->PopExtension(filename); } // look for a archive handler, e.g. for '.zip' or '.tar' const <API key> *acf; acf = <API key>::Find(filename, wxSTREAM_FILEEXT); if (acf) { auto_ptr<<API key>> arc(acf->NewStream(in.release())); auto_ptr<wxArchiveEntry> entry; // list the contents of the archive while ((entry.reset(arc->GetNextEntry())), entry.get() != NULL) std::wcout << entry->GetName().c_str() << "\n"; } else { wxLogError(wxT("can't handle '%s'"), filename.c_str()); } } @endcode @section <API key> Archives on Non-Seekable Streams In general, handling archives on non-seekable streams is done in the same way as for seekable streams, with a few caveats. The main limitation is that accessing entries randomly using <API key>::OpenEntry() is not possible, the entries can only be accessed sequentially in the order they are stored within the archive. For each archive type, there will also be other limitations which will depend on the order the entries' meta-data is stored within the archive. These are not too difficult to deal with, and are outlined below. @subsection <API key> PutNextEntry and the Entry Size When writing archives, some archive formats store the entry size before the entry's data (tar has this limitation, zip doesn't). In this case the entry's size must be passed to <API key>::PutNextEntry() or an error occurs. This is only an issue on non-seekable streams, since otherwise the archive output stream can seek back and fix up the header once the size of the entry is known. For generic programming, one way to handle this is to supply the size whenever it is known, and rely on the error message from the output stream when the operation is not supported. @subsection <API key> GetNextEntry and the Weak Reference Mechanism Some archive formats do not store all an entry's meta-data before the entry's data (zip is an example). In this case, when reading from a non-seekable stream, <API key>::GetNextEntry() can only return a partially populated wxArchiveEntry object - not all the fields are set. The input stream then keeps a weak reference to the entry object and updates it when more meta-data becomes available. A weak reference being one that does not prevent you from deleting the wxArchiveEntry object - the input stream only attempts to update it if it is still around. The documentation for each archive entry type gives the details of what meta-data becomes available and when. For generic programming, when the worst case must be assumed, you can rely on all the fields of wxArchiveEntry being fully populated when GetNextEntry() returns, with the the following exceptions: @li wxArchiveEntry::GetSize(): Guaranteed to be available after the entry has been read to wxInputStream::Eof(), or <API key>::CloseEntry() has been called. @li wxArchiveEntry::IsReadOnly(): Guaranteed to be available after the end of the archive has been reached, i.e. after GetNextEntry() returns @NULL and Eof() is @true. This mechanism allows <API key>::CopyEntry() to always fully preserve entries' meta-data. No matter what order order the meta-data occurs within the archive, the input stream will always have read it before the output stream must write it. @subsection <API key> wxArchiveNotifier Notifier objects can be used to get a notification whenever an input stream updates a wxArchiveEntry object's data via the weak reference mechanism. Consider the following code which renames an entry in an archive. This is the usual way to modify an entry's meta-data, simply set the required field before writing it with <API key>::CopyEntry(): @code auto_ptr<<API key>> arc(factory->NewStream(in)); auto_ptr<<API key>> outarc(factory->NewStream(out)); auto_ptr<wxArchiveEntry> entry; outarc->CopyArchiveMetaData(*arc); while (entry.reset(arc->GetNextEntry()), entry.get() != NULL) { if (entry->GetName() == from) entry->SetName(to); if (!outarc->CopyEntry(entry.release(), *arc)) break; } bool success = arc->Eof() && outarc->Close(); @endcode However, for non-seekable streams, this technique cannot be used for fields such as wxArchiveEntry::IsReadOnly(), which are not necessarily set when <API key>::GetNextEntry() returns. In this case a wxArchiveNotifier can be used: @code class MyNotifier : public wxArchiveNotifier { public: void OnEntryUpdated(wxArchiveEntry& entry) { entry.SetIsReadOnly(false); } }; @endcode The meta-data changes are done in your notifier's wxArchiveNotifier::OnEntryUpdated() method, then wxArchiveEntry::SetNotifier() is called before CopyEntry(): @code auto_ptr<<API key>> arc(factory->NewStream(in)); auto_ptr<<API key>> outarc(factory->NewStream(out)); auto_ptr<wxArchiveEntry> entry; MyNotifier notifier; outarc->CopyArchiveMetaData(*arc); while (entry.reset(arc->GetNextEntry()), entry.get() != NULL) { entry->SetNotifier(notifier); if (!outarc->CopyEntry(entry.release(), *arc)) break; } bool success = arc->Eof() && outarc->Close(); @endcode SetNotifier() calls OnEntryUpdated() immediately, then the input stream calls it again whenever it sets more fields in the entry. Since OnEntryUpdated() will be called at least once, this technique always works even when it is not strictly necessary to use it. For example, changing the entry name can be done this way too and it works on seekable streams as well as non-seekable. */
<?php namespace eZ\Publish\API\Repository\Tests; /** * Test case for operations in the ObjectStateService using in memory storage. * * @see eZ\Publish\API\Repository\ObjectStateService * @group integration * @group authorization */ class <API key> extends BaseTest { /** * Test for the <API key>() method. * * @see \eZ\Publish\API\Repository\ObjectStateService::<API key>() * @expectedException \eZ\Publish\API\Repository\Exceptions\<API key> * @depends eZ\Publish\API\Repository\Tests\<API key>::<API key> */ public function <API key>() { $repository = $this->getRepository(); $anonymousUserId = $this->generateId('user', 10); /* BEGIN: Use Case */ // $anonymousUserId is the ID of the "Anonymous" user in a eZ // Publish demo installation. // Set anonymous user $userService = $repository->getUserService(); $repository->setCurrentUser($userService->loadUser($anonymousUserId)); $objectStateService = $repository-><API key>(); $<API key> = $objectStateService-><API key>( 'publishing' ); $<API key>->defaultLanguageCode = 'eng-US'; $<API key>->names = array( 'eng-US' => 'Publishing', 'eng-GB' => 'Sindelfingen', ); $<API key>->descriptions = array( 'eng-US' => 'Put something online', 'eng-GB' => 'Put something ton Sindelfingen.', ); // Throws unauthorized exception, since the anonymous user must not // create object state groups $<API key> = $objectStateService-><API key>( $<API key> ); /* END: Use Case */ } /** * Test for the <API key>() method. * * @see \eZ\Publish\API\Repository\ObjectStateService::<API key>() * @expectedException \eZ\Publish\API\Repository\Exceptions\<API key> * @depends eZ\Publish\API\Repository\Tests\<API key>::<API key> */ public function <API key>() { $repository = $this->getRepository(); $objectStateGroupId = $this->generateId('objectstategroup', 2); $anonymousUserId = $this->generateId('user', 10); /* BEGIN: Use Case */ // $anonymousUserId is the ID of the "Anonymous" user in a eZ // Publish demo installation. // Set anonymous user $userService = $repository->getUserService(); $repository->setCurrentUser($userService->loadUser($anonymousUserId)); // $objectStateGroupId contains the ID of the standard object state // group ez_lock. $objectStateService = $repository-><API key>(); $<API key> = $objectStateService-><API key>( $objectStateGroupId ); $groupUpdateStruct = $objectStateService-><API key>(); $groupUpdateStruct->identifier = 'sindelfingen'; $groupUpdateStruct->defaultLanguageCode = 'ger-DE'; $groupUpdateStruct->names = array( 'ger-DE' => 'Sindelfingen', ); $groupUpdateStruct->descriptions = array( 'ger-DE' => 'Sindelfingen ist nicht nur eine Stadt', ); // Throws unauthorized exception, since the anonymous user must not // update object state groups $<API key> = $objectStateService-><API key>( $<API key>, $groupUpdateStruct ); /* END: Use Case */ } /** * Test for the <API key>() method. * * @see \eZ\Publish\API\Repository\ObjectStateService::<API key>() * @expectedException \eZ\Publish\API\Repository\Exceptions\<API key> * @depends eZ\Publish\API\Repository\Tests\<API key>::<API key> */ public function <API key>() { $repository = $this->getRepository(); $objectStateGroupId = $this->generateId('objectstategroup', 2); $anonymousUserId = $this->generateId('user', 10); /* BEGIN: Use Case */ // $anonymousUserId is the ID of the "Anonymous" user in a eZ // Publish demo installation. // Set anonymous user $userService = $repository->getUserService(); $repository->setCurrentUser($userService->loadUser($anonymousUserId)); // $objectStateGroupId contains the ID of the standard object state // group ez_lock. $objectStateService = $repository-><API key>(); $<API key> = $objectStateService-><API key>( $objectStateGroupId ); // Throws unauthorized exception, since the anonymous user must not // delete object state groups $objectStateService-><API key>($<API key>); /* END: Use Case */ } /** * Test for the createObjectState() method. * * @see \eZ\Publish\API\Repository\ObjectStateService::createObjectState() * @expectedException \eZ\Publish\API\Repository\Exceptions\<API key> * @depends eZ\Publish\API\Repository\Tests\<API key>::<API key> */ public function <API key>() { $repository = $this->getRepository(); $objectStateGroupId = $this->generateId('objectstategroup', 2); $anonymousUserId = $this->generateId('user', 10); /* BEGIN: Use Case */ // $anonymousUserId is the ID of the "Anonymous" user in a eZ // Publish demo installation. // Set anonymous user $userService = $repository->getUserService(); $repository->setCurrentUser($userService->loadUser($anonymousUserId)); // $objectStateGroupId contains the ID of the standard object state // group ez_lock. $objectStateService = $repository-><API key>(); $<API key> = $objectStateService-><API key>( $objectStateGroupId ); $<API key> = $objectStateService-><API key>( 'locked_and_unlocked' ); $<API key>->priority = 23; $<API key>->defaultLanguageCode = 'eng-US'; $<API key>->names = array( 'eng-US' => 'Locked and Unlocked', ); $<API key>->descriptions = array( 'eng-US' => 'A state between locked and unlocked.', ); // Throws unauthorized exception, since the anonymous user must not // create object states $createdObjectState = $objectStateService->createObjectState( $<API key>, $<API key> ); /* END: Use Case */ } /** * Test for the updateObjectState() method. * * @see \eZ\Publish\API\Repository\ObjectStateService::updateObjectState() * @expectedException \eZ\Publish\API\Repository\Exceptions\<API key> * @depends eZ\Publish\API\Repository\Tests\<API key>::<API key> */ public function <API key>() { $repository = $this->getRepository(); $objectStateId = $this->generateId('objectstate', 2); $anonymousUserId = $this->generateId('user', 10); /* BEGIN: Use Case */ // $anonymousUserId is the ID of the "Anonymous" user in a eZ // Publish demo installation. // Set anonymous user $userService = $repository->getUserService(); $repository->setCurrentUser($userService->loadUser($anonymousUserId)); // $objectStateId contains the ID of the "locked" state $objectStateService = $repository-><API key>(); $loadedObjectState = $objectStateService->loadObjectState( $objectStateId ); $updateStateStruct = $objectStateService-><API key>(); $updateStateStruct->identifier = 'somehow_locked'; $updateStateStruct->defaultLanguageCode = 'ger-DE'; $updateStateStruct->names = array( 'eng-US' => 'Somehow locked', 'ger-DE' => 'Irgendwie gelockt', ); $updateStateStruct->descriptions = array( 'eng-US' => 'The object is somehow locked', 'ger-DE' => 'Sindelfingen', ); // Throws unauthorized exception, since the anonymous user must not // update object states $updatedObjectState = $objectStateService->updateObjectState( $loadedObjectState, $updateStateStruct ); /* END: Use Case */ } /** * Test for the <API key>() method. * * @see \eZ\Publish\API\Repository\ObjectStateService::<API key>() * @expectedException \eZ\Publish\API\Repository\Exceptions\<API key> * @depends eZ\Publish\API\Repository\Tests\<API key>::<API key> */ public function <API key>() { $repository = $this->getRepository(); $objectStateId = $this->generateId('objectstate', 2); $anonymousUserId = $this->generateId('user', 10); /* BEGIN: Use Case */ // $anonymousUserId is the ID of the "Anonymous" user in a eZ // Publish demo installation. // Set anonymous user $userService = $repository->getUserService(); $repository->setCurrentUser($userService->loadUser($anonymousUserId)); // $objectStateId contains the ID of the "locked" state $objectStateService = $repository-><API key>(); $<API key> = $objectStateService->loadObjectState( $objectStateId ); // Throws unauthorized exception, since the anonymous user must not // set priorities for object states $objectStateService-><API key>( $<API key>, 23 ); /* END: Use Case */ } /** * Test for the deleteObjectState() method. * * @see \eZ\Publish\API\Repository\ObjectStateService::deleteObjectState() * @expectedException \eZ\Publish\API\Repository\Exceptions\<API key> * @depends eZ\Publish\API\Repository\Tests\<API key>::<API key> */ public function <API key>() { $repository = $this->getRepository(); $<API key> = $this->generateId('objectstate', 1); $lockedObjectStateId = $this->generateId('objectstate', 2); $anonymousUserId = $this->generateId('user', 10); /* BEGIN: Use Case */ // $anonymousUserId is the ID of the "Anonymous" user in a eZ // Publish demo installation. // Set anonymous user $userService = $repository->getUserService(); $repository->setCurrentUser($userService->loadUser($anonymousUserId)); // $<API key> is the ID of the state "not_locked" $objectStateService = $repository-><API key>(); $<API key> = $objectStateService->loadObjectState($<API key>); // Throws unauthorized exception, since the anonymous user must not // delete object states $objectStateService->deleteObjectState($<API key>); /* END: Use Case */ } /** * Test for the setContentState() method. * * @see \eZ\Publish\API\Repository\ObjectStateService::setContentState() * @expectedException \eZ\Publish\API\Repository\Exceptions\<API key> * @depends eZ\Publish\API\Repository\Tests\<API key>::testSetContentState */ public function <API key>() { $repository = $this->getRepository(); $anonymousUserId = $this->generateId('user', 10); $<API key> = $this->generateId('objectstategroup', 2); $lockedObjectStateId = $this->generateId('objectstate', 2); /* BEGIN: Use Case */ // $anonymousUserId is the ID of the "Anonymous" user in a eZ // Publish demo installation. // Set anonymous user $userService = $repository->getUserService(); $repository->setCurrentUser($userService->loadUser($anonymousUserId)); // $anonymousUserId is the content ID of "Anonymous User" // $<API key> contains the ID of the "ez_lock" object // state group // $lockedObjectStateId is the ID of the state "locked" $contentService = $repository->getContentService(); $objectStateService = $repository-><API key>(); $contentInfo = $contentService->loadContentInfo($anonymousUserId); $<API key> = $objectStateService-><API key>( $<API key> ); $lockedObjectState = $objectStateService->loadObjectState($lockedObjectStateId); // Throws unauthorized exception, since the anonymous user must not // set object state $objectStateService->setContentState( $contentInfo, $<API key>, $lockedObjectState ); /* END: Use Case */ } }
<?php namespace Drupal\Tests\node\<API key>; use Drupal\<API key>\WebDriverTestBase; use Drupal\node\Entity\Node; use Drupal\Tests\contextual\<API key>\<API key>; /** * Create a node with revisions and test contextual links. * * @group node */ class ContextualLinksTest extends WebDriverTestBase { use <API key>; /** * An array of node revisions. * * @var \Drupal\node\NodeInterface[] */ protected $nodes; /** * {@inheritdoc} */ protected static $modules = ['node', 'contextual']; /** * {@inheritdoc} */ protected $defaultTheme = 'stark'; /** * {@inheritdoc} */ protected function setUp() { parent::setUp(); $this-><API key>([ 'type' => 'page', 'name' => 'Basic page', 'display_submitted' => FALSE, ]); // Create initial node. $node = $this->drupalCreateNode(); $nodes = []; // Get original node. $nodes[] = clone $node; // Create two revisions. $revision_count = 2; for ($i = 0; $i < $revision_count; $i++) { // Create revision with a random title and body and update variables. $node->title = $this->randomMachineName(); $node->body = [ 'value' => $this->randomMachineName(32), 'format' => <API key>(), ]; $node->setNewRevision(); $node->save(); // Make sure we get revision information. $node = Node::load($node->id()); $nodes[] = clone $node; } $this->nodes = $nodes; $this->drupalLogin($this->createUser( [ 'view page revisions', 'revert page revisions', 'delete page revisions', 'edit any page content', 'delete any page content', 'access contextual links', 'administer content types', ] )); } /** * Tests the contextual links on revisions. */ public function <API key>() { // Confirm that the "Edit" and "Delete" contextual links appear for the // default revision. $this->drupalGet('node/' . $this->nodes[0]->id()); $page = $this->getSession()->getPage(); $page->waitFor(10, function () use ($page) { return $page->find('css', "main .contextual"); }); $this-><API key>('main'); $page->find('css', 'main .contextual button')->press(); $links = $page->findAll('css', "main .contextual-links li a"); $this->assertEquals('Edit', $links[0]->getText()); $this->assertEquals('Delete', $links[1]->getText()); // Confirm that "Edit" and "Delete" contextual links don't appear for // non-default revision. $this->drupalGet("node/" . $this->nodes[0]->id() . "/revisions/" . $this->nodes[1]->getRevisionId() . "/view"); $this->assertSession()->pageTextContains($this->nodes[1]->getTitle()); $page->waitFor(10, function () use ($page) { return $page->find('css', "main .contextual"); }); $this-><API key>('main'); $contextual_button = $page->find('css', 'main .contextual button'); $this->assertEmpty(0, $contextual_button ?: ''); } }
<?xml version="1.0" encoding="iso-8859-1"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "DTD/xhtml1-strict.dtd"> <html xmlns="http: <head> <title>Qt 4.4: <API key>.pro Example File (network/<API key>/<API key>.pro)</title> <link href="classic.css" rel="stylesheet" type="text/css" /> </head> <body> <table border="0" cellpadding="0" cellspacing="0" width="100%"> <tr> <td align="left" valign="top" width="32"><a href="http: <td width="1">&nbsp;&nbsp;</td><td class="postheader" valign="center"><a href="index.html"><font color="#004faf">Home</font></a>&nbsp;&middot; <a href="namespaces.html"><font color="#004faf">All&nbsp;Namespaces</font></a>&nbsp;&middot; <a href="classes.html"><font color="#004faf">All&nbsp;Classes</font></a>&nbsp;&middot; <a href="mainclasses.html"><font color="#004faf">Main&nbsp;Classes</font></a>&nbsp;&middot; <a href="groups.html"><font color="#004faf">Grouped&nbsp;Classes</font></a>&nbsp;&middot; <a href="modules.html"><font color="#004faf">Modules</font></a>&nbsp;&middot; <a href="functions.html"><font color="#004faf">Functions</font></a></td> <td align="right" valign="top" width="230"></td></tr></table><h1 class="title"><API key>.pro Example File<br /><span class="small-subtitle">network/<API key>/<API key>.pro</span> </h1> <pre> HEADERS = blockingclient.h \ fortunethread.h SOURCES = blockingclient.cpp \ main.cpp \ fortunethread.cpp QT += network # install target.path = $$[QT_INSTALL_EXAMPLES]/network/<API key> sources.files = $$SOURCES $$HEADERS $$RESOURCES $$FORMS <API key>.pro sources.path = $$[QT_INSTALL_EXAMPLES]/network/<API key> INSTALLS += target sources</pre> <p /><address><hr /><div align="center"> <table width="100%" cellspacing="0" border="0"><tr class="address"> <td width="30%" align="left">Copyright &copy; 2008 Nokia</td> <td width="40%" align="center"><a href="trademarks.html">Trademarks</a></td> <td width="30%" align="right"><div align="right">Qt 4.4.3</div></td> </tr></table></div></address></body> </html>
--retain=g_pfnVectors MEMORY { FLASH (RX) : origin = 0x00000000, length = 0x00040000 SRAM (RWX) : origin = 0x20000000, length = 0x00008000 } /* The following command line options are set as part of the CCS project. */ /* If you are building using the command line, or for some reason want to */ /* define them here, you can uncomment and modify these lines as needed. */ /* If you are using CCS for building, it is probably better to make any such */ /* modifications in your CCS project and leave this file alone. */ /* --heap_size=0 */ /* --stack_size=256 */ /* --library=rtsv7M4_T_le_eabi.lib */ /* Section allocation in memory */ SECTIONS { .intvecs: > 0x00000000 .text : > FLASH .const : > FLASH .cinit : > FLASH .pinit : > FLASH .init_array : > FLASH .vtable : > 0x20000000 .data : > SRAM .bss : > SRAM .sysmem : > SRAM .stack : > SRAM } __STACK_TOP = __stack + 512;
DELETE FROM `spell_script_names` WHERE `ScriptName`='<API key>'; INSERT INTO `spell_script_names` (`spell_id`, `ScriptName`) VALUES (-5143,'<API key>'); UPDATE `spell_script_names` SET `ScriptName`='<API key>' WHERE `spell_id`=44401;
describe("", function() { var rootEl; beforeEach(function() { rootEl = browser.rootEl; browser.get("examples/example-example47/index-jquery.html"); }); it('should load template defined inside script tag', function() { element(by.css('#tpl-link')).click(); expect(element(by.css('#tpl-content')).getText()).toMatch(/Content of the template/); }); });
<?php namespace eZ\Publish\Core\MVC\Symfony\SiteAccess\Matcher\Map; use eZ\Publish\Core\MVC\Symfony\SiteAccess\Matcher\Map; use eZ\Publish\Core\MVC\Symfony\Routing\SimplifiedRequest; class Host extends Map { public function getName() { return 'host:map'; } /** * Injects the request object to match against. * * @param \eZ\Publish\Core\MVC\Symfony\Routing\SimplifiedRequest $request */ public function setRequest(SimplifiedRequest $request) { if (!$this->key) { $this->setMapKey($request->host); } parent::setRequest($request); } public function reverseMatch($siteAccessName) { $matcher = parent::reverseMatch($siteAccessName); if ($matcher instanceof self) { $matcher->getRequest()->setHost($matcher->getMapKey()); } return $matcher; } }
// A simple class to extend an abstract class and get loaded with different // loaders. This class is loaded via LOADER2. public class from_loader2 implements IFace { public many_loader[] gen() { many_loader[] x = new many_loader[1]; x[0] = new many_loader(); return x; } }
#include <linux/export.h> #include <linux/init.h> #include <linux/platform_device.h> #include <linux/interrupt.h> #include <linux/leds.h> #include <linux/sched.h> #include <linux/bitops.h> #include <linux/fb.h> #include <linux/gpio.h> #include <linux/ioport.h> #include <linux/ucb1400.h> #include <linux/mtd/mtd.h> #include <linux/types.h> #include <linux/platform_data/pcf857x.h> #include <linux/platform_data/i2c-pxa.h> #include <linux/mtd/platnand.h> #include <linux/mtd/physmap.h> #include <linux/regulator/max1586.h> #include <asm/setup.h> #include <asm/mach-types.h> #include <asm/irq.h> #include <linux/sizes.h> #include <asm/mach/arch.h> #include <asm/mach/map.h> #include <asm/mach/irq.h> #include <asm/mach/flash.h> #include "pxa27x.h" #include <mach/balloon3.h> #include <mach/audio.h> #include <linux/platform_data/video-pxafb.h> #include <linux/platform_data/mmc-pxamci.h> #include "udc.h" #include "pxa27x-udc.h" #include <linux/platform_data/irda-pxaficp.h> #include <linux/platform_data/usb-ohci-pxa27x.h> #include "generic.h" #include "devices.h" static unsigned long balloon3_pin_config[] __initdata = { /* Select BTUART 'COM1/ttyS0' as IO option for pins 42/43/44/45 */ GPIO42_BTUART_RXD, GPIO43_BTUART_TXD, GPIO44_BTUART_CTS, GPIO45_BTUART_RTS, /* Reset, configured as GPIO wakeup source */ GPIO1_GPIO | WAKEUP_ON_EDGE_BOTH, }; static unsigned long <API key>; static unsigned long <API key> = (1 << <API key>) | (1 << BALLOON3_FEATURE_CF) | (1 << <API key>) | (1 << <API key>); int balloon3_has(enum balloon3_features feature) { return (<API key> & (1 << feature)) ? 1 : 0; } EXPORT_SYMBOL_GPL(balloon3_has); int __init <API key>(char *arg) { if (!arg) return 0; return kstrtoul(arg, 0, &<API key>); } early_param("balloon3_features", <API key>); #if defined(<API key>) || defined(<API key>) static unsigned long <API key>[] __initdata = { GPIO48_nPOE, GPIO49_nPWE, GPIO50_nPIOR, GPIO51_nPIOW, GPIO85_nPCE_1, GPIO54_nPCE_2, GPIO79_PSKTSEL, GPIO55_nPREG, GPIO56_nPWAIT, GPIO57_nIOIS16, }; static void __init balloon3_cf_init(void) { if (!balloon3_has(BALLOON3_FEATURE_CF)) return; pxa2xx_mfp_config(ARRAY_AND_SIZE(<API key>)); } #else static inline void balloon3_cf_init(void) {} #endif #if defined(CONFIG_MTD_PHYSMAP) || defined(<API key>) static struct mtd_partition <API key>[] = { { .name = "Flash", .offset = 0x00000000, .size = MTDPART_SIZ_FULL, } }; static struct physmap_flash_data balloon3_flash_data[] = { { .width = 2, /* bankwidth in bytes */ .parts = <API key>, .nr_parts = ARRAY_SIZE(<API key>) } }; static struct resource <API key> = { .start = PXA_CS0_PHYS, .end = PXA_CS0_PHYS + SZ_64M - 1, .flags = IORESOURCE_MEM, }; static struct platform_device balloon3_flash = { .name = "physmap-flash", .id = 0, .resource = &<API key>, .num_resources = 1, .dev = { .platform_data = balloon3_flash_data, }, }; static void __init balloon3_nor_init(void) { <API key>(&balloon3_flash); } #else static inline void balloon3_nor_init(void) {} #endif #if defined(<API key>) || \ defined(<API key>) static unsigned long <API key>[] __initdata = { GPIO28_AC97_BITCLK, <API key>, <API key>, GPIO31_AC97_SYNC, GPIO113_AC97_nRESET, GPIO95_GPIO, }; static struct ucb1400_pdata <API key> = { .irq = PXA_GPIO_TO_IRQ(<API key>), }; static struct platform_device <API key> = { .name = "ucb1400_core", .id = -1, .dev = { .platform_data = &<API key>, }, }; static void __init balloon3_ts_init(void) { if (!balloon3_has(<API key>)) return; pxa2xx_mfp_config(ARRAY_AND_SIZE(<API key>)); pxa_set_ac97_info(NULL); <API key>(&<API key>); } #else static inline void balloon3_ts_init(void) {} #endif #if defined(CONFIG_FB_PXA) || defined(<API key>) static unsigned long <API key>[] __initdata = { <API key>, GPIO99_GPIO, }; static struct pxafb_mode_info balloon3_lcd_modes[] = { { .pixclock = 38000, .xres = 480, .yres = 640, .bpp = 16, .hsync_len = 8, .left_margin = 8, .right_margin = 8, .vsync_len = 2, .upper_margin = 4, .lower_margin = 5, .sync = 0, }, }; static struct pxafb_mach_info balloon3_lcd_screen = { .modes = balloon3_lcd_modes, .num_modes = ARRAY_SIZE(balloon3_lcd_modes), .lcd_conn = LCD_COLOR_TFT_16BPP | LCD_PCLK_EDGE_FALL, }; static void <API key>(int on) { gpio_set_value(<API key>, on); } static void __init balloon3_lcd_init(void) { int ret; if (!balloon3_has(<API key>)) return; pxa2xx_mfp_config(ARRAY_AND_SIZE(<API key>)); ret = gpio_request(<API key>, "BKL-ON"); if (ret) { pr_err("Requesting BKL-ON GPIO failed!\n"); goto err; } ret = <API key>(<API key>, 1); if (ret) { pr_err("Setting BKL-ON GPIO direction failed!\n"); goto err2; } balloon3_lcd_screen.<API key> = <API key>; pxa_set_fb_info(NULL, &balloon3_lcd_screen); return; err2: gpio_free(<API key>); err: return; } #else static inline void balloon3_lcd_init(void) {} #endif #if defined(CONFIG_MMC_PXA) || defined(<API key>) static unsigned long <API key>[] __initdata = { GPIO32_MMC_CLK, GPIO92_MMC_DAT_0, GPIO109_MMC_DAT_1, GPIO110_MMC_DAT_2, GPIO111_MMC_DAT_3, GPIO112_MMC_CMD, }; static struct <API key> <API key> = { .ocr_mask = MMC_VDD_32_33 | MMC_VDD_33_34, .detect_delay_ms = 200, }; static void __init balloon3_mmc_init(void) { pxa2xx_mfp_config(ARRAY_AND_SIZE(<API key>)); pxa_set_mci_info(&<API key>); } #else static inline void balloon3_mmc_init(void) {} #endif #if defined(CONFIG_USB_PXA27X)||defined(<API key>) static void <API key>(int cmd) { if (cmd == <API key>) UP2OCR |= UP2OCR_DPPUE | UP2OCR_DPPUBE; else if (cmd == <API key>) UP2OCR &= ~UP2OCR_DPPUE; } static int <API key>(void) { return 1; } static struct <API key> balloon3_udc_info __initdata = { .udc_command = <API key>, .udc_is_connected = <API key>, .gpio_pullup = -1, }; static void __init balloon3_udc_init(void) { pxa_set_udc_info(&balloon3_udc_info); } #else static inline void balloon3_udc_init(void) {} #endif #if defined(CONFIG_IRDA) || defined(CONFIG_IRDA_MODULE) static struct <API key> <API key> = { .transceiver_cap = IR_FIRMODE | IR_SIRMODE | IR_OFF, }; static void __init balloon3_irda_init(void) { pxa_set_ficp_info(&<API key>); } #else static inline void balloon3_irda_init(void) {} #endif #if defined(CONFIG_USB_OHCI_HCD) || defined(<API key>) static unsigned long <API key>[] __initdata = { GPIO88_USBH1_PWR, GPIO89_USBH1_PEN, }; static struct <API key> balloon3_ohci_info = { .port_mode = PMM_PERPORT_MODE, .flags = ENABLE_PORT_ALL | POWER_CONTROL_LOW | POWER_SENSE_LOW, }; static void __init balloon3_uhc_init(void) { if (!balloon3_has(<API key>)) return; pxa2xx_mfp_config(ARRAY_AND_SIZE(<API key>)); pxa_set_ohci_info(&balloon3_ohci_info); } #else static inline void balloon3_uhc_init(void) {} #endif #if defined(CONFIG_LEDS_GPIO) || defined(<API key>) static unsigned long <API key>[] __initdata = { GPIO9_GPIO, /* NAND activity LED */ GPIO10_GPIO, /* Heartbeat LED */ }; struct gpio_led balloon3_gpio_leds[] = { { .name = "balloon3:green:idle", .default_trigger = "heartbeat", .gpio = <API key>, .active_low = 1, }, { .name = "balloon3:green:nand", .default_trigger = "nand-disk", .gpio = <API key>, .active_low = 1, }, }; static struct <API key> <API key> = { .leds = balloon3_gpio_leds, .num_leds = ARRAY_SIZE(balloon3_gpio_leds), }; static struct platform_device balloon3_leds = { .name = "leds-gpio", .id = 0, .dev = { .platform_data = &<API key>, } }; struct gpio_led <API key>[] = { { .name = "balloon3:green:led0", .gpio = <API key>, .active_low = 1, }, { .name = "balloon3:green:led1", .gpio = <API key>, .active_low = 1, }, { .name = "balloon3:orange:led2", .gpio = <API key>, .active_low = 1, }, { .name = "balloon3:orange:led3", .gpio = <API key>, .active_low = 1, }, { .name = "balloon3:orange:led4", .gpio = <API key>, .active_low = 1, }, { .name = "balloon3:orange:led5", .gpio = <API key>, .active_low = 1, }, { .name = "balloon3:red:led6", .gpio = <API key>, .active_low = 1, }, { .name = "balloon3:red:led7", .gpio = <API key>, .active_low = 1, }, }; static struct <API key> <API key> = { .leds = <API key>, .num_leds = ARRAY_SIZE(<API key>), }; static struct platform_device balloon3_pcf_leds = { .name = "leds-gpio", .id = 1, .dev = { .platform_data = &<API key>, } }; static void __init balloon3_leds_init(void) { pxa2xx_mfp_config(ARRAY_AND_SIZE(<API key>)); <API key>(&balloon3_leds); <API key>(&balloon3_pcf_leds); } #else static inline void balloon3_leds_init(void) {} #endif static void balloon3_mask_irq(struct irq_data *d) { int balloon3_irq = (d->irq - BALLOON3_IRQ(0)); <API key> &= ~(1 << balloon3_irq); __raw_writel(~<API key>, <API key>); } static void balloon3_unmask_irq(struct irq_data *d) { int balloon3_irq = (d->irq - BALLOON3_IRQ(0)); <API key> |= (1 << balloon3_irq); __raw_writel(~<API key>, <API key>); } static struct irq_chip balloon3_irq_chip = { .name = "FPGA", .irq_ack = balloon3_mask_irq, .irq_mask = balloon3_mask_irq, .irq_unmask = balloon3_unmask_irq, }; static void <API key>(struct irq_desc *desc) { unsigned long pending = __raw_readl(<API key>) & <API key>; do { struct irq_data *d = <API key>(desc); struct irq_chip *chip = irq_desc_get_chip(desc); unsigned int irq; /* clear useless edge notification */ if (chip->irq_ack) chip->irq_ack(d); while (pending) { irq = BALLOON3_IRQ(0) + __ffs(pending); generic_handle_irq(irq); pending &= pending - 1; } pending = __raw_readl(<API key>) & <API key>; } while (pending); } static void __init balloon3_init_irq(void) { int irq; pxa27x_init_irq(); /* setup extra Balloon3 irqs */ for (irq = BALLOON3_IRQ(0); irq <= BALLOON3_IRQ(7); irq++) { <API key>(irq, &balloon3_irq_chip, handle_level_irq); <API key>(irq, IRQ_NOREQUEST | IRQ_NOPROBE); } <API key>(BALLOON3_AUX_NIRQ, <API key>); irq_set_irq_type(BALLOON3_AUX_NIRQ, <API key>); pr_debug("%s: chained handler installed - irq %d automatically " "enabled\n", __func__, BALLOON3_AUX_NIRQ); } #if defined(CONFIG_GPIO_PCF857X) || defined(<API key>) static struct <API key> <API key> = { .gpio_base = <API key>, .n_latch = 0, .setup = NULL, .teardown = NULL, .context = NULL, }; static struct i2c_board_info __initdata balloon3_i2c_devs[] = { { I2C_BOARD_INFO("pcf8574a", 0x38), .platform_data = &<API key>, }, }; static void __init balloon3_i2c_init(void) { pxa_set_i2c_info(NULL); <API key>(0, ARRAY_AND_SIZE(balloon3_i2c_devs)); } #else static inline void balloon3_i2c_init(void) {} #endif #if defined(<API key>)||defined(<API key>) static void <API key>(struct nand_chip *this, int cmd, unsigned int ctrl) { uint8_t balloon3_ctl_set = 0, balloon3_ctl_clr = 0; if (ctrl & NAND_CTRL_CHANGE) { if (ctrl & NAND_CLE) balloon3_ctl_set |= <API key>; else balloon3_ctl_clr |= <API key>; if (ctrl & NAND_ALE) balloon3_ctl_set |= <API key>; else balloon3_ctl_clr |= <API key>; if (balloon3_ctl_clr) __raw_writel(balloon3_ctl_clr, <API key>); if (balloon3_ctl_set) __raw_writel(balloon3_ctl_set, <API key> + <API key>); } if (cmd != NAND_CMD_NONE) writeb(cmd, this->legacy.IO_ADDR_W); } static void <API key>(struct nand_chip *this, int chip) { if (chip < 0 || chip > 3) return; /* Assert all nCE lines */ __raw_writew( <API key> | <API key> | <API key> | <API key>, <API key> + <API key>); /* Deassert correct nCE line */ __raw_writew(<API key> << chip, <API key>); } static int <API key>(struct nand_chip *this) { return __raw_readl(<API key>) & <API key>; } static int balloon3_nand_probe(struct platform_device *pdev) { uint16_t ver; int ret; __raw_writew(<API key>, <API key> + <API key>); ver = __raw_readw(BALLOON3_FPGA_VER); if (ver < 0x4f08) pr_warn("The FPGA code, version 0x%04x, is too old. " "NAND support might be broken in this version!", ver); /* Power up the NAND chips */ ret = gpio_request(<API key>, "NAND"); if (ret) goto err1; ret = <API key>(<API key>, 1); if (ret) goto err2; gpio_set_value(<API key>, 1); /* Deassert all nCE lines and write protect line */ __raw_writel( <API key> | <API key> | <API key> | <API key> | <API key>, <API key> + <API key>); return 0; err2: gpio_free(<API key>); err1: return ret; } static void <API key>(struct platform_device *pdev) { /* Power down the NAND chips */ gpio_set_value(<API key>, 0); gpio_free(<API key>); } static struct mtd_partition <API key>[] = { [0] = { .name = "Boot", .offset = 0, .size = SZ_4M, }, [1] = { .name = "RootFS", .offset = MTDPART_OFS_APPEND, .size = MTDPART_SIZ_FULL }, }; struct platform_nand_data balloon3_nand_pdata = { .chip = { .nr_chips = 4, .chip_offset = 0, .nr_partitions = ARRAY_SIZE(<API key>), .partitions = <API key>, .chip_delay = 50, }, .ctrl = { .dev_ready = <API key>, .select_chip = <API key>, .cmd_ctrl = <API key>, .probe = balloon3_nand_probe, .remove = <API key>, }, }; static struct resource <API key>[] = { [0] = { .start = BALLOON3_NAND_BASE, .end = BALLOON3_NAND_BASE + 0x4, .flags = IORESOURCE_MEM, }, }; static struct platform_device balloon3_nand = { .name = "gen_nand", .num_resources = ARRAY_SIZE(<API key>), .resource = <API key>, .id = -1, .dev = { .platform_data = &balloon3_nand_pdata, } }; static void __init balloon3_nand_init(void) { <API key>(&balloon3_nand); } #else static inline void balloon3_nand_init(void) {} #endif #if defined(<API key>) || \ defined(<API key>) static struct <API key> <API key>[] = { REGULATOR_SUPPLY("vcc_core", NULL), }; static struct regulator_init_data <API key> = { .constraints = { .name = "vcc_core range", .min_uV = 900000, .max_uV = 1705000, .always_on = 1, .valid_ops_mask = <API key>, }, .consumer_supplies = <API key>, .<API key> = ARRAY_SIZE(<API key>), }; static struct max1586_subdev_data <API key>[] = { { .name = "vcc_core", .id = MAX1586_V3, .platform_data = &<API key>, } }; static struct <API key> <API key> = { .subdevs = <API key>, .num_subdevs = ARRAY_SIZE(<API key>), .v3_gain = <API key>, /* 730..1550 mV */ }; static struct i2c_board_info __initdata <API key>[] = { { I2C_BOARD_INFO("max1586", 0x14), .platform_data = &<API key>, }, }; static void __init balloon3_pmic_init(void) { <API key>(NULL); <API key>(1, ARRAY_AND_SIZE(<API key>)); } #else static inline void balloon3_pmic_init(void) {} #endif static void __init balloon3_init(void) { ARB_CNTRL = ARB_CORE_PARK | 0x234; pxa2xx_mfp_config(ARRAY_AND_SIZE(balloon3_pin_config)); pxa_set_ffuart_info(NULL); pxa_set_btuart_info(NULL); pxa_set_stuart_info(NULL); balloon3_i2c_init(); balloon3_irda_init(); balloon3_lcd_init(); balloon3_leds_init(); balloon3_mmc_init(); balloon3_nand_init(); balloon3_nor_init(); balloon3_pmic_init(); balloon3_ts_init(); balloon3_udc_init(); balloon3_uhc_init(); balloon3_cf_init(); } static struct map_desc balloon3_io_desc[] __initdata = { { /* CPLD/FPGA */ .virtual = (unsigned long)BALLOON3_FPGA_VIRT, .pfn = __phys_to_pfn(BALLOON3_FPGA_PHYS), .length = <API key>, .type = MT_DEVICE, }, }; static void __init balloon3_map_io(void) { pxa27x_map_io(); iotable_init(balloon3_io_desc, ARRAY_SIZE(balloon3_io_desc)); } MACHINE_START(BALLOON3, "Balloon3") /* Maintainer: Nick Bane. */ .map_io = balloon3_map_io, .nr_irqs = BALLOON3_NR_IRQS, .init_irq = balloon3_init_irq, .handle_irq = pxa27x_handle_irq, .init_time = pxa_timer_init, .init_machine = balloon3_init, .atag_offset = 0x100, .restart = pxa_restart, MACHINE_END
/=================================================================== // ob_sstable_mgr.h updateserver / Oceanbase // Description // sstable // Change Log /==================================================================== #ifndef <API key> #define <API key> #include <sys/types.h> #include <dirent.h> #include <sys/vfs.h> #include <unistd.h> #include <stdlib.h> #include <stdint.h> #include <stdio.h> #include <pthread.h> #include <new> #include <algorithm> #include "common/ob_atomic.h" #include "common/ob_define.h" #include "common/ob_vector.h" #include "common/page_arena.h" #include "common/hash/ob_hashmap.h" #include "common/ob_list.h" #include "common/ob_regex.h" #include "common/ob_fileinfo_manager.h" #include "common/ob_fetch_runnable.h" #include "common/ob_spin_rwlock.h" #include "sstable/ob_sstable_row.h" #include "sstable/ob_sstable_schema.h" #include "ob_ups_utils.h" #include "ob_store_mgr.h" #include "ob_schema_mgrv2.h" #define SSTABLE_SUFFIX ".sst" #define SCHEMA_SUFFIX ".schema" #define SSTABLE_FNAME_REGEX "^[0-9]+_[0-9]+-[0-9]+_[0-9]+.sst$" namespace oceanbase { namespace updateserver { struct SSTFileInfo { common::ObString path; common::ObString name; }; } // end namespace updateserver namespace common { template <> struct ob_vector_traits<updateserver::SSTFileInfo> { public: typedef updateserver::SSTFileInfo& pointee_type; typedef updateserver::SSTFileInfo value_type; typedef const updateserver::SSTFileInfo const_value_type; typedef value_type* iterator; typedef const value_type* const_iterator; typedef int32_t difference_type; }; } // end namespace common namespace updateserver { // sstable class ISSTableObserver { public: virtual ~ISSTableObserver() {}; public: // sstable virtual int add_sstable(const uint64_t sstable_id) = 0; // sstable virtual int erase_sstable(const uint64_t sstable_id) = 0; }; // dumpmemtablesstablecompaction class IRowIterator { public: virtual ~IRowIterator() {}; public: virtual int next_row() = 0; virtual int get_row(sstable::ObSSTableRow &sstable_row) = 0; virtual int reset_iter() = 0; virtual bool get_compressor_name(common::ObString &compressor_str) = 0; virtual bool get_sstable_schema(sstable::ObSSTableSchema &sstable_schema) = 0; virtual const common::ObRowkeyInfo *get_rowkey_info(const uint64_t table_id) const = 0; virtual bool get_store_type(int &store_type) = 0; virtual bool get_block_size(int64_t &block_size) = 0; }; typedef common::ObVector<SSTFileInfo> SSTList; Fetch, checkpoint, SSTable checkpoint, ckpt_ext_ Fetchckpt_id_checkpoint SSTableRAID struct ObUpsFetchParam : public common::ObFetchParam { bool fetch_sstable_; // whether to fetch sstables SSTList sst_list_; common::ObStringBuf string_buf_; int add_sst_file_info(const SSTFileInfo &sst_file_info); int clone(const ObUpsFetchParam& rp); ObUpsFetchParam() : fetch_sstable_(false), sst_list_() {} <API key>; }; // IFileInfo class SSTableInfo; class StoreInfo : public common::IFileInfo { static const int <API key> = O_RDONLY | O_DIRECT; static const int <API key> = O_RDONLY; public: StoreInfo(); virtual ~StoreInfo(); public: virtual int get_fd() const; public: void init(SSTableInfo *sstable_info, const StoreMgr::Handle store_handle); void destroy(); const char *get_dir() const; bool store_handle_match(const StoreMgr::Handle other) const; int64_t inc_ref_cnt(); int64_t dec_ref_cnt(); void remove_sstable_file(); SSTableInfo *get_sstable_info() const; StoreMgr::Handle get_store_handle() const; private: int get_fd_(int &fd, int mode) const; void remove_schema_file_(const char *path, const char *fname_substr); private: SSTableInfo *sstable_info_; StoreMgr::Handle store_handle_; mutable int fd_; volatile int64_t ref_cnt_; }; // sstable store_info class SSTableMgr; class SSTableInfo { public: static const int64_t MAX_SUBSTR_SIZE = 64; static const int64_t MAX_STORE_NUM = 20; public: SSTableInfo(); ~SSTableInfo(); public: int init(SSTableMgr *sstable_mgr, const uint64_t sstable_id, const uint64_t clog_id); void destroy(); int add_store(const StoreMgr::Handle store_handle); int erase_store(const StoreMgr::Handle store_handle); int64_t inc_ref_cnt(); int64_t dec_ref_cnt(); int64_t get_store_num() const; uint64_t get_sstable_id() const; uint64_t get_clog_id() const; void remove_sstable_file(); StoreInfo *get_store_info(); SSTableMgr *get_sstable_mgr() const; const char *get_fname_substr() const; void log_sstable_info() const; private: volatile int64_t ref_cnt_; SSTableMgr *sstable_mgr_; uint64_t sstable_id_; uint64_t clog_id_; int64_t loop_pos_; int64_t store_num_; StoreInfo *store_infos_[MAX_STORE_NUM]; }; struct SSTableID { static const uint64_t MINOR_VERSION_BIT = 32; static const uint64_t MAX_MAJOR_VERSION = (1UL<<32) - 1; static const uint64_t MAX_MINOR_VERSION = (1UL<<16) - 1; static const uint64_t MAX_CLOG_ID = INT64_MAX; static const uint64_t START_MAJOR_VERSION = 2; static const uint64_t START_MINOR_VERSION = 1; union { uint64_t id; struct { uint64_t minor_version_end:16; uint64_t minor_version_start:16; uint64_t major_version:32; }; }; SSTableID() : id(0) { }; SSTableID(const uint64_t other_id) { id = other_id; }; static inline uint64_t get_major_version(const uint64_t id) { SSTableID sst_id = id; return sst_id.major_version; }; static inline uint64_t <API key>(const uint64_t id) { SSTableID sst_id = id; return sst_id.minor_version_start; }; static inline uint64_t <API key>(const uint64_t id) { SSTableID sst_id = id; return sst_id.minor_version_end; }; static inline uint64_t get_id(const uint64_t major_version, const uint64_t minor_version_start, const uint64_t minor_version_end) { SSTableID sst_id; //sst_id.major_version = major_version; sst_id.id = major_version << MINOR_VERSION_BIT; sst_id.minor_version_start = static_cast<uint16_t>(minor_version_start); sst_id.minor_version_end = static_cast<uint16_t>(minor_version_end); return sst_id.id; }; static inline const char *log_str(const uint64_t id) { SSTableID sst_id = id; return sst_id.log_str(); }; inline bool continous(const SSTableID &other) const { bool bret = false; if (major_version == other.major_version) { if ((minor_version_end + 1) == other.minor_version_start) { bret = true; } } else { if (START_MINOR_VERSION == other.minor_version_start) { bret = true; } } return bret; }; inline const char *log_str() const { static const int64_t BUFFER_SIZE = 128; static __thread char buffers[2][BUFFER_SIZE]; static __thread uint64_t i = 0; char *buffer = buffers[i++ % 2]; buffer[0] = '\0'; snprintf(buffer, BUFFER_SIZE, "sstable_id=%lu name=[%lu_%lu-%lu]", id, major_version, minor_version_start, minor_version_end); return buffer; }; int serialize(char* buf, const int64_t buf_len, int64_t& pos) const { return common::serialization::encode_i64(buf, buf_len, pos, (int64_t)id); }; int deserialize(const char* buf, const int64_t data_len, int64_t& pos) { return common::serialization::decode_i64(buf, data_len, pos, (int64_t*)&id); }; int64_t get_serialize_size(void) const { return common::serialization::encoded_length_i64((int64_t)id); }; static inline int compare(const SSTableID &a, const SSTableID &b) { int ret = 0; if (a.major_version > b.major_version) { ret = 1; } else if (a.major_version < b.major_version) { ret = -1; } else if (a.minor_version_start > b.minor_version_start) { ret = 1; } else if (a.minor_version_start < b.minor_version_start) { ret = -1; } else if (a.minor_version_end > b.minor_version_end) { ret = 1; } else if (a.minor_version_end < b.minor_version_end) { ret = -1; } else { ret = 0; } return ret; }; static uint64_t trans_format_v1(const uint64_t id) { union SSTableIDV1 { uint64_t id; struct { uint64_t minor_version_end:8; uint64_t minor_version_start:8; uint64_t major_version:48; }; }; SSTableIDV1 v1; SSTableID sst_id; v1.id = id; //sst_id.major_version = v1.major_version; uint64_t major_version = v1.major_version; sst_id.id = (major_version << MINOR_VERSION_BIT); sst_id.minor_version_start = v1.minor_version_start; sst_id.minor_version_end = v1.minor_version_end; return sst_id.id; }; }; struct LoadBypassInfo { char fname[common::<API key>]; StoreMgr::Handle store_handle; static bool cmp(const LoadBypassInfo *a, const LoadBypassInfo *b) { return (NULL != a) && (NULL != b) && (strcmp(a->fname, b->fname) < 0); }; bool operator ==(const LoadBypassInfo &other) const { return 0 == strcmp(fname, other.fname); }; }; // sstable class SSTableMgr : public common::IFileInfoMgr { static const int64_t STORE_NUM = 10; static const int64_t SSTABLE_NUM = 1024; typedef common::hash::ObHashMap<StoreMgr::Handle, int64_t> StoreRefMap; typedef common::hash::ObHashMap<uint64_t, SSTableInfo*> SSTableInfoMap; typedef common::ObList<ISSTableObserver*> ObserverList; typedef common::hash::SimpleAllocer<SSTableInfo> <API key>; typedef common::hash::SimpleAllocer<StoreInfo> StoreInfoAllocator; public: SSTableMgr(); virtual ~SSTableMgr(); public: int init(const char *store_root, const char *raid_regex, const char *dir_regex); void destroy(); public: virtual const common::IFileInfo *get_fileinfo(const uint64_t sstable_id); virtual int revert_fileinfo(const common::IFileInfo *file_info); int get_schema(const uint64_t sstable_id, <API key> &sm); public: // dumpsstable int add_sstable(const uint64_t sstable_id, const uint64_t clog_id, const int64_t time_stamp, IRowIterator &iter, const CommonSchemaManager *sm); // TableMgrsstable sstabletrash // TableMgrStoreMgr int erase_sstable(const uint64_t sstable_id, const bool remove_sstable_file); // sstable bool load_new(); void reload_all(); void reload(const StoreMgr::Handle store_handle); void check_broken(); // (report broken) void umount_store(const char *path); // sstable int reg_observer(ISSTableObserver *observer); // master min_sstable_idmax_sstable_idsstable int fill_fetch_param(const uint64_t min_sstable_id, const uint64_t max_sstable_id, const uint64_t max_fill_major_num, ObUpsFetchParam &fetch_param); // slave uint64_t get_min_sstable_id(); uint64_t get_max_sstable_id(); // major frozen0 uint64_t <API key>(); // master // slavemaster uint64_t get_max_clog_id(); int load_sstable_bypass(const uint64_t major_version, const uint64_t minor_version_start, const uint64_t minor_version_end, const uint64_t clog_id, common::ObList<uint64_t> &table_list, uint64_t &checksum); static const char *build_str(const char *fmt, ...); static const char *sstable_id2str(const uint64_t sstable_id, const uint64_t clog_id); static bool sstable_str2id(const char *sstable_str, uint64_t &sstable_id, uint64_t &clog_id); inline StoreMgr &get_store_mgr() { return store_mgr_; }; inline <API key> &<API key>() { return sstable_allocator_; }; inline StoreInfoAllocator &get_store_allocator() { return store_allocator_; }; void log_sstable_info(); private: bool copy_sstable_file_(const uint64_t sstable_id, const uint64_t clog_id, const StoreMgr::Handle src_handle, const StoreMgr::Handle dest_handle); bool build_sstable_file_(const uint64_t sstable_id, const common::ObString &fpaths, const int64_t time_stamp, IRowIterator &iter); bool <API key>(const common::ObList<StoreMgr::Handle> &store_list, SSTableInfo &sstable_info, const int64_t time_stamp, IRowIterator &iter, const CommonSchemaManager *sm); bool build_schema_file_(const char *path, const char *fname_substr, const CommonSchemaManager *sm); void add_sstable_file_(const uint64_t sstable_id, const uint64_t clog_id, const StoreMgr::Handle store_handle, const bool invoke_callback); bool sstable_exist_(const uint64_t sstable_id); void <API key>(const uint64_t sstable_id); void <API key>(const uint64_t sstable_id); void load_dir_(const StoreMgr::Handle store_handle); bool check_sstable_(const char *fpath, uint64_t *sstable_checksum); int prepare_load_info_(const common::ObList<StoreMgr::Handle> &store_list, common::CharArena &allocator, common::ObList<LoadBypassInfo*> &info_list); int info_list_uniq_(common::CharArena &allocator, common::ObList<LoadBypassInfo*> &info_list); void load_list_bypass_(const common::ObList<LoadBypassInfo*> &info_list, const uint64_t major_version, const uint64_t minor_version_start, const uint64_t minor_version_end, const uint64_t clog_id, common::ObList<uint64_t> &sstable_list, uint64_t &checksum); private: bool inited_; SSTableInfoMap sstable_info_map_; // sstable_idSSTableInfomap common::SpinRWLock map_lock_; // sstable_info_map StoreMgr store_mgr_; common::ObRegex <API key>; // sstable ObserverList observer_list_; <API key> sstable_allocator_; // SSTableInfo StoreInfoAllocator store_allocator_; // StoreInfo }; } } #endif //<API key>
#include <drm/drmP.h> #include "i915_drv.h" #include <drm/i915_drm.h> #include "i915_trace.h" #include "intel_drv.h" /* * 965+ support PIPE_CONTROL commands, which provide finer grained control * over cache flushing. */ struct pipe_control { struct drm_i915_gem_object *obj; volatile u32 *cpu_page; u32 gtt_offset; }; static inline int ring_space(struct intel_ring_buffer *ring) { int space = (ring->head & HEAD_ADDR) - (ring->tail + <API key>); if (space < 0) space += ring->size; return space; } static int <API key>(struct intel_ring_buffer *ring, u32 invalidate_domains, u32 flush_domains) { u32 cmd; int ret; cmd = MI_FLUSH; if (((invalidate_domains|flush_domains) & <API key>) == 0) cmd |= MI_NO_WRITE_FLUSH; if (invalidate_domains & <API key>) cmd |= MI_READ_FLUSH; ret = intel_ring_begin(ring, 2); if (ret) return ret; intel_ring_emit(ring, cmd); intel_ring_emit(ring, MI_NOOP); intel_ring_advance(ring); return 0; } static int <API key>(struct intel_ring_buffer *ring, u32 invalidate_domains, u32 flush_domains) { struct drm_device *dev = ring->dev; u32 cmd; int ret; /* * read/write caches: * * <API key> is always invalidated, but is * only flushed if MI_NO_WRITE_FLUSH is unset. On 965, it is * also flushed at 2d versus 3d pipeline switches. * * read-only caches: * * <API key> is flushed on pre-965 if * MI_READ_FLUSH is set, and is always flushed on 965. * * <API key> may not exist? * * <API key>, which exists on 965, is * invalidated when MI_EXE_FLUSH is set. * * <API key>, which exists on 965, is * invalidated with every MI_FLUSH. * * TLBs: * * On 965, TLBs associated with <API key> * and I915_GEM_DOMAIN_CPU in are invalidated at PTE write and * <API key> and <API key> * are flushed at any MI_FLUSH. */ cmd = MI_FLUSH | MI_NO_WRITE_FLUSH; if ((invalidate_domains|flush_domains) & <API key>) cmd &= ~MI_NO_WRITE_FLUSH; if (invalidate_domains & <API key>) cmd |= MI_EXE_FLUSH; if (invalidate_domains & <API key> && (IS_G4X(dev) || IS_GEN5(dev))) cmd |= MI_INVALIDATE_ISP; ret = intel_ring_begin(ring, 2); if (ret) return ret; intel_ring_emit(ring, cmd); intel_ring_emit(ring, MI_NOOP); intel_ring_advance(ring); return 0; } /** * Emits a PIPE_CONTROL with a non-zero post-sync operation, for * implementing two workarounds on gen6. From section 1.4.7.1 * "PIPE_CONTROL" of the Sandy Bridge PRM volume 2 part 1: * * [DevSNB-C+{W/A}] Before any depth stall flush (including those * produced by non-pipelined state commands), software needs to first * send a PIPE_CONTROL with no bits set except Post-Sync Operation != * 0. * * [Dev-SNB{W/A}]: Before a PIPE_CONTROL with Write Cache Flush Enable * =1, a PIPE_CONTROL with any non-zero post-sync-op is required. * * And the workaround for these two requires this workaround first: * * [Dev-SNB{W/A}]: Pipe-control with CS-stall bit set must be sent * BEFORE the pipe-control with a post-sync op and no write-cache * flushes. * * And this last workaround is tricky because of the requirements on * that bit. From section 1.4.7.2.3 "Stall" of the Sandy Bridge PRM * volume 2 part 1: * * "1 of the following must also be set: * - Render Target Cache Flush Enable ([12] of DW1) * - Depth Cache Flush Enable ([0] of DW1) * - Stall at Pixel Scoreboard ([1] of DW1) * - Depth Stall ([13] of DW1) * - Post-Sync Operation ([13] of DW1) * - Notify Enable ([8] of DW1)" * * The cache flushes require the workaround flush that triggered this * one, so we can't use it. Depth stall would trigger the same. * Post-sync nonzero is what triggered this second workaround, so we * can't use that one either. Notify enable is IRQs, which aren't * really our business. That leaves only stall at scoreboard. */ static int <API key>(struct intel_ring_buffer *ring) { struct pipe_control *pc = ring->private; u32 scratch_addr = pc->gtt_offset + 128; int ret; ret = intel_ring_begin(ring, 6); if (ret) return ret; intel_ring_emit(ring, GFX_OP_PIPE_CONTROL(5)); intel_ring_emit(ring, <API key> | <API key>); intel_ring_emit(ring, scratch_addr | <API key>); /* address */ intel_ring_emit(ring, 0); /* low dword */ intel_ring_emit(ring, 0); /* high dword */ intel_ring_emit(ring, MI_NOOP); intel_ring_advance(ring); ret = intel_ring_begin(ring, 6); if (ret) return ret; intel_ring_emit(ring, GFX_OP_PIPE_CONTROL(5)); intel_ring_emit(ring, <API key>); intel_ring_emit(ring, scratch_addr | <API key>); /* address */ intel_ring_emit(ring, 0); intel_ring_emit(ring, 0); intel_ring_emit(ring, MI_NOOP); intel_ring_advance(ring); return 0; } static int <API key>(struct intel_ring_buffer *ring, u32 invalidate_domains, u32 flush_domains) { u32 flags = 0; struct pipe_control *pc = ring->private; u32 scratch_addr = pc->gtt_offset + 128; int ret; /* Force SNB workarounds for PIPE_CONTROL flushes */ ret = <API key>(ring); if (ret) return ret; /* Just flush everything. Experiments have shown that reducing the * number of bits based on the write domains has little performance * impact. */ if (flush_domains) { flags |= <API key>; flags |= <API key>; /* * Ensure that any following seqno writes only happen * when the render cache is indeed flushed. */ flags |= <API key>; } if (invalidate_domains) { flags |= <API key>; flags |= <API key>; flags |= <API key>; flags |= <API key>; flags |= <API key>; flags |= <API key>; /* * TLB invalidate requires a post-sync write. */ flags |= <API key> | <API key>; } ret = intel_ring_begin(ring, 4); if (ret) return ret; intel_ring_emit(ring, GFX_OP_PIPE_CONTROL(4)); intel_ring_emit(ring, flags); intel_ring_emit(ring, scratch_addr | <API key>); intel_ring_emit(ring, 0); intel_ring_advance(ring); return 0; } static int <API key>(struct intel_ring_buffer *ring) { int ret; ret = intel_ring_begin(ring, 4); if (ret) return ret; intel_ring_emit(ring, GFX_OP_PIPE_CONTROL(4)); intel_ring_emit(ring, <API key> | <API key>); intel_ring_emit(ring, 0); intel_ring_emit(ring, 0); intel_ring_advance(ring); return 0; } static int <API key>(struct intel_ring_buffer *ring, u32 invalidate_domains, u32 flush_domains) { u32 flags = 0; struct pipe_control *pc = ring->private; u32 scratch_addr = pc->gtt_offset + 128; int ret; /* * Ensure that any following seqno writes only happen when the render * cache is indeed flushed. * * Workaround: 4th PIPE_CONTROL command (except the ones with only * read-cache invalidate bits set) must have the CS_STALL bit set. We * don't try to be clever and just set it unconditionally. */ flags |= <API key>; /* Just flush everything. Experiments have shown that reducing the * number of bits based on the write domains has little performance * impact. */ if (flush_domains) { flags |= <API key>; flags |= <API key>; } if (invalidate_domains) { flags |= <API key>; flags |= <API key>; flags |= <API key>; flags |= <API key>; flags |= <API key>; flags |= <API key>; /* * TLB invalidate requires a post-sync write. */ flags |= <API key>; /* Workaround: we must issue a pipe_control with CS-stall bit * set before a pipe_control command that has the state cache * invalidate bit set. */ <API key>(ring); } ret = intel_ring_begin(ring, 4); if (ret) return ret; intel_ring_emit(ring, GFX_OP_PIPE_CONTROL(4)); intel_ring_emit(ring, flags); intel_ring_emit(ring, scratch_addr | <API key>); intel_ring_emit(ring, 0); intel_ring_advance(ring); return 0; } static void ring_write_tail(struct intel_ring_buffer *ring, u32 value) { drm_i915_private_t *dev_priv = ring->dev->dev_private; I915_WRITE_TAIL(ring, value); } u32 <API key>(struct intel_ring_buffer *ring) { drm_i915_private_t *dev_priv = ring->dev->dev_private; u32 acthd_reg = INTEL_INFO(ring->dev)->gen >= 4 ? RING_ACTHD(ring->mmio_base) : ACTHD; return I915_READ(acthd_reg); } static int init_ring_common(struct intel_ring_buffer *ring) { struct drm_device *dev = ring->dev; drm_i915_private_t *dev_priv = dev->dev_private; struct drm_i915_gem_object *obj = ring->obj; int ret = 0; u32 head; if (HAS_FORCE_WAKE(dev)) <API key>(dev_priv); /* Stop the ring if it's running. */ I915_WRITE_CTL(ring, 0); I915_WRITE_HEAD(ring, 0); ring->write_tail(ring, 0); head = I915_READ_HEAD(ring) & HEAD_ADDR; /* G45 ring initialization fails to reset head to zero */ if (head != 0) { DRM_DEBUG_KMS("%s head not reset to zero " "ctl %08x head %08x tail %08x start %08x\n", ring->name, I915_READ_CTL(ring), I915_READ_HEAD(ring), I915_READ_TAIL(ring), I915_READ_START(ring)); I915_WRITE_HEAD(ring, 0); if (I915_READ_HEAD(ring) & HEAD_ADDR) { DRM_ERROR("failed to set %s head to zero " "ctl %08x head %08x tail %08x start %08x\n", ring->name, I915_READ_CTL(ring), I915_READ_HEAD(ring), I915_READ_TAIL(ring), I915_READ_START(ring)); } } /* Initialize the ring. This must happen _after_ we've cleared the ring * registers with the above sequence (the readback of the HEAD registers * also enforces ordering), otherwise the hw might lose the new ring * register values. */ I915_WRITE_START(ring, obj->gtt_offset); I915_WRITE_CTL(ring, ((ring->size - PAGE_SIZE) & RING_NR_PAGES) | RING_VALID); /* If the head is still not zero, the ring is dead */ if (wait_for((I915_READ_CTL(ring) & RING_VALID) != 0 && I915_READ_START(ring) == obj->gtt_offset && (I915_READ_HEAD(ring) & HEAD_ADDR) == 0, 50)) { DRM_ERROR("%s initialization failed " "ctl %08x head %08x tail %08x start %08x\n", ring->name, I915_READ_CTL(ring), I915_READ_HEAD(ring), I915_READ_TAIL(ring), I915_READ_START(ring)); ret = -EIO; goto out; } if (!<API key>(ring->dev, DRIVER_MODESET)) <API key>(ring->dev); else { ring->head = I915_READ_HEAD(ring); ring->tail = I915_READ_TAIL(ring) & TAIL_ADDR; ring->space = ring_space(ring); ring->last_retired_head = -1; } out: if (HAS_FORCE_WAKE(dev)) <API key>(dev_priv); return ret; } static int init_pipe_control(struct intel_ring_buffer *ring) { struct pipe_control *pc; struct drm_i915_gem_object *obj; int ret; if (ring->private) return 0; pc = kmalloc(sizeof(*pc), GFP_KERNEL); if (!pc) return -ENOMEM; obj = <API key>(ring->dev, 4096); if (obj == NULL) { DRM_ERROR("Failed to allocate seqno page\n"); ret = -ENOMEM; goto err; } <API key>(obj, I915_CACHE_LLC); ret = i915_gem_object_pin(obj, 4096, true, false); if (ret) goto err_unref; pc->gtt_offset = obj->gtt_offset; pc->cpu_page = kmap(sg_page(obj->pages->sgl)); if (pc->cpu_page == NULL) goto err_unpin; pc->obj = obj; ring->private = pc; return 0; err_unpin: <API key>(obj); err_unref: <API key>(&obj->base); err: kfree(pc); return ret; } static void <API key>(struct intel_ring_buffer *ring) { struct pipe_control *pc = ring->private; struct drm_i915_gem_object *obj; if (!ring->private) return; obj = pc->obj; kunmap(sg_page(obj->pages->sgl)); <API key>(obj); <API key>(&obj->base); kfree(pc); ring->private = NULL; } static int init_render_ring(struct intel_ring_buffer *ring) { struct drm_device *dev = ring->dev; struct drm_i915_private *dev_priv = dev->dev_private; int ret = init_ring_common(ring); if (INTEL_INFO(dev)->gen > 3) { I915_WRITE(MI_MODE, _MASKED_BIT_ENABLE(VS_TIMER_DISPATCH)); if (IS_GEN7(dev)) I915_WRITE(GFX_MODE_GEN7, _MASKED_BIT_DISABLE(<API key>) | _MASKED_BIT_ENABLE(GFX_REPLAY_MODE)); } if (INTEL_INFO(dev)->gen >= 5) { ret = init_pipe_control(ring); if (ret) return ret; } if (IS_GEN6(dev)) { /* From the Sandybridge PRM, volume 1 part 3, page 24: * "If this bit is set, STCunit will have LRA as replacement * policy. [...] This bit must be reset. LRA replacement * policy is not supported." */ I915_WRITE(CACHE_MODE_0, _MASKED_BIT_DISABLE(<API key>)); /* This is not explicitly set for GEN6, so read the register. * see <API key>() for why we care. * TODO: consider explicitly setting the bit for GEN5 */ ring-><API key> = !!(I915_READ(GFX_MODE) & <API key>); } if (INTEL_INFO(dev)->gen >= 6) I915_WRITE(INSTPM, _MASKED_BIT_ENABLE(<API key>)); if (HAS_L3_GPU_CACHE(dev)) I915_WRITE_IMR(ring, ~<API key>); return ret; } static void render_ring_cleanup(struct intel_ring_buffer *ring) { struct drm_device *dev = ring->dev; if (!ring->private) return; if (HAS_BROKEN_CS_TLB(dev)) <API key>(to_gem_object(ring->private)); <API key>(ring); } static void update_mboxes(struct intel_ring_buffer *ring, u32 mmio_offset) { intel_ring_emit(ring, <API key>(1)); intel_ring_emit(ring, mmio_offset); intel_ring_emit(ring, ring-><API key>); } /** * gen6_add_request - Update the semaphore mailbox registers * * @ring - ring that is adding a request * @seqno - return seqno stuck into the ring * * Update the mailbox registers in the *other* rings with the current seqno. * This acts like a signal in the canonical semaphore. */ static int gen6_add_request(struct intel_ring_buffer *ring) { u32 mbox1_reg; u32 mbox2_reg; int ret; ret = intel_ring_begin(ring, 10); if (ret) return ret; mbox1_reg = ring->signal_mbox[0]; mbox2_reg = ring->signal_mbox[1]; update_mboxes(ring, mbox1_reg); update_mboxes(ring, mbox2_reg); intel_ring_emit(ring, <API key>); intel_ring_emit(ring, I915_GEM_HWS_INDEX << <API key>); intel_ring_emit(ring, ring-><API key>); intel_ring_emit(ring, MI_USER_INTERRUPT); intel_ring_advance(ring); return 0; } /** * intel_ring_sync - sync the waiter to the signaller on seqno * * @waiter - ring that is waiting * @signaller - ring which has, or will signal * @seqno - seqno which the waiter will block on */ static int gen6_ring_sync(struct intel_ring_buffer *waiter, struct intel_ring_buffer *signaller, u32 seqno) { int ret; u32 dw1 = MI_SEMAPHORE_MBOX | <API key> | <API key>; /* Throughout all of the GEM code, seqno passed implies our current * seqno is >= the last seqno executed. However for hardware the * comparison is strictly greater than. */ seqno -= 1; WARN_ON(signaller->semaphore_register[waiter->id] == <API key>); ret = intel_ring_begin(waiter, 4); if (ret) return ret; intel_ring_emit(waiter, dw1 | signaller->semaphore_register[waiter->id]); intel_ring_emit(waiter, seqno); intel_ring_emit(waiter, 0); intel_ring_emit(waiter, MI_NOOP); intel_ring_advance(waiter); return 0; } #define PIPE_CONTROL_FLUSH(ring__, addr__) \ do { \ intel_ring_emit(ring__, GFX_OP_PIPE_CONTROL(4) | <API key> | \ <API key>); \ intel_ring_emit(ring__, (addr__) | <API key>); \ intel_ring_emit(ring__, 0); \ intel_ring_emit(ring__, 0); \ } while (0) static int <API key>(struct intel_ring_buffer *ring) { struct pipe_control *pc = ring->private; u32 scratch_addr = pc->gtt_offset + 128; int ret; /* For Ironlake, MI_USER_INTERRUPT was deprecated and apparently * incoherent with writes to memory, i.e. completely fubar, * so we need to use PIPE_NOTIFY instead. * * However, we also need to workaround the qword write * incoherence by flushing the 6 PIPE_NOTIFY buffers out to * memory before requesting an interrupt. */ ret = intel_ring_begin(ring, 32); if (ret) return ret; intel_ring_emit(ring, GFX_OP_PIPE_CONTROL(4) | <API key> | <API key> | <API key>); intel_ring_emit(ring, pc->gtt_offset | <API key>); intel_ring_emit(ring, ring-><API key>); intel_ring_emit(ring, 0); PIPE_CONTROL_FLUSH(ring, scratch_addr); scratch_addr += 128; /* write to separate cachelines */ PIPE_CONTROL_FLUSH(ring, scratch_addr); scratch_addr += 128; PIPE_CONTROL_FLUSH(ring, scratch_addr); scratch_addr += 128; PIPE_CONTROL_FLUSH(ring, scratch_addr); scratch_addr += 128; PIPE_CONTROL_FLUSH(ring, scratch_addr); scratch_addr += 128; PIPE_CONTROL_FLUSH(ring, scratch_addr); intel_ring_emit(ring, GFX_OP_PIPE_CONTROL(4) | <API key> | <API key> | <API key> | PIPE_CONTROL_NOTIFY); intel_ring_emit(ring, pc->gtt_offset | <API key>); intel_ring_emit(ring, ring-><API key>); intel_ring_emit(ring, 0); intel_ring_advance(ring); return 0; } static u32 gen6_ring_get_seqno(struct intel_ring_buffer *ring, bool lazy_coherency) { /* Workaround to force correct ordering between irq and seqno writes on * ivb (and maybe also on snb) by reading from a CS register (like * ACTHD) before reading the status page. */ if (!lazy_coherency) <API key>(ring); return <API key>(ring, I915_GEM_HWS_INDEX); } static u32 ring_get_seqno(struct intel_ring_buffer *ring, bool lazy_coherency) { return <API key>(ring, I915_GEM_HWS_INDEX); } static u32 pc_render_get_seqno(struct intel_ring_buffer *ring, bool lazy_coherency) { struct pipe_control *pc = ring->private; return pc->cpu_page[0]; } static bool gen5_ring_get_irq(struct intel_ring_buffer *ring) { struct drm_device *dev = ring->dev; drm_i915_private_t *dev_priv = dev->dev_private; unsigned long flags; if (!dev->irq_enabled) return false; spin_lock_irqsave(&dev_priv->irq_lock, flags); if (ring->irq_refcount++ == 0) { dev_priv->gt_irq_mask &= ~ring->irq_enable_mask; I915_WRITE(GTIMR, dev_priv->gt_irq_mask); POSTING_READ(GTIMR); } <API key>(&dev_priv->irq_lock, flags); return true; } static void gen5_ring_put_irq(struct intel_ring_buffer *ring) { struct drm_device *dev = ring->dev; drm_i915_private_t *dev_priv = dev->dev_private; unsigned long flags; spin_lock_irqsave(&dev_priv->irq_lock, flags); if (--ring->irq_refcount == 0) { dev_priv->gt_irq_mask |= ring->irq_enable_mask; I915_WRITE(GTIMR, dev_priv->gt_irq_mask); POSTING_READ(GTIMR); } <API key>(&dev_priv->irq_lock, flags); } static bool i9xx_ring_get_irq(struct intel_ring_buffer *ring) { struct drm_device *dev = ring->dev; drm_i915_private_t *dev_priv = dev->dev_private; unsigned long flags; if (!dev->irq_enabled) return false; spin_lock_irqsave(&dev_priv->irq_lock, flags); if (ring->irq_refcount++ == 0) { dev_priv->irq_mask &= ~ring->irq_enable_mask; I915_WRITE(IMR, dev_priv->irq_mask); POSTING_READ(IMR); } <API key>(&dev_priv->irq_lock, flags); return true; } static void i9xx_ring_put_irq(struct intel_ring_buffer *ring) { struct drm_device *dev = ring->dev; drm_i915_private_t *dev_priv = dev->dev_private; unsigned long flags; spin_lock_irqsave(&dev_priv->irq_lock, flags); if (--ring->irq_refcount == 0) { dev_priv->irq_mask |= ring->irq_enable_mask; I915_WRITE(IMR, dev_priv->irq_mask); POSTING_READ(IMR); } <API key>(&dev_priv->irq_lock, flags); } static bool i8xx_ring_get_irq(struct intel_ring_buffer *ring) { struct drm_device *dev = ring->dev; drm_i915_private_t *dev_priv = dev->dev_private; unsigned long flags; if (!dev->irq_enabled) return false; spin_lock_irqsave(&dev_priv->irq_lock, flags); if (ring->irq_refcount++ == 0) { dev_priv->irq_mask &= ~ring->irq_enable_mask; I915_WRITE16(IMR, dev_priv->irq_mask); POSTING_READ16(IMR); } <API key>(&dev_priv->irq_lock, flags); return true; } static void i8xx_ring_put_irq(struct intel_ring_buffer *ring) { struct drm_device *dev = ring->dev; drm_i915_private_t *dev_priv = dev->dev_private; unsigned long flags; spin_lock_irqsave(&dev_priv->irq_lock, flags); if (--ring->irq_refcount == 0) { dev_priv->irq_mask |= ring->irq_enable_mask; I915_WRITE16(IMR, dev_priv->irq_mask); POSTING_READ16(IMR); } <API key>(&dev_priv->irq_lock, flags); } void <API key>(struct intel_ring_buffer *ring) { struct drm_device *dev = ring->dev; drm_i915_private_t *dev_priv = ring->dev->dev_private; u32 mmio = 0; /* The ring status page addresses are no longer next to the rest of * the ring registers as of gen7. */ if (IS_GEN7(dev)) { switch (ring->id) { case RCS: mmio = RENDER_HWS_PGA_GEN7; break; case BCS: mmio = BLT_HWS_PGA_GEN7; break; case VCS: mmio = BSD_HWS_PGA_GEN7; break; } } else if (IS_GEN6(ring->dev)) { mmio = RING_HWS_PGA_GEN6(ring->mmio_base); } else { mmio = RING_HWS_PGA(ring->mmio_base); } I915_WRITE(mmio, (u32)ring->status_page.gfx_addr); POSTING_READ(mmio); } static int bsd_ring_flush(struct intel_ring_buffer *ring, u32 invalidate_domains, u32 flush_domains) { int ret; ret = intel_ring_begin(ring, 2); if (ret) return ret; intel_ring_emit(ring, MI_FLUSH); intel_ring_emit(ring, MI_NOOP); intel_ring_advance(ring); return 0; } static int i9xx_add_request(struct intel_ring_buffer *ring) { int ret; ret = intel_ring_begin(ring, 4); if (ret) return ret; intel_ring_emit(ring, <API key>); intel_ring_emit(ring, I915_GEM_HWS_INDEX << <API key>); intel_ring_emit(ring, ring-><API key>); intel_ring_emit(ring, MI_USER_INTERRUPT); intel_ring_advance(ring); return 0; } static bool gen6_ring_get_irq(struct intel_ring_buffer *ring) { struct drm_device *dev = ring->dev; drm_i915_private_t *dev_priv = dev->dev_private; unsigned long flags; if (!dev->irq_enabled) return false; /* It looks like we need to prevent the gt from suspending while waiting * for an notifiy irq, otherwise irqs seem to get lost on at least the * blt/bsd rings on ivb. */ <API key>(dev_priv); spin_lock_irqsave(&dev_priv->irq_lock, flags); if (ring->irq_refcount++ == 0) { if (HAS_L3_GPU_CACHE(dev) && ring->id == RCS) I915_WRITE_IMR(ring, ~(ring->irq_enable_mask | <API key>)); else I915_WRITE_IMR(ring, ~ring->irq_enable_mask); dev_priv->gt_irq_mask &= ~ring->irq_enable_mask; I915_WRITE(GTIMR, dev_priv->gt_irq_mask); POSTING_READ(GTIMR); } <API key>(&dev_priv->irq_lock, flags); return true; } static void gen6_ring_put_irq(struct intel_ring_buffer *ring) { struct drm_device *dev = ring->dev; drm_i915_private_t *dev_priv = dev->dev_private; unsigned long flags; spin_lock_irqsave(&dev_priv->irq_lock, flags); if (--ring->irq_refcount == 0) { if (HAS_L3_GPU_CACHE(dev) && ring->id == RCS) I915_WRITE_IMR(ring, ~<API key>); else I915_WRITE_IMR(ring, ~0); dev_priv->gt_irq_mask |= ring->irq_enable_mask; I915_WRITE(GTIMR, dev_priv->gt_irq_mask); POSTING_READ(GTIMR); } <API key>(&dev_priv->irq_lock, flags); <API key>(dev_priv); } static int <API key>(struct intel_ring_buffer *ring, u32 offset, u32 length, unsigned flags) { int ret; ret = intel_ring_begin(ring, 2); if (ret) return ret; intel_ring_emit(ring, <API key> | MI_BATCH_GTT | (flags & <API key> ? 0 : <API key>)); intel_ring_emit(ring, offset); intel_ring_advance(ring); return 0; } /* Just userspace ABI convention to limit the wa batch bo to a resonable size */ #define I830_BATCH_LIMIT (256*1024) static int <API key>(struct intel_ring_buffer *ring, u32 offset, u32 len, unsigned flags) { int ret; if (flags & <API key>) { ret = intel_ring_begin(ring, 4); if (ret) return ret; intel_ring_emit(ring, MI_BATCH_BUFFER); intel_ring_emit(ring, offset | (flags & <API key> ? 0 : MI_BATCH_NON_SECURE)); intel_ring_emit(ring, offset + len - 8); intel_ring_emit(ring, MI_NOOP); intel_ring_advance(ring); } else { struct drm_i915_gem_object *obj = ring->private; u32 cs_offset = obj->gtt_offset; if (len > I830_BATCH_LIMIT) return -ENOSPC; ret = intel_ring_begin(ring, 9+3); if (ret) return ret; /* Blit the batch (which has now all relocs applied) to the stable batch * scratch bo area (so that the CS never stumbles over its tlb * invalidation bug) ... */ intel_ring_emit(ring, XY_SRC_COPY_BLT_CMD | <API key> | <API key>); intel_ring_emit(ring, BLT_DEPTH_32 | BLT_ROP_GXCOPY | 4096); intel_ring_emit(ring, 0); intel_ring_emit(ring, (DIV_ROUND_UP(len, 4096) << 16) | 1024); intel_ring_emit(ring, cs_offset); intel_ring_emit(ring, 0); intel_ring_emit(ring, 4096); intel_ring_emit(ring, offset); intel_ring_emit(ring, MI_FLUSH); /* ... and execute it. */ intel_ring_emit(ring, MI_BATCH_BUFFER); intel_ring_emit(ring, cs_offset | (flags & <API key> ? 0 : MI_BATCH_NON_SECURE)); intel_ring_emit(ring, cs_offset + len - 8); intel_ring_advance(ring); } return 0; } static int <API key>(struct intel_ring_buffer *ring, u32 offset, u32 len, unsigned flags) { int ret; ret = intel_ring_begin(ring, 2); if (ret) return ret; intel_ring_emit(ring, <API key> | MI_BATCH_GTT); intel_ring_emit(ring, offset | (flags & <API key> ? 0 : MI_BATCH_NON_SECURE)); intel_ring_advance(ring); return 0; } static void cleanup_status_page(struct intel_ring_buffer *ring) { struct drm_i915_gem_object *obj; obj = ring->status_page.obj; if (obj == NULL) return; kunmap(sg_page(obj->pages->sgl)); <API key>(obj); <API key>(&obj->base); ring->status_page.obj = NULL; } static int init_status_page(struct intel_ring_buffer *ring) { struct drm_device *dev = ring->dev; struct drm_i915_gem_object *obj; int ret; obj = <API key>(dev, 4096); if (obj == NULL) { DRM_ERROR("Failed to allocate status page\n"); ret = -ENOMEM; goto err; } <API key>(obj, I915_CACHE_LLC); ret = i915_gem_object_pin(obj, 4096, true, false); if (ret != 0) { goto err_unref; } ring->status_page.gfx_addr = obj->gtt_offset; ring->status_page.page_addr = kmap(sg_page(obj->pages->sgl)); if (ring->status_page.page_addr == NULL) { ret = -ENOMEM; goto err_unpin; } ring->status_page.obj = obj; memset(ring->status_page.page_addr, 0, PAGE_SIZE); <API key>(ring); DRM_DEBUG_DRIVER("%s hws offset: 0x%08x\n", ring->name, ring->status_page.gfx_addr); return 0; err_unpin: <API key>(obj); err_unref: <API key>(&obj->base); err: return ret; } static int init_phys_hws_pga(struct intel_ring_buffer *ring) { struct drm_i915_private *dev_priv = ring->dev->dev_private; u32 addr; if (!dev_priv->status_page_dmah) { dev_priv->status_page_dmah = drm_pci_alloc(ring->dev, PAGE_SIZE, PAGE_SIZE); if (!dev_priv->status_page_dmah) return -ENOMEM; } addr = dev_priv->status_page_dmah->busaddr; if (INTEL_INFO(ring->dev)->gen >= 4) addr |= (dev_priv->status_page_dmah->busaddr >> 28) & 0xf0; I915_WRITE(HWS_PGA, addr); ring->status_page.page_addr = dev_priv->status_page_dmah->vaddr; memset(ring->status_page.page_addr, 0, PAGE_SIZE); return 0; } static int <API key>(struct drm_device *dev, struct intel_ring_buffer *ring) { struct drm_i915_gem_object *obj; struct drm_i915_private *dev_priv = dev->dev_private; int ret; ring->dev = dev; INIT_LIST_HEAD(&ring->active_list); INIT_LIST_HEAD(&ring->request_list); ring->size = 32 * PAGE_SIZE; memset(ring->sync_seqno, 0, sizeof(ring->sync_seqno)); init_waitqueue_head(&ring->irq_queue); if (I915_NEED_GFX_HWS(dev)) { ret = init_status_page(ring); if (ret) return ret; } else { BUG_ON(ring->id != RCS); ret = init_phys_hws_pga(ring); if (ret) return ret; } obj = <API key>(dev, ring->size); if (obj == NULL) { DRM_ERROR("Failed to allocate ringbuffer\n"); ret = -ENOMEM; goto err_hws; } ring->obj = obj; ret = i915_gem_object_pin(obj, PAGE_SIZE, true, false); if (ret) goto err_unref; ret = <API key>(obj, true); if (ret) goto err_unpin; ring->virtual_start = ioremap_wc(dev_priv->mm.gtt->gma_bus_addr + obj->gtt_offset, ring->size); if (ring->virtual_start == NULL) { DRM_ERROR("Failed to map ringbuffer.\n"); ret = -EINVAL; goto err_unpin; } ret = ring->init(ring); if (ret) goto err_unmap; /* Workaround an erratum on the i830 which causes a hang if * the TAIL pointer points to within the last 2 cachelines * of the buffer. */ ring->effective_size = ring->size; if (IS_I830(ring->dev) || IS_845G(ring->dev)) ring->effective_size -= 128; return 0; err_unmap: iounmap(ring->virtual_start); err_unpin: <API key>(obj); err_unref: <API key>(&obj->base); ring->obj = NULL; err_hws: cleanup_status_page(ring); return ret; } void <API key>(struct intel_ring_buffer *ring) { struct drm_i915_private *dev_priv; int ret; if (ring->obj == NULL) return; /* Disable the ring buffer. The ring must be idle at this point */ dev_priv = ring->dev->dev_private; ret = intel_ring_idle(ring); if (ret) DRM_ERROR("failed to quiesce %s whilst cleaning up: %d\n", ring->name, ret); I915_WRITE_CTL(ring, 0); iounmap(ring->virtual_start); <API key>(ring->obj); <API key>(&ring->obj->base); ring->obj = NULL; if (ring->cleanup) ring->cleanup(ring); cleanup_status_page(ring); } static int <API key>(struct intel_ring_buffer *ring, u32 seqno) { int ret; ret = i915_wait_seqno(ring, seqno); if (!ret) <API key>(ring); return ret; } static int <API key>(struct intel_ring_buffer *ring, int n) { struct <API key> *request; u32 seqno = 0; int ret; <API key>(ring); if (ring->last_retired_head != -1) { ring->head = ring->last_retired_head; ring->last_retired_head = -1; ring->space = ring_space(ring); if (ring->space >= n) return 0; } list_for_each_entry(request, &ring->request_list, list) { int space; if (request->tail == -1) continue; space = request->tail - (ring->tail + <API key>); if (space < 0) space += ring->size; if (space >= n) { seqno = request->seqno; break; } /* Consume this request in case we need more space than * is available and so need to prevent a race between * updating last_retired_head and direct reads of * I915_RING_HEAD. It also provides a nice sanity check. */ request->tail = -1; } if (seqno == 0) return -ENOSPC; ret = <API key>(ring, seqno); if (ret) return ret; if (WARN_ON(ring->last_retired_head == -1)) return -ENOSPC; ring->head = ring->last_retired_head; ring->last_retired_head = -1; ring->space = ring_space(ring); if (WARN_ON(ring->space < n)) return -ENOSPC; return 0; } static int ring_wait_for_space(struct intel_ring_buffer *ring, int n) { struct drm_device *dev = ring->dev; struct drm_i915_private *dev_priv = dev->dev_private; unsigned long end; int ret; ret = <API key>(ring, n); if (ret != -ENOSPC) return ret; <API key>(ring); /* With GEM the hangcheck timer should kick us out of the loop, * leaving it early runs the risk of corrupting GEM state (due * to running on almost untested codepaths). But on resume * timers don't work yet, so prevent a complete hang in that * case by choosing an insanely large timeout. */ end = jiffies + 60 * HZ; do { ring->head = I915_READ_HEAD(ring); ring->space = ring_space(ring); if (ring->space >= n) { <API key>(ring); return 0; } if (dev->primary->master) { struct <API key> *master_priv = dev->primary->master->driver_priv; if (master_priv->sarea_priv) master_priv->sarea_priv->perf_boxes |= I915_BOX_WAIT; } msleep(1); ret = <API key>(dev_priv, dev_priv->mm.interruptible); if (ret) return ret; } while (!time_after(jiffies, end)); <API key>(ring); return -EBUSY; } static int <API key>(struct intel_ring_buffer *ring) { uint32_t __iomem *virt; int rem = ring->size - ring->tail; if (ring->space < rem) { int ret = ring_wait_for_space(ring, rem); if (ret) return ret; } virt = ring->virtual_start + ring->tail; rem /= 4; while (rem iowrite32(MI_NOOP, virt++); ring->tail = 0; ring->space = ring_space(ring); return 0; } int intel_ring_idle(struct intel_ring_buffer *ring) { u32 seqno; int ret; /* We need to add any requests required to flush the objects and ring */ if (ring-><API key>) { ret = i915_add_request(ring, NULL, NULL); if (ret) return ret; } /* Wait upon the last request to be completed */ if (list_empty(&ring->request_list)) return 0; seqno = list_entry(ring->request_list.prev, struct <API key>, list)->seqno; return i915_wait_seqno(ring, seqno); } static int <API key>(struct intel_ring_buffer *ring) { if (ring-><API key>) return 0; return i915_gem_get_seqno(ring->dev, &ring-><API key>); } int intel_ring_begin(struct intel_ring_buffer *ring, int num_dwords) { drm_i915_private_t *dev_priv = ring->dev->dev_private; int n = 4*num_dwords; int ret; ret = <API key>(dev_priv, dev_priv->mm.interruptible); if (ret) return ret; /* Preallocate the olr before touching the ring */ ret = <API key>(ring); if (ret) return ret; if (unlikely(ring->tail + n > ring->effective_size)) { ret = <API key>(ring); if (unlikely(ret)) return ret; } if (unlikely(ring->space < n)) { ret = ring_wait_for_space(ring, n); if (unlikely(ret)) return ret; } ring->space -= n; return 0; } void intel_ring_advance(struct intel_ring_buffer *ring) { struct drm_i915_private *dev_priv = ring->dev->dev_private; ring->tail &= ring->size - 1; if (dev_priv->stop_rings & intel_ring_flag(ring)) return; ring->write_tail(ring, ring->tail); } static void <API key>(struct intel_ring_buffer *ring, u32 value) { drm_i915_private_t *dev_priv = ring->dev->dev_private; /* Every tail move must follow the sequence below */ /* Disable notification that the ring is IDLE. The GT * will then assume that it is busy and bring it out of rc6. */ I915_WRITE(<API key>, _MASKED_BIT_ENABLE(<API key>)); /* Clear the context id. Here be magic! */ I915_WRITE64(GEN6_BSD_RNCID, 0x0); /* Wait for the ring not to be idle, i.e. for it to wake up. */ if (wait_for((I915_READ(<API key>) & <API key>) == 0, 50)) DRM_ERROR("timed out waiting for the BSD ring to wake up\n"); /* Now that the ring is fully powered up, update the tail */ I915_WRITE_TAIL(ring, value); POSTING_READ(RING_TAIL(ring->mmio_base)); /* Let the ring send IDLE messages to the GT again, * and so let it sleep to conserve power when idle. */ I915_WRITE(<API key>, _MASKED_BIT_DISABLE(<API key>)); } static int gen6_ring_flush(struct intel_ring_buffer *ring, u32 invalidate, u32 flush) { uint32_t cmd; int ret; ret = intel_ring_begin(ring, 4); if (ret) return ret; cmd = MI_FLUSH_DW; /* * Bspec vol 1c.5 - video engine command streamer: * "If ENABLED, all TLBs will be invalidated once the flush * operation is complete. This bit is only valid when the * Post-Sync Operation field is a value of 1h or 3h." */ if (invalidate & <API key>) cmd |= MI_INVALIDATE_TLB | MI_INVALIDATE_BSD | <API key> | <API key>; intel_ring_emit(ring, cmd); intel_ring_emit(ring, <API key> | MI_FLUSH_DW_USE_GTT); intel_ring_emit(ring, 0); intel_ring_emit(ring, MI_NOOP); intel_ring_advance(ring); return 0; } static int <API key>(struct intel_ring_buffer *ring, u32 offset, u32 len, unsigned flags) { int ret; ret = intel_ring_begin(ring, 2); if (ret) return ret; intel_ring_emit(ring, <API key> | MI_BATCH_PPGTT_HSW | (flags & <API key> ? 0 : <API key>)); /* bit0-7 is the length on GEN6+ */ intel_ring_emit(ring, offset); intel_ring_advance(ring); return 0; } static int <API key>(struct intel_ring_buffer *ring, u32 offset, u32 len, unsigned flags) { int ret; ret = intel_ring_begin(ring, 2); if (ret) return ret; intel_ring_emit(ring, <API key> | (flags & <API key> ? 0 : <API key>)); /* bit0-7 is the length on GEN6+ */ intel_ring_emit(ring, offset); intel_ring_advance(ring); return 0; } /* Blitter support (SandyBridge+) */ static int blt_ring_flush(struct intel_ring_buffer *ring, u32 invalidate, u32 flush) { uint32_t cmd; int ret; ret = intel_ring_begin(ring, 4); if (ret) return ret; cmd = MI_FLUSH_DW; /* * Bspec vol 1c.3 - blitter engine command streamer: * "If ENABLED, all TLBs will be invalidated once the flush * operation is complete. This bit is only valid when the * Post-Sync Operation field is a value of 1h or 3h." */ if (invalidate & <API key>) cmd |= MI_INVALIDATE_TLB | <API key> | <API key>; intel_ring_emit(ring, cmd); intel_ring_emit(ring, <API key> | MI_FLUSH_DW_USE_GTT); intel_ring_emit(ring, 0); intel_ring_emit(ring, MI_NOOP); intel_ring_advance(ring); return 0; } int <API key>(struct drm_device *dev) { drm_i915_private_t *dev_priv = dev->dev_private; struct intel_ring_buffer *ring = &dev_priv->ring[RCS]; ring->name = "render ring"; ring->id = RCS; ring->mmio_base = RENDER_RING_BASE; if (INTEL_INFO(dev)->gen >= 6) { ring->add_request = gen6_add_request; ring->flush = <API key>; if (INTEL_INFO(dev)->gen == 6) ring->flush = <API key>; ring->irq_get = gen6_ring_get_irq; ring->irq_put = gen6_ring_put_irq; ring->irq_enable_mask = GT_USER_INTERRUPT; ring->get_seqno = gen6_ring_get_seqno; ring->sync_to = gen6_ring_sync; ring->semaphore_register[0] = <API key>; ring->semaphore_register[1] = <API key>; ring->semaphore_register[2] = <API key>; ring->signal_mbox[0] = GEN6_VRSYNC; ring->signal_mbox[1] = GEN6_BRSYNC; } else if (IS_GEN5(dev)) { ring->add_request = <API key>; ring->flush = <API key>; ring->get_seqno = pc_render_get_seqno; ring->irq_get = gen5_ring_get_irq; ring->irq_put = gen5_ring_put_irq; ring->irq_enable_mask = GT_USER_INTERRUPT | GT_PIPE_NOTIFY; } else { ring->add_request = i9xx_add_request; if (INTEL_INFO(dev)->gen < 4) ring->flush = <API key>; else ring->flush = <API key>; ring->get_seqno = ring_get_seqno; if (IS_GEN2(dev)) { ring->irq_get = i8xx_ring_get_irq; ring->irq_put = i8xx_ring_put_irq; } else { ring->irq_get = i9xx_ring_get_irq; ring->irq_put = i9xx_ring_put_irq; } ring->irq_enable_mask = I915_USER_INTERRUPT; } ring->write_tail = ring_write_tail; if (IS_HASWELL(dev)) ring->dispatch_execbuffer = <API key>; else if (INTEL_INFO(dev)->gen >= 6) ring->dispatch_execbuffer = <API key>; else if (INTEL_INFO(dev)->gen >= 4) ring->dispatch_execbuffer = <API key>; else if (IS_I830(dev) || IS_845G(dev)) ring->dispatch_execbuffer = <API key>; else ring->dispatch_execbuffer = <API key>; ring->init = init_render_ring; ring->cleanup = render_ring_cleanup; /* Workaround batchbuffer to combat CS tlb bug. */ if (HAS_BROKEN_CS_TLB(dev)) { struct drm_i915_gem_object *obj; int ret; obj = <API key>(dev, I830_BATCH_LIMIT); if (obj == NULL) { DRM_ERROR("Failed to allocate batch bo\n"); return -ENOMEM; } ret = i915_gem_object_pin(obj, 0, true, false); if (ret != 0) { <API key>(&obj->base); DRM_ERROR("Failed to ping batch bo\n"); return ret; } ring->private = obj; } return <API key>(dev, ring); } int <API key>(struct drm_device *dev, u64 start, u32 size) { drm_i915_private_t *dev_priv = dev->dev_private; struct intel_ring_buffer *ring = &dev_priv->ring[RCS]; int ret; ring->name = "render ring"; ring->id = RCS; ring->mmio_base = RENDER_RING_BASE; if (INTEL_INFO(dev)->gen >= 6) { /* non-kms not supported on gen6+ */ return -ENODEV; } /* Note: gem is not supported on gen5/ilk without kms (the corresponding * gem_init ioctl returns with -ENODEV). Hence we do not need to set up * the special gen5 functions. */ ring->add_request = i9xx_add_request; if (INTEL_INFO(dev)->gen < 4) ring->flush = <API key>; else ring->flush = <API key>; ring->get_seqno = ring_get_seqno; if (IS_GEN2(dev)) { ring->irq_get = i8xx_ring_get_irq; ring->irq_put = i8xx_ring_put_irq; } else { ring->irq_get = i9xx_ring_get_irq; ring->irq_put = i9xx_ring_put_irq; } ring->irq_enable_mask = I915_USER_INTERRUPT; ring->write_tail = ring_write_tail; if (INTEL_INFO(dev)->gen >= 4) ring->dispatch_execbuffer = <API key>; else if (IS_I830(dev) || IS_845G(dev)) ring->dispatch_execbuffer = <API key>; else ring->dispatch_execbuffer = <API key>; ring->init = init_render_ring; ring->cleanup = render_ring_cleanup; ring->dev = dev; INIT_LIST_HEAD(&ring->active_list); INIT_LIST_HEAD(&ring->request_list); ring->size = size; ring->effective_size = ring->size; if (IS_I830(ring->dev) || IS_845G(ring->dev)) ring->effective_size -= 128; ring->virtual_start = ioremap_wc(start, size); if (ring->virtual_start == NULL) { DRM_ERROR("can not ioremap virtual address for" " ring buffer\n"); return -ENOMEM; } if (!I915_NEED_GFX_HWS(dev)) { ret = init_phys_hws_pga(ring); if (ret) return ret; } return 0; } int <API key>(struct drm_device *dev) { drm_i915_private_t *dev_priv = dev->dev_private; struct intel_ring_buffer *ring = &dev_priv->ring[VCS]; ring->name = "bsd ring"; ring->id = VCS; ring->write_tail = ring_write_tail; if (IS_GEN6(dev) || IS_GEN7(dev)) { ring->mmio_base = GEN6_BSD_RING_BASE; /* gen6 bsd needs a special wa for tail updates */ if (IS_GEN6(dev)) ring->write_tail = <API key>; ring->flush = gen6_ring_flush; ring->add_request = gen6_add_request; ring->get_seqno = gen6_ring_get_seqno; ring->irq_enable_mask = <API key>; ring->irq_get = gen6_ring_get_irq; ring->irq_put = gen6_ring_put_irq; ring->dispatch_execbuffer = <API key>; ring->sync_to = gen6_ring_sync; ring->semaphore_register[0] = <API key>; ring->semaphore_register[1] = <API key>; ring->semaphore_register[2] = <API key>; ring->signal_mbox[0] = GEN6_RVSYNC; ring->signal_mbox[1] = GEN6_BVSYNC; } else { ring->mmio_base = BSD_RING_BASE; ring->flush = bsd_ring_flush; ring->add_request = i9xx_add_request; ring->get_seqno = ring_get_seqno; if (IS_GEN5(dev)) { ring->irq_enable_mask = <API key>; ring->irq_get = gen5_ring_get_irq; ring->irq_put = gen5_ring_put_irq; } else { ring->irq_enable_mask = <API key>; ring->irq_get = i9xx_ring_get_irq; ring->irq_put = i9xx_ring_put_irq; } ring->dispatch_execbuffer = <API key>; } ring->init = init_ring_common; return <API key>(dev, ring); } int <API key>(struct drm_device *dev) { drm_i915_private_t *dev_priv = dev->dev_private; struct intel_ring_buffer *ring = &dev_priv->ring[BCS]; ring->name = "blitter ring"; ring->id = BCS; ring->mmio_base = BLT_RING_BASE; ring->write_tail = ring_write_tail; ring->flush = blt_ring_flush; ring->add_request = gen6_add_request; ring->get_seqno = gen6_ring_get_seqno; ring->irq_enable_mask = <API key>; ring->irq_get = gen6_ring_get_irq; ring->irq_put = gen6_ring_put_irq; ring->dispatch_execbuffer = <API key>; ring->sync_to = gen6_ring_sync; ring->semaphore_register[0] = <API key>; ring->semaphore_register[1] = <API key>; ring->semaphore_register[2] = <API key>; ring->signal_mbox[0] = GEN6_RBSYNC; ring->signal_mbox[1] = GEN6_VBSYNC; ring->init = init_ring_common; return <API key>(dev, ring); } int <API key>(struct intel_ring_buffer *ring) { int ret; if (!ring->gpu_caches_dirty) return 0; ret = ring->flush(ring, 0, <API key>); if (ret) return ret; <API key>(ring, 0, <API key>); ring->gpu_caches_dirty = false; return 0; } int <API key>(struct intel_ring_buffer *ring) { uint32_t flush_domains; int ret; flush_domains = 0; if (ring->gpu_caches_dirty) flush_domains = <API key>; ret = ring->flush(ring, <API key>, flush_domains); if (ret) return ret; <API key>(ring, <API key>, flush_domains); ring->gpu_caches_dirty = false; return 0; }
<?php ?> //<script> var Ossn = Ossn || {}; Ossn.Startups = new Array(); /** * Register a startup function * * @return void */ Ossn.<API key> = function($func) { Ossn.Startups.push($func); }; /** * Register a ajax request * * @param $data['form'] = form id * $data['callback'] = call back function * $data['error'] = on error function * $data['beforeSend'] = before send function * $data['url'] = form action url * * @return bool */ Ossn.ajaxRequest = function($data) { $(function() { var $form_name = $data['form']; var url = $data['url']; var callback = $data['callback']; var error = $data['error']; var befsend = $data['beforeSend']; var action = $data['action']; var containMedia = $data['containMedia']; if (url == true) { url = $($form_name).attr('action'); } $($form_name).submit(function(event) { event.preventDefault(); if (!callback) { return false; } if (!befsend) { befsend = function() {} } if (!action) { action = false; } if (action == true) { url = Ossn.AddTokenToUrl(url); } if (!error) { error = function(xhr, status, error) { if (error == 'Internal Server Error' || error !== '') { Ossn.MessageBox('syserror/unknown'); } }; } var $form = $(this); if(containMedia == true){ $vars = { async: true, cache: false, contentType: false, type: 'post', beforeSend: befsend, url: url, error: error, data: new FormData($form[0]), processData: false, success: callback, }; } else { $vars = { async: true, type: 'post', beforeSend: befsend, url: url, error: error, data: $form.serialize(), success: callback, }; } $.ajax($vars); }); }); }; /** * Register a post request * * @param $data['callback'] = call back function * $data['error'] = on error function * $data['beforeSend'] = before send function * $data['url'] = form action url * * @return bool */ Ossn.PostRequest = function($data) { var url = $data['url']; var callback = $data['callback']; var error = $data['error']; var befsend = $data['beforeSend']; var $fdata = $data['params']; var action = $data['action']; if (!callback) { return false; } if (!befsend) { befsend = function() {} } if (!action) { action = true; } if (action == true) { url = Ossn.AddTokenToUrl(url); } if (!error) { error = function() {}; } $.ajax({ async: true, type: 'post', beforeSend: befsend, url: url, error: error, data: $fdata, success: callback, }); }; /** * Message done * * @param $message = message * * @return mix data */ Ossn.MessageDone = function($message) { return "<div class='ossn-message-done'>" + $message + "</div>"; }; /** * Redirect user to other page * * @param $url = path * * @return void */ Ossn.redirect = function($url) { window.location = Ossn.site_url + $url; }; /** * Setup a profile cover buttons * * @return void */ Ossn.<API key>(function() { $(document).ready(function() { $('.profile-cover').hover(function() { $('.<API key>').find('a').show(); }, function() { $('.<API key>').find('a').hide(); }); }); }); /** * Setup a profile photo buttons * * @return void */ Ossn.<API key>(function() { $(document).ready(function() { $('.profile-photo').hover(function() { $('.upload-photo').slideDown(); }, function() { $('.upload-photo').slideUp(); }); }); }); /** * Setup ajax request for user register * * @return void */ Ossn.<API key>(function() { Ossn.ajaxRequest({ url: Ossn.site_url + "action/user/register", form: '#ossn-home-signup', beforeSend: function(request) { var failedValidate = false; $('#ossn-submit-button').show(); $('#ossn-home-signup .ossn-loading').addClass("ossn-hidden"); $('#ossn-home-signup').find('#ossn-signup-errors').hide(); $('#ossn-home-signup input').filter(function() { $(this).closest('span').removeClass('ossn-required'); if (this.type == 'radio') { if(!$("input[name='gender']:checked").val()){ $(this).closest('span').addClass('ossn-required'); failedValidate = true; } } if (this.value == "") { $(this).addClass('ossn-red-borders'); failedValidate = true; request.abort(); return false; } }); if(failedValidate == false){ $('#ossn-submit-button').hide(); $('#ossn-home-signup .ossn-loading').removeClass("ossn-hidden"); } }, callback: function(callback) { if (callback['dataerr']) { $('#ossn-home-signup').find('#ossn-signup-errors').html(callback['dataerr']).fadeIn(); $('#ossn-submit-button').show(); $('#ossn-home-signup .ossn-loading').addClass("ossn-hidden"); } if (callback['success'] == 1) { $('#ossn-home-signup').html(Ossn.MessageDone(callback['datasuccess'])); } $('#ossn-submit-button').attr('type', 'submit') $('#ossn-submit-button').attr('style', 'opacity:1;'); } }); }); /** * Setup system messages * * @return void */ Ossn.<API key>(function() { $(document).ready(function() { $('.<API key>').find('div').animate({ opacity: 0.9 }, 6000).slideUp('slow'); }); }); /** * Add a system messages for users * * @param string $messages Message for user * @param string $type Message type success (default) or error * * @return void */ Ossn.trigger_message = function($message, $type){ $type = $type || 'success'; if($type == 'error'){ //compitable to bootstrap framework $type = 'danger'; } if($message == ''){ return false; } $html = "<div class='alert alert-"+$type+"'><a href=\"#\" class=\"close\" data-dismiss=\"alert\">&times;</a>"+$message+"</div>"; $('.<API key>').append($html); if($('.<API key>').is(":not(:visible)")){ $('.<API key>').slideDown('slow'); } $('.<API key>').find('div').animate({ opacity: 0.9 }, 6000).slideUp('slow'); }; /** * Setup Google Location input * * @return void */ Ossn.<API key>(function() { $(document).ready(function() { var autocomplete; if (typeof google === 'object') { autocomplete = new google.maps.places.Autocomplete( /** @type {HTMLInputElement} */ (document.getElementById('<API key>')), { types: ['geocode'] }); google.maps.event.addListener(autocomplete, 'place_changed', function() {}); } }); }); /** * Topbar dropdown button * * @return void */ Ossn.<API key>(function() { $(document).ready(function() { $('.<API key>').click(function() { if ($('.<API key>').is(":not(:visible)")) { $('.<API key>').show(); } else { $('.<API key>').hide(); } }); }); }); /** * Show exception on component delete * * @return void */ Ossn.<API key>(function() { $(document).ready(function() { //show a confirmation mssage before delete component #444 $('.<API key>').click(function(e) { e.preventDefault(); var del = confirm(Ossn.Print('ossn:component:delete:exception')); if (del == true) { var actionurl = $(this).attr('href'); window.location = actionurl; } }); }); }); /** * Show exception , are you sure? * * @return void */ Ossn.<API key>(function() { $(document).ready(function() { $('.ossn-make-sure').click(function(e) { e.preventDefault(); var del = confirm(Ossn.Print('ossn:exception:make:sure')); if (del == true) { var actionurl = $(this).attr('href'); window.location = actionurl; } }); }); }); /** * Show exception on user delete * * @return void */ Ossn.<API key>(function() { $(document).ready(function() { $('.userdelete').click(function(e) { e.preventDefault(); var del = confirm(Ossn.Print('ossn:user:delete:exception')); if (del == true) { var actionurl = $(this).attr('href'); window.location = actionurl; } }); }); }); /** * Close a Ossn message box * * @return void */ Ossn.MessageBoxClose = function() { $('.ossn-message-box').hide(); $('.ossn-halt').removeClass('ossn-light').hide(); $('.ossn-halt').attr('style', ''); }; /** * Load Message box * * @return void */ Ossn.MessageBox = function($url) { Ossn.PostRequest({ url: Ossn.site_url + $url, beforeSend: function() { $('.ossn-halt').addClass('ossn-light'); $('.ossn-halt').attr('style', 'height:' + $(document).height() + 'px;'); $('.ossn-halt').show(); $('.ossn-message-box').html('<div class="ossn-loading ossn-box-loading"></div>'); $('.ossn-message-box').fadeIn('slow'); }, callback: function(callback) { $('.ossn-message-box').html(callback).fadeIn(); }, }); }; /** * Load a media viewer * * @return void */ Ossn.Viewer = function($url) { Ossn.PostRequest({ url: Ossn.site_url + $url, beforeSend: function() { $('.ossn-halt').removeClass('ossn-light'); $('.ossn-halt').show(); $('.ossn-viewer').html('<table class="ossn-container"><tr><td class="image-block" style="text-align: center;width:100%;"><div class="ossn-viewer-loding">Loading...</div></td></tr></table>'); $('.ossn-viewer').show(); }, callback: function(callback) { $('.ossn-viewer').html(callback).show(); }, }); }; /** * Close a media viewer * * @return void */ Ossn.ViewerClose = function($url) { $('.ossn-halt').addClass('ossn-light'); $('.ossn-halt').hide(); $('.ossn-viewer').html(''); $('.ossn-viewer').hide(); }; /** * Click on element * * @param $elem = element; * * @return void */ Ossn.Clk = function($elem) { $($elem).click(); }; /** * Get url paramter * * @param name Parameter name; * url complete url * * @return string */ Ossn.UrlParams = function(name, url) { var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(url); if (!results) { return 0; } return results[1] || 0; }; /** * Returns an object with key/values of the parsed query string. * * @param {String} string The string to parse * @return {Object} The parsed object string */ Ossn.ParseStr = function(string) { var params = {}, result, key, value, re = /([^&=]+)=?([^&]*)/g, re2 = /\[\]$/; while (result = re.exec(string)) { key = decodeURIComponent(result[1].replace(/\+/g, ' ')); value = decodeURIComponent(result[2].replace(/\+/g, ' ')); if (re2.test(key)) { key = key.replace(re2, ''); if (!params[key]) { params[key] = []; } params[key].push(value); } else { params[key] = value; } } return params; }; Ossn.ParseUrl = function(url, component, expand) { // which was release under the MIT // It was modified to fix mailto: and javascript: support. expand = expand || false; component = component || false; var re_str = // scheme (and user@ testing) '^(?:(?![^:@]+:[^:@/]*@)([^:/? // possibly a user[:password]@ + '((?:(([^:@]*)(?::([^:@]*))?)?@)?' // host and port + '([^:/? // path + '(((/(?:[^? // query string + '(?:\\?([^ // fragment + '(?: keys = { 1: "scheme", 4: "user", 5: "pass", 6: "host", 7: "port", 9: "path", 12: "query", 13: "fragment" }, results = {}; if (url.indexOf('mailto:') === 0) { results['scheme'] = 'mailto'; results['path'] = url.replace('mailto:', ''); return results; } if (url.indexOf('javascript:') === 0) { results['scheme'] = 'javascript'; results['path'] = url.replace('javascript:', ''); return results; } var re = new RegExp(re_str); var matches = re.exec(url); for (var i in keys) { if (matches[i]) { results[keys[i]] = matches[i]; } } if (expand && typeof(results['query']) != 'undefined') { results['query'] = ParseStr(results['query']); } if (component) { if (typeof(results[component]) != 'undefined') { return results[component]; } else { return false; } } return results; }; /** * Add action token to url * * @param string data Full complete url */ Ossn.AddTokenToUrl = function(data) { if (typeof data === 'string') { // is this a full URL, relative URL, or just the query string? var parts = Ossn.ParseUrl(data), args = {}, base = ''; if (parts['host'] === undefined) { if (data.indexOf('?') === 0) { // query string base = '?'; args = Ossn.ParseStr(parts['query']); } } else { // full or relative URL if (parts['query'] !== undefined) { // with query string args = Ossn.ParseStr(parts['query']); } var split = data.split('?'); base = split[0] + '?'; } args["ossn_ts"] = Ossn.Config.token.ossn_ts; args["ossn_token"] = Ossn.Config.token.ossn_token; return base + jQuery.param(args); } }; var sprintf = (function() { function get_type(variable) { return Object.prototype.toString.call(variable).slice(8, -1).toLowerCase(); } function str_repeat(input, multiplier) { for (var output = []; multiplier > 0; output[--multiplier] = input) { /* do nothing */ } return output.join(''); } var str_format = function() { if (!str_format.cache.hasOwnProperty(arguments[0])) { str_format.cache[arguments[0]] = str_format.parse(arguments[0]); } return str_format.format.call(null, str_format.cache[arguments[0]], arguments); }; str_format.format = function(parse_tree, argv) { var cursor = 1, tree_length = parse_tree.length, node_type = '', arg, output = [], i, k, match, pad, pad_character, pad_length; for (i = 0; i < tree_length; i++) { node_type = get_type(parse_tree[i]); if (node_type === 'string') { output.push(parse_tree[i]); } else if (node_type === 'array') { match = parse_tree[i]; // convenience purposes only if (match[2]) { // keyword argument arg = argv[cursor]; for (k = 0; k < match[2].length; k++) { if (!arg.hasOwnProperty(match[2][k])) { throw (sprintf('[sprintf] property "%s" does not exist', match[2][k])); } arg = arg[match[2][k]]; } } else if (match[1]) { // positional argument (explicit) arg = argv[match[1]]; } else { // positional argument (implicit) arg = argv[cursor++]; } if (/[^s]/.test(match[8]) && (get_type(arg) != 'number')) { throw (sprintf('[sprintf] expecting number but found %s', get_type(arg))); } switch (match[8]) { case 'b': arg = arg.toString(2); break; case 'c': arg = String.fromCharCode(arg); break; case 'd': arg = parseInt(arg, 10); break; case 'e': arg = match[7] ? arg.toExponential(match[7]) : arg.toExponential(); break; case 'f': arg = match[7] ? parseFloat(arg).toFixed(match[7]) : parseFloat(arg); break; case 'o': arg = arg.toString(8); break; case 's': arg = ((arg = String(arg)) && match[7] ? arg.substring(0, match[7]) : arg); break; case 'u': arg = Math.abs(arg); break; case 'x': arg = arg.toString(16); break; case 'X': arg = arg.toString(16).toUpperCase(); break; } arg = (/[def]/.test(match[8]) && match[3] && arg >= 0 ? '+' + arg : arg); pad_character = match[4] ? match[4] == '0' ? '0' : match[4].charAt(1) : ' '; pad_length = match[6] - String(arg).length; pad = match[6] ? str_repeat(pad_character, pad_length) : ''; output.push(match[5] ? arg + pad : pad + arg); } } return output.join(''); }; str_format.cache = {}; str_format.parse = function(fmt) { var _fmt = fmt, match = [], parse_tree = [], arg_names = 0; while (_fmt) { if ((match = /^[^\x25]+/.exec(_fmt)) !== null) { parse_tree.push(match[0]); } else if ((match = /^\x25{2}/.exec(_fmt)) !== null) { parse_tree.push('%'); } else if ((match = /^\x25(?:([1-9]\d*)\$|\(([^\)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-fosuxX])/.exec(_fmt)) !== null) { if (match[2]) { arg_names |= 1; var field_list = [], replacement_field = match[2], field_match = []; if ((field_match = /^([a-z_][a-z_\d]*)/i.exec(replacement_field)) !== null) { field_list.push(field_match[1]); while ((replacement_field = replacement_field.substring(field_match[0].length)) !== '') { if ((field_match = /^\.([a-z_][a-z_\d]*)/i.exec(replacement_field)) !== null) { field_list.push(field_match[1]); } else if ((field_match = /^\[(\d+)\]/.exec(replacement_field)) !== null) { field_list.push(field_match[1]); } else { throw ('[sprintf] huh?'); } } } else { throw ('[sprintf] huh?'); } match[2] = field_list; } else { arg_names |= 2; } if (arg_names === 3) { throw ('[sprintf] mixing positional and named placeholders is not (yet) supported'); } parse_tree.push(match); } else { throw ('[sprintf] huh?'); } _fmt = _fmt.substring(match[0].length); } return parse_tree; }; return str_format; })(); var vsprintf = function(fmt, argv) { argv.unshift(fmt); return sprintf.apply(null, argv); }; /** * Ossn Print * Print a langauge string */ Ossn.Print = function(str, args) { if (OssnLocale[str]) { if (!args) { return OssnLocale[str]; } else { return vsprintf(OssnLocale[str], args); } } return str; }; /** * Get a available update version * * @added in v3.0 */ Ossn.<API key>(function() { $(document).ready(function() { Ossn.PostRequest({ url: Ossn.site_url + "administrator/version", action: false, callback: function(callback) { if(callback['version']){ $('.avaiable-updates').html(callback['version']); } } }); }); }); /** * Initialize ossn startup functions * * @return void */ Ossn.Init = function() { for (var i = 0; i <= Ossn.Startups.length; i++) { if (typeof Ossn.Startups[i] !== "undefined") { Ossn.Startups[i](); } } };
# -*- coding: utf-8 -*- # <API key>.py # This file is part of NEST. # NEST is free software: you can redistribute it and/or modify # (at your option) any later version. # NEST is distributed in the hope that it will be useful, # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the import nest import nest.voltage_trace import numpy import pylab nest.ResetKernel() n_syn = 12.0 # number of synapses in a connection n_trials = 30 # number of measurement trials # parameter set for facilitation fac_params = {"U": 0.03, "u": 0.03, "tau_fac": 500., "tau_rec": 200., "weight": 1.} dep_params = {"U": 0.5, "u": 0.5, "tau_fac": 15., "tau_rec": 670., "weight": 1.} lin_params = {"U": 0.3, "u": 0.3, "tau_fac": 330., "tau_rec": 330., "weight": 1.} # Here we assign the parameter set to the synapse models t1_params = fac_params # for tsodyks2_synapse t2_params = t1_params.copy() # for furhmann_synapse t2_params['n'] = n_syn t2_params['weight'] = 1. / n_syn nest.SetDefaults("tsodyks2_synapse", t1_params) nest.SetDefaults("quantal_stp_synapse", t2_params) nest.SetDefaults("iaf_psc_exp", {"tau_syn_ex": 3., 'tau_m': 70.}) source = nest.Create('spike_generator') nest.SetStatus(source, {'spike_times': [30., 60., 90., 120., 150., 180., 210., 240., 270., 300., 330., 360., 390., 900.]}) parrot = nest.Create('parrot_neuron') neuron = nest.Create("iaf_psc_exp", 2) nest.Connect(source, parrot) nest.Connect(parrot, neuron[:1], syn_spec="tsodyks2_synapse") nest.Connect(parrot, neuron[1:], syn_spec="quantal_stp_synapse") voltmeter = nest.Create("voltmeter", 2) nest.SetStatus(voltmeter, {"withgid": False, "withtime": True}) t_plot = 1000. t_tot = 1500. ''' the following is a dry run trial so that the synapse dynamics is idential in all subsequent trials. ''' nest.Simulate(t_tot) ''' Now we connect the voltmeters ''' nest.Connect([voltmeter[0]], [neuron[0]]) nest.Connect([voltmeter[1]], [neuron[1]]) ''' WE now run the specified number of trials in a loop. ''' for t in range(n_trials): t_net = nest.GetKernelStatus('time') nest.SetStatus(source, {'origin': t_net}) nest.Simulate(t_tot) nest.Simulate(.1) # flush the last voltmeter events from the queue vm = numpy.array(nest.GetStatus([voltmeter[1]], 'events')[0]['V_m']) vm_reference = numpy.array(nest.GetStatus([voltmeter[0]], 'events')[0]['V_m']) t_tot = int(t_tot) t_plot = int(t_plot) vm.shape = (n_trials, t_tot) vm_reference.shape = (n_trials, t_tot) vm_mean = numpy.array([numpy.mean(vm[:, i]) for i in range(t_tot)]) vm_ref_mean = numpy.array([numpy.mean(vm_reference[:, i]) for i in range(t_tot)]) for t in range(n_trials): pylab.plot(vm[t][:t_plot], color='gray', lw=0.5) pylab.plot(vm_mean[:t_plot], color='black', lw=2.) pylab.plot(vm_reference[0][:t_plot], color='red', lw=2.) ''' To display the results, you need to execute pylab.show() '''
<?php $sidebarPage = new QodeAdminPage("_sidebar", "Sidebar", "fa fa-bars"); $qodeFramework->qodeOptions->addAdminPage("sidebarPage",$sidebarPage); //Widgets style $panel1 = new QodePanel("Widgets Style","widget_panel"); $sidebarPage->addChild("panel1",$panel1); $group1 = new QodeGroup("Title Style","Define styles for widgets title"); $panel1->addChild("group1",$group1); $row1 = new QodeRow(); $group1->addChild("row1",$row1); $sidebar_title_color = new QodeField("colorsimple","sidebar_title_color","","Text Color","This is some description"); $row1->addChild("sidebar_title_color",$sidebar_title_color); $<API key> = new QodeField("textsimple","<API key>","","Font Size (px)","This is some description"); $row1->addChild("<API key>",$<API key>); $<API key> = new QodeField("textsimple","<API key>","","Line Height (px)","This is some description"); $row1->addChild("<API key>",$<API key>); $<API key> = new QodeField("selectblanksimple","<API key>","","Text Transform","This is some description",$<API key>); $row1->addChild("<API key>",$<API key>); $row2 = new QodeRow(true); $group1->addChild("row2",$row2); $<API key> = new QodeField("fontsimple","<API key>","-1","Font Family","This is some description"); $row2->addChild("<API key>",$<API key>); $<API key> = new QodeField("selectblanksimple","<API key>","","Font Style","This is some description",$options_fontstyle); $row2->addChild("<API key>",$<API key>); $<API key> = new QodeField("selectblanksimple","<API key>","","Font Weight","This is some description",$options_fontweight); $row2->addChild("<API key>",$<API key>); $<API key> = new QodeField("textsimple","<API key>","","Letter Spacing (px)","This is some description"); $row2->addChild("<API key>",$<API key>); $group2 = new QodeGroup("Text Style","Define styles for widget text"); $panel1->addChild("group2",$group2); $row1 = new QodeRow(); $group2->addChild("row1",$row1); $sidebar_text_color = new QodeField("colorsimple","sidebar_text_color","","Text Color","This is some description"); $row1->addChild("sidebar_text_color",$sidebar_text_color); $<API key> = new QodeField("textsimple","<API key>","","Font Size (px)","This is some description"); $row1->addChild("<API key>",$<API key>); $<API key> = new QodeField("textsimple","<API key>","","Line Height (px)","This is some description"); $row1->addChild("<API key>",$<API key>); $<API key> = new QodeField("selectblanksimple","<API key>","","Text Transform","This is some description",$<API key>); $row1->addChild("<API key>",$<API key>); $row2 = new QodeRow(true); $group2->addChild("row2",$row2); $<API key> = new QodeField("fontsimple","<API key>","-1","Font Family","This is some description"); $row2->addChild("<API key>",$<API key>); $<API key> = new QodeField("selectblanksimple","<API key>","","Font Style","This is some description",$options_fontstyle); $row2->addChild("<API key>",$<API key>); $<API key> = new QodeField("selectblanksimple","<API key>","","Font Weight","This is some description",$options_fontweight); $row2->addChild("<API key>",$<API key>); $<API key> = new QodeField("textsimple","<API key>","","Letter Spacing (px)","This is some description"); $row2->addChild("<API key>",$<API key>); $group3 = new QodeGroup("Link Style","Define styles for widget links"); $panel1->addChild("group3",$group3); $row1 = new QodeRow(); $group3->addChild("row1",$row1); $sidebar_link_color = new QodeField("colorsimple","sidebar_link_color","","Text Color","This is some description"); $row1->addChild("sidebar_link_color",$sidebar_link_color); $<API key> = new QodeField("colorsimple","<API key>","","Text Hover Color","This is some description"); $row1->addChild("<API key>",$<API key>); $<API key> = new QodeField("textsimple","<API key>","","Font Size (px)","This is some description"); $row1->addChild("<API key>",$<API key>); $<API key> = new QodeField("textsimple","<API key>","","Line Height (px)","This is some description"); $row1->addChild("<API key>",$<API key>); $row2 = new QodeRow(true); $group3->addChild("row2",$row2); $<API key> = new QodeField("selectblanksimple","<API key>","","Text Transform","This is some description",$<API key>); $row2->addChild("<API key>",$<API key>); $<API key> = new QodeField("fontsimple","<API key>","-1","Font Family","This is some description"); $row2->addChild("<API key>",$<API key>); $<API key> = new QodeField("selectblanksimple","<API key>","","Font Style","This is some description",$options_fontstyle); $row2->addChild("<API key>",$<API key>); $<API key> = new QodeField("selectblanksimple","<API key>","","Font Weight","This is some description",$options_fontweight); $row2->addChild("<API key>",$<API key>); $row3 = new QodeRow(); $group3->addChild("row3",$row3); $<API key> = new QodeField("textsimple","<API key>","","Letter Spacing (px)","This is some description"); $row3->addChild("<API key>",$<API key>);
#pragma once #include "Texture.h" #if defined(HAS_GL) || defined(HAS_GLES) #include "system_gl.h" /* CGLTexture */ class CGLTexture : public CBaseTexture { public: CGLTexture(unsigned int width = 0, unsigned int height = 0, unsigned int format = XB_FMT_A8R8G8B8); virtual ~CGLTexture(); void CreateTextureObject(); virtual void <API key>(); void LoadToGPU(); void BindToUnit(unsigned int unit); private: GLuint m_texture; }; #endif
#ifndef <API key> #define <API key> #pragma once #include "ui/menu.h" namespace ui { class menu_file_selector : public menu { public: enum class result { INVALID = -1, EMPTY = 0x1000, SOFTLIST, CREATE, FILE }; menu_file_selector( mame_ui_manager &mui, render_container &container, <API key> *image, std::string &current_directory, std::string &current_file, bool has_empty, bool has_softlist, bool has_create, result &result); virtual ~menu_file_selector() override; protected: virtual void custom_render(void *selectedref, float top, float bottom, float x, float y, float x2, float y2) override; virtual bool custom_mouse_down() override; private: enum <API key> { <API key>, <API key>, <API key>, <API key>, <API key>, <API key> }; struct file_selector_entry { file_selector_entry() { } file_selector_entry(file_selector_entry &&) = default; file_selector_entry &operator=(file_selector_entry &&) = default; <API key> type; std::string basename; std::string fullpath; }; // internal state <API key> *const m_image; std::string & m_current_directory; std::string & m_current_file; bool const m_has_empty; bool const m_has_softlist; bool const m_has_create; result & m_result; std::vector<file_selector_entry> m_entrylist; std::string m_hover_directory; std::string m_filename; virtual void populate(float &customtop, float &custombottom) override; virtual void handle() override; // methods int compare_entries(const file_selector_entry *e1, const file_selector_entry *e2); file_selector_entry &append_entry(<API key> entry_type, const std::string &entry_basename, const std::string &entry_fullpath); file_selector_entry &append_entry(<API key> entry_type, std::string &&entry_basename, std::string &&entry_fullpath); file_selector_entry *append_dirent_entry(const osd::directory::entry *dirent); void <API key>(const file_selector_entry *entry); void select_item(const file_selector_entry &entry); void type_search_char(char32_t ch); }; class menu_select_rw : public menu { public: enum class result { INVALID = -1, READONLY = 0x3000, READWRITE, WRITE_OTHER, WRITE_DIFF }; menu_select_rw( mame_ui_manager &mui, render_container &container, bool can_in_place, result &result); virtual ~menu_select_rw() override; static void *itemref_from_result(result result); static result result_from_itemref(void *itemref); private: virtual void populate(float &customtop, float &custombottom) override; virtual void handle() override; // internal state bool m_can_in_place; result & m_result; }; } // namespace ui #endif // <API key>
ace.define('ace/mode/abap', ['require', 'exports', 'module' , 'ace/tokenizer', 'ace/mode/<API key>', 'ace/mode/folding/coffee', 'ace/range', 'ace/mode/text', 'ace/lib/oop'], function(require, exports, module) { var Tokenizer = require("../tokenizer").Tokenizer; var Rules = require("./<API key>").AbapHighlightRules; var FoldMode = require("./folding/coffee").FoldMode; var Range = require("../range").Range; var TextMode = require("./text").Mode; var oop = require("../lib/oop"); function Mode() { this.$tokenizer = new Tokenizer(new Rules().getRules(), "i"); this.foldingRules = new FoldMode(); } oop.inherits(Mode, TextMode); (function() { this.getNextLineIndent = function(state, line, tab) { var indent = this.$getIndent(line); return indent; }; this.toggleCommentLines = function(state, doc, startRow, endRow){ var range = new Range(0, 0, 0, 0); for (var i = startRow; i <= endRow; ++i) { var line = doc.getLine(i); if (hereComment.test(line)) continue; if (commentLine.test(line)) line = line.replace(commentLine, '$1'); else line = line.replace(indentation, '$& range.end.row = range.start.row = i; range.end.column = line.length + 1; doc.replace(range, line); } }; }).call(Mode.prototype); exports.Mode = Mode; }); ace.define('ace/mode/<API key>', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/<API key>'], function(require, exports, module) { var oop = require("../lib/oop"); var TextHighlightRules = require("./<API key>").TextHighlightRules; var AbapHighlightRules = function() { var keywordMapper = this.createKeywordMapper({ "variable.language": "this", "keyword": "ADD ALIAS ALIASES ASSERT ASSIGN ASSIGNING AT BACK" + " CALL CASE CATCH CHECK CLASS CLEAR CLOSE CNT COLLECT COMMIT COMMUNICATION COMPUTE CONCATENATE CONDENSE CONSTANTS CONTINUE CONTROLS CONVERT CREATE CURRENCY" + " DATA DEFINE DEFINITION DEFERRED DELETE DESCRIBE DETAIL DIVIDE DO" + " ELSE ELSEIF ENDAT ENDCASE ENDCLASS ENDDO ENDEXEC ENDFORM ENDFUNCTION ENDIF ENDIFEND ENDINTERFACE ENDLOOP ENDMETHOD ENDMODULE ENDON ENDPROVIDE ENDSELECT ENDTRY ENDWHILE EVENT EVENTS EXEC EXIT EXPORT EXPORTING EXTRACT" + " FETCH FIELDS FORM FORMAT FREE FROM FUNCTION" + " GENERATE GET" + " HIDE" + " IF IMPORT IMPORTING INDEX INFOTYPES INITIALIZATION INTERFACE INTERFACES INPUT INSERT IMPLEMENTATION" + " LEAVE LIKE LINE LOAD LOCAL LOOP" + " MESSAGE METHOD METHODS MODIFY MODULE MOVE MULTIPLY" + " ON OVERLAY OPTIONAL OTHERS" + " PACK PARAMETERS PERFORM POSITION PROGRAM PROVIDE PUT" + " RAISE RANGES READ RECEIVE RECEIVING REDEFINITION REFERENCE REFRESH REJECT REPLACE REPORT RESERVE RESTORE RETURNING ROLLBACK" + " SCAN SCROLL SEARCH SELECT SET SHIFT SKIP SORT SORTED SPLIT STANDARD STATICS STEP STOP SUBMIT SUBTRACT SUM SUMMARY SUPPRESS" + " TABLES TIMES TRANSFER TRANSLATE TRY TYPE TYPES" + " UNASSIGN ULINE UNPACK UPDATE" + " WHEN WHILE WINDOW WRITE" + " OCCURS STRUCTURE OBJECT PROPERTY" + " CASTING APPEND RAISING VALUE COLOR" + " CHANGING EXCEPTION EXCEPTIONS DEFAULT CHECKBOX COMMENT" + " ID NUMBER FOR TITLE OUTPUT" + " WITH EXIT USING" + " INTO WHERE GROUP BY HAVING ORDER BY SINGLE" + " APPENDING CORRESPONDING FIELDS OF TABLE" + " LEFT RIGHT OUTER INNER JOIN AS CLIENT SPECIFIED BYPASSING BUFFER UP TO ROWS CONNECTING" + " EQ NE LT LE GT GE NOT AND OR XOR IN LIKE BETWEEN", "constant.language": "TRUE FALSE NULL SPACE", "support.type": "c n i p f d t x string xstring decfloat16 decfloat34", "keyword.operator": "abs sign ceil floor trunc frac acos asin atan cos sin tan" + " abapOperator cosh sinh tanh exp log log10 sqrt" + " strlen xstrlen charlen numofchar dbmaxlen lines" }, "text", true, " "); var compoundKeywords = "WITH\\W+(?:HEADER\\W+LINE|FRAME|KEY)|NO\\W+STANDARD\\W+PAGE\\W+HEADING|"+ "EXIT\\W+FROM\\W+STEP\\W+LOOP|BEGIN\\W+OF\\W+(?:BLOCK|LINE)|BEGIN\\W+OF|"+ "END\\W+OF\\W+(?:BLOCK|LINE)|END\\W+OF|NO\\W+INTERVALS|"+ "RESPECTING\\W+BLANKS|SEPARATED\\W+BY|USING\\W+(?:EDIT\\W+MASK)|"+ "WHERE\\W+(?:LINE)|RADIOBUTTON\\W+GROUP|REF\\W+TO|"+ "(?:PUBLIC|PRIVATE|PROTECTED)(?:\\W+SECTION)?|DELETING\\W+(?:TRAILING|LEADING)"+ "(?:ALL\\W+OCCURRENCES)|(?:FIRST|LAST)\\W+OCCURRENCE|INHERITING\\W+FROM|"+ "LINE-COUNT|ADD-CORRESPONDING|AUTHORITY-CHECK|BREAK-POINT|CLASS-DATA|CLASS-METHODS|"+ "CLASS-METHOD|<API key>|EDITOR-CALL|END-OF-DEFINITION|END-OF-PAGE|END-OF-SELECTION|"+ "FIELD-GROUPS|FIELD-SYMBOLS|FUNCTION-POOL|MOVE-CORRESPONDING|<API key>|NEW-LINE|"+ "NEW-PAGE|NEW-SECTION|PRINT-CONTROL|<API key>|SELECT-OPTIONS|SELECTION-SCREEN|"+ "START-OF-SELECTION|<API key>|SYNTAX-CHECK|SYNTAX-TRACE|TOP-OF-PAGE|TYPE-POOL|"+ "TYPE-POOLS|LINE-SIZE|LINE-COUNT|MESSAGE-ID|DISPLAY-MODE|READ(?:-ONLY)?|"+ "IS\\W+(?:NOT\\W+)?(?:ASSIGNED|BOUND|INITIAL|SUPPLIED)"; this.$rules = { "start" : [ {token : "string", regex : "`", next : "string"}, {token : "string", regex : "'", next : "qstring"}, {token : "doc.comment", regex : /^\*.+/}, {token : "comment", regex : /".+$/}, {token : "invalid", regex: "\\.{2,}"}, {token : "keyword.operator", regex: /\W[\-+\%=<>*]\W|\*\*|[~:,\.&$]|->*?|=>/}, {token : "paren.lparen", regex : "[\\[({]"}, {token : "paren.rparen", regex : "[\\])}]"}, {token : "constant.numeric", regex: "[+-]?\\d+\\b"}, {token : "variable.parameter", regex : /sy|pa?\d\d\d\d\|t\d\d\d\.|innnn/}, {token : "keyword", regex : compoundKeywords}, {token : "variable.parameter", regex : /\w+-\w+(?:-\w+)*/}, {token : keywordMapper, regex : "\\w+\\b"}, ], "qstring" : [ {token : "constant.language.escape", regex : "''"}, {token : "string", regex : "'", next : "start", merge : true}, {token : "string", regex : ".|\w+", merge : true} ], "string" : [ {token : "constant.language.escape", regex : "``"}, {token : "string", regex : "`", next : "start", merge : true}, {token : "string", regex : ".|\w+", merge : true} ] } }; oop.inherits(AbapHighlightRules, TextHighlightRules); exports.AbapHighlightRules = AbapHighlightRules; }); ace.define('ace/mode/folding/coffee', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/folding/fold_mode', 'ace/range'], function(require, exports, module) { var oop = require("../../lib/oop"); var BaseFoldMode = require("./fold_mode").FoldMode; var Range = require("../../range").Range; var FoldMode = exports.FoldMode = function() {}; oop.inherits(FoldMode, BaseFoldMode); (function() { this.getFoldWidgetRange = function(session, foldStyle, row) { var range = this.indentationBlock(session, row); if (range) return range; var re = /\S/; var line = session.getLine(row); var startLevel = line.search(re); if (startLevel == -1 || line[startLevel] != " return; var startColumn = line.length; var maxRow = session.getLength(); var startRow = row; var endRow = row; while (++row < maxRow) { line = session.getLine(row); var level = line.search(re); if (level == -1) continue; if (line[level] != " break; endRow = row; } if (endRow > startRow) { var endColumn = session.getLine(endRow).length; return new Range(startRow, startColumn, endRow, endColumn); } }; this.getFoldWidget = function(session, foldStyle, row) { var line = session.getLine(row); var indent = line.search(/\S/); var next = session.getLine(row + 1); var prev = session.getLine(row - 1); var prevIndent = prev.search(/\S/); var nextIndent = next.search(/\S/); if (indent == -1) { session.foldWidgets[row - 1] = prevIndent!= -1 && prevIndent < nextIndent ? "start" : ""; return ""; } if (prevIndent == -1) { if (indent == nextIndent && line[indent] == "#" && next[indent] == "#") { session.foldWidgets[row - 1] = ""; session.foldWidgets[row + 1] = ""; return "start"; } } else if (prevIndent == indent && line[indent] == "#" && prev[indent] == "#") { if (session.getLine(row - 2).search(/\S/) == -1) { session.foldWidgets[row - 1] = "start"; session.foldWidgets[row + 1] = ""; return ""; } } if (prevIndent!= -1 && prevIndent < indent) session.foldWidgets[row - 1] = "start"; else session.foldWidgets[row - 1] = ""; if (indent < nextIndent) return "start"; else return ""; }; }).call(FoldMode.prototype); });
#include "../include/sane/config.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include <errno.h> #include <signal.h> #include <limits.h> #ifdef HAVE_UNISTD_H # include <unistd.h> #endif #include <fcntl.h> #define BACKEND_NAME sanei_access /**< name of this module for debugging */ #include "../include/sane/sane.h" #include "../include/sane/sanei_debug.h" #include "../include/sane/sanei_access.h" #ifndef PATH_MAX # define PATH_MAX 1024 #endif #if defined(_WIN32) || defined(HAVE_OS2_H) # define PATH_SEP '\\' #else # define PATH_SEP '/' #endif #define REPLACEMENT_CHAR '_' #define PID_BUFSIZE 50 #define PROCESS_SELF 0 #define PROCESS_DEAD -1 #define PROCESS_OTHER 1 #ifdef ENABLE_LOCKING /** get the status/owner of a lock file * * The function tries to open an existing lockfile. On success, it reads out * the pid which is stored inside and tries to find out more about the status * of the process with the corresponding PID. * * @param fn - the complete filename of the lockfile to check * @return * - PROCESS_SELF - the calling process is owner of the lockfile * - PROCESS_DEAD - the process who created the lockfile is already dead * - PROCESS_OTHER - the process who created the lockfile is still alive */ static int get_lock_status( char *fn ) { char pid_buf[PID_BUFSIZE]; int fd, status; pid_t pid; fd = open( fn, O_RDONLY ); if( fd < 0 ) { DBG( 2, "does_process_exist: open >%s< failed: %s\n", fn, strerror(errno)); return PROCESS_OTHER; } read( fd, pid_buf, (PID_BUFSIZE-1)); pid_buf[PID_BUFSIZE-1] = '\0'; close( fd ); pid_buf[24] = '\0'; pid = strtol( pid_buf, NULL, 10 ); DBG( 2, "does_process_exist: PID %i\n", pid ); status = kill( pid, 0 ); if( status == -1 ) { if( errno == ESRCH ) { DBG( 2, "does_process_exist: process %i does not exist!\n", pid ); return PROCESS_DEAD; } DBG( 1, "does_process_exist: kill failed: %s\n", strerror(errno)); } else { DBG( 2, "does_process_exist: process %i does exist!\n", pid ); if( pid == getpid()){ DBG( 2, "does_process_exist: it's me!!!\n" ); return PROCESS_SELF; } } return PROCESS_OTHER; } static void <API key>( char *fn, const char *devname ) { char *p; strcpy( fn, STRINGIFY(PATH_SANE_LOCK_DIR)"/LCK.." ); p = &fn[strlen(fn)]; strcat( fn, devname ); while( *p != '\0' ) { if( *p == PATH_SEP ) *p = REPLACEMENT_CHAR; p++; } DBG( 2, "sanei_access: lockfile name >%s<\n", fn ); } #endif void sanei_access_init( const char *backend ) { DBG_INIT(); DBG( 2, "sanei_access_init: >%s<\n", backend); } SANE_Status sanei_access_lock( const char *devicename, SANE_Word timeout ) { #ifdef ENABLE_LOCKING char fn[PATH_MAX]; char pid_buf[PID_BUFSIZE]; int fd, to, i; #endif DBG( 2, "sanei_access_lock: devname >%s<, timeout: %u\n", devicename, timeout ); #ifndef ENABLE_LOCKING return SANE_STATUS_GOOD; #else to = timeout; if (to <= 0) to = 1; <API key>( fn, devicename ); for (i = 0; i < to; i++) { fd = open( fn, O_CREAT | O_EXCL | O_WRONLY, 0644 ); if (fd < 0) { if (errno == EEXIST) { switch( get_lock_status( fn )) { case PROCESS_DEAD: DBG( 2, "sanei_access_lock: " "deleting old lock file, retrying...\n" ); unlink( fn ); continue; break; case PROCESS_SELF: DBG( 2, "sanei_access_lock: success\n" ); return SANE_STATUS_GOOD; break; default: break; } DBG( 2, "sanei_access_lock: lock exists, waiting...\n" ); sleep(1); } else { DBG( 1, "sanei_access_lock: open >%s< failed: %s\n", fn, strerror(errno)); return <API key>; } } else { DBG( 2, "sanei_access_lock: success\n" ); sprintf( pid_buf, "% 11i sane\n", getpid()); write(fd, pid_buf, strlen(pid_buf)); close( fd ); return SANE_STATUS_GOOD; } } DBG( 1, "sanei_access_lock: timeout!\n"); return <API key>; #endif } SANE_Status sanei_access_unlock( const char *devicename ) { #ifdef ENABLE_LOCKING char fn[PATH_MAX]; #endif DBG( 2, "sanei_access_unlock: devname >%s<\n", devicename ); #ifdef ENABLE_LOCKING <API key>( fn, devicename ); unlink( fn ); #endif return SANE_STATUS_GOOD; } /* END sanei_access.c .......................................................*/
/* noscript-1000px.css: Kludgey noscript stylesheet */ /* Base Grid */ .\35 grid-layout .\31 2u { width: 100%; } .\35 grid-layout .\31 1u { width: 91.5%; } .\35 grid-layout .\31 0u { width: 83%; } .\35 grid-layout .\39 u { width: 74.5%; } .\35 grid-layout .\38 u { width: 66%; } .\35 grid-layout .\37 u { width: 57.5%; } .\35 grid-layout .\36 u { width: 49%; } .\35 grid-layout .\35 u { width: 40.5%; } .\35 grid-layout .\34 u { width: 32%; } .\35 grid-layout .\33 u { width: 23.5%; } .\35 grid-layout .\32 u { width: 15%; } .\35 grid-layout .\31 u { width: 6.5%; } .\35 grid-layout .\31 u, .\35 grid-layout .\32 u, .\35 grid-layout .\33 u, .\35 grid-layout .\34 u, .\35 grid-layout .\35 u, .\35 grid-layout .\36 u, .\35 grid-layout .\37 u, .\35 grid-layout .\38 u, .\35 grid-layout .\39 u, .\35 grid-layout .\31 0u, .\35 grid-layout .\31 1u, .\35 grid-layout .\31 2u { margin: 1% 0 1% 2%; float: left; } .\35 grid-layout:after { content: ''; display: block; clear: both; height: 0; } /* Desktop */ .\35 grid-layout .row:after { content: ''; display: block; clear: both; height: 0; } .\35 grid-layout .row > :first-child { margin-left: 0; } .\35 grid-layout .row:first-child > * { margin-top: 0; } .\35 grid-layout .row:last-child > * { margin-bottom: 0; } .\35 grid-layout .offset-1u:first-child { margin-left: 8.5% !important; } .\35 grid-layout .offset-2u:first-child { margin-left: 17% !important; } .\35 grid-layout .offset-3u:first-child { margin-left: 25.5% !important; } .\35 grid-layout .offset-4u:first-child { margin-left: 34% !important; } .\35 grid-layout .offset-5u:first-child { margin-left: 42.5% !important; } .\35 grid-layout .offset-6u:first-child { margin-left: 51% !important; } .\35 grid-layout .offset-7u:first-child { margin-left: 59.5% !important; } .\35 grid-layout .offset-8u:first-child { margin-left: 68% !important; } .\35 grid-layout .offset-9u:first-child { margin-left: 76.5% !important; } .\35 grid-layout .offset-10u:first-child { margin-left: 85% !important; } .\35 grid-layout .offset-11u:first-child { margin-left: 93.5% !important; } .\35 grid-layout .offset-1u { margin-left: 10.5% !important; } .\35 grid-layout .offset-2u { margin-left: 19% !important; } .\35 grid-layout .offset-3u { margin-left: 27.5% !important; } .\35 grid-layout .offset-4u { margin-left: 36% !important; } .\35 grid-layout .offset-5u { margin-left: 44.5% !important; } .\35 grid-layout .offset-6u { margin-left: 53% !important; } .\35 grid-layout .offset-7u { margin-left: 61.5% !important; } .\35 grid-layout .offset-8u { margin-left: 70% !important; } .\35 grid-layout .offset-9u { margin-left: 78.5% !important; } .\35 grid-layout .offset-10u { margin-left: 87% !important; } .\35 grid-layout .offset-11u { margin-left: 95.5% !important; }
# Numenta Platform for Intelligent Computing (NuPIC) # following terms and conditions apply: # This program is free software: you can redistribute it and/or modify # published by the Free Software Foundation. # This program is distributed in the hope that it will be useful, # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. MODEL_PARAMS = { # Type of model that the rest of these parameters apply to. 'model': "CLA", # Version that specifies the format of the config. 'version': 1, # Intermediate variables used to compute fields in modelParams and also # referenced from the control section. 'aggregationInfo': { 'days': 0, 'fields': [('consumption', 'sum')], 'hours': 1, 'microseconds': 0, 'milliseconds': 0, 'minutes': 0, 'months': 0, 'seconds': 0, 'weeks': 0, 'years': 0}, 'predictAheadTime': None, # Model parameter dictionary. 'modelParams': { # The type of inference that this model will perform 'inferenceType': 'TemporalMultiStep', 'sensorParams': { # Sensor diagnostic output verbosity control; # if > 0: sensor region will print out on screen what it's sensing # at each step 0: silent; >=1: some info; >=2: more info; # >=3: even more info (see compute() in py/regions/RecordSensor.py) 'verbosity' : 0, # Include the encoders we use 'encoders': { u'consumption': { 'fieldname': u'consumption', 'resolution': 0.88, 'seed': 1, 'name': u'consumption', 'type': '<API key>', }, 'timestamp_timeOfDay': { 'fieldname': u'timestamp', 'name': u'timestamp_timeOfDay', 'timeOfDay': (21, 1), 'type': 'DateEncoder'}, 'timestamp_weekend': { 'fieldname': u'timestamp', 'name': u'timestamp_weekend', 'type': 'DateEncoder', 'weekend': 21} }, # A dictionary specifying the period for <API key> # resets from a RecordSensor; # None = disable <API key> resets (also disabled if # all of the specified values evaluate to 0). # Valid keys is the desired combination of the following: # days, hours, minutes, seconds, milliseconds, microseconds, weeks # Example for 1.5 days: sensorAutoReset = dict(days=1,hours=12), # (value generated from SENSOR_AUTO_RESET) 'sensorAutoReset' : None, }, 'spEnable': True, 'spParams': { # SP diagnostic output verbosity control; # 0: silent; >=1: some info; >=2: more info; 'spVerbosity' : 0, # Spatial Pooler implementation selector. # Options: 'py', 'cpp' (speed optimized, new) 'spatialImp' : 'cpp', 'globalInhibition': 1, # Number of cell columns in the cortical region (same number for # SP and TP) # (see also tpNCellsPerCol) 'columnCount': 2048, 'inputWidth': 0, # SP inhibition control (absolute value); # Maximum number of active columns in the SP region's output (when # there are more, the weaker ones are suppressed) '<API key>': 40, 'seed': 1956, # potentialPct # What percent of the columns's receptive field is available # for potential synapses. 'potentialPct': 0.85, # The default connected threshold. Any synapse whose # permanence value is above the connected threshold is # a "connected synapse", meaning it can contribute to the # cell's firing. Typical value is 0.10. 'synPermConnected': 0.1, 'synPermActiveInc': 0.04, 'synPermInactiveDec': 0.005, }, # Controls whether TP is enabled or disabled; # TP is necessary for making temporal predictions, such as predicting # the next inputs. Without TP, the model is only capable of # reconstructing missing sensor inputs (via SP). 'tpEnable' : True, 'tpParams': { # TP diagnostic output verbosity control; # 0: silent; [1..6]: increasing levels of verbosity # (see verbosity in nupic/trunk/py/nupic/research/TP.py and TP10X*.py) 'verbosity': 0, # Number of cell columns in the cortical region (same number for # SP and TP) # (see also tpNCellsPerCol) 'columnCount': 2048, # The number of cells (i.e., states), allocated per column. 'cellsPerColumn': 32, 'inputWidth': 2048, 'seed': 1960, # Temporal Pooler implementation selector (see _getTPClass in # CLARegion.py). 'temporalImp': 'cpp', # New Synapse formation count # NOTE: If None, use <API key> # TODO: need better explanation 'newSynapseCount': 20, # Maximum number of synapses per segment # > 0 for fixed-size CLA # -1 for non-fixed-size CLA # TODO: for Ron: once the appropriate value is placed in TP # constructor, see if we should eliminate this parameter from # description.py. '<API key>': 32, # Maximum number of segments per cell # > 0 for fixed-size CLA # -1 for non-fixed-size CLA # TODO: for Ron: once the appropriate value is placed in TP # constructor, see if we should eliminate this parameter from # description.py. 'maxSegmentsPerCell': 128, # Initial Permanence # TODO: need better explanation 'initialPerm': 0.21, # Permanence Increment 'permanenceInc': 0.1, # Permanence Decrement # If set to None, will automatically default to tpPermanenceInc # value. 'permanenceDec' : 0.1, 'globalDecay': 0.0, 'maxAge': 0, # Minimum number of active synapses for a segment to be considered # during search for the best-matching segments. # None=use default # Replaces: tpMinThreshold 'minThreshold': 12, # Segment activation threshold. # A segment is active if it has >= <API key> # connected synapses that are active due to infActiveState # None=use default # Replaces: <API key> 'activationThreshold': 16, 'outputType': 'normal', # "Pay Attention Mode" length. This tells the TP how many new # elements to append to the end of a learned sequence at a time. # Smaller values are better for datasets with short sequences, # higher values are better for datasets with long sequences. 'pamLength': 1, }, 'clParams': { 'regionName' : 'CLAClassifierRegion', # Classifier diagnostic output verbosity control; # 0: silent; [1..6]: increasing levels of verbosity 'clVerbosity' : 0, # This controls how fast the classifier learns/forgets. Higher values # make it adapt faster and forget older patterns faster. 'alpha': 0.0001, # This is set after the call to <API key> and is # computed from the aggregationInfo and predictAheadTime. 'steps': '1,5', 'implementation': 'cpp', }, '<API key>': False, }, }
<?php return array ( 'AU' => 'ავსტრალია', 'AT' => 'ავსტრია', 'AF' => 'ავღანეთი', 'AZ' => 'აზერბაიჯანი', 'AX' => 'ალანდის კუნძულები', 'AL' => 'ალბანეთი', 'DZ' => 'ალჟირი', 'US' => 'ამერიკის შეერთებული შტატები', 'AS' => 'ამერიკული სამოა', 'AI' => 'ანგვილა', 'AO' => 'ანგოლა', 'AD' => 'ანდორა', 'AQ' => 'ანტარქტიკა', 'AG' => 'ანტიგუა და ბარბუდა', 'AE' => 'არაბეთის გაერთიანებული ემირატები', 'AR' => 'არგენტინა', 'AW' => 'არუბა', 'TL' => 'აღმოსავლეთი ტიმორი', 'NZ' => 'ახალი ზელანდია', 'NC' => 'ახალი კალედონია', 'BD' => 'ბანგლადეში', 'BB' => 'ბარბადოსი', 'BS' => 'ბაჰამის კუნძულები', 'BH' => 'ბაჰრეინი', 'BE' => 'ბელგია', 'BZ' => 'ბელიზი', 'BY' => 'ბელორუსია', 'BJ' => 'ბენინი', 'BM' => 'ბერმუდა', 'BO' => 'ბოლივია', 'BA' => 'ბოსნია და ჰერცეგოვინა', 'BW' => 'ბოტსვანა', 'BR' => 'ბრაზილია', 'IO' => 'ბრიტანული ტერიტორია ინდოეთის ოკეანეში', 'BN' => 'ბრუნეი', 'BV' => 'ბუვეს კუნძული', 'BG' => 'ბულგარეთი', 'BF' => 'ბურკინა-ფასო', 'BI' => 'ბურუნდი', 'BT' => 'ბუტანი', 'GA' => 'გაბონი', 'GY' => 'გაიანა', 'GM' => 'გამბია', 'GH' => 'განა', 'DE' => 'გერმანია', 'GP' => 'გვადელუპე', 'GT' => 'გვატემალა', 'GN' => 'გვინეა', 'GW' => 'გვინეა-ბისაუ', 'GI' => 'გიბრალტარი', 'GD' => 'გრენადა', 'GL' => 'გრენლანდია', 'GU' => 'გუამი', 'DK' => 'დანია', 'EH' => 'დასავლეთი საჰარა', 'QO' => 'დაშორებული ოკეანია', 'GB' => 'დიდი ბრიტანეთი', 'DM' => 'დომინიკა', 'DO' => 'დომინიკანის რესპუბლიკა', 'EG' => 'ეგვიპტე', 'EU' => 'ევროკავშირი', 'ET' => 'ეთიოპია', 'EC' => 'ეკვადორი', 'GQ' => 'ეკვატორული გვინეა', 'IQ' => 'ერაყი', 'ER' => 'ერიტრეა', 'ES' => 'ესპანეთი', 'EE' => 'ესტონეთი', 'WF' => 'ვალისი და ფუტუნა', 'VU' => 'ვანუატუ', 'VA' => 'ვატიკანი', 'VE' => 'ვენესუელა', 'VN' => 'ვიეტნამი', 'ZM' => 'ზამბია', 'ZW' => 'ზიმბაბვე', 'TR' => 'თურქეთი', 'TM' => 'თურქმენეთი', 'JM' => 'იამაიკა', 'JP' => 'იაპონია', 'YE' => 'იემენი', 'IN' => 'ინდოეთი', 'ID' => 'ინდონეზია', 'JO' => 'იორდანია', 'IR' => 'ირანი', 'IE' => 'ირლანდია', 'IS' => 'ისლანდია', 'IL' => 'ისრაელი', 'IT' => 'იტალია', 'CV' => 'კაბო-ვერდე', 'KY' => 'კაიმანის კუნძულები', 'KH' => 'კამბოჯა', 'CM' => 'კამერუნი', 'CA' => 'კანადა', 'QA' => 'კატარი', 'KE' => 'კენია', 'CY' => 'კვიპროსი', 'KI' => 'კირიბატი', 'CO' => 'კოლუმბია', 'KM' => 'კომორის კუნძულები', 'CG' => 'კონგო', 'CD' => 'კონგო - კინშასა', 'CR' => 'კოსტა-რიკა', 'CU' => 'კუბა', 'KW' => 'კუვეიტი', 'CK' => 'კუკის კუნძულები', 'LA' => 'ლაოსი', 'LV' => 'ლატვია', 'LS' => 'ლესოთო', 'LB' => 'ლიბანი', 'LR' => 'ლიბერია', 'LY' => 'ლიბია', 'LT' => 'ლიტვა', 'LI' => 'ლიხტენშტაინი', 'LU' => 'ლუქსემბურგი', 'MG' => 'მადაგასკარი', 'MU' => 'მავრიკია', 'MR' => 'მავრიტანია', 'MO' => 'მაკაო', 'MK' => 'მაკედონია', 'MW' => 'მალავი', 'MY' => 'მალაიზია', 'MV' => 'მალდივის კუნძულები', 'ML' => 'მალი', 'MT' => 'მალტა', 'IM' => 'მანის კუნძული', 'MA' => 'მაროკო', 'MQ' => 'მარტინიკი', 'MH' => 'მარშალის კუნძულები', 'MX' => 'მექსიკა', 'MM' => 'მიანმარი', 'FM' => 'მიკრონეზია', 'MZ' => 'მოზამბიკი', 'MD' => 'მოლდოვა', 'MC' => 'მონაკო', 'MS' => 'მონსერატი', 'ME' => 'მონტენეგრო', 'MN' => 'მონღოლეთი', 'NA' => 'ნამიბია', 'NR' => 'ნაურუ', 'NP' => 'ნეპალი', 'NE' => 'ნიგერი', 'NG' => 'ნიგერია', 'NL' => 'ნიდერლანდები', 'AN' => 'ნიდერლანდების ანტილები', 'NI' => 'ნიკარაგუა', 'NO' => 'ნორვეგია', 'NF' => 'ნორფოლკის კუნძული', 'OM' => 'ომანი', 'PK' => 'პაკისტანი', 'PW' => 'პალაუ', 'PS' => 'პალესტინის ტერიტორია', 'PA' => 'პანამა', 'PG' => 'პაპუა-ახალი გვინეა', 'PY' => 'პარაგვაი', 'PE' => 'პერუ', 'PL' => 'პოლონეთი', 'PT' => 'პორტუგალია', 'PR' => 'პუერტო რიკო', 'RE' => 'რეიუნიონი', 'RW' => 'რუანდა', 'RO' => 'რუმინეთი', 'RU' => 'რუსეთი', 'GR' => 'საბერძნეთი', 'SV' => 'სალვადორი', 'WS' => 'სამოა', 'ZA' => 'სამხრეთ აფრიკა', 'KR' => 'სამხრეთი კორეა', 'GS' => 'სამხრეთი ჯორჯია და სამხრეთ სენდვიჩის კუნძულები', 'SM' => 'სან-მარინო', 'ST' => 'საო-ტომე და პრინსიპი', 'SA' => 'საუდის არაბეთი', 'FR' => 'საფრანგეთი', 'GE' => 'საქართველო', 'SC' => 'სეიშელის კუნძულები', 'SN' => 'სენეგალი', 'VC' => 'სენტ-ვინსენტი და გრენადინები', 'KN' => 'სენტ-კიტსი და ნევისი', 'LC' => 'სენტ-ლუსია', 'PM' => 'სენტ-პიერი და მიქელონი', 'RS' => 'სერბია', 'CS' => 'სერბია და მონტენეგრო', 'SZ' => 'სვაზილენდი', 'SL' => 'სიერა-ლეონე', 'SG' => 'სინგაპური', 'SY' => 'სირია', 'SK' => 'სლოვაკეთი', 'SI' => 'სლოვენია', 'SB' => 'სოლომონის კუნძულები', 'SO' => 'სომალი', 'AM' => 'სომხეთი', 'CI' => 'სპილოს ძვლის სანაპირო', 'SD' => 'სუდანი', 'SR' => 'სურინამი', 'TW' => 'ტაივანი', 'TH' => 'ტაილანდი', 'TZ' => 'ტანზანია', 'TJ' => 'ტაჯიკეთი', 'TG' => 'ტოგო', 'TO' => 'ტონგა', 'TT' => 'ტრინიდადი და ტობაგო', 'TV' => 'ტუვალუ', 'TN' => 'ტუნისი', 'UG' => 'უგანდა', 'UZ' => 'უზბეკეთი', 'UA' => 'უკრაინა', 'HU' => 'უნგრეთი', 'UY' => 'ურუგვაი', 'FK' => 'ფალკლენდის კუნძულები', 'FO' => 'ფაროს კუნძულები', 'PH' => 'ფილიპინები', 'FI' => 'ფინეთი', 'FJ' => 'ფიჯი', 'PF' => 'ფრანგული პოლინეზია', 'TF' => 'ფრანგული სამხრეთის ტერიტორიები', 'KZ' => 'ყაზახეთი', 'KG' => 'ყირგიზეთი', 'UM' => 'შეერთებული შტატების მცირე დაშორებული კუნძულები', 'CH' => 'შვეიცარია', 'SE' => 'შვეცია', 'CX' => 'შობის კუნძული', 'LK' => 'შრი-ლანკა', 'TD' => 'ჩადი', 'CZ' => 'ჩეხეთის რესპუბლიკა', 'CL' => 'ჩილე', 'CN' => 'ჩინეთი', 'KP' => 'ჩრდილოეთი კორეა', 'CF' => 'ცენტრალური აფრიკის რესპუბლიკა', 'SH' => 'წმინდა ელენეს კუნძული', 'JE' => 'ჯერსი', 'DJ' => 'ჯიბუტი', 'HT' => 'ჰაიტი', 'HM' => 'ჰერდის კუნძული და მაკდონალდის კუნძულები', 'HK' => 'ჰონგ კონგი', 'HN' => 'ჰონდურასი', 'HR' => 'ჰორვატია', );
using System; using ZeroKLobby.MicroLobby; namespace ZeroKLobby.Lines { public class BroadcastLine: IChatLine { public DateTime Date { get; set; } public string Message { get; set; } public BroadcastLine(string message) { Message = message; Date = DateTime.Now; Text = TextColor.Text + "[" + TextColor.Date + Date.ToShortTimeString() + TextColor.Text + "] " + TextColor.Message + "Broadcast: " + Message; } public string Text { get; private set; } } }
#ifndef <API key> #define <API key> #include <boost/shared_ptr.hpp> #include <net/packet.hpp> namespace fluo { namespace net { namespace packets { class MultiPurposePacket : public Packet { public: MultiPurposePacket(uint8_t packetId); MultiPurposePacket(uint8_t packetId, boost::shared_ptr<Packet> subpacket); virtual bool write(int8_t* buf, unsigned int len, unsigned int& index) const; virtual bool read(const int8_t* buf, unsigned int len, unsigned int& index); virtual void onReceive(); protected: virtual boost::shared_ptr<Packet> getSubpacket(uint16_t subId) = 0; private: boost::shared_ptr<Packet> subpacket_; }; } } } #endif
// hashcmd.cpp /* * Defines a shell command for hashing a BSONElement value */ #include <string> #include <vector> #include "mongo/base/init.h" #include "mongo/base/status.h" #include "mongo/db/auth/action_set.h" #include "mongo/db/auth/action_type.h" #include "mongo/db/auth/<API key>.h" #include "mongo/db/auth/privilege.h" #include "mongo/db/commands.h" #include "mongo/db/hasher.h" #include "mongo/db/jsobj.h" namespace mongo { // Testing only, enabled via command-line. class CmdHashElt : public Command { public: CmdHashElt() : Command("_hashBSONElement") {}; virtual LockType locktype() const { return NONE; } virtual bool slaveOk() const { return true; } // No auth needed because it only works when enabled via command line. virtual bool requiresAuth() { return false; } virtual void <API key>(const std::string& dbname, const BSONObj& cmdObj, std::vector<Privilege>* out) {} virtual void help( stringstream& help ) const { help << "returns the hash of the first BSONElement val in a BSONObj"; } /* CmdObj has the form {"hash" : <thingToHash>} * or {"hash" : <thingToHash>, "seed" : <number> } * Result has the form * {"key" : <thingTohash>, "seed" : <int>, "out": NumberLong(<hash>)} * * Example use in the shell: *> db.runCommand({hash: "hashthis", seed: 1}) *> {"key" : "hashthis", *> "seed" : 1, *> "out" : NumberLong(6271151123721111923), *> "ok" : 1 } **/ bool run( const string& db, BSONObj& cmdObj, int options, string& errmsg, BSONObjBuilder& result, bool fromRepl = false ){ result.appendAs(cmdObj.firstElement(),"key"); int seed = 0; if (cmdObj.hasField("seed")){ if (! cmdObj["seed"].isNumber()) { errmsg += "seed must be a number"; return false; } seed = cmdObj["seed"].numberInt(); } result.append( "seed" , seed ); result.append( "out" , BSONElementHasher::hash64( cmdObj.firstElement() , seed ) ); return true; } }; MONGO_INITIALIZER(RegisterHashEltCmd)(InitializerContext* context) { if (Command::testCommandsEnabled) { // Leaked intentionally: a Command registers itself when constructed. new CmdHashElt(); } return Status::OK(); } }
/* Written by Paul Eggert, Derek Price, and Bruno Haible. */ #include <config.h> /* Specification. */ #include <unistd.h> #include <errno.h> #include <string.h> #if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__ # define WIN32_LEAN_AND_MEAN # include <windows.h> #else # if !HAVE_DECL_GETLOGIN extern char *getlogin (void); # endif #endif /* See unistd.in.h for documentation. */ int getlogin_r (char *name, size_t size) { #undef getlogin_r #if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__ /* Native Windows platform. */ DWORD sz; /* When size > 0x7fff, the doc says that GetUserName will fail. Actually, on Windows XP SP3, it succeeds. But let's be safe, for the sake of older Windows versions. */ if (size > 0x7fff) size = 0x7fff; sz = size; if (!GetUserName (name, &sz)) { if (GetLastError () == <API key>) /* In this case, the doc says that sz contains the required size, but actually, on Windows XP SP3, it contains 2 * the required size. */ return ERANGE; else return ENOENT; } return 0; #elif HAVE_GETLOGIN_R /* Platform with a getlogin_r() function. */ int ret = getlogin_r (name, size); if (ret == 0 && memchr (name, '\0', size) == NULL) /* name contains a truncated result. */ return ERANGE; return ret; #else /* Platform with a getlogin() function. */ char *n; size_t nlen; errno = 0; n = getlogin (); if (!n) /* ENOENT is a reasonable errno value if getlogin returns NULL. */ return (errno != 0 ? errno : ENOENT); nlen = strlen (n); if (size <= nlen) return ERANGE; memcpy (name, n, nlen + 1); return 0; #endif }
# -*- coding: utf-8 -*- # OpenERP, Open Source Management Solution # This program is free software: you can redistribute it and/or modify # published by the Free Software Foundation, either version 3 of the # This program is distributed in the hope that it will be useful, # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the from datetime import datetime, timedelta import time import logging import openerp from openerp import SUPERUSER_ID from openerp.osv import fields, osv from openerp.tools import <API key> _logger = logging.getLogger(__name__) DATE_RANGE_FUNCTION = { 'minutes': lambda interval: timedelta(minutes=interval), 'hour': lambda interval: timedelta(hours=interval), 'day': lambda interval: timedelta(days=interval), 'month': lambda interval: timedelta(months=interval), False: lambda interval: timedelta(0), } def get_datetime(date_str): '''Return a datetime from a date string or a datetime string''' # complete date time if date_str contains only a date if ' ' not in date_str: date_str = date_str + " 00:00:00" return datetime.strptime(date_str, <API key>) class base_action_rule(osv.osv): """ Base Action Rules """ _name = 'base.action.rule' _description = 'Action Rules' _order = 'sequence' _columns = { 'name': fields.char('Rule Name', required=True), 'model_id': fields.many2one('ir.model', 'Related Document Model', required=True, domain=[('osv_memory', '=', False)]), 'model': fields.related('model_id', 'model', type="char", string='Model'), 'create_date': fields.datetime('Create Date', readonly=1), 'active': fields.boolean('Active', help="When unchecked, the rule is hidden and will not be executed."), 'sequence': fields.integer('Sequence', help="Gives the sequence order when displaying a list of rules."), 'kind': fields.selection( [('on_create', 'On Creation'), ('on_write', 'On Update'), ('on_create_or_write', 'On Creation & Update'), ('on_time', 'Based on Timed Condition')], string='When to Run'), 'trg_date_id': fields.many2one('ir.model.fields', string='Trigger Date', help="When should the condition be triggered. If present, will be checked by the scheduler. If empty, will be checked at creation and update.", domain="[('model_id', '=', model_id), ('ttype', 'in', ('date', 'datetime'))]"), 'trg_date_range': fields.integer('Delay after trigger date', help="Delay after the trigger date." \ "You can put a negative number if you need a delay before the" \ "trigger date, like sending a reminder 15 minutes before a meeting."), 'trg_date_range_type': fields.selection([('minutes', 'Minutes'), ('hour', 'Hours'), ('day', 'Days'), ('month', 'Months')], 'Delay type'), '<API key>': fields.many2one( 'resource.calendar', 'Use Calendar', help='When calculating a day-based timed condition, it is possible to use a calendar to compute the date based on working days.', ondelete='set null', ), 'act_user_id': fields.many2one('res.users', 'Set Responsible'), 'act_followers': fields.many2many("res.partner", string="Add Followers"), 'server_action_ids': fields.many2many('ir.actions.server', string='Server Actions', domain="[('model_id', '=', model_id)]", help="Examples: email reminders, call object service, etc."), 'filter_pre_id': fields.many2one('ir.filters', string='Before Update Filter', ondelete='restrict', domain="[('model_id', '=', model_id.model)]", help="If present, this condition must be satisfied before the update of the record."), 'filter_id': fields.many2one('ir.filters', string='Filter', ondelete='restrict', domain="[('model_id', '=', model_id.model)]", help="If present, this condition must be satisfied before executing the action rule."), 'last_run': fields.datetime('Last Run', readonly=1, copy=False), } _defaults = { 'active': True, 'trg_date_range_type': 'day', } def onchange_kind(self, cr, uid, ids, kind, context=None): clear_fields = [] if kind in ['on_create', 'on_create_or_write']: clear_fields = ['filter_pre_id', 'trg_date_id', 'trg_date_range', 'trg_date_range_type'] elif kind in ['on_write', 'on_create_or_write']: clear_fields = ['trg_date_id', 'trg_date_range', 'trg_date_range_type'] elif kind == 'on_time': clear_fields = ['filter_pre_id'] return {'value': dict.fromkeys(clear_fields, False)} def _filter(self, cr, uid, action, action_filter, record_ids, context=None): """ filter the list record_ids that satisfy the action filter """ if record_ids and action_filter: assert action.model == action_filter.model_id, "Filter model different from action rule model" model = self.pool[action_filter.model_id] domain = [('id', 'in', record_ids)] + eval(action_filter.domain) ctx = dict(context or {}) ctx.update(eval(action_filter.context)) record_ids = model.search(cr, uid, domain, context=ctx) return record_ids def _process(self, cr, uid, action, record_ids, context=None): """ process the given action on the records """ model = self.pool[action.model_id.model] # modify records values = {} if 'date_action_last' in model._all_columns: values['date_action_last'] = time.strftime(<API key>) if action.act_user_id and 'user_id' in model._all_columns: values['user_id'] = action.act_user_id.id if values: model.write(cr, uid, record_ids, values, context=context) if action.act_followers and hasattr(model, 'message_subscribe'): follower_ids = map(int, action.act_followers) model.message_subscribe(cr, uid, record_ids, follower_ids, context=context) # execute server actions if action.server_action_ids: server_action_ids = map(int, action.server_action_ids) for record in model.browse(cr, uid, record_ids, context): action_server_obj = self.pool.get('ir.actions.server') ctx = dict(context, active_model=model._name, active_ids=[record.id], active_id=record.id) action_server_obj.run(cr, uid, server_action_ids, context=ctx) return True def _register_hook(self, cr, ids=None): """ Wrap the methods `create` and `write` of the models specified by the rules given by `ids` (or all existing rules if `ids` is `None`.) """ updated = False if ids is None: ids = self.search(cr, SUPERUSER_ID, []) for action_rule in self.browse(cr, SUPERUSER_ID, ids): model = action_rule.model_id.model model_obj = self.pool[model] if not hasattr(model_obj, 'base_action_ruled'): # monkey-patch methods create and write def create(self, cr, uid, vals, context=None, **kwargs): # avoid loops or cascading actions if context and context.get('action'): return create.origin(self, cr, uid, vals, context=context) # call original method with a modified context context = dict(context or {}, action=True) new_id = create.origin(self, cr, uid, vals, context=context, **kwargs) # as it is a new record, we do not consider the actions that have a prefilter action_model = self.pool.get('base.action.rule') action_dom = [('model', '=', self._name), ('kind', 'in', ['on_create', 'on_create_or_write'])] action_ids = action_model.search(cr, uid, action_dom, context=context) # check postconditions, and execute actions on the records that satisfy them for action in action_model.browse(cr, uid, action_ids, context=context): if action_model._filter(cr, uid, action, action.filter_id, [new_id], context=context): action_model._process(cr, uid, action, [new_id], context=context) return new_id def write(self, cr, uid, ids, vals, context=None, **kwargs): # avoid loops or cascading actions if context and context.get('action'): return write.origin(self, cr, uid, ids, vals, context=context) # modify context context = dict(context or {}, action=True) ids = [ids] if isinstance(ids, (int, long, str)) else ids # retrieve the action rules to possibly execute action_model = self.pool.get('base.action.rule') action_dom = [('model', '=', self._name), ('kind', 'in', ['on_write', 'on_create_or_write'])] action_ids = action_model.search(cr, uid, action_dom, context=context) actions = action_model.browse(cr, uid, action_ids, context=context) # check preconditions pre_ids = {} for action in actions: pre_ids[action] = action_model._filter(cr, uid, action, action.filter_pre_id, ids, context=context) # call original method write.origin(self, cr, uid, ids, vals, context=context, **kwargs) # check postconditions, and execute actions on the records that satisfy them for action in actions: post_ids = action_model._filter(cr, uid, action, action.filter_id, pre_ids[action], context=context) if post_ids: action_model._process(cr, uid, action, post_ids, context=context) return True model_obj._patch_method('create', create) model_obj._patch_method('write', write) model_obj.base_action_ruled = True updated = True return updated def create(self, cr, uid, vals, context=None): res_id = super(base_action_rule, self).create(cr, uid, vals, context=context) if self._register_hook(cr, [res_id]): openerp.modules.registry.RegistryManager.<API key>(cr.dbname) return res_id def write(self, cr, uid, ids, vals, context=None): if isinstance(ids, (int, long)): ids = [ids] super(base_action_rule, self).write(cr, uid, ids, vals, context=context) if self._register_hook(cr, ids): openerp.modules.registry.RegistryManager.<API key>(cr.dbname) return True def onchange_model_id(self, cr, uid, ids, model_id, context=None): data = {'model': False, 'filter_pre_id': False, 'filter_id': False} if model_id: model = self.pool.get('ir.model').browse(cr, uid, model_id, context=context) data.update({'model': model.model}) return {'value': data} def _check_delay(self, cr, uid, action, record, record_dt, context=None): if action.<API key> and action.trg_date_range_type == 'day': start_dt = get_datetime(record_dt) action_dt = self.pool['resource.calendar'].<API key>( cr, uid, action.<API key>.id, action.trg_date_range, day_date=start_dt, compute_leaves=True, context=context ) else: delay = DATE_RANGE_FUNCTION[action.trg_date_range_type](action.trg_date_range) action_dt = get_datetime(record_dt) + delay return action_dt def _check(self, cr, uid, automatic=False, use_new_cursor=False, context=None): """ This Function is called by scheduler. """ context = context or {} # retrieve all the action rules to run based on a timed condition action_dom = [('kind', '=', 'on_time')] action_ids = self.search(cr, uid, action_dom, context=context) for action in self.browse(cr, uid, action_ids, context=context): now = datetime.now() if action.last_run: last_run = get_datetime(action.last_run) else: last_run = datetime.utcfromtimestamp(0) # retrieve all the records that satisfy the action's condition model = self.pool[action.model_id.model] domain = [] ctx = dict(context) if action.filter_id: domain = eval(action.filter_id.domain) ctx.update(eval(action.filter_id.context)) if 'lang' not in ctx: # Filters might be language-sensitive, attempt to reuse creator lang # as we are usually running this as super-user in background [filter_meta] = action.filter_id.get_metadata() user_id = filter_meta['write_uid'] and filter_meta['write_uid'][0] or \ filter_meta['create_uid'][0] ctx['lang'] = self.pool['res.users'].browse(cr, uid, user_id).lang record_ids = model.search(cr, uid, domain, context=ctx) # determine when action should occur for the records date_field = action.trg_date_id.name if date_field == 'date_action_last' and 'create_date' in model._all_columns: get_record_dt = lambda record: record[date_field] or record.create_date else: get_record_dt = lambda record: record[date_field] # process action on the records that should be executed for record in model.browse(cr, uid, record_ids, context=context): record_dt = get_record_dt(record) if not record_dt: continue action_dt = self._check_delay(cr, uid, action, record, record_dt, context=context) if last_run <= action_dt < now: try: context = dict(context or {}, action=True) self._process(cr, uid, action, [record.id], context=context) except Exception: import traceback _logger.error(traceback.format_exc()) action.write({'last_run': now.strftime(<API key>)}) if automatic: # auto-commit for batch processing cr.commit()
#ifndef _LMAUDIT_ #define _LMAUDIT_ #ifdef __cplusplus extern "C" { #endif #ifndef _LMHLOGDEFINED_ #define _LMHLOGDEFINED_ typedef struct _HLOG { DWORD time; DWORD last_flags; DWORD offset; DWORD rec_offset; } HLOG,*PHLOG,*LPHLOG; #define LOGFLAGS_FORWARD 0 #define LOGFLAGS_BACKWARD 0x1 #define LOGFLAGS_SEEK 0x2 #endif DWORD WINAPI NetAuditClear(LPCWSTR server,LPCWSTR backupfile,LPCWSTR service); DWORD WINAPI NetAuditRead(LPCWSTR server,LPCWSTR service,LPHLOG auditloghandle,DWORD offset,LPDWORD reserved1,DWORD reserved2,DWORD offsetflag,LPBYTE *bufptr,DWORD prefmaxlen,LPDWORD bytesread,LPDWORD totalavailable); DWORD WINAPI NetAuditWrite(DWORD type,LPBYTE buf,DWORD numbytes,LPCWSTR service,LPBYTE reserved); typedef struct _AUDIT_ENTRY { DWORD ae_len; DWORD ae_reserved; DWORD ae_time; DWORD ae_type; DWORD ae_data_offset; DWORD ae_data_size; } AUDIT_ENTRY,*PAUDIT_ENTRY,*LPAUDIT_ENTRY; #define <API key> typedef struct _AE_SRVSTATUS { DWORD ae_sv_status; } AE_SRVSTATUS,*PAE_SRVSTATUS,*LPAE_SRVSTATUS; typedef struct _AE_SESSLOGON { DWORD ae_so_compname; DWORD ae_so_username; DWORD ae_so_privilege; } AE_SESSLOGON,*PAE_SESSLOGON,*LPAE_SESSLOGON; typedef struct _AE_SESSLOGOFF { DWORD ae_sf_compname; DWORD ae_sf_username; DWORD ae_sf_reason; } AE_SESSLOGOFF,*PAE_SESSLOGOFF,*LPAE_SESSLOGOFF; typedef struct _AE_SESSPWERR { DWORD ae_sp_compname; DWORD ae_sp_username; } AE_SESSPWERR,*PAE_SESSPWERR,*LPAE_SESSPWERR; typedef struct _AE_CONNSTART { DWORD ae_ct_compname; DWORD ae_ct_username; DWORD ae_ct_netname; DWORD ae_ct_connid; } AE_CONNSTART,*PAE_CONNSTART,*LPAE_CONNSTART; typedef struct _AE_CONNSTOP { DWORD ae_cp_compname; DWORD ae_cp_username; DWORD ae_cp_netname; DWORD ae_cp_connid; DWORD ae_cp_reason; } AE_CONNSTOP,*PAE_CONNSTOP,*LPAE_CONNSTOP; typedef struct _AE_CONNREJ { DWORD ae_cr_compname; DWORD ae_cr_username; DWORD ae_cr_netname; DWORD ae_cr_reason; } AE_CONNREJ,*PAE_CONNREJ,*LPAE_CONNREJ; typedef struct _AE_RESACCESS { DWORD ae_ra_compname; DWORD ae_ra_username; DWORD ae_ra_resname; DWORD ae_ra_operation; DWORD ae_ra_returncode; DWORD ae_ra_restype; DWORD ae_ra_fileid; } AE_RESACCESS,*PAE_RESACCESS,*LPAE_RESACCESS; typedef struct _AE_RESACCESSREJ { DWORD ae_rr_compname; DWORD ae_rr_username; DWORD ae_rr_resname; DWORD ae_rr_operation; } AE_RESACCESSREJ,*PAE_RESACCESSREJ,*LPAE_RESACCESSREJ; typedef struct _AE_CLOSEFILE { DWORD ae_cf_compname; DWORD ae_cf_username; DWORD ae_cf_resname; DWORD ae_cf_fileid; DWORD ae_cf_duration; DWORD ae_cf_reason; } AE_CLOSEFILE,*PAE_CLOSEFILE,*LPAE_CLOSEFILE; typedef struct _AE_SERVICESTAT { DWORD ae_ss_compname; DWORD ae_ss_username; DWORD ae_ss_svcname; DWORD ae_ss_status; DWORD ae_ss_code; DWORD ae_ss_text; DWORD ae_ss_returnval; } AE_SERVICESTAT,*PAE_SERVICESTAT,*LPAE_SERVICESTAT; typedef struct _AE_ACLMOD { DWORD ae_am_compname; DWORD ae_am_username; DWORD ae_am_resname; DWORD ae_am_action; DWORD ae_am_datalen; } AE_ACLMOD,*PAE_ACLMOD,*LPAE_ACLMOD; typedef struct _AE_UASMOD { DWORD ae_um_compname; DWORD ae_um_username; DWORD ae_um_resname; DWORD ae_um_rectype; DWORD ae_um_action; DWORD ae_um_datalen; } AE_UASMOD,*PAE_UASMOD,*LPAE_UASMOD; typedef struct _AE_NETLOGON { DWORD ae_no_compname; DWORD ae_no_username; DWORD ae_no_privilege; DWORD ae_no_authflags; } AE_NETLOGON,*PAE_NETLOGON,*LPAE_NETLOGON; typedef struct _AE_NETLOGOFF { DWORD ae_nf_compname; DWORD ae_nf_username; DWORD ae_nf_reserved1; DWORD ae_nf_reserved2; } AE_NETLOGOFF,*PAE_NETLOGOFF,*LPAE_NETLOGOFF; typedef struct _AE_ACCLIM { DWORD ae_al_compname; DWORD ae_al_username; DWORD ae_al_resname; DWORD ae_al_limit; } AE_ACCLIM,*PAE_ACCLIM,*LPAE_ACCLIM; #define ACTION_LOCKOUT 00 #define ACTION_ADMINUNLOCK 01 typedef struct _AE_LOCKOUT { DWORD ae_lk_compname; DWORD ae_lk_username; DWORD ae_lk_action; DWORD ae_lk_bad_pw_count; } AE_LOCKOUT,*PAE_LOCKOUT,*LPAE_LOCKOUT; typedef struct _AE_GENERIC { DWORD ae_ge_msgfile; DWORD ae_ge_msgnum; DWORD ae_ge_params; DWORD ae_ge_param1; DWORD ae_ge_param2; DWORD ae_ge_param3; DWORD ae_ge_param4; DWORD ae_ge_param5; DWORD ae_ge_param6; DWORD ae_ge_param7; DWORD ae_ge_param8; DWORD ae_ge_param9; } AE_GENERIC,*PAE_GENERIC,*LPAE_GENERIC; #define AE_SRVSTATUS 0 #define AE_SESSLOGON 1 #define AE_SESSLOGOFF 2 #define AE_SESSPWERR 3 #define AE_CONNSTART 4 #define AE_CONNSTOP 5 #define AE_CONNREJ 6 #define AE_RESACCESS 7 #define AE_RESACCESSREJ 8 #define AE_CLOSEFILE 9 #define AE_SERVICESTAT 11 #define AE_ACLMOD 12 #define AE_UASMOD 13 #define AE_NETLOGON 14 #define AE_NETLOGOFF 15 #define AE_NETLOGDENIED 16 #define AE_ACCLIMITEXCD 17 #define AE_RESACCESS2 18 #define AE_ACLMODFAIL 19 #define AE_LOCKOUT 20 #define AE_GENERIC_TYPE 21 #define AE_SRVSTART 0 #define AE_SRVPAUSED 1 #define AE_SRVCONT 2 #define AE_SRVSTOP 3 #define AE_GUEST 0 #define AE_USER 1 #define AE_ADMIN 2 #define AE_NORMAL 0 #define AE_USERLIMIT 0 #define AE_GENERAL 0 #define AE_ERROR 1 #define AE_SESSDIS 1 #define AE_BADPW 1 #define AE_AUTODIS 2 #define AE_UNSHARE 2 #define AE_ADMINPRIVREQD 2 #define AE_ADMINDIS 3 #define AE_NOACCESSPERM 3 #define AE_ACCRESTRICT 4 #define AE_NORMAL_CLOSE 0 #define AE_SES_CLOSE 1 #define AE_ADMIN_CLOSE 2 #define AE_LIM_UNKNOWN 0 #define AE_LIM_LOGONHOURS 1 #define AE_LIM_EXPIRED 2 #define AE_LIM_INVAL_WKSTA 3 #define AE_LIM_DISABLED 4 #define AE_LIM_DELETED 5 #define AE_MOD 0 #define AE_DELETE 1 #define AE_ADD 2 #define AE_UAS_USER 0 #define AE_UAS_GROUP 1 #define AE_UAS_MODALS 2 #define SVAUD_SERVICE 0x1 #define SVAUD_GOODSESSLOGON 0x6 #define SVAUD_BADSESSLOGON 0x18 #define SVAUD_SESSLOGON (SVAUD_GOODSESSLOGON | SVAUD_BADSESSLOGON) #define SVAUD_GOODNETLOGON 0x60 #define SVAUD_BADNETLOGON 0x180 #define SVAUD_NETLOGON (SVAUD_GOODNETLOGON | SVAUD_BADNETLOGON) #define SVAUD_LOGON (SVAUD_NETLOGON | SVAUD_SESSLOGON) #define SVAUD_GOODUSE 0x600 #define SVAUD_BADUSE 0x1800 #define SVAUD_USE (SVAUD_GOODUSE | SVAUD_BADUSE) #define SVAUD_USERLIST 0x2000 #define SVAUD_PERMISSIONS 0x4000 #define SVAUD_RESOURCE 0x8000 #define SVAUD_LOGONLIM 0x00010000 #define AA_AUDIT_ALL 0x0001 #define AA_A_OWNER 0x0004 #define AA_CLOSE 0x0008 #define AA_S_OPEN 0x0010 #define AA_S_WRITE 0x0020 #define AA_S_CREATE 0x0020 #define AA_S_DELETE 0x0040 #define AA_S_ACL 0x0080 #define AA_S_ALL (AA_S_OPEN | AA_S_WRITE | AA_S_DELETE | AA_S_ACL) #define AA_F_OPEN 0x0100 #define AA_F_WRITE 0x0200 #define AA_F_CREATE 0x0200 #define AA_F_DELETE 0x0400 #define AA_F_ACL 0x0800 #define AA_F_ALL (AA_F_OPEN | AA_F_WRITE | AA_F_DELETE | AA_F_ACL) #define AA_A_OPEN 0x1000 #define AA_A_WRITE 0x2000 #define AA_A_CREATE 0x2000 #define AA_A_DELETE 0x4000 #define AA_A_ACL 0x8000 #define AA_A_ALL (AA_F_OPEN | AA_F_WRITE | AA_F_DELETE | AA_F_ACL) #ifdef __cplusplus } #endif #endif
package Genome::VariantReporting::Report::VcfReport; use strict; use warnings; use Genome; use Genome::File::Vcf::Writer; use List::AllUtils qw(all); class Genome::VariantReporting::Report::VcfReport { is => 'Genome::VariantReporting::Framework::Component::Report::SingleFile', <API key> => [ vcf_file => { is_structural => 1, is => 'Genome::File::Vcf', }, header => { is_structural => 1, is => 'Genome::Vcf::Header', }, ], doc => 'Output variants in vcf format. Set soft filter result ALLFILTERSPASS based on chosen filters specified in the interpreters section.' }; sub name { return 'vcf'; } sub <API key> { return qw(vcf-entry); } sub allows_hard_filters { return 0; } sub file_name { return 'report.vcf'; } sub report { my $self = shift; my $interpretations = shift; my %<API key> = %{$interpretations->{'vcf-entry'}}; # All the vcf-entry interpretations are duplicates due to the caveat of # having to pass interpretations for each passed alt allele # We just grab the first one my $entry = (values %<API key>)[0]->{'vcf_entry'}; unless (defined($self->header)) { $self->process_header($entry->{'header'}); } $self->_process_entry($entry, $interpretations); } sub process_header { my $self = shift; my $header = shift; $self-><API key>($header); $self-><API key>($header); $self->header($header); $self->print_vcf_header(); } sub <API key> { my $self = shift; my $header = shift; for my $filter ($self->soft_filters) { $header->add_info_str(sprintf( "<ID=%s,Number=A,Type=Integer,Description=\"%s\">", $filter->vcf_id, $filter->vcf_description, )); } } sub <API key> { my $self = shift; my $header = shift; my $filters = join(", ", map { $_->vcf_id } $self->soft_filters); $header->add_info_str(sprintf( "<ID=%s,Number=A,Type=Integer,Description=\"%s\">", 'ALLFILTERSPASS', 'Flags whether the alternate allele passed all the soft filters: ' . $filters )); } sub print_vcf_header { my $self = shift; my $output_file_path = File::Spec->join($self-><API key>, $self->file_name); $self->vcf_file(Genome::File::Vcf::Writer->fhopen($self->_output_fh, $output_file_path, $self->header)); } sub _process_entry { my $self = shift; my $entry = shift; my $interpretations = shift; $self-><API key>($interpretations, $entry); $self-><API key>($interpretations, $entry); $self->vcf_file->write($entry); } sub <API key> { my $self = shift; my $interpretations = shift; my $entry = shift; for my $filter ($self->soft_filters) { my @results; for my $alt_allele (@{$entry->{alternate_alleles}}) { push @results, $interpretations->{$filter->name}->{$alt_allele}->{filter_status}; } $entry->set_info_field($filter->vcf_id, join(',', @results)); } } sub <API key> { my $self = shift; my $interpretations = shift; my $entry = shift; my @final_results; for my $alt_allele (@{$entry->{alternate_alleles}}) { push(@final_results, $self-><API key>($interpretations, $alt_allele)); } $entry->set_info_field('ALLFILTERSPASS', join(',', @final_results)); } sub <API key> { my $self = shift; my $interpretations = shift; my $allele = shift; return (all { $interpretations->{$_->name}->{$allele}->{filter_status} == 1} $self->soft_filters) || 0; } sub soft_filters { my $self = shift; return grep { $_->isa('Genome::VariantReporting::Framework::Component::Filter') } values %{$self->interpreters}; } 1;
package com.googlecode.lanterna.graphics; import com.googlecode.lanterna.SGR; import com.googlecode.lanterna.TextColor; import java.util.EnumSet; /** * ThemeStyle is the lowest entry in the theme hierarchy, containing the actual colors and SGRs to use. * @author Martin */ public interface ThemeStyle { TextColor getForeground(); TextColor getBackground(); EnumSet<SGR> getSGRs(); }
#include "webrtc/p2p/base/stun.h" #include <string.h> #include "webrtc/base/byteorder.h" #include "webrtc/base/common.h" #include "webrtc/base/crc32.h" #include "webrtc/base/logging.h" #include "webrtc/base/messagedigest.h" #include "webrtc/base/scoped_ptr.h" #include "webrtc/base/stringencode.h" using rtc::ByteBuffer; namespace cricket { const char <API key>[] = "Try Alternate Server"; const char <API key>[] = "Bad Request"; const char <API key>[] = "Unauthorized"; const char <API key>[] = "Forbidden"; const char <API key>[] = "Stale Credentials"; const char <API key>[] = "Allocation Mismatch"; const char <API key>[] = "Stale Nonce"; const char <API key>[] = "Wrong Credentials"; const char <API key>[] = "Unsupported Protocol"; const char <API key>[] = "Role Conflict"; const char <API key>[] = "Server Error"; const char <API key>[] = { '\x72', '\xC6', '\x4B', '\xC6' }; const char <API key>[] = "0000000000000000"; const uint32 <API key> = 0x5354554E; // StunMessage StunMessage::StunMessage() : type_(0), length_(0), transaction_id_(<API key>) { ASSERT(<API key>(transaction_id_)); attrs_ = new std::vector<StunAttribute*>(); } StunMessage::~StunMessage() { for (size_t i = 0; i < attrs_->size(); i++) delete (*attrs_)[i]; delete attrs_; } bool StunMessage::IsLegacy() const { if (transaction_id_.size() == <API key>) return true; ASSERT(transaction_id_.size() == <API key>); return false; } bool StunMessage::SetTransactionID(const std::string& str) { if (!<API key>(str)) { return false; } transaction_id_ = str; return true; } bool StunMessage::AddAttribute(StunAttribute* attr) { // Fail any attributes that aren't valid for this type of message. if (attr->value_type() != <API key>(attr->type())) { return false; } attrs_->push_back(attr); attr->SetOwner(this); size_t attr_length = attr->length(); if (attr_length % 4 != 0) { attr_length += (4 - (attr_length % 4)); } length_ += static_cast<uint16>(attr_length + 4); return true; } const <API key>* StunMessage::GetAddress(int type) const { switch (type) { case <API key>: { // Return XOR-MAPPED-ADDRESS when MAPPED-ADDRESS attribute is // missing. const StunAttribute* mapped_address = GetAttribute(<API key>); if (!mapped_address) mapped_address = GetAttribute(<API key>); return reinterpret_cast<const <API key>*>(mapped_address); } default: return static_cast<const <API key>*>(GetAttribute(type)); } } const StunUInt32Attribute* StunMessage::GetUInt32(int type) const { return static_cast<const StunUInt32Attribute*>(GetAttribute(type)); } const StunUInt64Attribute* StunMessage::GetUInt64(int type) const { return static_cast<const StunUInt64Attribute*>(GetAttribute(type)); } const <API key>* StunMessage::GetByteString(int type) const { return static_cast<const <API key>*>(GetAttribute(type)); } const <API key>* StunMessage::GetErrorCode() const { return static_cast<const <API key>*>( GetAttribute(<API key>)); } const <API key>* StunMessage::<API key>() const { return static_cast<const <API key>*>( GetAttribute(<API key>)); } // Verifies a STUN message has a valid MESSAGE-INTEGRITY attribute, using the // procedure outlined in RFC 5389, section 15.4. bool StunMessage::<API key>(const char* data, size_t size, const std::string& password) { // Verifying the size of the message. if ((size % 4) != 0) { return false; } // Getting the message length from the STUN header. uint16 msg_length = rtc::GetBE16(&data[2]); if (size != (msg_length + kStunHeaderSize)) { return false; } // Finding Message Integrity attribute in stun message. size_t current_pos = kStunHeaderSize; bool <API key> = false; while (current_pos < size) { uint16 attr_type, attr_length; // Getting attribute type and length. attr_type = rtc::GetBE16(&data[current_pos]); attr_length = rtc::GetBE16(&data[current_pos + sizeof(attr_type)]); // If M-I, sanity check it, and break out. if (attr_type == <API key>) { if (attr_length != <API key> || current_pos + attr_length > size) { return false; } <API key> = true; break; } // Otherwise, skip to the next attribute. current_pos += sizeof(attr_type) + sizeof(attr_length) + attr_length; if ((attr_length % 4) != 0) { current_pos += (4 - (attr_length % 4)); } } if (!<API key>) { return false; } // Getting length of the message to calculate Message Integrity. size_t mi_pos = current_pos; rtc::scoped_ptr<char[]> temp_data(new char[current_pos]); memcpy(temp_data.get(), data, current_pos); if (size > mi_pos + <API key> + <API key>) { // Stun message has other attributes after message integrity. // Adjust the length parameter in stun message to calculate HMAC. size_t extra_offset = size - (mi_pos + <API key> + <API key>); size_t new_adjusted_len = size - extra_offset - kStunHeaderSize; // Writing new length of the STUN message @ Message Length in temp buffer. // 0 1 2 3 // 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 // |0 0| STUN Message Type | Message Length | rtc::SetBE16(temp_data.get() + 2, static_cast<uint16>(new_adjusted_len)); } char hmac[<API key>]; size_t ret = rtc::ComputeHmac(rtc::DIGEST_SHA_1, password.c_str(), password.size(), temp_data.get(), mi_pos, hmac, sizeof(hmac)); ASSERT(ret == sizeof(hmac)); if (ret != sizeof(hmac)) return false; // Comparing the calculated HMAC with the one present in the message. return memcmp(data + current_pos + <API key>, hmac, sizeof(hmac)) == 0; } bool StunMessage::AddMessageIntegrity(const std::string& password) { return AddMessageIntegrity(password.c_str(), password.size()); } bool StunMessage::AddMessageIntegrity(const char* key, size_t keylen) { // Add the attribute with a dummy value. Since this is a known attribute, it // can't fail. <API key>* msg_integrity_attr = new <API key>(<API key>, std::string(<API key>, '0')); VERIFY(AddAttribute(msg_integrity_attr)); // Calculate the HMAC for the message. rtc::ByteBuffer buf; if (!Write(&buf)) return false; int msg_len_for_hmac = static_cast<int>( buf.Length() - <API key> - msg_integrity_attr->length()); char hmac[<API key>]; size_t ret = rtc::ComputeHmac(rtc::DIGEST_SHA_1, key, keylen, buf.Data(), msg_len_for_hmac, hmac, sizeof(hmac)); ASSERT(ret == sizeof(hmac)); if (ret != sizeof(hmac)) { LOG(LS_ERROR) << "HMAC computation failed. Message-Integrity " << "has dummy value."; return false; } // Insert correct HMAC into the attribute. msg_integrity_attr->CopyBytes(hmac, sizeof(hmac)); return true; } // Verifies a message is in fact a STUN message, by performing the checks // outlined in RFC 5389, section 7.3, including the FINGERPRINT check detailed // in section 15.5. bool StunMessage::ValidateFingerprint(const char* data, size_t size) { // Check the message length. size_t <API key> = <API key> + StunUInt32Attribute::SIZE; if (size % 4 != 0 || size < kStunHeaderSize + <API key>) return false; // Skip the rest if the magic cookie isn't present. const char* magic_cookie = data + <API key> - <API key>; if (rtc::GetBE32(magic_cookie) != kStunMagicCookie) return false; // Check the fingerprint type and length. const char* <API key> = data + size - <API key>; if (rtc::GetBE16(<API key>) != <API key> || rtc::GetBE16(<API key> + sizeof(uint16)) != StunUInt32Attribute::SIZE) return false; // Check the fingerprint value. uint32 fingerprint = rtc::GetBE32(<API key> + <API key>); return ((fingerprint ^ <API key>) == rtc::ComputeCrc32(data, size - <API key>)); } bool StunMessage::AddFingerprint() { // Add the attribute with a dummy value. Since this is a known attribute, // it can't fail. StunUInt32Attribute* fingerprint_attr = new StunUInt32Attribute(<API key>, 0); VERIFY(AddAttribute(fingerprint_attr)); // Calculate the CRC-32 for the message and insert it. rtc::ByteBuffer buf; if (!Write(&buf)) return false; int msg_len_for_crc32 = static_cast<int>( buf.Length() - <API key> - fingerprint_attr->length()); uint32 c = rtc::ComputeCrc32(buf.Data(), msg_len_for_crc32); // Insert the correct CRC-32, XORed with a constant, into the attribute. fingerprint_attr->SetValue(c ^ <API key>); return true; } bool StunMessage::Read(ByteBuffer* buf) { if (!buf->ReadUInt16(&type_)) return false; if (type_ & 0x8000) { // RTP and RTCP set the MSB of first byte, since first two bits are version, // and version is always 2 (10). If set, this is not a STUN packet. return false; } if (!buf->ReadUInt16(&length_)) return false; std::string magic_cookie; if (!buf->ReadString(&magic_cookie, <API key>)) return false; std::string transaction_id; if (!buf->ReadString(&transaction_id, <API key>)) return false; uint32 magic_cookie_int = *reinterpret_cast<const uint32*>(magic_cookie.data()); if (rtc::NetworkToHost32(magic_cookie_int) != kStunMagicCookie) { // If magic cookie is invalid it means that the peer implements // RFC3489 instead of RFC5389. transaction_id.insert(0, magic_cookie); } ASSERT(<API key>(transaction_id)); transaction_id_ = transaction_id; if (length_ != buf->Length()) return false; attrs_->resize(0); size_t rest = buf->Length() - length_; while (buf->Length() > rest) { uint16 attr_type, attr_length; if (!buf->ReadUInt16(&attr_type)) return false; if (!buf->ReadUInt16(&attr_length)) return false; StunAttribute* attr = CreateAttribute(attr_type, attr_length); if (!attr) { // Skip any unknown or malformed attributes. if ((attr_length % 4) != 0) { attr_length += (4 - (attr_length % 4)); } if (!buf->Consume(attr_length)) return false; } else { if (!attr->Read(buf)) return false; attrs_->push_back(attr); } } ASSERT(buf->Length() == rest); return true; } bool StunMessage::Write(ByteBuffer* buf) const { buf->WriteUInt16(type_); buf->WriteUInt16(length_); if (!IsLegacy()) buf->WriteUInt32(kStunMagicCookie); buf->WriteString(transaction_id_); for (size_t i = 0; i < attrs_->size(); ++i) { buf->WriteUInt16((*attrs_)[i]->type()); buf->WriteUInt16(static_cast<uint16>((*attrs_)[i]->length())); if (!(*attrs_)[i]->Write(buf)) return false; } return true; } <API key> StunMessage::<API key>(int type) const { switch (type) { case <API key>: return STUN_VALUE_ADDRESS; case STUN_ATTR_USERNAME: return <API key>; case <API key>: return <API key>; case <API key>: return <API key>; case <API key>: return <API key>; case STUN_ATTR_REALM: return <API key>; case STUN_ATTR_NONCE: return <API key>; case <API key>: return <API key>; case STUN_ATTR_SOFTWARE: return <API key>; case <API key>: return STUN_VALUE_ADDRESS; case <API key>: return STUN_VALUE_UINT32; case STUN_ATTR_ORIGIN: return <API key>; case <API key>: return STUN_VALUE_UINT32; default: return STUN_VALUE_UNKNOWN; } } StunAttribute* StunMessage::CreateAttribute(int type, size_t length) /*const*/ { <API key> value_type = <API key>(type); return StunAttribute::Create(value_type, type, static_cast<uint16>(length), this); } const StunAttribute* StunMessage::GetAttribute(int type) const { for (size_t i = 0; i < attrs_->size(); ++i) { if ((*attrs_)[i]->type() == type) return (*attrs_)[i]; } return NULL; } bool StunMessage::<API key>(const std::string& transaction_id) { return transaction_id.size() == <API key> || transaction_id.size() == <API key>; } // StunAttribute StunAttribute::StunAttribute(uint16 type, uint16 length) : type_(type), length_(length) { } void StunAttribute::ConsumePadding(rtc::ByteBuffer* buf) const { int remainder = length_ % 4; if (remainder > 0) { buf->Consume(4 - remainder); } } void StunAttribute::WritePadding(rtc::ByteBuffer* buf) const { int remainder = length_ % 4; if (remainder > 0) { char zeroes[4] = {0}; buf->WriteBytes(zeroes, 4 - remainder); } } StunAttribute* StunAttribute::Create(<API key> value_type, uint16 type, uint16 length, StunMessage* owner) { switch (value_type) { case STUN_VALUE_ADDRESS: return new <API key>(type, length); case <API key>: return new <API key>(type, length, owner); case STUN_VALUE_UINT32: return new StunUInt32Attribute(type); case STUN_VALUE_UINT64: return new StunUInt64Attribute(type); case <API key>: return new <API key>(type, length); case <API key>: return new <API key>(type, length); case <API key>: return new <API key>(type, length); default: return NULL; } } <API key>* StunAttribute::CreateAddress(uint16 type) { return new <API key>(type, 0); } <API key>* StunAttribute::CreateXorAddress(uint16 type) { return new <API key>(type, 0, NULL); } StunUInt64Attribute* StunAttribute::CreateUInt64(uint16 type) { return new StunUInt64Attribute(type); } StunUInt32Attribute* StunAttribute::CreateUInt32(uint16 type) { return new StunUInt32Attribute(type); } <API key>* StunAttribute::CreateByteString(uint16 type) { return new <API key>(type, 0); } <API key>* StunAttribute::CreateErrorCode() { return new <API key>( <API key>, <API key>::MIN_SIZE); } <API key>* StunAttribute::<API key>() { return new <API key>(<API key>, 0); } <API key>::<API key>(uint16 type, const rtc::SocketAddress& addr) : StunAttribute(type, 0) { SetAddress(addr); } <API key>::<API key>(uint16 type, uint16 length) : StunAttribute(type, length) { } bool <API key>::Read(ByteBuffer* buf) { uint8 dummy; if (!buf->ReadUInt8(&dummy)) return false; uint8 stun_family; if (!buf->ReadUInt8(&stun_family)) { return false; } uint16 port; if (!buf->ReadUInt16(&port)) return false; if (stun_family == STUN_ADDRESS_IPV4) { in_addr v4addr; if (length() != SIZE_IP4) { return false; } if (!buf->ReadBytes(reinterpret_cast<char*>(&v4addr), sizeof(v4addr))) { return false; } rtc::IPAddress ipaddr(v4addr); SetAddress(rtc::SocketAddress(ipaddr, port)); } else if (stun_family == STUN_ADDRESS_IPV6) { in6_addr v6addr; if (length() != SIZE_IP6) { return false; } if (!buf->ReadBytes(reinterpret_cast<char*>(&v6addr), sizeof(v6addr))) { return false; } rtc::IPAddress ipaddr(v6addr); SetAddress(rtc::SocketAddress(ipaddr, port)); } else { return false; } return true; } bool <API key>::Write(ByteBuffer* buf) const { StunAddressFamily address_family = family(); if (address_family == STUN_ADDRESS_UNDEF) { LOG(LS_ERROR) << "Error writing address attribute: unknown family."; return false; } buf->WriteUInt8(0); buf->WriteUInt8(address_family); buf->WriteUInt16(address_.port()); switch (address_.family()) { case AF_INET: { in_addr v4addr = address_.ipaddr().ipv4_address(); buf->WriteBytes(reinterpret_cast<char*>(&v4addr), sizeof(v4addr)); break; } case AF_INET6: { in6_addr v6addr = address_.ipaddr().ipv6_address(); buf->WriteBytes(reinterpret_cast<char*>(&v6addr), sizeof(v6addr)); break; } } return true; } <API key>::<API key>(uint16 type, const rtc::SocketAddress& addr) : <API key>(type, addr), owner_(NULL) { } <API key>::<API key>(uint16 type, uint16 length, StunMessage* owner) : <API key>(type, length), owner_(owner) {} rtc::IPAddress <API key>::GetXoredIP() const { if (owner_) { rtc::IPAddress ip = ipaddr(); switch (ip.family()) { case AF_INET: { in_addr v4addr = ip.ipv4_address(); v4addr.s_addr = (v4addr.s_addr ^ rtc::HostToNetwork32(kStunMagicCookie)); return rtc::IPAddress(v4addr); } case AF_INET6: { in6_addr v6addr = ip.ipv6_address(); const std::string& transaction_id = owner_->transaction_id(); if (transaction_id.length() == <API key>) { uint32 <API key>[3]; memcpy(&<API key>[0], transaction_id.c_str(), transaction_id.length()); uint32* ip_as_ints = reinterpret_cast<uint32*>(&v6addr.s6_addr); // Transaction ID is in network byte order, but magic cookie // is stored in host byte order. ip_as_ints[0] = (ip_as_ints[0] ^ rtc::HostToNetwork32(kStunMagicCookie)); ip_as_ints[1] = (ip_as_ints[1] ^ <API key>[0]); ip_as_ints[2] = (ip_as_ints[2] ^ <API key>[1]); ip_as_ints[3] = (ip_as_ints[3] ^ <API key>[2]); return rtc::IPAddress(v6addr); } break; } } } // Invalid ip family or transaction ID, or missing owner. // Return an AF_UNSPEC address. return rtc::IPAddress(); } bool <API key>::Read(ByteBuffer* buf) { if (!<API key>::Read(buf)) return false; uint16 xoredport = port() ^ (kStunMagicCookie >> 16); rtc::IPAddress xored_ip = GetXoredIP(); SetAddress(rtc::SocketAddress(xored_ip, xoredport)); return true; } bool <API key>::Write(ByteBuffer* buf) const { StunAddressFamily address_family = family(); if (address_family == STUN_ADDRESS_UNDEF) { LOG(LS_ERROR) << "Error writing xor-address attribute: unknown family."; return false; } rtc::IPAddress xored_ip = GetXoredIP(); if (xored_ip.family() == AF_UNSPEC) { return false; } buf->WriteUInt8(0); buf->WriteUInt8(family()); buf->WriteUInt16(port() ^ (kStunMagicCookie >> 16)); switch (xored_ip.family()) { case AF_INET: { in_addr v4addr = xored_ip.ipv4_address(); buf->WriteBytes(reinterpret_cast<const char*>(&v4addr), sizeof(v4addr)); break; } case AF_INET6: { in6_addr v6addr = xored_ip.ipv6_address(); buf->WriteBytes(reinterpret_cast<const char*>(&v6addr), sizeof(v6addr)); break; } } return true; } StunUInt32Attribute::StunUInt32Attribute(uint16 type, uint32 value) : StunAttribute(type, SIZE), bits_(value) { } StunUInt32Attribute::StunUInt32Attribute(uint16 type) : StunAttribute(type, SIZE), bits_(0) { } bool StunUInt32Attribute::GetBit(size_t index) const { ASSERT(index < 32); return static_cast<bool>((bits_ >> index) & 0x1); } void StunUInt32Attribute::SetBit(size_t index, bool value) { ASSERT(index < 32); bits_ &= ~(1 << index); bits_ |= value ? (1 << index) : 0; } bool StunUInt32Attribute::Read(ByteBuffer* buf) { if (length() != SIZE || !buf->ReadUInt32(&bits_)) return false; return true; } bool StunUInt32Attribute::Write(ByteBuffer* buf) const { buf->WriteUInt32(bits_); return true; } StunUInt64Attribute::StunUInt64Attribute(uint16 type, uint64 value) : StunAttribute(type, SIZE), bits_(value) { } StunUInt64Attribute::StunUInt64Attribute(uint16 type) : StunAttribute(type, SIZE), bits_(0) { } bool StunUInt64Attribute::Read(ByteBuffer* buf) { if (length() != SIZE || !buf->ReadUInt64(&bits_)) return false; return true; } bool StunUInt64Attribute::Write(ByteBuffer* buf) const { buf->WriteUInt64(bits_); return true; } <API key>::<API key>(uint16 type) : StunAttribute(type, 0), bytes_(NULL) { } <API key>::<API key>(uint16 type, const std::string& str) : StunAttribute(type, 0), bytes_(NULL) { CopyBytes(str.c_str(), str.size()); } <API key>::<API key>(uint16 type, const void* bytes, size_t length) : StunAttribute(type, 0), bytes_(NULL) { CopyBytes(bytes, length); } <API key>::<API key>(uint16 type, uint16 length) : StunAttribute(type, length), bytes_(NULL) { } <API key>::~<API key>() { delete [] bytes_; } void <API key>::CopyBytes(const char* bytes) { CopyBytes(bytes, strlen(bytes)); } void <API key>::CopyBytes(const void* bytes, size_t length) { char* new_bytes = new char[length]; memcpy(new_bytes, bytes, length); SetBytes(new_bytes, length); } uint8 <API key>::GetByte(size_t index) const { ASSERT(bytes_ != NULL); ASSERT(index < length()); return static_cast<uint8>(bytes_[index]); } void <API key>::SetByte(size_t index, uint8 value) { ASSERT(bytes_ != NULL); ASSERT(index < length()); bytes_[index] = value; } bool <API key>::Read(ByteBuffer* buf) { bytes_ = new char[length()]; if (!buf->ReadBytes(bytes_, length())) { return false; } ConsumePadding(buf); return true; } bool <API key>::Write(ByteBuffer* buf) const { buf->WriteBytes(bytes_, length()); WritePadding(buf); return true; } void <API key>::SetBytes(char* bytes, size_t length) { delete [] bytes_; bytes_ = bytes; SetLength(static_cast<uint16>(length)); } <API key>::<API key>(uint16 type, int code, const std::string& reason) : StunAttribute(type, 0) { SetCode(code); SetReason(reason); } <API key>::<API key>(uint16 type, uint16 length) : StunAttribute(type, length), class_(0), number_(0) { } <API key>::~<API key>() { } int <API key>::code() const { return class_ * 100 + number_; } void <API key>::SetCode(int code) { class_ = static_cast<uint8>(code / 100); number_ = static_cast<uint8>(code % 100); } void <API key>::SetReason(const std::string& reason) { SetLength(MIN_SIZE + static_cast<uint16>(reason.size())); reason_ = reason; } bool <API key>::Read(ByteBuffer* buf) { uint32 val; if (length() < MIN_SIZE || !buf->ReadUInt32(&val)) return false; if ((val >> 11) != 0) LOG(LS_ERROR) << "error-code bits not zero"; class_ = ((val >> 8) & 0x7); number_ = (val & 0xff); if (!buf->ReadString(&reason_, length() - 4)) return false; ConsumePadding(buf); return true; } bool <API key>::Write(ByteBuffer* buf) const { buf->WriteUInt32(class_ << 8 | number_); buf->WriteString(reason_); WritePadding(buf); return true; } <API key>::<API key>(uint16 type, uint16 length) : StunAttribute(type, length) { attr_types_ = new std::vector<uint16>(); } <API key>::~<API key>() { delete attr_types_; } size_t <API key>::Size() const { return attr_types_->size(); } uint16 <API key>::GetType(int index) const { return (*attr_types_)[index]; } void <API key>::SetType(int index, uint16 value) { (*attr_types_)[index] = value; } void <API key>::AddType(uint16 value) { attr_types_->push_back(value); SetLength(static_cast<uint16>(attr_types_->size() * 2)); } bool <API key>::Read(ByteBuffer* buf) { if (length() % 2) return false; for (size_t i = 0; i < length() / 2; i++) { uint16 attr; if (!buf->ReadUInt16(&attr)) return false; attr_types_->push_back(attr); } // Padding of these attributes is done in RFC 5389 style. This is // slightly different from RFC3489, but it shouldn't be important. // RFC3489 pads out to a 32 bit boundary by duplicating one of the // entries in the list (not necessarily the last one - it's unspecified). // RFC5389 pads on the end, and the bytes are always ignored. ConsumePadding(buf); return true; } bool <API key>::Write(ByteBuffer* buf) const { for (size_t i = 0; i < attr_types_->size(); ++i) { buf->WriteUInt16((*attr_types_)[i]); } WritePadding(buf); return true; } int <API key>(int req_type) { return IsStunRequestType(req_type) ? (req_type | 0x100) : -1; } int <API key>(int req_type) { return IsStunRequestType(req_type) ? (req_type | 0x110) : -1; } bool IsStunRequestType(int msg_type) { return ((msg_type & kStunTypeMask) == 0x000); } bool <API key>(int msg_type) { return ((msg_type & kStunTypeMask) == 0x010); } bool <API key>(int msg_type) { return ((msg_type & kStunTypeMask) == 0x100); } bool <API key>(int msg_type) { return ((msg_type & kStunTypeMask) == 0x110); } bool <API key>(const std::string& username, const std::string& realm, const std::string& password, std::string* hash) { // http://tools.ietf.org/html/rfc5389#section-15.4 // long-term credentials will be calculated using the key and key is // key = MD5(username ":" realm ":" SASLprep(password)) std::string input = username; input += ':'; input += realm; input += ':'; input += password; char digest[rtc::MessageDigest::kMaxSize]; size_t size = rtc::ComputeDigest( rtc::DIGEST_MD5, input.c_str(), input.size(), digest, sizeof(digest)); if (size == 0) { return false; } *hash = std::string(digest, size); return true; } } // namespace cricket
# DESCRIPTION Pinpoint APM Collector # TO_BUILD docker build -t pinpoint-collector . # TO_RUN docker run -d --net=host -e HBASE_HOST=<HOST_IP> -e HBASE_PORT=2181 -e COLLECTOR_TCP_PORT=9994 -e <API key>=9995 -e <API key>=9996 -p 9994:9994 -p 9995:9995/udp -p 9996:9996/udp --name=pinpoint-collector pinpoint-collector FROM tomcat:8-jre8 MAINTAINER John Crygier <john.crygier@ventivtech.com> ENV PINPOINT_VERSION 1.0.4 RUN curl -SL "https://github.com/naver/pinpoint/releases/download/$PINPOINT_VERSION/pinpoint-collector-$PINPOINT_VERSION.war" -o pinpoint-collector.war && \ rm -rf /usr/local/tomcat/webapps && \ mkdir -p /usr/local/tomcat/webapps && \ unzip pinpoint-collector.war -d /usr/local/tomcat/webapps/ROOT && \ rm -rf pinpoint-collector.war ADD start.sh /usr/local/tomcat/start.sh RUN chmod a+x /usr/local/tomcat/start.sh ADD hbase.properties /assets/hbase.properties ADD pinpoint-collector.properties /assets/pinpoint-collector.properties CMD ["/usr/local/tomcat/start.sh"]
/** * @fileOverview Defines the {@link CKEDITOR.editor} class, which represents an * editor instance. */ (function() { // The counter for automatic instance names. var nameCounter = 0; var getNewName = function() { var name = 'editor' + ( ++nameCounter ); return ( CKEDITOR.instances && CKEDITOR.instances[ name ] ) ? getNewName() : name; }; // // These function loads custom configuration files and cache the // CKEDITOR.editorConfig functions defined on them, so there is no need to // download them more than once for several instances. var loadConfigLoaded = {}; var loadConfig = function( editor ) { var customConfig = editor.config.customConfig; // Check if there is a custom config to load. if ( !customConfig ) return false; customConfig = CKEDITOR.getUrl( customConfig ); var loadedConfig = loadConfigLoaded[ customConfig ] || ( loadConfigLoaded[ customConfig ] = {} ); // If the custom config has already been downloaded, reuse it. if ( loadedConfig.fn ) { // Call the cached CKEDITOR.editorConfig defined in the custom // config file for the editor instance depending on it. loadedConfig.fn.call( editor, editor.config ); // If there is no other customConfig in the chain, fire the // "configLoaded" event. if ( CKEDITOR.getUrl( editor.config.customConfig ) == customConfig || !loadConfig( editor ) ) editor.fireOnce( 'customConfigLoaded' ); } else { // Load the custom configuration file. CKEDITOR.scriptLoader.load( customConfig, function() { // If the CKEDITOR.editorConfig function has been properly // defined in the custom configuration file, cache it. if ( CKEDITOR.editorConfig ) loadedConfig.fn = CKEDITOR.editorConfig; else loadedConfig.fn = function(){}; // Call the load config again. This time the custom // config is already cached and so it will get loaded. loadConfig( editor ); }); } return true; }; var initConfig = function( editor, instanceConfig ) { // Setup the lister for the "customConfigLoaded" event. editor.on( 'customConfigLoaded', function() { if ( instanceConfig ) { // Register the events that may have been set at the instance // configuration object. if ( instanceConfig.on ) { for ( var eventName in instanceConfig.on ) { editor.on( eventName, instanceConfig.on[ eventName ] ); } } // Overwrite the settings from the in-page config. CKEDITOR.tools.extend( editor.config, instanceConfig, true ); delete editor.config.on; } onConfigLoaded( editor ); }); // The instance config may override the customConfig setting to avoid // loading the default ~/config.js file. if ( instanceConfig && instanceConfig.customConfig != undefined ) editor.config.customConfig = instanceConfig.customConfig; // Load configs from the custom configuration files. if ( !loadConfig( editor ) ) editor.fireOnce( 'customConfigLoaded' ); }; // var onConfigLoaded = function( editor ) { // Set config related properties. var skin = editor.config.skin.split( ',' ), skinName = skin[ 0 ], skinPath = CKEDITOR.getUrl( skin[ 1 ] || ( '_source/' + // @Packager.RemoveLine 'skins/' + skinName + '/' ) ); /** * The name of the skin used by this editor instance. The skin name can * be set though the {@link CKEDITOR.config.skin} setting. * @name CKEDITOR.editor.prototype.skinName * @type String * @example * alert( editor.skinName ); // "kama" (e.g.) */ editor.skinName = skinName; editor.skinPath = skinPath; /** * The CSS class name used for skin identification purposes. * @name CKEDITOR.editor.prototype.skinClass * @type String * @example * alert( editor.skinClass ); // "cke_skin_kama" (e.g.) */ editor.skinClass = 'cke_skin_' + skinName; editor.tabIndex = editor.config.tabIndex || editor.element.getAttribute( 'tabindex' ) || 0; // Fire the "configLoaded" event. editor.fireOnce( 'configLoaded' ); // Load language file. loadSkin( editor ); }; var loadLang = function( editor ) { CKEDITOR.lang.load( editor.config.language, editor.config.defaultLanguage, function( languageCode, lang ) { /** * The code for the language resources that have been loaded * for the user internface elements of this editor instance. * @name CKEDITOR.editor.prototype.langCode * @type String * @example * alert( editor.langCode ); // "en" (e.g.) */ editor.langCode = languageCode; /** * An object holding all language strings used by the editor * interface. * @name CKEDITOR.editor.prototype.lang * @type CKEDITOR.lang * @example * alert( editor.lang.bold ); // "Negrito" (e.g. if language is Portuguese) */ // As we'll be adding plugin specific entries that could come // from different language code files, we need a copy of lang, // not a direct reference to it. editor.lang = CKEDITOR.tools.prototypedCopy( lang ); // We're not able to support RTL in Firefox 2 at this time. if ( CKEDITOR.env.gecko && CKEDITOR.env.version < 10900 && editor.lang.dir == 'rtl' ) editor.lang.dir = 'ltr'; var config = editor.config; config.<API key> == 'ui' && ( config.<API key> = editor.lang.dir ); loadPlugins( editor ); }); }; var loadPlugins = function( editor ) { var config = editor.config, plugins = config.plugins, extraPlugins = config.extraPlugins, removePlugins = config.removePlugins; if ( extraPlugins ) { // Remove them first to avoid duplications. var removeRegex = new RegExp( '(?:^|,)(?:' + extraPlugins.replace( /\s*,\s*/g, '|' ) + ')(?=,|$)' , 'g' ); plugins = plugins.replace( removeRegex, '' ); plugins += ',' + extraPlugins; } if ( removePlugins ) { removeRegex = new RegExp( '(?:^|,)(?:' + removePlugins.replace( /\s*,\s*/g, '|' ) + ')(?=,|$)' , 'g' ); plugins = plugins.replace( removeRegex, '' ); } // Load the Adobe AIR plugin conditionally. CKEDITOR.env.air && ( plugins += ',adobeair' ); // Load all plugins defined in the "plugins" setting. CKEDITOR.plugins.load( plugins.split( ',' ), function( plugins ) { // The list of plugins. var pluginsArray = []; // The language code to get loaded for each plugin. Null // entries will be appended for plugins with no language files. var languageCodes = []; // The list of URLs to language files. var languageFiles = []; editor.plugins = plugins; // Loop through all plugins, to build the list of language // files to get loaded. for ( var pluginName in plugins ) { var plugin = plugins[ pluginName ], pluginLangs = plugin.lang, pluginPath = CKEDITOR.plugins.getPath( pluginName ), lang = null; // Set the plugin path in the plugin. plugin.path = pluginPath; // If the plugin has "lang". if ( pluginLangs ) { // Resolve the plugin language. If the current language // is not available, get the first one (default one). lang = ( CKEDITOR.tools.indexOf( pluginLangs, editor.langCode ) >= 0 ? editor.langCode : pluginLangs[ 0 ] ); if ( !plugin.langEntries || !plugin.langEntries[ lang ] ) { // Put the language file URL into the list of files to // get downloaded. languageFiles.push( CKEDITOR.getUrl( pluginPath + 'lang/' + lang + '.js' ) ); } else { CKEDITOR.tools.extend( editor.lang, plugin.langEntries[ lang ] ); lang = null; } } // Save the language code, so we know later which // language has been resolved to this plugin. languageCodes.push( lang ); pluginsArray.push( plugin ); } // Load all plugin specific language files in a row. CKEDITOR.scriptLoader.load( languageFiles, function() { // Initialize all plugins that have the "beforeInit" and "init" methods defined. var methods = [ 'beforeInit', 'init', 'afterInit' ]; for ( var m = 0 ; m < methods.length ; m++ ) { for ( var i = 0 ; i < pluginsArray.length ; i++ ) { var plugin = pluginsArray[ i ]; // Uses the first loop to update the language entries also. if ( m === 0 && languageCodes[ i ] && plugin.lang ) CKEDITOR.tools.extend( editor.lang, plugin.langEntries[ languageCodes[ i ] ] ); // Call the plugin method (beforeInit and init). if ( plugin[ methods[ m ] ] ) plugin[ methods[ m ] ]( editor ); } } // Load the editor skin. editor.fire( 'pluginsLoaded' ); loadTheme( editor ); }); }); }; var loadSkin = function( editor ) { CKEDITOR.skins.load( editor, 'editor', function() { loadLang( editor ); }); }; var loadTheme = function( editor ) { var theme = editor.config.theme; CKEDITOR.themes.load( theme, function() { var editorTheme = editor.theme = CKEDITOR.themes.get( theme ); editorTheme.path = CKEDITOR.themes.getPath( theme ); editorTheme.build( editor ); if ( editor.config.autoUpdateElement ) attachToForm( editor ); }); }; var attachToForm = function( editor ) { var element = editor.element; // If are replacing a textarea, we must if ( editor.elementMode == CKEDITOR.<API key> && element.is( 'textarea' ) ) { var form = element.$.form && new CKEDITOR.dom.element( element.$.form ); if ( form ) { function onSubmit() { editor.updateElement(); } form.on( 'submit',onSubmit ); // Setup the submit function because it doesn't fire the // "submit" event. if ( !form.$.submit.nodeName && !form.$.submit.length ) { form.$.submit = CKEDITOR.tools.override( form.$.submit, function( originalSubmit ) { return function() { editor.updateElement(); // For IE, the DOM submit function is not a // function, so we need thid check. if ( originalSubmit.apply ) originalSubmit.apply( this, arguments ); else originalSubmit(); }; }); } // Remove 'submit' events registered on form element before destroying.(#3988) editor.on( 'destroy', function() { form.removeListener( 'submit', onSubmit ); } ); } } }; function updateCommandsMode() { var command, commands = this._.commands, mode = this.mode; for ( var name in commands ) { command = commands[ name ]; command[ command.startDisabled ? 'disable' : command.modes[ mode ] ? 'enable' : 'disable' ](); } } /** * Initializes the editor instance. This function is called by the editor * contructor (editor_basic.js). * @private */ CKEDITOR.editor.prototype._init = function() { // Get the properties that have been saved in the editor_base // implementation. var element = CKEDITOR.dom.element.get( this._.element ), instanceConfig = this._.instanceConfig; delete this._.element; delete this._.instanceConfig; this._.commands = {}; this._.styles = []; /** * The DOM element that has been replaced by this editor instance. This * element holds the editor data on load and post. * @name CKEDITOR.editor.prototype.element * @type CKEDITOR.dom.element * @example * var editor = CKEDITOR.instances.editor1; * alert( <b>editor.element</b>.getName() ); "textarea" */ this.element = element; /** * The editor instance name. It hay be the replaced element id, name or * a default name using a progressive counter (editor1, editor2, ...). * @name CKEDITOR.editor.prototype.name * @type String * @example * var editor = CKEDITOR.instances.editor1; * alert( <b>editor.name</b> ); "editor1" */ this.name = ( element && ( this.elementMode == CKEDITOR.<API key> ) && ( element.getId() || element.getNameAtt() ) ) || getNewName(); if ( this.name in CKEDITOR.instances ) throw '[CKEDITOR.editor] The instance "' + this.name + '" already exists.'; /** * A unique random string assigned to each editor instance in the page. * @name CKEDITOR.editor.prototype.id * @type String */ this.id = CKEDITOR.tools.getNextId(); /** * The configurations for this editor instance. It inherits all * settings defined in (@link CKEDITOR.config}, combined with settings * loaded from custom configuration files and those defined inline in * the page when creating the editor. * @name CKEDITOR.editor.prototype.config * @type Object * @example * var editor = CKEDITOR.instances.editor1; * alert( <b>editor.config.theme</b> ); "default" e.g. */ this.config = CKEDITOR.tools.prototypedCopy( CKEDITOR.config ); /** * Namespace containing UI features related to this editor instance. * @name CKEDITOR.editor.prototype.ui * @type CKEDITOR.ui * @example */ this.ui = new CKEDITOR.ui( this ); /** * Controls the focus state of this editor instance. This property * is rarely used for normal API operations. It is mainly * destinated to developer adding UI elements to the editor interface. * @name CKEDITOR.editor.prototype.focusManager * @type CKEDITOR.focusManager * @example */ this.focusManager = new CKEDITOR.focusManager( this ); CKEDITOR.fire( 'instanceCreated', null, this ); this.on( 'mode', updateCommandsMode, null, null, 1 ); initConfig( this, instanceConfig ); }; })(); CKEDITOR.tools.extend( CKEDITOR.editor.prototype, /** @lends CKEDITOR.editor.prototype */ { /** * Adds a command definition to the editor instance. Commands added with * this function can be later executed with {@link #execCommand}. * @param {String} commandName The indentifier name of the command. * @param {CKEDITOR.commandDefinition} commandDefinition The command definition. * @example * editorInstance.addCommand( 'sample', * { * exec : function( editor ) * { * alert( 'Executing a command for the editor name "' + editor.name + '"!' ); * } * }); */ addCommand : function( commandName, commandDefinition ) { return this._.commands[ commandName ] = new CKEDITOR.command( this, commandDefinition ); }, /** * Add a trunk of css text to the editor which will be applied to the wysiwyg editing document. * Note: This function should be called before editor is loaded to take effect. * @param css {String} CSS text. * @example * editorInstance.addCss( 'body { background-color: grey; }' ); */ addCss : function( css ) { this._.styles.push( css ); }, /** * Destroys the editor instance, releasing all resources used by it. * If the editor replaced an element, the element will be recovered. * @param {Boolean} [noUpdate] If the instance is replacing a DOM * element, this parameter indicates whether or not to update the * element with the instance contents. * @example * alert( CKEDITOR.instances.editor1 ); e.g "object" * <b>CKEDITOR.instances.editor1.destroy()</b>; * alert( CKEDITOR.instances.editor1 ); "undefined" */ destroy : function( noUpdate ) { if ( !noUpdate ) this.updateElement(); this.fire( 'destroy' ); this.theme && this.theme.destroy( this ); CKEDITOR.remove( this ); CKEDITOR.fire( 'instanceDestroyed', null, this ); }, /** * Executes a command. * @param {String} commandName The indentifier name of the command. * @param {Object} [data] Data to be passed to the command * @returns {Boolean} "true" if the command has been successfuly * executed, otherwise "false". * @example * editorInstance.execCommand( 'Bold' ); */ execCommand : function( commandName, data ) { var command = this.getCommand( commandName ); var eventData = { name: commandName, commandData: data, command: command }; if ( command && command.state != CKEDITOR.TRISTATE_DISABLED ) { if ( this.fire( 'beforeCommandExec', eventData ) !== true ) { eventData.returnValue = command.exec( eventData.commandData ); // Fire the 'afterCommandExec' immediately if command is synchronous. if ( !command.async && this.fire( 'afterCommandExec', eventData ) !== true ) return eventData.returnValue; } } // throw 'Unknown command name "' + commandName + '"'; return false; }, /** * Gets one of the registered commands. Note that, after registering a * command definition with addCommand, it is transformed internally * into an instance of {@link CKEDITOR.command}, which will be then * returned by this function. * @param {String} commandName The name of the command to be returned. * This is the same used to register the command with addCommand. * @returns {CKEDITOR.command} The command object identified by the * provided name. */ getCommand : function( commandName ) { return this._.commands[ commandName ]; }, /** * Gets the editor data. The data will be in raw format. It is the same * data that is posted by the editor. * @type String * @returns (String) The editor data. * @example * if ( CKEDITOR.instances.editor1.<b>getData()</b> == '' ) * alert( 'There is no data available' ); */ getData : function() { this.fire( 'beforeGetData' ); var eventData = this._.data; if ( typeof eventData != 'string' ) { var element = this.element; if ( element && this.elementMode == CKEDITOR.<API key> ) eventData = element.is( 'textarea' ) ? element.getValue() : element.getHtml(); else eventData = ''; } eventData = { dataValue : eventData }; // Fire "getData" so data manipulation may happen. this.fire( 'getData', eventData ); return eventData.dataValue; }, /** * Gets the "raw data" currently available in the editor. This is a * fast method which return the data as is, without processing, so it's * not recommended to use it on resulting pages. It can be used instead * combined with the {@link #loadSnapshot} so one can automatic save * the editor data from time to time while the user is using the * editor, to avoid data loss, without risking performance issues. * @example * alert( editor.getSnapshot() ); */ getSnapshot : function() { var data = this.fire( 'getSnapshot' ); if ( typeof data != 'string' ) { var element = this.element; if ( element && this.elementMode == CKEDITOR.<API key> ) data = element.is( 'textarea' ) ? element.getValue() : element.getHtml(); } return data; }, /** * Loads "raw data" in the editor. This data is loaded with processing * straight to the editing area. It should not be used as a way to load * any kind of data, but instead in combination with * {@link #getSnapshot} produced data. * @example * var data = editor.getSnapshot(); * editor.<b>loadSnapshot( data )</b>; */ loadSnapshot : function( snapshot ) { this.fire( 'loadSnapshot', snapshot ); }, /** * Sets the editor data. The data must be provided in raw format (HTML).<br /> * <br /> * Note that this menthod is asynchronous. The "callback" parameter must * be used if interaction with the editor is needed after setting the data. * @param {String} data HTML code to replace the curent content in the * editor. * @param {Function} callback Function to be called after the setData * is completed. *@param {Boolean} internal Whether suppress any event firing when copying data internally inside editor. * @example * CKEDITOR.instances.editor1.<b>setData</b>( '&lt;p&gt;This is the editor data.&lt;/p&gt;' ); * @example * CKEDITOR.instances.editor1.<b>setData</b>( '&lt;p&gt;Some other editor data.&lt;/p&gt;', function() * { * this.checkDirty(); // true * }); */ setData : function( data , callback, internal ) { if( callback ) { this.on( 'dataReady', function( evt ) { evt.removeListener(); callback.call( evt.editor ); } ); } // Fire "setData" so data manipulation may happen. var eventData = { dataValue : data }; !internal && this.fire( 'setData', eventData ); this._.data = eventData.dataValue; !internal && this.fire( 'afterSetData', eventData ); }, /** * Inserts HTML into the currently selected position in the editor. * @param {String} data HTML code to be inserted into the editor. * @example * CKEDITOR.instances.editor1.<b>insertHtml( '&lt;p&gt;This is a new paragraph.&lt;/p&gt;' )</b>; */ insertHtml : function( data ) { this.fire( 'insertHtml', data ); }, /** * Insert text content into the currently selected position in the * editor, in WYSIWYG mode, styles of the selected element will be applied to the inserted text, * spaces around the text will be leaving untouched. * <strong>Note:</strong> two subsequent line-breaks will introduce one paragraph, which element depends on {@link CKEDITOR.config.enterMode}; * A single line-break will be instead translated into one &lt;br /&gt;. * @since 3.5 * @param {String} text Text to be inserted into the editor. * @example * CKEDITOR.instances.editor1.<b>insertText( ' line1 \n\n line2' )</b>; */ insertText : function( text ) { this.fire( 'insertText', text ); }, /** * Inserts an element into the currently selected position in the * editor. * @param {CKEDITOR.dom.element} element The element to be inserted * into the editor. * @example * var element = CKEDITOR.dom.element.createFromHtml( '&lt;img src="hello.png" border="0" title="Hello" /&gt;' ); * CKEDITOR.instances.editor1.<b>insertElement( element )</b>; */ insertElement : function( element ) { this.fire( 'insertElement', element ); }, /** * Checks whether the current editor contents present changes when * compared to the contents loaded into the editor at startup, or to * the contents available in the editor when {@link #resetDirty} has * been called. * @returns {Boolean} "true" is the contents present changes. * @example * function beforeUnload( e ) * { * if ( CKEDITOR.instances.editor1.<b>checkDirty()</b> ) * return e.returnValue = "You'll loose the changes made in the editor."; * } * * if ( window.addEventListener ) * window.addEventListener( 'beforeunload', beforeUnload, false ); * else * window.attachEvent( 'onbeforeunload', beforeUnload ); */ checkDirty : function() { return ( this.mayBeDirty && this._.previousValue !== this.getSnapshot() ); }, /** * Resets the "dirty state" of the editor so subsequent calls to * {@link #checkDirty} will return "false" if the user will not make * further changes to the contents. * @example * alert( editor.checkDirty() ); // "true" (e.g.) * editor.<b>resetDirty()</b>; * alert( editor.checkDirty() ); // "false" */ resetDirty : function() { if ( this.mayBeDirty ) this._.previousValue = this.getSnapshot(); }, /** * Updates the &lt;textarea&gt; element that has been replaced by the editor with * the current data available in the editor. * @example * CKEDITOR.instances.editor1.updateElement(); * alert( document.getElementById( 'editor1' ).value ); // The current editor data. */ updateElement : function() { var element = this.element; if ( element && this.elementMode == CKEDITOR.<API key> ) { var data = this.getData(); if ( this.config.htmlEncodeOutput ) data = CKEDITOR.tools.htmlEncode( data ); if ( element.is( 'textarea' ) ) element.setValue( data ); else element.setHtml( data ); } } }); CKEDITOR.on( 'loaded', function() { // Run the full initialization for pending editors. var pending = CKEDITOR.editor._pending; if ( pending ) { delete CKEDITOR.editor._pending; for ( var i = 0 ; i < pending.length ; i++ ) pending[ i ]._init(); } }); /** * Whether escape HTML when editor update original input element. * @name CKEDITOR.config.htmlEncodeOutput * @since 3.1 * @type Boolean * @default false * @example * config.htmlEncodeOutput = true; */ /** * Fired when a CKEDITOR instance is created, but still before initializing it. * To interact with a fully initialized instance, use the * {@link CKEDITOR#instanceReady} event instead. * @name CKEDITOR#instanceCreated * @event * @param {CKEDITOR.editor} editor The editor instance that has been created. */ /** * Fired when a CKEDITOR instance is destroyed. * @name CKEDITOR#instanceDestroyed * @event * @param {CKEDITOR.editor} editor The editor instance that has been destroyed. */ /** * Fired when all plugins are loaded and initialized into the editor instance. * @name CKEDITOR.editor#pluginsLoaded * @event * @param {CKEDITOR.editor} editor This editor instance. */ /** * Fired before the command execution when {@link #execCommand} is called. * @name CKEDITOR.editor#beforeCommandExec * @event * @param {CKEDITOR.editor} editor This editor instance. * @param {String} data.name The command name. * @param {Object} data.commandData The data to be sent to the command. This * can be manipulated by the event listener. * @param {CKEDITOR.command} data.command The command itself. */ /** * Fired after the command execution when {@link #execCommand} is called. * @name CKEDITOR.editor#afterCommandExec * @event * @param {CKEDITOR.editor} editor This editor instance. * @param {String} data.name The command name. * @param {Object} data.commandData The data sent to the command. * @param {CKEDITOR.command} data.command The command itself. * @param {Object} data.returnValue The value returned by the command execution. */ /** * Fired every custom configuration file is loaded, before the final * configurations initialization.<br /> * <br /> * Custom configuration files can be loaded thorugh the * {@link CKEDITOR.config.customConfig} setting. Several files can be loading * by chaning this setting. * @name CKEDITOR.editor#customConfigLoaded * @event * @param {CKEDITOR.editor} editor This editor instance. * @example */ /** * Fired once the editor configuration is ready (loaded and processed). * @name CKEDITOR.editor#configLoaded * @event * @param {CKEDITOR.editor} editor This editor instance. * @example * if( editor.config.fullPage ) * alert( 'This is a full page editor' ); */ /** * Fired when this editor instance is destroyed. The editor at this * point isn't usable and this event should be used to perform clean up * in any plugin. * @name CKEDITOR.editor#destroy * @event */ /** * Internal event to get the current data. * @name CKEDITOR.editor#beforeGetData * @event */ /** * Internal event to perform the #getSnapshot call. * @name CKEDITOR.editor#getSnapshot * @event */ /** * Internal event to perform the #loadSnapshot call. * @name CKEDITOR.editor#loadSnapshot * @event */ /** * Event fired before the #getData call returns allowing additional manipulation. * @name CKEDITOR.editor#getData * @event * @param {CKEDITOR.editor} editor This editor instance. * @param {String} data.dataValue The data that will be returned. */ /** * Event fired before the #setData call is executed allowing additional manipulation. * @name CKEDITOR.editor#setData * @event * @param {CKEDITOR.editor} editor This editor instance. * @param {String} data.dataValue The data that will be used. */ /** * Event fired at the end of the #setData call is executed. Usually it's better to use the * {@link CKEDITOR.editor.prototype.dataReady} event. * @name CKEDITOR.editor#afterSetData * @event * @param {CKEDITOR.editor} editor This editor instance. * @param {String} data.dataValue The data that has been set. */ /** * Internal event to perform the #insertHtml call * @name CKEDITOR.editor#insertHtml * @event * @param {CKEDITOR.editor} editor This editor instance. * @param {String} data The HTML to insert. */ /** * Internal event to perform the #insertText call * @name CKEDITOR.editor#insertText * @event * @param {CKEDITOR.editor} editor This editor instance. * @param {String} text The text to insert. */ /** * Internal event to perform the #insertElement call * @name CKEDITOR.editor#insertElement * @event * @param {CKEDITOR.editor} editor This editor instance. * @param {Object} element The element to insert. */
#nullable disable using System.Collections.Generic; using Microsoft.VisualStudio.Text.Tagging; namespace Microsoft.CodeAnalysis.Editor.Tagging { internal abstract partial class <API key><TTag> { private class TagSpanComparer : IEqualityComparer<ITagSpan<TTag>> { private readonly IEqualityComparer<TTag> _tagComparer; public TagSpanComparer(IEqualityComparer<TTag> tagComparer) => _tagComparer = tagComparer; public bool Equals(ITagSpan<TTag> x, ITagSpan<TTag> y) { if (x.Span != y.Span) { return false; } return _tagComparer.Equals(x.Tag, y.Tag); } public int GetHashCode(ITagSpan<TTag> obj) => obj.Span.GetHashCode() ^ _tagComparer.GetHashCode(obj.Tag); } } }
#!/bin/sh if [ $# -gt 0 ] ; then files="$*" else files=$(find corelib include -name \*.c -o -name \*.h) fi # Run in parallel echo $files | xargs -P 8 -n 8 $PYTHON thirdparty/cpplint.py \ --root=include --filter=-build/include_order --verbose=2
package fake import ( v1 "github.com/openshift/origin/pkg/security/api/v1" api "k8s.io/kubernetes/pkg/api" unversioned "k8s.io/kubernetes/pkg/api/unversioned" core "k8s.io/kubernetes/pkg/client/testing/core" watch "k8s.io/kubernetes/pkg/watch" ) // <API key> implements <API key> type <API key> struct { Fake *FakeCore ns string } var <API key> = unversioned.<API key>{Group: "", Version: "v1", Resource: "<API key>"} func (c *<API key>) Create(<API key> *v1.<API key>) (result *v1.<API key>, err error) { obj, err := c.Fake. Invokes(core.NewCreateAction(<API key>, c.ns, <API key>), &v1.<API key>{}) if obj == nil { return nil, err } return obj.(*v1.<API key>), err } func (c *<API key>) Update(<API key> *v1.<API key>) (result *v1.<API key>, err error) { obj, err := c.Fake. Invokes(core.NewUpdateAction(<API key>, c.ns, <API key>), &v1.<API key>{}) if obj == nil { return nil, err } return obj.(*v1.<API key>), err } func (c *<API key>) UpdateStatus(<API key> *v1.<API key>) (*v1.<API key>, error) { obj, err := c.Fake. Invokes(core.<API key>(<API key>, "status", c.ns, <API key>), &v1.<API key>{}) if obj == nil { return nil, err } return obj.(*v1.<API key>), err } func (c *<API key>) Delete(name string, options *api.DeleteOptions) error { _, err := c.Fake. Invokes(core.NewDeleteAction(<API key>, c.ns, name), &v1.<API key>{}) return err } func (c *<API key>) DeleteCollection(options *api.DeleteOptions, listOptions api.ListOptions) error { action := core.<API key>(<API key>, c.ns, listOptions) _, err := c.Fake.Invokes(action, &v1.<API key>{}) return err } func (c *<API key>) Get(name string) (result *v1.<API key>, err error) { obj, err := c.Fake. Invokes(core.NewGetAction(<API key>, c.ns, name), &v1.<API key>{}) if obj == nil { return nil, err } return obj.(*v1.<API key>), err } func (c *<API key>) List(opts api.ListOptions) (result *v1.<API key>, err error) { obj, err := c.Fake. Invokes(core.NewListAction(<API key>, c.ns, opts), &v1.<API key>{}) if obj == nil { return nil, err } return obj.(*v1.<API key>), err } // Watch returns a watch.Interface that watches the requested <API key>. func (c *<API key>) Watch(opts api.ListOptions) (watch.Interface, error) { return c.Fake. InvokesWatch(core.NewWatchAction(<API key>, c.ns, opts)) }
package proto import ( "encoding" "fmt" "reflect" "time" "github.com/go-redis/redis/v8/internal/util" ) // Scan parses bytes `b` to `v` with appropriate type. func Scan(b []byte, v interface{}) error { switch v := v.(type) { case nil: return fmt.Errorf("redis: Scan(nil)") case *string: *v = util.BytesToString(b) return nil case *[]byte: *v = b return nil case *int: var err error *v, err = util.Atoi(b) return err case *int8: n, err := util.ParseInt(b, 10, 8) if err != nil { return err } *v = int8(n) return nil case *int16: n, err := util.ParseInt(b, 10, 16) if err != nil { return err } *v = int16(n) return nil case *int32: n, err := util.ParseInt(b, 10, 32) if err != nil { return err } *v = int32(n) return nil case *int64: n, err := util.ParseInt(b, 10, 64) if err != nil { return err } *v = n return nil case *uint: n, err := util.ParseUint(b, 10, 64) if err != nil { return err } *v = uint(n) return nil case *uint8: n, err := util.ParseUint(b, 10, 8) if err != nil { return err } *v = uint8(n) return nil case *uint16: n, err := util.ParseUint(b, 10, 16) if err != nil { return err } *v = uint16(n) return nil case *uint32: n, err := util.ParseUint(b, 10, 32) if err != nil { return err } *v = uint32(n) return nil case *uint64: n, err := util.ParseUint(b, 10, 64) if err != nil { return err } *v = n return nil case *float32: n, err := util.ParseFloat(b, 32) if err != nil { return err } *v = float32(n) return err case *float64: var err error *v, err = util.ParseFloat(b, 64) return err case *bool: *v = len(b) == 1 && b[0] == '1' return nil case *time.Time: var err error *v, err = time.Parse(time.RFC3339Nano, util.BytesToString(b)) return err case encoding.BinaryUnmarshaler: return v.UnmarshalBinary(b) default: return fmt.Errorf( "redis: can't unmarshal %T (consider implementing BinaryUnmarshaler)", v) } } func ScanSlice(data []string, slice interface{}) error { v := reflect.ValueOf(slice) if !v.IsValid() { return fmt.Errorf("redis: ScanSlice(nil)") } if v.Kind() != reflect.Ptr { return fmt.Errorf("redis: ScanSlice(non-pointer %T)", slice) } v = v.Elem() if v.Kind() != reflect.Slice { return fmt.Errorf("redis: ScanSlice(non-slice %T)", slice) } next := <API key>(v) for i, s := range data { elem := next() if err := Scan([]byte(s), elem.Addr().Interface()); err != nil { err = fmt.Errorf("redis: ScanSlice index=%d value=%q failed: %w", i, s, err) return err } } return nil } func <API key>(v reflect.Value) func() reflect.Value { elemType := v.Type().Elem() if elemType.Kind() == reflect.Ptr { elemType = elemType.Elem() return func() reflect.Value { if v.Len() < v.Cap() { v.Set(v.Slice(0, v.Len()+1)) elem := v.Index(v.Len() - 1) if elem.IsNil() { elem.Set(reflect.New(elemType)) } return elem.Elem() } elem := reflect.New(elemType) v.Set(reflect.Append(v, elem)) return elem.Elem() } } zero := reflect.Zero(elemType) return func() reflect.Value { if v.Len() < v.Cap() { v.Set(v.Slice(0, v.Len()+1)) return v.Index(v.Len() - 1) } v.Set(reflect.Append(v, zero)) return v.Index(v.Len() - 1) } }
// file at the top-level directory of this distribution and at // option. This file may not be copied, modified, or distributed // except according to those terms. fn main() { yield true; //~ ERROR yield syntax is experimental }
package com.intellij.internal.statistic.eventLog; import com.intellij.openapi.diagnostic.Logger; import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.Nullable; @ApiStatus.Internal public class <API key> implements <API key> { private final Logger myLogger; public <API key>(Logger logger) { myLogger = logger; } @Override public void info(String message) { myLogger.info(message); } @Override public void info(@Nullable String message, Throwable t) { myLogger.info(message, t); } @Override public void warn(String message) { myLogger.warn(message); } @Override public void warn(@Nullable String message, Throwable t) { myLogger.warn(message, t); } @Override public void trace(String message) { myLogger.trace(message); } @Override public boolean isTraceEnabled() { return myLogger.isTraceEnabled(); } }
#Azure Key Vault .NET Sample Code ##Contents 1. \samples - Key Vault sample applications 1. \scripts - PowerShell sample scripts for generating setting files ##Pre-requisites 1. Visual Studio 2015 or Visual Studio 2013 2. Azure SDK 2.8 3. Azure PowerShell version 1.0.0 or newer 4. NuGet version 2.7 or newer 5. nuget.org (https: 6. Active Azure subscription > Please read the [documentation about Key Vault][2] to familiarize yourself with the basic concepts of Key Vault before running this sample application. ##Common steps for both samples - Create a X509 Certificate To create a new X509 certificate, [makecert][8] or [openssl][3] can be used. For example, the following commands will generate a certificate file from a private key and a certificate signing request file: First, use [genrsa][4] command to generate a key then create a CSR using [req][5] command openssl genrsa -des3 -out keyvault.key 2048 openssl req -new -key keyvault.key -out keyvault.csr > Note: It is OK to choose the default answer for each question. Then, use [x509][6] command to self-sign the CSR and then convert it to a .PFX format with [pkcs12][7] command. openssl x509 -req -days 3000 -in keyvault.csr -signkey keyvault.key -out keyvault.cer openssl pkcs12 -export -out keyvault.pfx -inkey keyvault.key -in keyvault.cer Or use [makecert][8] from Developer Command Prompt for Visual Studio: makecert -sv keyvault.pvk -n "CN=Key Vault Credentials" keyvault.cer -pe -len 2048 -a sha256 Follow prompts pvk2pfx -pvk keyvault.pvk -spc keyvault.cer -pfx keyvault.pfx -pi <pvk-password> > Note: The keyvault.cer file is a required input to the <API key>.ps1 and <API key>.ps1 scripts* ##Sample #1 - HelloKeyVault A console application that walks through the key scenarios supported by Key Vault: 1. Create/Import a key (HSM or software keys) 2. Encrypt a secret using a content key 3. Wrap the content key using a Key Vault key 4. Unwrap the content key 5. Decrypt the secret 6. Set a secret Setup steps Update the app configuration settings in HelloKeyVault\App.config with your vault URL, application principal ID and secret. The information can optionally be generated using *scripts\<API key>.ps1*. To use the sample script, follow these steps: 1. Create a new X509 certificate or get an existing one to use as the Key Vault authentication certificate. See common steps above. - From explorer, right-click on the pfx file and click 'Install PFX' - Select 'Local Machine', accept all defaults. Confirm installed cert under Personal -> Certificates by running certlm.msc 2. Update the values of mandatory variables in <API key>.ps1 3. Launch the Microsoft Azure PowerShell window 4. Run the <API key>.ps1 script within the Microsoft Azure PowerShell window 5. Copy the results of the script into the HelloKeyVault\App.config file Running the sample application Once the setup steps are completed, build and run the HelloKeyVault.exe program. Observe the results printed out in the command line window. ##Sample #2 - <API key> This sample app demonstrates how an Azure web service can retrieve application secrets like passwords or storage account credentials from Key Vault at run-time. This eliminates the need to package secret values with the deployment package. This sample app also demonstrates managing a single bootstrapping X509 certificate that is used to authenticate with the Key Vault. The web app presents an online message board to users and uses an Azure storage account to persist the message board contents. The storage account access key is retrieved from the Key Vault service at run-time. The web app also demonstrates secret caching using a custom configuration manager. The configuration manager handles resolving a secret ID to a corresponding secret value and caching the secret value for a specified period of time. It also caches service configuration settings and refreshes them when updated. Setup steps 1. Create a new X509 certificate or get an existing one to use as the Key Vault authentication certificate. See common steps above. 2. Create a new Azure cloud service in the [Azure management portal][1]. Upload the PFX file for the certificate you just created into the certificate tab for the cloud service. For instructions see step 3 in [service certificate][9]. 3. Create a new Azure storage account in the [Azure management portal][1]. Remember the storage account name -- you'll need it as an input parameter for the <API key>.ps1 script. 4. Update the service configuration settings in <API key>.Cloud.cscfg by providing: - Key Vault authentication certificate thumbprint (you can find the thumbprint in the 'detailed' tab of the certificate). - Name of the storage account to store messages in. - URI to a Key Vault secret, containing a storage account key. - Duration that the secret should be cached (e.g. 00:20:00). - Client ID of the application that you have registered in Azure Active Directory with X509 certificate based credentials. For step 4 the service configuration settings can be generated using *scripts\<API key>.ps1*. To use the sample script, follow these steps: 1. Update the values of mandatory variables in <API key>.ps1 2. Launch the Microsoft Azure PowerShell window 3. Run the <API key>.ps1 script within the Microsoft Azure PowerShell window 4. Copy the results of the script into both CSCFG files in the project Running the sample application Once the setup steps are completed, build and publish the web service to the Azure cloud service created in the setup steps. Note that the service configuration file and the package used to publish contain no secret values. >NOTE: You can also deploy the application locally, to the Azure Compute Emulator. In this case, the Key Vault authentication certificate with the private key must be installed in the local machine's Personal certificate store. Navigate to the web service from your browser to save messages and read recent messages. Look at the traces displayed to see what's happening in the background. Updating the app's secret values To update the storage account key, stored in the Key Vault secret, follow these steps: 1. Go back to the Azure portal and regenerate the storage account keys. 2. The web service will now fail to load or save messages, as expected. 3. Read the trace messages to confirm this. 4. Use <API key> PowerShell cmdlet to update the secret stored in your vault. There are two ways to get the updated secret values into the app: - Wait for the cached secret value to reach its expiry time and get refreshed. When the cached secret reaches its expiry time the service will retrieve the updated secret. - Force the application to re-read the service configuration settings by making a change to the service configuration (e.g. .cscfg file) in the running service. This triggers an event within the service to flush the cached service configurations and secrets. Consequently, the new configuration settings get retrieved, secret IDs get resolved to their corresponding values and the new values get cached. After the cached secret value gets updated with the new storage account key, the message board application will start to work again. [1]: http://manage.windowsazure.com [2]: http://go.microsoft.com/fwlink/?LinkID=512410 [3]: http: [4]: https: [5]: https: [6]: https: [7]: https: [8]: http://msdn.microsoft.com/en-us/library/vstudio/bfsktky3(v=vs.100).aspx [9]: https://azure.microsoft.com/en-us/documentation/articles/<API key>/
package com.intellij.codeHighlighting; import org.jetbrains.annotations.NotNull; public interface <API key> { HighlightingPass @NotNull [] <API key>(); }
package com.intellij.terminal; import com.intellij.idea.ActionsBundle; import com.intellij.util.ui.UIUtil; import com.jediterm.terminal.ui.TerminalAction; import com.jediterm.terminal.ui.<API key>; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.awt.event.KeyEvent; import java.util.Collections; import java.util.Objects; public abstract class TerminalSplitAction extends TerminalAction { private final boolean myVertically; private TerminalSplitAction(@NotNull <API key> presentation, boolean vertically) { super(presentation); myVertically = vertically; } @Override public boolean actionPerformed(@Nullable KeyEvent e) { split(myVertically); return true; } public abstract void split(boolean vertically); public static TerminalSplitAction create(boolean vertically, @Nullable <API key> listener) { String text = vertically ? UIUtil.removeMnemonic(ActionsBundle.message("action.SplitVertically.text")) : UIUtil.removeMnemonic(ActionsBundle.message("action.SplitHorizontally.text")); return new TerminalSplitAction(new <API key>(text, Collections.emptyList()), vertically) { @Override public boolean isEnabled(@Nullable KeyEvent e) { return listener != null && listener.canSplit(vertically); } @Override public void split(boolean vertically) { Objects.requireNonNull(listener).split(vertically); } }; } }
#include <grpc/support/port_platform.h> #ifdef GPR_POSIX_SOCKET #include "src/core/iomgr/tcp_client.h" #include <errno.h> #include <netinet/in.h> #include <string.h> #include <unistd.h> #include "src/core/iomgr/alarm.h" #include "src/core/iomgr/iomgr_posix.h" #include "src/core/iomgr/pollset_posix.h" #include "src/core/iomgr/sockaddr_utils.h" #include "src/core/iomgr/socket_utils_posix.h" #include "src/core/iomgr/tcp_posix.h" #include <grpc/support/alloc.h> #include <grpc/support/log.h> #include <grpc/support/time.h> typedef struct { void (*cb)(void *arg, grpc_endpoint *tcp); void *cb_arg; gpr_mu mu; grpc_fd *fd; gpr_timespec deadline; grpc_alarm alarm; int refs; grpc_iomgr_closure write_closure; } async_connect; static int prepare_socket(const struct sockaddr *addr, int fd) { if (fd < 0) { goto error; } if (!<API key>(fd, 1) || !<API key>(fd, 1) || (addr->sa_family != AF_UNIX && !<API key>(fd, 1))) { gpr_log(GPR_ERROR, "Unable to configure socket %d: %s", fd, strerror(errno)); goto error; } return 1; error: if (fd >= 0) { close(fd); } return 0; } static void on_alarm(void *acp, int success) { int done; async_connect *ac = acp; gpr_mu_lock(&ac->mu); if (ac->fd != NULL && success) { grpc_fd_shutdown(ac->fd); } done = (--ac->refs == 0); gpr_mu_unlock(&ac->mu); if (done) { gpr_mu_destroy(&ac->mu); gpr_free(ac); } } static void on_writable(void *acp, int success) { async_connect *ac = acp; int so_error = 0; socklen_t so_error_size; int err; int fd = ac->fd->fd; int done; grpc_endpoint *ep = NULL; void (*cb)(void *arg, grpc_endpoint *tcp) = ac->cb; void *cb_arg = ac->cb_arg; grpc_alarm_cancel(&ac->alarm); if (success) { do { so_error_size = sizeof(so_error); err = getsockopt(fd, SOL_SOCKET, SO_ERROR, &so_error, &so_error_size); } while (err < 0 && errno == EINTR); if (err < 0) { gpr_log(GPR_ERROR, "getsockopt(ERROR): %s", strerror(errno)); goto finish; } else if (so_error != 0) { if (so_error == ENOBUFS) { /* We will get one of these errors if we have run out of memory in the kernel for the data structures allocated when you connect a socket. If this happens it is very likely that if we wait a little bit then try again the connection will work (since other programs or this program will close their network connections and free up memory). This does _not_ indicate that there is anything wrong with the server we are connecting to, this is a local problem. If you are looking at this code, then chances are that your program or another program on the same computer opened too many network connections. The "easy" fix: don't do that! */ gpr_log(GPR_ERROR, "kernel out of buffers"); <API key>(ac->fd, &ac->write_closure); return; } else { switch (so_error) { case ECONNREFUSED: gpr_log(GPR_ERROR, "socket error: connection refused"); break; default: gpr_log(GPR_ERROR, "socket error: %d", so_error); break; } goto finish; } } else { ep = grpc_tcp_create(ac->fd, <API key>); goto finish; } } else { gpr_log(GPR_ERROR, "on_writable failed during connect"); goto finish; } abort(); finish: gpr_mu_lock(&ac->mu); if (!ep) { grpc_fd_orphan(ac->fd, NULL, NULL); } done = (--ac->refs == 0); gpr_mu_unlock(&ac->mu); if (done) { gpr_mu_destroy(&ac->mu); gpr_free(ac); } cb(cb_arg, ep); } void <API key>(void (*cb)(void *arg, grpc_endpoint *ep), void *arg, const struct sockaddr *addr, int addr_len, gpr_timespec deadline) { int fd; grpc_dualstack_mode dsmode; int err; async_connect *ac; struct sockaddr_in6 addr6_v4mapped; struct sockaddr_in addr4_copy; /* Use dualstack sockets where available. */ if (<API key>(addr, &addr6_v4mapped)) { addr = (const struct sockaddr *)&addr6_v4mapped; addr_len = sizeof(addr6_v4mapped); } fd = <API key>(addr, SOCK_STREAM, 0, &dsmode); if (fd < 0) { gpr_log(GPR_ERROR, "Unable to create socket: %s", strerror(errno)); } if (dsmode == GRPC_DSMODE_IPV4) { /* If we got an AF_INET socket, map the address back to IPv4. */ GPR_ASSERT(<API key>(addr, &addr4_copy)); addr = (struct sockaddr *)&addr4_copy; addr_len = sizeof(addr4_copy); } if (!prepare_socket(addr, fd)) { cb(arg, NULL); return; } do { err = connect(fd, addr, addr_len); } while (err < 0 && errno == EINTR); if (err >= 0) { gpr_log(GPR_DEBUG, "instant connect"); cb(arg, grpc_tcp_create(grpc_fd_create(fd), <API key>)); return; } if (errno != EWOULDBLOCK && errno != EINPROGRESS) { gpr_log(GPR_ERROR, "connect error: %s", strerror(errno)); close(fd); cb(arg, NULL); return; } ac = gpr_malloc(sizeof(async_connect)); ac->cb = cb; ac->cb_arg = arg; ac->fd = grpc_fd_create(fd); gpr_mu_init(&ac->mu); ac->refs = 2; ac->write_closure.cb = on_writable; ac->write_closure.cb_arg = ac; grpc_alarm_init(&ac->alarm, deadline, on_alarm, ac, gpr_now()); <API key>(ac->fd, &ac->write_closure); } #endif
<!DOCTYPE HTML PUBLIC "- <!--NewPage <HTML> <HEAD> <!-- Generated by javadoc (build 1.6.0_18) on Tue Jan 04 14:56:04 CST 2011 --> <META http-equiv="Content-Type" content="text/html; charset=utf-8"> <TITLE> <API key> (xmemcached 1.3.0 API) </TITLE> <META NAME="date" CONTENT="2011-01-04"> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style"> <SCRIPT type="text/javascript"> function windowTitle() { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="<API key> (xmemcached 1.3.0 API)"; } } </SCRIPT> <NOSCRIPT> </NOSCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <HR> <A NAME="navbar_top"></A> <A HREF="#skip-navbar_top" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_top_firstrow"></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="class-use/<API key>.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="../../../../net/rubyeye/xmemcached/buffer/IoBuffer.html" title="interface in net.rubyeye.xmemcached.buffer"><B>PREV CLASS</B></A>&nbsp; &nbsp;<A HREF="../../../../net/rubyeye/xmemcached/buffer/SimpleIoBuffer.html" title="class in net.rubyeye.xmemcached.buffer"><B>NEXT CLASS</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../index.html?net/rubyeye/xmemcached/buffer/<API key>.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="<API key>.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <! if(window==top) { document.writeln('<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } </SCRIPT> <NOSCRIPT> <A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> <TR> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> SUMMARY:&nbsp;NESTED&nbsp;|&nbsp;<A HREF="#field_summary">FIELD</A>&nbsp;|&nbsp;<A HREF="#constructor_summary">CONSTR</A>&nbsp;|&nbsp;<A HREF="#method_summary">METHOD</A></FONT></TD> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> DETAIL:&nbsp;<A HREF="#field_detail">FIELD</A>&nbsp;|&nbsp;<A HREF="#constructor_detail">CONSTR</A>&nbsp;|&nbsp;<A HREF="#method_detail">METHOD</A></FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_top"></A> <HR> <H2> <FONT SIZE="-1"> net.rubyeye.xmemcached.buffer</FONT> <BR> Class <API key></H2> <PRE> java.lang.Object <IMG SRC="../../../../resources/inherit.gif" ALT="extended by "><B>net.rubyeye.xmemcached.buffer.<API key></B> </PRE> <DL> <DT><B>All Implemented Interfaces:</B> <DD><A HREF="../../../../net/rubyeye/xmemcached/buffer/BufferAllocator.html" title="interface in net.rubyeye.xmemcached.buffer">BufferAllocator</A></DD> </DL> <HR> <B>Deprecated.</B> <P> <DL> <DT><PRE><FONT SIZE="-1">@Deprecated </FONT>public class <B><API key></B><DT>extends java.lang.Object<DT>implements <A HREF="../../../../net/rubyeye/xmemcached/buffer/BufferAllocator.html" title="interface in net.rubyeye.xmemcached.buffer">BufferAllocator</A></DL> </PRE> <P> Simple IoBuffer allocator,allcate a new heap ByteBuffer each time. <P> <P> <DL> <DT><B>Author:</B></DT> <DD>dennis</DD> </DL> <HR> <P> <A NAME="field_summary"></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> <B>Field Summary</B></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>static&nbsp;<A HREF="../../../../net/rubyeye/xmemcached/buffer/IoBuffer.html" title="interface in net.rubyeye.xmemcached.buffer">IoBuffer</A></CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../net/rubyeye/xmemcached/buffer/<API key>.html#EMPTY_IOBUFFER">EMPTY_IOBUFFER</A></B></CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<B>Deprecated.</B>&nbsp;&nbsp;</TD> </TR> </TABLE> &nbsp; <A NAME="constructor_summary"></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> <B>Constructor Summary</B></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><CODE><B><A HREF="../../../../net/rubyeye/xmemcached/buffer/<API key>.html#<API key>()"><API key></A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<B>Deprecated.</B>&nbsp;&nbsp;</TD> </TR> </TABLE> &nbsp; <A NAME="method_summary"></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> <B>Method Summary</B></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;<A HREF="../../../../net/rubyeye/xmemcached/buffer/IoBuffer.html" title="interface in net.rubyeye.xmemcached.buffer">IoBuffer</A></CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../net/rubyeye/xmemcached/buffer/<API key>.html#allocate(int)">allocate</A></B>(int&nbsp;capacity)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<B>Deprecated.</B>&nbsp;&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;void</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../net/rubyeye/xmemcached/buffer/<API key>.html#dispose()">dispose</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<B>Deprecated.</B>&nbsp;&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>static&nbsp;<A HREF="../../../../net/rubyeye/xmemcached/buffer/BufferAllocator.html" title="interface in net.rubyeye.xmemcached.buffer">BufferAllocator</A></CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../net/rubyeye/xmemcached/buffer/<API key>.html#newInstance()">newInstance</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<B>Deprecated.</B>&nbsp;&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;<A HREF="../../../../net/rubyeye/xmemcached/buffer/IoBuffer.html" title="interface in net.rubyeye.xmemcached.buffer">IoBuffer</A></CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../net/rubyeye/xmemcached/buffer/<API key>.html#wrap(java.nio.ByteBuffer)">wrap</A></B>(java.nio.ByteBuffer&nbsp;byteBuffer)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<B>Deprecated.</B>&nbsp;&nbsp;</TD> </TR> </TABLE> &nbsp;<A NAME="<API key>.lang.Object"></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#EEEEFF" CLASS="<API key>"> <TH ALIGN="left"><B>Methods inherited from class java.lang.Object</B></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><CODE>clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</CODE></TD> </TR> </TABLE> &nbsp; <P> <A NAME="field_detail"></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2"> <B>Field Detail</B></FONT></TH> </TR> </TABLE> <A NAME="EMPTY_IOBUFFER"></A><H3> EMPTY_IOBUFFER</H3> <PRE> public static final <A HREF="../../../../net/rubyeye/xmemcached/buffer/IoBuffer.html" title="interface in net.rubyeye.xmemcached.buffer">IoBuffer</A> <B>EMPTY_IOBUFFER</B></PRE> <DL> <DD><B>Deprecated.</B>&nbsp;<DL> </DL> </DL> <A NAME="constructor_detail"></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2"> <B>Constructor Detail</B></FONT></TH> </TR> </TABLE> <A NAME="<API key>()"></A><H3> <API key></H3> <PRE> public <B><API key></B>()</PRE> <DL> <DD><B>Deprecated.</B>&nbsp;</DL> <A NAME="method_detail"></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2"> <B>Method Detail</B></FONT></TH> </TR> </TABLE> <A NAME="allocate(int)"></A><H3> allocate</H3> <PRE> public final <A HREF="../../../../net/rubyeye/xmemcached/buffer/IoBuffer.html" title="interface in net.rubyeye.xmemcached.buffer">IoBuffer</A> <B>allocate</B>(int&nbsp;capacity)</PRE> <DL> <DD><B>Deprecated.</B>&nbsp;<DD><DL> <DT><B>Specified by:</B><DD><CODE><A HREF="../../../../net/rubyeye/xmemcached/buffer/BufferAllocator.html#allocate(int)">allocate</A></CODE> in interface <CODE><A HREF="../../../../net/rubyeye/xmemcached/buffer/BufferAllocator.html" title="interface in net.rubyeye.xmemcached.buffer">BufferAllocator</A></CODE></DL> </DD> <DD><DL> </DL> </DD> </DL> <HR> <A NAME="dispose()"></A><H3> dispose</H3> <PRE> public final void <B>dispose</B>()</PRE> <DL> <DD><B>Deprecated.</B>&nbsp;<DD><DL> <DT><B>Specified by:</B><DD><CODE><A HREF="../../../../net/rubyeye/xmemcached/buffer/BufferAllocator.html#dispose()">dispose</A></CODE> in interface <CODE><A HREF="../../../../net/rubyeye/xmemcached/buffer/BufferAllocator.html" title="interface in net.rubyeye.xmemcached.buffer">BufferAllocator</A></CODE></DL> </DD> <DD><DL> </DL> </DD> </DL> <HR> <A NAME="newInstance()"></A><H3> newInstance</H3> <PRE> public static final <A HREF="../../../../net/rubyeye/xmemcached/buffer/BufferAllocator.html" title="interface in net.rubyeye.xmemcached.buffer">BufferAllocator</A> <B>newInstance</B>()</PRE> <DL> <DD><B>Deprecated.</B>&nbsp;<DD><DL> </DL> </DD> <DD><DL> </DL> </DD> </DL> <HR> <A NAME="wrap(java.nio.ByteBuffer)"></A><H3> wrap</H3> <PRE> public final <A HREF="../../../../net/rubyeye/xmemcached/buffer/IoBuffer.html" title="interface in net.rubyeye.xmemcached.buffer">IoBuffer</A> <B>wrap</B>(java.nio.ByteBuffer&nbsp;byteBuffer)</PRE> <DL> <DD><B>Deprecated.</B>&nbsp;<DD><DL> <DT><B>Specified by:</B><DD><CODE><A HREF="../../../../net/rubyeye/xmemcached/buffer/BufferAllocator.html#wrap(java.nio.ByteBuffer)">wrap</A></CODE> in interface <CODE><A HREF="../../../../net/rubyeye/xmemcached/buffer/BufferAllocator.html" title="interface in net.rubyeye.xmemcached.buffer">BufferAllocator</A></CODE></DL> </DD> <DD><DL> </DL> </DD> </DL> <HR> <A NAME="navbar_bottom"></A> <A HREF="#skip-navbar_bottom" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="<API key>"></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="class-use/<API key>.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="../../../../net/rubyeye/xmemcached/buffer/IoBuffer.html" title="interface in net.rubyeye.xmemcached.buffer"><B>PREV CLASS</B></A>&nbsp; &nbsp;<A HREF="../../../../net/rubyeye/xmemcached/buffer/SimpleIoBuffer.html" title="class in net.rubyeye.xmemcached.buffer"><B>NEXT CLASS</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../index.html?net/rubyeye/xmemcached/buffer/<API key>.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="<API key>.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <! if(window==top) { document.writeln('<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } </SCRIPT> <NOSCRIPT> <A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> <TR> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> SUMMARY:&nbsp;NESTED&nbsp;|&nbsp;<A HREF="#field_summary">FIELD</A>&nbsp;|&nbsp;<A HREF="#constructor_summary">CONSTR</A>&nbsp;|&nbsp;<A HREF="#method_summary">METHOD</A></FONT></TD> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> DETAIL:&nbsp;<A HREF="#field_detail">FIELD</A>&nbsp;|&nbsp;<A HREF="#constructor_detail">CONSTR</A>&nbsp;|&nbsp;<A HREF="#method_detail">METHOD</A></FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_bottom"></A> <HR> Copyright & </BODY> </HTML>
/* $Id: xuartlite_intr.c,v 1.1.2.1 2009/11/24 05:14:29 svemula Exp $ */ #include "xuartlite.h" #include "xuartlite_i.h" #include "xil_io.h" static void ReceiveDataHandler(XUartLite *InstancePtr); static void SendDataHandler(XUartLite *InstancePtr); typedef void (*Handler)(XUartLite *InstancePtr); void <API key>(XUartLite *InstancePtr, XUartLite_Handler FuncPtr, void *CallBackRef) { /* * Assert validates the input arguments * CallBackRef not checked, no way to know what is valid */ Xil_AssertVoid(InstancePtr != NULL); Xil_AssertVoid(FuncPtr != NULL); Xil_AssertVoid(InstancePtr->IsReady == <API key>); InstancePtr->RecvHandler = FuncPtr; InstancePtr->RecvCallBackRef = CallBackRef; } void <API key>(XUartLite *InstancePtr, XUartLite_Handler FuncPtr, void *CallBackRef) { /* * Assert validates the input arguments * CallBackRef not checked, no way to know what is valid */ Xil_AssertVoid(InstancePtr != NULL); Xil_AssertVoid(FuncPtr != NULL); Xil_AssertVoid(InstancePtr->IsReady == <API key>); InstancePtr->SendHandler = FuncPtr; InstancePtr->SendCallBackRef = CallBackRef; } void <API key>(XUartLite *InstancePtr) { u32 IsrStatus; Xil_AssertVoid(InstancePtr != NULL); /* * Read the status register to determine which, coulb be both * interrupt is active */ IsrStatus = XUartLite_ReadReg(InstancePtr->RegBaseAddress, <API key>); if ((IsrStatus & (XUL_SR_RX_FIFO_FULL | <API key>)) != 0) { ReceiveDataHandler(InstancePtr); } if (((IsrStatus & <API key>) != 0) && (InstancePtr->SendBuffer.RequestedBytes > 0)) { SendDataHandler(InstancePtr); } } static void ReceiveDataHandler(XUartLite *InstancePtr) { /* * If there are bytes still to be received in the specified buffer * go ahead and receive them */ if (InstancePtr->ReceiveBuffer.RemainingBytes != 0) { <API key>(InstancePtr); } /* * If the last byte of a message was received then call the application * handler, this code should not use an else from the previous check of * the number of bytes to receive because the call to receive the buffer * updates the bytes to receive */ if (InstancePtr->ReceiveBuffer.RemainingBytes == 0) { InstancePtr->RecvHandler(InstancePtr->RecvCallBackRef, InstancePtr->ReceiveBuffer.RequestedBytes - InstancePtr->ReceiveBuffer.RemainingBytes); } /* * Update the receive stats to reflect the receive interrupt */ InstancePtr->Stats.ReceiveInterrupts++; } static void SendDataHandler(XUartLite *InstancePtr) { /* * If there are not bytes to be sent from the specified buffer, * call the callback function */ if (InstancePtr->SendBuffer.RemainingBytes == 0) { int SaveReq; /* * Save and zero the requested bytes since transmission * is complete */ SaveReq = InstancePtr->SendBuffer.RequestedBytes; InstancePtr->SendBuffer.RequestedBytes = 0; /* * Call the application handler to indicate * the data has been sent */ InstancePtr->SendHandler(InstancePtr->SendCallBackRef, SaveReq); } /* * Otherwise there is still more data to send in the specified buffer * so go ahead and send it */ else { <API key>(InstancePtr); } /* * Update the transmit stats to reflect the transmit interrupt */ InstancePtr->Stats.TransmitInterrupts++; } void <API key>(XUartLite *InstancePtr) { Xil_AssertVoid(InstancePtr != NULL); Xil_AssertVoid(InstancePtr->IsReady == <API key>); /* * Write to the control register to disable the interrupts, the only * other bits in this register are the FIFO reset bits such that * writing them to zero will not affect them. */ XUartLite_WriteReg(InstancePtr->RegBaseAddress, <API key>, 0); } void <API key>(XUartLite *InstancePtr) { Xil_AssertVoid(InstancePtr != NULL); Xil_AssertVoid(InstancePtr->IsReady == <API key>); /* * Write to the control register to enable the interrupts, the only * other bits in this register are the FIFO reset bits such that * writing them to zero will not affect them. */ XUartLite_WriteReg(InstancePtr->RegBaseAddress, <API key>, XUL_CR_ENABLE_INTR); }
from material.frontend import Module class Accounting(Module): icon = "mdi-action-payment"
// The LLVM Compiler Infrastructure // This file is distributed under the University of Illinois Open Source // This pass forwards branches to unconditional branches to make them branch // directly to the target block. This pass often results in dead MBB's, which // it then removes. // Note that this pass must be run after register allocation, it cannot handle // SSA form. #include "BranchFolding.h" #include "llvm/ADT/STLExtras.h" #include "llvm/ADT/SmallSet.h" #include "llvm/ADT/Statistic.h" #include "llvm/CodeGen/MachineFunctionPass.h" #include "llvm/CodeGen/<API key>.h" #include "llvm/CodeGen/MachineModuleInfo.h" #include "llvm/CodeGen/MachineRegisterInfo.h" #include "llvm/CodeGen/Passes.h" #include "llvm/CodeGen/RegisterScavenging.h" #include "llvm/IR/Function.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/Debug.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/raw_ostream.h" #include "llvm/Target/TargetInstrInfo.h" #include "llvm/Target/TargetMachine.h" #include "llvm/Target/TargetRegisterInfo.h" #include <algorithm> using namespace llvm; #define DEBUG_TYPE "branchfolding" STATISTIC(NumDeadBlocks, "Number of dead blocks removed"); STATISTIC(NumBranchOpts, "Number of branches optimized"); STATISTIC(NumTailMerge , "Number of block tails merged"); STATISTIC(NumHoist , "Number of times common instructions are hoisted"); static cl::opt<cl::boolOrDefault> FlagEnableTailMerge("enable-tail-merge", cl::init(cl::BOU_UNSET), cl::Hidden); // Throttle for huge numbers of predecessors (compile speed problems) static cl::opt<unsigned> TailMergeThreshold("<API key>", cl::desc("Max number of predecessors to consider tail merging"), cl::init(150), cl::Hidden); // Heuristic for tail merging (and, inversely, tail duplication). // TODO: This should be replaced with a target query. static cl::opt<unsigned> TailMergeSize("tail-merge-size", cl::desc("Min number of instructions to consider tail merging"), cl::init(3), cl::Hidden); namespace { BranchFolderPass - Wrap branch folder in a machine function pass. class BranchFolderPass : public MachineFunctionPass { public: static char ID; explicit BranchFolderPass(): MachineFunctionPass(ID) {} bool <API key>(MachineFunction &MF) override; void getAnalysisUsage(AnalysisUsage &AU) const override { AU.addRequired<TargetPassConfig>(); MachineFunctionPass::getAnalysisUsage(AU); } }; } char BranchFolderPass::ID = 0; char &llvm::BranchFolderPassID = BranchFolderPass::ID; INITIALIZE_PASS(BranchFolderPass, "branch-folder", "Control Flow Optimizer", false, false) bool BranchFolderPass::<API key>(MachineFunction &MF) { if (skipOptnoneFunction(*MF.getFunction())) return false; TargetPassConfig *PassConfig = &getAnalysis<TargetPassConfig>(); // TailMerge can create jump into if branches that make CFG irreducible for // HW that requires structurized CFG. bool EnableTailMerge = !MF.getTarget().<API key>() && PassConfig->getEnableTailMerge(); BranchFolder Folder(EnableTailMerge, /*CommonHoist=*/true); return Folder.OptimizeFunction(MF, MF.getTarget().getInstrInfo(), MF.getTarget().getRegisterInfo(), <API key><MachineModuleInfo>()); } BranchFolder::BranchFolder(bool <API key>, bool CommonHoist) { switch (FlagEnableTailMerge) { case cl::BOU_UNSET: EnableTailMerge = <API key>; break; case cl::BOU_TRUE: EnableTailMerge = true; break; case cl::BOU_FALSE: EnableTailMerge = false; break; } <API key> = CommonHoist; } RemoveDeadBlock - Remove the specified dead machine basic block from the function, updating the CFG. void BranchFolder::RemoveDeadBlock(MachineBasicBlock *MBB) { assert(MBB->pred_empty() && "MBB must be dead!"); DEBUG(dbgs() << "\nRemoving MBB: " << *MBB); MachineFunction *MF = MBB->getParent(); // drop all successors. while (!MBB->succ_empty()) MBB->removeSuccessor(MBB->succ_end()-1); // Avoid matching if this pointer gets reused. TriedMerging.erase(MBB); // Remove the block. MF->erase(MBB); } <API key> - If a basic block is just a bunch of implicit_def followed by terminators, and if the implicitly defined registers are not used by the terminators, remove those implicit_def's. e.g. BB1: r0 = implicit_def r1 = implicit_def br This block can be optimized away later if the implicit instructions are removed. bool BranchFolder::<API key>(MachineBasicBlock *MBB) { SmallSet<unsigned, 4> ImpDefRegs; MachineBasicBlock::iterator I = MBB->begin(); while (I != MBB->end()) { if (!I->isImplicitDef()) break; unsigned Reg = I->getOperand(0).getReg(); for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true); SubRegs.isValid(); ++SubRegs) ImpDefRegs.insert(*SubRegs); ++I; } if (ImpDefRegs.empty()) return false; MachineBasicBlock::iterator FirstTerm = I; while (I != MBB->end()) { if (!TII-><API key>(I)) return false; // See if it uses any of the implicitly defined registers. for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) { MachineOperand &MO = I->getOperand(i); if (!MO.isReg() || !MO.isUse()) continue; unsigned Reg = MO.getReg(); if (ImpDefRegs.count(Reg)) return false; } ++I; } I = MBB->begin(); while (I != FirstTerm) { MachineInstr *ImpDefMI = &*I; ++I; MBB->erase(ImpDefMI); } return true; } OptimizeFunction - Perhaps branch folding, tail merging and other CFG optimizations on the given function. bool BranchFolder::OptimizeFunction(MachineFunction &MF, const TargetInstrInfo *tii, const TargetRegisterInfo *tri, MachineModuleInfo *mmi) { if (!tii) return false; TriedMerging.clear(); TII = tii; TRI = tri; MMI = mmi; RS = nullptr; // Use a RegScavenger to help update liveness when required. MachineRegisterInfo &MRI = MF.getRegInfo(); if (MRI.tracksLiveness() && TRI-><API key>(MF)) RS = new RegScavenger(); else MRI.invalidateLiveness(); // Fix CFG. The later algorithms expect it to be right. bool MadeChange = false; for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; I++) { MachineBasicBlock *MBB = I, *TBB = nullptr, *FBB = nullptr; SmallVector<MachineOperand, 4> Cond; if (!TII->AnalyzeBranch(*MBB, TBB, FBB, Cond, true)) MadeChange |= MBB-><API key>(TBB, FBB, !Cond.empty()); MadeChange |= <API key>(MBB); } bool <API key> = true; while (<API key>) { <API key> = TailMergeBlocks(MF); <API key> |= OptimizeBranches(MF); if (<API key>) <API key> |= HoistCommonCode(MF); MadeChange |= <API key>; } // See if any jump tables have become dead as the code generator // did its thing. <API key> *JTI = MF.getJumpTableInfo(); if (!JTI) { delete RS; return MadeChange; } // Walk the function to find jump tables that are live. BitVector JTIsLive(JTI->getJumpTables().size()); for (MachineFunction::iterator BB = MF.begin(), E = MF.end(); BB != E; ++BB) { for (MachineBasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op) { MachineOperand &Op = I->getOperand(op); if (!Op.isJTI()) continue; // Remember that this JT is live. JTIsLive.set(Op.getIndex()); } } // Finally, remove dead jump tables. This happens when the // indirect jump was unreachable (and thus deleted). for (unsigned i = 0, e = JTIsLive.size(); i != e; ++i) if (!JTIsLive.test(i)) { JTI->RemoveJumpTable(i); MadeChange = true; } delete RS; return MadeChange; } // Tail Merging of Blocks HashMachineInstr - Compute a hash value for MI and its operands. static unsigned HashMachineInstr(const MachineInstr *MI) { unsigned Hash = MI->getOpcode(); for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) { const MachineOperand &Op = MI->getOperand(i); // Merge in bits from the operand if easy. unsigned OperandHash = 0; switch (Op.getType()) { case MachineOperand::MO_Register: OperandHash = Op.getReg(); break; case MachineOperand::MO_Immediate: OperandHash = Op.getImm(); break; case MachineOperand::<API key>: OperandHash = Op.getMBB()->getNumber(); break; case MachineOperand::MO_FrameIndex: case MachineOperand::<API key>: case MachineOperand::MO_JumpTableIndex: OperandHash = Op.getIndex(); break; case MachineOperand::MO_GlobalAddress: case MachineOperand::MO_ExternalSymbol: // Global address / external symbol are too hard, don't bother, but do // pull in the offset. OperandHash = Op.getOffset(); break; default: break; } Hash += ((OperandHash << 3) | Op.getType()) << (i&31); } return Hash; } HashEndOfMBB - Hash the last instruction in the MBB. static unsigned HashEndOfMBB(const MachineBasicBlock *MBB) { MachineBasicBlock::const_iterator I = MBB->end(); if (I == MBB->begin()) return 0; // Empty MBB. --I; // Skip debug info so it will not affect codegen. while (I->isDebugValue()) { if (I==MBB->begin()) return 0; // MBB empty except for debug info. --I; } return HashMachineInstr(I); } <API key> - Given two machine basic blocks, compute the number of instructions they actually have in common together at their end. Return iterators for the first shared instruction in each block. static unsigned <API key>(MachineBasicBlock *MBB1, MachineBasicBlock *MBB2, MachineBasicBlock::iterator &I1, MachineBasicBlock::iterator &I2) { I1 = MBB1->end(); I2 = MBB2->end(); unsigned TailLen = 0; while (I1 != MBB1->begin() && I2 != MBB2->begin()) { --I1; --I2; // Skip debugging pseudos; necessary to avoid changing the code. while (I1->isDebugValue()) { if (I1==MBB1->begin()) { while (I2->isDebugValue()) { if (I2==MBB2->begin()) // I1==DBG at begin; I2==DBG at begin return TailLen; --I2; } ++I2; // I1==DBG at begin; I2==non-DBG, or first of DBGs not at begin return TailLen; } --I1; } // I1==first (untested) non-DBG preceding known match while (I2->isDebugValue()) { if (I2==MBB2->begin()) { ++I1; // I1==non-DBG, or first of DBGs not at begin; I2==DBG at begin return TailLen; } --I2; } // I1, I2==first (untested) non-DBGs preceding known match if (!I1->isIdenticalTo(I2) || // FIXME: This check is dubious. It's used to get around a problem where // people incorrectly expect inline asm directives to remain in the same // relative order. This is untenable because normal compiler // optimizations (like this one) may reorder and/or merge these // directives. I1->isInlineAsm()) { ++I1; ++I2; break; } ++TailLen; } // Back past possible debugging pseudos at beginning of block. This matters // when one block differs from the other only by whether debugging pseudos // are present at the beginning. (This way, the various checks later for // I1==MBB1->begin() work as expected.) if (I1 == MBB1->begin() && I2 != MBB2->begin()) { --I2; while (I2->isDebugValue()) { if (I2 == MBB2->begin()) return TailLen; --I2; } ++I2; } if (I2 == MBB2->begin() && I1 != MBB1->begin()) { --I1; while (I1->isDebugValue()) { if (I1 == MBB1->begin()) return TailLen; --I1; } ++I1; } return TailLen; } void BranchFolder::MaintainLiveIns(MachineBasicBlock *CurMBB, MachineBasicBlock *NewMBB) { if (RS) { RS->enterBasicBlock(CurMBB); if (!CurMBB->empty()) RS->forward(std::prev(CurMBB->end())); BitVector RegsLiveAtExit(TRI->getNumRegs()); RS->getRegsUsed(RegsLiveAtExit, false); for (unsigned int i = 0, e = TRI->getNumRegs(); i != e; i++) if (RegsLiveAtExit[i]) NewMBB->addLiveIn(i); } } <API key> - Delete the instruction OldInst and everything after it, replacing it with an unconditional branch to NewDest. void BranchFolder::<API key>(MachineBasicBlock::iterator OldInst, MachineBasicBlock *NewDest) { MachineBasicBlock *CurMBB = OldInst->getParent(); TII-><API key>(OldInst, NewDest); // For targets that use the register scavenger, we must maintain LiveIns. MaintainLiveIns(CurMBB, NewDest); ++NumTailMerge; } SplitMBBAt - Given a machine basic block and an iterator into it, split the MBB so that the part before the iterator falls into the part starting at the iterator. This returns the new MBB. MachineBasicBlock *BranchFolder::SplitMBBAt(MachineBasicBlock &CurMBB, MachineBasicBlock::iterator BBI1, const BasicBlock *BB) { if (!TII->isLegalToSplitMBBAt(CurMBB, BBI1)) return nullptr; MachineFunction &MF = *CurMBB.getParent(); // Create the fall-through block. MachineFunction::iterator MBBI = &CurMBB; MachineBasicBlock *NewMBB =MF.<API key>(BB); CurMBB.getParent()->insert(++MBBI, NewMBB); // Move all the successors of this block to the specified block. NewMBB->transferSuccessors(&CurMBB); // Add an edge from CurMBB to NewMBB for the fall-through. CurMBB.addSuccessor(NewMBB); // Splice the code over. NewMBB->splice(NewMBB->end(), &CurMBB, BBI1, CurMBB.end()); // For targets that use the register scavenger, we must maintain LiveIns. MaintainLiveIns(&CurMBB, NewMBB); return NewMBB; } EstimateRuntime - Make a rough estimate for how long it will take to run the specified code. static unsigned EstimateRuntime(MachineBasicBlock::iterator I, MachineBasicBlock::iterator E) { unsigned Time = 0; for (; I != E; ++I) { if (I->isDebugValue()) continue; if (I->isCall()) Time += 10; else if (I->mayLoad() || I->mayStore()) Time += 2; else ++Time; } return Time; } // CurMBB needs to add an unconditional branch to SuccMBB (we removed these // branches temporarily for tail merging). In the case where CurMBB ends // with a conditional branch to the next block, optimize by reversing the // test and conditionally branching to SuccMBB instead. static void FixTail(MachineBasicBlock *CurMBB, MachineBasicBlock *SuccBB, const TargetInstrInfo *TII) { MachineFunction *MF = CurMBB->getParent(); MachineFunction::iterator I = std::next(MachineFunction::iterator(CurMBB)); MachineBasicBlock *TBB = nullptr, *FBB = nullptr; SmallVector<MachineOperand, 4> Cond; DebugLoc dl; // FIXME: this is nowhere if (I != MF->end() && !TII->AnalyzeBranch(*CurMBB, TBB, FBB, Cond, true)) { MachineBasicBlock *NextBB = I; if (TBB == NextBB && !Cond.empty() && !FBB) { if (!TII-><API key>(Cond)) { TII->RemoveBranch(*CurMBB); TII->InsertBranch(*CurMBB, SuccBB, nullptr, Cond, dl); return; } } } TII->InsertBranch(*CurMBB, SuccBB, nullptr, SmallVector<MachineOperand, 0>(), dl); } bool BranchFolder::MergePotentialsElt::operator<(const MergePotentialsElt &o) const { if (getHash() < o.getHash()) return true; if (getHash() > o.getHash()) return false; if (getBlock()->getNumber() < o.getBlock()->getNumber()) return true; if (getBlock()->getNumber() > o.getBlock()->getNumber()) return false; // _GLIBCXX_DEBUG checks strict weak ordering, which involves comparing // an object with itself. #ifndef _GLIBCXX_DEBUG llvm_unreachable("Predecessor appears twice"); #else return false; #endif } CountTerminators - Count the number of terminators in the given block and set I to the position of the first non-terminator, if there is one, or MBB->end() otherwise. static unsigned CountTerminators(MachineBasicBlock *MBB, MachineBasicBlock::iterator &I) { I = MBB->end(); unsigned NumTerms = 0; for (;;) { if (I == MBB->begin()) { I = MBB->end(); break; } --I; if (!I->isTerminator()) break; ++NumTerms; } return NumTerms; } ProfitableToMerge - Check if two machine basic blocks have a common tail and decide if it would be profitable to merge those tails. Return the length of the common tail and iterators to the first common instruction in each block. static bool ProfitableToMerge(MachineBasicBlock *MBB1, MachineBasicBlock *MBB2, unsigned minCommonTailLength, unsigned &CommonTailLen, MachineBasicBlock::iterator &I1, MachineBasicBlock::iterator &I2, MachineBasicBlock *SuccBB, MachineBasicBlock *PredBB) { CommonTailLen = <API key>(MBB1, MBB2, I1, I2); if (CommonTailLen == 0) return false; DEBUG(dbgs() << "Common tail length of BB#" << MBB1->getNumber() << " and BB#" << MBB2->getNumber() << " is " << CommonTailLen << '\n'); // It's almost always profitable to merge any number of non-terminator // instructions with the block that falls through into the common successor. if (MBB1 == PredBB || MBB2 == PredBB) { MachineBasicBlock::iterator I; unsigned NumTerms = CountTerminators(MBB1 == PredBB ? MBB2 : MBB1, I); if (CommonTailLen > NumTerms) return true; } // If one of the blocks can be completely merged and happens to be in // a position where the other could fall through into it, merge any number // of instructions, because it can be done without a branch. // TODO: If the blocks are not adjacent, move one of them so that they are? if (MBB1->isLayoutSuccessor(MBB2) && I2 == MBB2->begin()) return true; if (MBB2->isLayoutSuccessor(MBB1) && I1 == MBB1->begin()) return true; // If both blocks have an unconditional branch temporarily stripped out, // count that as an additional common instruction for the following // heuristics. unsigned EffectiveTailLen = CommonTailLen; if (SuccBB && MBB1 != PredBB && MBB2 != PredBB && !MBB1->back().isBarrier() && !MBB2->back().isBarrier()) ++EffectiveTailLen; // Check if the common tail is long enough to be worthwhile. if (EffectiveTailLen >= minCommonTailLength) return true; // If we are optimizing for code size, 2 instructions in common is enough if // we don't have to split a block. At worst we will be introducing 1 new // branch instruction, which is likely to be smaller than the 2 // instructions that would be deleted in the merge. MachineFunction *MF = MBB1->getParent(); if (EffectiveTailLen >= 2 && MF->getFunction()->getAttributes(). hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize) && (I1 == MBB1->begin() || I2 == MBB2->begin())) return true; return false; } ComputeSameTails - Look through all the blocks in MergePotentials that have hash CurHash (guaranteed to match the last element). Build the vector SameTails of all those that have the (same) largest number of instructions in common of any pair of these blocks. SameTails entries contain an iterator into MergePotentials (from which the MachineBasicBlock can be found) and a MachineBasicBlock::iterator into that MBB indicating the instruction where the matching code sequence begins. Order of elements in SameTails is the reverse of the order in which those blocks appear in MergePotentials (where they are not necessarily consecutive). unsigned BranchFolder::ComputeSameTails(unsigned CurHash, unsigned minCommonTailLength, MachineBasicBlock *SuccBB, MachineBasicBlock *PredBB) { unsigned maxCommonTailLength = 0U; SameTails.clear(); MachineBasicBlock::iterator TrialBBI1, TrialBBI2; MPIterator HighestMPIter = std::prev(MergePotentials.end()); for (MPIterator CurMPIter = std::prev(MergePotentials.end()), B = MergePotentials.begin(); CurMPIter != B && CurMPIter->getHash() == CurHash; --CurMPIter) { for (MPIterator I = std::prev(CurMPIter); I->getHash() == CurHash; --I) { unsigned CommonTailLen; if (ProfitableToMerge(CurMPIter->getBlock(), I->getBlock(), minCommonTailLength, CommonTailLen, TrialBBI1, TrialBBI2, SuccBB, PredBB)) { if (CommonTailLen > maxCommonTailLength) { SameTails.clear(); maxCommonTailLength = CommonTailLen; HighestMPIter = CurMPIter; SameTails.push_back(SameTailElt(CurMPIter, TrialBBI1)); } if (HighestMPIter == CurMPIter && CommonTailLen == maxCommonTailLength) SameTails.push_back(SameTailElt(I, TrialBBI2)); } if (I == B) break; } } return maxCommonTailLength; } <API key> - Remove all blocks with hash CurHash from MergePotentials, restoring branches at ends of blocks as appropriate. void BranchFolder::<API key>(unsigned CurHash, MachineBasicBlock *SuccBB, MachineBasicBlock *PredBB) { MPIterator CurMPIter, B; for (CurMPIter = std::prev(MergePotentials.end()), B = MergePotentials.begin(); CurMPIter->getHash() == CurHash; --CurMPIter) { // Put the unconditional branch back, if we need one. MachineBasicBlock *CurMBB = CurMPIter->getBlock(); if (SuccBB && CurMBB != PredBB) FixTail(CurMBB, SuccBB, TII); if (CurMPIter == B) break; } if (CurMPIter->getHash() != CurHash) CurMPIter++; MergePotentials.erase(CurMPIter, MergePotentials.end()); } <API key> - None of the blocks to be tail-merged consist only of the common tail. Create a block that does by splitting one. bool BranchFolder::<API key>(MachineBasicBlock *&PredBB, MachineBasicBlock *SuccBB, unsigned maxCommonTailLength, unsigned &commonTailIndex) { commonTailIndex = 0; unsigned TimeEstimate = ~0U; for (unsigned i = 0, e = SameTails.size(); i != e; ++i) { // Use PredBB if possible; that doesn't require a new branch. if (SameTails[i].getBlock() == PredBB) { commonTailIndex = i; break; } // Otherwise, make a (fairly bogus) choice based on estimate of // how long it will take the various blocks to execute. unsigned t = EstimateRuntime(SameTails[i].getBlock()->begin(), SameTails[i].getTailStartPos()); if (t <= TimeEstimate) { TimeEstimate = t; commonTailIndex = i; } } MachineBasicBlock::iterator BBI = SameTails[commonTailIndex].getTailStartPos(); MachineBasicBlock *MBB = SameTails[commonTailIndex].getBlock(); // If the common tail includes any debug info we will take it pretty // randomly from one of the inputs. Might be better to remove it? DEBUG(dbgs() << "\nSplitting BB#" << MBB->getNumber() << ", size " << maxCommonTailLength); // If the split block unconditionally falls-thru to SuccBB, it will be // merged. In control flow terms it should then take SuccBB's name. e.g. If // SuccBB is an inner loop, the common tail is still part of the inner loop. const BasicBlock *BB = (SuccBB && MBB->succ_size() == 1) ? SuccBB->getBasicBlock() : MBB->getBasicBlock(); MachineBasicBlock *newMBB = SplitMBBAt(*MBB, BBI, BB); if (!newMBB) { DEBUG(dbgs() << "... failed!"); return false; } SameTails[commonTailIndex].setBlock(newMBB); SameTails[commonTailIndex].setTailStartPos(newMBB->begin()); // If we split PredBB, newMBB is the new predecessor. if (PredBB == MBB) PredBB = newMBB; return true; } // See if any of the blocks in MergePotentials (which all have a common single // successor, or all have no successor) can be tail-merged. If there is a // successor, any blocks in MergePotentials that are not tail-merged and // are not immediately before Succ must have an unconditional branch to // Succ added (but the predecessor/successor lists need no adjustment). // The lone predecessor of Succ that falls through into Succ, // if any, is given in PredBB. bool BranchFolder::TryTailMergeBlocks(MachineBasicBlock *SuccBB, MachineBasicBlock *PredBB) { bool MadeChange = false; // Except for the special cases below, tail-merge if there are at least // this many instructions in common. unsigned minCommonTailLength = TailMergeSize; DEBUG(dbgs() << "\nTryTailMergeBlocks: "; for (unsigned i = 0, e = MergePotentials.size(); i != e; ++i) dbgs() << "BB#" << MergePotentials[i].getBlock()->getNumber() << (i == e-1 ? "" : ", "); dbgs() << "\n"; if (SuccBB) { dbgs() << " with successor BB#" << SuccBB->getNumber() << '\n'; if (PredBB) dbgs() << " which has fall-through from BB << PredBB->getNumber() << "\n"; } dbgs() << "Looking for common tails of at least " << minCommonTailLength << " instruction" << (minCommonTailLength == 1 ? "" : "s") << '\n'; ); // Sort by hash value so that blocks with identical end sequences sort // together. std::stable_sort(MergePotentials.begin(), MergePotentials.end()); // Walk through equivalence sets looking for actual exact matches. while (MergePotentials.size() > 1) { unsigned CurHash = MergePotentials.back().getHash(); // Build SameTails, identifying the set of blocks with this hash code // and with the maximum number of instructions in common. unsigned maxCommonTailLength = ComputeSameTails(CurHash, minCommonTailLength, SuccBB, PredBB); // If we didn't find any pair that has at least minCommonTailLength // instructions in common, remove all blocks with this hash code and retry. if (SameTails.empty()) { <API key>(CurHash, SuccBB, PredBB); continue; } // If one of the blocks is the entire common tail (and not the entry // block, which we can't jump to), we can treat all blocks with this same // tail at once. Use PredBB if that is one of the possibilities, as that // will not introduce any extra branches. MachineBasicBlock *EntryBB = MergePotentials.begin()->getBlock()-> getParent()->begin(); unsigned commonTailIndex = SameTails.size(); // If there are two blocks, check to see if one can be made to fall through // into the other. if (SameTails.size() == 2 && SameTails[0].getBlock()->isLayoutSuccessor(SameTails[1].getBlock()) && SameTails[1].tailIsWholeBlock()) commonTailIndex = 1; else if (SameTails.size() == 2 && SameTails[1].getBlock()->isLayoutSuccessor( SameTails[0].getBlock()) && SameTails[0].tailIsWholeBlock()) commonTailIndex = 0; else { // Otherwise just pick one, favoring the fall-through predecessor if // there is one. for (unsigned i = 0, e = SameTails.size(); i != e; ++i) { MachineBasicBlock *MBB = SameTails[i].getBlock(); if (MBB == EntryBB && SameTails[i].tailIsWholeBlock()) continue; if (MBB == PredBB) { commonTailIndex = i; break; } if (SameTails[i].tailIsWholeBlock()) commonTailIndex = i; } } if (commonTailIndex == SameTails.size() || (SameTails[commonTailIndex].getBlock() == PredBB && !SameTails[commonTailIndex].tailIsWholeBlock())) { // None of the blocks consist entirely of the common tail. // Split a block so that one does. if (!<API key>(PredBB, SuccBB, maxCommonTailLength, commonTailIndex)) { <API key>(CurHash, SuccBB, PredBB); continue; } } MachineBasicBlock *MBB = SameTails[commonTailIndex].getBlock(); // MBB is common tail. Adjust all other BB's to jump to this one. // Traversal must be forwards so erases work. DEBUG(dbgs() << "\nUsing common tail in BB#" << MBB->getNumber() << " for "); for (unsigned int i=0, e = SameTails.size(); i != e; ++i) { if (commonTailIndex == i) continue; DEBUG(dbgs() << "BB#" << SameTails[i].getBlock()->getNumber() << (i == e-1 ? "" : ", ")); // Hack the end off BB i, making it jump to BB commonTailIndex instead. <API key>(SameTails[i].getTailStartPos(), MBB); // BB i is no longer a predecessor of SuccBB; remove it from the worklist. MergePotentials.erase(SameTails[i].getMPIter()); } DEBUG(dbgs() << "\n"); // We leave commonTailIndex in the worklist in case there are other blocks // that match it with a smaller number of instructions. MadeChange = true; } return MadeChange; } bool BranchFolder::TailMergeBlocks(MachineFunction &MF) { bool MadeChange = false; if (!EnableTailMerge) return MadeChange; // First find blocks with no successors. MergePotentials.clear(); for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E && MergePotentials.size() < TailMergeThreshold; ++I) { if (TriedMerging.count(I)) continue; if (I->succ_empty()) MergePotentials.push_back(MergePotentialsElt(HashEndOfMBB(I), I)); } // If this is a large problem, avoid visiting the same basic blocks // multiple times. if (MergePotentials.size() == TailMergeThreshold) for (unsigned i = 0, e = MergePotentials.size(); i != e; ++i) TriedMerging.insert(MergePotentials[i].getBlock()); // See if we can do any tail merging on those. if (MergePotentials.size() >= 2) MadeChange |= TryTailMergeBlocks(nullptr, nullptr); // Look at blocks (IBB) with multiple predecessors (PBB). // We change each predecessor to a canonical form, by // (1) temporarily removing any unconditional branch from the predecessor // to IBB, and // (2) alter conditional branches so they branch to the other block // not IBB; this may require adding back an unconditional branch to IBB // later, where there wasn't one coming in. E.g. // Bcc IBB // fallthrough to QBB // here becomes // Bncc QBB // with a conceptual B to IBB after that, which never actually exists. // With those changes, we see whether the predecessors' tails match, // and merge them if so. We change things out of canonical form and // back to the way they were later in the process. (OptimizeBranches // would undo some of this, but we can't use it, because we'd get into // a compile-time infinite loop repeatedly doing and undoing the same // transformations.) for (MachineFunction::iterator I = std::next(MF.begin()), E = MF.end(); I != E; ++I) { if (I->pred_size() < 2) continue; SmallPtrSet<MachineBasicBlock *, 8> UniquePreds; MachineBasicBlock *IBB = I; MachineBasicBlock *PredBB = std::prev(I); MergePotentials.clear(); for (MachineBasicBlock::pred_iterator P = I->pred_begin(), E2 = I->pred_end(); P != E2 && MergePotentials.size() < TailMergeThreshold; ++P) { MachineBasicBlock *PBB = *P; if (TriedMerging.count(PBB)) continue; // Skip blocks that loop to themselves, can't tail merge these. if (PBB == IBB) continue; // Visit each predecessor only once. if (!UniquePreds.insert(PBB)) continue; // Skip blocks which may jump to a landing pad. Can't tail merge these. if (PBB-><API key>()) continue; MachineBasicBlock *TBB = nullptr, *FBB = nullptr; SmallVector<MachineOperand, 4> Cond; if (!TII->AnalyzeBranch(*PBB, TBB, FBB, Cond, true)) { // Failing case: IBB is the target of a cbr, and we cannot reverse the // branch. SmallVector<MachineOperand, 4> NewCond(Cond); if (!Cond.empty() && TBB == IBB) { if (TII-><API key>(NewCond)) continue; // This is the QBB case described above if (!FBB) FBB = std::next(MachineFunction::iterator(PBB)); } // Failing case: the only way IBB can be reached from PBB is via // exception handling. Happens for landing pads. Would be nice to have // a bit in the edge so we didn't have to do all this. if (IBB->isLandingPad()) { MachineFunction::iterator IP = PBB; IP++; MachineBasicBlock *PredNextBB = nullptr; if (IP != MF.end()) PredNextBB = IP; if (!TBB) { if (IBB != PredNextBB) // fallthrough continue; } else if (FBB) { if (TBB != IBB && FBB != IBB) // cbr then ubr continue; } else if (Cond.empty()) { if (TBB != IBB) // ubr continue; } else { if (TBB != IBB && IBB != PredNextBB) // cbr continue; } } // Remove the unconditional branch at the end, if any. if (TBB && (Cond.empty() || FBB)) { DebugLoc dl; // FIXME: this is nowhere TII->RemoveBranch(*PBB); if (!Cond.empty()) // reinsert conditional branch only, for now TII->InsertBranch(*PBB, (TBB == IBB) ? FBB : TBB, nullptr, NewCond, dl); } MergePotentials.push_back(MergePotentialsElt(HashEndOfMBB(PBB), *P)); } } // If this is a large problem, avoid visiting the same basic blocks multiple // times. if (MergePotentials.size() == TailMergeThreshold) for (unsigned i = 0, e = MergePotentials.size(); i != e; ++i) TriedMerging.insert(MergePotentials[i].getBlock()); if (MergePotentials.size() >= 2) MadeChange |= TryTailMergeBlocks(IBB, PredBB); // Reinsert an unconditional branch if needed. The 1 below can occur as a // result of removing blocks in TryTailMergeBlocks. PredBB = std::prev(I); // this may have been changed in TryTailMergeBlocks if (MergePotentials.size() == 1 && MergePotentials.begin()->getBlock() != PredBB) FixTail(MergePotentials.begin()->getBlock(), IBB, TII); } return MadeChange; } // Branch Optimization bool BranchFolder::OptimizeBranches(MachineFunction &MF) { bool MadeChange = false; // Make sure blocks are numbered in order MF.RenumberBlocks(); for (MachineFunction::iterator I = std::next(MF.begin()), E = MF.end(); I != E; ) { MachineBasicBlock *MBB = I++; MadeChange |= OptimizeBlock(MBB); // If it is dead, remove it. if (MBB->pred_empty()) { RemoveDeadBlock(MBB); MadeChange = true; ++NumDeadBlocks; } } return MadeChange; } // Blocks should be considered empty if they contain only debug info; // else the debug info would affect codegen. static bool IsEmptyBlock(MachineBasicBlock *MBB) { if (MBB->empty()) return true; for (MachineBasicBlock::iterator MBBI = MBB->begin(), MBBE = MBB->end(); MBBI!=MBBE; ++MBBI) { if (!MBBI->isDebugValue()) return false; } return true; } // Blocks with only debug info and branches should be considered the same // as blocks with only branches. static bool IsBranchOnlyBlock(MachineBasicBlock *MBB) { MachineBasicBlock::iterator MBBI, MBBE; for (MBBI = MBB->begin(), MBBE = MBB->end(); MBBI!=MBBE; ++MBBI) { if (!MBBI->isDebugValue()) break; } return (MBBI->isBranch()); } IsBetterFallthrough - Return true if it would be clearly better to fall-through to MBB1 than to fall through into MBB2. This has to return a strict ordering, returning true for both (MBB1,MBB2) and (MBB2,MBB1) will result in infinite loops. static bool IsBetterFallthrough(MachineBasicBlock *MBB1, MachineBasicBlock *MBB2) { // Right now, we use a simple heuristic. If MBB2 ends with a call, and // MBB1 doesn't, we prefer to fall through into MBB1. This allows us to // optimize branches that branch to either a return block or an assert block // into a fallthrough to the return. if (IsEmptyBlock(MBB1) || IsEmptyBlock(MBB2)) return false; // If there is a clear successor ordering we make sure that one block // will fall through to the next if (MBB1->isSuccessor(MBB2)) return true; if (MBB2->isSuccessor(MBB1)) return false; // Neither block consists entirely of debug info (per IsEmptyBlock check), // so we needn't test for falling off the beginning here. MachineBasicBlock::iterator MBB1I = --MBB1->end(); while (MBB1I->isDebugValue()) --MBB1I; MachineBasicBlock::iterator MBB2I = --MBB2->end(); while (MBB2I->isDebugValue()) --MBB2I; return MBB2I->isCall() && !MBB1I->isCall(); } getBranchDebugLoc - Find and return, if any, the DebugLoc of the branch instructions on the block. Always use the DebugLoc of the first branching instruction found unless its absent, in which case use the DebugLoc of the second if present. static DebugLoc getBranchDebugLoc(MachineBasicBlock &MBB) { MachineBasicBlock::iterator I = MBB.end(); if (I == MBB.begin()) return DebugLoc(); --I; while (I->isDebugValue() && I != MBB.begin()) --I; if (I->isBranch()) return I->getDebugLoc(); return DebugLoc(); } OptimizeBlock - Analyze and optimize control flow related to the specified block. This is never called on the entry block. bool BranchFolder::OptimizeBlock(MachineBasicBlock *MBB) { bool MadeChange = false; MachineFunction &MF = *MBB->getParent(); ReoptimizeBlock: MachineFunction::iterator FallThrough = MBB; ++FallThrough; // If this block is empty, make everyone use its fall-through, not the block // explicitly. Landing pads should not do this since the landing-pad table // points to this block. Blocks with their addresses taken shouldn't be // optimized away. if (IsEmptyBlock(MBB) && !MBB->isLandingPad() && !MBB->hasAddressTaken()) { // Dead block? Leave for cleanup later. if (MBB->pred_empty()) return MadeChange; if (FallThrough == MF.end()) { // TODO: Simplify preds to not branch here if possible! } else { // Rewrite all predecessors of the old block to go to the fallthrough // instead. while (!MBB->pred_empty()) { MachineBasicBlock *Pred = *(MBB->pred_end()-1); Pred-><API key>(MBB, FallThrough); } // If MBB was the target of a jump table, update jump tables to go to the // fallthrough instead. if (<API key> *MJTI = MF.getJumpTableInfo()) MJTI-><API key>(MBB, FallThrough); MadeChange = true; } return MadeChange; } // Check to see if we can simplify the terminator of the block before this // one. MachineBasicBlock &PrevBB = *std::prev(MachineFunction::iterator(MBB)); MachineBasicBlock *PriorTBB = nullptr, *PriorFBB = nullptr; SmallVector<MachineOperand, 4> PriorCond; bool PriorUnAnalyzable = TII->AnalyzeBranch(PrevBB, PriorTBB, PriorFBB, PriorCond, true); if (!PriorUnAnalyzable) { // If the CFG for the prior block has extra edges, remove them. MadeChange |= PrevBB.<API key>(PriorTBB, PriorFBB, !PriorCond.empty()); // If the previous branch is conditional and both conditions go to the same // destination, remove the branch, replacing it with an unconditional one or // a fall-through. if (PriorTBB && PriorTBB == PriorFBB) { DebugLoc dl = getBranchDebugLoc(PrevBB); TII->RemoveBranch(PrevBB); PriorCond.clear(); if (PriorTBB != MBB) TII->InsertBranch(PrevBB, PriorTBB, nullptr, PriorCond, dl); MadeChange = true; ++NumBranchOpts; goto ReoptimizeBlock; } // If the previous block unconditionally falls through to this block and // this block has no other predecessors, move the contents of this block // into the prior block. This doesn't usually happen when SimplifyCFG // has been used, but it can happen if tail merging splits a fall-through // predecessor of a block. // This has to check PrevBB->succ_size() because EH edges are ignored by // AnalyzeBranch. if (PriorCond.empty() && !PriorTBB && MBB->pred_size() == 1 && PrevBB.succ_size() == 1 && !MBB->hasAddressTaken() && !MBB->isLandingPad()) { DEBUG(dbgs() << "\nMerging into block: " << PrevBB << "From MBB: " << *MBB); // Remove redundant DBG_VALUEs first. if (PrevBB.begin() != PrevBB.end()) { MachineBasicBlock::iterator PrevBBIter = PrevBB.end(); --PrevBBIter; MachineBasicBlock::iterator MBBIter = MBB->begin(); // Check if DBG_VALUE at the end of PrevBB is identical to the // DBG_VALUE at the beginning of MBB. while (PrevBBIter != PrevBB.begin() && MBBIter != MBB->end() && PrevBBIter->isDebugValue() && MBBIter->isDebugValue()) { if (!MBBIter->isIdenticalTo(PrevBBIter)) break; MachineInstr *DuplicateDbg = MBBIter; ++MBBIter; -- PrevBBIter; DuplicateDbg->eraseFromParent(); } } PrevBB.splice(PrevBB.end(), MBB, MBB->begin(), MBB->end()); PrevBB.removeSuccessor(PrevBB.succ_begin()); assert(PrevBB.succ_empty()); PrevBB.transferSuccessors(MBB); MadeChange = true; return MadeChange; } // If the previous branch *only* branches to *this* block (conditional or // not) remove the branch. if (PriorTBB == MBB && !PriorFBB) { TII->RemoveBranch(PrevBB); MadeChange = true; ++NumBranchOpts; goto ReoptimizeBlock; } // If the prior block branches somewhere else on the condition and here if // the condition is false, remove the uncond second branch. if (PriorFBB == MBB) { DebugLoc dl = getBranchDebugLoc(PrevBB); TII->RemoveBranch(PrevBB); TII->InsertBranch(PrevBB, PriorTBB, nullptr, PriorCond, dl); MadeChange = true; ++NumBranchOpts; goto ReoptimizeBlock; } // If the prior block branches here on true and somewhere else on false, and // if the branch condition is reversible, reverse the branch to create a // fall-through. if (PriorTBB == MBB) { SmallVector<MachineOperand, 4> NewPriorCond(PriorCond); if (!TII-><API key>(NewPriorCond)) { DebugLoc dl = getBranchDebugLoc(PrevBB); TII->RemoveBranch(PrevBB); TII->InsertBranch(PrevBB, PriorFBB, nullptr, NewPriorCond, dl); MadeChange = true; ++NumBranchOpts; goto ReoptimizeBlock; } } // If this block has no successors (e.g. it is a return block or ends with // a call to a no-return function like abort or __cxa_throw) and if the pred // falls through into this block, and if it would otherwise fall through // into the block after this, move this block to the end of the function. // We consider it more likely that execution will stay in the function (e.g. // due to loops) than it is to exit it. This asserts in loops etc, moving // the assert condition out of the loop body. if (MBB->succ_empty() && !PriorCond.empty() && !PriorFBB && MachineFunction::iterator(PriorTBB) == FallThrough && !MBB->canFallThrough()) { bool DoTransform = true; // We have to be careful that the succs of PredBB aren't both no-successor // blocks. If neither have successors and if PredBB is the second from // last block in the function, we'd just keep swapping the two blocks for // last. Only do the swap if one is clearly better to fall through than // the other. if (FallThrough == --MF.end() && !IsBetterFallthrough(PriorTBB, MBB)) DoTransform = false; if (DoTransform) { // Reverse the branch so we will fall through on the previous true cond. SmallVector<MachineOperand, 4> NewPriorCond(PriorCond); if (!TII-><API key>(NewPriorCond)) { DEBUG(dbgs() << "\nMoving MBB: " << *MBB << "To make fallthrough to: " << *PriorTBB << "\n"); DebugLoc dl = getBranchDebugLoc(PrevBB); TII->RemoveBranch(PrevBB); TII->InsertBranch(PrevBB, MBB, nullptr, NewPriorCond, dl); // Move this block to the end of the function. MBB->moveAfter(--MF.end()); MadeChange = true; ++NumBranchOpts; return MadeChange; } } } } // Analyze the branch in the current block. MachineBasicBlock *CurTBB = nullptr, *CurFBB = nullptr; SmallVector<MachineOperand, 4> CurCond; bool CurUnAnalyzable= TII->AnalyzeBranch(*MBB, CurTBB, CurFBB, CurCond, true); if (!CurUnAnalyzable) { // If the CFG for the prior block has extra edges, remove them. MadeChange |= MBB-><API key>(CurTBB, CurFBB, !CurCond.empty()); // If this is a two-way branch, and the FBB branches to this block, reverse // the condition so the single-basic-block loop is faster. Instead of: // Loop: xxx; jcc Out; jmp Loop // we want: // Loop: xxx; jncc Loop; jmp Out if (CurTBB && CurFBB && CurFBB == MBB && CurTBB != MBB) { SmallVector<MachineOperand, 4> NewCond(CurCond); if (!TII-><API key>(NewCond)) { DebugLoc dl = getBranchDebugLoc(*MBB); TII->RemoveBranch(*MBB); TII->InsertBranch(*MBB, CurFBB, CurTBB, NewCond, dl); MadeChange = true; ++NumBranchOpts; goto ReoptimizeBlock; } } // If this branch is the only thing in its block, see if we can forward // other blocks across it. if (CurTBB && CurCond.empty() && !CurFBB && IsBranchOnlyBlock(MBB) && CurTBB != MBB && !MBB->hasAddressTaken()) { DebugLoc dl = getBranchDebugLoc(*MBB); // This block may contain just an unconditional branch. Because there can // be 'non-branch terminators' in the block, try removing the branch and // then seeing if the block is empty. TII->RemoveBranch(*MBB); // If the only things remaining in the block are debug info, remove these // as well, so this will behave the same as an empty block in non-debug // mode. if (!MBB->empty()) { bool NonDebugInfoFound = false; for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end(); I != E; ++I) { if (!I->isDebugValue()) { NonDebugInfoFound = true; break; } } if (!NonDebugInfoFound) // Make the block empty, losing the debug info (we could probably // improve this in some cases.) MBB->erase(MBB->begin(), MBB->end()); } // If this block is just an unconditional branch to CurTBB, we can // usually completely eliminate the block. The only case we cannot // completely eliminate the block is when the block before this one // falls through into MBB and we can't understand the prior block's branch // condition. if (MBB->empty()) { bool <API key> = !PrevBB.canFallThrough(); if (<API key> || !PriorUnAnalyzable || !PrevBB.isSuccessor(MBB)) { // If the prior block falls through into us, turn it into an // explicit branch to us to make updates simpler. if (!<API key> && PrevBB.isSuccessor(MBB) && PriorTBB != MBB && PriorFBB != MBB) { if (!PriorTBB) { assert(PriorCond.empty() && !PriorFBB && "Bad branch analysis"); PriorTBB = MBB; } else { assert(!PriorFBB && "Machine CFG out of date!"); PriorFBB = MBB; } DebugLoc pdl = getBranchDebugLoc(PrevBB); TII->RemoveBranch(PrevBB); TII->InsertBranch(PrevBB, PriorTBB, PriorFBB, PriorCond, pdl); } // Iterate through all the predecessors, revectoring each in-turn. size_t PI = 0; bool DidChange = false; bool HasBranchToSelf = false; while(PI != MBB->pred_size()) { MachineBasicBlock *PMBB = *(MBB->pred_begin() + PI); if (PMBB == MBB) { // If this block has an uncond branch to itself, leave it. ++PI; HasBranchToSelf = true; } else { DidChange = true; PMBB-><API key>(MBB, CurTBB); // If this change resulted in PMBB ending in a conditional // branch where both conditions go to the same destination, // change this to an unconditional branch (and fix the CFG). MachineBasicBlock *NewCurTBB = nullptr, *NewCurFBB = nullptr; SmallVector<MachineOperand, 4> NewCurCond; bool NewCurUnAnalyzable = TII->AnalyzeBranch(*PMBB, NewCurTBB, NewCurFBB, NewCurCond, true); if (!NewCurUnAnalyzable && NewCurTBB && NewCurTBB == NewCurFBB) { DebugLoc pdl = getBranchDebugLoc(*PMBB); TII->RemoveBranch(*PMBB); NewCurCond.clear(); TII->InsertBranch(*PMBB, NewCurTBB, nullptr, NewCurCond, pdl); MadeChange = true; ++NumBranchOpts; PMBB-><API key>(NewCurTBB, nullptr, false); } } } // Change any jumptables to go to the new MBB. if (<API key> *MJTI = MF.getJumpTableInfo()) MJTI-><API key>(MBB, CurTBB); if (DidChange) { ++NumBranchOpts; MadeChange = true; if (!HasBranchToSelf) return MadeChange; } } } // Add the branch back if the block is more than just an uncond branch. TII->InsertBranch(*MBB, CurTBB, nullptr, CurCond, dl); } } // If the prior block doesn't fall through into this block, and if this // block doesn't fall through into some other block, see if we can find a // place to move this block where a fall-through will happen. if (!PrevBB.canFallThrough()) { // Now we know that there was no fall-through into this block, check to // see if it has a fall-through into its successor. bool CurFallsThru = MBB->canFallThrough(); if (!MBB->isLandingPad()) { // Check all the predecessors of this block. If one of them has no fall // throughs, move this block right after it. for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(), E = MBB->pred_end(); PI != E; ++PI) { // Analyze the branch at the end of the pred. MachineBasicBlock *PredBB = *PI; MachineFunction::iterator PredFallthrough = PredBB; ++PredFallthrough; MachineBasicBlock *PredTBB = nullptr, *PredFBB = nullptr; SmallVector<MachineOperand, 4> PredCond; if (PredBB != MBB && !PredBB->canFallThrough() && !TII->AnalyzeBranch(*PredBB, PredTBB, PredFBB, PredCond, true) && (!CurFallsThru || !CurTBB || !CurFBB) && (!CurFallsThru || MBB->getNumber() >= PredBB->getNumber())) { // If the current block doesn't fall through, just move it. // If the current block can fall through and does not end with a // conditional branch, we need to append an unconditional jump to // the (current) next block. To avoid a possible compile-time // infinite loop, move blocks only backward in this case. // Also, if there are already 2 branches here, we cannot add a third; // this means we have the case // Bcc next // B elsewhere // next: if (CurFallsThru) { MachineBasicBlock *NextBB = std::next(MachineFunction::iterator(MBB)); CurCond.clear(); TII->InsertBranch(*MBB, NextBB, nullptr, CurCond, DebugLoc()); } MBB->moveAfter(PredBB); MadeChange = true; goto ReoptimizeBlock; } } } if (!CurFallsThru) { // Check all successors to see if we can move this block before it. for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(), E = MBB->succ_end(); SI != E; ++SI) { // Analyze the branch at the end of the block before the succ. MachineBasicBlock *SuccBB = *SI; MachineFunction::iterator SuccPrev = SuccBB; --SuccPrev; // If this block doesn't already fall-through to that successor, and if // the succ doesn't already have a block that can fall through into it, // and if the successor isn't an EH destination, we can arrange for the // fallthrough to happen. if (SuccBB != MBB && &*SuccPrev != MBB && !SuccPrev->canFallThrough() && !CurUnAnalyzable && !SuccBB->isLandingPad()) { MBB->moveBefore(SuccBB); MadeChange = true; goto ReoptimizeBlock; } } // Okay, there is no really great place to put this block. If, however, // the block before this one would be a fall-through if this block were // removed, move this block to the end of the function. MachineBasicBlock *PrevTBB = nullptr, *PrevFBB = nullptr; SmallVector<MachineOperand, 4> PrevCond; if (FallThrough != MF.end() && !TII->AnalyzeBranch(PrevBB, PrevTBB, PrevFBB, PrevCond, true) && PrevBB.isSuccessor(FallThrough)) { MBB->moveAfter(--MF.end()); MadeChange = true; return MadeChange; } } } return MadeChange; } // Hoist Common Code HoistCommonCode - Hoist common instruction sequences at the start of basic blocks to their common predecessor. bool BranchFolder::HoistCommonCode(MachineFunction &MF) { bool MadeChange = false; for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ) { MachineBasicBlock *MBB = I++; MadeChange |= <API key>(MBB); } return MadeChange; } findFalseBlock - BB has a fallthrough. Find its 'false' successor given its 'true' successor. static MachineBasicBlock *findFalseBlock(MachineBasicBlock *BB, MachineBasicBlock *TrueBB) { for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(), E = BB->succ_end(); SI != E; ++SI) { MachineBasicBlock *SuccBB = *SI; if (SuccBB != TrueBB) return SuccBB; } return nullptr; } <API key> - Find the location to move common instructions in successors to. The location is usually just before the terminator, however if the terminator is a conditional branch and its previous instruction is the flag setting instruction, the previous instruction is the preferred location. This function also gathers uses and defs of the instructions from the insertion point to the end of the block. The data is used by <API key> to ensure safety. static MachineBasicBlock::iterator <API key>(MachineBasicBlock *MBB, const TargetInstrInfo *TII, const TargetRegisterInfo *TRI, SmallSet<unsigned,4> &Uses, SmallSet<unsigned,4> &Defs) { MachineBasicBlock::iterator Loc = MBB->getFirstTerminator(); if (!TII-><API key>(Loc)) return MBB->end(); for (unsigned i = 0, e = Loc->getNumOperands(); i != e; ++i) { const MachineOperand &MO = Loc->getOperand(i); if (!MO.isReg()) continue; unsigned Reg = MO.getReg(); if (!Reg) continue; if (MO.isUse()) { for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI) Uses.insert(*AI); } else { if (!MO.isDead()) // Don't try to hoist code in the rare case the terminator defines a // register that is later used. return MBB->end(); // If the terminator defines a register, make sure we don't hoist // the instruction whose def might be clobbered by the terminator. for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI) Defs.insert(*AI); } } if (Uses.empty()) return Loc; if (Loc == MBB->begin()) return MBB->end(); // The terminator is probably a conditional branch, try not to separate the // branch from condition setting instruction. MachineBasicBlock::iterator PI = Loc; --PI; while (PI != MBB->begin() && PI->isDebugValue()) --PI; bool IsDef = false; for (unsigned i = 0, e = PI->getNumOperands(); !IsDef && i != e; ++i) { const MachineOperand &MO = PI->getOperand(i); // If PI has a regmask operand, it is probably a call. Separate away. if (MO.isRegMask()) return Loc; if (!MO.isReg() || MO.isUse()) continue; unsigned Reg = MO.getReg(); if (!Reg) continue; if (Uses.count(Reg)) IsDef = true; } if (!IsDef) // The condition setting instruction is not just before the conditional // branch. return Loc; // Be conservative, don't insert instruction above something that may have // side-effects. And since it's potentially bad to separate flag setting // instruction from the conditional branch, just abort the optimization // completely. // Also avoid moving code above predicated instruction since it's hard to // reason about register liveness with predicated instruction. bool DontMoveAcrossStore = true; if (!PI->isSafeToMove(TII, nullptr, DontMoveAcrossStore) || TII->isPredicated(PI)) return MBB->end(); // Find out what registers are live. Note this routine is ignoring other live // registers which are only used by instructions in successor blocks. for (unsigned i = 0, e = PI->getNumOperands(); i != e; ++i) { const MachineOperand &MO = PI->getOperand(i); if (!MO.isReg()) continue; unsigned Reg = MO.getReg(); if (!Reg) continue; if (MO.isUse()) { for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI) Uses.insert(*AI); } else { if (Uses.erase(Reg)) { for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid(); ++SubRegs) Uses.erase(*SubRegs); // Use sub-registers to be conservative } for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI) Defs.insert(*AI); } } return PI; } <API key> - If the successors of MBB has common instruction sequence at the start of the function, move the instructions before MBB terminator if it's legal. bool BranchFolder::<API key>(MachineBasicBlock *MBB) { MachineBasicBlock *TBB = nullptr, *FBB = nullptr; SmallVector<MachineOperand, 4> Cond; if (TII->AnalyzeBranch(*MBB, TBB, FBB, Cond, true) || !TBB || Cond.empty()) return false; if (!FBB) FBB = findFalseBlock(MBB, TBB); if (!FBB) // Malformed bcc? True and false blocks are the same? return false; // Restrict the optimization to cases where MBB is the only predecessor, // it is an obvious win. if (TBB->pred_size() > 1 || FBB->pred_size() > 1) return false; // Find a suitable position to hoist the common instructions to. Also figure // out which registers are used or defined by instructions from the insertion // point to the end of the block. SmallSet<unsigned, 4> Uses, Defs; MachineBasicBlock::iterator Loc = <API key>(MBB, TII, TRI, Uses, Defs); if (Loc == MBB->end()) return false; bool HasDups = false; SmallVector<unsigned, 4> LocalDefs; SmallSet<unsigned, 4> LocalDefsSet; MachineBasicBlock::iterator TIB = TBB->begin(); MachineBasicBlock::iterator FIB = FBB->begin(); MachineBasicBlock::iterator TIE = TBB->end(); MachineBasicBlock::iterator FIE = FBB->end(); while (TIB != TIE && FIB != FIE) { // Skip dbg_value instructions. These do not count. if (TIB->isDebugValue()) { while (TIB != TIE && TIB->isDebugValue()) ++TIB; if (TIB == TIE) break; } if (FIB->isDebugValue()) { while (FIB != FIE && FIB->isDebugValue()) ++FIB; if (FIB == FIE) break; } if (!TIB->isIdenticalTo(FIB, MachineInstr::CheckKillDead)) break; if (TII->isPredicated(TIB)) // Hard to reason about register liveness with predicated instruction. break; bool IsSafe = true; for (unsigned i = 0, e = TIB->getNumOperands(); i != e; ++i) { MachineOperand &MO = TIB->getOperand(i); // Don't attempt to hoist instructions with register masks. if (MO.isRegMask()) { IsSafe = false; break; } if (!MO.isReg()) continue; unsigned Reg = MO.getReg(); if (!Reg) continue; if (MO.isDef()) { if (Uses.count(Reg)) { // Avoid clobbering a register that's used by the instruction at // the point of insertion. IsSafe = false; break; } if (Defs.count(Reg) && !MO.isDead()) { // Don't hoist the instruction if the def would be clobber by the // instruction at the point insertion. FIXME: This is overly // conservative. It should be possible to hoist the instructions // in BB2 in the following example: // BB1: // r1, eflag = op1 r2, r3 // brcc eflag // BB2: // r1 = op2, ... // = op3, r1<kill> IsSafe = false; break; } } else if (!LocalDefsSet.count(Reg)) { if (Defs.count(Reg)) { // Use is defined by the instruction at the point of insertion. IsSafe = false; break; } if (MO.isKill() && Uses.count(Reg)) // Kills a register that's read by the instruction at the point of // insertion. Remove the kill marker. MO.setIsKill(false); } } if (!IsSafe) break; bool DontMoveAcrossStore = true; if (!TIB->isSafeToMove(TII, nullptr, DontMoveAcrossStore)) break; // Remove kills from LocalDefsSet, these registers had short live ranges. for (unsigned i = 0, e = TIB->getNumOperands(); i != e; ++i) { MachineOperand &MO = TIB->getOperand(i); if (!MO.isReg() || !MO.isUse() || !MO.isKill()) continue; unsigned Reg = MO.getReg(); if (!Reg || !LocalDefsSet.count(Reg)) continue; for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI) LocalDefsSet.erase(*AI); } // Track local defs so we can update liveins. for (unsigned i = 0, e = TIB->getNumOperands(); i != e; ++i) { MachineOperand &MO = TIB->getOperand(i); if (!MO.isReg() || !MO.isDef() || MO.isDead()) continue; unsigned Reg = MO.getReg(); if (!Reg) continue; LocalDefs.push_back(Reg); for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI) LocalDefsSet.insert(*AI); } HasDups = true; ++TIB; ++FIB; } if (!HasDups) return false; MBB->splice(Loc, TBB, TBB->begin(), TIB); FBB->erase(FBB->begin(), FIB); // Update livein's. for (unsigned i = 0, e = LocalDefs.size(); i != e; ++i) { unsigned Def = LocalDefs[i]; if (LocalDefsSet.count(Def)) { TBB->addLiveIn(Def); FBB->addLiveIn(Def); } } ++NumHoist; return true; }
#include "components/breakpad/app/breakpad_client.h" #include "base/files/file_path.h" #include "base/logging.h" namespace breakpad { namespace { BreakpadClient* g_client = NULL; } // namespace void SetBreakpadClient(BreakpadClient* client) { g_client = client; } BreakpadClient* GetBreakpadClient() { DCHECK(g_client); return g_client; } BreakpadClient::BreakpadClient() {} BreakpadClient::~BreakpadClient() {} void BreakpadClient::SetClientID(const std::string& client_id) { } #if defined(OS_WIN) bool BreakpadClient::<API key>( base::FilePath* crash_dir) { return false; } void BreakpadClient::<API key>(const base::FilePath& exe_path, base::string16* product_name, base::string16* version, base::string16* special_build, base::string16* channel_name) { } bool BreakpadClient::<API key>(base::string16* title, base::string16* message, bool* is_rtl_locale) { return false; } bool BreakpadClient::AboutToRestart() { return false; } bool BreakpadClient::<API key>(bool is_per_usr_install) { return false; } bool BreakpadClient::GetIsPerUserInstall(const base::FilePath& exe_path) { return true; } bool BreakpadClient::<API key>(bool is_per_user_install) { return false; } int BreakpadClient::<API key>() { return 0; } void BreakpadClient::<API key>() { } void BreakpadClient::<API key>(bool is_real_crash) { } #endif #if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_IOS) void BreakpadClient::<API key>(std::string* product_name, std::string* version) { } base::FilePath BreakpadClient::<API key>() { return base::FilePath(); } #endif bool BreakpadClient::<API key>(base::FilePath* crash_dir) { return false; } size_t BreakpadClient::RegisterCrashKeys() { return 0; } bool BreakpadClient::IsRunningUnattended() { return true; } bool BreakpadClient::<API key>() { return false; } #if defined(OS_WIN) || defined(OS_MACOSX) bool BreakpadClient::<API key>(bool* breakpad_enabled) { return false; } #endif #if defined(OS_ANDROID) int BreakpadClient::<API key>() { return 0; } #endif #if defined(OS_MACOSX) void BreakpadClient::<API key>(BreakpadRef breakpad) { } #endif bool BreakpadClient::<API key>(const std::string& process_type) { return false; } } // namespace breakpad
#include "media/mojo/services/<API key>.h" #include "base/bind.h" namespace media { <API key>::<API key>( interfaces::ProvisionFetcherPtr <API key>) : <API key>(std::move(<API key>)), weak_factory_(this) { DVLOG(1) << __FUNCTION__; } <API key>::~<API key>() {} // ProvisionFetcher implementation: void <API key>::Retrieve(const std::string& default_url, const std::string& request_data, const ResponseCB& response_cb) { DVLOG(1) << __FUNCTION__; <API key>->Retrieve( default_url, request_data, base::Bind(&<API key>::OnResponse, weak_factory_.GetWeakPtr(), response_cb)); } void <API key>::OnResponse(const ResponseCB& response_cb, bool success, const std::string& response) { response_cb.Run(success, response); } } // namespace media
#ifndef <API key> #define <API key> #include "../platform/WebString.h" #include "../platform/WebVector.h" #include "<API key>.h" namespace blink { struct <API key> { // If |multiSelect| is true, the dialog allows the user to select multiple files. bool multiSelect; // If |directory| is true, the dialog allows the user to select a directory. bool directory; // If |saveAs| is true, the dialog allows the user to select a possibly // non-existent file. This can be used for a "Save As" dialog. bool saveAs; // |title| is the title for a file chooser dialog. It can be an empty string. WebString title; // |initialValue| is a filename which the dialog should select by default. // It can be an empty string. WebString initialValue;
using System; using System.Collections.Generic; using System.Linq; using System.Web; using Orchard.ContentManagement.MetaData; using Orchard.Data.Migration; using Orchard.Environment.Extensions; namespace Orchard.Blogs.<API key>.Migrations { [OrchardFeature("Orchard.Blogs.<API key>")] public class Migrations : DataMigrationImpl { public int Create() { <API key>.AlterTypeDefinition("Blog", cfg => cfg .WithPart("LocalizationPart")); <API key>.AlterTypeDefinition("BlogPost", cfg => cfg .WithPart("LocalizationPart")); return 1; } } }
_CLC_OVERLOAD _CLC_DECL int atom_cmpxchg(volatile local int *p, int cmp, int val); _CLC_OVERLOAD _CLC_DECL unsigned int atom_cmpxchg(volatile local unsigned int *p, unsigned int cmp, unsigned int val);
// Use of this source code is governed by a BSD-style package worker import ( "bytes" "encoding/hex" "fmt" "strings" "time" "golang.org/x/net/context" mproto "github.com/youtube/vitess/go/mysql/proto" "github.com/youtube/vitess/go/sqltypes" "github.com/youtube/vitess/go/vt/key" "github.com/youtube/vitess/go/vt/logutil" myproto "github.com/youtube/vitess/go/vt/mysqlctl/proto" "github.com/youtube/vitess/go/vt/tabletserver/tabletconn" "github.com/youtube/vitess/go/vt/topo" "github.com/youtube/vitess/go/vt/topo/topoproto" pb "github.com/youtube/vitess/go/vt/proto/topodata" ) // QueryResultReader will stream rows towards the output channel. type QueryResultReader struct { Output <-chan *mproto.QueryResult Fields []mproto.Field conn tabletconn.TabletConn clientErrFn func() error } // <API key> creates a new QueryResultReader for // the provided tablet / sql query func <API key>(ctx context.Context, ts topo.Server, tabletAlias *pb.TabletAlias, sql string) (*QueryResultReader, error) { tablet, err := ts.GetTablet(ctx, tabletAlias) if err != nil { return nil, err } endPoint, err := topo.TabletEndPoint(tablet.Tablet) if err != nil { return nil, err } // use sessionId for now conn, err := tabletconn.GetDialer()(ctx, endPoint, tablet.Keyspace, tablet.Shard, pb.TabletType_UNKNOWN, *<API key>) if err != nil { return nil, err } sr, clientErrFn, err := conn.StreamExecute(ctx, sql, make(map[string]interface{}), 0) if err != nil { return nil, err } // read the columns, or grab the error cols, ok := <-sr if !ok { return nil, fmt.Errorf("Cannot read Fields for query '%v': %v", sql, clientErrFn()) } return &QueryResultReader{ Output: sr, Fields: cols.Fields, conn: conn, clientErrFn: clientErrFn, }, nil } // orderedColumns returns the list of columns: // - first the primary key columns in the right order // - then the rest of the columns func orderedColumns(tableDefinition *myproto.TableDefinition) []string { result := make([]string, 0, len(tableDefinition.Columns)) result = append(result, tableDefinition.PrimaryKeyColumns...) for _, column := range tableDefinition.Columns { found := false for _, primaryKey := range tableDefinition.PrimaryKeyColumns { if primaryKey == column { found = true break } } if !found { result = append(result, column) } } return result } // <API key> returns a 64 bits hex number as a string // (in the form of 0x0123456789abcdef) from the provided keyspaceId func <API key>(keyspaceID []byte) string { hex := hex.EncodeToString(keyspaceID) return "0x" + hex + strings.Repeat("0", 16-len(hex)) } // TableScan returns a QueryResultReader that gets all the rows from a // table, ordered by Primary Key. The returned columns are ordered // with the Primary Key columns in front. func TableScan(ctx context.Context, log logutil.Logger, ts topo.Server, tabletAlias *pb.TabletAlias, tableDefinition *myproto.TableDefinition) (*QueryResultReader, error) { sql := fmt.Sprintf("SELECT %v FROM %v ORDER BY %v", strings.Join(orderedColumns(tableDefinition), ", "), tableDefinition.Name, strings.Join(tableDefinition.PrimaryKeyColumns, ", ")) log.Infof("SQL query for %v/%v: %v", topoproto.TabletAliasString(tabletAlias), tableDefinition.Name, sql) return <API key>(ctx, ts, tabletAlias, sql) } // TableScanByKeyRange returns a QueryResultReader that gets all the // rows from a table that match the supplied KeyRange, ordered by // Primary Key. The returned columns are ordered with the Primary Key // columns in front. func TableScanByKeyRange(ctx context.Context, log logutil.Logger, ts topo.Server, tabletAlias *pb.TabletAlias, tableDefinition *myproto.TableDefinition, keyRange *pb.KeyRange, keyspaceIDType key.KeyspaceIdType) (*QueryResultReader, error) { where := "" if keyRange != nil { switch keyspaceIDType { case key.KIT_UINT64: if len(keyRange.Start) > 0 { if len(keyRange.End) > 0 { // have start & end where = fmt.Sprintf("WHERE keyspace_id >= %v AND keyspace_id < %v ", <API key>(keyRange.Start), <API key>(keyRange.End)) } else { // have start only where = fmt.Sprintf("WHERE keyspace_id >= %v ", <API key>(keyRange.Start)) } } else { if len(keyRange.End) > 0 { // have end only where = fmt.Sprintf("WHERE keyspace_id < %v ", <API key>(keyRange.End)) } } case key.KIT_BYTES: if len(keyRange.Start) > 0 { if len(keyRange.End) > 0 { // have start & end where = fmt.Sprintf("WHERE HEX(keyspace_id) >= '%v' AND HEX(keyspace_id) < '%v' ", hex.EncodeToString(keyRange.Start), hex.EncodeToString(keyRange.End)) } else { // have start only where = fmt.Sprintf("WHERE HEX(keyspace_id) >= '%v' ", hex.EncodeToString(keyRange.Start)) } } else { if len(keyRange.End) > 0 { // have end only where = fmt.Sprintf("WHERE HEX(keyspace_id) < '%v' ", hex.EncodeToString(keyRange.End)) } } default: return nil, fmt.Errorf("Unsupported KeyspaceIdType: %v", keyspaceIDType) } } sql := fmt.Sprintf("SELECT %v FROM %v %vORDER BY %v", strings.Join(orderedColumns(tableDefinition), ", "), tableDefinition.Name, where, strings.Join(tableDefinition.PrimaryKeyColumns, ", ")) log.Infof("SQL query for %v/%v: %v", topoproto.TabletAliasString(tabletAlias), tableDefinition.Name, sql) return <API key>(ctx, ts, tabletAlias, sql) } func (qrr *QueryResultReader) Error() error { return qrr.clientErrFn() } // Close closes the connection to the tablet. func (qrr *QueryResultReader) Close() { qrr.conn.Close() } // RowReader returns individual rows from a QueryResultReader type RowReader struct { queryResultReader *QueryResultReader currentResult *mproto.QueryResult currentIndex int } // NewRowReader returns a RowReader based on the QueryResultReader func NewRowReader(queryResultReader *QueryResultReader) *RowReader { return &RowReader{ queryResultReader: queryResultReader, } } // Next will return: // (row, nil) for the next row // (nil, nil) for EOF // (nil, error) if an error occurred func (rr *RowReader) Next() ([]sqltypes.Value, error) { if rr.currentResult == nil || rr.currentIndex == len(rr.currentResult.Rows) { var ok bool rr.currentResult, ok = <-rr.queryResultReader.Output if !ok { if err := rr.queryResultReader.Error(); err != nil { return nil, err } return nil, nil } rr.currentIndex = 0 } result := rr.currentResult.Rows[rr.currentIndex] rr.currentIndex++ return result, nil } // Fields returns the types for the rows func (rr *RowReader) Fields() []mproto.Field { return rr.queryResultReader.Fields } // Drain will empty the RowReader and return how many rows we got func (rr *RowReader) Drain() (int, error) { count := 0 for { row, err := rr.Next() if err != nil { return 0, err } if row == nil { return count, nil } count++ } } // DiffReport has the stats for a diff job type DiffReport struct { // general stats processedRows int // stats about the diff matchingRows int mismatchedRows int extraRowsLeft int extraRowsRight int // QPS variables and stats startingTime time.Time processingQPS int } // HasDifferences returns true if the diff job recorded any difference func (dr *DiffReport) HasDifferences() bool { return dr.mismatchedRows > 0 || dr.extraRowsLeft > 0 || dr.extraRowsRight > 0 } // ComputeQPS fills in processingQPS func (dr *DiffReport) ComputeQPS() { if dr.processedRows > 0 { dr.processingQPS = int(time.Duration(dr.processedRows) * time.Second / time.Now().Sub(dr.startingTime)) } } func (dr *DiffReport) String() string { return fmt.Sprintf("DiffReport{%v processed, %v matching, %v mismatched, %v extra left, %v extra right, %v q/s}", dr.processedRows, dr.matchingRows, dr.mismatchedRows, dr.extraRowsLeft, dr.extraRowsRight, dr.processingQPS) } // RowsEqual returns the index of the first different fields, or -1 if // both rows are the same func RowsEqual(left, right []sqltypes.Value) int { for i, l := range left { if !bytes.Equal(l.Raw(), right[i].Raw()) { return i } } return -1 } // CompareRows returns: // -1 if left is smaller than right // 0 if left and right are equal // +1 if left is bigger than right // TODO: This can panic if types for left and right don't match. func CompareRows(fields []mproto.Field, compareCount int, left, right []sqltypes.Value) (int, error) { for i := 0; i < compareCount; i++ { lv, err := mproto.Convert(fields[i], left[i]) if err != nil { return 0, err } rv, err := mproto.Convert(fields[i], right[i]) if err != nil { return 0, err } switch l := lv.(type) { case int64: r := rv.(int64) if l < r { return -1, nil } else if l > r { return 1, nil } case uint64: r := rv.(uint64) if l < r { return -1, nil } else if l > r { return 1, nil } case float64: r := rv.(float64) if l < r { return -1, nil } else if l > r { return 1, nil } case []byte: r := rv.([]byte) return bytes.Compare(l, r), nil default: return 0, fmt.Errorf("Unsuported type %T returned by mysql.proto.Convert", l) } } return 0, nil } // RowDiffer will consume rows on both sides, and compare them. // It assumes left and right are sorted by ascending primary key. // it will record errors if extra rows exist on either side. type RowDiffer struct { left *RowReader right *RowReader pkFieldCount int } // NewRowDiffer returns a new RowDiffer func NewRowDiffer(left, right *QueryResultReader, tableDefinition *myproto.TableDefinition) (*RowDiffer, error) { if len(left.Fields) != len(right.Fields) { return nil, fmt.Errorf("Cannot diff inputs with different types") } for i, field := range left.Fields { if field.Type != right.Fields[i].Type { return nil, fmt.Errorf("Cannot diff inputs with different types: field %v types are %v and %v", i, field.Type, right.Fields[i].Type) } } return &RowDiffer{ left: NewRowReader(left), right: NewRowReader(right), pkFieldCount: len(tableDefinition.PrimaryKeyColumns), }, nil } // Go runs the diff. If there is no error, it will drain both sides. // If an error occurs, it will just return it and stop. func (rd *RowDiffer) Go(log logutil.Logger) (dr DiffReport, err error) { dr.startingTime = time.Now() defer dr.ComputeQPS() var left []sqltypes.Value var right []sqltypes.Value advanceLeft := true advanceRight := true for { if advanceLeft { left, err = rd.left.Next() if err != nil { return } advanceLeft = false } if advanceRight { right, err = rd.right.Next() if err != nil { return } advanceRight = false } dr.processedRows++ if left == nil { // no more rows from the left if right == nil { // no more rows from right either, we're done return } // drain right, update count if count, err := rd.right.Drain(); err != nil { return dr, err } else { dr.extraRowsRight += 1 + count } return } if right == nil { // no more rows from the right // we know we have rows from left, drain, update count if count, err := rd.left.Drain(); err != nil { return dr, err } else { dr.extraRowsLeft += 1 + count } return } // we have both left and right, compare f := RowsEqual(left, right) if f == -1 { // rows are the same, next dr.matchingRows++ advanceLeft = true advanceRight = true continue } if f >= rd.pkFieldCount { // rows have the same primary key, only content is different if dr.mismatchedRows < 10 { log.Errorf("Different content %v in same PK: %v != %v", dr.mismatchedRows, left, right) } dr.mismatchedRows++ advanceLeft = true advanceRight = true continue } // have to find the 'smallest' raw and advance it c, err := CompareRows(rd.left.Fields(), rd.pkFieldCount, left, right) if err != nil { return dr, err } if c < 0 { if dr.extraRowsLeft < 10 { log.Errorf("Extra row %v on left: %v", dr.extraRowsLeft, left) } dr.extraRowsLeft++ advanceLeft = true continue } else if c > 0 { if dr.extraRowsRight < 10 { log.Errorf("Extra row %v on right: %v", dr.extraRowsRight, right) } dr.extraRowsRight++ advanceRight = true continue } // After looking at primary keys more carefully, // they're the same. Logging a regular difference // then, and advancing both. if dr.mismatchedRows < 10 { log.Errorf("Different content %v in same PK: %v != %v", dr.mismatchedRows, left, right) } dr.mismatchedRows++ advanceLeft = true advanceRight = true } } // RowSubsetDiffer will consume rows on both sides, and compare them. // It assumes superset and subset are sorted by ascending primary key. // It will record errors in DiffReport.extraRowsRight if extra rows // exist on the subset side, and DiffReport.extraRowsLeft will // always be zero. type RowSubsetDiffer struct { superset *RowReader subset *RowReader pkFieldCount int } // NewRowSubsetDiffer returns a new RowSubsetDiffer func NewRowSubsetDiffer(superset, subset *QueryResultReader, pkFieldCount int) (*RowSubsetDiffer, error) { if len(superset.Fields) != len(subset.Fields) { return nil, fmt.Errorf("Cannot diff inputs with different types") } for i, field := range superset.Fields { if field.Type != subset.Fields[i].Type { return nil, fmt.Errorf("Cannot diff inputs with different types: field %v types are %v and %v", i, field.Type, subset.Fields[i].Type) } } return &RowSubsetDiffer{ superset: NewRowReader(superset), subset: NewRowReader(subset), pkFieldCount: pkFieldCount, }, nil } // Go runs the diff. If there is no error, it will drain both sides. // If an error occurs, it will just return it and stop. func (rd *RowSubsetDiffer) Go(log logutil.Logger) (dr DiffReport, err error) { dr.startingTime = time.Now() defer dr.ComputeQPS() var superset []sqltypes.Value var subset []sqltypes.Value advanceSuperset := true advanceSubset := true for { if advanceSuperset { superset, err = rd.superset.Next() if err != nil { return } advanceSuperset = false } if advanceSubset { subset, err = rd.subset.Next() if err != nil { return } advanceSubset = false } dr.processedRows++ if superset == nil { // no more rows from the superset if subset == nil { // no more rows from subset either, we're done return } // drain subset, update count if count, err := rd.subset.Drain(); err != nil { return dr, err } else { dr.extraRowsRight += 1 + count } return } if subset == nil { // no more rows from the subset // we know we have rows from superset, drain if _, err := rd.superset.Drain(); err != nil { return dr, err } return } // we have both superset and subset, compare f := RowsEqual(superset, subset) if f == -1 { // rows are the same, next dr.matchingRows++ advanceSuperset = true advanceSubset = true continue } if f >= rd.pkFieldCount { // rows have the same primary key, only content is different if dr.mismatchedRows < 10 { log.Errorf("Different content %v in same PK: %v != %v", dr.mismatchedRows, superset, subset) } dr.mismatchedRows++ advanceSuperset = true advanceSubset = true continue } // have to find the 'smallest' raw and advance it c, err := CompareRows(rd.superset.Fields(), rd.pkFieldCount, superset, subset) if err != nil { return dr, err } if c < 0 { advanceSuperset = true continue } else if c > 0 { if dr.extraRowsRight < 10 { log.Errorf("Extra row %v on subset: %v", dr.extraRowsRight, subset) } dr.extraRowsRight++ advanceSubset = true continue } // After looking at primary keys more carefully, // they're the same. Logging a regular difference // then, and advancing both. if dr.mismatchedRows < 10 { log.Errorf("Different content %v in same PK: %v != %v", dr.mismatchedRows, superset, subset) } dr.mismatchedRows++ advanceSuperset = true advanceSubset = true } }
'use strict'; // Raw var _ = require('lodash'); var inherits = require('inherits'); var EventEmitter = require('events').EventEmitter; function Raw(sql, bindings) { if (sql && sql.toSQL) { var output = sql.toSQL(); sql = output.sql; bindings = output.bindings; } this.sql = sql + ''; this.bindings = _.isArray(bindings) ? bindings : bindings ? [bindings] : []; this.interpolateBindings(); this._debug = void 0; this._transacting = void 0; } inherits(Raw, EventEmitter); // Wraps the current sql with `before` and `after`. Raw.prototype.wrap = function(before, after) { this.sql = before + this.sql + after; return this; }; // Calls `toString` on the Knex object. Raw.prototype.toString = function() { return this.toQuery(); }; // Ensure all Raw / builder bindings are mixed-in to the ? placeholders // as appropriate. Raw.prototype.interpolateBindings = function() { var replacements = []; this.bindings = _.reduce(this.bindings, function(accum, param, index) { var innerBindings = [param]; if (param && param.toSQL) { var result = this.splicer(param, index); innerBindings = result.bindings; replacements.push(result.replacer); } return accum.concat(innerBindings); }, [], this); // we run this in reverse order, because ? concats earlier in the // query string will disrupt indices for later ones this.sql = _.reduce(replacements.reverse(), function(accum, fn) { return fn(accum); }, this.sql.split('?')).join('?'); }; // Returns a replacer function that splices into the i'th // ? in the sql string the inner raw's sql, // and the bindings associated with it Raw.prototype.splicer = function(raw, i) { var obj = raw.toSQL(); // the replacer function assumes that the sql has been // already sql.split('?') and will be arr.join('?') var replacer = function(arr) { arr[i] = arr[i] + obj.sql + arr[i + 1]; arr.splice(i + 1, 1); return arr; }; return { replacer: replacer, bindings: obj.bindings }; }; // Returns the raw sql for the query. Raw.prototype.toSQL = function() { return { sql: this.sql, method: 'raw', bindings: this.bindings }; }; // Allow the `Raw` object to be utilized with full access to the relevant // promise API. require('./interface')(Raw); module.exports = Raw;
// Type definitions for eetase 4.0 import AsyncStreamEmitter = require('<API key>'); declare function eetase<T>(object: T): AsyncStreamEmitter<any> & T; export = eetase;
from ctypes import c_uint, byref from django.contrib.gis.geos.error import GEOSIndexError from django.contrib.gis.geos.geometry import GEOSGeometry from django.contrib.gis.geos.libgeos import get_pointer_arr, GEOM_PTR from django.contrib.gis.geos.linestring import LinearRing from django.contrib.gis.geos import prototypes as capi class Polygon(GEOSGeometry): _minlength = 1 def __init__(self, *args, **kwargs): """ Initializes on an exterior ring and a sequence of holes (both instances may be either LinearRing instances, or a tuple/list that may be constructed into a LinearRing). Examples of initialization, where shell, hole1, and hole2 are valid LinearRing geometries: poly = Polygon(shell, hole1, hole2) poly = Polygon(shell, (hole1, hole2)) Example where a tuple parameters are used: poly = Polygon(((0, 0), (0, 10), (10, 10), (0, 10), (0, 0)), ((4, 4), (4, 6), (6, 6), (6, 4), (4, 4))) """ if not args: raise TypeError('Must provide at least one LinearRing, or a tuple, to initialize a Polygon.') # Getting the ext_ring and init_holes parameters from the argument list ext_ring = args[0] init_holes = args[1:] n_holes = len(init_holes) # If initialized as Polygon(shell, (LinearRing, LinearRing)) [for <API key>] if n_holes == 1 and isinstance(init_holes[0], (tuple, list)): if len(init_holes[0]) == 0: init_holes = () n_holes = 0 elif isinstance(init_holes[0][0], LinearRing): init_holes = init_holes[0] n_holes = len(init_holes) polygon = self._create_polygon(n_holes + 1, (ext_ring,) + init_holes) super(Polygon, self).__init__(polygon, **kwargs) def __iter__(self): "Iterates over each ring in the polygon." for i in xrange(len(self)): yield self[i] def __len__(self): "Returns the number of rings in this Polygon." return self.num_interior_rings + 1 @classmethod def from_bbox(cls, bbox): "Constructs a Polygon from a bounding box (4-tuple)." x0, y0, x1, y1 = bbox return GEOSGeometry( 'POLYGON((%s %s, %s %s, %s %s, %s %s, %s %s))' % ( x0, y0, x0, y1, x1, y1, x1, y0, x0, y0) ) These routines are needed for list-like operation w/ListMixin def _create_polygon(self, length, items): # Instantiate LinearRing objects if necessary, but don't clone them yet # _construct_ring will throw a TypeError if a parameter isn't a valid ring # If we cloned the pointers here, we wouldn't be able to clean up # in case of error. rings = [] for r in items: if isinstance(r, GEOM_PTR): rings.append(r) else: rings.append(self._construct_ring(r)) shell = self._clone(rings.pop(0)) n_holes = length - 1 if n_holes: holes = get_pointer_arr(n_holes) for i, r in enumerate(rings): holes[i] = self._clone(r) holes_param = byref(holes) else: holes_param = None return capi.create_polygon(shell, holes_param, c_uint(n_holes)) def _clone(self, g): if isinstance(g, GEOM_PTR): return capi.geom_clone(g) else: return capi.geom_clone(g.ptr) def _construct_ring(self, param, msg='Parameter must be a sequence of LinearRings or objects that can initialize to LinearRings'): "Helper routine for trying to construct a ring from the given parameter." if isinstance(param, LinearRing): return param try: ring = LinearRing(param) return ring except TypeError: raise TypeError(msg) def _set_list(self, length, items): # Getting the current pointer, replacing with the newly constructed # geometry, and destroying the old geometry. prev_ptr = self.ptr srid = self.srid self.ptr = self._create_polygon(length, items) if srid: self.srid = srid capi.destroy_geom(prev_ptr) def <API key>(self, index): """ Returns the ring at the specified index. The first index, 0, will always return the exterior ring. Indices > 0 will return the interior ring at the given index (e.g., poly[1] and poly[2] would return the first and second interior ring, respectively). CAREFUL: Internal/External are not the same as Interior/Exterior! <API key> returns a pointer from the existing geometries for use internally by the object's methods. <API key> returns a clone of the same geometry for use by external code. """ if index == 0: return capi.get_extring(self.ptr) else: # Getting the interior ring, have to subtract 1 from the index. return capi.get_intring(self.ptr, index-1) def <API key>(self, index): return GEOSGeometry(capi.geom_clone(self.<API key>(index)), srid=self.srid) _set_single = GEOSGeometry._set_single_rebuild <API key> = GEOSGeometry.<API key> @property def num_interior_rings(self): "Returns the number of interior rings." # Getting the number of rings return capi.get_nrings(self.ptr) def _get_ext_ring(self): "Gets the exterior ring of the Polygon." return self[0] def _set_ext_ring(self, ring): "Sets the exterior ring of the Polygon." self[0] = ring # Properties for the exterior ring/shell. exterior_ring = property(_get_ext_ring, _set_ext_ring) shell = exterior_ring @property def tuple(self): "Gets the tuple for each ring in this Polygon." return tuple([self[i].tuple for i in xrange(len(self))]) coords = tuple @property def kml(self): "Returns the KML representation of this Polygon." inner_kml = ''.join(["<innerBoundaryIs>%s</innerBoundaryIs>" % self[i+1].kml for i in xrange(self.num_interior_rings)]) return "<Polygon><outerBoundaryIs>%s</outerBoundaryIs>%s</Polygon>" % (self[0].kml, inner_kml)
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; namespace Tests.Expressions { partial class ExpressionCatalog { private static IEnumerable<Expression> ArrayIndex() { var arr1 = Expression.Constant(new[] { 2, 3, 5 }); for (var i = -1; i <= 3; i++) { yield return Expression.ArrayIndex(arr1, Expression.Constant(i)); } var arr2 = Expression.Constant(new[,] { { 2, 3, 5 }, { 7, 11, 13 } }); for (var i = -1; i <= 2; i++) { for (var j = -1; i <= 3; i++) { yield return Expression.ArrayIndex(arr2, Expression.Constant(i), Expression.Constant(j)); } } } private static IEnumerable<KeyValuePair<ExpressionType, Expression>> ArrayIndex_WithLog() { var arr1 = Expression.Constant(new[] { 2, 3, 5 }); var arr2 = Expression.Constant(new[,] { { 2, 3, 5 }, { 7, 11, 13 } }); yield return WithLog(ExpressionType.ArrayIndex, (log, summary) => { var valueParam = Expression.Parameter(typeof(int)); var toStringTemplate = (Expression<Func<int, string>>)(x => x.ToString()); var concatTemplate = (Expression<Func<string, string, string>>)((s1, s2) => s1 + s2); return Expression.Block( new[] { valueParam }, Expression.Assign( valueParam, Expression.ArrayIndex(arr1, ReturnWithLog(log, 1)) ), Expression.Invoke( concatTemplate, Expression.Invoke(toStringTemplate, valueParam), summary ) ); }); yield return WithLog(ExpressionType.ArrayIndex, (log, summary) => { var valueParam = Expression.Parameter(typeof(int)); var toStringTemplate = (Expression<Func<int, string>>)(x => x.ToString()); var concatTemplate = (Expression<Func<string, string, string>>)((s1, s2) => s1 + s2); return Expression.Block( new[] { valueParam }, Expression.Assign( valueParam, Expression.ArrayIndex(arr2, ReturnWithLog(log, 1), ReturnWithLog(log, 2)) ), Expression.Invoke( concatTemplate, Expression.Invoke(toStringTemplate, valueParam), summary ) ); }); } private static IEnumerable<Expression> ArrayAccess() { var arr1 = Expression.Constant(new[] { 2, 3, 5 }); for (var i = -1; i <= 3; i++) { yield return Expression.ArrayAccess(arr1, Expression.Constant(i)); } var arr2 = Expression.Constant(new[,] { { 2, 3, 5 }, { 7, 11, 13 } }); for (var i = -1; i <= 2; i++) { for (var j = -1; i <= 3; i++) { yield return Expression.ArrayAccess(arr2, Expression.Constant(i), Expression.Constant(j)); } } } private static IEnumerable<KeyValuePair<ExpressionType, Expression>> ArrayAccess_WithLog() { var arr1 = Expression.Constant(new[] { 2, 3, 5 }); var arr2 = Expression.Constant(new[,] { { 2, 3, 5 }, { 7, 11, 13 } }); yield return WithLog(ExpressionType.Index, (log, summary) => { var valueParam = Expression.Parameter(typeof(int)); var toStringTemplate = (Expression<Func<int, string>>)(x => x.ToString()); var concatTemplate = (Expression<Func<string, string, string>>)((s1, s2) => s1 + s2); return Expression.Block( new[] { valueParam }, Expression.Assign( valueParam, Expression.ArrayAccess(arr1, ReturnWithLog(log, 1)) ), Expression.Invoke( concatTemplate, Expression.Invoke(toStringTemplate, valueParam), summary ) ); }); yield return WithLog(ExpressionType.Index, (log, summary) => { var valueParam = Expression.Parameter(typeof(int)); var toStringTemplate = (Expression<Func<int, string>>)(x => x.ToString()); var concatTemplate = (Expression<Func<string, string, string>>)((s1, s2) => s1 + s2); return Expression.Block( new[] { valueParam }, Expression.Assign( valueParam, Expression.ArrayAccess(arr2, ReturnWithLog(log, 1), ReturnWithLog(log, 2)) ), Expression.Invoke( concatTemplate, Expression.Invoke(toStringTemplate, valueParam), summary ) ); }); } private static IEnumerable<Expression> ArrayLength() { yield return Expression.ArrayLength(Expression.Constant(new object[0])); yield return Expression.ArrayLength(Expression.Constant(new int[1])); yield return Expression.ArrayLength(Expression.Constant(new string[42])); } private static IEnumerable<KeyValuePair<ExpressionType, Expression>> NewArrayInit() { var expr = (Expression<Func<int>>)(() => new[] { 2, 3, 5, 7 }.Sum()); yield return new KeyValuePair<ExpressionType, Expression>(ExpressionType.NewArrayInit, expr.Body); } private static IEnumerable<KeyValuePair<ExpressionType, Expression>> <API key>() { yield return WithLog(ExpressionType.NewArrayInit, (log, summary) => { var valueParam = Expression.Parameter(typeof(int[])); var newArrTemplate = (Expression<Func<int[]>>)(() => new[] { 2, 3, 5, 7 }); var toStringTemplate = (Expression<Func<int[], string>>)(xs => string.Join(", ", xs)); var concatTemplate = (Expression<Func<string, string, string>>)((s1, s2) => s1 + s2); return Expression.Block( new[] { valueParam }, Expression.Assign( valueParam, Expression.Invoke( ReturnAllConstants(log, newArrTemplate) ) ), Expression.Invoke( concatTemplate, Expression.Invoke(toStringTemplate, valueParam), summary ) ); }); } private static IEnumerable<Expression> NewArrayBounds() { foreach (var e in new[] { Expression.NewArrayBounds(typeof(int), Expression.Constant(-1)), Expression.NewArrayBounds(typeof(int), Expression.Constant(0)), Expression.NewArrayBounds(typeof(int), Expression.Constant(1), Expression.Constant(-1)), Expression.NewArrayBounds(typeof(int), Expression.Constant(1), Expression.Constant(0)), }) { yield return e; } } private static IEnumerable<KeyValuePair<ExpressionType, Expression>> <API key>() { yield return WithLog(ExpressionType.NewArrayBounds, (log, summary) => { var valueParam = Expression.Parameter(typeof(int[])); var toStringTemplate = (Expression<Func<int[], string>>)(xs => string.Join(", ", xs)); var concatTemplate = (Expression<Func<string, string, string>>)((s1, s2) => s1 + s2); return Expression.Block( new[] { valueParam }, Expression.Assign( valueParam, Expression.NewArrayBounds( typeof(int), ReturnWithLog(log, 1) ) ), Expression.Invoke( concatTemplate, Expression.Invoke(toStringTemplate, valueParam), summary ) ); }); yield return WithLog(ExpressionType.NewArrayBounds, (log, summary) => { var valueParam = Expression.Parameter(typeof(int[,])); var toStringTemplate = (Expression<Func<int[,], string>>)(xs => string.Join(", ", xs)); var concatTemplate = (Expression<Func<string, string, string>>)((s1, s2) => s1 + s2); return Expression.Block( new[] { valueParam }, Expression.Assign( valueParam, Expression.NewArrayBounds( typeof(int), ReturnWithLog(log, 1), ReturnWithLog(log, 2) ) ), Expression.Invoke( concatTemplate, Expression.Invoke(toStringTemplate, valueParam), summary ) ); }); } } }
import { CipherSuite } from './http'; export interface Options { /** Maximum parallel `http.batch()` connections per VU. */ batch?: number; /** Maximum parallel `http.batch()` host connections per VU. */ batchPerHost?: number; /** Blacklist IP ranges from being called. */ blacklistIPs?: string[]; /** Blacklist hostnames from being called. Wildcards are supported. */ blockHostnames?: string[]; /** Discard response bodies. */ <API key>?: boolean; dns?: { /** 0, inf, or any time duration(60s, 5m30s, 10m, 2h). */ ttl: string; select: 'first' | 'random' | 'roundRobin'; policy: 'preferIPv4' | 'preferIPv6' | 'onlyIPv4' | 'onlyIPv6' | 'any'; }; /** Test duration. */ duration?: string; executionSegment?: string; <API key>?: string; /** Third party collector configuration. */ ext?: { [name: string]: CollectorOptions }; /** Static hostname mapping. */ hosts?: { [name: string]: string }; /** Log all HTTP requests and responses. */ httpDebug?: string; /** Disable TLS verification. Insecure. */ <API key>?: boolean; /** Iterations to execute. */ iterations?: number; /** Persist the k6 process after test completion. */ linger?: boolean; /** Maximum HTTP redirects to follow. */ maxRedirects?: number; /** Minimum test iteration duration. */ <API key>?: string; /** Disable keepalive connections. */ noConnectionReuse?: boolean; /** This disables the default behavior of resetting the cookie jar after each VU iteration. If it's enabled, saved cookies will be persisted across VU iterations.. */ noCookiesReset?: boolean; /** Disable usage reports. */ noUsageReport?: boolean; /** Disable cross-VU TCP connection reuse. */ noVUConnectionReuse?: boolean; /** Start test in paused state. */ paused?: boolean; /** Maximum requests per second across all VUs. */ rps?: number; /** Scenario specifications. */ scenarios?: { [name: string]: Scenario}; /** Setup function timeout. */ setupTimeout?: string; /** Test stage specifications. Program of target VU stages. */ stages?: Stage[]; /** Define stats for trend metrics. */ summaryTrendStats?: string[]; /** Which system tags to include in collected metrics. */ systemTags?: string[]; /** Tags to set test wide across all metrics. */ tags?: { [name: string]: string }; /** Teardown function timeout. */ teardownTimeout?: string; /** Threshold specifications. Defines pass and fail conditions. */ thresholds?: { [name: string]: Threshold[] }; /** Throw error on failed HTTP request. */ throw?: boolean; /** TLS client certificates. */ tlsAuth?: Certificate[]; /** Allowed TLS cipher suites. */ tlsCipherSuites?: CipherSuite[]; /** Allowed TLS version. Use `http.SSL_*` `http.TLS_*` constants. */ tlsVersion?: string | { min: string; max: string }; /** User agent string to include in HTTP requests. */ userAgent?: string; /** Number of VUs to run concurrently. */ vus?: number; /** Maximum VUs. Preallocates VUs to enable faster scaling. */ vusMax?: number; } /** * Third party collector configuration. */ export interface CollectorOptions { [name: string]: any; } /** * Test stage. */ export interface Stage { /** Stage duration. */ duration: string; /** Target number of VUs. */ target: number; } export type Threshold = string | ObjectThreshold; export interface ObjectThreshold { /** Abort test if threshold violated. */ abortOnFail?: boolean; /** Duration to delay evaluation. Enables collecting additional metrics. */ delayAbortEval?: string; /** Threshold expression. */ threshold: string; } /** * TLS client certificate. */ export interface Certificate { /** PEM encoded certificate. */ cert: string; /** Domains certificate is valid for. */ domains: string[]; /** PEM encoded certificate key. */ key: string; } export type ExecutorOptions = "shared-iterations" | "per-vu-iterations" | "constant-vus" | "ramping-vus" | "<API key>" | "<API key>" | "<API key>"; export abstract class BaseScenario { /** * Executor type. Options available: * - `shared-iterations` * - `per-vu-iterations` * - `constant-vus` * - `ramping-vus` * - `<API key>` * - `<API key>` * - `<API key>` */ executor: ExecutorOptions; /** * Time offset since the start of the test, at which point this scenario should begin execution. * * Default value is 0s. */ startTime?: string; gracefulStop?: string; /** * Name of exported JS function to execute. * * The default value is "default". */ exec?: string; /** Environment variables specific to this scenario. */ env?: { [name: string]: string }; /** Tags specific to this scenario. */ tags?: { [name: string]: string }; } export interface <API key> extends BaseScenario { executor: "shared-iterations"; /** * Number of VUs to run concurrently. * * The default value is 1. */ vus?: number; /** * Number of iterations to execute across all VUs. * * The default value is 1. */ iterations?: number; /** * Maximum scenario duration before it's forcibly stopped (excluding gracefulStop). * * The default value is 10m. */ maxDuration?: string; } export interface <API key> extends BaseScenario { executor: "per-vu-iterations"; /** * Number of VUs to run concurrently. * * The default value is 1. */ vus?: number; /** * Number of iterations to execute across per VU. * * The default value is 1. */ iterations?: number; /** * Maximum scenario duration before it's forcibly stopped (excluding gracefulStop). * * The default value is 10m. */ maxDuration?: string; } export interface ConstantVUsScenario extends BaseScenario { executor: "constant-vus"; /** * Number of VUs to run concurrently. * * The default value is 1. */ vus?: number; /** * Total scenario duration (excluding `gracefulStop`) */ duration: string; } export interface RampingVUsScenario extends BaseScenario { executor: "ramping-vus"; /** Array of objects that specify the number of VUs to ramp up or down to. */ stages: Stage[]; /** * Number of VUs to run at test start. * * The default value is 1. */ startVUs?: number; /** * Time to wait for an already started iteration to finish before stopping it during a ramp down. * * The default value is 30s. */ gracefulRampDown?: string; } export interface <API key> extends BaseScenario { executor: "<API key>"; /** Total scenario duration (excluding `gracefulStop`) */ duration: string; /** Number of iterations to execute each `timeUnit` period. */ rate: number; /** * Period of time to apply the `rate` value. * * The default value is 1s. */ timeUnit?: string; /** Number of VUs to pre-allocate before test start in order to preserve runtime resources. */ preAllocatedVUs: number; /** * Maximum number of VUs to allow during the test run. * * The default value is the value of the `preAllocatedVUs` option. */ maxVUs?: number; } export interface <API key> extends BaseScenario { executor: "<API key>"; /** Maximum number of VUs to allow during the test run. */ maxVUs?: number; /** Array of objects that specify the number of iterations to ramp up or down to. */ stages: Stage[]; /** Number of iterations to execute each `timeUnit` period at test start. */ startRate?: number; /** * Period of time to apply the `startRate` the `stages` target value.. * * The default value is 1s. */ timeUnit?: string; /** Number of VUs to pre-allocate before test start in order to preserve runtime resources. */ preAllocatedVUs: number; } export interface <API key> extends BaseScenario { executor: "<API key>"; /** * Number of VUs to run concurrently. * * The default value is 1. */ vus?: number; /** Total scenario duration (excluding `gracefulStop`) */ duration: string; /** Maximum number of VUs to allow during the test run. */ maxVUs?: number; } export type Scenario = <API key> | <API key> | ConstantVUsScenario | RampingVUsScenario | <API key> | <API key> | <API key>;
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using AutoMapper; using umbraco.interfaces; using Umbraco.Core; using Umbraco.Core.CodeAnnotations; using Umbraco.Core.Models; using Umbraco.Core.Models.Membership; using Umbraco.Core.Services; using Umbraco.Web.Models.ContentEditing; namespace Umbraco.Web.Models.Mapping { <summary> Converts an IUserGroup instance into a dictionary of permissions by category </summary> internal class <API key> : ValueResolver<IUserGroup, IDictionary<string, IEnumerable<Permission>>> { private readonly <API key> _textService; public <API key>(<API key> textService) { if (textService == null) throw new <API key>("textService"); _textService = textService; } protected override IDictionary<string, IEnumerable<Permission>> ResolveCore(IUserGroup source) { return ActionsResolver.Current.Actions .Where(x => x.<API key>) .Select(x => GetPermission(x, source)) .GroupBy(x => x.Category) .ToDictionary(x => x.Key, x => (IEnumerable<Permission>)x.ToArray()); } private Permission GetPermission(IAction action, IUserGroup source) { var result = new Permission(); var attribute = action.GetType().GetCustomAttribute<<API key>>(false); result.Category = attribute == null ? _textService.Localize(string.Format("actionCategories/{0}", Constants.Conventions.<API key>.OtherCategory)) : _textService.Localize(string.Format("actionCategories/{0}", attribute.Category)); result.Name = attribute == null || attribute.Name.IsNullOrWhiteSpace() ? _textService.Localize(string.Format("actions/{0}", action.Alias)) : attribute.Name; result.Description = _textService.Localize(String.Format("actionDescriptions/{0}", action.Alias)); result.Icon = action.Icon; result.Checked = source.Permissions != null && source.Permissions.Contains(action.Letter.ToString(CultureInfo.InvariantCulture)); result.PermissionCode = action.Letter.ToString(CultureInfo.InvariantCulture); return result; } } }
frappe.ui.form.on('Transaction Log', { });
// RCMessageTipLabel.h // iOS-IMKit #ifndef __RCTipLabel #define __RCTipLabel #import <UIKit/UIKit.h> /** * RCTipLabel */ @interface RCTipLabel : UILabel /** * UIEdgeInsets */ @property(nonatomic, assign) UIEdgeInsets marginInsets; /** * greyTipLabel * * @return return greyTipLabel */ + (instancetype)greyTipLabel; @end #endif
<?php use Carbon\Carbon; use Illuminate\Database\Connection; use Illuminate\Pagination\Paginator; use Illuminate\Database\Query\Builder; use Illuminate\Database\Eloquent\SoftDeletes; use Illuminate\Database\Capsule\Manager as DB; use Illuminate\Database\Eloquent\Model as Eloquent; use Illuminate\Database\Eloquent\SoftDeletingScope; class <API key> extends <API key> { public function setUp() { $db = new DB; $db->addConnection([ 'driver' => 'sqlite', 'database' => ':memory:', ]); $db->bootEloquent(); $db->setAsGlobal(); $this->createSchema(); } /** * Setup the database schema. * * @return void */ public function createSchema() { $this->schema()->create('users', function ($table) { $table->increments('id'); $table->integer('group_id')->nullable(); $table->string('email')->unique(); $table->timestamps(); $table->softDeletes(); }); $this->schema()->create('posts', function ($table) { $table->increments('id'); $table->integer('user_id'); $table->string('title'); $table->timestamps(); $table->softDeletes(); }); $this->schema()->create('comments', function ($table) { $table->increments('id'); $table->integer('owner_id')->nullable(); $table->string('owner_type')->nullable(); $table->integer('post_id'); $table->string('body'); $table->timestamps(); $table->softDeletes(); }); $this->schema()->create('addresses', function ($table) { $table->increments('id'); $table->integer('user_id'); $table->string('address'); $table->timestamps(); $table->softDeletes(); }); $this->schema()->create('groups', function ($table) { $table->increments('id'); $table->string('name'); $table->timestamps(); $table->softDeletes(); }); } /** * Tear down the database schema. * * @return void */ public function tearDown() { $this->schema()->drop('users'); $this->schema()->drop('posts'); $this->schema()->drop('comments'); } /** * Tests... */ public function <API key>() { $this->createUsers(); $users = SoftDeletesTestUser::all(); $this->assertCount(1, $users); $this->assertEquals(2, $users->first()->id); $this->assertNull(SoftDeletesTestUser::find(1)); } public function <API key>() { $this->createUsers(); $query = SoftDeletesTestUser::query()->toBase(); $this->assertInstanceOf(Builder::class, $query); $this->assertCount(1, $query->get()); } public function <API key>() { $this->createUsers(); $count = 0; $query = SoftDeletesTestUser::query(); $query->chunk(2, function ($user) use (&$count) { $count += count($user); }); $this->assertEquals(1, $count); $query = SoftDeletesTestUser::query(); $this->assertCount(1, $query->pluck('email')->all()); Paginator::currentPageResolver(function () { return 1; }); $query = SoftDeletesTestUser::query(); $this->assertCount(1, $query->paginate(2)->all()); $query = SoftDeletesTestUser::query(); $this->assertCount(1, $query->simplePaginate(2)->all()); $this->assertEquals(0, SoftDeletesTestUser::where('email', 'taylorotwell@gmail.com')->increment('id')); $this->assertEquals(0, SoftDeletesTestUser::where('email', 'taylorotwell@gmail.com')->decrement('id')); } public function <API key>() { $this->createUsers(); $this->assertCount(2, SoftDeletesTestUser::withTrashed()->get()); $this->assertInstanceOf(Eloquent::class, SoftDeletesTestUser::withTrashed()->find(1)); } public function <API key>() { $this->createUsers(); $this->assertInstanceOf(Carbon::class, SoftDeletesTestUser::withTrashed()->find(1)->deleted_at); $this->assertNull(SoftDeletesTestUser::find(2)->deleted_at); } public function <API key>() { $this->createUsers(); SoftDeletesTestUser::find(2)->forceDelete(); $users = SoftDeletesTestUser::withTrashed()->get(); $this->assertCount(1, $users); $this->assertEquals(1, $users->first()->id); } public function <API key>() { $this->createUsers(); $taylor = SoftDeletesTestUser::withTrashed()->find(1); $this->assertTrue($taylor->trashed()); $taylor->restore(); $users = SoftDeletesTestUser::all(); $this->assertCount(2, $users); $this->assertNull($users->find(1)->deleted_at); $this->assertNull($users->find(2)->deleted_at); } public function <API key>() { $this->createUsers(); $users = SoftDeletesTestUser::onlyTrashed()->get(); $this->assertCount(1, $users); $this->assertEquals(1, $users->first()->id); } public function <API key>() { $this->createUsers(); $users = SoftDeletesTestUser::withoutTrashed()->get(); $this->assertCount(1, $users); $this->assertEquals(2, $users->first()->id); $users = SoftDeletesTestUser::withTrashed()->withoutTrashed()->get(); $this->assertCount(1, $users); $this->assertEquals(2, $users->first()->id); } public function testFirstOrNew() { $this->createUsers(); $result = SoftDeletesTestUser::firstOrNew(['email' => 'taylorotwell@gmail.com']); $this->assertNull($result->id); $result = SoftDeletesTestUser::withTrashed()->firstOrNew(['email' => 'taylorotwell@gmail.com']); $this->assertEquals(1, $result->id); } public function testFindOrNew() { $this->createUsers(); $result = SoftDeletesTestUser::findOrNew(1); $this->assertNull($result->id); $result = SoftDeletesTestUser::withTrashed()->findOrNew(1); $this->assertEquals(1, $result->id); } public function testFirstOrCreate() { $this->createUsers(); $result = SoftDeletesTestUser::withTrashed()->firstOrCreate(['email' => 'taylorotwell@gmail.com']); $this->assertEquals('taylorotwell@gmail.com', $result->email); $this->assertCount(1, SoftDeletesTestUser::all()); $result = SoftDeletesTestUser::firstOrCreate(['email' => 'foo@bar.com']); $this->assertEquals('foo@bar.com', $result->email); $this->assertCount(2, SoftDeletesTestUser::all()); $this->assertCount(3, SoftDeletesTestUser::withTrashed()->get()); } public function testUpdateOrCreate() { $this->createUsers(); $result = SoftDeletesTestUser::updateOrCreate(['email' => 'foo@bar.com'], ['email' => 'bar@baz.com']); $this->assertEquals('bar@baz.com', $result->email); $this->assertCount(2, SoftDeletesTestUser::all()); $result = SoftDeletesTestUser::withTrashed()->updateOrCreate(['email' => 'taylorotwell@gmail.com'], ['email' => 'foo@bar.com']); $this->assertEquals('foo@bar.com', $result->email); $this->assertCount(2, SoftDeletesTestUser::all()); $this->assertCount(3, SoftDeletesTestUser::withTrashed()->get()); } public function <API key>() { $this->createUsers(); $abigail = SoftDeletesTestUser::where('email', 'abigailotwell@gmail.com')->first(); $abigail->address()->create(['address' => 'Laravel avenue 43']); // delete on builder $abigail->address()->delete(); $abigail = $abigail->fresh(); $this->assertNull($abigail->address); $this->assertEquals('Laravel avenue 43', $abigail->address()->withTrashed()->first()->address); // restore $abigail->address()->withTrashed()->restore(); $abigail = $abigail->fresh(); $this->assertEquals('Laravel avenue 43', $abigail->address->address); // delete on model $abigail->address->delete(); $abigail = $abigail->fresh(); $this->assertNull($abigail->address); $this->assertEquals('Laravel avenue 43', $abigail->address()->withTrashed()->first()->address); // force delete $abigail->address()->withTrashed()->forceDelete(); $abigail = $abigail->fresh(); $this->assertNull($abigail->address); } public function <API key>() { $this->createUsers(); $abigail = SoftDeletesTestUser::where('email', 'abigailotwell@gmail.com')->first(); $group = <API key>::create(['name' => 'admin']); $abigail->group()->associate($group); $abigail->save(); // delete on builder $abigail->group()->delete(); $abigail = $abigail->fresh(); $this->assertNull($abigail->group); $this->assertEquals('admin', $abigail->group()->withTrashed()->first()->name); // restore $abigail->group()->withTrashed()->restore(); $abigail = $abigail->fresh(); $this->assertEquals('admin', $abigail->group->name); // delete on model $abigail->group->delete(); $abigail = $abigail->fresh(); $this->assertNull($abigail->group); $this->assertEquals('admin', $abigail->group()->withTrashed()->first()->name); // force delete $abigail->group()->withTrashed()->forceDelete(); $abigail = $abigail->fresh(); $this->assertNull($abigail->group()->withTrashed()->first()); } public function <API key>() { $this->createUsers(); $abigail = SoftDeletesTestUser::where('email', 'abigailotwell@gmail.com')->first(); $abigail->posts()->create(['title' => 'First Title']); $abigail->posts()->create(['title' => 'Second Title']); // delete on builder $abigail->posts()->where('title', 'Second Title')->delete(); $abigail = $abigail->fresh(); $this->assertCount(1, $abigail->posts); $this->assertEquals('First Title', $abigail->posts->first()->title); $this->assertCount(2, $abigail->posts()->withTrashed()->get()); // restore $abigail->posts()->withTrashed()->restore(); $abigail = $abigail->fresh(); $this->assertCount(2, $abigail->posts); // force delete $abigail->posts()->where('title', 'Second Title')->forceDelete(); $abigail = $abigail->fresh(); $this->assertCount(1, $abigail->posts); $this->assertCount(1, $abigail->posts()->withTrashed()->get()); } public function <API key>() { $this->createUsers(); $abigail = SoftDeletesTestUser::where('email', 'abigailotwell@gmail.com')->first(); $post = $abigail->posts()->create(['title' => 'First Title']); $post->comments()->create(['body' => 'Comment Body']); $abigail->posts()->first()->comments()->delete(); $abigail = $abigail->fresh(); $this->assertCount(0, $abigail->posts()->first()->comments); $this->assertCount(1, $abigail->posts()->first()->comments()->withTrashed()->get()); } public function <API key>() { $this->createUsers(); $abigail = SoftDeletesTestUser::where('email', 'abigailotwell@gmail.com')->first(); $post = $abigail->posts()->create(['title' => 'First Title']); $users = SoftDeletesTestUser::where('email', 'taylorotwell@gmail.com')->has('posts')->get(); $this->assertEquals(0, count($users)); $users = SoftDeletesTestUser::where('email', 'abigailotwell@gmail.com')->has('posts')->get(); $this->assertEquals(1, count($users)); $users = SoftDeletesTestUser::where('email', 'doesnt@exist.com')->orHas('posts')->get(); $this->assertEquals(1, count($users)); $users = SoftDeletesTestUser::whereHas('posts', function ($query) { $query->where('title', 'First Title'); })->get(); $this->assertEquals(1, count($users)); $users = SoftDeletesTestUser::whereHas('posts', function ($query) { $query->where('title', 'Another Title'); })->get(); $this->assertEquals(0, count($users)); $users = SoftDeletesTestUser::where('email', 'doesnt@exist.com')->orWhereHas('posts', function ($query) { $query->where('title', 'First Title'); })->get(); $this->assertEquals(1, count($users)); // With Post Deleted... $post->delete(); $users = SoftDeletesTestUser::has('posts')->get(); $this->assertEquals(0, count($users)); } /** * @group test */ public function <API key>() { $this->createUsers(); $abigail = SoftDeletesTestUser::where('email', 'abigailotwell@gmail.com')->first(); $post = $abigail->posts()->create(['title' => 'First Title']); $post->delete(); $users = SoftDeletesTestUser::has('posts')->get(); $this->assertEquals(0, count($users)); $users = SoftDeletesTestUser::whereHas('posts', function ($q) { $q->onlyTrashed(); })->get(); $this->assertEquals(1, count($users)); $users = SoftDeletesTestUser::whereHas('posts', function ($q) { $q->withTrashed(); })->get(); $this->assertEquals(1, count($users)); } /** * @group test */ public function <API key>() { $this->createUsers(); $abigail = SoftDeletesTestUser::where('email', 'abigailotwell@gmail.com')->first(); $post = $abigail->posts()->create(['title' => 'First Title']); $comment = $post->comments()->create(['body' => 'Comment Body']); $comment->delete(); $users = SoftDeletesTestUser::has('posts.comments')->get(); $this->assertEquals(0, count($users)); $users = SoftDeletesTestUser::doesntHave('posts.comments')->get(); $this->assertEquals(1, count($users)); } /** * @group test */ public function <API key>() { $this->createUsers(); $abigail = <API key>::where('email', 'abigailotwell@gmail.com')->first(); $post = $abigail->posts()->create(['title' => 'First Title']); $post->delete(); $users = <API key>::has('posts')->get(); $this->assertEquals(1, count($users)); } /** * @group test */ public function <API key>() { $this->createUsers(); $abigail = SoftDeletesTestUser::where('email', 'abigailotwell@gmail.com')->first(); $post1 = $abigail->posts()->create(['title' => 'First Title']); $post1->delete(); $post2 = $abigail->posts()->create(['title' => 'Second Title']); $post3 = $abigail->posts()->create(['title' => 'Third Title']); $user = SoftDeletesTestUser::withCount('posts')->orderBy('postsCount', 'desc')->first(); $this->assertEquals(2, $user->posts_count); $user = SoftDeletesTestUser::withCount(['posts' => function ($q) { $q->onlyTrashed(); }])->orderBy('postsCount', 'desc')->first(); $this->assertEquals(1, $user->posts_count); $user = SoftDeletesTestUser::withCount(['posts' => function ($q) { $q->withTrashed(); }])->orderBy('postsCount', 'desc')->first(); $this->assertEquals(3, $user->posts_count); $user = SoftDeletesTestUser::withCount(['posts' => function ($q) { $q->withTrashed()->where('title', 'First Title'); }])->orderBy('postsCount', 'desc')->first(); $this->assertEquals(1, $user->posts_count); $user = SoftDeletesTestUser::withCount(['posts' => function ($q) { $q->where('title', 'First Title'); }])->orderBy('postsCount', 'desc')->first(); $this->assertEquals(0, $user->posts_count); } public function <API key>() { $this->createUsers(); $users = SoftDeletesTestUser::where('email', 'taylorotwell@gmail.com')->orWhere('email', 'abigailotwell@gmail.com'); $this->assertEquals(['abigailotwell@gmail.com'], $users->pluck('email')->all()); } public function <API key>() { $this->createUsers(); $abigail = SoftDeletesTestUser::where('email', 'abigailotwell@gmail.com')->first(); $post1 = $abigail->posts()->create(['title' => 'First Title']); $post1->comments()->create([ 'body' => 'Comment Body', 'owner_type' => SoftDeletesTestUser::class, 'owner_id' => $abigail->id, ]); $abigail->delete(); $comment = <API key>::with(['owner' => function ($q) { $q->withoutGlobalScope(SoftDeletingScope::class); }])->first(); $this->assertEquals($abigail->email, $comment->owner->email); $comment = <API key>::with(['owner' => function ($q) { $q->withTrashed(); }])->first(); $this->assertEquals($abigail->email, $comment->owner->email); $comment = <API key>::with(['owner' => function ($q) { $q->withTrashed(); }])->first(); $this->assertEquals($abigail->email, $comment->owner->email); } /** * @expectedException <API key> */ public function <API key>() { $this->createUsers(); $abigail = SoftDeletesTestUser::where('email', 'abigailotwell@gmail.com')->first(); $post1 = $abigail->posts()->create(['title' => 'First Title']); $post1->comments()->create([ 'body' => 'Comment Body', 'owner_type' => SoftDeletesTestUser::class, 'owner_id' => $abigail->id, ]); <API key>::with(['owner' => function ($q) { $q-><API key>(); }])->first(); } public function <API key>() { $this->createUsers(); $abigail = SoftDeletesTestUser::where('email', 'abigailotwell@gmail.com')->first(); $post1 = $abigail->posts()->create(['title' => 'First Title']); $post1->comments()->create([ 'body' => 'Comment Body', 'owner_type' => SoftDeletesTestUser::class, 'owner_id' => $abigail->id, ]); $comment = <API key>::with(['owner' => function ($q) { $q->where('email', 'taylorotwell@gmail.com'); }])->first(); $this->assertEquals(null, $comment->owner); } public function <API key>() { $this->createUsers(); $abigail = SoftDeletesTestUser::where('email', 'abigailotwell@gmail.com')->first(); $post1 = $abigail->posts()->create(['title' => 'First Title']); $comment1 = $post1->comments()->create([ 'body' => 'Comment Body', 'owner_type' => SoftDeletesTestUser::class, 'owner_id' => $abigail->id, ]); $comment = <API key>::with('owner')->first(); $this->assertEquals($abigail->email, $comment->owner->email); $abigail->delete(); $comment = <API key>::with('owner')->first(); $this->assertEquals(null, $comment->owner); } public function <API key>() { $taylor = <API key>::create(['id' => 1, 'email' => 'taylorotwell@gmail.com']); $post1 = $taylor->posts()->create(['title' => 'First Title']); $post1->comments()->create([ 'body' => 'Comment Body', 'owner_type' => <API key>::class, 'owner_id' => $taylor->id, ]); $comment = <API key>::with('owner')->first(); $this->assertEquals($taylor->email, $comment->owner->email); $taylor->delete(); $comment = <API key>::with('owner')->first(); $this->assertEquals(null, $comment->owner); } /** * Helpers... */ protected function createUsers() { $taylor = SoftDeletesTestUser::create(['id' => 1, 'email' => 'taylorotwell@gmail.com']); $abigail = SoftDeletesTestUser::create(['id' => 2, 'email' => 'abigailotwell@gmail.com']); $taylor->delete(); } /** * Get a database connection instance. * * @return Connection */ protected function connection() { return Eloquent::<API key>()->connection(); } /** * Get a schema builder instance. * * @return Schema\Builder */ protected function schema() { return $this->connection()->getSchemaBuilder(); } } /** * Eloquent Models... */ class <API key> extends Eloquent { protected $table = 'users'; protected $guarded = []; public function posts() { return $this->hasMany(SoftDeletesTestPost::class, 'user_id'); } } /** * Eloquent Models... */ class SoftDeletesTestUser extends Eloquent { use SoftDeletes; protected $dates = ['deleted_at']; protected $table = 'users'; protected $guarded = []; public function posts() { return $this->hasMany(SoftDeletesTestPost::class, 'user_id'); } public function address() { return $this->hasOne(<API key>::class, 'user_id'); } public function group() { return $this->belongsTo(<API key>::class, 'group_id'); } } class <API key> extends Eloquent { use SoftDeletes; protected $dates = ['deleted_at']; protected $table = 'users'; protected $guarded = []; public function posts() { return $this->hasMany(SoftDeletesTestPost::class, 'user_id')->withTrashed(); } } /** * Eloquent Models... */ class SoftDeletesTestPost extends Eloquent { use SoftDeletes; protected $dates = ['deleted_at']; protected $table = 'posts'; protected $guarded = []; public function comments() { return $this->hasMany(<API key>::class, 'post_id'); } } /** * Eloquent Models... */ class <API key> extends Eloquent { protected $table = 'comments'; protected $guarded = []; public function owner() { return $this->morphTo(); } } /** * Eloquent Models... */ class <API key> extends Eloquent { use SoftDeletes; protected $dates = ['deleted_at']; protected $table = 'comments'; protected $guarded = []; public function owner() { return $this->morphTo(); } } class <API key> extends Eloquent { use SoftDeletes; protected $dates = ['deleted_at']; protected $table = 'comments'; protected $guarded = []; public function owner() { return $this->morphTo(); } } /** * Eloquent Models... */ class <API key> extends Eloquent { use SoftDeletes; protected $dates = ['deleted_at']; protected $table = 'addresses'; protected $guarded = []; } /** * Eloquent Models... */ class <API key> extends Eloquent { use SoftDeletes; protected $dates = ['deleted_at']; protected $table = 'groups'; protected $guarded = []; public function users() { $this->hasMany(SoftDeletesTestUser::class); } }
from crits.vocabulary.relationships import RelationshipTypes def migrate_backdoors(self): """ Create backdoor objects from backdoors on samples. """ if not self.unsupported_attrs: return if 'backdoor' not in self.unsupported_attrs: return print "Migrating backdoor for %s" % self.id from crits.backdoors.handlers import add_new_backdoor backdoor = self.unsupported_attrs['backdoor'] name = backdoor.get('name', '') version = backdoor.get('version', None) if not name: return # Create a new backdoor family, and if we have a version the more specific # backdoor will be created too. Use source and campaign of the current # Sample. result = add_new_backdoor(name, version=version, source=self.source, campaign=self.campaign) if result['success']: self.add_relationship(result['object'], RelationshipTypes.RELATED_TO, rel_reason="Migrated") # Save the object after relationship was created. self.save() else: print "Error migrating %s: %s" % (self.id, result['message']) def migrate_exploits(self): """ Create exploit objects from exploits on samples. """ if not self.unsupported_attrs: return if 'exploit' not in self.unsupported_attrs: return from crits.exploits.handlers import add_new_exploit exploits = self.unsupported_attrs['exploit'] for exp in exploits: print "Migrating exploit for %s" % self.id # Create a new exploit object. Use the source and campaign from the # current sample. The "old" exploit format was a list of dictionaries # with the key of "cve" and a value that we will use for name and CVE. result = add_new_exploit(exp['cve'], cve=exp['cve'], source=self.source, campaign=self.campaign) if result['success']: self.add_relationship(result['object'], RelationshipTypes.RELATED_TO, rel_reason="Migrated") # Save the object after relationship was created. self.save() else: print "Error migrating %s: %s" % (self.id, result['message']) def migrate_sample(self): """ Migrate to the latest schema version. """ migrate_3_to_4(self) def migrate_3_to_4(self): """ Migrate from schema 3 to 4. """ if self.schema_version < 3: migrate_2_to_3(self) if self.schema_version == 3: migrate_backdoors(self) migrate_exploits(self) self.schema_version = 4 self.save() self.reload() def migrate_2_to_3(self): """ Migrate from schema 2 to 3. """ if self.schema_version < 2: migrate_1_to_2(self) if self.schema_version == 2: from crits.core.core_migrate import <API key> <API key>(self) self.schema_version = 3 def migrate_1_to_2(self): """ Migrate from schema 1 to 2. """ if self.schema_version < 1: migrate_0_to_1(self) if self.schema_version == 1: self.discover_binary() self.schema_version = 2 def migrate_0_to_1(self): """ Migrate from schema 0 to 1. """ if self.schema_version < 1: self.schema_version = 1
#ifndef BT_SERIALIZER_H #define BT_SERIALIZER_H #include "btScalar.h" // has definitions like SIMD_FORCE_INLINE #include "btStackAlloc.h" #include "btHashMap.h" #if !defined( __CELLOS_LV2__) && !defined(__MWERKS__) #include <memory.h> #endif #include <string.h> only the 32bit versions for now extern char sBulletDNAstr[]; extern int sBulletDNAlen; extern char sBulletDNAstr64[]; extern int sBulletDNAlen64; SIMD_FORCE_INLINE int btStrLen(const char* str) { if (!str) return(0); int len = 0; while (*str != 0) { str++; len++; } return len; } class btChunk { public: int m_chunkCode; int m_length; void *m_oldPtr; int m_dna_nr; int m_number; }; enum <API key> { BT_SERIALIZE_NO_BVH = 1, <API key> = 2, <API key> = 4 }; class btSerializer { public: virtual ~btSerializer() {} virtual const unsigned char* getBufferPointer() const = 0; virtual int <API key>() const = 0; virtual btChunk* allocate(size_t size, int numElements) = 0; virtual void finalizeChunk(btChunk* chunk, const char* structType, int chunkCode,void* oldPtr)= 0; virtual void* findPointer(void* oldPtr) = 0; virtual void* getUniquePointer(void*oldPtr) = 0; virtual void startSerialization() = 0; virtual void finishSerialization() = 0; virtual const char* findNameForPointer(const void* ptr) const = 0; virtual void <API key>(const void* ptr, const char* name) = 0; virtual void serializeName(const char* ptr) = 0; virtual int <API key>() const = 0; virtual void <API key>(int flags) = 0; }; #define BT_HEADER_LENGTH 12 #if defined(__sgi) || defined (__sparc) || defined (__sparc__) || defined (__PPC__) || defined (__ppc__) || defined (__BIG_ENDIAN__) #else #endif #define BT_SOFTBODY_CODE BT_MAKE_ID('S','B','D','Y') #define <API key> BT_MAKE_ID('C','O','B','J') #define BT_RIGIDBODY_CODE BT_MAKE_ID('R','B','D','Y') #define BT_CONSTRAINT_CODE BT_MAKE_ID('C','O','N','S') #define BT_BOXSHAPE_CODE BT_MAKE_ID('B','O','X','S') #define <API key> BT_MAKE_ID('Q','B','V','H') #define <API key> BT_MAKE_ID('T','M','A','P') #define BT_SHAPE_CODE BT_MAKE_ID('S','H','A','P') #define BT_ARRAY_CODE BT_MAKE_ID('A','R','A','Y') #define BT_SBMATERIAL_CODE BT_MAKE_ID('S','B','M','T') #define BT_SBNODE_CODE BT_MAKE_ID('S','B','N','D') #define <API key> BT_MAKE_ID('D','W','L','D') #define BT_DNA_CODE BT_MAKE_ID('D','N','A','1') struct btPointerUid { union { void* m_ptr; int m_uniqueIds[2]; }; }; The btDefaultSerializer is the main Bullet serialization class. The constructor takes an optional argument for backwards compatibility, it is recommended to leave this empty/zero. class btDefaultSerializer : public btSerializer { <API key><char*> mTypes; <API key><short*> mStructs; <API key><short> mTlens; btHashMap<btHashInt, int> mStructReverse; btHashMap<btHashString,int> mTypeLookup; btHashMap<btHashPtr,void*> m_chunkP; btHashMap<btHashPtr,const char*> m_nameMap; btHashMap<btHashPtr,btPointerUid> m_uniquePointers; int m_uniqueIdGenerator; int m_totalSize; unsigned char* m_buffer; int m_currentSize; void* m_dna; int m_dnaLength; int <API key>; <API key><btChunk*> m_chunkPtrs; protected: virtual void* findPointer(void* oldPtr) { void** ptr = m_chunkP.find(oldPtr); if (ptr && *ptr) return *ptr; return 0; } void writeDNA() { btChunk* dnaChunk = allocate(m_dnaLength,1); memcpy(dnaChunk->m_oldPtr,m_dna,m_dnaLength); finalizeChunk(dnaChunk,"DNA1",BT_DNA_CODE, m_dna); } int getReverseType(const char *type) const { btHashString key(type); const int* valuePtr = mTypeLookup.find(key); if (valuePtr) return *valuePtr; return -1; } void initDNA(const char* bdnaOrg,int dnalen) { was already initialized if (m_dna) return; int littleEndian= 1; littleEndian= ((char*)&littleEndian)[0]; m_dna = btAlignedAlloc(dnalen,16); memcpy(m_dna,bdnaOrg,dnalen); m_dnaLength = dnalen; int *intPtr=0; short *shtPtr=0; char *cp = 0;int dataLen =0; intPtr = (int*)m_dna; /* SDNA (4 bytes) (magic number) NAME (4 bytes) <nr> (4 bytes) amount of names (int) <string> <string> */ if (strncmp((const char*)m_dna, "SDNA", 4)==0) { // skip ++ NAME intPtr++; intPtr++; } // Parse names if (!littleEndian) *intPtr = btSwapEndian(*intPtr); dataLen = *intPtr; intPtr++; cp = (char*)intPtr; int i; for ( i=0; i<dataLen; i++) { while (*cp)cp++; cp++; } cp = btAlignPointer(cp,4); /* TYPE (4 bytes) <nr> amount of types (int) <string> <string> */ intPtr = (int*)cp; btAssert(strncmp(cp, "TYPE", 4)==0); intPtr++; if (!littleEndian) *intPtr = btSwapEndian(*intPtr); dataLen = *intPtr; intPtr++; cp = (char*)intPtr; for (i=0; i<dataLen; i++) { mTypes.push_back(cp); while (*cp)cp++; cp++; } cp = btAlignPointer(cp,4); /* TLEN (4 bytes) <len> (short) the lengths of types <len> */ // Parse type lens intPtr = (int*)cp; btAssert(strncmp(cp, "TLEN", 4)==0); intPtr++; dataLen = (int)mTypes.size(); shtPtr = (short*)intPtr; for (i=0; i<dataLen; i++, shtPtr++) { if (!littleEndian) shtPtr[0] = btSwapEndian(shtPtr[0]); mTlens.push_back(shtPtr[0]); } if (dataLen & 1) shtPtr++; /* STRC (4 bytes) <nr> amount of structs (int) <typenr> <nr_of_elems> <typenr> <namenr> <typenr> <namenr> */ intPtr = (int*)shtPtr; cp = (char*)intPtr; btAssert(strncmp(cp, "STRC", 4)==0); intPtr++; if (!littleEndian) *intPtr = btSwapEndian(*intPtr); dataLen = *intPtr ; intPtr++; shtPtr = (short*)intPtr; for (i=0; i<dataLen; i++) { mStructs.push_back (shtPtr); if (!littleEndian) { shtPtr[0]= btSwapEndian(shtPtr[0]); shtPtr[1]= btSwapEndian(shtPtr[1]); int len = shtPtr[1]; shtPtr+= 2; for (int a=0; a<len; a++, shtPtr+=2) { shtPtr[0]= btSwapEndian(shtPtr[0]); shtPtr[1]= btSwapEndian(shtPtr[1]); } } else { shtPtr+= (2*shtPtr[1])+2; } } // build reverse lookups for (i=0; i<(int)mStructs.size(); i++) { short *strc = mStructs.at(i); mStructReverse.insert(strc[0], i); mTypeLookup.insert(btHashString(mTypes[strc[0]]),i); } } public: btDefaultSerializer(int totalSize=0) :m_totalSize(totalSize), m_currentSize(0), m_dna(0), m_dnaLength(0), <API key>(0) { m_buffer = m_totalSize?(unsigned char*)btAlignedAlloc(totalSize,16):0; const bool VOID_IS_8 = ((sizeof(void*)==8)); #ifdef <API key> if (VOID_IS_8) { #if _WIN64 initDNA((const char*)sBulletDNAstr64,sBulletDNAlen64); #else btAssert(0); #endif } else { #ifndef _WIN64 initDNA((const char*)sBulletDNAstr,sBulletDNAlen); #else btAssert(0); #endif } #else //<API key> if (VOID_IS_8) { initDNA((const char*)sBulletDNAstr64,sBulletDNAlen64); } else { initDNA((const char*)sBulletDNAstr,sBulletDNAlen); } #endif //<API key> } virtual ~btDefaultSerializer() { if (m_buffer) btAlignedFree(m_buffer); if (m_dna) btAlignedFree(m_dna); } void writeHeader(unsigned char* buffer) const { #ifdef <API key> memcpy(buffer, "BULLETd", 7); #else memcpy(buffer, "BULLETf", 7); #endif //<API key> int littleEndian= 1; littleEndian= ((char*)&littleEndian)[0]; if (sizeof(void*)==8) { buffer[7] = '-'; } else { buffer[7] = '_'; } if (littleEndian) { buffer[8]='v'; } else { buffer[8]='V'; } buffer[9] = '2'; buffer[10] = '8'; buffer[11] = '1'; } virtual void startSerialization() { m_uniqueIdGenerator= 1; if (m_totalSize) { unsigned char* buffer = internalAlloc(BT_HEADER_LENGTH); writeHeader(buffer); } } virtual void finishSerialization() { writeDNA(); //if we didn't pre-allocate a buffer, we need to create a contiguous buffer now int mysize = 0; if (!m_totalSize) { if (m_buffer) btAlignedFree(m_buffer); m_currentSize += BT_HEADER_LENGTH; m_buffer = (unsigned char*)btAlignedAlloc(m_currentSize,16); unsigned char* currentPtr = m_buffer; writeHeader(m_buffer); currentPtr += BT_HEADER_LENGTH; mysize+=BT_HEADER_LENGTH; for (int i=0;i< m_chunkPtrs.size();i++) { int curLength = sizeof(btChunk)+m_chunkPtrs[i]->m_length; memcpy(currentPtr,m_chunkPtrs[i], curLength); btAlignedFree(m_chunkPtrs[i]); currentPtr+=curLength; mysize+=curLength; } } mTypes.clear(); mStructs.clear(); mTlens.clear(); mStructReverse.clear(); mTypeLookup.clear(); m_chunkP.clear(); m_nameMap.clear(); m_uniquePointers.clear(); m_chunkPtrs.clear(); } virtual void* getUniquePointer(void*oldPtr) { if (!oldPtr) return 0; btPointerUid* uptr = (btPointerUid*)m_uniquePointers.find(oldPtr); if (uptr) { return uptr->m_ptr; } m_uniqueIdGenerator++; btPointerUid uid; uid.m_uniqueIds[0] = m_uniqueIdGenerator; uid.m_uniqueIds[1] = m_uniqueIdGenerator; m_uniquePointers.insert(oldPtr,uid); return uid.m_ptr; } virtual const unsigned char* getBufferPointer() const { return m_buffer; } virtual int <API key>() const { return m_currentSize; } virtual void finalizeChunk(btChunk* chunk, const char* structType, int chunkCode,void* oldPtr) { if (!(<API key>&<API key>)) { btAssert(!findPointer(oldPtr)); } chunk->m_dna_nr = getReverseType(structType); chunk->m_chunkCode = chunkCode; void* uniquePtr = getUniquePointer(oldPtr); m_chunkP.insert(oldPtr,uniquePtr);//chunk->m_oldPtr); chunk->m_oldPtr = uniquePtr;//oldPtr; } virtual unsigned char* internalAlloc(size_t size) { unsigned char* ptr = 0; if (m_totalSize) { ptr = m_buffer+m_currentSize; m_currentSize += int(size); btAssert(m_currentSize<m_totalSize); } else { ptr = (unsigned char*)btAlignedAlloc(size,16); m_currentSize += int(size); } return ptr; } virtual btChunk* allocate(size_t size, int numElements) { unsigned char* ptr = internalAlloc(int(size)*numElements+sizeof(btChunk)); unsigned char* data = ptr + sizeof(btChunk); btChunk* chunk = (btChunk*)ptr; chunk->m_chunkCode = 0; chunk->m_oldPtr = data; chunk->m_length = int(size)*numElements; chunk->m_number = numElements; m_chunkPtrs.push_back(chunk); return chunk; } virtual const char* findNameForPointer(const void* ptr) const { const char*const * namePtr = m_nameMap.find(ptr); if (namePtr && *namePtr) return *namePtr; return 0; } virtual void <API key>(const void* ptr, const char* name) { m_nameMap.insert(ptr,name); } virtual void serializeName(const char* name) { if (name) { //don't serialize name twice if (findPointer((void*)name)) return; int len = btStrLen(name); if (len) { int newLen = len+1; int padding = ((newLen+3)&~3)-newLen; newLen += padding; //serialize name string now btChunk* chunk = allocate(sizeof(char),newLen); char* destinationName = (char*)chunk->m_oldPtr; for (int i=0;i<len;i++) { destinationName[i] = name[i]; } destinationName[len] = 0; finalizeChunk(chunk,"char",BT_ARRAY_CODE,(void*)name); } } } virtual int <API key>() const { return <API key>; } virtual void <API key>(int flags) { <API key> = flags; } }; #endif //BT_SERIALIZER_H
ENV["RAILS_ENV"] = "test" require File.expand_path(File.dirname(__FILE__) + "/../config/environment") require 'test_help' # begin # require "redgreen" # rescue MissingSourceFile # end $LOAD_PATH.unshift File.dirname(__FILE__) + "/../../../../lib" require "webrat" Webrat.configure do |config| config.mode = ENV['<API key>'].to_sym config.<API key> = '*safari' end ActionController::Base.class_eval do def perform_action <API key> end end Dispatcher.class_eval do def self.failsafe_response(output, status, exception = nil) raise exception end end
/** The modal for suspending a user. @class <API key> @extends Discourse.Controller @namespace Discourse @uses Discourse.ModalFunctionality @module Discourse **/ Discourse.<API key> = Discourse.ObjectController.extend(Discourse.ModalFunctionality, { actions: { suspend: function() { var duration = parseInt(this.get('duration'), 10); if (duration > 0) { var self = this; this.send('hideModal'); this.get('model').suspend(duration, this.get('reason')).then(function() { window.location.reload(); }, function(e) { var error = I18n.t('admin.user.suspend_failed', { error: "http: " + e.status + " - " + e.body }); bootbox.alert(error, function() { self.send('showModal'); }); }); } } } });
# <API key>: true class ActiveStorage::VariantRecord < ActiveRecord::Base self.table_name = "<API key>" belongs_to :blob has_one_attached :image end
require File.expand_path('../../../spec_helper', __FILE__) describe "Bignum#divmod" do before :each do @bignum = bignum_value(55) end # Based on MRI's test/test_integer.rb (test_divmod), # MRI maintains the following property: # if q, r = a.divmod(b) ==> # assert(0 < b ? (0 <= r && r < b) : (b < r && r <= 0)) # So, r is always between 0 and b. it "returns an Array containing quotient and modulus obtained from dividing self by the given argument" do @bignum.divmod(4).should == [2305843009213693965, 3] @bignum.divmod(13).should == [709490156681136604, 11] @bignum.divmod(4.5).should == [2049638230412172288, 3.5] not_supported_on :opal do @bignum.divmod(4.0).should == [2305843009213693952, 0.0] @bignum.divmod(13.0).should == [709490156681136640, 8.0] @bignum.divmod(2.0).should == [4611686018427387904, 0.0] end @bignum.divmod(bignum_value).should == [1, 55] (-(10**50)).divmod(-(10**40 + 1)).should == [9999999999, -<SHA1-like>] (10**50).divmod(10**40 + 1).should == [9999999999, <SHA1-like>] (-10**50).divmod(10**40 + 1).should == [-10000000000, 10000000000] (10**50).divmod(-(10**40 + 1)).should == [-10000000000, -10000000000] end describe "with q = floor(x/y), a = q*b + r," do it "returns [q,r] when a < 0, b > 0 and |a| < b" do a = -@bignum + 1 b = @bignum a.divmod(b).should == [-1, 1] end it "returns [q,r] when a > 0, b < 0 and a > |b|" do b = -@bignum + 1 a = @bignum a.divmod(b).should == [-2, -@bignum + 2] end it "returns [q,r] when a > 0, b < 0 and a < |b|" do a = @bignum - 1 b = -@bignum a.divmod(b).should == [-1, -1] end it "returns [q,r] when a < 0, b < 0 and |a| < |b|" do a = -@bignum + 1 b = -@bignum a.divmod(b).should == [0, -@bignum + 1] end end it "raises a ZeroDivisionError when the given argument is 0" do lambda { @bignum.divmod(0) }.should raise_error(ZeroDivisionError) lambda { (-@bignum).divmod(0) }.should raise_error(ZeroDivisionError) end # Behaviour established as correct in r23953 it "raises a FloatDomainError if other is NaN" do lambda { @bignum.divmod(nan_value) }.should raise_error(FloatDomainError) end it "raises a ZeroDivisionError when the given argument is 0 and a Float" do lambda { @bignum.divmod(0.0) }.should raise_error(ZeroDivisionError) lambda { (-@bignum).divmod(0.0) }.should raise_error(ZeroDivisionError) end it "raises a TypeError when the given argument is not an Integer" do lambda { @bignum.divmod(mock('10')) }.should raise_error(TypeError) lambda { @bignum.divmod("10") }.should raise_error(TypeError) lambda { @bignum.divmod(:symbol) }.should raise_error(TypeError) end end
# Dictionary This is an official subpackage for the super awesome Orion CMS framework. This is not a standalone app you must use as part of the framework. [Orionjs.org](http://Orionjs.org) has all the guides and hand holding you need to build simple and complex apps on meteor. Orion is the first and perhaps the only structurally organized framework for meteor that takes care of security, scaling, support and performance. It is a plug and play solution backed by a core team of seasoned developers. Code examples, tutorial and documentation makes Orionjs the definate framework to use for your next project.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html><head><meta http-equiv="Content-Type" content="text/html;charset=UTF-8"> <title>Loki: Member List</title> <link href="tabs.css" rel="stylesheet" type="text/css"> <link href="doxygen.css" rel="stylesheet" type="text/css"> </head><body> <!-- Generated by Doxygen 1.5.8 --> <div class="navigation" id="top"> <div class="tabs"> <ul> <li><a href="main.html"><span>Main&nbsp;Page</span></a></li> <li><a href="modules.html"><span>Modules</span></a></li> <li><a href="namespaces.html"><span>Namespaces</span></a></li> <li class="current"><a href="annotated.html"><span>Classes</span></a></li> <li><a href="files.html"><span>Files</span></a></li> <li> <form action="search.php" method="get"> <table cellspacing="0" cellpadding="0" border="0"> <tr> <td><label>&nbsp;<u>S</u>earch&nbsp;for&nbsp;</label></td> <td><input type="text" name="query" value="" size="20" accesskey="s"/></td> </tr> </table> </form> </li> </ul> </div> <div class="tabs"> <ul> <li><a href="annotated.html"><span>Class&nbsp;List</span></a></li> <li><a href="classes.html"><span>Class&nbsp;Index</span></a></li> <li><a href="hierarchy.html"><span>Class&nbsp;Hierarchy</span></a></li> <li><a href="functions.html"><span>Class&nbsp;Members</span></a></li> </ul> </div> </div> <div class="contents"> <h1>Loki::ArrayStorage&lt; T &gt; Member List</h1>This is the complete list of members for <a class="el" href="a00007.html">Loki::ArrayStorage&lt; T &gt;</a>, including all inherited members.<p><table> <tr class="memlist"><td><a class="el" href="a00007.html#<API key>">PointerType</a> typedef</td><td><a class="el" href="a00007.html">Loki::ArrayStorage&lt; T &gt;</a></td><td></td></tr> </table></div> <hr size="1"><address style="text-align: right;"><small>Generated on Thu Jan 29 18:51:45 2009 for Loki by&nbsp; <a href="http: <img src="doxygen.png" alt="doxygen" align="middle" border="0"></a> 1.5.8 </small></address> </body> </html>
package hudson.diagnosis; import hudson.Extension; import jenkins.model.Jenkins; import hudson.model.PeriodicWork; import org.jenkinsci.Symbol; import java.util.logging.Logger; /** * Periodically checks the disk usage of <tt>JENKINS_HOME</tt>, * and activate {@link <API key>} if necessary. * * @author Kohsuke Kawaguchi */ @Extension @Symbol("diskUsageCheck") public class <API key> extends PeriodicWork { public long getRecurrencePeriod() { return HOUR; } protected void doRun() { long free = Jenkins.getInstance().getRootDir().getUsableSpace(); long total = Jenkins.getInstance().getRootDir().getTotalSpace(); if(free<=0 || total<=0) { // information unavailable. pointless to try. LOGGER.info("JENKINS_HOME disk usage information isn't available. aborting to monitor"); cancel(); return; } LOGGER.fine("Monitoring disk usage of JENKINS_HOME. total="+total+" free="+free); // if it's more than 90% full and less than the minimum, activate // it's AND and not OR so that small Hudson home won't get a warning, // and similarly, if you have a 1TB disk, you don't get a warning when you still have 100GB to go. <API key>.get().activated = (total/free>10 && free< <API key>); } private static final Logger LOGGER = Logger.getLogger(<API key>.class.getName()); /** * Gets the minimum amount of space to check for, with a default of 1GB */ public static long <API key> = Long.getLong( <API key>.class.getName() + ".freeSpaceThreshold", 1024L*1024*1024); }
package com.iluwatar.flyweight; /** * * Interface for Potions. * */ public interface Potion { void drink(); }
#!/usr/bin/env node var RSVP = require('rsvp'); var spawn = require('child_process').spawn; function run(command, _args) { var args = _args || []; return new RSVP.Promise(function(resolve, reject) { console.log('Running: ' + command + ' ' + args.join(' ')); var child = spawn(command, args); child.stdout.on('data', function (data) { console.log(data.toString()); }); child.stderr.on('data', function (data) { console.error(data.toString()); }); child.on('error', function(err) { reject(err); }); child.on('exit', function(code) { if (code === 0) { resolve(); } else { reject(code); } }); }); } RSVP.resolve() .then(function() { return run('./node_modules/.bin/ember', [ 'sauce:connect' ]); }) .then(function() { // calling testem directly here instead of `ember test` so that // we do not have to do a double build (by the time this is run // we have already ran `ember build`). return run('./node_modules/.bin/testem', [ 'ci', '--port', '7000' ]); }) .finally(function() { return run('./node_modules/.bin/ember', [ 'sauce:disconnect' ]); }) .catch(function() { process.exit(1); });
//Not using strict: uneven strict support in browsers, #392, and causes //problems with requirejs.exec()/transpiler plugins that may not be strict. /*jslint regexp: true, nomen: true, sloppy: true */ /*global window, navigator, document, importScripts, jQuery, setTimeout, opera */ var requirejs, require, define; (function (global) { var req, s, head, baseElement, dataMain, src, interactiveScript, <API key>, mainScript, subPath, version = '2.0.6', commentRegExp = /(\/\*([\s\S]*?)\*\/|([^:]|^)\/\/(.*)$)/mg, cjsRequireRegExp = /[^.]\s*require\s*\(\s*["']([^'"\s]+)["']\s*\)/g, jsSuffixRegExp = /\.js$/, currDirRegExp = /^\.\ op = Object.prototype, ostring = op.toString, hasOwn = op.hasOwnProperty, ap = Array.prototype, aps = ap.slice, apsp = ap.splice, isBrowser = !!(typeof window !== 'undefined' && navigator && document), isWebWorker = !isBrowser && typeof importScripts !== 'undefined', //PS3 indicates loaded and complete, but need to wait for complete //specifically. Sequence is 'loading', 'loaded', execution, // then 'complete'. The UA check is unfortunate, but not sure how //to feature test w/o causing perf issues. readyRegExp = isBrowser && navigator.platform === 'PLAYSTATION 3' ? /^complete$/ : /^(complete|loaded)$/, defContextName = '_', //Oh the tragedy, detecting opera. See the usage of isOpera for reason. isOpera = typeof opera !== 'undefined' && opera.toString() === '[object Opera]', contexts = {}, cfg = {}, globalDefQueue = [], useInteractive = false; function isFunction(it) { return ostring.call(it) === '[object Function]'; } function isArray(it) { return ostring.call(it) === '[object Array]'; } /** * Helper function for iterating over an array. If the func returns * a true value, it will break out of the loop. */ function each(ary, func) { if (ary) { var i; for (i = 0; i < ary.length; i += 1) { if (ary[i] && func(ary[i], i, ary)) { break; } } } } /** * Helper function for iterating over an array backwards. If the func * returns a true value, it will break out of the loop. */ function eachReverse(ary, func) { if (ary) { var i; for (i = ary.length - 1; i > -1; i -= 1) { if (ary[i] && func(ary[i], i, ary)) { break; } } } } function hasProp(obj, prop) { return hasOwn.call(obj, prop); } /** * Cycles over properties in an object and calls a function for each * property value. If the function returns a truthy value, then the * iteration is stopped. */ function eachProp(obj, func) { var prop; for (prop in obj) { if (obj.hasOwnProperty(prop)) { if (func(obj[prop], prop)) { break; } } } } /** * Simple function to mix in properties from source into target, * but only if target does not already have a property of the same name. * This is not robust in IE for transferring methods that match * Object.prototype names, but the uses of mixin here seem unlikely to * trigger a problem related to that. */ function mixin(target, source, force, deepStringMixin) { if (source) { eachProp(source, function (value, prop) { if (force || !hasProp(target, prop)) { if (deepStringMixin && typeof value !== 'string') { if (!target[prop]) { target[prop] = {}; } mixin(target[prop], value, force, deepStringMixin); } else { target[prop] = value; } } }); } return target; } //Similar to Function.prototype.bind, but the 'this' object is specified //first, since it is easier to read/figure out what 'this' will be. function bind(obj, fn) { return function () { return fn.apply(obj, arguments); }; } function scripts() { return document.<API key>('script'); } //Allow getting a global that expressed in //dot notation, like 'a.b.c'. function getGlobal(value) { if (!value) { return value; } var g = global; each(value.split('.'), function (part) { g = g[part]; }); return g; } function <API key>(func, relMap, enableBuildCallback) { return function () { //A version of a require function that passes a moduleName //value for items that may need to //look up paths relative to the moduleName var args = aps.call(arguments, 0), lastArg; if (enableBuildCallback && isFunction((lastArg = args[args.length - 1]))) { lastArg.__requireJsBuild = true; } args.push(relMap); return func.apply(null, args); }; } function addRequireMethods(req, context, relMap) { each([ ['toUrl'], ['undef'], ['defined', 'requireDefined'], ['specified', 'requireSpecified'] ], function (item) { var prop = item[1] || item[0]; req[item[0]] = context ? <API key>(context[prop], relMap) : //If no context, then use default context. Reference from //contexts instead of early binding to default context, so //that during builds, the latest instance of the default //context with its config gets used. function () { var ctx = contexts[defContextName]; return ctx[prop].apply(ctx, arguments); }; }); } /** * Constructs an error with a pointer to an URL with more information. * @param {String} id the error ID that maps to an ID on a web page. * @param {String} message human readable error. * @param {Error} [err] the original error, if there is one. * * @returns {Error} */ function makeError(id, msg, err, requireModules) { var e = new Error(msg + '\nhttp://requirejs.org/docs/errors.html e.requireType = id; e.requireModules = requireModules; if (err) { e.originalError = err; } return e; } if (typeof define !== 'undefined') { //If a define is already in play via another AMD loader, //do not overwrite. return; } if (typeof requirejs !== 'undefined') { if (isFunction(requirejs)) { //Do not overwrite and existing requirejs instance. return; } cfg = requirejs; requirejs = undefined; } //Allow for a require config object if (typeof require !== 'undefined' && !isFunction(require)) { //assume it is a config object. cfg = require; require = undefined; } function newContext(contextName) { var inCheckLoaded, Module, context, handlers, <API key>, config = { waitSeconds: 7, baseUrl: './', paths: {}, pkgs: {}, shim: {} }, registry = {}, undefEvents = {}, defQueue = [], defined = {}, urlFetched = {}, requireCounter = 1, unnormalizedCounter = 1, //Used to track the order in which modules //should be executed, by the order they //load. Important for consistent cycle resolution //behavior. waitAry = []; /** * Trims the . and .. from an array of path segments. * It will keep a leading path segment if a .. will become * the first path segment, to help with module name lookups, * which act like paths, but can be remapped. But the end result, * all paths that use this function should look normalized. * NOTE: this method MODIFIES the input array. * @param {Array} ary the array of path segments. */ function trimDots(ary) { var i, part; for (i = 0; ary[i]; i += 1) { part = ary[i]; if (part === '.') { ary.splice(i, 1); i -= 1; } else if (part === '..') { if (i === 1 && (ary[2] === '..' || ary[0] === '..')) { //End of the line. Keep at least one non-dot //path segment at the front so it can be mapped //correctly to disk. Otherwise, there is likely //no path mapping for a path starting with '..'. //This can still fail, but catches the most reasonable //uses of .. break; } else if (i > 0) { ary.splice(i - 1, 2); i -= 2; } } } } /** * Given a relative module name, like ./something, normalize it to * a real name that can be mapped to a path. * @param {String} name the relative name * @param {String} baseName a real name that the name arg is relative * to. * @param {Boolean} applyMap apply the map config to the value. Should * only be done if this normalization is for a dependency ID. * @returns {String} normalized name */ function normalize(name, baseName, applyMap) { var pkgName, pkgConfig, mapValue, nameParts, i, j, nameSegment, foundMap, foundI, foundStarMap, starI, baseParts = baseName && baseName.split('/'), normalizedBaseParts = baseParts, map = config.map, starMap = map && map['*']; //Adjust any relative paths. if (name && name.charAt(0) === '.') { //If have a base name, try to normalize against it, //otherwise, assume it is a top-level require that will //be relative to baseUrl in the end. if (baseName) { if (config.pkgs[baseName]) { //If the baseName is a package name, then just treat it as one //name to concat the name with. normalizedBaseParts = baseParts = [baseName]; } else { //Convert baseName to array, and lop off the last part, //so that . matches that 'directory' and not name of the baseName's //module. For instance, baseName of 'one/two/three', maps to //'one/two/three.js', but we want the directory, 'one/two' for //this normalization. normalizedBaseParts = baseParts.slice(0, baseParts.length - 1); } name = normalizedBaseParts.concat(name.split('/')); trimDots(name); //Some use of packages may use a . path to reference the //'main' module name, so normalize for that. pkgConfig = config.pkgs[(pkgName = name[0])]; name = name.join('/'); if (pkgConfig && name === pkgName + '/' + pkgConfig.main) { name = pkgName; } } else if (name.indexOf('./') === 0) { // No baseName, so this is ID is resolved relative // to baseUrl, pull off the leading dot. name = name.substring(2); } } //Apply map config if available. if (applyMap && (baseParts || starMap) && map) { nameParts = name.split('/'); for (i = nameParts.length; i > 0; i -= 1) { nameSegment = nameParts.slice(0, i).join('/'); if (baseParts) { //Find the longest baseName segment match in the config. //So, do joins on the biggest to smallest lengths of baseParts. for (j = baseParts.length; j > 0; j -= 1) { mapValue = map[baseParts.slice(0, j).join('/')]; //baseName segment has config, find if it has one for //this name. if (mapValue) { mapValue = mapValue[nameSegment]; if (mapValue) { //Match, update name to the new value. foundMap = mapValue; foundI = i; break; } } } } if (foundMap) { break; } //Check for a star map match, but just hold on to it, //if there is a shorter segment match later in a matching //config, then favor over this star map. if (!foundStarMap && starMap && starMap[nameSegment]) { foundStarMap = starMap[nameSegment]; starI = i; } } if (!foundMap && foundStarMap) { foundMap = foundStarMap; foundI = starI; } if (foundMap) { nameParts.splice(0, foundI, foundMap); name = nameParts.join('/'); } } return name; } function removeScript(name) { if (isBrowser) { each(scripts(), function (scriptNode) { if (scriptNode.getAttribute('data-requiremodule') === name && scriptNode.getAttribute('data-requirecontext') === context.contextName) { scriptNode.parentNode.removeChild(scriptNode); return true; } }); } } function hasPathFallback(id) { var pathConfig = config.paths[id]; if (pathConfig && isArray(pathConfig) && pathConfig.length > 1) { removeScript(id); //Pop off the first array value, since it failed, and //retry pathConfig.shift(); context.undef(id); context.require([id]); return true; } } /** * Creates a module mapping that includes plugin prefix, module * name, and path. If parentModuleMap is provided it will * also normalize the name via require.normalize() * * @param {String} name the module name * @param {String} [parentModuleMap] parent module map * for the module name, used to resolve relative names. * @param {Boolean} isNormalized: is the ID already normalized. * This is true if this call is done for a define() module ID. * @param {Boolean} applyMap: apply the map config to the ID. * Should only be true if this map is for a dependency. * * @returns {Object} */ function makeModuleMap(name, parentModuleMap, isNormalized, applyMap) { var url, pluginModule, suffix, index = name ? name.indexOf('!') : -1, prefix = null, parentName = parentModuleMap ? parentModuleMap.name : null, originalName = name, isDefine = true, normalizedName = ''; //If no name, then it means it is a require call, generate an //internal name. if (!name) { isDefine = false; name = '_@r' + (requireCounter += 1); } if (index !== -1) { prefix = name.substring(0, index); name = name.substring(index + 1, name.length); } if (prefix) { prefix = normalize(prefix, parentName, applyMap); pluginModule = defined[prefix]; } //Account for relative paths if there is a base name. if (name) { if (prefix) { if (pluginModule && pluginModule.normalize) { //Plugin is loaded, use its normalize method. normalizedName = pluginModule.normalize(name, function (name) { return normalize(name, parentName, applyMap); }); } else { normalizedName = normalize(name, parentName, applyMap); } } else { //A regular module. normalizedName = normalize(name, parentName, applyMap); url = context.nameToUrl(normalizedName); } } //If the id is a plugin id that cannot be determined if it needs //normalization, stamp it with a unique ID so two matching relative //ids that may conflict can be separate. suffix = prefix && !pluginModule && !isNormalized ? '_unnormalized' + (unnormalizedCounter += 1) : ''; return { prefix: prefix, name: normalizedName, parentMap: parentModuleMap, unnormalized: !!suffix, url: url, originalName: originalName, isDefine: isDefine, id: (prefix ? prefix + '!' + normalizedName : normalizedName) + suffix }; } function getModule(depMap) { var id = depMap.id, mod = registry[id]; if (!mod) { mod = registry[id] = new context.Module(depMap); } return mod; } function on(depMap, name, fn) { var id = depMap.id, mod = registry[id]; if (hasProp(defined, id) && (!mod || mod.defineEmitComplete)) { if (name === 'defined') { fn(defined[id]); } } else { getModule(depMap).on(name, fn); } } function onError(err, errback) { var ids = err.requireModules, notified = false; if (errback) { errback(err); } else { each(ids, function (id) { var mod = registry[id]; if (mod) { //Set error on module, so it skips timeout checks. mod.error = err; if (mod.events.error) { notified = true; mod.emit('error', err); } } }); if (!notified) { req.onError(err); } } } /** * Internal method to transfer globalQueue items to this context's * defQueue. */ function takeGlobalQueue() { //Push all the globalDefQueue items into the context's defQueue if (globalDefQueue.length) { //Array splice in the values since the context code has a //local var ref to defQueue, so cannot just reassign the one //on context. apsp.apply(defQueue, [defQueue.length - 1, 0].concat(globalDefQueue)); globalDefQueue = []; } } /** * Helper function that creates a require function object to give to * modules that ask for it as a dependency. It needs to be specific * per module because of the implication of path mappings that may * need to be relative to the module name. */ function makeRequire(mod, enableBuildCallback, altRequire) { var relMap = mod && mod.map, modRequire = <API key>(altRequire || context.require, relMap, enableBuildCallback); addRequireMethods(modRequire, context, relMap); modRequire.isBrowser = isBrowser; return modRequire; } handlers = { 'require': function (mod) { return makeRequire(mod); }, 'exports': function (mod) { mod.usingExports = true; if (mod.map.isDefine) { return (mod.exports = defined[mod.map.id] = {}); } }, 'module': function (mod) { return (mod.module = { id: mod.map.id, uri: mod.map.url, config: function () { return (config.config && config.config[mod.map.id]) || {}; }, exports: defined[mod.map.id] }); } }; function removeWaiting(id) { //Clean up machinery used for waiting modules. delete registry[id]; each(waitAry, function (mod, i) { if (mod.map.id === id) { waitAry.splice(i, 1); if (!mod.defined) { context.waitCount -= 1; } return true; } }); } function findCycle(mod, traced, processed) { var id = mod.map.id, depArray = mod.depMaps, foundModule; //Do not bother with unitialized modules or not yet enabled //modules. if (!mod.inited) { return; } //Found the cycle. if (traced[id]) { return mod; } traced[id] = true; //Trace through the dependencies. each(depArray, function (depMap) { var depId = depMap.id, depMod = registry[depId]; if (!depMod || processed[depId] || !depMod.inited || !depMod.enabled) { return; } return (foundModule = findCycle(depMod, traced, processed)); }); processed[id] = true; return foundModule; } function forceExec(mod, traced, uninited) { var id = mod.map.id, depArray = mod.depMaps; if (!mod.inited || !mod.map.isDefine) { return; } if (traced[id]) { return defined[id]; } traced[id] = mod; each(depArray, function (depMap) { var depId = depMap.id, depMod = registry[depId], value; if (handlers[depId]) { return; } if (depMod) { if (!depMod.inited || !depMod.enabled) { //Dependency is not inited, //so this module cannot be //given a forced value yet. uninited[id] = true; return; } //Get the value for the current dependency value = forceExec(depMod, traced, uninited); //Even with forcing it may not be done, //in particular if the module is waiting //on a plugin resource. if (!uninited[depId]) { mod.defineDepById(depId, value); } } }); mod.check(true); return defined[id]; } function modCheck(mod) { mod.check(); } function checkLoaded() { var map, modId, err, usingPathFallback, waitInterval = config.waitSeconds * 1000, //It is possible to disable the wait interval by using waitSeconds of 0. expired = waitInterval && (context.startTime + waitInterval) < new Date().getTime(), noLoads = [], stillLoading = false, needCycleCheck = true; //Do not bother if this call was a result of a cycle break. if (inCheckLoaded) { return; } inCheckLoaded = true; //Figure out the state of all the modules. eachProp(registry, function (mod) { map = mod.map; modId = map.id; //Skip things that are not enabled or in error state. if (!mod.enabled) { return; } if (!mod.error) { //If the module should be executed, and it has not //been inited and time is up, remember it. if (!mod.inited && expired) { if (hasPathFallback(modId)) { usingPathFallback = true; stillLoading = true; } else { noLoads.push(modId); removeScript(modId); } } else if (!mod.inited && mod.fetched && map.isDefine) { stillLoading = true; if (!map.prefix) { //No reason to keep looking for unfinished //loading. If the only stillLoading is a //plugin resource though, keep going, //because it may be that a plugin resource //is waiting on a non-plugin cycle. return (needCycleCheck = false); } } } }); if (expired && noLoads.length) { //If wait time expired, throw error of unloaded modules. err = makeError('timeout', 'Load timeout for modules: ' + noLoads, null, noLoads); err.contextName = context.contextName; return onError(err); } //Not expired, check for a cycle. if (needCycleCheck) { each(waitAry, function (mod) { if (mod.defined) { return; } var cycleMod = findCycle(mod, {}, {}), traced = {}; if (cycleMod) { forceExec(cycleMod, traced, {}); //traced modules may have been //removed from the registry, but //their listeners still need to //be called. eachProp(traced, modCheck); } }); //Now that dependencies have //been satisfied, trigger the //completion check that then //notifies listeners. eachProp(registry, modCheck); } //If still waiting on loads, and the waiting load is something //other than a plugin resource, or there are still outstanding //scripts, then just try back later. if ((!expired || usingPathFallback) && stillLoading) { //Something is still waiting to load. Wait for it, but only //if a timeout is not already in effect. if ((isBrowser || isWebWorker) && !<API key>) { <API key> = setTimeout(function () { <API key> = 0; checkLoaded(); }, 50); } } inCheckLoaded = false; } Module = function (map) { this.events = undefEvents[map.id] || {}; this.map = map; this.shim = config.shim[map.id]; this.depExports = []; this.depMaps = []; this.depMatched = []; this.pluginMaps = {}; this.depCount = 0; /* this.exports this.factory this.depMaps = [], this.enabled, this.fetched */ }; Module.prototype = { init: function (depMaps, factory, errback, options) { options = options || {}; //Do not do more inits if already done. Can happen if there //are multiple define calls for the same module. That is not //a normal, common case, but it is also not unexpected. if (this.inited) { return; } this.factory = factory; if (errback) { //Register for errors on this module. this.on('error', errback); } else if (this.events.error) { //If no errback already, but there are error listeners //on this module, set up an errback to pass to the deps. errback = bind(this, function (err) { this.emit('error', err); }); } //Do a copy of the dependency array, so that //source inputs are not modified. For example //"shim" deps are passed in here directly, and //doing a direct modification of the depMaps array //would affect that config. this.depMaps = depMaps && depMaps.slice(0); this.depMaps.rjsSkipMap = depMaps.rjsSkipMap; this.errback = errback; //Indicate this module has be initialized this.inited = true; this.ignore = options.ignore; //Could have option to init this module in enabled mode, //or could have been previously marked as enabled. However, //the dependencies are not known until init is called. So //if enabled previously, now trigger dependencies as enabled. if (options.enabled || this.enabled) { //Enable this module and dependencies. //Will call this.check() this.enable(); } else { this.check(); } }, defineDepById: function (id, depExports) { var i; //Find the index for this dependency. each(this.depMaps, function (map, index) { if (map.id === id) { i = index; return true; } }); return this.defineDep(i, depExports); }, defineDep: function (i, depExports) { //Because of cycles, defined callback for a given //export can be called more than once. if (!this.depMatched[i]) { this.depMatched[i] = true; this.depCount -= 1; this.depExports[i] = depExports; } }, fetch: function () { if (this.fetched) { return; } this.fetched = true; context.startTime = (new Date()).getTime(); var map = this.map; //If the manager is for a plugin managed resource, //ask the plugin to load it now. if (this.shim) { makeRequire(this, true)(this.shim.deps || [], bind(this, function () { return map.prefix ? this.callPlugin() : this.load(); })); } else { //Regular dependency. return map.prefix ? this.callPlugin() : this.load(); } }, load: function () { var url = this.map.url; //Regular dependency. if (!urlFetched[url]) { urlFetched[url] = true; context.load(this.map.id, url); } }, /** * Checks is the module is ready to define itself, and if so, * define it. If the silent argument is true, then it will just * define, but not notify listeners, and not ask for a context-wide * check of all loaded modules. That is useful for cycle breaking. */ check: function (silent) { if (!this.enabled || this.enabling) { return; } var err, cjsModule, id = this.map.id, depExports = this.depExports, exports = this.exports, factory = this.factory; if (!this.inited) { this.fetch(); } else if (this.error) { this.emit('error', this.error); } else if (!this.defining) { //The factory could trigger another require call //that would result in checking this module to //define itself again. If already in the process //of doing that, skip this work. this.defining = true; if (this.depCount < 1 && !this.defined) { if (isFunction(factory)) { //If there is an error listener, favor passing //to that instead of throwing an error. if (this.events.error) { try { exports = context.execCb(id, factory, depExports, exports); } catch (e) { err = e; } } else { exports = context.execCb(id, factory, depExports, exports); } if (this.map.isDefine) { //If setting exports via 'module' is in play, //favor that over return value and exports. After that, //favor a non-undefined return value over exports use. cjsModule = this.module; if (cjsModule && cjsModule.exports !== undefined && //Make sure it is not already the exports value cjsModule.exports !== this.exports) { exports = cjsModule.exports; } else if (exports === undefined && this.usingExports) { //exports already set the defined value. exports = this.exports; } } if (err) { err.requireMap = this.map; err.requireModules = [this.map.id]; err.requireType = 'define'; return onError((this.error = err)); } } else { //Just a literal value exports = factory; } this.exports = exports; if (this.map.isDefine && !this.ignore) { defined[id] = exports; if (req.onResourceLoad) { req.onResourceLoad(context, this.map, this.depMaps); } } //Clean up delete registry[id]; this.defined = true; context.waitCount -= 1; if (context.waitCount === 0) { //Clear the wait array used for cycles. waitAry = []; } } //Finished the define stage. Allow calling check again //to allow define notifications below in the case of a //cycle. this.defining = false; if (!silent) { if (this.defined && !this.defineEmitted) { this.defineEmitted = true; this.emit('defined', this.exports); this.defineEmitComplete = true; } } } }, callPlugin: function () { var map = this.map, id = map.id, pluginMap = makeModuleMap(map.prefix, null, false, true); on(pluginMap, 'defined', bind(this, function (plugin) { var load, normalizedMap, normalizedMod, name = this.map.name, parentName = this.map.parentMap ? this.map.parentMap.name : null; //If current map is not normalized, wait for that //normalized name to load instead of continuing. if (this.map.unnormalized) { //Normalize the ID if the plugin allows it. if (plugin.normalize) { name = plugin.normalize(name, function (name) { return normalize(name, parentName, true); }) || ''; } normalizedMap = makeModuleMap(map.prefix + '!' + name, this.map.parentMap, false, true); on(normalizedMap, 'defined', bind(this, function (value) { this.init([], function () { return value; }, null, { enabled: true, ignore: true }); })); normalizedMod = registry[normalizedMap.id]; if (normalizedMod) { if (this.events.error) { normalizedMod.on('error', bind(this, function (err) { this.emit('error', err); })); } normalizedMod.enable(); } return; } load = bind(this, function (value) { this.init([], function () { return value; }, null, { enabled: true }); }); load.error = bind(this, function (err) { this.inited = true; this.error = err; err.requireModules = [id]; //Remove temp unnormalized modules for this module, //since they will never be resolved otherwise now. eachProp(registry, function (mod) { if (mod.map.id.indexOf(id + '_unnormalized') === 0) { removeWaiting(mod.map.id); } }); onError(err); }); //Allow plugins to load other code without having to know the //context or how to 'complete' the load. load.fromText = function (moduleName, text) { /*jslint evil: true */ var hasInteractive = useInteractive; //Turn off interactive script matching for IE for any define //calls in the text, then turn it back on at the end. if (hasInteractive) { useInteractive = false; } //Prime the system by creating a module instance for getModule(makeModuleMap(moduleName)); req.exec(text); if (hasInteractive) { useInteractive = true; } //Support anonymous modules. context.completeLoad(moduleName); }; //Use parentName here since the plugin's name is not reliable, //could be some weird string with no path that actually wants to //reference the parentName's path. plugin.load(map.name, makeRequire(map.parentMap, true, function (deps, cb, er) { deps.rjsSkipMap = true; return context.require(deps, cb, er); }), load, config); })); context.enable(pluginMap, this); this.pluginMaps[pluginMap.id] = pluginMap; }, enable: function () { this.enabled = true; if (!this.waitPushed) { waitAry.push(this); context.waitCount += 1; this.waitPushed = true; } //Set flag mentioning that the module is enabling, //so that immediate calls to the defined callbacks //for dependencies do not trigger inadvertent load //with the depCount still being zero. this.enabling = true; //Enable each dependency each(this.depMaps, bind(this, function (depMap, i) { var id, mod, handler; if (typeof depMap === 'string') { //Dependency needs to be converted to a depMap //and wired up to this module. depMap = makeModuleMap(depMap, (this.map.isDefine ? this.map : this.map.parentMap), false, !this.depMaps.rjsSkipMap); this.depMaps[i] = depMap; handler = handlers[depMap.id]; if (handler) { this.depExports[i] = handler(this); return; } this.depCount += 1; on(depMap, 'defined', bind(this, function (depExports) { this.defineDep(i, depExports); this.check(); })); if (this.errback) { on(depMap, 'error', this.errback); } } id = depMap.id; mod = registry[id]; //Skip special modules like 'require', 'exports', 'module' //Also, don't call enable if it is already enabled, //important in circular dependency cases. if (!handlers[id] && mod && !mod.enabled) { context.enable(depMap, this); } })); //Enable each plugin that is used in //a dependency eachProp(this.pluginMaps, bind(this, function (pluginMap) { var mod = registry[pluginMap.id]; if (mod && !mod.enabled) { context.enable(pluginMap, this); } })); this.enabling = false; this.check(); }, on: function (name, cb) { var cbs = this.events[name]; if (!cbs) { cbs = this.events[name] = []; } cbs.push(cb); }, emit: function (name, evt) { each(this.events[name], function (cb) { cb(evt); }); if (name === 'error') { //Now that the error handler was triggered, remove //the listeners, since this broken Module instance //can stay around for a while in the registry/waitAry. delete this.events[name]; } } }; function callGetModule(args) { getModule(makeModuleMap(args[0], null, true)).init(args[1], args[2]); } function removeListener(node, func, name, ieName) { //Favor detachEvent because of IE9 //issue, see attachEvent/addEventListener comment elsewhere //in this file. if (node.detachEvent && !isOpera) { //Probably IE. If not it will throw an error, which will be //useful to know. if (ieName) { node.detachEvent(ieName, func); } } else { node.removeEventListener(name, func, false); } } /** * Given an event from a script node, get the requirejs info from it, * and then removes the event listeners on the node. * @param {Event} evt * @returns {Object} */ function getScriptData(evt) { //Using currentTarget instead of target for Firefox 2.0's sake. Not //all old browsers will be supported, but this one was easy enough //to support and still makes sense. var node = evt.currentTarget || evt.srcElement; //Remove the listeners once here. removeListener(node, context.onScriptLoad, 'load', 'onreadystatechange'); removeListener(node, context.onScriptError, 'error'); return { node: node, id: node && node.getAttribute('data-requiremodule') }; } return (context = { config: config, contextName: contextName, registry: registry, defined: defined, urlFetched: urlFetched, waitCount: 0, defQueue: defQueue, Module: Module, makeModuleMap: makeModuleMap, /** * Set a configuration for the context. * @param {Object} cfg config object to integrate. */ configure: function (cfg) { //Make sure the baseUrl ends in a slash. if (cfg.baseUrl) { if (cfg.baseUrl.charAt(cfg.baseUrl.length - 1) !== '/') { cfg.baseUrl += '/'; } } //Save off the paths and packages since they require special processing, //they are additive. var pkgs = config.pkgs, shim = config.shim, paths = config.paths, map = config.map; //Mix in the config values, favoring the new values over //existing ones in context.config. mixin(config, cfg, true); //Merge paths. config.paths = mixin(paths, cfg.paths, true); //Merge map if (cfg.map) { config.map = mixin(map || {}, cfg.map, true, true); } //Merge shim if (cfg.shim) { eachProp(cfg.shim, function (value, id) { //Normalize the structure if (isArray(value)) { value = { deps: value }; } if (value.exports && !value.exports.__buildReady) { value.exports = context.makeShimExports(value.exports); } shim[id] = value; }); config.shim = shim; } //Adjust packages if necessary. if (cfg.packages) { each(cfg.packages, function (pkgObj) { var location; pkgObj = typeof pkgObj === 'string' ? { name: pkgObj } : pkgObj; location = pkgObj.location; //Create a brand new object on pkgs, since currentPackages can //be passed in again, and config.pkgs is the internal transformed //state for all package configs. pkgs[pkgObj.name] = { name: pkgObj.name, location: location || pkgObj.name, //Remove leading dot in main, so main paths are normalized, //and remove any trailing .js, since different package //envs have different conventions: some use a module name, //some use a file name. main: (pkgObj.main || 'main') .replace(currDirRegExp, '') .replace(jsSuffixRegExp, '') }; }); //Done with modifications, assing packages back to context config config.pkgs = pkgs; } //If there are any "waiting to execute" modules in the registry, //update the maps for them, since their info, like URLs to load, //may have changed. eachProp(registry, function (mod, id) { //If module already has init called, since it is too //late to modify them, and ignore unnormalized ones //since they are transient. if (!mod.inited && !mod.map.unnormalized) { mod.map = makeModuleMap(id); } }); //If a deps array or a config callback is specified, then call //require with those args. This is useful when require is defined as a //config object before require.js is loaded. if (cfg.deps || cfg.callback) { context.require(cfg.deps || [], cfg.callback); } }, makeShimExports: function (exports) { var func; if (typeof exports === 'string') { func = function () { return getGlobal(exports); }; //Save the exports for use in nodefine checking. func.exports = exports; return func; } else { return function () { return exports.apply(global, arguments); }; } }, requireDefined: function (id, relMap) { return hasProp(defined, makeModuleMap(id, relMap, false, true).id); }, requireSpecified: function (id, relMap) { id = makeModuleMap(id, relMap, false, true).id; return hasProp(defined, id) || hasProp(registry, id); }, require: function (deps, callback, errback, relMap) { var moduleName, id, map, requireMod, args; if (typeof deps === 'string') { if (isFunction(callback)) { //Invalid call return onError(makeError('requireargs', 'Invalid require call'), errback); } //Synchronous access to one module. If require.get is //available (as in the Node adapter), prefer that. //In this case deps is the moduleName and callback is //the relMap if (req.get) { return req.get(context, deps, callback); } //Just return the module wanted. In this scenario, the //second arg (if passed) is just the relMap. moduleName = deps; relMap = callback; //Normalize module name, if it contains . or .. map = makeModuleMap(moduleName, relMap, false, true); id = map.id; if (!hasProp(defined, id)) { return onError(makeError('notloaded', 'Module name "' + id + '" has not been loaded yet for context: ' + contextName)); } return defined[id]; } //Callback require. Normalize args. if callback or errback is //not a function, it means it is a relMap. Test errback first. if (errback && !isFunction(errback)) { relMap = errback; errback = undefined; } if (callback && !isFunction(callback)) { relMap = callback; callback = undefined; } //Any defined modules in the global queue, intake them now. takeGlobalQueue(); //Make sure any remaining defQueue items get properly processed. while (defQueue.length) { args = defQueue.shift(); if (args[0] === null) { return onError(makeError('mismatch', 'Mismatched anonymous define() module: ' + args[args.length - 1])); } else { //args are id, deps, factory. Should be normalized by the //define() function. callGetModule(args); } } //Mark all the dependencies as needing to be loaded. requireMod = getModule(makeModuleMap(null, relMap)); requireMod.init(deps, callback, errback, { enabled: true }); checkLoaded(); return context.require; }, undef: function (id) { //Bind any waiting define() calls to this context, //fix for #408 takeGlobalQueue(); var map = makeModuleMap(id, null, true), mod = registry[id]; delete defined[id]; delete urlFetched[map.url]; delete undefEvents[id]; if (mod) { //Hold on to listeners in case the //module will be attempted to be reloaded //using a different config. if (mod.events.defined) { undefEvents[id] = mod.events; } removeWaiting(id); } }, /** * Called to enable a module if it is still in the registry * awaiting enablement. parent module is passed in for context, * used by the optimizer. */ enable: function (depMap, parent) { var mod = registry[depMap.id]; if (mod) { getModule(depMap).enable(); } }, /** * Internal method used by environment adapters to complete a load event. * A load event could be a script load or just a load pass from a synchronous * load call. * @param {String} moduleName the name of the module to potentially complete. */ completeLoad: function (moduleName) { var found, args, mod, shim = config.shim[moduleName] || {}, shExports = shim.exports && shim.exports.exports; takeGlobalQueue(); while (defQueue.length) { args = defQueue.shift(); if (args[0] === null) { args[0] = moduleName; //If already found an anonymous module and bound it //to this name, then this is some other anon module //waiting for its completeLoad to fire. if (found) { break; } found = true; } else if (args[0] === moduleName) { //Found matching define call for this script! found = true; } callGetModule(args); } //Do this after the cycle of callGetModule in case the result //of those calls/init calls changes the registry. mod = registry[moduleName]; if (!found && !defined[moduleName] && mod && !mod.inited) { if (config.enforceDefine && (!shExports || !getGlobal(shExports))) { if (hasPathFallback(moduleName)) { return; } else { return onError(makeError('nodefine', 'No define call for ' + moduleName, null, [moduleName])); } } else { //A script that does not call define(), so just simulate //the call for it. callGetModule([moduleName, (shim.deps || []), shim.exports]); } } checkLoaded(); }, /** * Converts a module name + .extension into an URL path. * *Requires* the use of a module name. It does not support using * plain URLs like nameToUrl. */ toUrl: function (moduleNamePlusExt, relModuleMap) { var index = moduleNamePlusExt.lastIndexOf('.'), ext = null; if (index !== -1) { ext = moduleNamePlusExt.substring(index, moduleNamePlusExt.length); moduleNamePlusExt = moduleNamePlusExt.substring(0, index); } return context.nameToUrl(normalize(moduleNamePlusExt, relModuleMap && relModuleMap.id, true), ext); }, /** * Converts a module name to a file path. Supports cases where * moduleName may actually be just an URL. * Note that it **does not** call normalize on the moduleName, * it is assumed to have already been normalized. This is an * internal API, not a public one. Use toUrl for the public API. */ nameToUrl: function (moduleName, ext) { var paths, pkgs, pkg, pkgPath, syms, i, parentModule, url, parentPath; //If a colon is in the URL, it indicates a protocol is used and it is just //an URL to a file, or if it starts with a slash, contains a query arg (i.e. ?) //or ends with .js, then assume the user meant to use an url and not a module id. //The slash is important for protocol-less URLs as well as full paths. if (req.jsExtRegExp.test(moduleName)) { //Just a plain path, not module name lookup, so just return it. //Add extension if it is included. This is a bit wonky, only non-.js things pass //an extension, this method probably needs to be reworked. url = moduleName + (ext || ''); } else { //A module that needs to be converted to a path. paths = config.paths; pkgs = config.pkgs; syms = moduleName.split('/'); //For each module name segment, see if there is a path //registered for it. Start with most specific name //and work up from it. for (i = syms.length; i > 0; i -= 1) { parentModule = syms.slice(0, i).join('/'); pkg = pkgs[parentModule]; parentPath = paths[parentModule]; if (parentPath) { //If an array, it means there are a few choices, //Choose the one that is desired if (isArray(parentPath)) { parentPath = parentPath[0]; } syms.splice(0, i, parentPath); break; } else if (pkg) { //If module name is just the package name, then looking //for the main module. if (moduleName === pkg.name) { pkgPath = pkg.location + '/' + pkg.main; } else { pkgPath = pkg.location; } syms.splice(0, i, pkgPath); break; } } //Join the path parts together, then figure out if baseUrl is needed. url = syms.join('/'); url += (ext || (/\?/.test(url) ? '' : '.js')); url = (url.charAt(0) === '/' || url.match(/^[\w\+\.\-]+:/) ? '' : config.baseUrl) + url; } return config.urlArgs ? url + ((url.indexOf('?') === -1 ? '?' : '&') + config.urlArgs) : url; }, //Delegates to req.load. Broken out as a separate function to //allow overriding in the optimizer. load: function (id, url) { req.load(context, id, url); }, /** * Executes a module callack function. Broken out as a separate function * solely to allow the build system to sequence the files in the built * layer in the right sequence. * * @private */ execCb: function (name, callback, args, exports) { return callback.apply(exports, args); }, /** * callback for script loads, used to check status of loading. * * @param {Event} evt the event from the browser for the script * that was loaded. */ onScriptLoad: function (evt) { //Using currentTarget instead of target for Firefox 2.0's sake. Not //all old browsers will be supported, but this one was easy enough //to support and still makes sense. if (evt.type === 'load' || (readyRegExp.test((evt.currentTarget || evt.srcElement).readyState))) { //Reset interactive script so a script node is not held onto for //to long. interactiveScript = null; //Pull out the name of the module and the context. var data = getScriptData(evt); context.completeLoad(data.id); } }, /** * Callback for script errors. */ onScriptError: function (evt) { var data = getScriptData(evt); if (!hasPathFallback(data.id)) { return onError(makeError('scripterror', 'Script error', evt, [data.id])); } } }); } /** * Main entry point. * * If the only argument to require is a string, then the module that * is represented by that string is fetched for the appropriate context. * * If the first argument is an array, then it will be treated as an array * of dependency string names to fetch. An optional function callback can * be specified to execute when all of those dependencies are available. * * Make a local req variable to help Caja compliance (it assumes things * on a require that are not standardized), and to give a short * name for minification/local scope use. */ req = requirejs = function (deps, callback, errback, optional) { //Find the right context, use default var context, config, contextName = defContextName; // Determine if have config object in the call. if (!isArray(deps) && typeof deps !== 'string') { // deps is a config object config = deps; if (isArray(callback)) { // Adjust args if there are dependencies deps = callback; callback = errback; errback = optional; } else { deps = []; } } if (config && config.context) { contextName = config.context; } context = contexts[contextName]; if (!context) { context = contexts[contextName] = req.s.newContext(contextName); } if (config) { context.configure(config); } return context.require(deps, callback, errback); }; /** * Support require.config() to make it easier to cooperate with other * AMD loaders on globally agreed names. */ req.config = function (config) { return req(config); }; /** * Export require as a global, but only if it does not already exist. */ if (!require) { require = req; } req.version = version; //Used to filter out dependencies that are already paths. req.jsExtRegExp = /^\/|:|\?|\.js$/; req.isBrowser = isBrowser; s = req.s = { contexts: contexts, newContext: newContext }; //Create default context. req({}); //Exports some context-sensitive methods on global require, using //default context if no context specified. addRequireMethods(req); if (isBrowser) { head = s.head = document.<API key>('head')[0]; //If BASE tag is in play, using appendChild is a problem for IE6. //When that browser dies, this can be removed. Details in this jQuery bug: baseElement = document.<API key>('base')[0]; if (baseElement) { head = s.head = baseElement.parentNode; } } /** * Any errors that require explicitly generates will be passed to this * function. Intercept/override it if you want custom error handling. * @param {Error} err the error object. */ req.onError = function (err) { throw err; }; /** * Does the request to load a module for the browser case. * Make this a separate function to allow other environments * to override it. * * @param {Object} context the require context to find state. * @param {String} moduleName the name of the module. * @param {Object} url the URL to the module. */ req.load = function (context, moduleName, url) { var config = (context && context.config) || {}, node; if (isBrowser) { //In the browser so use a script tag node = config.xhtml ? document.createElementNS('http: document.createElement('script'); node.type = config.scriptType || 'text/javascript'; node.charset = 'utf-8'; node.async = true; node.setAttribute('data-requirecontext', context.contextName); node.setAttribute('data-requiremodule', moduleName); //Set up load listener. Test attachEvent first because IE9 has //a subtle issue in its addEventListener and script onload firings //that do not match the behavior of all other browsers with //addEventListener support, which fire the onload event for a //script right after the script execution. See: //UNFORTUNATELY Opera implements attachEvent but does not follow the script //script execution mode. if (node.attachEvent && //Check if node.attachEvent is artificially added by custom script or //natively supported by browser //if we can NOT find [native code] then it must NOT natively supported. //in IE8, node.attachEvent does not have toString() //Note the test for "[native code" with no closing brace, see: !(node.attachEvent.toString && node.attachEvent.toString().indexOf('[native code') < 0) && !isOpera) { //Probably IE. IE (at least 6-8) do not fire //script onload right after executing the script, so //we cannot tie the anonymous define call to a name. //However, IE reports the script as being in 'interactive' //readyState at the time of the define call. useInteractive = true; node.attachEvent('onreadystatechange', context.onScriptLoad); //It would be great to add an error handler here to catch //404s in IE9+. However, onreadystatechange will fire before //the error handler, so that does not help. If addEvenListener //is used, then IE will fire error before load, but we cannot //use that pathway given the connect.microsoft.com issue //mentioned above about not doing the 'script execute, //then fire the script load event listener before execute //next script' that other browsers do. //Best hope: IE10 fixes the issues, //and then destroys all installs of IE 6-9. //node.attachEvent('onerror', context.onScriptError); } else { node.addEventListener('load', context.onScriptLoad, false); node.addEventListener('error', context.onScriptError, false); } node.src = url; //For some cache cases in IE 6-8, the script executes before the end //of the appendChild execution, so to tie an anonymous define //call to the module name (which is stored on the node), hold on //to a reference to this node, but clear after the DOM insertion. <API key> = node; if (baseElement) { head.insertBefore(node, baseElement); } else { head.appendChild(node); } <API key> = null; return node; } else if (isWebWorker) { //In a web worker, use importScripts. This is not a very //efficient use of importScripts, importScripts will block until //its script is downloaded and evaluated. However, if web workers //are in play, the expectation that a build has been done so that //only one script needs to be loaded anyway. This may need to be //reevaluated if other use cases become common. importScripts(url); //Account for anonymous modules context.completeLoad(moduleName); } }; function <API key>() { if (interactiveScript && interactiveScript.readyState === 'interactive') { return interactiveScript; } eachReverse(scripts(), function (script) { if (script.readyState === 'interactive') { return (interactiveScript = script); } }); return interactiveScript; } //Look for a data-main script attribute, which could also adjust the baseUrl. if (isBrowser) { //Figure out baseUrl. Get it from the script tag with require.js in it. eachReverse(scripts(), function (script) { //Set the 'head' where we can append children by //using the script's parent. if (!head) { head = script.parentNode; } //Look for a data-main attribute to set main script for the page //to load. If it is there, the path to data main becomes the //baseUrl, if it is not already set. dataMain = script.getAttribute('data-main'); if (dataMain) { //Set final baseUrl if there is not already an explicit one. if (!cfg.baseUrl) { //Pull off the directory of data-main for use as the //baseUrl. src = dataMain.split('/'); mainScript = src.pop(); subPath = src.length ? src.join('/') + '/' : './'; cfg.baseUrl = subPath; dataMain = mainScript; } //Strip off any trailing .js since dataMain is now //like a module name. dataMain = dataMain.replace(jsSuffixRegExp, ''); //Put the data-main script in the files to load. cfg.deps = cfg.deps ? cfg.deps.concat(dataMain) : [dataMain]; return true; } }); } /** * The function that handles definitions of modules. Differs from * require() in that a string for the module should be the first argument, * and the function to execute after dependencies are loaded should * return a value to define the module corresponding to the first argument's * name. */ define = function (name, deps, callback) { var node, context; //Allow for anonymous functions if (typeof name !== 'string') { //Adjust args appropriately callback = deps; deps = name; name = null; } //This module may not have dependencies if (!isArray(deps)) { callback = deps; deps = []; } //If no name, and callback is a function, then figure out if it a //CommonJS thing with dependencies. if (!deps.length && isFunction(callback)) { //Remove comments from the callback string, //look for require calls, and pull them into the dependencies, //but only if there are function args. if (callback.length) { callback .toString() .replace(commentRegExp, '') .replace(cjsRequireRegExp, function (match, dep) { deps.push(dep); }); //May be a CommonJS thing even without require calls, but still //could use exports, and module. Avoid doing exports and module //work though if it just needs require. //REQUIRES the function to expect the CommonJS variables in the //order listed below. deps = (callback.length === 1 ? ['require'] : ['require', 'exports', 'module']).concat(deps); } } //If in IE 6-8 and hit an anonymous define() call, do the interactive //work. if (useInteractive) { node = <API key> || <API key>(); if (node) { if (!name) { name = node.getAttribute('data-requiremodule'); } context = contexts[node.getAttribute('data-requirecontext')]; } } //Always save off evaluating the def call until the script onload handler. //This allows multiple modules to be in a file without prematurely //tracing dependencies, and allows for anonymous module support, //where the module name is not known until the script onload event //occurs. If no context, use the global queue, and get it processed //in the onscript load callback. (context ? context.defQueue : globalDefQueue).push([name, deps, callback]); }; define.amd = { jQuery: true }; /** * Executes the text. Normally just uses eval, but can be modified * to use a better, <API key> call. Only used for transpiling * loader plugins, not for plain JS modules. * @param {String} text the text to execute/evaluate. */ req.exec = function (text) { /*jslint evil: true */ return eval(text); }; //Set up with config info. req(cfg); }(this)); var jam = { "packages": [ { "name": "backbone", "location": "../vendor/jam/backbone", "main": "backbone.js" }, { "name": "backbone.layoutmanager", "location": "../vendor/jam/backbone.layoutmanager", "main": "backbone.layoutmanager.js" }, { "name": "jquery", "location": "../vendor/jam/jquery", "main": "dist/jquery.js" }, { "name": "lodash", "location": "../vendor/jam/lodash", "main": "./lodash.js" }, { "name": "underscore", "location": "../vendor/jam/underscore", "main": "underscore.js" } ], "version": "0.2.11", "shim": { "backbone": { "deps": [ "lodash" ], "exports": "Backbone" }, "backbone.layoutmanager": { "deps": [ "jquery", "backbone", "underscore" ], "exports": "Backbone.Layout" }, "underscore": { "exports": "_" } } }; if (typeof require !== "undefined" && require.config) { require.config({packages: jam.packages, shim: jam.shim}); } else { var require = {packages: jam.packages, shim: jam.shim}; } if (typeof exports !== "undefined" && typeof module !== "undefined") { module.exports = jam; }
// XMLHTTPRequest.h // XMLHttpRequest // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // all copies or substantial portions of the Software. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #ifndef <API key> #define <API key> #include "network/HttpClient.h" #include "js_bindings_config.h" #include "ScriptingCore.h" #include "jstypes.h" #include "jsapi.h" #include "jsfriendapi.h" #include "jsb_helper.h" class MinXmlHttpRequest : public cocos2d::Object { public: enum class ResponseType { STRING, ARRAY_BUFFER, BLOB, DOCUMENT, JSON }; // Ready States (http://www.w3.org/TR/XMLHttpRequest/#<API key>) static const unsigned short UNSENT = 0; static const unsigned short OPENED = 1; static const unsigned short HEADERS_RECEIVED = 2; static const unsigned short LOADING = 3; static const unsigned short DONE = 4; MinXmlHttpRequest(); ~MinXmlHttpRequest(); <API key>(MinXmlHttpRequest); <API key>(MinXmlHttpRequest); <API key>(MinXmlHttpRequest, onreadystatechange); <API key>(MinXmlHttpRequest, responseType); <API key>(MinXmlHttpRequest, withCredentials); <API key>(MinXmlHttpRequest, upload); <API key>(MinXmlHttpRequest, timeout); JS_BINDED_PROP_GET(MinXmlHttpRequest, readyState); JS_BINDED_PROP_GET(MinXmlHttpRequest, status); JS_BINDED_PROP_GET(MinXmlHttpRequest, statusText); JS_BINDED_PROP_GET(MinXmlHttpRequest, responseText); JS_BINDED_PROP_GET(MinXmlHttpRequest, response); JS_BINDED_PROP_GET(MinXmlHttpRequest, responseXML); JS_BINDED_FUNC(MinXmlHttpRequest, open); JS_BINDED_FUNC(MinXmlHttpRequest, send); JS_BINDED_FUNC(MinXmlHttpRequest, abort); JS_BINDED_FUNC(MinXmlHttpRequest, <API key>); JS_BINDED_FUNC(MinXmlHttpRequest, getResponseHeader); JS_BINDED_FUNC(MinXmlHttpRequest, setRequestHeader); JS_BINDED_FUNC(MinXmlHttpRequest, overrideMimeType); void <API key>(cocos2d::network::HttpClient *sender, cocos2d::network::HttpResponse *response); private: void _gotHeader(std::string header); void _setRequestHeader(const char* field, const char* value); void <API key>(); void _sendRequest(JSContext *cx); std::string _url; JSContext* _cx; std::string _meth; std::string _type; char* _data; uint32_t _dataSize; JSObject* <API key>; int _readyState; int _status; std::string _statusText; ResponseType _responseType; unsigned _timeout; bool _isAsync; cocos2d::network::HttpRequest* _httpRequest; bool _isNetwork; bool <API key>; std::unordered_map<std::string, std::string> _httpHeader; std::unordered_map<std::string, std::string> _requestHeader; }; #endif
package org.openhab.io.imperihome.internal.model.device; import java.math.BigDecimal; import org.apache.commons.lang.StringUtils; import org.eclipse.smarthome.core.items.Item; import org.eclipse.smarthome.core.library.types.HSBType; import org.eclipse.smarthome.core.library.types.PercentType; import org.eclipse.smarthome.core.types.State; import org.openhab.io.imperihome.internal.model.param.DeviceParam; import org.openhab.io.imperihome.internal.model.param.ParamType; /** * RGB light device. * * @author Pepijn de Geus - Initial contribution */ public class RgbLightDevice extends <API key> { public RgbLightDevice(Item item) { super(DeviceType.RGB_LIGHT, item); } @Override public void stateUpdated(Item item, State newState) { super.stateUpdated(item, newState); boolean status = false; int level = 0; String color = "00000000"; State state = item.getStateAs(HSBType.class); boolean isHsbState = state instanceof HSBType; // State can be of UndefType, even with the getStateAs above if (isHsbState) { HSBType hsbState = (HSBType) state; PercentType[] rgb = hsbState.toRGB(); // Set state to ON if any channel > 0 boolean isOn = rgb[0].doubleValue() > 0 || rgb[1].doubleValue() > 0 || rgb[2].doubleValue() > 0; if (isOn) { status = true; } // Build hex string int r = <API key>(rgb[0]) & 0xFF; int g = <API key>(rgb[1]) & 0xFF; int b = <API key>(rgb[2]) & 0xFF; color = (isOn ? "FF" : "00") + toHex(r) + toHex(g) + toHex(b); } State pState = item.getStateAs(PercentType.class); if (pState instanceof PercentType) { level = ((PercentType) pState).intValue(); if (level > 0) { status = true; } } addParam(new DeviceParam(ParamType.STATUS, status ^ isInverted() ? "1" : "0")); addParam(new DeviceParam(ParamType.LEVEL, String.valueOf(level))); addParam(new DeviceParam(ParamType.DIMMABLE, "0")); addParam(new DeviceParam(ParamType.WHITE_CHANNEL, "1")); addParam(new DeviceParam(ParamType.COLOR, color)); } private String toHex(int value) { String hex = Integer.toHexString(value); return StringUtils.leftPad(hex, 2, '0'); } private int <API key>(PercentType percent) { return percent.toBigDecimal().multiply(BigDecimal.valueOf(255)) .divide(BigDecimal.valueOf(100), 2, BigDecimal.ROUND_HALF_UP).intValue(); } }
<?php include_once("../../../config.php"); require_login(); if (empty($CFG->aspellpath)) { error('Spellchecker not configured'); } header('Content-type: text/html; charset=utf-8'); $aspell_prog = escapeshellarg($CFG->aspellpath); $spellercss = $CFG->wwwroot .'/lib/speller/spellerStyle.css'; $word_win_src = $CFG->wwwroot .'/lib/speller/wordWindow.js'; $textinputs = $_POST['textinputs']; // array if(!($lang = check_language($aspell_prog))) { error_handler("No suitable dictionary found installed on your server!"); exit; } $aspell_opts = '-a -H --lang='. $lang .' --encoding=utf-8'; if (!empty($CFG->aspellextradicts)) { // eg /usr/bin/.aspell.en.pws $aspell_opts .= ' --add-extra-dicts='.$CFG->aspellextradicts; } $tempfiledir = $CFG->dataroot; // Use dataroot since it must be writable $input_separator = 'A'; function check_language($cmd) { return users current language if its dictionary is found installed in system and always return english if user's own language is not in the list. If english dictionary isn't found, then false is returned. global $CFG; clearstatcache(); $current_lang = str_replace('_utf8', '', current_language()); $output = ''; if(!($handle = popen($cmd .' dump dicts', 'r'))) { error_handler("Couldn't create handle!"); exit; } while(!feof($handle)) { $output .= fread($handle, 1024); } @pclose($handle); $dicts = explode(chr(10), strtolower($output)); if(is_array($dicts)) { if(in_array($current_lang,$dicts)) { return $current_lang; } } if (!empty($CFG->editordictionary)) { return $CFG->editordictionary; } return false; } // set the JavaScript variable to the submitted text. // textinputs is an array, each element corresponding to the (url-encoded) // value of the text control submitted for spell-checking function <API key>() { global $textinputs; foreach( $textinputs as $key=>$val ) { // $val = str_replace( "'", "%27", $val ); echo "textinputs[$key] = decodeURIComponent(\"" . $val . "\");\n"; } } // make declarations for the text input index function <API key>( $text_input_idx ) { echo "words[$text_input_idx] = [];\n"; echo "suggs[$text_input_idx] = [];\n"; } // set an element of the JavaScript 'words' array to a misspelled word function print_words_elem( $word, $index, $text_input_idx ) { echo "words[$text_input_idx][$index] = '" . escape_quote( $word ) . "';\n"; } // set an element of the JavaScript 'suggs' array to a list of suggestions function print_suggs_elem( $suggs, $index, $text_input_idx ) { echo "suggs[$text_input_idx][$index] = ["; foreach( $suggs as $key=>$val ) { if( $val ) { echo "'" . escape_quote( $val ) . "'"; if ( $key+1 < count( $suggs )) { echo ", "; } } } echo "];\n"; } // escape single quote function escape_quote( $str ) { return preg_replace ( "/'/", "\\'", $str ); } // handle a server-side error. function error_handler( $err ) { echo "error = '" . escape_quote( $err ) . "';\n"; } // get the list of misspelled words. Put the results in the javascript words array // for each misspelled word, get suggestions and put in the javascript suggs array function <API key>() { global $aspell_prog; global $aspell_opts; global $tempfiledir; global $textinputs; global $input_separator; $aspell_err = ""; // create temp file $tempfile = tempnam( $tempfiledir, 'aspell_data_' ); // open temp file, add the submitted text. if( $fh = fopen( $tempfile, 'w' )) { for( $i = 0; $i < count( $textinputs ); $i++ ) { $text = urldecode( $textinputs[$i] ); $lines = explode( "\n", $text ); fwrite ( $fh, "%\n" ); // exit terse mode fwrite ( $fh, "^$input_separator\n" ); fwrite ( $fh, "!\n" ); // enter terse mode foreach( $lines as $key=>$value ) { // use carat on each line to escape possible aspell commands fwrite( $fh, "^$value\n" ); } } fclose( $fh ); // exec aspell command - redirect STDERR to STDOUT $cmd = "$aspell_prog $aspell_opts < $tempfile 2>&1"; if( $aspellret = shell_exec( $cmd )) { $linesout = explode( "\n", $aspellret ); $index = 0; $text_input_index = -1; // parse each line of aspell return foreach( $linesout as $key=>$val ) { $chardesc = substr( $val, 0, 1 ); // if '&', then not in dictionary but has suggestions // if '#', then not in dictionary and no suggestions // if '*', then it is a delimiter between text inputs // if '@' then version info if( $chardesc == '&' || $chardesc == ' $line = explode( " ", $val, 5 ); print_words_elem( $line[1], $index, $text_input_index ); if( isset( $line[4] )) { $suggs = explode( ", ", $line[4] ); } else { $suggs = array(); } print_suggs_elem( $suggs, $index, $text_input_index ); $index++; } elseif( $chardesc == '*' ) { $text_input_index++; <API key>( $text_input_index ); $index = 0; } elseif( $chardesc != '@' && $chardesc != "" ) { // assume this is error output $aspell_err .= $val; } } if( $aspell_err ) { $aspell_err = "Error executing `$cmd`\\n$aspell_err"; error_handler( $aspell_err ); } } else { error_handler( "System error: Aspell program execution failed (`$cmd`)" ); } } else { error_handler( "System error: Could not open file '$tempfile' for writing" ); } // close temp file, delete file unlink( $tempfile ); } ?> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <link rel="stylesheet" type="text/css" href="<?php echo $spellercss ?>" /> <script type="text/javascript" src="<?php echo $word_win_src ?>"></script> <script type="text/javascript"> //<![CDATA[ var suggs = new Array(); var words = new Array(); var textinputs = new Array(); var error; <?php <API key>(); <API key>(); ?> var wordWindowObj = new wordWindow(); wordWindowObj.originalSpellings = words; wordWindowObj.suggestions = suggs; wordWindowObj.textInputs = textinputs; function init_spell() { // check if any error occured during server-side processing if( error ) { alert( error ); } else { // call the init_spell() function in the parent frameset if (parent.frames.length) { parent.init_spell( wordWindowObj ); } else { alert('This page was loaded outside of a frameset. It might not display properly'); } } } </script> </head> <body onLoad="init_spell();"> <script type="text/javascript"> //<![CDATA[ wordWindowObj.writeBody(); </script> </body> </html>
/* ScriptData SDName: Azshara SD%Complete: 90 SDComment: Quest support: 2744, 3141, 9364, 10994 SDCategory: Azshara EndScriptData */ /* ContentData npc_spitelashes <API key> <API key> npc_depth_charge EndContentData */ #include "ScriptMgr.h" #include "ScriptedCreature.h" #include "ScriptedGossip.h" #include "Player.h" #include "SpellInfo.h" class npc_spitelashes : public CreatureScript { public: npc_spitelashes() : CreatureScript("npc_spitelashes") { } CreatureAI* GetAI(Creature* creature) const OVERRIDE { return new npc_spitelashesAI(creature); } struct npc_spitelashesAI : public ScriptedAI { npc_spitelashesAI(Creature* creature) : ScriptedAI(creature) {} uint32 morphtimer; bool spellhit; void Reset() OVERRIDE { morphtimer = 0; spellhit = false; } void EnterCombat(Unit* /*who*/) OVERRIDE {} void SpellHit(Unit* unit, const SpellInfo* spell) OVERRIDE { if (spellhit) return; switch (spell->Id) { case 118: case 12824: case 12825: case 12826: if (Player* player = unit->ToPlayer()) if (player->GetQuestStatus(9364) == <API key>) { spellhit = true; DoCast(me, 29124); } break; default: break; } } void UpdateAI(uint32 diff) OVERRIDE { // we mustn't remove the Creature in the same round in which we cast the summon spell, otherwise there will be no summons if (spellhit && morphtimer >= 5000) { me->DespawnOrUnsummon(); return; } // walk 5 seconds before summoning if (spellhit && morphtimer<5000) { morphtimer+=diff; if (morphtimer >= 5000) { DoCast(me, 28406); //summon copies DoCast(me, 6924); //visual explosion } } if (!UpdateVictim()) return; @todo add abilities for the different creatures <API key>(); } }; }; #define GOSSIP_HELLO_LT1 "Can you help me?" #define GOSSIP_HELLO_LT2 "Tell me your story" #define GOSSIP_SELECT_LT1 "Please continue" #define GOSSIP_SELECT_LT2 "I do not understand" #define GOSSIP_SELECT_LT3 "Indeed" #define GOSSIP_SELECT_LT4 "I will do this with or your help, Loramus" #define GOSSIP_SELECT_LT5 "Yes" class <API key> : public CreatureScript { public: <API key>() : CreatureScript("<API key>") { } bool OnGossipSelect(Player* player, Creature* creature, uint32 /*sender*/, uint32 action) OVERRIDE { player->PlayerTalkClass->ClearMenus(); switch (action) { case <API key>+1: player->CLOSE_GOSSIP_MENU(); player-><API key>(2744); break; case <API key>+2: player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_SELECT_LT1, GOSSIP_SENDER_MAIN, <API key> + 21); player->SEND_GOSSIP_MENU(1813, creature->GetGUID()); break; case <API key>+21: player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_SELECT_LT2, GOSSIP_SENDER_MAIN, <API key> + 22); player->SEND_GOSSIP_MENU(1814, creature->GetGUID()); break; case <API key>+22: player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_SELECT_LT3, GOSSIP_SENDER_MAIN, <API key> + 23); player->SEND_GOSSIP_MENU(1815, creature->GetGUID()); break; case <API key>+23: player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_SELECT_LT4, GOSSIP_SENDER_MAIN, <API key> + 24); player->SEND_GOSSIP_MENU(1816, creature->GetGUID()); break; case <API key>+24: player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_SELECT_LT5, GOSSIP_SENDER_MAIN, <API key> + 25); player->SEND_GOSSIP_MENU(1817, creature->GetGUID()); break; case <API key>+25: player->CLOSE_GOSSIP_MENU(); player-><API key>(3141); break; } return true; } bool OnGossipHello(Player* player, Creature* creature) OVERRIDE { if (creature->IsQuestGiver()) player->PrepareQuestMenu(creature->GetGUID()); if (player->GetQuestStatus(2744) == <API key>) player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_HELLO_LT1, GOSSIP_SENDER_MAIN, <API key>+1); if (player->GetQuestStatus(3141) == <API key>) player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_HELLO_LT2, GOSSIP_SENDER_MAIN, <API key>+2); player->SEND_GOSSIP_MENU(player->GetGossipTextId(creature), creature->GetGUID()); return true; } }; enum <API key> { <API key> = 10994, NPC_DEPTH_CHARGE = 23025, <API key> = 39865, SPELL_RIZZLE_ESCAPE = 39871, <API key> = 40525, <API key> = 38576, <API key> = 39912, <API key> = 39886, SAY_RIZZLE_START = 0, SAY_RIZZLE_GRENADE = 1, SAY_RIZZLE_FINAL = 2, MSG_ESCAPE_NOTICE = 3 }; #define <API key> "Hand over the Southfury moonstone and I'll let you go." Position const WPs[58] = { {3691.97f, -3962.41f, 35.9118f, 3.67f}, {3675.02f, -3960.49f, 35.9118f, 3.67f}, {3653.19f, -3958.33f, 33.9118f, 3.59f}, {3621.12f, -3958.51f, 29.9118f, 3.48f}, {3604.86f, -3963, 29.9118f, 3.48f}, {3569.94f, -3970.25f, 29.9118f, 3.44f}, {3541.03f, -3975.64f, 29.9118f, 3.41f}, {3510.84f, -3978.71f, 29.9118f, 3.41f}, {3472.7f, -3997.07f, 29.9118f, 3.35f}, {3439.15f, -4014.55f, 29.9118f, 3.29f}, {3412.8f, -4025.87f, 29.9118f, 3.25f}, {3384.95f, -4038.04f, 29.9118f, 3.24f}, {3346.77f, -4052.93f, 29.9118f, 3.22f}, {3299.56f, -4071.59f, 29.9118f, 3.20f}, {3261.22f, -4080.38f, 30.9118f, 3.19f}, {3220.68f, -4083.09f, 31.9118f, 3.18f}, {3187.11f, -4070.45f, 33.9118f, 3.16f}, {3162.78f, -4062.75f, 33.9118f, 3.15f}, {3136.09f, -4050.32f, 33.9118f, 3.07f}, {3119.47f, -4044.51f, 36.0363f, 3.07f}, {3098.95f, -4019.8f, 33.9118f, 3.07f}, {3073.07f, -4011.42f, 33.9118f, 3.07f}, {3051.71f, -3993.37f, 33.9118f, 3.02f}, {3027.52f, -3978.6f, 33.9118f, 3.00f}, {3003.78f, -3960.14f, 33.9118f, 2.98f}, {2977.99f, -3941.98f, 31.9118f, 2.96f}, {2964.57f, -3932.07f, 30.9118f, 2.96f}, {2947.9f, -3921.31f, 29.9118f, 2.96f}, {2924.91f, -3910.8f, 29.9118f, 2.94f}, {2903.04f, -3896.42f, 29.9118f, 2.93f}, {2884.75f, -3874.03f, 29.9118f, 2.90f}, {2868.19f, -3851.48f, 29.9118f, 2.82f}, {2854.62f, -3819.72f, 29.9118f, 2.80f}, {2825.53f, -3790.4f, 29.9118f, 2.744f}, {2804.31f, -3773.05f, 29.9118f, 2.71f}, {2769.78f, -3763.57f, 29.9118f, 2.70f}, {2727.23f, -3745.92f, 30.9118f, 2.69f}, {2680.12f, -3737.49f, 30.9118f, 2.67f}, {2647.62f, -3739.94f, 30.9118f, 2.66f}, {2616.6f, -3745.75f, 30.9118f, 2.64f}, {2589.38f, -3731.97f, 30.9118f, 2.61f}, {2562.94f, -3722.35f, 31.9118f, 2.56f}, {2521.05f, -3716.6f, 31.9118f, 2.55f}, {2485.26f, -3706.67f, 31.9118f, 2.51f}, {2458.93f, -3696.67f, 31.9118f, 2.51f}, {2432, -3692.03f, 31.9118f, 2.46f}, {2399.59f, -3681.97f, 31.9118f, 2.45f}, {2357.75f, -3666.6f, 31.9118f, 2.44f}, {2311.99f, -3656.88f, 31.9118f, 2.94f}, {2263.41f, -3649.55f, 31.9118f, 3.02f}, {2209.05f, -3641.76f, 31.9118f, 2.99f}, {2164.83f, -3637.64f, 31.9118f, 3.15f}, {2122.42f, -3639, 31.9118f, 3.21f}, {2075.73f, -3643.59f, 31.9118f, 3.22f}, {2033.59f, -3649.52f, 31.9118f, 3.42f}, {1985.22f, -3662.99f, 31.9118f, 3.42f}, {1927.09f, -3679.56f, 33.9118f, 3.42f}, {1873.57f, -3695.32f, 33.9118f, 3.44f} }; class <API key> : public CreatureScript { public: <API key>() : CreatureScript("<API key>") { } bool OnGossipSelect(Player* player, Creature* creature, uint32 /*sender*/, uint32 action) OVERRIDE { player->PlayerTalkClass->ClearMenus(); if (action == <API key> + 1 && player->GetQuestStatus(<API key>) == <API key>) { player->CLOSE_GOSSIP_MENU(); creature->CastSpell(player, <API key>, true); CAST_AI(<API key>::<API key>, creature->AI())->MustDieTimer = 3000; CAST_AI(<API key>::<API key>, creature->AI())->MustDie = true; } return true; } bool OnGossipHello(Player* player, Creature* creature) OVERRIDE { if (player->GetQuestStatus(<API key>) != <API key>) return true; player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, <API key>, GOSSIP_SENDER_MAIN, <API key> + 1); player->SEND_GOSSIP_MENU(10811, creature->GetGUID()); return true; } CreatureAI* GetAI(Creature* creature) const OVERRIDE { return new <API key>(creature); } struct <API key> : public ScriptedAI { <API key>(Creature* creature) : ScriptedAI(creature) {} uint32 SpellEscapeTimer; uint32 TeleportTimer; uint32 CheckTimer; uint32 GrenadeTimer; uint32 MustDieTimer; uint32 CurrWP; uint64 PlayerGUID; bool MustDie; bool Escape; bool ContinueWP; bool Reached; void Reset() OVERRIDE { SpellEscapeTimer = 1300; TeleportTimer = 3500; CheckTimer = 10000; GrenadeTimer = 30000; MustDieTimer = 3000; CurrWP = 0; PlayerGUID = 0; MustDie = false; Escape = false; ContinueWP = false; Reached = false; } void UpdateAI(uint32 diff) OVERRIDE { if (MustDie) { if (MustDieTimer <= diff) { me->DespawnOrUnsummon(); return; } else MustDieTimer -= diff; } if (!Escape) { if (!PlayerGUID) return; if (SpellEscapeTimer <= diff) { DoCast(me, SPELL_RIZZLE_ESCAPE, false); SpellEscapeTimer = 10000; } else SpellEscapeTimer -= diff; if (TeleportTimer <= diff) { // temp solution - unit can't be teleported by core using spelleffect 5, only players DoTeleportTo(3706.39f, -3969.15f, 35.9118f); //begin swimming and summon depth charges Player* player = ObjectAccessor::GetPlayer(*me, PlayerGUID); if (!player) return; Talk(MSG_ESCAPE_NOTICE, player->GetGUID()); DoCast(me, <API key>); me->SetHover(true); me->SetSwim(true); me->SetSpeed(MOVE_RUN, 0.85f, true); me->GetMotionMaster()->MovementExpired(); me->GetMotionMaster()->MovePoint(CurrWP, WPs[CurrWP]); Escape = true; } else TeleportTimer -= diff; return; } if (ContinueWP) { me->GetMotionMaster()->MovePoint(CurrWP, WPs[CurrWP]); ContinueWP = false; } if (GrenadeTimer <= diff) { if (Player* player = ObjectAccessor::GetPlayer(*me, PlayerGUID)) { Talk(SAY_RIZZLE_GRENADE, player->GetGUID()); DoCast(player, <API key>, true); } GrenadeTimer = 30000; } else GrenadeTimer -= diff; if (CheckTimer <= diff) { Player* player = ObjectAccessor::GetPlayer(*me, PlayerGUID); if (!player) { me->DespawnOrUnsummon(); return; } if (me->IsWithinDist(player, 10) && me->GetPositionX() > player->GetPositionX() && !Reached) { Talk(SAY_RIZZLE_FINAL); me->SetUInt32Value(UNIT_NPC_FLAGS, 1); me->setFaction(35); me->GetMotionMaster()->MoveIdle(); me-><API key>(<API key>); Reached = true; } CheckTimer = 1000; } else CheckTimer -= diff; } void AttackStart(Unit* who) OVERRIDE { if (!who || PlayerGUID) return; Player* player = who->ToPlayer(); if (player && player->GetQuestStatus(<API key>) == <API key>) { PlayerGUID = who->GetGUID(); Talk(SAY_RIZZLE_START); DoCast(who, <API key>, false); return; } } void EnterCombat(Unit* /*who*/) OVERRIDE {} void MovementInform(uint32 type, uint32 id) OVERRIDE { if (type != POINT_MOTION_TYPE) return; if (id == 57) { me->DespawnOrUnsummon(); return; } ++CurrWP; ContinueWP = true; } }; }; class npc_depth_charge : public CreatureScript { public: npc_depth_charge() : CreatureScript("npc_depth_charge") { } CreatureAI* GetAI(Creature* creature) const OVERRIDE { return new npc_depth_chargeAI(creature); } struct npc_depth_chargeAI : public ScriptedAI { npc_depth_chargeAI(Creature* creature) : ScriptedAI(creature) {} bool WeMustDie; uint32 WeMustDieTimer; void Reset() OVERRIDE { me->SetHover(true); me->SetSwim(true); me->SetFlag(UNIT_FIELD_FLAGS, <API key>); WeMustDie = false; WeMustDieTimer = 1000; } void UpdateAI(uint32 diff) OVERRIDE { if (WeMustDie) { if (WeMustDieTimer <= diff) me->DespawnOrUnsummon(); else WeMustDieTimer -= diff; } return; } void MoveInLineOfSight(Unit* who) OVERRIDE { if (!who) return; if (who->GetTypeId() == TYPEID_PLAYER && me->IsWithinDistInMap(who, 5)) { DoCast(who, <API key>); WeMustDie = true; return; } } void AttackStart(Unit* /*who*/) OVERRIDE {} void EnterCombat(Unit* /*who*/) OVERRIDE {} }; }; void AddSC_azshara() { new npc_spitelashes(); new <API key>(); new <API key>(); new npc_depth_charge(); }
/* <API key>: GPL-2.0 */ #ifndef __LINUX_COMPILER_H #define __LINUX_COMPILER_H #include <linux/compiler_types.h> #ifndef __ASSEMBLY__ #ifdef __KERNEL__ /* * Note: <API key> can be used by special lowlevel code * to disable branch tracing on a per file basis. */ #if defined(<API key>) \ && !defined(<API key>) && !defined(__CHECKER__) void <API key>(struct ftrace_likely_data *f, int val, int expect, int is_constant); #define likely_notrace(x) __builtin_expect(!!(x), 1) #define unlikely_notrace(x) __builtin_expect(!!(x), 0) #define __branch_check__(x, expect, is_constant) ({ \ long ______r; \ static struct ftrace_likely_data \ __aligned(4) \ __section("<API key>") \ ______f = { \ .data.func = __func__, \ .data.file = __FILE__, \ .data.line = __LINE__, \ }; \ ______r = __builtin_expect(!!(x), expect); \ <API key>(&______f, ______r, \ expect, is_constant); \ ______r; \ }) /* * Using <API key>(x) to ignore cases where the return * value is always the same. This idea is taken from a similar patch * written by Daniel Walker. */ # ifndef likely # define likely(x) (__branch_check__(x, 1, <API key>(x))) # endif # ifndef unlikely # define unlikely(x) (__branch_check__(x, 0, <API key>(x))) # endif #ifdef <API key> /* * "Define 'is'", Bill Clinton * "Define 'if'", Steven Rostedt */ #define if(cond, ...) __trace_if( (cond , ## __VA_ARGS__) ) #define __trace_if(cond) \ if (<API key>(!!(cond)) ? !!(cond) : \ ({ \ int ______r; \ static struct ftrace_branch_data \ __aligned(4) \ __section("_ftrace_branch") \ ______f = { \ .func = __func__, \ .file = __FILE__, \ .line = __LINE__, \ }; \ ______r = !!(cond); \ ______f.miss_hit[______r]++; \ ______r; \ })) #endif /* <API key> */ #else # define likely(x) __builtin_expect(!!(x), 1) # define unlikely(x) __builtin_expect(!!(x), 0) #endif /* Optimization barrier */ #ifndef barrier # define barrier() __memory_barrier() #endif #ifndef barrier_data # define barrier_data(ptr) barrier() #endif /* workaround for GCC PR82365 if needed */ #ifndef <API key> # define <API key>() do { } while (0) #endif /* Unreachable code */ #ifdef <API key> /* * These macros help objtool understand GCC code flow for unreachable code. * The __COUNTER__ based labels are a hack to make each instance of the macros * unique, to convince GCC not to merge duplicate inline asm statements. */ #define annotate_reachable() ({ \ asm volatile("%c0:\n\t" \ ".pushsection .discard.reachable\n\t" \ ".long %c0b - .\n\t" \ ".popsection\n\t" : : "i" (__COUNTER__)); \ }) #define <API key>() ({ \ asm volatile("%c0:\n\t" \ ".pushsection .discard.unreachable\n\t" \ ".long %c0b - .\n\t" \ ".popsection\n\t" : : "i" (__COUNTER__)); \ }) #define ASM_UNREACHABLE \ "999:\n\t" \ ".pushsection .discard.unreachable\n\t" \ ".long 999b - .\n\t" \ ".popsection\n\t" #else #define annotate_reachable() #define <API key>() #endif #ifndef ASM_UNREACHABLE # define ASM_UNREACHABLE #endif #ifndef unreachable # define unreachable() do { \ <API key>(); \ <API key>(); \ } while (0) #endif /* * KENTRY - kernel entry point * This can be used to annotate symbols (functions or data) that are used * without their linker symbol being referenced explicitly. For example, * interrupt vector handlers, or functions in the kernel image that are found * programatically. * * Not required for symbols exported with EXPORT_SYMBOL, or initcalls. Those * are handled in their own way (with KEEP() in linker scripts). * * KENTRY can be avoided if the symbols in question are marked as KEEP() in the * linker script. For example an architecture could KEEP() its entire * boot/exception vector code rather than annotate each function and data. */ #ifndef KENTRY # define KENTRY(sym) \ extern typeof(sym) sym; \ static const unsigned long __kentry_##sym \ __used \ __section("___kentry" "+" #sym ) \ = (unsigned long)&sym; #endif #ifndef RELOC_HIDE # define RELOC_HIDE(ptr, off) \ ({ unsigned long __ptr; \ __ptr = (unsigned long) (ptr); \ (typeof(ptr)) (__ptr + (off)); }) #endif #ifndef OPTIMIZER_HIDE_VAR #define OPTIMIZER_HIDE_VAR(var) barrier() #endif /* Not-quite-unique ID. */ #ifndef __UNIQUE_ID # define __UNIQUE_ID(prefix) __PASTE(__PASTE(__UNIQUE_ID_, prefix), __LINE__) #endif #include <uapi/linux/types.h> #define __READ_ONCE_SIZE \ ({ \ switch (size) { \ case 1: *(__u8 *)res = *(volatile __u8 *)p; break; \ case 2: *(__u16 *)res = *(volatile __u16 *)p; break; \ case 4: *(__u32 *)res = *(volatile __u32 *)p; break; \ case 8: *(__u64 *)res = *(volatile __u64 *)p; break; \ default: \ barrier(); \ __builtin_memcpy((void *)res, (const void *)p, size); \ barrier(); \ } \ }) static __always_inline void __read_once_size(const volatile void *p, void *res, int size) { __READ_ONCE_SIZE; } #ifdef CONFIG_KASAN # define <API key> <API key> notrace __maybe_unused #else # define <API key> __always_inline #endif static <API key> void <API key>(const volatile void *p, void *res, int size) { __READ_ONCE_SIZE; } static __always_inline void __write_once_size(volatile void *p, void *res, int size) { switch (size) { case 1: *(volatile __u8 *)p = *(__u8 *)res; break; case 2: *(volatile __u16 *)p = *(__u16 *)res; break; case 4: *(volatile __u32 *)p = *(__u32 *)res; break; case 8: *(volatile __u64 *)p = *(__u64 *)res; break; default: barrier(); __builtin_memcpy((void *)p, (const void *)res, size); barrier(); } } /* * Prevent the compiler from merging or refetching reads or writes. The * compiler is also forbidden from reordering successive instances of * READ_ONCE and WRITE_ONCE, but only when the compiler is aware of some * particular ordering. One way to make the compiler aware of ordering is to * put the two invocations of READ_ONCE or WRITE_ONCE in different C * statements. * * These two macros will also work on aggregate data types like structs or * unions. If the size of the accessed data type exceeds the word size of * the machine (e.g., 32 bits or 64 bits) READ_ONCE() and WRITE_ONCE() will * fall back to memcpy(). There's at least two memcpy()s: one for the * __builtin_memcpy() and then one for the macro doing the copy of variable * - '__u' allocated on the stack. * * Their two major use cases are: (1) Mediating communication between * process-level code and irq/NMI handlers, all running on the same CPU, * and (2) Ensuring that the compiler does not fold, spindle, or otherwise * mutilate accesses that either do not require ordering or that interact * with an explicit memory barrier or atomic instruction that provides the * required ordering. */ #include <asm/barrier.h> #include <linux/kasan-checks.h> #define __READ_ONCE(x, check) \ ({ \ union { typeof(x) __val; char __c[1]; } __u; \ if (check) \ __read_once_size(&(x), __u.__c, sizeof(x)); \ else \ <API key>(&(x), __u.__c, sizeof(x)); \ <API key>(); /* Enforce dependency ordering from x */ \ __u.__val; \ }) #define READ_ONCE(x) __READ_ONCE(x, 1) /* * Use READ_ONCE_NOCHECK() instead of READ_ONCE() if you need * to hide memory access from KASAN. */ #define READ_ONCE_NOCHECK(x) __READ_ONCE(x, 0) static <API key> unsigned long read_word_at_a_time(const void *addr) { kasan_check_read(addr, 1); return *(unsigned long *)addr; } #define WRITE_ONCE(x, val) \ ({ \ union { typeof(x) __val; char __c[1]; } __u = \ { .__val = (__force typeof(x)) (val) }; \ __write_once_size(&(x), __u.__c, sizeof(x)); \ __u.__val; \ }) #endif /* __KERNEL__ */ /* * Force the compiler to emit 'sym' as a symbol, so that we can reference * it from inline assembler. Necessary in case 'sym' could be inlined * otherwise, or eliminated entirely due to lack of references that are * visible to the compiler. */ #define __ADDRESSABLE(sym) \ static void * __section(".discard.addressable") __used \ __PASTE(__addressable_##sym, __LINE__) = (void *)&sym; /** * offset_to_ptr - convert a relative memory offset to an absolute pointer * @off: the address of the 32-bit offset value */ static inline void *offset_to_ptr(const int *off) { return (void *)((unsigned long)off + *off); } #endif /* __ASSEMBLY__ */ /* Compile time object size, -1 for unknown */ #ifndef <API key> # define <API key>(obj) -1 #endif #ifndef <API key> # define <API key>(message) #endif #ifndef __compiletime_error # define __compiletime_error(message) #endif #ifdef __OPTIMIZE__ # define <API key>(condition, msg, prefix, suffix) \ do { \ extern void prefix ## suffix(void) __compiletime_error(msg); \ if (!(condition)) \ prefix ## suffix(); \ } while (0) #else # define <API key>(condition, msg, prefix, suffix) do { } while (0) #endif #define _compiletime_assert(condition, msg, prefix, suffix) \ <API key>(condition, msg, prefix, suffix) /** * compiletime_assert - break build and emit msg if condition is false * @condition: a compile-time constant condition to check * @msg: a message to emit if condition is false * * In tradition of POSIX assert, this macro will break the build if the * supplied condition is *false*, emitting the supplied error message if the * compiler has support to do so. */ #define compiletime_assert(condition, msg) \ _compiletime_assert(condition, msg, <API key>, __LINE__) #define <API key>(t) \ compiletime_assert(__native_word(t), \ "Need native word sized stores/loads for atomicity.") /* &a[0] degrades to a pointer: a different type from an array */ #define __must_be_array(a) BUILD_BUG_ON_ZERO(__same_type((a), &(a)[0])) #endif /* __LINUX_COMPILER_H */
using System; namespace Org.BouncyCastle.Math.Field { public interface <API key> : IExtensionField { IPolynomial MinimalPolynomial { get; } } }
package ome.util.math.geom2D; import java.awt.Rectangle; import org.testng.annotations.*; import junit.framework.TestCase; /** * Unit test for {@link EllipseArea}. * * @author Jean-Marie Burel &nbsp;&nbsp;&nbsp;&nbsp; <a * href="mailto:j.burel@dundee.ac.uk">j.burel@dundee.ac.uk</a> * @author <br> * Andrea Falconi &nbsp;&nbsp;&nbsp;&nbsp; <a * href="mailto:a.falconi@dundee.ac.uk"> a.falconi@dundee.ac.uk</a> * @since OME2.2 */ public class TestEllipseArea extends TestCase { private static final int LENGTH = 4, MAX_ITER = 1000; public void TestEllipse() { EllipseArea area = new EllipseArea(0, 0, Integer.MIN_VALUE, Integer.MAX_VALUE); Rectangle r = area.getBounds(); assertEquals("Should set x to argument passed to constructor.", 0, r.x, 0); assertEquals("Should set y to argument passed to constructor.", 0, r.y, 0); assertEquals("Should set w to argument passed to constructor.", Integer.MIN_VALUE, r.width, 0); assertEquals("Should set h to argument passed to constructor.", Integer.MAX_VALUE, r.height, 0); } @Test public void testSetBounds() { EllipseArea area = new EllipseArea(0, 0, 1, 1); area.setBounds(0, 0, 2, 2); Rectangle r = area.getBounds(); assertEquals("Should set x to argument passed to setBounds() method.", 0, r.x, 0); assertEquals("Should set y to argument passed to setBounds() method.", 0, r.y, 0); assertEquals("Should set w to argument passed to setBounds() method.", 2, r.width, 0); assertEquals("Should set h to argument passed to setBounds() method.", 2, r.height, 0); } @Test public void testScale() { EllipseArea area = new EllipseArea(0, 0, 1, 1); double j; Rectangle r = area.getBounds(); Rectangle rScale; for (int i = 0; i < MAX_ITER; i++) { j = (double) i / MAX_ITER; area.scale(j); rScale = area.getBounds(); assertEquals("Wrong scale x [i = " + i + "].", rScale.x, (int) (r.x * j), 0); assertEquals("Wrong scale y [i = " + i + "].", rScale.y, (int) (r.y * j), 0); assertEquals("Wrong scale w [i = " + i + "].", rScale.width, (int) (r.width * j), 0); assertEquals("Wrong scale h [i = " + i + "].", rScale.height, (int) (r.height * j), 0); } } @Test public void testPlanePoints1() { EllipseArea area = new EllipseArea(0, 0, 1, 1); // Empty array PlanePoint[] points = area.getPoints(); assertEquals("Wrong size of the array", 0, points.length, 0); } @Test public void testPlanePoints2() { // Ellipse which only contains the origin. EllipseArea area = new EllipseArea(-1, -1, 2, 2); PlanePoint[] points = area.getPoints(); assertEquals("Wrong size of the array", 1, points.length, 0); assertEquals("Wrong x coordinate", 0, points[0].x1, 0); assertEquals("Wrong y coordinate", 0, points[0].x2, 0); } @Test public void testPlanePoints3() { // Ellipse containing 9 points. // (-1, 1), (0, 1), (1, 1), (-1, 0), (0, 0), (0, 1) // (-1, -1), (0, -1), (1, -1) EllipseArea area = new EllipseArea(-2, -2, LENGTH, LENGTH); PlanePoint[] points = area.getPoints(); assertEquals("Wrong size of the array", 2 * LENGTH + 1, points.length, 0); PlanePoint point; int k = -1, j = -1, l = 1; for (int i = 0; i < points.length; i++) { point = points[i]; assertEquals("Wrong x coordinate", k, point.x1, 0); assertEquals("Wrong y coordinate", j, point.x2, 0); if (i == l * (LENGTH - 1) - 1) { l++; j++; k = -2; } k++; } } @Test public void testOnBoundaries() { EllipseArea area = new EllipseArea(-1, -1, 2, 2); assertFalse(area.onBoundaries(0, 0)); } }
/* -*- mode: C; c-basic-offset: 3; -*- */ #include <stdio.h> // fprintf #include <stdlib.h> // exit #include "vtest.h" #define DEFOP(op,ukind) op, #op, ukind /* The opcodes appear in the same order here as in libvex_ir.h That is not necessary but helpful when supporting a new architecture. */ static irop_t irops[] = { { DEFOP(Iop_Add8, UNDEF_LEFT), .s390x = 1, .amd64 = 1, .x86 = 1, .arm = 0, .ppc64 = 1, .ppc32 = 1, .mips32 = 1, .mips64 = 1 }, { DEFOP(Iop_Add16, UNDEF_LEFT), .s390x = 1, .amd64 = 1, .x86 = 1, .arm = 0, .ppc64 = 1, .ppc32 = 1, .mips32 = 1, .mips64 = 1 }, { DEFOP(Iop_Add32, UNDEF_LEFT), .s390x = 1, .amd64 = 1, .x86 = 1, .arm = 1, .ppc64 = 1, .ppc32 = 1, .mips32 = 1, .mips64 = 1 }, { DEFOP(Iop_Add64, UNDEF_LEFT), .s390x = 1, .amd64 = 1, .x86 = 1, .arm = 1, .ppc64 = 1, .ppc32 = 1, .mips32 = 0, .mips64 = 1 }, // mips asserts { DEFOP(Iop_Sub8, UNDEF_LEFT), .s390x = 1, .amd64 = 1, .x86 = 1, .arm = 0, .ppc64 = 1, .ppc32 = 1, .mips32 = 1, .mips64 = 1 }, { DEFOP(Iop_Sub16, UNDEF_LEFT), .s390x = 1, .amd64 = 1, .x86 = 1, .arm = 0, .ppc64 = 0, .ppc32 = 0, .mips32 = 1, .mips64 = 1 }, { DEFOP(Iop_Sub32, UNDEF_LEFT), .s390x = 1, .amd64 = 1, .x86 = 1, .arm = 1, .ppc64 = 1, .ppc32 = 1, .mips32 = 1, .mips64 = 1 }, { DEFOP(Iop_Sub64, UNDEF_LEFT), .s390x = 1, .amd64 = 1, .x86 = 1, .arm = 1, .ppc64 = 1, .ppc32 = 0, .mips32 = 0, .mips64 = 1 }, // ppc32, mips assert { DEFOP(Iop_Mul8, UNDEF_LEFT), .s390x = 0, .amd64 = 0, .x86 = 0, .arm = 0, .ppc64 = 0, .ppc32 = 0, .mips32 = 0, .mips64 = 0 }, { DEFOP(Iop_Mul16, UNDEF_LEFT), .s390x = 0, .amd64 = 1, .x86 = 1, .arm = 0, .ppc64 = 0, .ppc32 = 0, .mips32 = 0, .mips64 = 0 }, { DEFOP(Iop_Mul32, UNDEF_LEFT), .s390x = 0, .amd64 = 1, .x86 = 1, .arm = 1, .ppc64 = 1, .ppc32 = 1, .mips32 = 1, .mips64 = 1 }, { DEFOP(Iop_Mul64, UNDEF_LEFT), .s390x = 0, .amd64 = 1, .x86 = 0, .arm = 0, .ppc64 = 1, .ppc32 = 0, .mips32 = 0, .mips64 = 1 }, // ppc32, mips assert { DEFOP(Iop_Or8, UNDEF_OR), .s390x = 1, .amd64 = 1, .x86 = 1, .arm = 0, .ppc64 = 1, .ppc32 = 1, .mips32 = 1, .mips64 = 1 }, { DEFOP(Iop_Or16, UNDEF_OR), .s390x = 1, .amd64 = 1, .x86 = 1, .arm = 0, .ppc64 = 1, .ppc32 = 1, .mips32 = 1, .mips64 = 1 }, { DEFOP(Iop_Or32, UNDEF_OR), .s390x = 1, .amd64 = 1, .x86 = 1, .arm = 1, .ppc64 = 1, .ppc32 = 1, .mips32 = 1, .mips64 = 1 }, { DEFOP(Iop_Or64, UNDEF_OR), .s390x = 1, .amd64 = 1, .x86 = 1, .arm = 1, .ppc64 = 1, .ppc32 = 1, .mips32 = 0, .mips64 = 1 }, // mips asserts { DEFOP(Iop_And8, UNDEF_AND), .s390x = 1, .amd64 = 1, .x86 = 1, .arm = 0, .ppc64 = 1, .ppc32 = 1, .mips32 = 1, .mips64 = 1 }, { DEFOP(Iop_And16, UNDEF_AND), .s390x = 1, .amd64 = 1, .x86 = 1, .arm = 0, .ppc64 = 1, .ppc32 = 1, .mips32 = 1, .mips64 = 1 }, { DEFOP(Iop_And32, UNDEF_AND), .s390x = 1, .amd64 = 1, .x86 = 1, .arm = 1, .ppc64 = 1, .ppc32 = 1, .mips32 = 1, .mips64 = 1 }, { DEFOP(Iop_And64, UNDEF_AND), .s390x = 1, .amd64 = 1, .x86 = 1, .arm = 1, .ppc64 = 1, .ppc32 = 1, .mips32 = 1, .mips64 = 1 }, { DEFOP(Iop_Xor8, UNDEF_SAME), .s390x = 1, .amd64 = 1, .x86 = 1, .arm = 0, .ppc64 = 1, .ppc32 = 1, .mips32 = 1, .mips64 = 1 }, { DEFOP(Iop_Xor16, UNDEF_SAME), .s390x = 1, .amd64 = 1, .x86 = 1, .arm = 0, .ppc64 = 1, .ppc32 = 1, .mips32 = 1, .mips64 = 1 }, { DEFOP(Iop_Xor32, UNDEF_SAME), .s390x = 1, .amd64 = 1, .x86 = 1, .arm = 1, .ppc64 = 1, .ppc32 = 1, .mips32 = 1, .mips64 = 1 }, { DEFOP(Iop_Xor64, UNDEF_SAME), .s390x = 1, .amd64 = 1, .x86 = 1, .arm = 1, .ppc64 = 1, .ppc32 = 1, .mips32 = 1, .mips64 = 1 }, { DEFOP(Iop_Shl8, UNDEF_SHL), .s390x = 1, .amd64 = 1, .x86 = 1, .arm = 0, .ppc64 = 1, .ppc32 = 1, .mips32 = 0, .mips64 = 0 }, { DEFOP(Iop_Shl16, UNDEF_SHL), .s390x = 1, .amd64 = 1, .x86 = 1, .arm = 0, .ppc64 = 1, .ppc32 = 1, .mips32 = 0, .mips64 = 0 }, { DEFOP(Iop_Shl32, UNDEF_SHL), .s390x = 1, .amd64 = 1, .x86 = 1, .arm = 1, .ppc64 = 1, .ppc32 = 1, .mips32 = 1, .mips64 = 1 }, { DEFOP(Iop_Shl64, UNDEF_SHL), .s390x = 1, .amd64 = 1, .x86 = 1, .arm = 1, .ppc64 = 1, .ppc32 = 0, .mips32 = 0, .mips64 = 1 }, // ppc32 asserts { DEFOP(Iop_Shr8, UNDEF_SHR), .s390x = 1, .amd64 = 1, .x86 = 1, .arm = 0, .ppc64 = 0, .ppc32 = 0, .mips32 = 0, .mips64 = 0 }, // ppc32/64 assert { DEFOP(Iop_Shr16, UNDEF_SHR), .s390x = 1, .amd64 = 1, .x86 = 1, .arm = 0, .ppc64 = 0, .ppc32 = 0, .mips32 = 0, .mips64 = 0 }, // ppc32/64 assert { DEFOP(Iop_Shr32, UNDEF_SHR), .s390x = 1, .amd64 = 1, .x86 = 1, .arm = 1, .ppc64 = 1, .ppc32 = 1, .mips32 = 1, .mips64 = 1 }, { DEFOP(Iop_Shr64, UNDEF_SHR), .s390x = 1, .amd64 = 1, .x86 = 1, .arm = 1, .ppc64 = 1, .ppc32 = 0, .mips32 = 0, .mips64 = 1 }, // ppc32 asserts { DEFOP(Iop_Sar8, UNDEF_SAR), .s390x = 1, .amd64 = 1, .x86 = 1, .arm = 0, .ppc64 = 0, .ppc32 = 0, .mips32 = 0, .mips64 = 0 }, // ppc32/64 assert { DEFOP(Iop_Sar16, UNDEF_SAR), .s390x = 1, .amd64 = 1, .x86 = 1, .arm = 0, .ppc64 = 0, .ppc32 = 0, .mips32 = 0, .mips64 = 0 }, // ppc32/64 assert { DEFOP(Iop_Sar32, UNDEF_SAR), .s390x = 1, .amd64 = 1, .x86 = 1, .arm = 1, .ppc64 = 1, .ppc32 = 1, .mips32 = 1, .mips64 = 1 }, { DEFOP(Iop_Sar64, UNDEF_SAR), .s390x = 1, .amd64 = 1, .x86 = 0, .arm = 1, .ppc64 = 1, .ppc32 = 0, .mips32 = 0, .mips64 = 1 }, // ppc32 asserts { DEFOP(Iop_CmpEQ8, UNDEF_ALL), .s390x = 1, .amd64 = 1, .x86 = 1, .arm = 0, .ppc64 = 0, .ppc32 = 0, .mips32 = 0, .mips64 = 0 }, { DEFOP(Iop_CmpEQ16, UNDEF_ALL), .s390x = 1, .amd64 = 1, .x86 = 1, .arm = 0, .ppc64 = 0, .ppc32 = 0, .mips32 = 1, .mips64 = 1 }, { DEFOP(Iop_CmpEQ32, UNDEF_ALL), .s390x = 1, .amd64 = 1, .x86 = 1, .arm = 1, .ppc64 = 1, .ppc32 = 1, .mips32 = 1, .mips64 = 1 }, { DEFOP(Iop_CmpEQ64, UNDEF_ALL), .s390x = 1, .amd64 = 1, .x86 = 1, .arm = 0, .ppc64 = 1, .ppc32 = 0, .mips32 = 0, .mips64 = 1 }, // ppc32, mips assert { DEFOP(Iop_CmpNE8, UNDEF_ALL), .s390x = 1, .amd64 = 1, .x86 = 1, .arm = 0, .ppc64 = 0, .ppc32 = 0, .mips32 = 0, .mips64 = 0 }, { DEFOP(Iop_CmpNE16, UNDEF_ALL), .s390x = 1, .amd64 = 1, .x86 = 1, .arm = 0, .ppc64 = 0, .ppc32 = 0, .mips32 = 0, .mips64 = 0 }, { DEFOP(Iop_CmpNE32, UNDEF_ALL), .s390x = 1, .amd64 = 1, .x86 = 1, .arm = 1, .ppc64 = 1, .ppc32 = 1, .mips32 = 1, .mips64 = 1 }, { DEFOP(Iop_CmpNE64, UNDEF_ALL), .s390x = 1, .amd64 = 1, .x86 = 1, .arm = 0, .ppc64 = 1, .ppc32 = 0, .mips32 = 0, .mips64 = 1 }, // ppc32, mips assert { DEFOP(Iop_Not8, UNDEF_SAME), .s390x = 1, .amd64 = 1, .x86 = 1, .arm = 0, .ppc64 = 1, .ppc32 = 1, .mips32 = 1, .mips64 = 1 }, { DEFOP(Iop_Not16, UNDEF_SAME), .s390x = 1, .amd64 = 1, .x86 = 1, .arm = 0, .ppc64 = 1, .ppc32 = 1, .mips32 = 1, .mips64 = 1 }, { DEFOP(Iop_Not32, UNDEF_SAME), .s390x = 1, .amd64 = 1, .x86 = 1, .arm = 1, .ppc64 = 1, .ppc32 = 1, .mips32 = 1, .mips64 = 1 }, { DEFOP(Iop_Not64, UNDEF_SAME), .s390x = 1, .amd64 = 1, .x86 = 1, .arm = 1, .ppc64 = 1, .ppc32 = 1, .mips32 = 0, .mips64 = 0 }, { DEFOP(Iop_CasCmpEQ8, UNDEF_NONE), .s390x = 1, .amd64 = 1, .x86 = 1, .arm = 0, .ppc64 = 0, .ppc32 = 0, .mips32 = 0, .mips64 = 0 }, { DEFOP(Iop_CasCmpEQ16, UNDEF_NONE), .s390x = 1, .amd64 = 1, .x86 = 1, .arm = 0, .ppc64 = 0, .ppc32 = 0, .mips32 = 0, .mips64 = 0 }, { DEFOP(Iop_CasCmpEQ32, UNDEF_NONE), .s390x = 1, .amd64 = 1, .x86 = 1, .arm = 0, .ppc64 = 0, .ppc32 = 0, .mips32 = 0, .mips64 = 0 }, { DEFOP(Iop_CasCmpEQ64, UNDEF_NONE), .s390x = 1, .amd64 = 1, .x86 = 0, .arm = 0, .ppc64 = 0, .ppc32 = 0, .mips32 = 0, .mips64 = 0 }, { DEFOP(Iop_CasCmpNE8, UNDEF_NONE), .s390x = 1, .amd64 = 1, .x86 = 1, .arm = 0, .ppc64 = 0, .ppc32 = 0, .mips32 = 0, .mips64 = 0 }, { DEFOP(Iop_CasCmpNE16, UNDEF_NONE), .s390x = 1, .amd64 = 1, .x86 = 1, .arm = 0, .ppc64 = 0, .ppc32 = 0, .mips32 = 0, .mips64 = 0 }, { DEFOP(Iop_CasCmpNE32, UNDEF_NONE), .s390x = 1, .amd64 = 1, .x86 = 1, .arm = 0, .ppc64 = 0, .ppc32 = 0, .mips32 = 0, .mips64 = 0 }, { DEFOP(Iop_CasCmpNE64, UNDEF_NONE), .s390x = 1, .amd64 = 1, .x86 = 0, .arm = 0, .ppc64 = 0, .ppc32 = 0, .mips32 = 0, .mips64 = 0 }, { DEFOP(Iop_ExpCmpNE8, UNDEF_UNKNOWN), }, // exact (expensive) equality { DEFOP(Iop_ExpCmpNE16, UNDEF_UNKNOWN), }, // exact (expensive) equality { DEFOP(Iop_ExpCmpNE32, UNDEF_UNKNOWN), }, // exact (expensive) equality { DEFOP(Iop_ExpCmpNE64, UNDEF_UNKNOWN), }, // exact (expensive) equality { DEFOP(Iop_MullS8, UNDEF_LEFT), .s390x = 1, .amd64 = 1, .x86 = 1, .arm = 0, .ppc64 = 0, .ppc32 = 0, .mips32 = 0, .mips64 = 0 }, { DEFOP(Iop_MullS16, UNDEF_LEFT), .s390x = 1, .amd64 = 1, .x86 = 1, .arm = 0, .ppc64 = 0, .ppc32 = 0, .mips32 = 0, .mips64 = 0 }, { DEFOP(Iop_MullS32, UNDEF_LEFT), .s390x = 1, .amd64 = 1, .x86 = 1, .arm = 1, .ppc64 = 1, .ppc32 = 1, .mips32 = 0, .mips64 = 1 }, // mips asserts // s390 has signed multiplication of 64-bit values but the result // is 64-bit (not 128-bit). So we cannot test this op standalone. { DEFOP(Iop_MullS64, UNDEF_LEFT), .s390x = 0, .amd64 = 1, .x86 = 0, .arm = 0, .ppc64 = 1, .ppc32 = 0, .mips32 =0, .mips64 = 1 }, // ppc32, mips assert { DEFOP(Iop_MullU8, UNDEF_LEFT), .s390x = 1, .amd64 = 1, .x86 = 1, .arm = 0, .ppc64 = 0, .ppc32 = 0, .mips32 =0, .mips64 = 0 }, { DEFOP(Iop_MullU16, UNDEF_LEFT), .s390x = 1, .amd64 = 1, .x86 = 1, .arm = 0, .ppc64 = 0, .ppc32 = 0, .mips32 =0, .mips64 = 0 }, { DEFOP(Iop_MullU32, UNDEF_LEFT), .s390x = 1, .amd64 = 1, .x86 = 1, .arm = 1, .ppc64 = 1, .ppc32 = 1, .mips32 =0, .mips64 = 1 }, // mips asserts { DEFOP(Iop_MullU64, UNDEF_LEFT), .s390x = 1, .amd64 = 1, .x86 = 0, .arm = 0, .ppc64 = 1, .ppc32 = 0, .mips32 =0, .mips64 = 1 }, // ppc32, mips assert { DEFOP(Iop_Clz64, UNDEF_ALL), .s390x = 1, .amd64 = 1, .x86 = 0, .arm = 0, .ppc64 = 1, .ppc32 = 0, .mips32 =0, .mips64 = 1 }, // ppc32 asserts { DEFOP(Iop_Clz32, UNDEF_ALL), .s390x = 0, .amd64 = 0, .x86 = 1, .arm = 1, .ppc64 = 1, .ppc32 = 1, .mips32 =1, .mips64 = 1 }, { DEFOP(Iop_Ctz64, UNDEF_ALL), .s390x = 0, .amd64 = 1, .x86 = 0, .arm = 0, .ppc64 = 0, .ppc32 = 0, .mips32 =0, .mips64 = 0 }, { DEFOP(Iop_Ctz32, UNDEF_ALL), .s390x = 0, .amd64 = 0, .x86 = 1, .arm = 0, .ppc64 = 0, .ppc32 = 0, .mips32 =0, .mips64 = 0 }, { DEFOP(Iop_CmpLT32S, UNDEF_ALL), .s390x = 1, .amd64 = 1, .x86 = 1, .arm = 1, .ppc64 = 1, .ppc32 = 1, .mips32 =1, .mips64 = 1 }, { DEFOP(Iop_CmpLT64S, UNDEF_ALL), .s390x = 1, .amd64 = 1, .x86 = 0, .arm = 0, .ppc64 = 0, .ppc32 = 0, .mips32 =0, .mips64 = 1 }, // ppc, mips assert { DEFOP(Iop_CmpLE32S, UNDEF_ALL), .s390x = 1, .amd64 = 1, .x86 = 1, .arm = 1, .ppc64 = 1, .ppc32 = 1, .mips32 =1, .mips64 = 1 }, { DEFOP(Iop_CmpLE64S, UNDEF_ALL), .s390x = 1, .amd64 = 1, .x86 = 0, .arm = 0, .ppc64 = 0, .ppc32 = 0, .mips32 =0, .mips64 = 1 }, // ppc, mips assert { DEFOP(Iop_CmpLT32U, UNDEF_ALL), .s390x = 1, .amd64 = 1, .x86 = 1, .arm = 1, .ppc64 = 1, .ppc32 = 1, .mips32 =1, .mips64 = 1 }, { DEFOP(Iop_CmpLT64U, UNDEF_ALL), .s390x = 1, .amd64 = 1, .x86 = 0, .arm = 0, .ppc64 = 1, .ppc32 = 0, .mips32 =0, .mips64 = 1 }, // ppc32, mips assert { DEFOP(Iop_CmpLE32U, UNDEF_ALL), .s390x = 1, .amd64 = 1, .x86 = 1, .arm = 1, .ppc64 = 1, .ppc32 = 1, .mips32 =1, .mips64 = 1 }, { DEFOP(Iop_CmpLE64U, UNDEF_ALL), .s390x = 1, .amd64 = 1, .x86 = 0, .arm = 0, .ppc64 = 1, .ppc32 = 0, .mips32 =0, .mips64 = 0 }, // ppc32 asserts { DEFOP(Iop_CmpNEZ8, UNDEF_ALL), }, // not supported by mc_translate { DEFOP(Iop_CmpNEZ16, UNDEF_ALL), }, // not supported by mc_translate { DEFOP(Iop_CmpNEZ32, UNDEF_ALL), }, // not supported by mc_translate { DEFOP(Iop_CmpNEZ64, UNDEF_ALL), }, // not supported by mc_translate { DEFOP(Iop_CmpwNEZ32, UNDEF_ALL), .s390x = 1, .amd64 = 1, .x86 = 1, .arm = 1, .ppc64 = 1, .ppc32 = 1, .mips32 = 1, .mips64 = 1 }, { DEFOP(Iop_CmpwNEZ64, UNDEF_ALL), .s390x = 1, .amd64 = 1, .x86 = 1, .arm = 1, .ppc64 = 1, .ppc32 = 1, .mips32 = 0, .mips64 = 1 }, // mips asserts { DEFOP(Iop_Left8, UNDEF_UNKNOWN), }, // not supported by mc_translate { DEFOP(Iop_Left16, UNDEF_UNKNOWN), }, // not supported by mc_translate { DEFOP(Iop_Left32, UNDEF_UNKNOWN), }, // not supported by mc_translate { DEFOP(Iop_Left64, UNDEF_UNKNOWN), }, // not supported by mc_translate { DEFOP(Iop_Max32U, UNDEF_UNKNOWN), }, // not supported by mc_translate { DEFOP(Iop_CmpORD32U, UNDEF_ORD), .s390x = 0, .amd64 = 0, .x86 = 0, .arm = 0, .ppc64 = 1, .ppc32 = 1, .mips32 = 0, .mips64 = 0 }, // support added in vbit-test { DEFOP(Iop_CmpORD64U, UNDEF_ORD), .s390x = 0, .amd64 = 0, .x86 = 0, .arm = 0, .ppc64 = 1, .ppc32 = 0, .mips32 = 0, .mips64 = 0 }, // support added in vbit-test { DEFOP(Iop_CmpORD32S, UNDEF_ORD), .s390x = 0, .amd64 = 0, .x86 = 0, .arm = 0, .ppc64 = 1, .ppc32 = 1, .mips32 = 0, .mips64 = 0 }, // support added in vbit-test { DEFOP(Iop_CmpORD64S, UNDEF_ORD), .s390x = 0, .amd64 = 0, .x86 = 0, .arm = 0, .ppc64 = 1, .ppc32 = 0, .mips32 = 0, .mips64 = 0 }, // support added in vbit-test { DEFOP(Iop_DivU32, UNDEF_ALL), .s390x = 0, .amd64 = 0, .x86 = 0, .arm = 0, .ppc64 = 1, .ppc32 = 1, .mips32 = 0, .mips64 = 0 }, { DEFOP(Iop_DivS32, UNDEF_ALL), .s390x = 0, .amd64 = 0, .x86 = 0, .arm = 0, .ppc64 = 1, .ppc32 = 1, .mips32 = 0, .mips64 = 0 }, { DEFOP(Iop_DivU64, UNDEF_ALL), .s390x = 0, .amd64 = 0, .x86 = 0, .arm = 0, .ppc64 = 1, .ppc32 = 0, .mips32 = 0, .mips64 = 0 }, // ppc32 asserts { DEFOP(Iop_DivS64, UNDEF_ALL), .s390x = 0, .amd64 = 0, .x86 = 0, .arm = 0, .ppc64 = 1, .ppc32 = 0, .mips32 = 0, .mips64 = 0 }, // ppc32 asserts { DEFOP(Iop_DivU64E, UNDEF_ALL), .s390x = 0, .amd64 = 0, .x86 = 0, .arm = 0, .ppc64 = 1, .ppc32 = 0, .mips32 = 0, .mips64 = 0 }, // ppc32 asserts { DEFOP(Iop_DivS64E, UNDEF_ALL), .s390x = 0, .amd64 = 0, .x86 = 0, .arm = 0, .ppc64 = 1, .ppc32 = 0, .mips32 = 0, .mips64 = 0 }, // ppc32 asserts { DEFOP(Iop_DivU32E, UNDEF_ALL), .s390x = 0, .amd64 = 0, .x86 = 0, .arm = 0, .ppc64 = 1, .ppc32 = 1, .mips32 = 0, .mips64 = 0 }, { DEFOP(Iop_DivS32E, UNDEF_ALL), .s390x = 0, .amd64 = 0, .x86 = 0, .arm = 0, .ppc64 = 1, .ppc32 = 1, .mips32 = 0, .mips64 = 0 }, // On s390 the DivMod operations always appear in a certain context // So they cannot be tested in isolation on that platform. { DEFOP(Iop_DivModU64to32, UNDEF_ALL), .s390x = 0, .amd64 = 1, .x86 = 1, .arm = 0, .ppc64 = 0, .ppc32 = 0, .mips32 = 1, .mips64 = 1 }, { DEFOP(Iop_DivModS64to32, UNDEF_ALL), .s390x = 0, .amd64 = 1, .x86 = 1, .arm = 0, .ppc64 = 0, .ppc32 = 0, .mips32 = 1, .mips64 = 1 }, { DEFOP(Iop_DivModU128to64, UNDEF_ALL), .s390x = 0, .amd64 = 1, .x86 = 0, .arm = 0, .ppc64 = 0, .ppc32 = 0, .mips32 = 0, .mips64 = 1 }, // mips asserts { DEFOP(Iop_DivModS128to64, UNDEF_ALL), .s390x = 0, .amd64 = 1, .x86 = 0, .arm = 0, .ppc64 = 0, .ppc32 = 0, .mips32 = 0, .mips64 = 1 }, // mips asserts { DEFOP(Iop_DivModS64to64, UNDEF_ALL), .s390x = 0, .amd64 = 0, .x86 = 0, .arm = 0, .ppc64 = 0, .ppc32 = 0, .mips32 = 0, .mips64 = 0 }, // mips asserts { DEFOP(Iop_8Uto16, UNDEF_ZEXT), .s390x = 1, .amd64 = 1, .x86 = 1, .arm = 0, .ppc64 = 1, .ppc32 = 1, .mips32 = 1, .mips64 = 1 }, { DEFOP(Iop_8Uto32, UNDEF_ZEXT), .s390x = 1, .amd64 = 1, .x86 = 1, .arm = 1, .ppc64 = 1, .ppc32 = 1, .mips32 = 1, .mips64 = 1 }, { DEFOP(Iop_8Uto64, UNDEF_ZEXT), .s390x = 1, .amd64 = 1, .x86 = 0, .arm = 0, .ppc64 = 1, .ppc32 = 0, .mips32 = 0, .mips64 = 1 }, // ppc32 assert { DEFOP(Iop_16Uto32, UNDEF_ZEXT), .s390x = 1, .amd64 = 1, .x86 = 1, .arm = 1, .ppc64 = 1, .ppc32 = 1, .mips32 = 1, .mips64 = 1 }, { DEFOP(Iop_16Uto64, UNDEF_ZEXT), .s390x = 1, .amd64 = 1, .x86 = 1, .arm = 0, .ppc64 = 1, .ppc32 = 0, .mips32 = 0, .mips64 = 1 }, // ppc32 assert { DEFOP(Iop_32Uto64, UNDEF_ZEXT), .s390x = 1, .amd64 = 1, .x86 = 1, .arm = 0, .ppc64 = 1, .ppc32 = 1, .mips32 = 0, .mips64 = 1 }, // mips asserts { DEFOP(Iop_8Sto16, UNDEF_SEXT), .s390x = 1, .amd64 = 1, .x86 = 1, .arm = 0, .ppc64 = 1, .ppc32 = 1, .mips32 = 1, .mips64 = 1 }, { DEFOP(Iop_8Sto32, UNDEF_SEXT), .s390x = 1, .amd64 = 1, .x86 = 1, .arm = 1, .ppc64 = 1, .ppc32 = 1, .mips32 = 1, .mips64 = 1 }, { DEFOP(Iop_8Sto64, UNDEF_SEXT), .s390x = 1, .amd64 = 1, .x86 = 0, .arm = 0, .ppc64 = 1, .ppc32 = 0, .mips32 = 0, .mips64 = 1 }, // ppc32, mips assert { DEFOP(Iop_16Sto32, UNDEF_SEXT), .s390x = 1, .amd64 = 1, .x86 = 1, .arm = 1, .ppc64 = 1, .ppc32 = 1, .mips32 = 1, .mips64 = 1 }, { DEFOP(Iop_16Sto64, UNDEF_SEXT), .s390x = 1, .amd64 = 1, .x86 = 0, .arm = 0, .ppc64 = 1, .ppc32 = 0, .mips32 = 0, .mips64 = 1 }, // ppc32, mips assert { DEFOP(Iop_32Sto64, UNDEF_SEXT), .s390x = 1, .amd64 = 1, .x86 = 1, .arm = 0, .ppc64 = 1, .ppc32 = 1, .mips32 = 0, .mips64 = 1 }, // mips asserts { DEFOP(Iop_64to8, UNDEF_TRUNC), .s390x = 1, .amd64 = 1, .x86 = 0, .arm = 1, .ppc64 = 1, .ppc32 = 0, .mips32 = 0, .mips64 = 1 }, // ppc32, mips assert { DEFOP(Iop_32to8, UNDEF_TRUNC), .s390x = 1, .amd64 = 1, .x86 = 1, .arm = 1, .ppc64 = 1, .ppc32 = 1, .mips32 = 1, .mips64 = 1 }, { DEFOP(Iop_64to16, UNDEF_TRUNC), .s390x = 1, .amd64 = 1, .x86 = 0, .arm = 0, .ppc64 = 1, .ppc32 = 0, .mips32 = 0, .mips64 = 1 }, // ppc32, mips assert { DEFOP(Iop_16to8, UNDEF_TRUNC), .s390x = 1, .amd64 = 1, .x86 = 1, .arm = 0, .ppc64 = 1, .ppc32 = 1, .mips32 = 1, .mips64 = 1 }, { DEFOP(Iop_16HIto8, UNDEF_UPPER), .s390x = 1, .amd64 = 1, .x86 = 1, .arm = 0, .ppc64 = 1, .ppc32 = 1, .mips32 = 1, .mips64 = 1 }, { DEFOP(Iop_8HLto16, UNDEF_CONCAT), .s390x = 1, .amd64 = 1, .x86 = 1, .arm = 0, .ppc64 = 0, .ppc32 = 0, .mips32 = 1, .mips64 = 1 }, // ppc isel { DEFOP(Iop_32to16, UNDEF_TRUNC), .s390x = 1, .amd64 = 1, .x86 = 1, .arm = 1, .ppc64 = 1, .ppc32 = 1, .mips32 = 1, .mips64 = 1 }, { DEFOP(Iop_32HIto16, UNDEF_UPPER), .s390x = 1, .amd64 = 1, .x86 = 1, .arm = 0, .ppc64 = 0, .ppc32 = 0, .mips32 = 1, .mips64 = 1 }, { DEFOP(Iop_16HLto32, UNDEF_CONCAT), .s390x = 1, .amd64 = 1, .x86 = 1, .arm = 0, .ppc64 = 0, .ppc32 = 0, .mips32 = 1, .mips64 = 1 }, // ppc isel { DEFOP(Iop_64to32, UNDEF_TRUNC), .s390x = 1, .amd64 = 1, .x86 = 1, .arm = 1, .ppc64 = 1, .ppc32 = 1, .mips32 = 0, .mips64 = 1 }, // mips asserts { DEFOP(Iop_64HIto32, UNDEF_UPPER), .s390x = 1, .amd64 = 1, .x86 = 1, .arm = 1, .ppc64 = 1, .ppc32 = 1, .mips32 = 0, .mips64 = 1 }, { DEFOP(Iop_32HLto64, UNDEF_CONCAT), .s390x = 1, .amd64 = 1, .x86 = 1, .arm = 1, .ppc64 = 1, .ppc32 = 1, .mips32 = 0, .mips64 = 1 }, // mips asserts { DEFOP(Iop_128to64, UNDEF_TRUNC), .s390x = 1, .amd64 = 1, .x86 = 0, .arm = 0, .ppc64 = 1, .ppc32 = 1, .mips32 = 0, .mips64 = 1 }, // mips asserts { DEFOP(Iop_128HIto64, UNDEF_UPPER), .s390x = 1, .amd64 = 1, .x86 = 0, .arm = 0, .ppc64 = 1, .ppc32 = 1, .mips32 = 0, .mips64 = 1 }, // mips asserts { DEFOP(Iop_64HLto128, UNDEF_CONCAT), .s390x = 1, .amd64 = 1, .x86 = 0, .arm = 0, .ppc64 = 1, .ppc32 = 1, .mips32 = 0, .mips64 = 1 }, // mips asserts { DEFOP(Iop_Not1, UNDEF_ALL), .s390x = 1, .amd64 = 1, .x86 = 1, .arm = 1, .ppc64 = 1, .ppc32 = 1, .mips32 = 1, .mips64 = 1 }, { DEFOP(Iop_32to1, UNDEF_TRUNC), .s390x = 1, .amd64 = 1, .x86 = 1, .arm = 1, .ppc64 = 1, .ppc32 = 1, .mips32 = 1, .mips64 = 1 }, { DEFOP(Iop_64to1, UNDEF_TRUNC), .s390x = 1, .amd64 = 1, .x86 = 0, .arm = 0, .ppc64 = 1, .ppc32 = 0, .mips32 = 0, .mips64 = 1 }, // ppc32, mips assert { DEFOP(Iop_1Uto8, UNDEF_ZEXT), .s390x = 1, .amd64 = 1, .x86 = 1, .arm = 1, .ppc64 = 1, .ppc32 = 1, .mips32 = 1, .mips64 = 1 }, { DEFOP(Iop_1Uto32, UNDEF_ZEXT), .s390x = 1, .amd64 = 1, .x86 = 1, .arm = 1, .ppc64 = 1, .ppc32 = 1, .mips32 = 1, .mips64 = 1 }, { DEFOP(Iop_1Uto64, UNDEF_ZEXT), .s390x = 1, .amd64 = 1, .x86 = 0, .arm = 0, .ppc64 = 1, .ppc32 = 0, .mips32 = 0, .mips64 = 1 }, // ppc32 assert { DEFOP(Iop_1Sto8, UNDEF_ALL), .s390x = 1, .amd64 = 1, .x86 = 1, .arm = 0, .ppc64 = 1, .ppc32 = 1, .mips32 = 1, .mips64 = 1 }, { DEFOP(Iop_1Sto16, UNDEF_ALL), }, // not handled by mc_translate { DEFOP(Iop_1Sto32, UNDEF_ALL), .s390x = 1, .amd64 = 1, .x86 = 1, .arm = 1, .ppc64 = 1, .ppc32 = 1, .mips32 = 1, .mips64 = 1 }, { DEFOP(Iop_1Sto64, UNDEF_ALL), .s390x = 1, .amd64 = 1, .x86 = 1, .arm = 1, .ppc64 = 1, .ppc32 = 1, .mips32 = 1, .mips64 = 1 }, { DEFOP(Iop_AddF64, UNDEF_ALL), .s390x = 1, .amd64 = 1, .x86 = 1, .arm = 1, .ppc64 = 1, .ppc32 = 1, .mips32 = 0, .mips64 = 1 }, // mips asserts { DEFOP(Iop_SubF64, UNDEF_ALL), .s390x = 1, .amd64 = 1, .x86 = 1, .arm = 1, .ppc64 = 1, .ppc32 = 1, .mips32 = 0, .mips64 = 1 }, // mips asserts { DEFOP(Iop_MulF64, UNDEF_ALL), .s390x = 1, .amd64 = 1, .x86 = 1, .arm = 1, .ppc64 = 1, .ppc32 = 1, .mips32 = 0, .mips64 = 1 }, // mips asserts { DEFOP(Iop_DivF64, UNDEF_ALL), .s390x = 1, .amd64 = 1, .x86 = 1, .arm = 1, .ppc64 = 1, .ppc32 = 1, .mips32 = 0, .mips64 = 1 }, // mips asserts { DEFOP(Iop_AddF32, UNDEF_ALL), .s390x = 1, .amd64 = 0, .x86 = 0, .arm = 1, .ppc64 = 0, .ppc32 = 0, .mips32 = 1, .mips64 = 1 }, { DEFOP(Iop_SubF32, UNDEF_ALL), .s390x = 1, .amd64 = 0, .x86 = 0, .arm = 1, .ppc64 = 0, .ppc32 = 0, .mips32 = 1, .mips64 = 1 }, { DEFOP(Iop_MulF32, UNDEF_ALL), .s390x = 1, .amd64 = 0, .x86 = 0, .arm = 1, .ppc64 = 0, .ppc32 = 0, .mips32 = 1, .mips64 = 1 }, { DEFOP(Iop_DivF32, UNDEF_ALL), .s390x = 1, .amd64 = 0, .x86 = 0, .arm = 1, .ppc64 = 0, .ppc32 = 0, .mips32 = 1, .mips64 = 1 }, { DEFOP(Iop_AddF64r32, UNDEF_ALL), .s390x = 0, .amd64 = 0, .x86 = 0, .arm = 0, .ppc64 = 1, .ppc32 = 1, .mips32 = 0, .mips64 = 0 }, { DEFOP(Iop_SubF64r32, UNDEF_ALL), .s390x = 0, .amd64 = 0, .x86 = 0, .arm = 0, .ppc64 = 1, .ppc32 = 1, .mips32 = 0, .mips64 = 0 }, { DEFOP(Iop_MulF64r32, UNDEF_ALL), .s390x = 0, .amd64 = 0, .x86 = 0, .arm = 0, .ppc64 = 1, .ppc32 = 1, .mips32 = 0, .mips64 = 0 }, { DEFOP(Iop_DivF64r32, UNDEF_ALL), .s390x = 0, .amd64 = 0, .x86 = 0, .arm = 0, .ppc64 = 1, .ppc32 = 1, .mips32 = 0, .mips64 = 0 }, { DEFOP(Iop_NegF64, UNDEF_ALL), .s390x = 1, .amd64 = 1, .x86 = 1, .arm = 1, .ppc64 = 1, .ppc32 = 1, .mips32 = 1, .mips64 = 1 }, { DEFOP(Iop_AbsF64, UNDEF_ALL), .s390x = 1, .amd64 = 1, .x86 = 1, .arm = 1, .ppc64 = 1, .ppc32 = 1, .mips32 = 1, .mips64 = 1 }, { DEFOP(Iop_NegF32, UNDEF_ALL), .s390x = 1, .amd64 = 0, .x86 = 0, .arm = 1, .ppc64 = 0, .ppc32 = 0, .mips32 = 1, .mips64 = 1 }, { DEFOP(Iop_AbsF32, UNDEF_ALL), .s390x = 1, .amd64 = 0, .x86 = 0, .arm = 1, .ppc64 = 0, .ppc32 = 0, .mips32 = 1, .mips64 = 1 }, { DEFOP(Iop_SqrtF64, UNDEF_ALL), .s390x = 1, .amd64 = 1, .x86 = 1, .arm = 1, .ppc64 = 1, .ppc32 = 1, .mips32 = 0, .mips64 = 1 }, // mips asserts { DEFOP(Iop_SqrtF32, UNDEF_ALL), .s390x = 1, .amd64 = 0, .x86 = 0, .arm = 1, .ppc64 = 0, .ppc32 = 0, .mips32 = 1, .mips64 = 1 }, { DEFOP(Iop_CmpF64, UNDEF_ALL), .s390x = 1, .amd64 = 1, .x86 = 1, .arm = 1, .ppc64 = 1, .ppc32 = 1, .mips32 = 1, .mips64 = 1 }, { DEFOP(Iop_CmpF32, UNDEF_ALL), .s390x = 1, .amd64 = 0, .x86 = 0, .arm = 0, .ppc64 = 0, .ppc32 = 0, .mips32 = 0, .mips64 = 0 }, // mips asserts { DEFOP(Iop_CmpF128, UNDEF_ALL), .s390x = 1, .amd64 = 0, .x86 = 0, .arm = 0, .ppc64 = 0, .ppc32 = 0, .mips32 = 0, .mips64 = 0 }, { DEFOP(Iop_F64toI16S, UNDEF_ALL), .s390x = 0, .amd64 = 0, .x86 = 1, .arm = 0, .ppc64 = 0, .ppc32 = 0, .mips32 = 0, .mips64 = 0 }, { DEFOP(Iop_F64toI32S, UNDEF_ALL), .s390x = 1, .amd64 = 1, .x86 = 1, .arm = 1, .ppc64 = 1, .ppc32 = 1, .mips32 = 1, .mips64 = 1 }, { DEFOP(Iop_F64toI64S, UNDEF_ALL), .s390x = 1, .amd64 = 1, .x86 = 1, .arm = 0, .ppc64 = 1, .ppc32 = 1, .mips32 = 0, .mips64 = 0 }, { DEFOP(Iop_F64toI64U, UNDEF_ALL), .s390x = 1, .amd64 = 0, .x86 = 0, .arm = 0, .ppc64 = 1, .ppc32 = 1, .mips32 = 0, .mips64 = 0 }, { DEFOP(Iop_F64toI32U, UNDEF_ALL), .s390x = 1, .amd64 = 0, .x86 = 0, .arm = 1, .ppc64 = 1, .ppc32 = 1, .mips32 = 0, .mips64 = 0 }, { DEFOP(Iop_I32StoF64, UNDEF_ALL), .s390x = 1, .amd64 = 1, .x86 = 1, .arm = 1, .ppc64 = 0, .ppc32 = 0, .mips32 = 1, .mips64 = 1 }, { DEFOP(Iop_I64StoF64, UNDEF_ALL), .s390x = 1, .amd64 = 1, .x86 = 1, .arm = 0, .ppc64 = 1, .ppc32 = 1, .mips32 = 0, .mips64 = 1 }, { DEFOP(Iop_I64UtoF64, UNDEF_ALL), .s390x = 1, .amd64 = 0, .x86 = 0, .arm = 0, .ppc64 = 1, .ppc32 = 1, .mips32 = 0, .mips64 = 0 }, // mips asserts { DEFOP(Iop_I64UtoF32, UNDEF_ALL), .s390x = 1, .amd64 = 0, .x86 = 0, .arm = 0, .ppc64 = 1, .ppc32 = 1, .mips32 = 0, .mips64 = 0 }, { DEFOP(Iop_I32UtoF32, UNDEF_ALL), .s390x = 1, .amd64 = 0, .x86 = 0, .arm = 0, .ppc64 = 0, .ppc32 = 0, .mips32 = 0, .mips64 = 0 }, { DEFOP(Iop_I32UtoF64, UNDEF_ALL), .s390x = 1, .amd64 = 0, .x86 = 0, .arm = 1, .ppc64 = 0, .ppc32 = 0, .mips32 = 0, .mips64 = 0 }, { DEFOP(Iop_F32toI32S, UNDEF_ALL), .s390x = 1, .amd64 = 0, .x86 = 0, .arm = 0, .ppc64 = 0, .ppc32 = 0, .mips32 = 0, .mips64 = 0 }, { DEFOP(Iop_F32toI64S, UNDEF_ALL), .s390x = 1, .amd64 = 0, .x86 = 0, .arm = 0, .ppc64 = 0, .ppc32 = 0, .mips32 = 0, .mips64 = 1 }, { DEFOP(Iop_F32toI32U, UNDEF_ALL), .s390x = 1, .amd64 = 0, .x86 = 0, .arm = 0, .ppc64 = 0, .ppc32 = 0, .mips32 = 0, .mips64 = 0 }, { DEFOP(Iop_F32toI64U, UNDEF_ALL), .s390x = 1, .amd64 = 0, .x86 = 0, .arm = 0, .ppc64 = 0, .ppc32 = 0, .mips32 = 0, .mips64 = 0 }, { DEFOP(Iop_I32StoF32, UNDEF_ALL), .s390x = 1, .amd64 = 0, .x86 = 0, .arm = 0, .ppc64 = 0, .ppc32 = 0, .mips32 = 1, .mips64 = 1 }, { DEFOP(Iop_I64StoF32, UNDEF_ALL), .s390x = 1, .amd64 = 0, .x86 = 0, .arm = 0, .ppc64 = 0, .ppc32 = 0, .mips32 = 0, .mips64 = 1 }, { DEFOP(Iop_F32toF64, UNDEF_ALL), .s390x = 1, .amd64 = 1, .x86 = 1, .arm = 1, .ppc64 = 1, .ppc32 = 1, .mips32 = 1, .mips64 = 1 }, { DEFOP(Iop_F64toF32, UNDEF_ALL), .s390x = 1, .amd64 = 1, .x86 = 1, .arm = 1, .ppc64 = 0, .ppc32 = 0, .mips32 = 0, .mips64 = 1 }, // mips asserts { DEFOP(<API key>, UNDEF_SAME), .s390x = 1, .amd64 = 1, .x86 = 1, .arm = 1, .ppc64 = 1, .ppc32 = 1, .mips32 = 0, .mips64 = 1 }, // mips asserts { DEFOP(<API key>, UNDEF_SAME), .s390x = 1, .amd64 = 1, .x86 = 1, .arm = 1, .ppc64 = 1, .ppc32 = 1, .mips32 = 0, .mips64 = 1 }, // mips asserts { DEFOP(<API key>, UNDEF_SAME), .s390x = 1, .amd64 = 1, .x86 = 1, .arm = 1, .ppc64 = 1, .ppc32 = 1, .mips32 = 1, .mips64 = 1 }, // ppc requires this op to show up in a specific context. So it cannot be // tested standalone on that platform. { DEFOP(<API key>, UNDEF_SAME), .s390x = 1, .amd64 = 1, .x86 = 1, .arm = 1, .ppc64 = 0, .ppc32 = 0, .mips32 = 1, .mips64 = 1 }, { DEFOP(Iop_F64HLtoF128, UNDEF_CONCAT), .s390x = 1, .amd64 = 0, .x86 = 0, .arm = 0, .ppc64 = 0, .ppc32 = 0, .mips32 = 0, .mips64 = 0 }, { DEFOP(Iop_F128HItoF64, UNDEF_UPPER), .s390x = 1, .amd64 = 0, .x86 = 0, .arm = 0, .ppc64 = 0, .ppc32 = 0, .mips32 = 0, .mips64 = 0 }, { DEFOP(Iop_F128LOtoF64, UNDEF_TRUNC), .s390x = 1, .amd64 = 0, .x86 = 0, .arm = 0, .ppc64 = 0, .ppc32 = 0, .mips32 = 0, .mips64 = 0 }, { DEFOP(Iop_AddF128, UNDEF_ALL), .s390x = 1, .amd64 = 0, .x86 = 0, .arm = 0, .ppc64 = 0, .ppc32 = 0, .mips32 = 0, .mips64 = 0 }, { DEFOP(Iop_SubF128, UNDEF_ALL), .s390x = 1, .amd64 = 0, .x86 = 0, .arm = 0, .ppc64 = 0, .ppc32 = 0, .mips32 = 0, .mips64 = 0 }, { DEFOP(Iop_MulF128, UNDEF_ALL), .s390x = 1, .amd64 = 0, .x86 = 0, .arm = 0, .ppc64 = 0, .ppc32 = 0, .mips32 = 0, .mips64 = 0 }, { DEFOP(Iop_DivF128, UNDEF_ALL), .s390x = 1, .amd64 = 0, .x86 = 0, .arm = 0, .ppc64 = 0, .ppc32 = 0, .mips32 = 0, .mips64 = 0 }, { DEFOP(Iop_NegF128, UNDEF_ALL), .s390x = 1, .amd64 = 0, .x86 = 0, .arm = 0, .ppc64 = 0, .ppc32 = 0, .mips32 = 0, .mips64 = 0 }, { DEFOP(Iop_AbsF128, UNDEF_ALL), .s390x = 1, .amd64 = 0, .x86 = 0, .arm = 0, .ppc64 = 0, .ppc32 = 0, .mips32 = 0, .mips64 = 0 }, { DEFOP(Iop_SqrtF128, UNDEF_ALL), .s390x = 1, .amd64 = 0, .x86 = 0, .arm = 0, .ppc64 = 0, .ppc32 = 0, .mips32 = 0, .mips64 = 0 }, { DEFOP(Iop_I32StoF128, UNDEF_ALL), .s390x = 1, .amd64 = 0, .x86 = 0, .arm = 0, .ppc64 = 0, .ppc32 = 0, .mips32 = 0, .mips64 = 0 }, { DEFOP(Iop_I64StoF128, UNDEF_ALL), .s390x = 1, .amd64 = 0, .x86 = 0, .arm = 0, .ppc64 = 0, .ppc32 = 0, .mips32 = 0, .mips64 = 0 }, { DEFOP(Iop_I32UtoF128, UNDEF_ALL), .s390x = 1, .amd64 = 0, .x86 = 0, .arm = 0, .ppc64 = 0, .ppc32 = 0, .mips32 = 0, .mips64 = 0 }, { DEFOP(Iop_I64UtoF128, UNDEF_ALL), .s390x = 1, .amd64 = 0, .x86 = 0, .arm = 0, .ppc64 = 0, .ppc32 = 0, .mips32 = 0, .mips64 = 0 }, { DEFOP(Iop_F32toF128, UNDEF_ALL), .s390x = 1, .amd64 = 0, .x86 = 0, .arm = 0, .ppc64 = 0, .ppc32 = 0, .mips32 = 0, .mips64 = 0 }, { DEFOP(Iop_F64toF128, UNDEF_ALL), .s390x = 1, .amd64 = 0, .x86 = 0, .arm = 0, .ppc64 = 0, .ppc32 = 0, .mips32 = 0, .mips64 = 0 }, { DEFOP(Iop_F128toI32S, UNDEF_ALL), .s390x = 1, .amd64 = 0, .x86 = 0, .arm = 0, .ppc64 = 0, .ppc32 = 0, .mips32 = 0, .mips64 = 0 }, { DEFOP(Iop_F128toI64S, UNDEF_ALL), .s390x = 1, .amd64 = 0, .x86 = 0, .arm = 0, .ppc64 = 0, .ppc32 = 0, .mips32 = 0, .mips64 = 0 }, { DEFOP(Iop_F128toI32U, UNDEF_ALL), .s390x = 1, .amd64 = 0, .x86 = 0, .arm = 0, .ppc64 = 0, .ppc32 = 0, .mips32 = 0, .mips64 = 0 }, { DEFOP(Iop_F128toI64U, UNDEF_ALL), .s390x = 1, .amd64 = 0, .x86 = 0, .arm = 0, .ppc64 = 0, .ppc32 = 0, .mips32 = 0, .mips64 = 0 }, { DEFOP(Iop_F128toF64, UNDEF_ALL), .s390x = 1, .amd64 = 0, .x86 = 0, .arm = 0, .ppc64 = 0, .ppc32 = 0, .mips32 = 0, .mips64 = 0 }, { DEFOP(Iop_F128toF32, UNDEF_ALL), .s390x = 1, .amd64 = 0, .x86 = 0, .arm = 0, .ppc64 = 0, .ppc32 = 0, .mips32 = 0, .mips64 = 0 }, { DEFOP(Iop_AtanF64, UNDEF_ALL), .s390x = 0, .amd64 = 1, .x86 = 1, .arm = 0, .ppc64 = 0, .ppc32 = 0, .mips32 = 0, .mips64 = 0 }, { DEFOP(Iop_Yl2xF64, UNDEF_ALL), .s390x = 0, .amd64 = 1, .x86 = 1, .arm = 0, .ppc64 = 0, .ppc32 = 0, .mips32 = 0, .mips64 = 0 }, { DEFOP(Iop_Yl2xp1F64, UNDEF_ALL), .s390x = 0, .amd64 = 1, .x86 = 1, .arm = 0, .ppc64 = 0, .ppc32 = 0, .mips32 = 0, .mips64 = 0 }, { DEFOP(Iop_PRemF64, UNDEF_ALL), .s390x = 0, .amd64 = 1, .x86 = 1, .arm = 0, .ppc64 = 0, .ppc32 = 0, .mips32 = 0, .mips64 = 0 }, { DEFOP(Iop_PRemC3210F64, UNDEF_ALL), .s390x = 0, .amd64 = 1, .x86 = 1, .arm = 0, .ppc64 = 0, .ppc32 = 0, .mips32 = 0, .mips64 = 0 }, { DEFOP(Iop_PRem1F64, UNDEF_ALL), .s390x = 0, .amd64 = 1, .x86 = 1, .arm = 0, .ppc64 = 0, .ppc32 = 0, .mips32 = 0, .mips64 = 0 }, { DEFOP(Iop_PRem1C3210F64, UNDEF_ALL), .s390x = 0, .amd64 = 1, .x86 = 1, .arm = 0, .ppc64 = 0, .ppc32 = 0, .mips32 = 0, .mips64 = 0 }, { DEFOP(Iop_ScaleF64, UNDEF_ALL), .s390x = 0, .amd64 = 1, .x86 = 1, .arm = 0, .ppc64 = 0, .ppc32 = 0, .mips32 = 0, .mips64 = 0 }, { DEFOP(Iop_SinF64, UNDEF_ALL), .s390x = 0, .amd64 = 1, .x86 = 1, .arm = 0, .ppc64 = 0, .ppc32 = 0, .mips32 = 0, .mips64 = 0 }, { DEFOP(Iop_CosF64, UNDEF_ALL), .s390x = 0, .amd64 = 1, .x86 = 1, .arm = 0, .ppc64 = 0, .ppc32 = 0, .mips32 = 0, .mips64 = 0 }, { DEFOP(Iop_TanF64, UNDEF_ALL), .s390x = 0, .amd64 = 1, .x86 = 1, .arm = 0, .ppc64 = 0, .ppc32 = 0, .mips32 = 0, .mips64 = 0 }, { DEFOP(Iop_2xm1F64, UNDEF_ALL), .s390x = 0, .amd64 = 1, .x86 = 1, .arm = 0, .ppc64 = 0, .ppc32 = 0, .mips32 = 0, .mips64 = 0 }, { DEFOP(Iop_RoundF64toInt, UNDEF_ALL), .s390x = 0, .amd64 = 1, .x86 = 1, .arm = 0, .ppc64 = 0, .ppc32 = 0, .mips32 = 0, .mips64 = 1 }, { DEFOP(Iop_RoundF32toInt, UNDEF_ALL), .s390x = 0, .amd64 = 1, .x86 = 1, .arm = 0, .ppc64 = 0, .ppc32 = 0, .mips32 = 1, .mips64 = 1 }, { DEFOP(Iop_MAddF32, UNDEF_ALL), .s390x = 1, .amd64 = 0, .x86 = 0, .arm = 0, .ppc64 = 0, .ppc32 = 0, .mips32 = 0, .mips64 = 1 }, { DEFOP(Iop_MSubF32, UNDEF_ALL), .s390x = 1, .amd64 = 0, .x86 = 0, .arm = 0, .ppc64 = 0, .ppc32 = 0, .mips32 = 0, .mips64 = 1 }, { DEFOP(Iop_MAddF64, UNDEF_ALL), .s390x = 1, .amd64 = 0, .x86 = 0, .arm = 0, .ppc64 = 1, .ppc32 = 1, .mips32 = 0, .mips64 = 1 }, { DEFOP(Iop_MSubF64, UNDEF_ALL), .s390x = 1, .amd64 = 0, .x86 = 0, .arm = 0, .ppc64 = 1, .ppc32 = 1, .mips32 = 0, .mips64 = 1 }, { DEFOP(Iop_MAddF64r32, UNDEF_ALL), .s390x = 0, .amd64 = 0, .x86 = 0, .arm = 0, .ppc64 = 1, .ppc32 = 1, .mips32 = 0, .mips64 = 0 }, { DEFOP(Iop_MSubF64r32, UNDEF_ALL), .s390x = 0, .amd64 = 0, .x86 = 0, .arm = 0, .ppc64 = 1, .ppc32 = 1, .mips32 = 0, .mips64 = 0 }, { DEFOP(<API key>, UNDEF_ALL), .s390x = 0, .amd64 = 0, .x86 = 0, .arm = 0, .ppc64 = 1, .ppc32 = 1, .mips32 = 0, .mips64 = 0 }, { DEFOP(<API key>, UNDEF_ALL), .s390x = 0, .amd64 = 0, .x86 = 0, .arm = 0, .ppc64 = 1, .ppc32 = 1, .mips32 = 0, .mips64 = 1 }, { DEFOP(<API key>, UNDEF_ALL), .s390x = 0, .amd64 = 0, .x86 = 0, .arm = 0, .ppc64 = 1, .ppc32 = 1, .mips32 = 0, .mips64 = 1 }, { DEFOP(<API key>, UNDEF_ALL), .s390x = 0, .amd64 = 0, .x86 = 0, .arm = 0, .ppc64 = 1, .ppc32 = 1, .mips32 = 0, .mips64 = 1 }, { DEFOP(<API key>, UNDEF_ALL), .s390x = 0, .amd64 = 0, .x86 = 0, .arm = 0, .ppc64 = 1, .ppc32 = 1, .mips32 = 0, .mips64 = 1 }, { DEFOP(Iop_TruncF64asF32, UNDEF_ALL), .s390x = 0, .amd64 = 0, .x86 = 0, .arm = 0, .ppc64 = 1, .ppc32 = 1, .mips32 = 0, .mips64 = 1 }, // mips asserts { DEFOP(Iop_RoundF64toF32, UNDEF_ALL), .s390x = 0, .amd64 = 0, .x86 = 0, .arm = 0, .ppc64 = 1, .ppc32 = 1, .mips32 = 0, .mips64 = 0 }, { DEFOP(Iop_QAdd32S, UNDEF_UNKNOWN), }, { DEFOP(Iop_QSub32S, UNDEF_UNKNOWN), }, { DEFOP(Iop_Add16x2, UNDEF_UNKNOWN), }, { DEFOP(Iop_Sub16x2, UNDEF_UNKNOWN), }, { DEFOP(Iop_QAdd16Sx2, UNDEF_UNKNOWN), }, { DEFOP(Iop_QAdd16Ux2, UNDEF_UNKNOWN), }, { DEFOP(Iop_QSub16Sx2, UNDEF_UNKNOWN), }, { DEFOP(Iop_QSub16Ux2, UNDEF_UNKNOWN), }, { DEFOP(Iop_HAdd16Ux2, UNDEF_UNKNOWN), }, { DEFOP(Iop_HAdd16Sx2, UNDEF_UNKNOWN), }, { DEFOP(Iop_HSub16Ux2, UNDEF_UNKNOWN), }, { DEFOP(Iop_HSub16Sx2, UNDEF_UNKNOWN), }, { DEFOP(Iop_Add8x4, UNDEF_UNKNOWN), }, { DEFOP(Iop_Sub8x4, UNDEF_UNKNOWN), }, { DEFOP(Iop_QAdd8Sx4, UNDEF_UNKNOWN), }, { DEFOP(Iop_QAdd8Ux4, UNDEF_UNKNOWN), }, { DEFOP(Iop_QSub8Sx4, UNDEF_UNKNOWN), }, { DEFOP(Iop_QSub8Ux4, UNDEF_UNKNOWN), }, { DEFOP(Iop_HAdd8Ux4, UNDEF_UNKNOWN), }, { DEFOP(Iop_HAdd8Sx4, UNDEF_UNKNOWN), }, { DEFOP(Iop_HSub8Ux4, UNDEF_UNKNOWN), }, { DEFOP(Iop_HSub8Sx4, UNDEF_UNKNOWN), }, { DEFOP(Iop_Sad8Ux4, UNDEF_UNKNOWN), }, { DEFOP(Iop_CmpNEZ16x2, UNDEF_UNKNOWN), }, { DEFOP(Iop_CmpNEZ8x4, UNDEF_UNKNOWN), }, { DEFOP(Iop_I32UtoFx2, UNDEF_UNKNOWN), }, { DEFOP(Iop_I32StoFx2, UNDEF_UNKNOWN), }, { DEFOP(Iop_FtoI32Ux2_RZ, UNDEF_UNKNOWN), }, { DEFOP(Iop_FtoI32Sx2_RZ, UNDEF_UNKNOWN), }, { DEFOP(<API key>, UNDEF_UNKNOWN), }, { DEFOP(<API key>, UNDEF_UNKNOWN), }, { DEFOP(<API key>, UNDEF_UNKNOWN), }, { DEFOP(<API key>, UNDEF_UNKNOWN), }, { DEFOP(Iop_Max32Fx2, UNDEF_UNKNOWN), }, { DEFOP(Iop_Min32Fx2, UNDEF_UNKNOWN), }, { DEFOP(Iop_PwMax32Fx2, UNDEF_UNKNOWN), }, { DEFOP(Iop_PwMin32Fx2, UNDEF_UNKNOWN), }, { DEFOP(Iop_CmpEQ32Fx2, UNDEF_UNKNOWN), }, { DEFOP(Iop_CmpGT32Fx2, UNDEF_UNKNOWN), }, { DEFOP(Iop_CmpGE32Fx2, UNDEF_UNKNOWN), }, { DEFOP(Iop_RecipEst32Fx2, UNDEF_UNKNOWN), }, { DEFOP(Iop_RecipStep32Fx2, UNDEF_UNKNOWN), }, { DEFOP(Iop_RSqrtEst32Fx2, UNDEF_UNKNOWN), }, { DEFOP(Iop_RSqrtStep32Fx2, UNDEF_UNKNOWN), }, { DEFOP(Iop_Neg32Fx2, UNDEF_UNKNOWN), }, { DEFOP(Iop_Abs32Fx2, UNDEF_UNKNOWN), }, { DEFOP(Iop_CmpNEZ8x8, UNDEF_UNKNOWN), }, { DEFOP(Iop_CmpNEZ16x4, UNDEF_UNKNOWN), }, { DEFOP(Iop_CmpNEZ32x2, UNDEF_UNKNOWN), }, { DEFOP(Iop_Add8x8, UNDEF_UNKNOWN), }, { DEFOP(Iop_Add16x4, UNDEF_UNKNOWN), }, { DEFOP(Iop_Add32x2, UNDEF_UNKNOWN), }, { DEFOP(Iop_QAdd8Ux8, UNDEF_UNKNOWN), }, { DEFOP(Iop_QAdd16Ux4, UNDEF_UNKNOWN), }, { DEFOP(Iop_QAdd32Ux2, UNDEF_UNKNOWN), }, { DEFOP(Iop_QAdd64Ux1, UNDEF_UNKNOWN), }, { DEFOP(Iop_QAdd8Sx8, UNDEF_UNKNOWN), }, { DEFOP(Iop_QAdd16Sx4, UNDEF_UNKNOWN), }, { DEFOP(Iop_QAdd32Sx2, UNDEF_UNKNOWN), }, { DEFOP(Iop_QAdd64Sx1, UNDEF_UNKNOWN), }, { DEFOP(Iop_PwAdd8x8, UNDEF_UNKNOWN), }, { DEFOP(Iop_PwAdd16x4, UNDEF_UNKNOWN), }, { DEFOP(Iop_PwAdd32x2, UNDEF_UNKNOWN), }, { DEFOP(Iop_PwMax8Sx8, UNDEF_UNKNOWN), }, { DEFOP(Iop_PwMax16Sx4, UNDEF_UNKNOWN), }, { DEFOP(Iop_PwMax32Sx2, UNDEF_UNKNOWN), }, { DEFOP(Iop_PwMax8Ux8, UNDEF_UNKNOWN), }, { DEFOP(Iop_PwMax16Ux4, UNDEF_UNKNOWN), }, { DEFOP(Iop_PwMax32Ux2, UNDEF_UNKNOWN), }, { DEFOP(Iop_PwMin8Sx8, UNDEF_UNKNOWN), }, { DEFOP(Iop_PwMin16Sx4, UNDEF_UNKNOWN), }, { DEFOP(Iop_PwMin32Sx2, UNDEF_UNKNOWN), }, { DEFOP(Iop_PwMin8Ux8, UNDEF_UNKNOWN), }, { DEFOP(Iop_PwMin16Ux4, UNDEF_UNKNOWN), }, { DEFOP(Iop_PwMin32Ux2, UNDEF_UNKNOWN), }, { DEFOP(Iop_PwAddL8Ux8, UNDEF_UNKNOWN), }, { DEFOP(Iop_PwAddL16Ux4, UNDEF_UNKNOWN), }, { DEFOP(Iop_PwAddL32Ux2, UNDEF_UNKNOWN), }, { DEFOP(Iop_PwAddL8Sx8, UNDEF_UNKNOWN), }, { DEFOP(Iop_PwAddL16Sx4, UNDEF_UNKNOWN), }, { DEFOP(Iop_PwAddL32Sx2, UNDEF_UNKNOWN), }, { DEFOP(Iop_Sub8x8, UNDEF_UNKNOWN), }, { DEFOP(Iop_Sub16x4, UNDEF_UNKNOWN), }, { DEFOP(Iop_Sub32x2, UNDEF_UNKNOWN), }, { DEFOP(Iop_QSub8Ux8, UNDEF_UNKNOWN), }, { DEFOP(Iop_QSub16Ux4, UNDEF_UNKNOWN), }, { DEFOP(Iop_QSub32Ux2, UNDEF_UNKNOWN), }, { DEFOP(Iop_QSub64Ux1, UNDEF_UNKNOWN), }, { DEFOP(Iop_QSub8Sx8, UNDEF_UNKNOWN), }, { DEFOP(Iop_QSub16Sx4, UNDEF_UNKNOWN), }, { DEFOP(Iop_QSub32Sx2, UNDEF_UNKNOWN), }, { DEFOP(Iop_QSub64Sx1, UNDEF_UNKNOWN), }, { DEFOP(Iop_Abs8x8, UNDEF_UNKNOWN), }, { DEFOP(Iop_Abs16x4, UNDEF_UNKNOWN), }, { DEFOP(Iop_Abs32x2, UNDEF_UNKNOWN), }, { DEFOP(Iop_Mul8x8, UNDEF_UNKNOWN), }, { DEFOP(Iop_Mul16x4, UNDEF_UNKNOWN), }, { DEFOP(Iop_Mul32x2, UNDEF_UNKNOWN), }, { DEFOP(Iop_Mul32Fx2, UNDEF_UNKNOWN), }, { DEFOP(Iop_MulHi16Ux4, UNDEF_UNKNOWN), }, { DEFOP(Iop_MulHi16Sx4, UNDEF_UNKNOWN), }, { DEFOP(<API key>, UNDEF_UNKNOWN), }, { DEFOP(Iop_QDMulHi16Sx4, UNDEF_UNKNOWN), }, { DEFOP(Iop_QDMulHi32Sx2, UNDEF_UNKNOWN), }, { DEFOP(Iop_QRDMulHi16Sx4, UNDEF_UNKNOWN), }, { DEFOP(Iop_QRDMulHi32Sx2, UNDEF_UNKNOWN), }, { DEFOP(Iop_Avg8Ux8, UNDEF_UNKNOWN), }, { DEFOP(Iop_Avg16Ux4, UNDEF_UNKNOWN), }, { DEFOP(Iop_Max8Sx8, UNDEF_UNKNOWN), }, { DEFOP(Iop_Max16Sx4, UNDEF_UNKNOWN), }, { DEFOP(Iop_Max32Sx2, UNDEF_UNKNOWN), }, { DEFOP(Iop_Max8Ux8, UNDEF_UNKNOWN), }, { DEFOP(Iop_Max16Ux4, UNDEF_UNKNOWN), }, { DEFOP(Iop_Max32Ux2, UNDEF_UNKNOWN), }, { DEFOP(Iop_Min8Sx8, UNDEF_UNKNOWN), }, { DEFOP(Iop_Min16Sx4, UNDEF_UNKNOWN), }, { DEFOP(Iop_Min32Sx2, UNDEF_UNKNOWN), }, { DEFOP(Iop_Min8Ux8, UNDEF_UNKNOWN), }, { DEFOP(Iop_Min16Ux4, UNDEF_UNKNOWN), }, { DEFOP(Iop_Min32Ux2, UNDEF_UNKNOWN), }, { DEFOP(Iop_CmpEQ8x8, UNDEF_UNKNOWN), }, { DEFOP(Iop_CmpEQ16x4, UNDEF_UNKNOWN), }, { DEFOP(Iop_CmpEQ32x2, UNDEF_UNKNOWN), }, { DEFOP(Iop_CmpGT8Ux8, UNDEF_UNKNOWN), }, { DEFOP(Iop_CmpGT16Ux4, UNDEF_UNKNOWN), }, { DEFOP(Iop_CmpGT32Ux2, UNDEF_UNKNOWN), }, { DEFOP(Iop_CmpGT8Sx8, UNDEF_UNKNOWN), }, { DEFOP(Iop_CmpGT16Sx4, UNDEF_UNKNOWN), }, { DEFOP(Iop_CmpGT32Sx2, UNDEF_UNKNOWN), }, { DEFOP(Iop_Cnt8x8, UNDEF_UNKNOWN), }, { DEFOP(Iop_Clz8x8, UNDEF_UNKNOWN), }, { DEFOP(Iop_Clz16x4, UNDEF_UNKNOWN), }, { DEFOP(Iop_Clz32x2, UNDEF_UNKNOWN), }, { DEFOP(Iop_Cls8x8, UNDEF_UNKNOWN), }, { DEFOP(Iop_Cls16x4, UNDEF_UNKNOWN), }, { DEFOP(Iop_Cls32x2, UNDEF_UNKNOWN), }, { DEFOP(Iop_Shl8x8, UNDEF_UNKNOWN), }, { DEFOP(Iop_Shl16x4, UNDEF_UNKNOWN), }, { DEFOP(Iop_Shl32x2, UNDEF_UNKNOWN), }, { DEFOP(Iop_Shr8x8, UNDEF_UNKNOWN), }, { DEFOP(Iop_Shr16x4, UNDEF_UNKNOWN), }, { DEFOP(Iop_Shr32x2, UNDEF_UNKNOWN), }, { DEFOP(Iop_Sar8x8, UNDEF_UNKNOWN), }, { DEFOP(Iop_Sar16x4, UNDEF_UNKNOWN), }, { DEFOP(Iop_Sar32x2, UNDEF_UNKNOWN), }, { DEFOP(Iop_Sal8x8, UNDEF_UNKNOWN), }, { DEFOP(Iop_Sal16x4, UNDEF_UNKNOWN), }, { DEFOP(Iop_Sal32x2, UNDEF_UNKNOWN), }, { DEFOP(Iop_Sal64x1, UNDEF_UNKNOWN), }, { DEFOP(Iop_ShlN8x8, UNDEF_UNKNOWN), }, { DEFOP(Iop_ShlN16x4, UNDEF_UNKNOWN), }, { DEFOP(Iop_ShlN32x2, UNDEF_UNKNOWN), }, { DEFOP(Iop_ShrN8x8, UNDEF_UNKNOWN), }, { DEFOP(Iop_ShrN16x4, UNDEF_UNKNOWN), }, { DEFOP(Iop_ShrN32x2, UNDEF_UNKNOWN), }, { DEFOP(Iop_SarN8x8, UNDEF_UNKNOWN), }, { DEFOP(Iop_SarN16x4, UNDEF_UNKNOWN), }, { DEFOP(Iop_SarN32x2, UNDEF_UNKNOWN), }, { DEFOP(Iop_QShl8x8, UNDEF_UNKNOWN), }, { DEFOP(Iop_QShl16x4, UNDEF_UNKNOWN), }, { DEFOP(Iop_QShl32x2, UNDEF_UNKNOWN), }, { DEFOP(Iop_QShl64x1, UNDEF_UNKNOWN), }, { DEFOP(Iop_QSal8x8, UNDEF_UNKNOWN), }, { DEFOP(Iop_QSal16x4, UNDEF_UNKNOWN), }, { DEFOP(Iop_QSal32x2, UNDEF_UNKNOWN), }, { DEFOP(Iop_QSal64x1, UNDEF_UNKNOWN), }, { DEFOP(Iop_QShlNsatSU8x8, UNDEF_UNKNOWN), }, { DEFOP(Iop_QShlNsatSU16x4, UNDEF_UNKNOWN), }, { DEFOP(Iop_QShlNsatSU32x2, UNDEF_UNKNOWN), }, { DEFOP(Iop_QShlNsatSU64x1, UNDEF_UNKNOWN), }, { DEFOP(Iop_QShlNsatUU8x8, UNDEF_UNKNOWN), }, { DEFOP(Iop_QShlNsatUU16x4, UNDEF_UNKNOWN), }, { DEFOP(Iop_QShlNsatUU32x2, UNDEF_UNKNOWN), }, { DEFOP(Iop_QShlNsatUU64x1, UNDEF_UNKNOWN), }, { DEFOP(Iop_QShlNsatSS8x8, UNDEF_UNKNOWN), }, { DEFOP(Iop_QShlNsatSS16x4, UNDEF_UNKNOWN), }, { DEFOP(Iop_QShlNsatSS32x2, UNDEF_UNKNOWN), }, { DEFOP(Iop_QShlNsatSS64x1, UNDEF_UNKNOWN), }, { DEFOP(<API key>, UNDEF_UNKNOWN), }, { DEFOP(<API key>, UNDEF_UNKNOWN), }, { DEFOP(<API key>, UNDEF_UNKNOWN), }, { DEFOP(<API key>, UNDEF_UNKNOWN), }, { DEFOP(<API key>, UNDEF_UNKNOWN), }, { DEFOP(Iop_InterleaveHI8x8, UNDEF_UNKNOWN), }, { DEFOP(<API key>, UNDEF_UNKNOWN), }, { DEFOP(<API key>, UNDEF_UNKNOWN), }, { DEFOP(Iop_InterleaveLO8x8, UNDEF_UNKNOWN), }, { DEFOP(<API key>, UNDEF_UNKNOWN), }, { DEFOP(<API key>, UNDEF_UNKNOWN), }, { DEFOP(<API key>, UNDEF_UNKNOWN), }, { DEFOP(<API key>, UNDEF_UNKNOWN), }, { DEFOP(<API key>, UNDEF_UNKNOWN), }, { DEFOP(<API key>, UNDEF_UNKNOWN), }, { DEFOP(Iop_CatOddLanes8x8, UNDEF_UNKNOWN), }, { DEFOP(Iop_CatOddLanes16x4, UNDEF_UNKNOWN), }, { DEFOP(Iop_CatEvenLanes8x8, UNDEF_UNKNOWN), }, { DEFOP(<API key>, UNDEF_UNKNOWN), }, { DEFOP(Iop_GetElem8x8, UNDEF_UNKNOWN), }, { DEFOP(Iop_GetElem16x4, UNDEF_UNKNOWN), }, { DEFOP(Iop_GetElem32x2, UNDEF_UNKNOWN), }, { DEFOP(Iop_SetElem8x8, UNDEF_UNKNOWN), }, { DEFOP(Iop_SetElem16x4, UNDEF_UNKNOWN), }, { DEFOP(Iop_SetElem32x2, UNDEF_UNKNOWN), }, { DEFOP(Iop_Dup8x8, UNDEF_UNKNOWN), }, { DEFOP(Iop_Dup16x4, UNDEF_UNKNOWN), }, { DEFOP(Iop_Dup32x2, UNDEF_UNKNOWN), }, { DEFOP(Iop_Slice64, UNDEF_UNKNOWN), }, { DEFOP(<API key>, UNDEF_UNKNOWN), }, { DEFOP(<API key>, UNDEF_UNKNOWN), }, { DEFOP(<API key>, UNDEF_UNKNOWN), }, { DEFOP(<API key>, UNDEF_UNKNOWN), }, { DEFOP(<API key>, UNDEF_UNKNOWN), }, { DEFOP(<API key>, UNDEF_UNKNOWN), }, { DEFOP(Iop_Perm8x8, UNDEF_UNKNOWN), }, { DEFOP(Iop_GetMSBs8x8, UNDEF_UNKNOWN), }, { DEFOP(Iop_RecipEst32Ux2, UNDEF_UNKNOWN), }, { DEFOP(Iop_RSqrtEst32Ux2, UNDEF_UNKNOWN), }, { DEFOP(Iop_AddD64, UNDEF_ALL), .s390x = 1, .ppc64 = 1, .ppc32 = 1 }, { DEFOP(Iop_SubD64, UNDEF_ALL), .s390x = 1, .ppc64 = 1, .ppc32 = 1 }, { DEFOP(Iop_MulD64, UNDEF_ALL), .s390x = 1, .ppc64 = 1, .ppc32 = 1 }, { DEFOP(Iop_DivD64, UNDEF_ALL), .s390x = 1, .ppc64 = 1, .ppc32 = 1 }, { DEFOP(Iop_AddD128, UNDEF_ALL), .s390x = 1, .ppc64 = 1, .ppc32 = 1 }, { DEFOP(Iop_SubD128, UNDEF_ALL), .s390x = 1, .ppc64 = 1, .ppc32 = 1 }, { DEFOP(Iop_MulD128, UNDEF_ALL), .s390x = 1, .ppc64 = 1, .ppc32 = 1 }, { DEFOP(Iop_DivD128, UNDEF_ALL), .s390x = 1, .ppc64 = 1, .ppc32 = 1 }, { DEFOP(Iop_ShlD64, UNDEF_ALL), .s390x = 0, .ppc64 = 1, .ppc32 = 1 }, { DEFOP(Iop_ShrD64, UNDEF_ALL), .s390x = 0, .ppc64 = 1, .ppc32 = 1 }, { DEFOP(Iop_ShlD128, UNDEF_ALL), .s390x = 0, .ppc64 = 1, .ppc32 = 1 }, { DEFOP(Iop_ShrD128, UNDEF_ALL), .s390x = 0, .ppc64 = 1, .ppc32 = 1 }, { DEFOP(Iop_D32toD64, UNDEF_ALL), .s390x = 1, .ppc64 = 1, .ppc32 = 1 }, { DEFOP(Iop_D64toD128, UNDEF_ALL), .s390x = 1, .ppc64 = 1, .ppc32 = 1 }, { DEFOP(Iop_I32StoD128, UNDEF_ALL), .s390x = 1, .ppc64 = 0, .ppc32 = 0 }, { DEFOP(Iop_I32UtoD128, UNDEF_ALL), .s390x = 1, .ppc64 = 0, .ppc32 = 0 }, { DEFOP(Iop_I64StoD128, UNDEF_ALL), .s390x = 1, .ppc64 = 1, .ppc32 = 1 }, { DEFOP(Iop_I64UtoD128, UNDEF_ALL), .s390x = 1, .ppc64 = 0, .ppc32 = 0 }, { DEFOP(Iop_D64toD32, UNDEF_ALL), .s390x = 1, .ppc64 = 1, .ppc32 = 1 }, { DEFOP(Iop_D128toD64, UNDEF_ALL), .s390x = 1, .ppc64 = 1, .ppc32 = 1 }, { DEFOP(Iop_I32StoD64, UNDEF_ALL), .s390x = 1, .ppc64 = 0, .ppc32 = 0 }, { DEFOP(Iop_I32UtoD64, UNDEF_ALL), .s390x = 1, .ppc64 = 0, .ppc32 = 0 }, { DEFOP(Iop_I64StoD64, UNDEF_ALL), .s390x = 1, .ppc64 = 1, .ppc32 = 1 }, { DEFOP(Iop_I64UtoD64, UNDEF_ALL), .s390x = 1, .ppc64 = 0, .ppc32 = 0 }, { DEFOP(Iop_D64toI32S, UNDEF_ALL), .s390x = 1, .ppc64 = 0, .ppc32 = 0 }, { DEFOP(Iop_D64toI32U, UNDEF_ALL), .s390x = 1, .ppc64 = 0, .ppc32 = 0 }, { DEFOP(Iop_D64toI64S, UNDEF_ALL), .s390x = 1, .ppc64 = 1, .ppc32 = 1 }, { DEFOP(Iop_D64toI64U, UNDEF_ALL), .s390x = 1, .ppc64 = 0, .ppc32 = 0 }, { DEFOP(Iop_D128toI64S, UNDEF_ALL), .s390x = 1, .ppc64 = 1, .ppc32 = 1 }, { DEFOP(Iop_D128toI64U, UNDEF_ALL), .s390x = 1, .ppc64 = 0, .ppc32 = 0 }, { DEFOP(Iop_D128toI32S, UNDEF_ALL), .s390x = 1, .ppc64 = 0, .ppc32 = 0 }, { DEFOP(Iop_D128toI32U, UNDEF_ALL), .s390x = 1, .ppc64 = 0, .ppc32 = 0 }, { DEFOP(Iop_F32toD32, UNDEF_ALL), .s390x = 1, .ppc64 = 0, .ppc32 = 0 }, { DEFOP(Iop_F32toD64, UNDEF_ALL), .s390x = 1, .ppc64 = 0, .ppc32 = 0 }, { DEFOP(Iop_F32toD128, UNDEF_ALL), .s390x = 1, .ppc64 = 0, .ppc32 = 0 }, { DEFOP(Iop_F64toD32, UNDEF_ALL), .s390x = 1, .ppc64 = 0, .ppc32 = 0 }, { DEFOP(Iop_F64toD64, UNDEF_ALL), .s390x = 1, .ppc64 = 0, .ppc32 = 0 }, { DEFOP(Iop_F64toD128, UNDEF_ALL), .s390x = 1, .ppc64 = 0, .ppc32 = 0 }, { DEFOP(Iop_F128toD32, UNDEF_ALL), .s390x = 1, .ppc64 = 0, .ppc32 = 0 }, { DEFOP(Iop_F128toD64, UNDEF_ALL), .s390x = 1, .ppc64 = 0, .ppc32 = 0 }, { DEFOP(Iop_F128toD128, UNDEF_ALL), .s390x = 1, .ppc64 = 0, .ppc32 = 0 }, { DEFOP(Iop_D32toF32, UNDEF_ALL), .s390x = 1, .ppc64 = 0, .ppc32 = 0 }, { DEFOP(Iop_D32toF64, UNDEF_ALL), .s390x = 1, .ppc64 = 0, .ppc32 = 0 }, { DEFOP(Iop_D32toF128, UNDEF_ALL), .s390x = 1, .ppc64 = 0, .ppc32 = 0 }, { DEFOP(Iop_D64toF32, UNDEF_ALL), .s390x = 1, .ppc64 = 0, .ppc32 = 0 }, { DEFOP(Iop_D64toF64, UNDEF_ALL), .s390x = 1, .ppc64 = 0, .ppc32 = 0 }, { DEFOP(Iop_D64toF128, UNDEF_ALL), .s390x = 1, .ppc64 = 0, .ppc32 = 0 }, { DEFOP(Iop_D128toF32, UNDEF_ALL), .s390x = 1, .ppc64 = 0, .ppc32 = 0 }, { DEFOP(Iop_D128toF64, UNDEF_ALL), .s390x = 1, .ppc64 = 0, .ppc32 = 0 }, { DEFOP(Iop_D128toF128, UNDEF_ALL), .s390x = 1, .ppc64 = 0, .ppc32 = 0 }, { DEFOP(Iop_RoundD64toInt, UNDEF_ALL), .s390x = 0, .ppc64 = 1, .ppc32 = 1 }, { DEFOP(Iop_RoundD128toInt, UNDEF_ALL), .s390x = 0, .ppc64 = 1, .ppc32 = 1 }, { DEFOP(Iop_CmpD64, UNDEF_ALL), .s390x = 1, .ppc64 = 1, .ppc32 = 1 }, { DEFOP(Iop_CmpD128, UNDEF_ALL), .s390x = 1, .ppc64 = 1, .ppc32 = 1 }, { DEFOP(Iop_CmpExpD64, UNDEF_ALL), .s390x = 1, .ppc64 = 0, .ppc32 = 0 }, { DEFOP(Iop_CmpExpD128, UNDEF_ALL), .s390x = 1, .ppc64 = 0, .ppc32 = 0 }, { DEFOP(Iop_QuantizeD64, UNDEF_ALL), .s390x = 1, .ppc64 = 1, .ppc32 = 1 }, { DEFOP(Iop_QuantizeD128, UNDEF_ALL), .s390x = 1, .ppc64 = 1, .ppc32 = 1 }, { DEFOP(<API key>, UNDEF_ALL), .s390x = 1, .ppc64 = 1, .ppc32 = 1 }, { DEFOP(<API key>, UNDEF_ALL), .s390x = 1, .ppc64 = 1, .ppc32 = 1 }, { DEFOP(Iop_ExtractExpD64, UNDEF_ALL), .s390x = 1, .ppc64 = 1, .ppc32 = 1 }, { DEFOP(Iop_ExtractExpD128, UNDEF_ALL), .s390x = 1, .ppc64 = 1, .ppc32 = 1 }, { DEFOP(Iop_ExtractSigD64, UNDEF_ALL), .s390x = 1, .ppc64 = 0, .ppc32 = 0 }, { DEFOP(Iop_ExtractSigD128, UNDEF_ALL), .s390x = 1, .ppc64 = 0, .ppc32 = 0 }, { DEFOP(Iop_InsertExpD64, UNDEF_ALL), .s390x = 1, .ppc64 = 1, .ppc32 = 1 }, { DEFOP(Iop_InsertExpD128, UNDEF_ALL), .s390x = 1, .ppc64 = 1, .ppc32 = 1 }, { DEFOP(Iop_D64HLtoD128, UNDEF_CONCAT), .s390x = 1, .ppc64 = 1, .ppc32 = 1 }, { DEFOP(Iop_D128HItoD64, UNDEF_UPPER), .s390x = 1, .ppc64 = 1, .ppc32 = 1 }, { DEFOP(Iop_D128LOtoD64, UNDEF_TRUNC), .s390x = 1, .ppc64 = 1, .ppc32 = 1 }, { DEFOP(Iop_DPBtoBCD, UNDEF_ALL), .s390x = 0, .ppc64 = 1, .ppc32 = 1 }, { DEFOP(Iop_BCDtoDPB, UNDEF_ALL), .s390x = 0, .ppc64 = 1, .ppc32 = 1 }, { DEFOP(<API key>, UNDEF_SAME), .s390x = 1, .ppc64 = 1, .ppc32 = 1 }, { DEFOP(<API key>, UNDEF_SAME), .s390x = 1, .ppc64 = 1, .ppc32 = 1 }, { DEFOP(Iop_Add32Fx4, UNDEF_UNKNOWN), }, { DEFOP(Iop_Sub32Fx4, UNDEF_UNKNOWN), }, { DEFOP(Iop_Mul32Fx4, UNDEF_UNKNOWN), }, { DEFOP(Iop_Div32Fx4, UNDEF_UNKNOWN), }, { DEFOP(Iop_Max32Fx4, UNDEF_UNKNOWN), }, { DEFOP(Iop_Min32Fx4, UNDEF_UNKNOWN), }, { DEFOP(Iop_Add32Fx2, UNDEF_UNKNOWN), }, { DEFOP(Iop_Sub32Fx2, UNDEF_UNKNOWN), }, { DEFOP(Iop_CmpEQ32Fx4, UNDEF_UNKNOWN), }, { DEFOP(Iop_CmpLT32Fx4, UNDEF_UNKNOWN), }, { DEFOP(Iop_CmpLE32Fx4, UNDEF_UNKNOWN), }, { DEFOP(Iop_CmpUN32Fx4, UNDEF_UNKNOWN), }, { DEFOP(Iop_CmpGT32Fx4, UNDEF_UNKNOWN), }, { DEFOP(Iop_CmpGE32Fx4, UNDEF_UNKNOWN), }, { DEFOP(Iop_PwMax32Fx4, UNDEF_UNKNOWN), }, { DEFOP(Iop_PwMin32Fx4, UNDEF_UNKNOWN), }, { DEFOP(Iop_Abs32Fx4, UNDEF_UNKNOWN), }, { DEFOP(Iop_Sqrt32Fx4, UNDEF_UNKNOWN), }, { DEFOP(Iop_Neg32Fx4, UNDEF_UNKNOWN), }, { DEFOP(Iop_RecipEst32Fx4, UNDEF_UNKNOWN), }, { DEFOP(Iop_RecipStep32Fx4, UNDEF_UNKNOWN), }, { DEFOP(Iop_RSqrtEst32Fx4, UNDEF_UNKNOWN), }, { DEFOP(Iop_RSqrtStep32Fx4, UNDEF_UNKNOWN), }, { DEFOP(Iop_I32UtoFx4, UNDEF_UNKNOWN), }, { DEFOP(Iop_I32StoFx4, UNDEF_UNKNOWN), }, { DEFOP(Iop_FtoI32Ux4_RZ, UNDEF_UNKNOWN), }, { DEFOP(Iop_FtoI32Sx4_RZ, UNDEF_UNKNOWN), }, { DEFOP(Iop_QFtoI32Ux4_RZ, UNDEF_UNKNOWN), }, { DEFOP(Iop_QFtoI32Sx4_RZ, UNDEF_UNKNOWN), }, { DEFOP(Iop_RoundF32x4_RM, UNDEF_UNKNOWN), }, { DEFOP(Iop_RoundF32x4_RP, UNDEF_UNKNOWN), }, { DEFOP(Iop_RoundF32x4_RN, UNDEF_UNKNOWN), }, { DEFOP(Iop_RoundF32x4_RZ, UNDEF_UNKNOWN), }, { DEFOP(<API key>, UNDEF_UNKNOWN), }, { DEFOP(<API key>, UNDEF_UNKNOWN), }, { DEFOP(<API key>, UNDEF_UNKNOWN), }, { DEFOP(<API key>, UNDEF_UNKNOWN), }, { DEFOP(Iop_F32toF16x4, UNDEF_UNKNOWN), }, { DEFOP(Iop_F16toF32x4, UNDEF_UNKNOWN), }, { DEFOP(Iop_Add32F0x4, UNDEF_UNKNOWN), }, { DEFOP(Iop_Sub32F0x4, UNDEF_UNKNOWN), }, { DEFOP(Iop_Mul32F0x4, UNDEF_UNKNOWN), }, { DEFOP(Iop_Div32F0x4, UNDEF_UNKNOWN), }, { DEFOP(Iop_Max32F0x4, UNDEF_UNKNOWN), }, { DEFOP(Iop_Min32F0x4, UNDEF_UNKNOWN), }, { DEFOP(Iop_CmpEQ32F0x4, UNDEF_UNKNOWN), }, { DEFOP(Iop_CmpLT32F0x4, UNDEF_UNKNOWN), }, { DEFOP(Iop_CmpLE32F0x4, UNDEF_UNKNOWN), }, { DEFOP(Iop_CmpUN32F0x4, UNDEF_UNKNOWN), }, { DEFOP(Iop_RecipEst32F0x4, UNDEF_UNKNOWN), }, { DEFOP(Iop_Sqrt32F0x4, UNDEF_UNKNOWN), }, { DEFOP(Iop_RSqrtEst32F0x4, UNDEF_UNKNOWN), }, { DEFOP(Iop_Add64Fx2, UNDEF_UNKNOWN), }, { DEFOP(Iop_Sub64Fx2, UNDEF_UNKNOWN), }, { DEFOP(Iop_Mul64Fx2, UNDEF_UNKNOWN), }, { DEFOP(Iop_Div64Fx2, UNDEF_UNKNOWN), }, { DEFOP(Iop_Max64Fx2, UNDEF_UNKNOWN), }, { DEFOP(Iop_Min64Fx2, UNDEF_UNKNOWN), }, { DEFOP(Iop_CmpEQ64Fx2, UNDEF_UNKNOWN), }, { DEFOP(Iop_CmpLT64Fx2, UNDEF_UNKNOWN), }, { DEFOP(Iop_CmpLE64Fx2, UNDEF_UNKNOWN), }, { DEFOP(Iop_CmpUN64Fx2, UNDEF_UNKNOWN), }, { DEFOP(Iop_Abs64Fx2, UNDEF_UNKNOWN), }, { DEFOP(Iop_Sqrt64Fx2, UNDEF_UNKNOWN), }, { DEFOP(Iop_Neg64Fx2, UNDEF_UNKNOWN), }, { DEFOP(Iop_Add64F0x2, UNDEF_UNKNOWN), }, { DEFOP(Iop_Sub64F0x2, UNDEF_UNKNOWN), }, { DEFOP(Iop_Mul64F0x2, UNDEF_UNKNOWN), }, { DEFOP(Iop_Div64F0x2, UNDEF_UNKNOWN), }, { DEFOP(Iop_Max64F0x2, UNDEF_UNKNOWN), }, { DEFOP(Iop_Min64F0x2, UNDEF_UNKNOWN), }, { DEFOP(Iop_CmpEQ64F0x2, UNDEF_UNKNOWN), }, { DEFOP(Iop_CmpLT64F0x2, UNDEF_UNKNOWN), }, { DEFOP(Iop_CmpLE64F0x2, UNDEF_UNKNOWN), }, { DEFOP(Iop_CmpUN64F0x2, UNDEF_UNKNOWN), }, { DEFOP(Iop_Sqrt64F0x2, UNDEF_UNKNOWN), }, { DEFOP(Iop_V128to64, UNDEF_UNKNOWN), }, { DEFOP(Iop_V128HIto64, UNDEF_UNKNOWN), }, { DEFOP(Iop_64HLtoV128, UNDEF_UNKNOWN), }, { DEFOP(Iop_64UtoV128, UNDEF_UNKNOWN), }, { DEFOP(Iop_SetV128lo64, UNDEF_UNKNOWN), }, { DEFOP(Iop_ZeroHI64ofV128, UNDEF_UNKNOWN) }, { DEFOP(Iop_ZeroHI96ofV128, UNDEF_UNKNOWN) }, { DEFOP(Iop_ZeroHI112ofV128, UNDEF_UNKNOWN) }, { DEFOP(Iop_ZeroHI120ofV128, UNDEF_UNKNOWN) }, { DEFOP(Iop_32UtoV128, UNDEF_UNKNOWN), }, { DEFOP(Iop_V128to32, UNDEF_UNKNOWN), }, { DEFOP(Iop_SetV128lo32, UNDEF_UNKNOWN), }, { DEFOP(Iop_NotV128, UNDEF_UNKNOWN), }, { DEFOP(Iop_AndV128, UNDEF_UNKNOWN), }, { DEFOP(Iop_OrV128, UNDEF_UNKNOWN), }, { DEFOP(Iop_XorV128, UNDEF_UNKNOWN), }, { DEFOP(Iop_ShlV128, UNDEF_UNKNOWN), }, { DEFOP(Iop_ShrV128, UNDEF_UNKNOWN), }, { DEFOP(Iop_CmpNEZ8x16, UNDEF_UNKNOWN), }, { DEFOP(Iop_CmpNEZ16x8, UNDEF_UNKNOWN), }, { DEFOP(Iop_CmpNEZ32x4, UNDEF_UNKNOWN), }, { DEFOP(Iop_CmpNEZ64x2, UNDEF_UNKNOWN), }, { DEFOP(Iop_Add8x16, UNDEF_UNKNOWN), }, { DEFOP(Iop_Add16x8, UNDEF_UNKNOWN), }, { DEFOP(Iop_Add32x4, UNDEF_UNKNOWN), }, { DEFOP(Iop_Add64x2, UNDEF_UNKNOWN), }, { DEFOP(Iop_QAdd8Ux16, UNDEF_UNKNOWN), }, { DEFOP(Iop_QAdd16Ux8, UNDEF_UNKNOWN), }, { DEFOP(Iop_QAdd32Ux4, UNDEF_UNKNOWN), }, { DEFOP(Iop_QAdd64Ux2, UNDEF_UNKNOWN), }, { DEFOP(Iop_QAdd8Sx16, UNDEF_UNKNOWN), }, { DEFOP(Iop_QAdd16Sx8, UNDEF_UNKNOWN), }, { DEFOP(Iop_QAdd32Sx4, UNDEF_UNKNOWN), }, { DEFOP(Iop_QAdd64Sx2, UNDEF_UNKNOWN), }, { DEFOP(<API key>, UNDEF_UNKNOWN), }, { DEFOP(<API key>, UNDEF_UNKNOWN), }, { DEFOP(<API key>, UNDEF_UNKNOWN), }, { DEFOP(<API key>, UNDEF_UNKNOWN), }, { DEFOP(<API key>, UNDEF_UNKNOWN), }, { DEFOP(<API key>, UNDEF_UNKNOWN), }, { DEFOP(<API key>, UNDEF_UNKNOWN), }, { DEFOP(<API key>, UNDEF_UNKNOWN), }, { DEFOP(Iop_Sub8x16, UNDEF_UNKNOWN), }, { DEFOP(Iop_Sub16x8, UNDEF_UNKNOWN), }, { DEFOP(Iop_Sub32x4, UNDEF_UNKNOWN), }, { DEFOP(Iop_Sub64x2, UNDEF_UNKNOWN), }, { DEFOP(Iop_QSub8Ux16, UNDEF_UNKNOWN), }, { DEFOP(Iop_QSub16Ux8, UNDEF_UNKNOWN), }, { DEFOP(Iop_QSub32Ux4, UNDEF_UNKNOWN), }, { DEFOP(Iop_QSub64Ux2, UNDEF_UNKNOWN), }, { DEFOP(Iop_QSub8Sx16, UNDEF_UNKNOWN), }, { DEFOP(Iop_QSub16Sx8, UNDEF_UNKNOWN), }, { DEFOP(Iop_QSub32Sx4, UNDEF_UNKNOWN), }, { DEFOP(Iop_QSub64Sx2, UNDEF_UNKNOWN), }, { DEFOP(Iop_Mul8x16, UNDEF_UNKNOWN), }, { DEFOP(Iop_Mul16x8, UNDEF_UNKNOWN), }, { DEFOP(Iop_Mul32x4, UNDEF_UNKNOWN), }, { DEFOP(Iop_MulHi16Ux8, UNDEF_UNKNOWN), }, { DEFOP(Iop_MulHi32Ux4, UNDEF_UNKNOWN), }, { DEFOP(Iop_MulHi16Sx8, UNDEF_UNKNOWN), }, { DEFOP(Iop_MulHi32Sx4, UNDEF_UNKNOWN), }, { DEFOP(Iop_MullEven8Ux16, UNDEF_UNKNOWN), }, { DEFOP(Iop_MullEven16Ux8, UNDEF_UNKNOWN), }, { DEFOP(Iop_MullEven32Ux4, UNDEF_UNKNOWN), }, { DEFOP(Iop_MullEven8Sx16, UNDEF_UNKNOWN), }, { DEFOP(Iop_MullEven16Sx8, UNDEF_UNKNOWN), }, { DEFOP(Iop_MullEven32Sx4, UNDEF_UNKNOWN), }, { DEFOP(Iop_Mull8Ux8, UNDEF_UNKNOWN), }, { DEFOP(Iop_Mull8Sx8, UNDEF_UNKNOWN), }, { DEFOP(Iop_Mull16Ux4, UNDEF_UNKNOWN), }, { DEFOP(Iop_Mull16Sx4, UNDEF_UNKNOWN), }, { DEFOP(Iop_Mull32Ux2, UNDEF_UNKNOWN), }, { DEFOP(Iop_Mull32Sx2, UNDEF_UNKNOWN), }, { DEFOP(Iop_QDMulHi16Sx8, UNDEF_UNKNOWN), }, { DEFOP(Iop_QDMulHi32Sx4, UNDEF_UNKNOWN), }, { DEFOP(Iop_QRDMulHi16Sx8, UNDEF_UNKNOWN), }, { DEFOP(Iop_QRDMulHi32Sx4, UNDEF_UNKNOWN), }, { DEFOP(Iop_QDMull16Sx4, UNDEF_UNKNOWN), }, { DEFOP(Iop_QDMull32Sx2, UNDEF_UNKNOWN), }, { DEFOP(<API key>, UNDEF_UNKNOWN), }, { DEFOP(<API key>, UNDEF_UNKNOWN), }, { DEFOP(Iop_PwAdd8x16, UNDEF_UNKNOWN), }, { DEFOP(Iop_PwAdd16x8, UNDEF_UNKNOWN), }, { DEFOP(Iop_PwAdd32x4, UNDEF_UNKNOWN), }, { DEFOP(Iop_PwAdd32Fx2, UNDEF_UNKNOWN), }, { DEFOP(Iop_PwAddL8Ux16, UNDEF_UNKNOWN), }, { DEFOP(Iop_PwAddL16Ux8, UNDEF_UNKNOWN), }, { DEFOP(Iop_PwAddL32Ux4, UNDEF_UNKNOWN), }, { DEFOP(Iop_PwAddL8Sx16, UNDEF_UNKNOWN), }, { DEFOP(Iop_PwAddL16Sx8, UNDEF_UNKNOWN), }, { DEFOP(Iop_PwAddL32Sx4, UNDEF_UNKNOWN), }, { DEFOP(Iop_Abs8x16, UNDEF_UNKNOWN), }, { DEFOP(Iop_Abs16x8, UNDEF_UNKNOWN), }, { DEFOP(Iop_Abs32x4, UNDEF_UNKNOWN), }, { DEFOP(Iop_Abs64x2, UNDEF_UNKNOWN), }, { DEFOP(Iop_Avg8Ux16, UNDEF_UNKNOWN), }, { DEFOP(Iop_Avg16Ux8, UNDEF_UNKNOWN), }, { DEFOP(Iop_Avg32Ux4, UNDEF_UNKNOWN), }, { DEFOP(Iop_Avg8Sx16, UNDEF_UNKNOWN), }, { DEFOP(Iop_Avg16Sx8, UNDEF_UNKNOWN), }, { DEFOP(Iop_Avg32Sx4, UNDEF_UNKNOWN), }, { DEFOP(Iop_Max8Sx16, UNDEF_UNKNOWN), }, { DEFOP(Iop_Max16Sx8, UNDEF_UNKNOWN), }, { DEFOP(Iop_Max32Sx4, UNDEF_UNKNOWN), }, { DEFOP(Iop_Max64Sx2, UNDEF_UNKNOWN), }, { DEFOP(Iop_Max8Ux16, UNDEF_UNKNOWN), }, { DEFOP(Iop_Max16Ux8, UNDEF_UNKNOWN), }, { DEFOP(Iop_Max32Ux4, UNDEF_UNKNOWN), }, { DEFOP(Iop_Max64Ux2, UNDEF_UNKNOWN), }, { DEFOP(Iop_Min8Sx16, UNDEF_UNKNOWN), }, { DEFOP(Iop_Min16Sx8, UNDEF_UNKNOWN), }, { DEFOP(Iop_Min32Sx4, UNDEF_UNKNOWN), }, { DEFOP(Iop_Min64Sx2, UNDEF_UNKNOWN), }, { DEFOP(Iop_Min8Ux16, UNDEF_UNKNOWN), }, { DEFOP(Iop_Min16Ux8, UNDEF_UNKNOWN), }, { DEFOP(Iop_Min32Ux4, UNDEF_UNKNOWN), }, { DEFOP(Iop_Min64Ux2, UNDEF_UNKNOWN), }, { DEFOP(Iop_CmpEQ8x16, UNDEF_UNKNOWN), }, { DEFOP(Iop_CmpEQ16x8, UNDEF_UNKNOWN), }, { DEFOP(Iop_CmpEQ32x4, UNDEF_UNKNOWN), }, { DEFOP(Iop_CmpEQ64x2, UNDEF_UNKNOWN), }, { DEFOP(Iop_CmpGT8Sx16, UNDEF_UNKNOWN), }, { DEFOP(Iop_CmpGT16Sx8, UNDEF_UNKNOWN), }, { DEFOP(Iop_CmpGT32Sx4, UNDEF_UNKNOWN), }, { DEFOP(Iop_CmpGT64Sx2, UNDEF_UNKNOWN), }, { DEFOP(Iop_CmpGT8Ux16, UNDEF_UNKNOWN), }, { DEFOP(Iop_CmpGT16Ux8, UNDEF_UNKNOWN), }, { DEFOP(Iop_CmpGT32Ux4, UNDEF_UNKNOWN), }, { DEFOP(Iop_CmpGT64Ux2, UNDEF_UNKNOWN), }, { DEFOP(Iop_Cnt8x16, UNDEF_UNKNOWN), }, { DEFOP(Iop_Clz8x16, UNDEF_UNKNOWN), }, { DEFOP(Iop_Clz16x8, UNDEF_UNKNOWN), }, { DEFOP(Iop_Clz32x4, UNDEF_UNKNOWN), }, { DEFOP(Iop_Clz64x2, UNDEF_UNKNOWN), }, { DEFOP(Iop_Cls8x16, UNDEF_UNKNOWN), }, { DEFOP(Iop_Cls16x8, UNDEF_UNKNOWN), }, { DEFOP(Iop_Cls32x4, UNDEF_UNKNOWN), }, { DEFOP(Iop_ShlN8x16, UNDEF_UNKNOWN), }, { DEFOP(Iop_ShlN16x8, UNDEF_UNKNOWN), }, { DEFOP(Iop_ShlN32x4, UNDEF_UNKNOWN), }, { DEFOP(Iop_ShlN64x2, UNDEF_UNKNOWN), }, { DEFOP(Iop_ShrN8x16, UNDEF_UNKNOWN), }, { DEFOP(Iop_ShrN16x8, UNDEF_UNKNOWN), }, { DEFOP(Iop_ShrN32x4, UNDEF_UNKNOWN), }, { DEFOP(Iop_ShrN64x2, UNDEF_UNKNOWN), }, { DEFOP(Iop_SarN8x16, UNDEF_UNKNOWN), }, { DEFOP(Iop_SarN16x8, UNDEF_UNKNOWN), }, { DEFOP(Iop_SarN32x4, UNDEF_UNKNOWN), }, { DEFOP(Iop_SarN64x2, UNDEF_UNKNOWN), }, { DEFOP(Iop_Shl8x16, UNDEF_UNKNOWN), }, { DEFOP(Iop_Shl16x8, UNDEF_UNKNOWN), }, { DEFOP(Iop_Shl32x4, UNDEF_UNKNOWN), }, { DEFOP(Iop_Shl64x2, UNDEF_UNKNOWN), }, { DEFOP(Iop_Shr8x16, UNDEF_UNKNOWN), }, { DEFOP(Iop_Shr16x8, UNDEF_UNKNOWN), }, { DEFOP(Iop_Shr32x4, UNDEF_UNKNOWN), }, { DEFOP(Iop_Shr64x2, UNDEF_UNKNOWN), }, { DEFOP(Iop_Sar8x16, UNDEF_UNKNOWN), }, { DEFOP(Iop_Sar16x8, UNDEF_UNKNOWN), }, { DEFOP(Iop_Sar32x4, UNDEF_UNKNOWN), }, { DEFOP(Iop_Sar64x2, UNDEF_UNKNOWN), }, { DEFOP(Iop_Sal8x16, UNDEF_UNKNOWN), }, { DEFOP(Iop_Sal16x8, UNDEF_UNKNOWN), }, { DEFOP(Iop_Sal32x4, UNDEF_UNKNOWN), }, { DEFOP(Iop_Sal64x2, UNDEF_UNKNOWN), }, { DEFOP(Iop_Rol8x16, UNDEF_UNKNOWN), }, { DEFOP(Iop_Rol16x8, UNDEF_UNKNOWN), }, { DEFOP(Iop_Rol32x4, UNDEF_UNKNOWN), }, { DEFOP(Iop_Rol64x2, UNDEF_UNKNOWN), }, { DEFOP(Iop_QShl8x16, UNDEF_UNKNOWN), }, { DEFOP(Iop_QShl16x8, UNDEF_UNKNOWN), }, { DEFOP(Iop_QShl32x4, UNDEF_UNKNOWN), }, { DEFOP(Iop_QShl64x2, UNDEF_UNKNOWN), }, { DEFOP(Iop_QSal8x16, UNDEF_UNKNOWN), }, { DEFOP(Iop_QSal16x8, UNDEF_UNKNOWN), }, { DEFOP(Iop_QSal32x4, UNDEF_UNKNOWN), }, { DEFOP(Iop_QSal64x2, UNDEF_UNKNOWN), }, { DEFOP(Iop_QShlNsatSU8x16, UNDEF_UNKNOWN), }, { DEFOP(Iop_QShlNsatSU16x8, UNDEF_UNKNOWN), }, { DEFOP(Iop_QShlNsatSU32x4, UNDEF_UNKNOWN), }, { DEFOP(Iop_QShlNsatSU64x2, UNDEF_UNKNOWN), }, { DEFOP(Iop_QShlNsatUU8x16, UNDEF_UNKNOWN), }, { DEFOP(Iop_QShlNsatUU16x8, UNDEF_UNKNOWN), }, { DEFOP(Iop_QShlNsatUU32x4, UNDEF_UNKNOWN), }, { DEFOP(Iop_QShlNsatUU64x2, UNDEF_UNKNOWN), }, { DEFOP(Iop_QShlNsatSS8x16, UNDEF_UNKNOWN), }, { DEFOP(Iop_QShlNsatSS16x8, UNDEF_UNKNOWN), }, { DEFOP(Iop_QShlNsatSS32x4, UNDEF_UNKNOWN), }, { DEFOP(Iop_QShlNsatSS64x2, UNDEF_UNKNOWN), }, { DEFOP(Iop_QandUQsh8x16, UNDEF_UNKNOWN), }, { DEFOP(Iop_QandUQsh16x8, UNDEF_UNKNOWN), }, { DEFOP(Iop_QandUQsh32x4, UNDEF_UNKNOWN), }, { DEFOP(Iop_QandUQsh64x2, UNDEF_UNKNOWN), }, { DEFOP(Iop_QandSQsh8x16, UNDEF_UNKNOWN), }, { DEFOP(Iop_QandSQsh16x8, UNDEF_UNKNOWN), }, { DEFOP(Iop_QandSQsh32x4, UNDEF_UNKNOWN), }, { DEFOP(Iop_QandSQsh64x2, UNDEF_UNKNOWN), }, { DEFOP(Iop_QandUQRsh8x16, UNDEF_UNKNOWN), }, { DEFOP(Iop_QandUQRsh16x8, UNDEF_UNKNOWN), }, { DEFOP(Iop_QandUQRsh32x4, UNDEF_UNKNOWN), }, { DEFOP(Iop_QandUQRsh64x2, UNDEF_UNKNOWN), }, { DEFOP(Iop_QandSQRsh8x16, UNDEF_UNKNOWN), }, { DEFOP(Iop_QandSQRsh16x8, UNDEF_UNKNOWN), }, { DEFOP(Iop_QandSQRsh32x4, UNDEF_UNKNOWN), }, { DEFOP(Iop_QandSQRsh64x2, UNDEF_UNKNOWN), }, { DEFOP(Iop_Sh8Sx16, UNDEF_UNKNOWN), }, { DEFOP(Iop_Sh16Sx8, UNDEF_UNKNOWN), }, { DEFOP(Iop_Sh32Sx4, UNDEF_UNKNOWN), }, { DEFOP(Iop_Sh64Sx2, UNDEF_UNKNOWN), }, { DEFOP(Iop_Sh8Ux16, UNDEF_UNKNOWN), }, { DEFOP(Iop_Sh16Ux8, UNDEF_UNKNOWN), }, { DEFOP(Iop_Sh32Ux4, UNDEF_UNKNOWN), }, { DEFOP(Iop_Sh64Ux2, UNDEF_UNKNOWN), }, { DEFOP(Iop_Rsh8Sx16, UNDEF_UNKNOWN), }, { DEFOP(Iop_Rsh16Sx8, UNDEF_UNKNOWN), }, { DEFOP(Iop_Rsh32Sx4, UNDEF_UNKNOWN), }, { DEFOP(Iop_Rsh64Sx2, UNDEF_UNKNOWN), }, { DEFOP(Iop_Rsh8Ux16, UNDEF_UNKNOWN), }, { DEFOP(Iop_Rsh16Ux8, UNDEF_UNKNOWN), }, { DEFOP(Iop_Rsh32Ux4, UNDEF_UNKNOWN), }, { DEFOP(Iop_Rsh64Ux2, UNDEF_UNKNOWN), }, { DEFOP(<API key>, UNDEF_UNKNOWN), }, { DEFOP(<API key>, UNDEF_UNKNOWN), }, { DEFOP(<API key>, UNDEF_UNKNOWN), }, { DEFOP(<API key>, UNDEF_UNKNOWN), }, { DEFOP(<API key>, UNDEF_UNKNOWN), }, { DEFOP(<API key>, UNDEF_UNKNOWN), }, { DEFOP(<API key>, UNDEF_UNKNOWN), }, { DEFOP(<API key>, UNDEF_UNKNOWN), }, { DEFOP(<API key>, UNDEF_UNKNOWN), }, { DEFOP(<API key>, UNDEF_UNKNOWN), }, { DEFOP(<API key>, UNDEF_UNKNOWN), }, { DEFOP(<API key>, UNDEF_UNKNOWN), }, { DEFOP(<API key>, UNDEF_UNKNOWN), }, { DEFOP(<API key>, UNDEF_UNKNOWN), }, { DEFOP(<API key>, UNDEF_UNKNOWN), }, { DEFOP(<API key>, UNDEF_UNKNOWN), }, { DEFOP(<API key>, UNDEF_UNKNOWN), }, { DEFOP(<API key>, UNDEF_UNKNOWN), }, { DEFOP(<API key>, UNDEF_UNKNOWN), }, { DEFOP(<API key>, UNDEF_UNKNOWN), }, { DEFOP(<API key>, UNDEF_UNKNOWN), }, { DEFOP(<API key>, UNDEF_UNKNOWN), }, { DEFOP(<API key>, UNDEF_UNKNOWN), }, { DEFOP(<API key>, UNDEF_UNKNOWN), }, { DEFOP(<API key>, UNDEF_UNKNOWN), }, { DEFOP(<API key>, UNDEF_UNKNOWN), }, { DEFOP(<API key>, UNDEF_UNKNOWN), }, { DEFOP(Iop_NarrowUn16to8x8, UNDEF_UNKNOWN), }, { DEFOP(<API key>, UNDEF_UNKNOWN), }, { DEFOP(<API key>, UNDEF_UNKNOWN), }, { DEFOP(<API key>, UNDEF_UNKNOWN), }, { DEFOP(<API key>, UNDEF_UNKNOWN), }, { DEFOP(<API key>, UNDEF_UNKNOWN), }, { DEFOP(<API key>, UNDEF_UNKNOWN), }, { DEFOP(<API key>, UNDEF_UNKNOWN), }, { DEFOP(<API key>, UNDEF_UNKNOWN), }, { DEFOP(<API key>, UNDEF_UNKNOWN), }, { DEFOP(<API key>, UNDEF_UNKNOWN), }, { DEFOP(<API key>, UNDEF_UNKNOWN), }, { DEFOP(<API key>, UNDEF_UNKNOWN), }, { DEFOP(<API key>, UNDEF_UNKNOWN), }, { DEFOP(Iop_Widen8Uto16x8, UNDEF_UNKNOWN), }, { DEFOP(Iop_Widen16Uto32x4, UNDEF_UNKNOWN), }, { DEFOP(Iop_Widen32Uto64x2, UNDEF_UNKNOWN), }, { DEFOP(Iop_Widen8Sto16x8, UNDEF_UNKNOWN), }, { DEFOP(Iop_Widen16Sto32x4, UNDEF_UNKNOWN), }, { DEFOP(Iop_Widen32Sto64x2, UNDEF_UNKNOWN), }, { DEFOP(<API key>, UNDEF_UNKNOWN), }, { DEFOP(<API key>, UNDEF_UNKNOWN), }, { DEFOP(<API key>, UNDEF_UNKNOWN), }, { DEFOP(<API key>, UNDEF_UNKNOWN), }, { DEFOP(<API key>, UNDEF_UNKNOWN), }, { DEFOP(<API key>, UNDEF_UNKNOWN), }, { DEFOP(<API key>, UNDEF_UNKNOWN), }, { DEFOP(<API key>, UNDEF_UNKNOWN), }, { DEFOP(<API key>, UNDEF_UNKNOWN), }, { DEFOP(<API key>, UNDEF_UNKNOWN), }, { DEFOP(<API key>, UNDEF_UNKNOWN), }, { DEFOP(<API key>, UNDEF_UNKNOWN), }, { DEFOP(<API key>, UNDEF_UNKNOWN), }, { DEFOP(<API key>, UNDEF_UNKNOWN), }, { DEFOP(Iop_CatOddLanes8x16, UNDEF_UNKNOWN), }, { DEFOP(Iop_CatOddLanes16x8, UNDEF_UNKNOWN), }, { DEFOP(Iop_CatOddLanes32x4, UNDEF_UNKNOWN), }, { DEFOP(<API key>, UNDEF_UNKNOWN), }, { DEFOP(<API key>, UNDEF_UNKNOWN), }, { DEFOP(<API key>, UNDEF_UNKNOWN), }, { DEFOP(Iop_GetElem8x16, UNDEF_UNKNOWN), }, { DEFOP(Iop_GetElem16x8, UNDEF_UNKNOWN), }, { DEFOP(Iop_GetElem32x4, UNDEF_UNKNOWN), }, { DEFOP(Iop_GetElem64x2, UNDEF_UNKNOWN), }, { DEFOP(Iop_Dup8x16, UNDEF_UNKNOWN), }, { DEFOP(Iop_Dup16x8, UNDEF_UNKNOWN), }, { DEFOP(Iop_Dup32x4, UNDEF_UNKNOWN), }, { DEFOP(Iop_SliceV128, UNDEF_UNKNOWN), }, { DEFOP(<API key>, UNDEF_UNKNOWN), }, { DEFOP(<API key>, UNDEF_UNKNOWN), }, { DEFOP(<API key>, UNDEF_UNKNOWN), }, { DEFOP(<API key>, UNDEF_UNKNOWN), }, { DEFOP(<API key>, UNDEF_UNKNOWN), }, { DEFOP(<API key>, UNDEF_UNKNOWN), }, { DEFOP(<API key>, UNDEF_UNKNOWN), }, { DEFOP(Iop_Perm8x16, UNDEF_UNKNOWN), }, { DEFOP(Iop_Perm32x4, UNDEF_UNKNOWN), }, { DEFOP(Iop_GetMSBs8x16, UNDEF_UNKNOWN), }, { DEFOP(Iop_RecipEst32Ux4, UNDEF_UNKNOWN), }, { DEFOP(Iop_RSqrtEst32Ux4, UNDEF_UNKNOWN), }, { DEFOP(Iop_V256to64_0, UNDEF_UNKNOWN), }, { DEFOP(Iop_V256to64_1, UNDEF_UNKNOWN), }, { DEFOP(Iop_V256to64_2, UNDEF_UNKNOWN), }, { DEFOP(Iop_V256to64_3, UNDEF_UNKNOWN), }, { DEFOP(Iop_64x4toV256, UNDEF_UNKNOWN), }, { DEFOP(Iop_V256toV128_0, UNDEF_UNKNOWN), }, { DEFOP(Iop_V256toV128_1, UNDEF_UNKNOWN), }, { DEFOP(Iop_V128HLtoV256, UNDEF_UNKNOWN), }, { DEFOP(Iop_AndV256, UNDEF_UNKNOWN), }, { DEFOP(Iop_OrV256, UNDEF_UNKNOWN), }, { DEFOP(Iop_XorV256, UNDEF_UNKNOWN), }, { DEFOP(Iop_NotV256, UNDEF_UNKNOWN), }, { DEFOP(Iop_CmpNEZ8x32, UNDEF_UNKNOWN), }, { DEFOP(Iop_CmpNEZ16x16, UNDEF_UNKNOWN), }, { DEFOP(Iop_CmpNEZ32x8, UNDEF_UNKNOWN), }, { DEFOP(Iop_CmpNEZ64x4, UNDEF_UNKNOWN), }, { DEFOP(Iop_Add8x32, UNDEF_UNKNOWN), }, { DEFOP(Iop_Add16x16, UNDEF_UNKNOWN), }, { DEFOP(Iop_Add32x8, UNDEF_UNKNOWN), }, { DEFOP(Iop_Add64x4, UNDEF_UNKNOWN), }, { DEFOP(Iop_Sub8x32, UNDEF_UNKNOWN), }, { DEFOP(Iop_Sub16x16, UNDEF_UNKNOWN), }, { DEFOP(Iop_Sub32x8, UNDEF_UNKNOWN), }, { DEFOP(Iop_Sub64x4, UNDEF_UNKNOWN), }, { DEFOP(Iop_CmpEQ8x32, UNDEF_UNKNOWN), }, { DEFOP(Iop_CmpEQ16x16, UNDEF_UNKNOWN), }, { DEFOP(Iop_CmpEQ32x8, UNDEF_UNKNOWN), }, { DEFOP(Iop_CmpEQ64x4, UNDEF_UNKNOWN), }, { DEFOP(Iop_CmpGT8Sx32, UNDEF_UNKNOWN), }, { DEFOP(Iop_CmpGT16Sx16, UNDEF_UNKNOWN), }, { DEFOP(Iop_CmpGT32Sx8, UNDEF_UNKNOWN), }, { DEFOP(Iop_CmpGT64Sx4, UNDEF_UNKNOWN), }, { DEFOP(Iop_ShlN16x16, UNDEF_UNKNOWN), }, { DEFOP(Iop_ShlN32x8, UNDEF_UNKNOWN), }, { DEFOP(Iop_ShlN64x4, UNDEF_UNKNOWN), }, { DEFOP(Iop_ShrN16x16, UNDEF_UNKNOWN), }, { DEFOP(Iop_ShrN32x8, UNDEF_UNKNOWN), }, { DEFOP(Iop_ShrN64x4, UNDEF_UNKNOWN), }, { DEFOP(Iop_SarN16x16, UNDEF_UNKNOWN), }, { DEFOP(Iop_SarN32x8, UNDEF_UNKNOWN), }, { DEFOP(Iop_Max8Sx32, UNDEF_UNKNOWN), }, { DEFOP(Iop_Max16Sx16, UNDEF_UNKNOWN), }, { DEFOP(Iop_Max32Sx8, UNDEF_UNKNOWN), }, { DEFOP(Iop_Max8Ux32, UNDEF_UNKNOWN), }, { DEFOP(Iop_Max16Ux16, UNDEF_UNKNOWN), }, { DEFOP(Iop_Max32Ux8, UNDEF_UNKNOWN), }, { DEFOP(Iop_Min8Sx32, UNDEF_UNKNOWN), }, { DEFOP(Iop_Min16Sx16, UNDEF_UNKNOWN), }, { DEFOP(Iop_Min32Sx8, UNDEF_UNKNOWN), }, { DEFOP(Iop_Min8Ux32, UNDEF_UNKNOWN), }, { DEFOP(Iop_Min16Ux16, UNDEF_UNKNOWN), }, { DEFOP(Iop_Min32Ux8, UNDEF_UNKNOWN), }, { DEFOP(Iop_Mul16x16, UNDEF_UNKNOWN), }, { DEFOP(Iop_Mul32x8, UNDEF_UNKNOWN), }, { DEFOP(Iop_MulHi16Ux16, UNDEF_UNKNOWN), }, { DEFOP(Iop_MulHi16Sx16, UNDEF_UNKNOWN), }, { DEFOP(Iop_QAdd8Ux32, UNDEF_UNKNOWN), }, { DEFOP(Iop_QAdd16Ux16, UNDEF_UNKNOWN), }, { DEFOP(Iop_QAdd8Sx32, UNDEF_UNKNOWN), }, { DEFOP(Iop_QAdd16Sx16, UNDEF_UNKNOWN), }, { DEFOP(Iop_QSub8Ux32, UNDEF_UNKNOWN), }, { DEFOP(Iop_QSub16Ux16, UNDEF_UNKNOWN), }, { DEFOP(Iop_QSub8Sx32, UNDEF_UNKNOWN), }, { DEFOP(Iop_QSub16Sx16, UNDEF_UNKNOWN), }, { DEFOP(Iop_Avg8Ux32, UNDEF_UNKNOWN), }, { DEFOP(Iop_Avg16Ux16, UNDEF_UNKNOWN), }, { DEFOP(Iop_Perm32x8, UNDEF_UNKNOWN), }, { DEFOP(Iop_Add64Fx4, UNDEF_UNKNOWN), }, { DEFOP(Iop_Sub64Fx4, UNDEF_UNKNOWN), }, { DEFOP(Iop_Mul64Fx4, UNDEF_UNKNOWN), }, { DEFOP(Iop_Div64Fx4, UNDEF_UNKNOWN), }, { DEFOP(Iop_Add32Fx8, UNDEF_UNKNOWN), }, { DEFOP(Iop_Sub32Fx8, UNDEF_UNKNOWN), }, { DEFOP(Iop_Mul32Fx8, UNDEF_UNKNOWN), }, { DEFOP(Iop_Div32Fx8, UNDEF_UNKNOWN), }, { DEFOP(Iop_Sqrt32Fx8, UNDEF_UNKNOWN), }, { DEFOP(Iop_Sqrt64Fx4, UNDEF_UNKNOWN), }, { DEFOP(Iop_RSqrtEst32Fx8, UNDEF_UNKNOWN), }, { DEFOP(Iop_RecipEst32Fx8, UNDEF_UNKNOWN), }, { DEFOP(Iop_Max32Fx8, UNDEF_UNKNOWN), }, { DEFOP(Iop_Min32Fx8, UNDEF_UNKNOWN), }, { DEFOP(Iop_Max64Fx4, UNDEF_UNKNOWN), }, { DEFOP(Iop_Min64Fx4, UNDEF_UNKNOWN), }, { DEFOP(Iop_BCDAdd, UNDEF_UNKNOWN), }, { DEFOP(Iop_BCDSub, UNDEF_UNKNOWN), }, { DEFOP(<API key>, UNDEF_UNKNOWN), }, { DEFOP(<API key>, UNDEF_UNKNOWN), }, { DEFOP(<API key>, UNDEF_UNKNOWN), }, { DEFOP(<API key>, UNDEF_UNKNOWN), }, { DEFOP(Iop_CipherV128, UNDEF_UNKNOWN), }, { DEFOP(Iop_CipherLV128, UNDEF_UNKNOWN), }, { DEFOP(Iop_CipherSV128, UNDEF_UNKNOWN), }, { DEFOP(Iop_NCipherV128, UNDEF_UNKNOWN), }, { DEFOP(Iop_NCipherLV128, UNDEF_UNKNOWN), }, { DEFOP(Iop_SHA512, UNDEF_UNKNOWN), }, { DEFOP(Iop_SHA256, UNDEF_UNKNOWN), }, { DEFOP(<API key>, UNDEF_UNKNOWN), }, }; /* Return a descriptor for OP, iff it exists and it is implemented for the current architecture. */ irop_t * get_irop(IROp op) { unsigned i; for (i = 0; i < sizeof irops / sizeof *irops; ++i) { irop_t *p = irops + i; if (p->op == op) { #ifdef __s390x__ #define S390X_FEATURES "../../../tests/s390x_features" switch (op) { case Iop_I32StoD64: // CDFTR case Iop_I32StoD128: // CXFTR case Iop_I32UtoD64: // CDLFTR case Iop_I32UtoD128: // CXLFTR case Iop_I64UtoD64: // CDLGTR case Iop_I64UtoD128: // CXLGTR case Iop_D64toI32S: // CFDTR case Iop_D128toI32S: // CFXTR case Iop_D64toI64U: // CLGDTR case Iop_D64toI32U: // CLFDTR case Iop_D128toI64U: // CLGXTR case Iop_D128toI32U: // CLFXTR case Iop_I32UtoF32: case Iop_I32UtoF64: case Iop_I32UtoF128: case Iop_I64UtoF32: case Iop_I64UtoF64: case Iop_I64UtoF128: case Iop_F32toI32U: case Iop_F32toI64U: case Iop_F64toI32U: case Iop_F64toI64U: case Iop_F128toI32U: case Iop_F128toI64U: { int rc; /* These IROps require the floating point extension facility */ rc = system(S390X_FEATURES " s390x-fpext"); // s390x_features returns 1 if feature does not exist rc /= 256; if (rc != 0) return NULL; } /* PFPO Iops */ case Iop_F32toD32: case Iop_F32toD64: case Iop_F32toD128: case Iop_F64toD32: case Iop_F64toD64: case Iop_F64toD128: case Iop_F128toD32: case Iop_F128toD64: case Iop_F128toD128: case Iop_D32toF32: case Iop_D32toF64: case Iop_D32toF128: case Iop_D64toF32: case Iop_D64toF64: case Iop_D64toF128: case Iop_D128toF32: case Iop_D128toF64: case Iop_D128toF128: { int rc; /* These IROps require the Perform Floating Point Operation facility */ rc = system(S390X_FEATURES " s390x-pfpo"); // s390x_features returns 1 if feature does not exist rc /= 256; if (rc != 0) return NULL; } } return p->s390x ? p : NULL; #endif #ifdef __x86_64__ return p->amd64 ? p : NULL; #endif #ifdef __powerpc__ #ifdef __powerpc64__ return p->ppc64 ? p : NULL; #else return p->ppc32 ? p : NULL; #endif #endif #ifdef __mips__ #if (__mips==64) return p->mips64 ? p : NULL; #else return p->mips32 ? p : NULL; #endif #endif #ifdef __arm__ return p->arm ? p : NULL; #endif #ifdef __i386__ return p->x86 ? p : NULL; #endif return NULL; } } fprintf(stderr, "unknown opcode %d\n", op); exit(1); }
<?php namespace VuFindTest\Query; use VuFindSearch\Query\Query; use VuFindSearch\Query\QueryGroup; use <API key>; class QueryGroupTest extends <API key> { /** * Test containsTerm() method * * @return void */ public function testContainsTerm() { $q = $this->getSampleQueryGroup(); // Should report true for actual contained terms: $this->assertTrue($q->containsTerm('test')); $this->assertTrue($q->containsTerm('word')); $this->assertTrue($q->containsTerm('query')); // Should not contain a non-present term: $this->assertFalse($q->containsTerm('garbage')); // Should not contain a partial term (matches on word boundaries): $this->assertFalse($q->containsTerm('tes')); } /** * Test getAllTerms() method * * @return void */ public function testGetAllTerms() { $q = $this->getSampleQueryGroup(); $this->assertEquals('test query multi word query', $q->getAllTerms()); } /** * Test replaceTerm() method * * @return void */ public function testReplaceTerm() { $q = $this->getSampleQueryGroup(); $q->replaceTerm('query', 'question'); $this->assertEquals('test question multi word question', $q->getAllTerms()); } /** * Test QueryGroup cloning. * * @return void */ public function testClone() { $q = $this->getSampleQueryGroup(); $qClone = clone($q); $q->replaceTerm('query', 'question'); $qClone->setOperator('AND'); $this->assertEquals('test question multi word question', $q->getAllTerms()); $this->assertEquals('OR', $q->getOperator()); $this->assertEquals('test query multi word query', $qClone->getAllTerms()); $this->assertEquals('AND', $qClone->getOperator()); } /** * Test setting/clearing of reduced handler. * * @return void */ public function testReducedHandler() { $q = $this->getSampleQueryGroup(); $q->setReducedHandler('foo'); $this->assertEquals('foo', $q->getReducedHandler()); $q->unsetReducedHandler(); $this->assertEquals(null, $q->getReducedHandler()); } /** * Test setting an invalid operator. * * @return void * * @expectedException VuFindSearch\Exception\<API key> * @<API key> Unknown or invalid boolean operator: fizz */ public function testIllegalOperator() { $q = $this->getSampleQueryGroup(); $q->setOperator('fizz'); } /** * Get a test object. * * @return QueryGroup */ protected function getSampleQueryGroup() { $q1 = new Query('test'); $q2 = new Query('query'); $q3 = new Query('multi word query'); return new QueryGroup('OR', [$q1, $q2, $q3]); } }
var <API key> = [ [ "Add", "<API key>.html#<API key>", null ], [ "AddOrEdit", "<API key>.html#<API key>", null ], [ "BulkImport", "<API key>.html#<API key>", null ], [ "Count", "<API key>.html#<API key>", null ], [ "CountFiltered", "<API key>.html#<API key>", null ], [ "CountWhere", "<API key>.html#<API key>", null ], [ "Delete", "<API key>.html#<API key>", null ], [ "Get", "<API key>.html#<API key>", null ], [ "Get", "<API key>.html#<API key>", null ], [ "Get", "<API key>.html#<API key>", null ], [ "GetCustomFields", "<API key>.html#<API key>", null ], [ "GetDisplayFields", "<API key>.html#<API key>", null ], [ "GetFiltered", "<API key>.html#<API key>", null ], [ "GetPagedResult", "<API key>.html#<API key>", null ], [ "GetPagedResult", "<API key>.html#<API key>", null ], [ "GetWhere", "<API key>.html#<API key>", null ], [ "Update", "<API key>.html#<API key>", null ], [ "ObjectName", "<API key>.html#<API key>", null ], [ "ObjectNamespace", "<API key>.html#<API key>", null ], [ "Catalog", "<API key>.html#<API key>", null ], [ "LoginId", "<API key>.html#<API key>", null ], [ "UserId", "<API key>.html#<API key>", null ] ];
#include "<API key>.h" #include "<API key>.h" @cond PRIVATE QString <API key>::name() const { return QStringLiteral( "joinattributestable" ); } QString <API key>::displayName() const { return QObject::tr( "Join attributes by field value" ); } QStringList <API key>::tags() const { return QObject::tr( "join,connect,attributes,values,fields,tables" ).split( ',' ); } QString <API key>::group() const { return QObject::tr( "Vector general" ); } QString <API key>::groupId() const { return QStringLiteral( "vectorgeneral" ); } void <API key>::initAlgorithm( const QVariantMap & ) { QStringList methods; methods << QObject::tr( "Create separate feature for each matching feature (one-to-many)" ) << QObject::tr( "Take attributes of the first matching feature only (one-to-one)" ); addParameter( new <API key>( QStringLiteral( "INPUT" ), QObject::tr( "Input layer" ), QList< int>() << QgsProcessing::TypeVector ) ); addParameter( new <API key>( QStringLiteral( "FIELD" ), QObject::tr( "Table field" ), QVariant(), QStringLiteral( "INPUT" ) ) ); addParameter( new <API key>( QStringLiteral( "INPUT_2" ), QObject::tr( "Input layer 2" ), QList< int>() << QgsProcessing::TypeVector ) ); addParameter( new <API key>( QStringLiteral( "FIELD_2" ), QObject::tr( "Table field 2" ), QVariant(), QStringLiteral( "INPUT_2" ) ) ); addParameter( new <API key>( QStringLiteral( "FIELDS_TO_COPY" ), QObject::tr( "Layer 2 fields to copy (leave empty to copy all fields)" ), QVariant(), QStringLiteral( "INPUT_2" ), <API key>::Any, true, true ) ); addParameter( new <API key>( QStringLiteral( "METHOD" ), QObject::tr( "Join type" ), methods, false, 1 ) ); addParameter( new <API key>( QStringLiteral( "DISCARD_NONMATCHING" ), QObject::tr( "Discard records which could not be joined" ), false ) ); addParameter( new <API key>( QStringLiteral( "PREFIX" ), QObject::tr( "Joined field prefix" ), QVariant(), false, true ) ); addParameter( new <API key>( QStringLiteral( "OUTPUT" ), QObject::tr( "Joined layer" ), QgsProcessing::<API key>, QVariant(), true, true ) ); std::unique_ptr< <API key> > nonMatchingSink = std::make_unique< <API key> >( QStringLiteral( "NON_MATCHING" ), QObject::tr( "Unjoinable features from first layer" ), QgsProcessing::<API key>, QVariant(), true, false ); // TODO GUI doesn't support advanced outputs yet //nonMatchingSink->setFlags(nonMatchingSink->flags() | <API key>::FlagAdvanced ); addParameter( nonMatchingSink.release() ); addOutput( new <API key>( QStringLiteral( "JOINED_COUNT" ), QObject::tr( "Number of joined features from input table" ) ) ); addOutput( new <API key>( QStringLiteral( "UNJOINABLE_COUNT" ), QObject::tr( "Number of unjoinable features from input table" ) ) ); } QString <API key>::shortHelpString() const { return QObject::tr( "This algorithm takes an input vector layer and creates a new vector layer that is an extended version of the " "input one, with additional attributes in its attribute table.\n\n" "The additional attributes and their values are taken from a second vector layer. An attribute is selected " "in each of them to define the join criteria." ); } <API key> *<API key>::createInstance() const { return new <API key>(); } QVariantMap <API key>::processAlgorithm( const QVariantMap &parameters, <API key> &context, <API key> *feedback ) { const int joinMethod = parameterAsEnum( parameters, QStringLiteral( "METHOD" ), context ); const bool discardNonMatching = parameterAsBoolean( parameters, QStringLiteral( "DISCARD_NONMATCHING" ), context ); std::unique_ptr< <API key> > input( parameterAsSource( parameters, QStringLiteral( "INPUT" ), context ) ); if ( !input ) throw <API key>( invalidSourceError( parameters, QStringLiteral( "INPUT" ) ) ); std::unique_ptr< <API key> > input2( parameterAsSource( parameters, QStringLiteral( "INPUT_2" ), context ) ); if ( !input2 ) throw <API key>( invalidSourceError( parameters, QStringLiteral( "INPUT_2" ) ) ); const QString prefix = parameterAsString( parameters, QStringLiteral( "PREFIX" ), context ); const QString field1Name = parameterAsString( parameters, QStringLiteral( "FIELD" ), context ); const QString field2Name = parameterAsString( parameters, QStringLiteral( "FIELD_2" ), context ); const QStringList fieldsToCopy = parameterAsFields( parameters, QStringLiteral( "FIELDS_TO_COPY" ), context ); const int joinField1Index = input->fields().lookupField( field1Name ); const int joinField2Index = input2->fields().lookupField( field2Name ); if ( joinField1Index < 0 || joinField2Index < 0 ) throw <API key>( QObject::tr( "Invalid join fields" ) ); QgsFields outFields2; QgsAttributeList fields2Indices; if ( fieldsToCopy.empty() ) { outFields2 = input2->fields(); fields2Indices.reserve( outFields2.count() ); for ( int i = 0; i < outFields2.count(); ++i ) { fields2Indices << i; } } else { fields2Indices.reserve( fieldsToCopy.count() ); for ( const QString &field : fieldsToCopy ) { const int index = input2->fields().lookupField( field ); if ( index >= 0 ) { fields2Indices << index; outFields2.append( input2->fields().at( index ) ); } } } if ( !prefix.isEmpty() ) { for ( int i = 0; i < outFields2.count(); ++i ) { outFields2.rename( i, prefix + outFields2[ i ].name() ); } } QgsAttributeList fields2Fetch = fields2Indices; fields2Fetch << joinField2Index; const QgsFields outFields = QgsProcessingUtils::combineFields( input->fields(), outFields2 ); QString dest; std::unique_ptr< QgsFeatureSink > sink( parameterAsSink( parameters, QStringLiteral( "OUTPUT" ), context, dest, outFields, input->wkbType(), input->sourceCrs(), QgsFeatureSink::<API key> ) ); if ( parameters.value( QStringLiteral( "OUTPUT" ) ).isValid() && !sink ) throw <API key>( invalidSinkError( parameters, QStringLiteral( "OUTPUT" ) ) ); QString destNonMatching1; std::unique_ptr< QgsFeatureSink > sinkNonMatching1( parameterAsSink( parameters, QStringLiteral( "NON_MATCHING" ), context, destNonMatching1, input->fields(), input->wkbType(), input->sourceCrs(), QgsFeatureSink::<API key> ) ); if ( parameters.value( QStringLiteral( "NON_MATCHING" ) ).isValid() && !sinkNonMatching1 ) throw <API key>( invalidSinkError( parameters, QStringLiteral( "NON_MATCHING" ) ) ); // cache attributes of input2 QMultiHash< QVariant, QgsAttributes > <API key>; QgsFeatureIterator features = input2->getFeatures( QgsFeatureRequest().setFlags( QgsFeatureRequest::NoGeometry ).<API key>( fields2Fetch ), <API key>::<API key> ); double step = input2->featureCount() > 0 ? 50.0 / input2->featureCount() : 1; int i = 0; QgsFeature feat; while ( features.nextFeature( feat ) ) { i++; if ( feedback->isCanceled() ) { break; } feedback->setProgress( i * step ); if ( joinMethod == 1 && <API key>.contains( feat.attribute( joinField2Index ) ) ) continue; // only keep selected attributes QgsAttributes attributes; for ( int j = 0; j < feat.attributes().count(); ++j ) { if ( ! fields2Indices.contains( j ) ) continue; attributes << feat.attribute( j ); } <API key>.insert( feat.attribute( joinField2Index ), attributes ); } // Create output vector layer with additional attribute step = input->featureCount() > 0 ? 50.0 / input->featureCount() : 1; features = input->getFeatures( QgsFeatureRequest(), <API key>::<API key> ); i = 0; long long joinedCount = 0; long long unjoinedCount = 0; while ( features.nextFeature( feat ) ) { i++; if ( feedback->isCanceled() ) { break; } feedback->setProgress( 50 + i * step ); if ( <API key>.count( feat.attribute( joinField1Index ) ) > 0 ) { joinedCount++; if ( sink ) { const QgsAttributes attrs = feat.attributes(); QList< QgsAttributes > attributes = <API key>.values( feat.attribute( joinField1Index ) ); QList< QgsAttributes >::iterator attrsIt = attributes.begin(); for ( ; attrsIt != attributes.end(); ++attrsIt ) { QgsAttributes newAttrs = attrs; newAttrs.append( *attrsIt ); feat.setAttributes( newAttrs ); if ( !sink->addFeature( feat, QgsFeatureSink::FastInsert ) ) throw <API key>( writeFeatureError( sink.get(), parameters, QStringLiteral( "OUTPUT" ) ) ); } } } else { // no matching for input feature if ( sink && !discardNonMatching ) { if ( !sink->addFeature( feat, QgsFeatureSink::FastInsert ) ) throw <API key>( writeFeatureError( sink.get(), parameters, QStringLiteral( "OUTPUT" ) ) ); } if ( sinkNonMatching1 ) { if ( !sinkNonMatching1->addFeature( feat, QgsFeatureSink::FastInsert ) ) throw <API key>( writeFeatureError( sinkNonMatching1.get(), parameters, QStringLiteral( "NON_MATCHING" ) ) ); } unjoinedCount++; } } feedback->pushInfo( QObject::tr( "%1 feature(s) from input layer were successfully matched" ).arg( joinedCount ) ); if ( unjoinedCount > 0 ) feedback->reportError( QObject::tr( "%1 feature(s) from input layer could not be matched" ).arg( unjoinedCount ) ); QVariantMap outputs; if ( sink ) outputs.insert( QStringLiteral( "OUTPUT" ), dest ); outputs.insert( QStringLiteral( "JOINED_COUNT" ), joinedCount ); outputs.insert( QStringLiteral( "UNJOINABLE_COUNT" ), unjoinedCount ); if ( sinkNonMatching1 ) outputs.insert( QStringLiteral( "NON_MATCHING" ), destNonMatching1 ); return outputs; } @endcond