code
stringlengths 3
1.05M
| repo_name
stringlengths 4
116
| path
stringlengths 3
942
| language
stringclasses 30
values | license
stringclasses 15
values | size
int32 3
1.05M
|
---|---|---|---|---|---|
/*
* Copyright 2014-2016 CyberVision, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kaaproject.kaa.client.common;
import org.apache.avro.Schema;
/**
* Interface for objects whose serialization depends on schema
*
* @author Yaroslav Zeygerman
*
*/
public interface SchemaDependent {
/**
* @return schema object
* @see org.apache.avro.Schema
*/
Schema getSchema();
}
| forGGe/kaa | client/client-multi/client-java-core/src/main/java/org/kaaproject/kaa/client/common/SchemaDependent.java | Java | apache-2.0 | 932 |
/* Copyright 2015 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
@TIMEOUT=20
*/
var assert = require('assert');
var http = require('http');
var responseCheck = '';
var connectionEvent = 0;
var serverCloseEvent = 0;
var requestEvent = 0;
var responseEvent = 0;
var socketEvent = 0;
// server side code
// server will return the received msg from client
// and shutdown
var server = http.createServer(function (req, res) {
var body = '';
var url = req.url;
req.on('data', function (chunk) {
body += chunk;
});
var endHandler = function () {
res.writeHead(200, { 'Connection' : 'close',
'Content-Length' : body.length
});
res.write(body);
res.end(function(){
if(body == 'close server') {
server.close();
}
});
};
req.on('end', endHandler);
});
server.on('request', function() {
requestEvent++;
});
server.on('connection', function() {
connectionEvent++;
});
server.on('close', function() {
serverCloseEvent++;
});
server.listen(3001, 3);
// client side code
// 1. send POST req to server and check response msg
// 2. send GET req to server and check response msg
// 3. send 'close server' msg
// 1. POST req
var msg = 'http request test msg';
var options = {
method : 'POST',
port : 3001,
headers : {'Content-Length': msg.length}
};
var postResponseHandler = function (res) {
var res_body = '';
assert.equal(200, res.statusCode);
var endHandler = function(){
assert.equal(msg, res_body);
responseCheck += '1';
};
res.on('end', endHandler);
res.on('data', function(chunk){
res_body += chunk.toString();
});
};
var req = http.request(options, postResponseHandler);
req.on('response', function() {
responseEvent++;
});
req.on('socket', function() {
socketEvent++;
});
req.write(msg);
req.end();
// 2. GET req
options = {
method : 'GET',
port : 3001
};
var getResponseHandler = function (res) {
var res_body = '';
assert.equal(200, res.statusCode);
var endHandler = function(){
// GET msg, no received body
assert.equal('', res_body);
responseCheck += '2';
};
res.on('end', endHandler);
res.on('data', function(chunk){
res_body += chunk.toString();
});
};
var getReq = http.request(options, getResponseHandler);
getReq.on('response', function() {
responseEvent++;
});
getReq.on('socket', function() {
socketEvent++;
});
getReq.end();
// 3. close server req
var finalMsg = 'close server';
var finalOptions = {
method : 'POST',
port : 3001,
headers : {'Content-Length': finalMsg.length}
};
var finalResponseHandler = function (res) {
var res_body = '';
assert.equal(200, res.statusCode);
var endHandler = function(){
assert.equal(finalMsg, res_body);
responseCheck += '3';
};
res.on('end', endHandler);
res.on('data', function(chunk){
res_body += chunk.toString();
});
};
var finalReq = http.request(finalOptions, finalResponseHandler);
finalReq.on('response', function() {
responseEvent++;
});
finalReq.on('socket', function() {
socketEvent++;
});
finalReq.write(finalMsg);
finalReq.end();
process.on('exit', function() {
assert.equal(responseCheck.length, 3);
assert.equal(connectionEvent, 3);
assert.equal(serverCloseEvent, 1);
assert.equal(requestEvent, 3);
assert.equal(responseEvent, 3);
assert.equal(socketEvent, 3);
});
| qdk0901/iotjs-openwrt | test/run_pass/test_httpserver.js | JavaScript | apache-2.0 | 3,937 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.itest.karaf;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.ops4j.pax.exam.junit.PaxExam;
@RunWith(PaxExam.class)
public class CamelYammerTest extends BaseKarafTest {
public static final String COMPONENT = extractName(CamelYammerTest.class);
@Test
public void test() throws Exception {
testComponent(COMPONENT);
}
} | objectiser/camel | tests/camel-itest-karaf/src/test/java/org/apache/camel/itest/karaf/CamelYammerTest.java | Java | apache-2.0 | 1,193 |
create table ACT_GE_PROPERTY (
NAME_ nvarchar(64),
VALUE_ nvarchar(300),
REV_ int,
primary key (NAME_)
);
insert into ACT_GE_PROPERTY
values ('schema.version', '5.21.0.0', 1);
insert into ACT_GE_PROPERTY
values ('schema.history', 'create(5.21.0.0)', 1);
insert into ACT_GE_PROPERTY
values ('next.dbid', '1', 1);
create table ACT_GE_BYTEARRAY (
ID_ nvarchar(64),
REV_ int,
NAME_ nvarchar(255),
DEPLOYMENT_ID_ nvarchar(64),
BYTES_ varbinary(max),
GENERATED_ tinyint,
primary key (ID_)
);
create table ACT_RE_DEPLOYMENT (
ID_ nvarchar(64),
NAME_ nvarchar(255),
CATEGORY_ nvarchar(255),
TENANT_ID_ nvarchar(255) default '',
DEPLOY_TIME_ datetime,
primary key (ID_)
);
create table ACT_RE_MODEL (
ID_ nvarchar(64) not null,
REV_ int,
NAME_ nvarchar(255),
KEY_ nvarchar(255),
CATEGORY_ nvarchar(255),
CREATE_TIME_ datetime,
LAST_UPDATE_TIME_ datetime,
VERSION_ int,
META_INFO_ nvarchar(4000),
DEPLOYMENT_ID_ nvarchar(64),
EDITOR_SOURCE_VALUE_ID_ nvarchar(64),
EDITOR_SOURCE_EXTRA_VALUE_ID_ nvarchar(64),
TENANT_ID_ nvarchar(255) default '',
primary key (ID_)
);
create table ACT_RU_EXECUTION (
ID_ nvarchar(64),
REV_ int,
PROC_INST_ID_ nvarchar(64),
BUSINESS_KEY_ nvarchar(255),
PARENT_ID_ nvarchar(64),
PROC_DEF_ID_ nvarchar(64),
SUPER_EXEC_ nvarchar(64),
ACT_ID_ nvarchar(255),
IS_ACTIVE_ tinyint,
IS_CONCURRENT_ tinyint,
IS_SCOPE_ tinyint,
IS_EVENT_SCOPE_ tinyint,
SUSPENSION_STATE_ tinyint,
CACHED_ENT_STATE_ int,
TENANT_ID_ nvarchar(255) default '',
NAME_ nvarchar(255),
LOCK_TIME_ datetime,
primary key (ID_)
);
create table ACT_RU_JOB (
ID_ nvarchar(64) NOT NULL,
REV_ int,
TYPE_ nvarchar(255) NOT NULL,
LOCK_EXP_TIME_ datetime,
LOCK_OWNER_ nvarchar(255),
EXCLUSIVE_ bit,
EXECUTION_ID_ nvarchar(64),
PROCESS_INSTANCE_ID_ nvarchar(64),
PROC_DEF_ID_ nvarchar(64),
RETRIES_ int,
EXCEPTION_STACK_ID_ nvarchar(64),
EXCEPTION_MSG_ nvarchar(4000),
DUEDATE_ datetime NULL,
REPEAT_ nvarchar(255),
HANDLER_TYPE_ nvarchar(255),
HANDLER_CFG_ nvarchar(4000),
TENANT_ID_ nvarchar(255) default '',
primary key (ID_)
);
create table ACT_RE_PROCDEF (
ID_ nvarchar(64) not null,
REV_ int,
CATEGORY_ nvarchar(255),
NAME_ nvarchar(255),
KEY_ nvarchar(255) not null,
VERSION_ int not null,
DEPLOYMENT_ID_ nvarchar(64),
RESOURCE_NAME_ nvarchar(4000),
DGRM_RESOURCE_NAME_ nvarchar(4000),
DESCRIPTION_ nvarchar(4000),
HAS_START_FORM_KEY_ tinyint,
HAS_GRAPHICAL_NOTATION_ tinyint,
SUSPENSION_STATE_ tinyint,
TENANT_ID_ nvarchar(255) default '',
primary key (ID_)
);
create table ACT_RU_TASK (
ID_ nvarchar(64),
REV_ int,
EXECUTION_ID_ nvarchar(64),
PROC_INST_ID_ nvarchar(64),
PROC_DEF_ID_ nvarchar(64),
NAME_ nvarchar(255),
PARENT_TASK_ID_ nvarchar(64),
DESCRIPTION_ nvarchar(4000),
TASK_DEF_KEY_ nvarchar(255),
OWNER_ nvarchar(255),
ASSIGNEE_ nvarchar(255),
DELEGATION_ nvarchar(64),
PRIORITY_ int,
CREATE_TIME_ datetime,
DUE_DATE_ datetime,
CATEGORY_ nvarchar(255),
SUSPENSION_STATE_ int,
TENANT_ID_ nvarchar(255) default '',
FORM_KEY_ nvarchar(255),
primary key (ID_)
);
create table ACT_RU_IDENTITYLINK (
ID_ nvarchar(64),
REV_ int,
GROUP_ID_ nvarchar(255),
TYPE_ nvarchar(255),
USER_ID_ nvarchar(255),
TASK_ID_ nvarchar(64),
PROC_INST_ID_ nvarchar(64),
PROC_DEF_ID_ nvarchar(64),
primary key (ID_)
);
create table ACT_RU_VARIABLE (
ID_ nvarchar(64) not null,
REV_ int,
TYPE_ nvarchar(255) not null,
NAME_ nvarchar(255) not null,
EXECUTION_ID_ nvarchar(64),
PROC_INST_ID_ nvarchar(64),
TASK_ID_ nvarchar(64),
BYTEARRAY_ID_ nvarchar(64),
DOUBLE_ double precision,
LONG_ numeric(19,0),
TEXT_ nvarchar(4000),
TEXT2_ nvarchar(4000),
primary key (ID_)
);
create table ACT_RU_EVENT_SUBSCR (
ID_ nvarchar(64) not null,
REV_ int,
EVENT_TYPE_ nvarchar(255) not null,
EVENT_NAME_ nvarchar(255),
EXECUTION_ID_ nvarchar(64),
PROC_INST_ID_ nvarchar(64),
ACTIVITY_ID_ nvarchar(64),
CONFIGURATION_ nvarchar(255),
CREATED_ datetime not null,
PROC_DEF_ID_ nvarchar(64),
TENANT_ID_ nvarchar(255) default '',
primary key (ID_)
);
create table ACT_EVT_LOG (
LOG_NR_ numeric(19,0) IDENTITY(1,1),
TYPE_ nvarchar(64),
PROC_DEF_ID_ nvarchar(64),
PROC_INST_ID_ nvarchar(64),
EXECUTION_ID_ nvarchar(64),
TASK_ID_ nvarchar(64),
TIME_STAMP_ datetime not null,
USER_ID_ nvarchar(255),
DATA_ varbinary(max),
LOCK_OWNER_ nvarchar(255),
LOCK_TIME_ datetime null,
IS_PROCESSED_ tinyint default 0,
primary key (LOG_NR_)
);
create table ACT_PROCDEF_INFO (
ID_ nvarchar(64) not null,
PROC_DEF_ID_ nvarchar(64) not null,
REV_ int,
INFO_JSON_ID_ nvarchar(64),
primary key (ID_)
);
create index ACT_IDX_EXEC_BUSKEY on ACT_RU_EXECUTION(BUSINESS_KEY_);
create index ACT_IDX_TASK_CREATE on ACT_RU_TASK(CREATE_TIME_);
create index ACT_IDX_IDENT_LNK_USER on ACT_RU_IDENTITYLINK(USER_ID_);
create index ACT_IDX_IDENT_LNK_GROUP on ACT_RU_IDENTITYLINK(GROUP_ID_);
create index ACT_IDX_EVENT_SUBSCR_CONFIG_ on ACT_RU_EVENT_SUBSCR(CONFIGURATION_);
create index ACT_IDX_VARIABLE_TASK_ID on ACT_RU_VARIABLE(TASK_ID_);
create index ACT_IDX_ATHRZ_PROCEDEF on ACT_RU_IDENTITYLINK(PROC_DEF_ID_);
create index ACT_IDX_EXECUTION_PROC on ACT_RU_EXECUTION(PROC_DEF_ID_);
create index ACT_IDX_EXECUTION_PARENT on ACT_RU_EXECUTION(PARENT_ID_);
create index ACT_IDX_EXECUTION_SUPER on ACT_RU_EXECUTION(SUPER_EXEC_);
create index ACT_IDX_EXECUTION_IDANDREV on ACT_RU_EXECUTION(ID_, REV_);
create index ACT_IDX_VARIABLE_BA on ACT_RU_VARIABLE(BYTEARRAY_ID_);
create index ACT_IDX_VARIABLE_EXEC on ACT_RU_VARIABLE(EXECUTION_ID_);
create index ACT_IDX_VARIABLE_PROCINST on ACT_RU_VARIABLE(PROC_INST_ID_);
create index ACT_IDX_IDENT_LNK_TASK on ACT_RU_IDENTITYLINK(TASK_ID_);
create index ACT_IDX_IDENT_LNK_PROCINST on ACT_RU_IDENTITYLINK(PROC_INST_ID_);
create index ACT_IDX_TASK_EXEC on ACT_RU_TASK(EXECUTION_ID_);
create index ACT_IDX_TASK_PROCINST on ACT_RU_TASK(PROC_INST_ID_);
create index ACT_IDX_EXEC_PROC_INST_ID on ACT_RU_EXECUTION(PROC_INST_ID_);
create index ACT_IDX_TASK_PROC_DEF_ID on ACT_RU_TASK(PROC_DEF_ID_);
create index ACT_IDX_EVENT_SUBSCR_EXEC_ID on ACT_RU_EVENT_SUBSCR(EXECUTION_ID_);
create index ACT_IDX_JOB_EXCEPTION_STACK_ID on ACT_RU_JOB(EXCEPTION_STACK_ID_);
create index ACT_IDX_INFO_PROCDEF on ACT_PROCDEF_INFO(PROC_DEF_ID_);
alter table ACT_GE_BYTEARRAY
add constraint ACT_FK_BYTEARR_DEPL
foreign key (DEPLOYMENT_ID_)
references ACT_RE_DEPLOYMENT (ID_);
alter table ACT_RE_PROCDEF
add constraint ACT_UNIQ_PROCDEF
unique (KEY_,VERSION_, TENANT_ID_);
alter table ACT_RU_EXECUTION
add constraint ACT_FK_EXE_PARENT
foreign key (PARENT_ID_)
references ACT_RU_EXECUTION (ID_);
alter table ACT_RU_EXECUTION
add constraint ACT_FK_EXE_SUPER
foreign key (SUPER_EXEC_)
references ACT_RU_EXECUTION (ID_);
alter table ACT_RU_EXECUTION
add constraint ACT_FK_EXE_PROCDEF
foreign key (PROC_DEF_ID_)
references ACT_RE_PROCDEF (ID_);
alter table ACT_RU_IDENTITYLINK
add constraint ACT_FK_TSKASS_TASK
foreign key (TASK_ID_)
references ACT_RU_TASK (ID_);
alter table ACT_RU_IDENTITYLINK
add constraint ACT_FK_ATHRZ_PROCEDEF
foreign key (PROC_DEF_ID_)
references ACT_RE_PROCDEF (ID_);
alter table ACT_RU_IDENTITYLINK
add constraint ACT_FK_IDL_PROCINST
foreign key (PROC_INST_ID_)
references ACT_RU_EXECUTION (ID_);
alter table ACT_RU_TASK
add constraint ACT_FK_TASK_EXE
foreign key (EXECUTION_ID_)
references ACT_RU_EXECUTION (ID_);
alter table ACT_RU_TASK
add constraint ACT_FK_TASK_PROCINST
foreign key (PROC_INST_ID_)
references ACT_RU_EXECUTION (ID_);
alter table ACT_RU_TASK
add constraint ACT_FK_TASK_PROCDEF
foreign key (PROC_DEF_ID_)
references ACT_RE_PROCDEF (ID_);
alter table ACT_RU_VARIABLE
add constraint ACT_FK_VAR_EXE
foreign key (EXECUTION_ID_)
references ACT_RU_EXECUTION (ID_);
alter table ACT_RU_VARIABLE
add constraint ACT_FK_VAR_PROCINST
foreign key (PROC_INST_ID_)
references ACT_RU_EXECUTION(ID_);
alter table ACT_RU_VARIABLE
add constraint ACT_FK_VAR_BYTEARRAY
foreign key (BYTEARRAY_ID_)
references ACT_GE_BYTEARRAY (ID_);
alter table ACT_RU_JOB
add constraint ACT_FK_JOB_EXCEPTION
foreign key (EXCEPTION_STACK_ID_)
references ACT_GE_BYTEARRAY (ID_);
alter table ACT_RU_EVENT_SUBSCR
add constraint ACT_FK_EVENT_EXEC
foreign key (EXECUTION_ID_)
references ACT_RU_EXECUTION(ID_);
alter table ACT_RE_MODEL
add constraint ACT_FK_MODEL_SOURCE
foreign key (EDITOR_SOURCE_VALUE_ID_)
references ACT_GE_BYTEARRAY (ID_);
alter table ACT_RE_MODEL
add constraint ACT_FK_MODEL_SOURCE_EXTRA
foreign key (EDITOR_SOURCE_EXTRA_VALUE_ID_)
references ACT_GE_BYTEARRAY (ID_);
alter table ACT_RE_MODEL
add constraint ACT_FK_MODEL_DEPLOYMENT
foreign key (DEPLOYMENT_ID_)
references ACT_RE_DEPLOYMENT (ID_);
alter table ACT_PROCDEF_INFO
add constraint ACT_FK_INFO_JSON_BA
foreign key (INFO_JSON_ID_)
references ACT_GE_BYTEARRAY (ID_);
alter table ACT_PROCDEF_INFO
add constraint ACT_FK_INFO_PROCDEF
foreign key (PROC_DEF_ID_)
references ACT_RE_PROCDEF (ID_);
alter table ACT_PROCDEF_INFO
add constraint ACT_UNIQ_INFO_PROCDEF
unique (PROC_DEF_ID_); | Halburt/Hsite | db_2/act/create/activiti.mssql.create.engine.sql | SQL | apache-2.0 | 10,099 |
//===-- NativeProcessDarwin.cpp ---------------------------------*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "NativeProcessDarwin.h"
// C includes
#include <mach/mach_init.h>
#include <mach/mach_traps.h>
#include <sys/ptrace.h>
#include <sys/stat.h>
#include <sys/sysctl.h>
#include <sys/types.h>
// C++ includes
// LLDB includes
#include "lldb/Host/PseudoTerminal.h"
#include "lldb/Target/ProcessLaunchInfo.h"
#include "lldb/Utility/Log.h"
#include "lldb/Utility/State.h"
#include "lldb/Utility/StreamString.h"
#include "CFBundle.h"
#include "CFString.h"
#include "DarwinProcessLauncher.h"
#include "MachException.h"
#include "llvm/Support/FileSystem.h"
using namespace lldb;
using namespace lldb_private;
using namespace lldb_private::process_darwin;
using namespace lldb_private::darwin_process_launcher;
// Hidden Impl
namespace {
struct hack_task_dyld_info {
mach_vm_address_t all_image_info_addr;
mach_vm_size_t all_image_info_size;
};
}
// Public Static Methods
Status NativeProcessProtocol::Launch(
ProcessLaunchInfo &launch_info,
NativeProcessProtocol::NativeDelegate &native_delegate, MainLoop &mainloop,
NativeProcessProtocolSP &native_process_sp) {
Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Status error;
// Verify the working directory is valid if one was specified.
FileSpec working_dir(launch_info.GetWorkingDirectory());
if (working_dir) {
FileInstance::Instance().Resolve(working_dir);
if (!FileSystem::Instance().IsDirectory(working_dir)) {
error.SetErrorStringWithFormat("No such file or directory: %s",
working_dir.GetCString());
return error;
}
}
// Launch the inferior.
int pty_master_fd = -1;
LaunchFlavor launch_flavor = LaunchFlavor::Default;
error = LaunchInferior(launch_info, &pty_master_fd, &launch_flavor);
// Handle launch failure.
if (!error.Success()) {
LLDB_LOGF(log,
"NativeProcessDarwin::%s() failed to launch process: "
"%s",
__FUNCTION__, error.AsCString());
return error;
}
// Handle failure to return a pid.
if (launch_info.GetProcessID() == LLDB_INVALID_PROCESS_ID) {
LLDB_LOGF(log,
"NativeProcessDarwin::%s() launch succeeded but no "
"pid was returned! Aborting.",
__FUNCTION__);
return error;
}
// Create the Darwin native process impl.
std::shared_ptr<NativeProcessDarwin> np_darwin_sp(
new NativeProcessDarwin(launch_info.GetProcessID(), pty_master_fd));
if (!np_darwin_sp->RegisterNativeDelegate(native_delegate)) {
native_process_sp.reset();
error.SetErrorStringWithFormat("failed to register the native delegate");
return error;
}
// Finalize the processing needed to debug the launched process with a
// NativeProcessDarwin instance.
error = np_darwin_sp->FinalizeLaunch(launch_flavor, mainloop);
if (!error.Success()) {
LLDB_LOGF(log,
"NativeProcessDarwin::%s() aborting, failed to finalize"
" the launching of the process: %s",
__FUNCTION__, error.AsCString());
return error;
}
// Return the process and process id to the caller through the launch args.
native_process_sp = np_darwin_sp;
return error;
}
Status NativeProcessProtocol::Attach(
lldb::pid_t pid, NativeProcessProtocol::NativeDelegate &native_delegate,
MainLoop &mainloop, NativeProcessProtocolSP &native_process_sp) {
Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
LLDB_LOGF(log, "NativeProcessDarwin::%s(pid = %" PRIi64 ")", __FUNCTION__,
pid);
// Retrieve the architecture for the running process.
ArchSpec process_arch;
Status error = ResolveProcessArchitecture(pid, process_arch);
if (!error.Success())
return error;
// TODO get attach to return this value.
const int pty_master_fd = -1;
std::shared_ptr<NativeProcessDarwin> native_process_darwin_sp(
new NativeProcessDarwin(pid, pty_master_fd));
if (!native_process_darwin_sp->RegisterNativeDelegate(native_delegate)) {
error.SetErrorStringWithFormat("failed to register the native "
"delegate");
return error;
}
native_process_darwin_sp->AttachToInferior(mainloop, pid, error);
if (!error.Success())
return error;
native_process_sp = native_process_darwin_sp;
return error;
}
// ctor/dtor
NativeProcessDarwin::NativeProcessDarwin(lldb::pid_t pid, int pty_master_fd)
: NativeProcessProtocol(pid), m_task(TASK_NULL), m_did_exec(false),
m_cpu_type(0), m_exception_port(MACH_PORT_NULL), m_exc_port_info(),
m_exception_thread(nullptr), m_exception_messages_mutex(),
m_sent_interrupt_signo(0), m_auto_resume_signo(0), m_thread_list(),
m_thread_actions(), m_waitpid_pipe(), m_waitpid_thread(nullptr),
m_waitpid_reader_handle() {
// TODO add this to the NativeProcessProtocol constructor.
m_terminal_fd = pty_master_fd;
}
NativeProcessDarwin::~NativeProcessDarwin() {}
// Instance methods
Status NativeProcessDarwin::FinalizeLaunch(LaunchFlavor launch_flavor,
MainLoop &main_loop) {
Status error;
Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
error = StartExceptionThread();
if (!error.Success()) {
LLDB_LOGF(log,
"NativeProcessDarwin::%s(): failure starting the "
"mach exception port monitor thread: %s",
__FUNCTION__, error.AsCString());
// Terminate the inferior process. There's nothing meaningful we can do if
// we can't receive signals and exceptions. Since we launched the process,
// it's fair game for us to kill it.
::ptrace(PT_KILL, m_pid, 0, 0);
SetState(eStateExited);
return error;
}
StartSTDIOThread();
if (launch_flavor == LaunchFlavor::PosixSpawn) {
SetState(eStateAttaching);
errno = 0;
int err = ::ptrace(PT_ATTACHEXC, m_pid, 0, 0);
if (err == 0) {
// m_flags |= eMachProcessFlagsAttached;
LLDB_LOGF(log,
"NativeProcessDarwin::%s(): successfully spawned "
"process with pid %" PRIu64,
__FUNCTION__, m_pid);
} else {
error.SetErrorToErrno();
SetState(eStateExited);
LLDB_LOGF(log,
"NativeProcessDarwin::%s(): error: failed to "
"attach to spawned pid %" PRIu64 " (error=%d (%s))",
__FUNCTION__, m_pid, (int)error.GetError(), error.AsCString());
return error;
}
}
LLDB_LOGF(log, "NativeProcessDarwin::%s(): new pid is %" PRIu64 "...",
__FUNCTION__, m_pid);
// Spawn a thread to reap our child inferior process...
error = StartWaitpidThread(main_loop);
if (error.Fail()) {
LLDB_LOGF(log,
"NativeProcessDarwin::%s(): failed to start waitpid() "
"thread: %s",
__FUNCTION__, error.AsCString());
kill(SIGKILL, static_cast<::pid_t>(m_pid));
return error;
}
if (TaskPortForProcessID(error) == TASK_NULL) {
// We failed to get the task for our process ID which is bad. Kill our
// process; otherwise, it will be stopped at the entry point and get
// reparented to someone else and never go away.
LLDB_LOGF(log,
"NativeProcessDarwin::%s(): could not get task port "
"for process, sending SIGKILL and exiting: %s",
__FUNCTION__, error.AsCString());
kill(SIGKILL, static_cast<::pid_t>(m_pid));
return error;
}
// Indicate that we're stopped, as we always launch suspended.
SetState(eStateStopped);
// Success.
return error;
}
Status NativeProcessDarwin::SaveExceptionPortInfo() {
return m_exc_port_info.Save(m_task);
}
bool NativeProcessDarwin::ProcessUsingSpringBoard() const {
// TODO implement flags
// return (m_flags & eMachProcessFlagsUsingSBS) != 0;
return false;
}
bool NativeProcessDarwin::ProcessUsingBackBoard() const {
// TODO implement flags
// return (m_flags & eMachProcessFlagsUsingBKS) != 0;
return false;
}
// Called by the exception thread when an exception has been received from our
// process. The exception message is completely filled and the exception data
// has already been copied.
void NativeProcessDarwin::ExceptionMessageReceived(
const MachException::Message &message) {
Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_VERBOSE));
std::lock_guard<std::recursive_mutex> locker(m_exception_messages_mutex);
if (m_exception_messages.empty()) {
// Suspend the task the moment we receive our first exception message.
SuspendTask();
}
// Use a locker to automatically unlock our mutex in case of exceptions Add
// the exception to our internal exception stack
m_exception_messages.push_back(message);
LLDB_LOGF(log, "NativeProcessDarwin::%s(): new queued message count: %lu",
__FUNCTION__, m_exception_messages.size());
}
void *NativeProcessDarwin::ExceptionThread(void *arg) {
Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_VERBOSE));
if (!arg) {
LLDB_LOGF(log,
"NativeProcessDarwin::%s(): cannot run mach exception "
"thread, mandatory process arg was null",
__FUNCTION__);
return nullptr;
}
return reinterpret_cast<NativeProcessDarwin *>(arg)->DoExceptionThread();
}
void *NativeProcessDarwin::DoExceptionThread() {
Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_VERBOSE));
LLDB_LOGF(log, "NativeProcessDarwin::%s(arg=%p) starting thread...",
__FUNCTION__, this);
pthread_setname_np("exception monitoring thread");
// Ensure we don't get CPU starved.
MaybeRaiseThreadPriority();
// We keep a count of the number of consecutive exceptions received so we
// know to grab all exceptions without a timeout. We do this to get a bunch
// of related exceptions on our exception port so we can process then
// together. When we have multiple threads, we can get an exception per
// thread and they will come in consecutively. The main loop in this thread
// can stop periodically if needed to service things related to this process.
//
// [did we lose some words here?]
//
// flag set in the options, so we will wait forever for an exception on
// 0 our exception port. After we get one exception, we then will use the
// MACH_RCV_TIMEOUT option with a zero timeout to grab all other current
// exceptions for our process. After we have received the last pending
// exception, we will get a timeout which enables us to then notify our main
// thread that we have an exception bundle available. We then wait for the
// main thread to tell this exception thread to start trying to get
// exceptions messages again and we start again with a mach_msg read with
// infinite timeout.
//
// We choose to park a thread on this, rather than polling, because the
// polling is expensive. On devices, we need to minimize overhead caused by
// the process monitor.
uint32_t num_exceptions_received = 0;
Status error;
task_t task = m_task;
mach_msg_timeout_t periodic_timeout = 0;
#if defined(WITH_SPRINGBOARD) && !defined(WITH_BKS)
mach_msg_timeout_t watchdog_elapsed = 0;
mach_msg_timeout_t watchdog_timeout = 60 * 1000;
::pid_t pid = (::pid_t)process->GetID();
CFReleaser<SBSWatchdogAssertionRef> watchdog;
if (process->ProcessUsingSpringBoard()) {
// Request a renewal for every 60 seconds if we attached using SpringBoard.
watchdog.reset(::SBSWatchdogAssertionCreateForPID(nullptr, pid, 60));
LLDB_LOGF(log,
"::SBSWatchdogAssertionCreateForPID(NULL, %4.4x, 60) "
"=> %p",
pid, watchdog.get());
if (watchdog.get()) {
::SBSWatchdogAssertionRenew(watchdog.get());
CFTimeInterval watchdogRenewalInterval =
::SBSWatchdogAssertionGetRenewalInterval(watchdog.get());
LLDB_LOGF(log,
"::SBSWatchdogAssertionGetRenewalInterval(%p) => "
"%g seconds",
watchdog.get(), watchdogRenewalInterval);
if (watchdogRenewalInterval > 0.0) {
watchdog_timeout = (mach_msg_timeout_t)watchdogRenewalInterval * 1000;
if (watchdog_timeout > 3000) {
// Give us a second to renew our timeout.
watchdog_timeout -= 1000;
} else if (watchdog_timeout > 1000) {
// Give us a quarter of a second to renew our timeout.
watchdog_timeout -= 250;
}
}
}
if (periodic_timeout == 0 || periodic_timeout > watchdog_timeout)
periodic_timeout = watchdog_timeout;
}
#endif // #if defined (WITH_SPRINGBOARD) && !defined (WITH_BKS)
#ifdef WITH_BKS
CFReleaser<BKSWatchdogAssertionRef> watchdog;
if (process->ProcessUsingBackBoard()) {
::pid_t pid = process->GetID();
CFAllocatorRef alloc = kCFAllocatorDefault;
watchdog.reset(::BKSWatchdogAssertionCreateForPID(alloc, pid));
}
#endif // #ifdef WITH_BKS
// Do we want to use a weak pointer to the NativeProcessDarwin here, in which
// case we can guarantee we don't whack the process monitor if we race
// between this thread and the main one on shutdown?
while (IsExceptionPortValid()) {
::pthread_testcancel();
MachException::Message exception_message;
if (num_exceptions_received > 0) {
// We don't want a timeout here, just receive as many exceptions as we
// can since we already have one. We want to get all currently available
// exceptions for this task at once.
error = exception_message.Receive(
GetExceptionPort(),
MACH_RCV_MSG | MACH_RCV_INTERRUPT | MACH_RCV_TIMEOUT, 0);
} else if (periodic_timeout > 0) {
// We need to stop periodically in this loop, so try and get a mach
// message with a valid timeout (ms).
error = exception_message.Receive(GetExceptionPort(),
MACH_RCV_MSG | MACH_RCV_INTERRUPT |
MACH_RCV_TIMEOUT,
periodic_timeout);
} else {
// We don't need to parse all current exceptions or stop periodically,
// just wait for an exception forever.
error = exception_message.Receive(GetExceptionPort(),
MACH_RCV_MSG | MACH_RCV_INTERRUPT, 0);
}
if (error.Success()) {
// We successfully received an exception.
if (exception_message.CatchExceptionRaise(task)) {
++num_exceptions_received;
ExceptionMessageReceived(exception_message);
}
} else {
if (error.GetError() == MACH_RCV_INTERRUPTED) {
// We were interrupted.
// If we have no task port we should exit this thread, as it implies
// the inferior went down.
if (!IsExceptionPortValid()) {
LLDB_LOGF(log,
"NativeProcessDarwin::%s(): the inferior "
"exception port is no longer valid, "
"canceling exception thread...",
__FUNCTION__);
// Should we be setting a process state here?
break;
}
// Make sure the inferior task is still valid.
if (IsTaskValid()) {
// Task is still ok.
LLDB_LOGF(log,
"NativeProcessDarwin::%s(): interrupted, but "
"the inferior task iss till valid, "
"continuing...",
__FUNCTION__);
continue;
} else {
// The inferior task is no longer valid. Time to exit as the process
// has gone away.
LLDB_LOGF(log,
"NativeProcessDarwin::%s(): the inferior task "
"has exited, and so will we...",
__FUNCTION__);
// Does this race at all with our waitpid()?
SetState(eStateExited);
break;
}
} else if (error.GetError() == MACH_RCV_TIMED_OUT) {
// We timed out when waiting for exceptions.
if (num_exceptions_received > 0) {
// We were receiving all current exceptions with a timeout of zero.
// It is time to go back to our normal looping mode.
num_exceptions_received = 0;
// Notify our main thread we have a complete exception message bundle
// available. Get the possibly updated task port back from the
// process in case we exec'ed and our task port changed.
task = ExceptionMessageBundleComplete();
// In case we use a timeout value when getting exceptions, make sure
// our task is still valid.
if (IsTaskValid(task)) {
// Task is still ok.
LLDB_LOGF(log,
"NativeProcessDarwin::%s(): got a timeout, "
"continuing...",
__FUNCTION__);
continue;
} else {
// The inferior task is no longer valid. Time to exit as the
// process has gone away.
LLDB_LOGF(log,
"NativeProcessDarwin::%s(): the inferior "
"task has exited, and so will we...",
__FUNCTION__);
// Does this race at all with our waitpid()?
SetState(eStateExited);
break;
}
}
#if defined(WITH_SPRINGBOARD) && !defined(WITH_BKS)
if (watchdog.get()) {
watchdog_elapsed += periodic_timeout;
if (watchdog_elapsed >= watchdog_timeout) {
LLDB_LOGF(log, "SBSWatchdogAssertionRenew(%p)", watchdog.get());
::SBSWatchdogAssertionRenew(watchdog.get());
watchdog_elapsed = 0;
}
}
#endif
} else {
LLDB_LOGF(log,
"NativeProcessDarwin::%s(): continuing after "
"receiving an unexpected error: %u (%s)",
__FUNCTION__, error.GetError(), error.AsCString());
// TODO: notify of error?
}
}
}
#if defined(WITH_SPRINGBOARD) && !defined(WITH_BKS)
if (watchdog.get()) {
// TODO: change SBSWatchdogAssertionRelease to SBSWatchdogAssertionCancel
// when we
// all are up and running on systems that support it. The SBS framework has
// a #define that will forward SBSWatchdogAssertionRelease to
// SBSWatchdogAssertionCancel for now so it should still build either way.
DNBLogThreadedIf(LOG_TASK, "::SBSWatchdogAssertionRelease(%p)",
watchdog.get());
::SBSWatchdogAssertionRelease(watchdog.get());
}
#endif // #if defined (WITH_SPRINGBOARD) && !defined (WITH_BKS)
LLDB_LOGF(log, "NativeProcessDarwin::%s(%p): thread exiting...", __FUNCTION__,
this);
return nullptr;
}
Status NativeProcessDarwin::StartExceptionThread() {
Status error;
Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
LLDB_LOGF(log, "NativeProcessDarwin::%s() called", __FUNCTION__);
// Make sure we've looked up the inferior port.
TaskPortForProcessID(error);
// Ensure the inferior task is valid.
if (!IsTaskValid()) {
error.SetErrorStringWithFormat("cannot start exception thread: "
"task 0x%4.4x is not valid",
m_task);
return error;
}
// Get the mach port for the process monitor.
mach_port_t task_self = mach_task_self();
// Allocate an exception port that we will use to track our child process
auto mach_err = ::mach_port_allocate(task_self, MACH_PORT_RIGHT_RECEIVE,
&m_exception_port);
error.SetError(mach_err, eErrorTypeMachKernel);
if (error.Fail()) {
LLDB_LOGF(log,
"NativeProcessDarwin::%s(): mach_port_allocate("
"task_self=0x%4.4x, MACH_PORT_RIGHT_RECEIVE, "
"&m_exception_port) failed: %u (%s)",
__FUNCTION__, task_self, error.GetError(), error.AsCString());
return error;
}
// Add the ability to send messages on the new exception port
mach_err = ::mach_port_insert_right(
task_self, m_exception_port, m_exception_port, MACH_MSG_TYPE_MAKE_SEND);
error.SetError(mach_err, eErrorTypeMachKernel);
if (error.Fail()) {
LLDB_LOGF(log,
"NativeProcessDarwin::%s(): mach_port_insert_right("
"task_self=0x%4.4x, m_exception_port=0x%4.4x, "
"m_exception_port=0x%4.4x, MACH_MSG_TYPE_MAKE_SEND) "
"failed: %u (%s)",
__FUNCTION__, task_self, m_exception_port, m_exception_port,
error.GetError(), error.AsCString());
return error;
}
// Save the original state of the exception ports for our child process.
error = SaveExceptionPortInfo();
if (error.Fail() || (m_exc_port_info.mask == 0)) {
LLDB_LOGF(log,
"NativeProcessDarwin::%s(): SaveExceptionPortInfo() "
"failed, cannot install exception handler: %s",
__FUNCTION__, error.AsCString());
return error;
}
// Set the ability to get all exceptions on this port.
mach_err = ::task_set_exception_ports(
m_task, m_exc_port_info.mask, m_exception_port,
EXCEPTION_DEFAULT | MACH_EXCEPTION_CODES, THREAD_STATE_NONE);
error.SetError(mach_err, eErrorTypeMachKernel);
if (error.Fail()) {
LLDB_LOGF(log,
"::task_set_exception_ports (task = 0x%4.4x, "
"exception_mask = 0x%8.8x, new_port = 0x%4.4x, "
"behavior = 0x%8.8x, new_flavor = 0x%8.8x) failed: "
"%u (%s)",
m_task, m_exc_port_info.mask, m_exception_port,
(EXCEPTION_DEFAULT | MACH_EXCEPTION_CODES), THREAD_STATE_NONE,
error.GetError(), error.AsCString());
return error;
}
// Create the exception thread.
auto pthread_err =
::pthread_create(&m_exception_thread, nullptr, ExceptionThread, this);
error.SetError(pthread_err, eErrorTypePOSIX);
if (error.Fail()) {
LLDB_LOGF(log,
"NativeProcessDarwin::%s(): failed to create Mach "
"exception-handling thread: %u (%s)",
__FUNCTION__, error.GetError(), error.AsCString());
}
return error;
}
lldb::addr_t
NativeProcessDarwin::GetDYLDAllImageInfosAddress(Status &error) const {
error.Clear();
struct hack_task_dyld_info dyld_info;
mach_msg_type_number_t count = TASK_DYLD_INFO_COUNT;
// Make sure that COUNT isn't bigger than our hacked up struct
// hack_task_dyld_info. If it is, then make COUNT smaller to match.
if (count > (sizeof(struct hack_task_dyld_info) / sizeof(natural_t))) {
count = (sizeof(struct hack_task_dyld_info) / sizeof(natural_t));
}
TaskPortForProcessID(error);
if (error.Fail())
return LLDB_INVALID_ADDRESS;
auto mach_err =
::task_info(m_task, TASK_DYLD_INFO, (task_info_t)&dyld_info, &count);
error.SetError(mach_err, eErrorTypeMachKernel);
if (error.Success()) {
// We now have the address of the all image infos structure.
return dyld_info.all_image_info_addr;
}
// We don't have it.
return LLDB_INVALID_ADDRESS;
}
uint32_t NativeProcessDarwin::GetCPUTypeForLocalProcess(::pid_t pid) {
int mib[CTL_MAXNAME] = {
0,
};
size_t len = CTL_MAXNAME;
if (::sysctlnametomib("sysctl.proc_cputype", mib, &len))
return 0;
mib[len] = pid;
len++;
cpu_type_t cpu;
size_t cpu_len = sizeof(cpu);
if (::sysctl(mib, static_cast<u_int>(len), &cpu, &cpu_len, 0, 0))
cpu = 0;
return cpu;
}
uint32_t NativeProcessDarwin::GetCPUType() const {
if (m_cpu_type == 0 && m_pid != 0)
m_cpu_type = GetCPUTypeForLocalProcess(m_pid);
return m_cpu_type;
}
task_t NativeProcessDarwin::ExceptionMessageBundleComplete() {
// We have a complete bundle of exceptions for our child process.
Status error;
Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_VERBOSE));
std::lock_guard<std::recursive_mutex> locker(m_exception_messages_mutex);
LLDB_LOGF(log,
"NativeProcessDarwin::%s(): processing %lu exception "
"messages.",
__FUNCTION__, m_exception_messages.size());
if (m_exception_messages.empty()) {
// Not particularly useful...
return m_task;
}
bool auto_resume = false;
m_did_exec = false;
// First check for any SIGTRAP and make sure we didn't exec
const task_t task = m_task;
size_t i;
if (m_pid != 0) {
bool received_interrupt = false;
uint32_t num_task_exceptions = 0;
for (i = 0; i < m_exception_messages.size(); ++i) {
if (m_exception_messages[i].state.task_port != task) {
// This is an exception that is not for our inferior, ignore.
continue;
}
// This is an exception for the inferior.
++num_task_exceptions;
const int signo = m_exception_messages[i].state.SoftSignal();
if (signo == SIGTRAP) {
// SIGTRAP could mean that we exec'ed. We need to check the
// dyld all_image_infos.infoArray to see if it is NULL and if so, say
// that we exec'ed.
const addr_t aii_addr = GetDYLDAllImageInfosAddress(error);
if (aii_addr == LLDB_INVALID_ADDRESS)
break;
const addr_t info_array_count_addr = aii_addr + 4;
uint32_t info_array_count = 0;
size_t bytes_read = 0;
Status read_error;
read_error = ReadMemory(info_array_count_addr, // source addr
&info_array_count, // dest addr
4, // byte count
bytes_read); // #bytes read
if (read_error.Success() && (bytes_read == 4)) {
if (info_array_count == 0) {
// We got the all infos address, and there are zero entries. We
// think we exec'd.
m_did_exec = true;
// Force the task port to update itself in case the task port
// changed after exec
const task_t old_task = m_task;
const bool force_update = true;
const task_t new_task = TaskPortForProcessID(error, force_update);
if (old_task != new_task) {
LLDB_LOGF(log,
"exec: inferior task port changed "
"from 0x%4.4x to 0x%4.4x",
old_task, new_task);
}
}
} else {
LLDB_LOGF(log,
"NativeProcessDarwin::%s() warning: "
"failed to read all_image_infos."
"infoArrayCount from 0x%8.8llx",
__FUNCTION__, info_array_count_addr);
}
} else if ((m_sent_interrupt_signo != 0) &&
(signo == m_sent_interrupt_signo)) {
// We just received the interrupt that we sent to ourselves.
received_interrupt = true;
}
}
if (m_did_exec) {
cpu_type_t process_cpu_type = GetCPUTypeForLocalProcess(m_pid);
if (m_cpu_type != process_cpu_type) {
LLDB_LOGF(log,
"NativeProcessDarwin::%s(): arch changed from "
"0x%8.8x to 0x%8.8x",
__FUNCTION__, m_cpu_type, process_cpu_type);
m_cpu_type = process_cpu_type;
// TODO figure out if we need to do something here.
// DNBArchProtocol::SetArchitecture (process_cpu_type);
}
m_thread_list.Clear();
// TODO hook up breakpoints.
// m_breakpoints.DisableAll();
}
if (m_sent_interrupt_signo != 0) {
if (received_interrupt) {
LLDB_LOGF(log,
"NativeProcessDarwin::%s(): process "
"successfully interrupted with signal %i",
__FUNCTION__, m_sent_interrupt_signo);
// Mark that we received the interrupt signal
m_sent_interrupt_signo = 0;
// Now check if we had a case where:
// 1 - We called NativeProcessDarwin::Interrupt() but we stopped
// for another reason.
// 2 - We called NativeProcessDarwin::Resume() (but still
// haven't gotten the interrupt signal).
// 3 - We are now incorrectly stopped because we are handling
// the interrupt signal we missed.
// 4 - We might need to resume if we stopped only with the
// interrupt signal that we never handled.
if (m_auto_resume_signo != 0) {
// Only auto_resume if we stopped with _only_ the interrupt signal.
if (num_task_exceptions == 1) {
auto_resume = true;
LLDB_LOGF(log,
"NativeProcessDarwin::%s(): auto "
"resuming due to unhandled interrupt "
"signal %i",
__FUNCTION__, m_auto_resume_signo);
}
m_auto_resume_signo = 0;
}
} else {
LLDB_LOGF(log,
"NativeProcessDarwin::%s(): didn't get signal "
"%i after MachProcess::Interrupt()",
__FUNCTION__, m_sent_interrupt_signo);
}
}
}
// Let all threads recover from stopping and do any clean up based on the
// previous thread state (if any).
m_thread_list.ProcessDidStop(*this);
// Let each thread know of any exceptions
for (i = 0; i < m_exception_messages.size(); ++i) {
// Let the thread list forward all exceptions on down to each thread.
if (m_exception_messages[i].state.task_port == task) {
// This exception is for our inferior.
m_thread_list.NotifyException(m_exception_messages[i].state);
}
if (log) {
StreamString stream;
m_exception_messages[i].Dump(stream);
stream.Flush();
log->PutCString(stream.GetString().c_str());
}
}
if (log) {
StreamString stream;
m_thread_list.Dump(stream);
stream.Flush();
log->PutCString(stream.GetString().c_str());
}
bool step_more = false;
if (m_thread_list.ShouldStop(step_more) && (auto_resume == false)) {
// TODO - need to hook up event system here. !!!!
#if 0
// Wait for the eEventProcessRunningStateChanged event to be reset
// before changing state to stopped to avoid race condition with very
// fast start/stops.
struct timespec timeout;
//DNBTimer::OffsetTimeOfDay(&timeout, 0, 250 * 1000); // Wait for 250 ms
DNBTimer::OffsetTimeOfDay(&timeout, 1, 0); // Wait for 250 ms
m_events.WaitForEventsToReset(eEventProcessRunningStateChanged,
&timeout);
#endif
SetState(eStateStopped);
} else {
// Resume without checking our current state.
PrivateResume();
}
return m_task;
}
void NativeProcessDarwin::StartSTDIOThread() {
// TODO implement
}
Status NativeProcessDarwin::StartWaitpidThread(MainLoop &main_loop) {
Status error;
Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
// Strategy: create a thread that sits on waitpid(), waiting for the inferior
// process to die, reaping it in the process. Arrange for the thread to have
// a pipe file descriptor that it can send a byte over when the waitpid
// completes. Have the main loop have a read object for the other side of
// the pipe, and have the callback for the read do the process termination
// message sending.
// Create a single-direction communication channel.
const bool child_inherits = false;
error = m_waitpid_pipe.CreateNew(child_inherits);
if (error.Fail()) {
LLDB_LOGF(log,
"NativeProcessDarwin::%s(): failed to create waitpid "
"communication pipe: %s",
__FUNCTION__, error.AsCString());
return error;
}
// Hook up the waitpid reader callback.
// TODO make PipePOSIX derive from IOObject. This is goofy here.
const bool transfer_ownership = false;
auto io_sp = IOObjectSP(new NativeFile(m_waitpid_pipe.GetReadFileDescriptor(),
transfer_ownership));
m_waitpid_reader_handle = main_loop.RegisterReadObject(
io_sp, [this](MainLoopBase &) { HandleWaitpidResult(); }, error);
// Create the thread.
auto pthread_err =
::pthread_create(&m_waitpid_thread, nullptr, WaitpidThread, this);
error.SetError(pthread_err, eErrorTypePOSIX);
if (error.Fail()) {
LLDB_LOGF(log,
"NativeProcessDarwin::%s(): failed to create waitpid "
"handling thread: %u (%s)",
__FUNCTION__, error.GetError(), error.AsCString());
return error;
}
return error;
}
void *NativeProcessDarwin::WaitpidThread(void *arg) {
Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
if (!arg) {
LLDB_LOGF(log,
"NativeProcessDarwin::%s(): cannot run waitpid "
"thread, mandatory process arg was null",
__FUNCTION__);
return nullptr;
}
return reinterpret_cast<NativeProcessDarwin *>(arg)->DoWaitpidThread();
}
void NativeProcessDarwin::MaybeRaiseThreadPriority() {
#if defined(__arm__) || defined(__arm64__) || defined(__aarch64__)
struct sched_param thread_param;
int thread_sched_policy;
if (pthread_getschedparam(pthread_self(), &thread_sched_policy,
&thread_param) == 0) {
thread_param.sched_priority = 47;
pthread_setschedparam(pthread_self(), thread_sched_policy, &thread_param);
}
#endif
}
void *NativeProcessDarwin::DoWaitpidThread() {
Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
if (m_pid == LLDB_INVALID_PROCESS_ID) {
LLDB_LOGF(log,
"NativeProcessDarwin::%s(): inferior process ID is "
"not set, cannot waitpid on it",
__FUNCTION__);
return nullptr;
}
// Name the thread.
pthread_setname_np("waitpid thread");
// Ensure we don't get CPU starved.
MaybeRaiseThreadPriority();
Status error;
int status = -1;
while (1) {
// Do a waitpid.
::pid_t child_pid = ::waitpid(m_pid, &status, 0);
if (child_pid < 0)
error.SetErrorToErrno();
if (error.Fail()) {
if (error.GetError() == EINTR) {
// This is okay, we can keep going.
LLDB_LOGF(log,
"NativeProcessDarwin::%s(): waitpid(pid = %" PRIu64
", &status, 0) interrupted, continuing",
__FUNCTION__, m_pid);
continue;
}
// This error is not okay, abort.
LLDB_LOGF(log,
"NativeProcessDarwin::%s(): waitpid(pid = %" PRIu64
", &status, 0) aborting due to error: %u (%s)",
__FUNCTION__, m_pid, error.GetError(), error.AsCString());
break;
}
// Log the successful result.
LLDB_LOGF(log,
"NativeProcessDarwin::%s(): waitpid(pid = %" PRIu64
", &status, 0) => %i, status = %i",
__FUNCTION__, m_pid, child_pid, status);
// Handle the result.
if (WIFSTOPPED(status)) {
LLDB_LOGF(log,
"NativeProcessDarwin::%s(): waitpid(pid = %" PRIu64
") received a stop, continuing waitpid() loop",
__FUNCTION__, m_pid);
continue;
} else // if (WIFEXITED(status) || WIFSIGNALED(status))
{
LLDB_LOGF(log,
"NativeProcessDarwin::%s(pid = %" PRIu64 "): "
"waitpid thread is setting exit status for pid = "
"%i to %i",
__FUNCTION__, m_pid, child_pid, status);
error = SendInferiorExitStatusToMainLoop(child_pid, status);
return nullptr;
}
}
// We should never exit as long as our child process is alive. If we get
// here, something completely unexpected went wrong and we should exit.
LLDB_LOGF(log,
"NativeProcessDarwin::%s(): internal error: waitpid thread "
"exited out of its main loop in an unexpected way. pid = %" PRIu64
". Sending exit status of -1.",
__FUNCTION__, m_pid);
error = SendInferiorExitStatusToMainLoop((::pid_t)m_pid, -1);
return nullptr;
}
Status NativeProcessDarwin::SendInferiorExitStatusToMainLoop(::pid_t pid,
int status) {
Status error;
Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
size_t bytes_written = 0;
// Send the pid.
error = m_waitpid_pipe.Write(&pid, sizeof(pid), bytes_written);
if (error.Fail() || (bytes_written < sizeof(pid))) {
LLDB_LOGF(log,
"NativeProcessDarwin::%s() - failed to write "
"waitpid exiting pid to the pipe. Client will not "
"hear about inferior exit status!",
__FUNCTION__);
return error;
}
// Send the status.
bytes_written = 0;
error = m_waitpid_pipe.Write(&status, sizeof(status), bytes_written);
if (error.Fail() || (bytes_written < sizeof(status))) {
LLDB_LOGF(log,
"NativeProcessDarwin::%s() - failed to write "
"waitpid exit result to the pipe. Client will not "
"hear about inferior exit status!",
__FUNCTION__);
}
return error;
}
Status NativeProcessDarwin::HandleWaitpidResult() {
Status error;
Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
// Read the pid.
const bool notify_status = true;
::pid_t pid = -1;
size_t bytes_read = 0;
error = m_waitpid_pipe.Read(&pid, sizeof(pid), bytes_read);
if (error.Fail() || (bytes_read < sizeof(pid))) {
LLDB_LOGF(log,
"NativeProcessDarwin::%s() - failed to read "
"waitpid exiting pid from the pipe. Will notify "
"as if parent process died with exit status -1.",
__FUNCTION__);
SetExitStatus(WaitStatus(WaitStatus::Exit, -1), notify_status);
return error;
}
// Read the status.
int status = -1;
error = m_waitpid_pipe.Read(&status, sizeof(status), bytes_read);
if (error.Fail() || (bytes_read < sizeof(status))) {
LLDB_LOGF(log,
"NativeProcessDarwin::%s() - failed to read "
"waitpid exit status from the pipe. Will notify "
"as if parent process died with exit status -1.",
__FUNCTION__);
SetExitStatus(WaitStatus(WaitStatus::Exit, -1), notify_status);
return error;
}
// Notify the monitor that our state has changed.
LLDB_LOGF(log,
"NativeProcessDarwin::%s(): main loop received waitpid "
"exit status info: pid=%i (%s), status=%i",
__FUNCTION__, pid,
(pid == m_pid) ? "the inferior" : "not the inferior", status);
SetExitStatus(WaitStatus::Decode(status), notify_status);
return error;
}
task_t NativeProcessDarwin::TaskPortForProcessID(Status &error,
bool force) const {
if ((m_task == TASK_NULL) || force) {
Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
if (m_pid == LLDB_INVALID_PROCESS_ID) {
LLDB_LOGF(log,
"NativeProcessDarwin::%s(): cannot get task due "
"to invalid pid",
__FUNCTION__);
return TASK_NULL;
}
const uint32_t num_retries = 10;
const uint32_t usec_interval = 10000;
mach_port_t task_self = mach_task_self();
task_t task = TASK_NULL;
for (uint32_t i = 0; i < num_retries; i++) {
kern_return_t err = ::task_for_pid(task_self, m_pid, &task);
if (err == 0) {
// Succeeded. Save and return it.
error.Clear();
m_task = task;
LLDB_LOGF(log,
"NativeProcessDarwin::%s(): ::task_for_pid("
"stub_port = 0x%4.4x, pid = %llu, &task) "
"succeeded: inferior task port = 0x%4.4x",
__FUNCTION__, task_self, m_pid, m_task);
return m_task;
} else {
// Failed to get the task for the inferior process.
error.SetError(err, eErrorTypeMachKernel);
if (log) {
LLDB_LOGF(log,
"NativeProcessDarwin::%s(): ::task_for_pid("
"stub_port = 0x%4.4x, pid = %llu, &task) "
"failed, err = 0x%8.8x (%s)",
__FUNCTION__, task_self, m_pid, err, error.AsCString());
}
}
// Sleep a bit and try again
::usleep(usec_interval);
}
// We failed to get the task for the inferior process. Ensure that it is
// cleared out.
m_task = TASK_NULL;
}
return m_task;
}
void NativeProcessDarwin::AttachToInferior(MainLoop &mainloop, lldb::pid_t pid,
Status &error) {
error.SetErrorString("TODO: implement");
}
Status NativeProcessDarwin::PrivateResume() {
Status error;
Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
std::lock_guard<std::recursive_mutex> locker(m_exception_messages_mutex);
m_auto_resume_signo = m_sent_interrupt_signo;
if (log) {
if (m_auto_resume_signo)
LLDB_LOGF(log,
"NativeProcessDarwin::%s(): task 0x%x resuming (with "
"unhandled interrupt signal %i)...",
__FUNCTION__, m_task, m_auto_resume_signo);
else
LLDB_LOGF(log, "NativeProcessDarwin::%s(): task 0x%x resuming...",
__FUNCTION__, m_task);
}
error = ReplyToAllExceptions();
if (error.Fail()) {
LLDB_LOGF(log,
"NativeProcessDarwin::%s(): aborting, failed to "
"reply to exceptions: %s",
__FUNCTION__, error.AsCString());
return error;
}
// bool stepOverBreakInstruction = step;
// Let the thread prepare to resume and see if any threads want us to step
// over a breakpoint instruction (ProcessWillResume will modify the value of
// stepOverBreakInstruction).
m_thread_list.ProcessWillResume(*this, m_thread_actions);
// Set our state accordingly
if (m_thread_actions.NumActionsWithState(eStateStepping))
SetState(eStateStepping);
else
SetState(eStateRunning);
// Now resume our task.
error = ResumeTask();
return error;
}
Status NativeProcessDarwin::ReplyToAllExceptions() {
Status error;
Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_VERBOSE));
TaskPortForProcessID(error);
if (error.Fail()) {
LLDB_LOGF(log, "NativeProcessDarwin::%s(): no task port, aborting",
__FUNCTION__);
return error;
}
std::lock_guard<std::recursive_mutex> locker(m_exception_messages_mutex);
if (m_exception_messages.empty()) {
// We're done.
return error;
}
size_t index = 0;
for (auto &message : m_exception_messages) {
if (log) {
LLDB_LOGF(log,
"NativeProcessDarwin::%s(): replying to exception "
"%zu...",
__FUNCTION__, index++);
}
int thread_reply_signal = 0;
const tid_t tid =
m_thread_list.GetThreadIDByMachPortNumber(message.state.thread_port);
const ResumeAction *action = nullptr;
if (tid != LLDB_INVALID_THREAD_ID)
action = m_thread_actions.GetActionForThread(tid, false);
if (action) {
thread_reply_signal = action->signal;
if (thread_reply_signal)
m_thread_actions.SetSignalHandledForThread(tid);
}
error = message.Reply(m_pid, m_task, thread_reply_signal);
if (error.Fail() && log) {
// We log any error here, but we don't stop the exception response
// handling.
LLDB_LOGF(log,
"NativeProcessDarwin::%s(): failed to reply to "
"exception: %s",
__FUNCTION__, error.AsCString());
error.Clear();
}
}
// Erase all exception message as we should have used and replied to them all
// already.
m_exception_messages.clear();
return error;
}
Status NativeProcessDarwin::ResumeTask() {
Status error;
Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
TaskPortForProcessID(error);
if (error.Fail()) {
LLDB_LOGF(log,
"NativeProcessDarwin::%s(): failed to get task port "
"for process when attempting to resume: %s",
__FUNCTION__, error.AsCString());
return error;
}
if (m_task == TASK_NULL) {
error.SetErrorString("task port retrieval succeeded but task port is "
"null when attempting to resume the task");
return error;
}
LLDB_LOGF(log,
"NativeProcessDarwin::%s(): requesting resume of task "
"0x%4.4x",
__FUNCTION__, m_task);
// Get the BasicInfo struct to verify that we're suspended before we try to
// resume the task.
struct task_basic_info task_info;
error = GetTaskBasicInfo(m_task, &task_info);
if (error.Fail()) {
LLDB_LOGF(log,
"NativeProcessDarwin::%s(): failed to get task "
"BasicInfo when attempting to resume: %s",
__FUNCTION__, error.AsCString());
return error;
}
// task_resume isn't counted like task_suspend calls are, so if the task is
// not suspended, don't try and resume it since it is already running
if (task_info.suspend_count > 0) {
auto mach_err = ::task_resume(m_task);
error.SetError(mach_err, eErrorTypeMachKernel);
if (log) {
if (error.Success())
LLDB_LOGF(log, "::task_resume(target_task = 0x%4.4x): success", m_task);
else
LLDB_LOGF(log, "::task_resume(target_task = 0x%4.4x) error: %s", m_task,
error.AsCString());
}
} else {
LLDB_LOGF(log,
"::task_resume(target_task = 0x%4.4x): ignored, "
"already running",
m_task);
}
return error;
}
bool NativeProcessDarwin::IsTaskValid() const {
if (m_task == TASK_NULL)
return false;
struct task_basic_info task_info;
return GetTaskBasicInfo(m_task, &task_info).Success();
}
bool NativeProcessDarwin::IsTaskValid(task_t task) const {
if (task == TASK_NULL)
return false;
struct task_basic_info task_info;
return GetTaskBasicInfo(task, &task_info).Success();
}
mach_port_t NativeProcessDarwin::GetExceptionPort() const {
return m_exception_port;
}
bool NativeProcessDarwin::IsExceptionPortValid() const {
return MACH_PORT_VALID(m_exception_port);
}
Status
NativeProcessDarwin::GetTaskBasicInfo(task_t task,
struct task_basic_info *info) const {
Status error;
Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
// Validate args.
if (info == NULL) {
error.SetErrorStringWithFormat("NativeProcessDarwin::%s(): mandatory "
"info arg is null",
__FUNCTION__);
return error;
}
// Grab the task if we don't already have it.
if (task == TASK_NULL) {
error.SetErrorStringWithFormat("NativeProcessDarwin::%s(): given task "
"is invalid",
__FUNCTION__);
}
mach_msg_type_number_t count = TASK_BASIC_INFO_COUNT;
auto err = ::task_info(m_task, TASK_BASIC_INFO, (task_info_t)info, &count);
error.SetError(err, eErrorTypeMachKernel);
if (error.Fail()) {
LLDB_LOGF(log,
"::task_info(target_task = 0x%4.4x, "
"flavor = TASK_BASIC_INFO, task_info_out => %p, "
"task_info_outCnt => %u) failed: %u (%s)",
m_task, info, count, error.GetError(), error.AsCString());
return error;
}
Log *verbose_log(
GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_VERBOSE));
if (verbose_log) {
float user = (float)info->user_time.seconds +
(float)info->user_time.microseconds / 1000000.0f;
float system = (float)info->user_time.seconds +
(float)info->user_time.microseconds / 1000000.0f;
verbose_LLDB_LOGF(log,
"task_basic_info = { suspend_count = %i, "
"virtual_size = 0x%8.8llx, resident_size = "
"0x%8.8llx, user_time = %f, system_time = %f }",
info->suspend_count, (uint64_t)info->virtual_size,
(uint64_t)info->resident_size, user, system);
}
return error;
}
Status NativeProcessDarwin::SuspendTask() {
Status error;
Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
if (m_task == TASK_NULL) {
error.SetErrorString("task port is null, cannot suspend task");
LLDB_LOGF(log, "NativeProcessDarwin::%s() failed: %s", __FUNCTION__,
error.AsCString());
return error;
}
auto mach_err = ::task_suspend(m_task);
error.SetError(mach_err, eErrorTypeMachKernel);
if (error.Fail() && log)
LLDB_LOGF(log, "::task_suspend(target_task = 0x%4.4x)", m_task);
return error;
}
Status NativeProcessDarwin::Resume(const ResumeActionList &resume_actions) {
Status error;
Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
LLDB_LOGF(log, "NativeProcessDarwin::%s() called", __FUNCTION__);
if (CanResume()) {
m_thread_actions = resume_actions;
error = PrivateResume();
return error;
}
auto state = GetState();
if (state == eStateRunning) {
LLDB_LOGF(log,
"NativeProcessDarwin::%s(): task 0x%x is already "
"running, ignoring...",
__FUNCTION__, TaskPortForProcessID(error));
return error;
}
// We can't resume from this state.
error.SetErrorStringWithFormat("task 0x%x has state %s, can't resume",
TaskPortForProcessID(error),
StateAsCString(state));
return error;
}
Status NativeProcessDarwin::Halt() {
Status error;
error.SetErrorString("TODO: implement");
return error;
}
Status NativeProcessDarwin::Detach() {
Status error;
error.SetErrorString("TODO: implement");
return error;
}
Status NativeProcessDarwin::Signal(int signo) {
Status error;
error.SetErrorString("TODO: implement");
return error;
}
Status NativeProcessDarwin::Interrupt() {
Status error;
error.SetErrorString("TODO: implement");
return error;
}
Status NativeProcessDarwin::Kill() {
Status error;
error.SetErrorString("TODO: implement");
return error;
}
Status NativeProcessDarwin::GetMemoryRegionInfo(lldb::addr_t load_addr,
MemoryRegionInfo &range_info) {
Status error;
error.SetErrorString("TODO: implement");
return error;
}
Status NativeProcessDarwin::ReadMemory(lldb::addr_t addr, void *buf,
size_t size, size_t &bytes_read) {
Status error;
error.SetErrorString("TODO: implement");
return error;
}
Status NativeProcessDarwin::ReadMemoryWithoutTrap(lldb::addr_t addr, void *buf,
size_t size,
size_t &bytes_read) {
Status error;
error.SetErrorString("TODO: implement");
return error;
}
Status NativeProcessDarwin::WriteMemory(lldb::addr_t addr, const void *buf,
size_t size, size_t &bytes_written) {
Status error;
error.SetErrorString("TODO: implement");
return error;
}
Status NativeProcessDarwin::AllocateMemory(size_t size, uint32_t permissions,
lldb::addr_t &addr) {
Status error;
error.SetErrorString("TODO: implement");
return error;
}
Status NativeProcessDarwin::DeallocateMemory(lldb::addr_t addr) {
Status error;
error.SetErrorString("TODO: implement");
return error;
}
lldb::addr_t NativeProcessDarwin::GetSharedLibraryInfoAddress() {
return LLDB_INVALID_ADDRESS;
}
size_t NativeProcessDarwin::UpdateThreads() { return 0; }
bool NativeProcessDarwin::GetArchitecture(ArchSpec &arch) const {
return false;
}
Status NativeProcessDarwin::SetBreakpoint(lldb::addr_t addr, uint32_t size,
bool hardware) {
Status error;
error.SetErrorString("TODO: implement");
return error;
}
void NativeProcessDarwin::DoStopIDBumped(uint32_t newBumpId) {}
Status NativeProcessDarwin::GetLoadedModuleFileSpec(const char *module_path,
FileSpec &file_spec) {
Status error;
error.SetErrorString("TODO: implement");
return error;
}
Status NativeProcessDarwin::GetFileLoadAddress(const llvm::StringRef &file_name,
lldb::addr_t &load_addr) {
Status error;
error.SetErrorString("TODO: implement");
return error;
}
// NativeProcessProtocol protected interface
Status NativeProcessDarwin::GetSoftwareBreakpointTrapOpcode(
size_t trap_opcode_size_hint, size_t &actual_opcode_size,
const uint8_t *&trap_opcode_bytes) {
Status error;
error.SetErrorString("TODO: implement");
return error;
}
| llvm-mirror/lldb | source/Plugins/Process/Darwin/NativeProcessDarwin.cpp | C++ | apache-2.0 | 52,984 |
#define IDM_EXIT 102
#define IDEF_FirstName 201
#define IDEF_LastName 202
#define IDEF_Compamy 203
#define IDEF_Address 204
#define IDEF_City 205
#define IDEF_State 206
#define IDEF_Zip 207
#define IDEF_Phone 208
#define IDPB_Send 301
#define IDPB_Clear 302
| zengboming/LAN-Communications-Guardian | win32多线程程序设计 源码/PRNTWAIT/PRNTWAIT.H | C++ | apache-2.0 | 305 |
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
class AddForeignKeysToVrPagesTranslationsTable extends Migration {
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('vr_pages_translations', function(Blueprint $table)
{
$table->foreign('language_code', 'fk_vr_pages_translations_vr_language_codes1')->references('language_code')->on('vr_language_codes')->onUpdate('NO ACTION')->onDelete('NO ACTION');
$table->foreign('page_id', 'fk_vr_pages_translations_vr_pages1')->references('id')->on('vr_pages')->onUpdate('NO ACTION')->onDelete('NO ACTION');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('vr_pages_translations', function(Blueprint $table)
{
$table->dropForeign('fk_vr_pages_translations_vr_language_codes1');
$table->dropForeign('fk_vr_pages_translations_vr_pages1');
});
}
}
| makalaite/personal_vr.dev | database/migrations/2017_05_23_080810_add_foreign_keys_to_vr_pages_translations_table.php | PHP | apache-2.0 | 963 |
// Based on Knockout Bindings for TinyMCE
// https://github.com/SteveSanderson/knockout/wiki/Bindings---tinyMCE
// Initial version by Ryan Niemeyer. Updated by Scott Messinger, Frederik Raabye, Thomas Hallock, Drew Freyling, and Shane Carr.
(function() {
var instances_by_id = {} // needed for referencing instances during updates.
, init_id = 0; // generated id increment storage
ko.bindingHandlers.ace = {
init: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
var options = allBindingsAccessor().aceOptions || {};
var value = ko.utils.unwrapObservable(valueAccessor());
// Ace attaches to the element by DOM id, so we need to make one for the element if it doesn't have one already.
if (!element.id) {
element.id = 'knockout-ace-' + init_id;
init_id = init_id + 1;
}
var editor = ace.edit( element.id );
if ( options.theme ) editor.setTheme("ace/theme/" + options.theme);
if ( options.mode ) editor.getSession().setMode("ace/mode/" + options.mode);
if ( options.readOnly ) editor.setReadOnly(true);
editor.setValue(value);
editor.gotoLine( 0 );
editor.getSession().on("change",function(delta){
if (ko.isWriteableObservable(valueAccessor())) {
valueAccessor()( editor.getValue() );
}
});
instances_by_id[element.id] = editor;
// destroy the editor instance when the element is removed
ko.utils.domNodeDisposal.addDisposeCallback(element, function() {
editor.destroy();
delete instances_by_id[element.id];
});
},
update: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
var value = ko.utils.unwrapObservable(valueAccessor());
var id = element.id;
//handle programmatic updates to the observable
// also makes sure it doesn't update it if it's the same.
// otherwise, it will reload the instance, causing the cursor to jump.
if (id !== undefined && id !== '' && instances_by_id.hasOwnProperty(id)) {
var editor = instances_by_id[id];
var content = editor.getValue();
if (content !== value) {
editor.setValue(value);
editor.gotoLine( 0 );
}
}
}
};
ko.aceEditors = {
resizeAll: function(){
for (var id in instances_by_id) {
if (!instances_by_id.hasOwnProperty(id)) continue;
var editor = instances_by_id[id];
editor.resize();
}
},
get: function(id){
return instances_by_id[id];
}
};
}());
| duncansmart/kudu | Kudu.Services.Web/Content/Scripts/knockout-ace.js | JavaScript | apache-2.0 | 2,620 |
/**
* Copyright (C) 2007 Logan Johnson
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package atunit.guice;
import java.lang.reflect.Field;
import java.lang.reflect.Type;
import java.util.Collection;
import java.util.Map;
import com.google.common.collect.Iterables;
import com.google.common.collect.Multimap;
import com.google.common.collect.Multimaps;
import com.google.inject.AbstractModule;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.Key;
import com.google.inject.Module;
import com.google.inject.TypeLiteral;
import atunit.core.Container;
public class GuiceContainer implements Container {
public Object createTest(Class<?> testClass, Map<Field, Object> fieldValues) throws Exception {
FieldModule fields = new FieldModule(fieldValues);
Injector injector;
if ( Module.class.isAssignableFrom(testClass)) {
injector = Guice.createInjector(fields, (Module)testClass.newInstance() );
} else {
injector = Guice.createInjector(fields);
}
return injector.getInstance(testClass);
}
protected class FieldModule extends AbstractModule {
final Map<Field,Object> fields;
public FieldModule(Map<Field,Object> fields) {
this.fields = fields;
}
@Override
@SuppressWarnings("unchecked")
protected void configure() {
// map field values by type
Multimap<Type, Field> fieldsByType = Multimaps.newHashMultimap();
for ( Field field : fields.keySet() ) {
fieldsByType.put(field.getGenericType(), field);
}
// for any types that don't have duplicates, bind instances.
for ( Type type : fieldsByType.keySet() ) {
Collection<Field> fields = fieldsByType.get(type);
if ( fields.size() == 1 ) {
Field field = Iterables.getOnlyElement(fields);
TypeLiteral literal = TypeLiteral.get(type);
bind(literal).toInstance(this.fields.get(field));
}
}
}
}
}
| stackoverflowmailer/atunit | src/atunit/guice/GuiceContainer.java | Java | apache-2.0 | 2,410 |
require 'spec_helper'
describe 'yum_test::test_repository_two' do
let(:test_repository_two_run) do
ChefSpec::SoloRunner.new(
step_into: 'yum_repository'
).converge(described_recipe)
end
let(:test_repository_two_template) do
test_repository_two_run.template('/etc/yum.repos.d/unit-test-2.repo')
end
let(:test_repository_two_content) do
'# This file was generated by Chef
# Do NOT modify this file by hand.
[unit-test-2]
name=test all the things!
baseurl=http://example.com/wat
cost=10
enabled=1
enablegroups=1
exclude=package1 package2 package3
failovermethod=priority
fastestmirror_enabled=true
gpgcheck=1
gpgkey=http://example.com/RPM-GPG-KEY-FOOBAR-1
http_caching=all
include=/some/other.repo
includepkgs=package4 package5
keepalive=1
metadata_expire=never
mirrorlist=http://hellothereiammirrorliststring.biz
mirror_expire=300
mirrorlist_expire=86400
priority=10
proxy=http://hellothereiamproxystring.biz
proxy_username=kermit
proxy_password=dafrog
repo_gpgcheck=1
retries=10
skip_if_unavailable=1
sslcacert=/path/to/directory
sslclientcert=/path/to/client/cert
sslclientkey=/path/to/client/key
sslverify=true
timeout=10
'
end
context 'creating a yum_repository with full parameters' do
it 'creates yum_repository[test2]' do
expect(test_repository_two_run).to create_yum_repository('test2')
end
it 'steps into yum_repository and creates template[/etc/yum.repos.d/unit-test-2.repo]' do
expect(test_repository_two_run).to create_template('/etc/yum.repos.d/unit-test-2.repo')
end
it 'steps into yum_repository and renders file[/etc/yum.repos.d/unit-test-2.repo]' do
expect(test_repository_two_run).to render_file('/etc/yum.repos.d/unit-test-2.repo').with_content(test_repository_two_content)
end
it 'steps into yum_repository and runs execute[yum clean metadata unit-test2]' do
expect(test_repository_two_run).to_not run_execute('yum clean metadata unit-test-2')
end
it 'steps into yum_repository and runs execute[yum-makecache-unit-test-2]' do
expect(test_repository_two_run).to_not run_execute('yum-makecache-unit-test-2')
end
it 'steps into yum_repository and runs ruby_block[yum-cache-reload-unit-test-2]' do
expect(test_repository_two_run).to_not run_ruby_block('yum-cache-reload-unit-test-2')
end
it 'sends a :run to execute[yum-makecache-unit-test-2]' do
expect(test_repository_two_template).to notify('execute[yum-makecache-unit-test-2]')
end
it 'sends a :create to ruby_block[yum-cache-reload-unit-test-2]' do
expect(test_repository_two_template).to notify('ruby_block[yum-cache-reload-unit-test-2]')
end
end
end
| YColander/yum | spec/unit/test_repository_two_spec.rb | Ruby | apache-2.0 | 2,683 |
/*
* Copyright (C) 2014 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.exoplayer.text.webvtt;
import junit.framework.TestCase;
/**
* Unit test for {@link WebvttSubtitle}.
*/
public class WebvttSubtitleTest extends TestCase {
private static final String FIRST_SUBTITLE_STRING = "This is the first subtitle.";
private static final String SECOND_SUBTITLE_STRING = "This is the second subtitle.";
private static final String FIRST_AND_SECOND_SUBTITLE_STRING =
FIRST_SUBTITLE_STRING + SECOND_SUBTITLE_STRING;
private WebvttSubtitle emptySubtitle = new WebvttSubtitle(new String[] {}, 0, new long[] {});
private WebvttSubtitle simpleSubtitle = new WebvttSubtitle(
new String[] {FIRST_SUBTITLE_STRING, SECOND_SUBTITLE_STRING}, 0,
new long[] {1000000, 2000000, 3000000, 4000000});
private WebvttSubtitle overlappingSubtitle = new WebvttSubtitle(
new String[] {FIRST_SUBTITLE_STRING, SECOND_SUBTITLE_STRING}, 0,
new long[] {1000000, 3000000, 2000000, 4000000});
private WebvttSubtitle nestedSubtitle = new WebvttSubtitle(
new String[] {FIRST_SUBTITLE_STRING, SECOND_SUBTITLE_STRING}, 0,
new long[] {1000000, 4000000, 2000000, 3000000});
public void testEventCount() {
assertEquals(0, emptySubtitle.getEventTimeCount());
assertEquals(4, simpleSubtitle.getEventTimeCount());
assertEquals(4, overlappingSubtitle.getEventTimeCount());
assertEquals(4, nestedSubtitle.getEventTimeCount());
}
public void testStartTime() {
assertEquals(0, emptySubtitle.getStartTime());
assertEquals(0, simpleSubtitle.getStartTime());
assertEquals(0, overlappingSubtitle.getStartTime());
assertEquals(0, nestedSubtitle.getStartTime());
}
public void testLastEventTime() {
assertEquals(-1, emptySubtitle.getLastEventTime());
assertEquals(4000000, simpleSubtitle.getLastEventTime());
assertEquals(4000000, overlappingSubtitle.getLastEventTime());
assertEquals(4000000, nestedSubtitle.getLastEventTime());
}
public void testSimpleSubtitleEventTimes() {
testSubtitleEventTimesHelper(simpleSubtitle);
}
public void testSimpleSubtitleEventIndices() {
testSubtitleEventIndicesHelper(simpleSubtitle);
}
public void testSimpleSubtitleText() {
// Test before first subtitle
assertNull(simpleSubtitle.getText(0));
assertNull(simpleSubtitle.getText(500000));
assertNull(simpleSubtitle.getText(999999));
// Test first subtitle
assertEquals(FIRST_SUBTITLE_STRING, simpleSubtitle.getText(1000000));
assertEquals(FIRST_SUBTITLE_STRING, simpleSubtitle.getText(1500000));
assertEquals(FIRST_SUBTITLE_STRING, simpleSubtitle.getText(1999999));
// Test after first subtitle, before second subtitle
assertNull(simpleSubtitle.getText(2000000));
assertNull(simpleSubtitle.getText(2500000));
assertNull(simpleSubtitle.getText(2999999));
// Test second subtitle
assertEquals(SECOND_SUBTITLE_STRING, simpleSubtitle.getText(3000000));
assertEquals(SECOND_SUBTITLE_STRING, simpleSubtitle.getText(3500000));
assertEquals(SECOND_SUBTITLE_STRING, simpleSubtitle.getText(3999999));
// Test after second subtitle
assertNull(simpleSubtitle.getText(4000000));
assertNull(simpleSubtitle.getText(4500000));
assertNull(simpleSubtitle.getText(Long.MAX_VALUE));
}
public void testOverlappingSubtitleEventTimes() {
testSubtitleEventTimesHelper(overlappingSubtitle);
}
public void testOverlappingSubtitleEventIndices() {
testSubtitleEventIndicesHelper(overlappingSubtitle);
}
public void testOverlappingSubtitleText() {
// Test before first subtitle
assertNull(overlappingSubtitle.getText(0));
assertNull(overlappingSubtitle.getText(500000));
assertNull(overlappingSubtitle.getText(999999));
// Test first subtitle
assertEquals(FIRST_SUBTITLE_STRING, overlappingSubtitle.getText(1000000));
assertEquals(FIRST_SUBTITLE_STRING, overlappingSubtitle.getText(1500000));
assertEquals(FIRST_SUBTITLE_STRING, overlappingSubtitle.getText(1999999));
// Test after first and second subtitle
assertEquals(FIRST_AND_SECOND_SUBTITLE_STRING, overlappingSubtitle.getText(2000000));
assertEquals(FIRST_AND_SECOND_SUBTITLE_STRING, overlappingSubtitle.getText(2500000));
assertEquals(FIRST_AND_SECOND_SUBTITLE_STRING, overlappingSubtitle.getText(2999999));
// Test second subtitle
assertEquals(SECOND_SUBTITLE_STRING, overlappingSubtitle.getText(3000000));
assertEquals(SECOND_SUBTITLE_STRING, overlappingSubtitle.getText(3500000));
assertEquals(SECOND_SUBTITLE_STRING, overlappingSubtitle.getText(3999999));
// Test after second subtitle
assertNull(overlappingSubtitle.getText(4000000));
assertNull(overlappingSubtitle.getText(4500000));
assertNull(overlappingSubtitle.getText(Long.MAX_VALUE));
}
public void testNestedSubtitleEventTimes() {
testSubtitleEventTimesHelper(nestedSubtitle);
}
public void testNestedSubtitleEventIndices() {
testSubtitleEventIndicesHelper(nestedSubtitle);
}
public void testNestedSubtitleText() {
// Test before first subtitle
assertNull(nestedSubtitle.getText(0));
assertNull(nestedSubtitle.getText(500000));
assertNull(nestedSubtitle.getText(999999));
// Test first subtitle
assertEquals(FIRST_SUBTITLE_STRING, nestedSubtitle.getText(1000000));
assertEquals(FIRST_SUBTITLE_STRING, nestedSubtitle.getText(1500000));
assertEquals(FIRST_SUBTITLE_STRING, nestedSubtitle.getText(1999999));
// Test after first and second subtitle
assertEquals(FIRST_AND_SECOND_SUBTITLE_STRING, nestedSubtitle.getText(2000000));
assertEquals(FIRST_AND_SECOND_SUBTITLE_STRING, nestedSubtitle.getText(2500000));
assertEquals(FIRST_AND_SECOND_SUBTITLE_STRING, nestedSubtitle.getText(2999999));
// Test first subtitle
assertEquals(FIRST_SUBTITLE_STRING, nestedSubtitle.getText(3000000));
assertEquals(FIRST_SUBTITLE_STRING, nestedSubtitle.getText(3500000));
assertEquals(FIRST_SUBTITLE_STRING, nestedSubtitle.getText(3999999));
// Test after second subtitle
assertNull(nestedSubtitle.getText(4000000));
assertNull(nestedSubtitle.getText(4500000));
assertNull(nestedSubtitle.getText(Long.MAX_VALUE));
}
private void testSubtitleEventTimesHelper(WebvttSubtitle subtitle) {
assertEquals(1000000, subtitle.getEventTime(0));
assertEquals(2000000, subtitle.getEventTime(1));
assertEquals(3000000, subtitle.getEventTime(2));
assertEquals(4000000, subtitle.getEventTime(3));
}
private void testSubtitleEventIndicesHelper(WebvttSubtitle subtitle) {
// Test first event
assertEquals(0, subtitle.getNextEventTimeIndex(0));
assertEquals(0, subtitle.getNextEventTimeIndex(500000));
assertEquals(0, subtitle.getNextEventTimeIndex(999999));
// Test second event
assertEquals(1, subtitle.getNextEventTimeIndex(1000000));
assertEquals(1, subtitle.getNextEventTimeIndex(1500000));
assertEquals(1, subtitle.getNextEventTimeIndex(1999999));
// Test third event
assertEquals(2, subtitle.getNextEventTimeIndex(2000000));
assertEquals(2, subtitle.getNextEventTimeIndex(2500000));
assertEquals(2, subtitle.getNextEventTimeIndex(2999999));
// Test fourth event
assertEquals(3, subtitle.getNextEventTimeIndex(3000000));
assertEquals(3, subtitle.getNextEventTimeIndex(3500000));
assertEquals(3, subtitle.getNextEventTimeIndex(3999999));
// Test null event (i.e. look for events after the last event)
assertEquals(-1, subtitle.getNextEventTimeIndex(4000000));
assertEquals(-1, subtitle.getNextEventTimeIndex(4500000));
assertEquals(-1, subtitle.getNextEventTimeIndex(Long.MAX_VALUE));
}
}
| kstv/ExoPlayer | library/src/test/java/com/google/android/exoplayer/text/webvtt/WebvttSubtitleTest.java | Java | apache-2.0 | 8,307 |
netdev_group 'bgp_group' do
template_path 'bgp.xml.erb'
action :delete
end
| opscode-cookbooks/netdev | test/fixtures/cookbooks/group/recipes/bgp_delete.rb | Ruby | apache-2.0 | 79 |
{% load i18n %}
{% if is_paginated %}
<nav class="text-center">
<ul class="pagination">
{% if page_obj.has_previous %}
<li>
<a href="?page={{ page_obj.previous_page_number }}">
<span>«</span>
</a>
</li>
{% endif %}
<li class="page-current"><a>
{% blocktrans trimmed with page=page_obj.number of=page_obj.paginator.num_pages %}
Page {{ page }} of {{ of }}
{% endblocktrans %}
</a></li>
{% if page_obj.has_next %}
<li>
<a href="?page={{ page_obj.next_page_number }}">
<span>»</span>
</a>
</li>
{% endif %}
</ul>
</nav>
{% endif %}
| akuks/pretix | src/pretix/control/templates/pretixcontrol/pagination.html | HTML | apache-2.0 | 881 |
/*
* Copyright (C) 2016 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.exoplayer2.upstream;
import android.annotation.SuppressLint;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.os.SystemClock;
import android.util.Log;
import com.google.android.exoplayer2.util.Assertions;
import com.google.android.exoplayer2.util.TraceUtil;
import com.google.android.exoplayer2.util.Util;
import java.io.IOException;
import java.util.concurrent.ExecutorService;
/**
* Manages the background loading of {@link Loadable}s.
*/
public final class Loader implements LoaderErrorThrower {
/**
* Thrown when an unexpected exception or error is encountered during loading.
*/
public static final class UnexpectedLoaderException extends IOException {
public UnexpectedLoaderException(Throwable cause) {
super("Unexpected " + cause.getClass().getSimpleName() + ": " + cause.getMessage(), cause);
}
}
/**
* An object that can be loaded using a {@link Loader}.
*/
public interface Loadable {
/**
* Cancels the load.
*/
void cancelLoad();
/**
* Returns whether the load has been canceled.
*/
boolean isLoadCanceled();
/**
* Performs the load, returning on completion or cancellation.
*
* @throws IOException
* @throws InterruptedException
*/
void load() throws IOException, InterruptedException;
}
/**
* A callback to be notified of {@link Loader} events.
*/
public interface Callback<T extends Loadable> {
/**
* Called when a load has completed.
* <p>
* Note: There is guaranteed to be a memory barrier between {@link Loadable#load()} exiting and
* this callback being called.
*
* @param loadable The loadable whose load has completed.
* @param elapsedRealtimeMs {@link SystemClock#elapsedRealtime} when the load ended.
* @param loadDurationMs The duration of the load.
*/
void onLoadCompleted(T loadable, long elapsedRealtimeMs, long loadDurationMs);
/**
* Called when a load has been canceled.
* <p>
* Note: If the {@link Loader} has not been released then there is guaranteed to be a memory
* barrier between {@link Loadable#load()} exiting and this callback being called. If the
* {@link Loader} has been released then this callback may be called before
* {@link Loadable#load()} exits.
*
* @param loadable The loadable whose load has been canceled.
* @param elapsedRealtimeMs {@link SystemClock#elapsedRealtime} when the load was canceled.
* @param loadDurationMs The duration of the load up to the point at which it was canceled.
* @param released True if the load was canceled because the {@link Loader} was released. False
* otherwise.
*/
void onLoadCanceled(T loadable, long elapsedRealtimeMs, long loadDurationMs, boolean released);
/**
* Called when a load encounters an error.
* <p>
* Note: There is guaranteed to be a memory barrier between {@link Loadable#load()} exiting and
* this callback being called.
*
* @param loadable The loadable whose load has encountered an error.
* @param elapsedRealtimeMs {@link SystemClock#elapsedRealtime} when the error occurred.
* @param loadDurationMs The duration of the load up to the point at which the error occurred.
* @param error The load error.
* @return The desired retry action. One of {@link Loader#RETRY},
* {@link Loader#RETRY_RESET_ERROR_COUNT}, {@link Loader#DONT_RETRY} and
* {@link Loader#DONT_RETRY_FATAL}.
*/
int onLoadError(T loadable, long elapsedRealtimeMs, long loadDurationMs, IOException error);
}
public static final int RETRY = 0;
public static final int RETRY_RESET_ERROR_COUNT = 1;
public static final int DONT_RETRY = 2;
public static final int DONT_RETRY_FATAL = 3;
private static final int MSG_START = 0;
private static final int MSG_CANCEL = 1;
private static final int MSG_END_OF_SOURCE = 2;
private static final int MSG_IO_EXCEPTION = 3;
private static final int MSG_FATAL_ERROR = 4;
private final ExecutorService downloadExecutorService;
private LoadTask<? extends Loadable> currentTask;
private IOException fatalError;
/**
* @param threadName A name for the loader's thread.
*/
public Loader(String threadName) {
this.downloadExecutorService = Util.newSingleThreadExecutor(threadName);
}
/**
* Starts loading a {@link Loadable}.
* <p>
* The calling thread must be a {@link Looper} thread, which is the thread on which the
* {@link Callback} will be called.
*
* @param <T> The type of the loadable.
* @param loadable The {@link Loadable} to load.
* @param callback A callback to called when the load ends.
* @param defaultMinRetryCount The minimum number of times the load must be retried before
* {@link #maybeThrowError()} will propagate an error.
* @throws IllegalStateException If the calling thread does not have an associated {@link Looper}.
* @return {@link SystemClock#elapsedRealtime} when the load started.
*/
public <T extends Loadable> long startLoading(T loadable, Callback<T> callback,
int defaultMinRetryCount) {
Looper looper = Looper.myLooper();
Assertions.checkState(looper != null);
long startTimeMs = SystemClock.elapsedRealtime();
new LoadTask<>(looper, loadable, callback, defaultMinRetryCount, startTimeMs).start(0);
return startTimeMs;
}
/**
* Returns whether the {@link Loader} is currently loading a {@link Loadable}.
*/
public boolean isLoading() {
return currentTask != null;
}
/**
* Cancels the current load. This method should only be called when a load is in progress.
*/
public void cancelLoading() {
currentTask.cancel(false);
}
/**
* Releases the {@link Loader}. This method should be called when the {@link Loader} is no longer
* required.
*/
public void release() {
release(null);
}
/**
* Releases the {@link Loader}, running {@code postLoadAction} on its thread. This method should
* be called when the {@link Loader} is no longer required.
*
* @param postLoadAction A {@link Runnable} to run on the loader's thread when
* {@link Loadable#load()} is no longer running.
*/
public void release(Runnable postLoadAction) {
if (currentTask != null) {
currentTask.cancel(true);
}
if (postLoadAction != null) {
downloadExecutorService.execute(postLoadAction);
}
downloadExecutorService.shutdown();
}
// LoaderErrorThrower implementation.
@Override
public void maybeThrowError() throws IOException {
maybeThrowError(Integer.MIN_VALUE);
}
@Override
public void maybeThrowError(int minRetryCount) throws IOException {
if (fatalError != null) {
throw fatalError;
} else if (currentTask != null) {
currentTask.maybeThrowError(minRetryCount == Integer.MIN_VALUE
? currentTask.defaultMinRetryCount : minRetryCount);
}
}
// Internal classes.
@SuppressLint("HandlerLeak")
private final class LoadTask<T extends Loadable> extends Handler implements Runnable {
private static final String TAG = "LoadTask";
private final T loadable;
private final Loader.Callback<T> callback;
public final int defaultMinRetryCount;
private final long startTimeMs;
private IOException currentError;
private int errorCount;
private volatile Thread executorThread;
private volatile boolean released;
public LoadTask(Looper looper, T loadable, Loader.Callback<T> callback,
int defaultMinRetryCount, long startTimeMs) {
super(looper);
this.loadable = loadable;
this.callback = callback;
this.defaultMinRetryCount = defaultMinRetryCount;
this.startTimeMs = startTimeMs;
}
public void maybeThrowError(int minRetryCount) throws IOException {
if (currentError != null && errorCount > minRetryCount) {
throw currentError;
}
}
public void start(long delayMillis) {
Assertions.checkState(currentTask == null);
currentTask = this;
if (delayMillis > 0) {
sendEmptyMessageDelayed(MSG_START, delayMillis);
} else {
execute();
}
}
public void cancel(boolean released) {
this.released = released;
currentError = null;
if (hasMessages(MSG_START)) {
removeMessages(MSG_START);
if (!released) {
sendEmptyMessage(MSG_CANCEL);
}
} else {
loadable.cancelLoad();
if (executorThread != null) {
executorThread.interrupt();
}
}
if (released) {
finish();
long nowMs = SystemClock.elapsedRealtime();
callback.onLoadCanceled(loadable, nowMs, nowMs - startTimeMs, true);
}
}
@Override
public void run() {
try {
executorThread = Thread.currentThread();
if (!loadable.isLoadCanceled()) {
TraceUtil.beginSection("load:" + loadable.getClass().getSimpleName());
try {
loadable.load();
} finally {
TraceUtil.endSection();
}
}
if (!released) {
sendEmptyMessage(MSG_END_OF_SOURCE);
}
} catch (IOException e) {
if (!released) {
obtainMessage(MSG_IO_EXCEPTION, e).sendToTarget();
}
} catch (InterruptedException e) {
// The load was canceled.
Assertions.checkState(loadable.isLoadCanceled());
if (!released) {
sendEmptyMessage(MSG_END_OF_SOURCE);
}
} catch (Exception e) {
// This should never happen, but handle it anyway.
Log.e(TAG, "Unexpected exception loading stream", e);
if (!released) {
obtainMessage(MSG_IO_EXCEPTION, new UnexpectedLoaderException(e)).sendToTarget();
}
} catch (OutOfMemoryError e) {
// This can occur if a stream is malformed in a way that causes an extractor to think it
// needs to allocate a large amount of memory. We don't want the process to die in this
// case, but we do want the playback to fail.
Log.e(TAG, "OutOfMemory error loading stream", e);
if (!released) {
obtainMessage(MSG_IO_EXCEPTION, new UnexpectedLoaderException(e)).sendToTarget();
}
} catch (Error e) {
// We'd hope that the platform would kill the process if an Error is thrown here, but the
// executor may catch the error (b/20616433). Throw it here, but also pass and throw it from
// the handler thread so that the process dies even if the executor behaves in this way.
Log.e(TAG, "Unexpected error loading stream", e);
if (!released) {
obtainMessage(MSG_FATAL_ERROR, e).sendToTarget();
}
throw e;
}
}
@Override
public void handleMessage(Message msg) {
if (released) {
return;
}
if (msg.what == MSG_START) {
execute();
return;
}
if (msg.what == MSG_FATAL_ERROR) {
throw (Error) msg.obj;
}
finish();
long nowMs = SystemClock.elapsedRealtime();
long durationMs = nowMs - startTimeMs;
if (loadable.isLoadCanceled()) {
callback.onLoadCanceled(loadable, nowMs, durationMs, false);
return;
}
switch (msg.what) {
case MSG_CANCEL:
callback.onLoadCanceled(loadable, nowMs, durationMs, false);
break;
case MSG_END_OF_SOURCE:
callback.onLoadCompleted(loadable, nowMs, durationMs);
break;
case MSG_IO_EXCEPTION:
currentError = (IOException) msg.obj;
int retryAction = callback.onLoadError(loadable, nowMs, durationMs, currentError);
if (retryAction == DONT_RETRY_FATAL) {
fatalError = currentError;
} else if (retryAction != DONT_RETRY) {
errorCount = retryAction == RETRY_RESET_ERROR_COUNT ? 1 : errorCount + 1;
start(getRetryDelayMillis());
}
break;
}
}
private void execute() {
currentError = null;
downloadExecutorService.execute(currentTask);
}
private void finish() {
currentTask = null;
}
private long getRetryDelayMillis() {
return Math.min((errorCount - 1) * 1000, 5000);
}
}
}
| michalliu/ExoPlayer | library/core/src/main/java/com/google/android/exoplayer2/upstream/Loader.java | Java | apache-2.0 | 13,042 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.zeppelin.notebook;
import java.io.IOException;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Random;
import org.apache.zeppelin.display.AngularObject;
import org.apache.zeppelin.display.AngularObjectRegistry;
import org.apache.zeppelin.display.Input;
import org.apache.zeppelin.interpreter.Interpreter;
import org.apache.zeppelin.interpreter.InterpreterException;
import org.apache.zeppelin.interpreter.InterpreterGroup;
import org.apache.zeppelin.interpreter.InterpreterResult;
import org.apache.zeppelin.interpreter.InterpreterSetting;
import org.apache.zeppelin.notebook.repo.NotebookRepo;
import org.apache.zeppelin.notebook.utility.IdHashes;
import org.apache.zeppelin.scheduler.Job;
import org.apache.zeppelin.scheduler.Job.Status;
import org.apache.zeppelin.scheduler.JobListener;
import org.apache.zeppelin.search.SearchService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.gson.Gson;
/**
* Binded interpreters for a note
*/
public class Note implements Serializable, JobListener {
private static final long serialVersionUID = 7920699076577612429L;
final List<Paragraph> paragraphs = new LinkedList<>();
private String name = "";
private String id;
@SuppressWarnings("rawtypes")
Map<String, List<AngularObject>> angularObjects = new HashMap<>();
private transient NoteInterpreterLoader replLoader;
private transient JobListenerFactory jobListenerFactory;
private transient NotebookRepo repo;
private transient SearchService index;
/**
* note configurations.
*
* - looknfeel - cron
*/
private Map<String, Object> config = new HashMap<>();
/**
* note information.
*
* - cron : cron expression validity.
*/
private Map<String, Object> info = new HashMap<>();
public Note() {}
public Note(NotebookRepo repo, NoteInterpreterLoader replLoader,
JobListenerFactory jlFactory, SearchService noteIndex) {
this.repo = repo;
this.replLoader = replLoader;
this.jobListenerFactory = jlFactory;
this.index = noteIndex;
generateId();
}
private void generateId() {
id = IdHashes.encode(System.currentTimeMillis() + new Random().nextInt());
}
public String id() {
return id;
}
public String getId() {
return id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public NoteInterpreterLoader getNoteReplLoader() {
return replLoader;
}
public void setReplLoader(NoteInterpreterLoader replLoader) {
this.replLoader = replLoader;
}
public JobListenerFactory getJobListenerFactory() {
return jobListenerFactory;
}
public void setJobListenerFactory(JobListenerFactory jobListenerFactory) {
this.jobListenerFactory = jobListenerFactory;
}
public NotebookRepo getNotebookRepo() {
return repo;
}
public void setNotebookRepo(NotebookRepo repo) {
this.repo = repo;
}
public void setIndex(SearchService index) {
this.index = index;
}
@SuppressWarnings("rawtypes")
public Map<String, List<AngularObject>> getAngularObjects() {
return angularObjects;
}
/**
* Add paragraph last.
*
* @param p
*/
public Paragraph addParagraph() {
Paragraph p = new Paragraph(this, this, replLoader);
synchronized (paragraphs) {
paragraphs.add(p);
}
return p;
}
/**
* Clone paragraph and add it to note.
*
* @param srcParagraph
*/
public void addCloneParagraph(Paragraph srcParagraph) {
Paragraph newParagraph = new Paragraph(this, this, replLoader);
Map<String, Object> config = new HashMap<>(srcParagraph.getConfig());
Map<String, Object> param = new HashMap<>(srcParagraph.settings.getParams());
Map<String, Input> form = new HashMap<>(srcParagraph.settings.getForms());
Gson gson = new Gson();
InterpreterResult result = gson.fromJson(
gson.toJson(srcParagraph.getReturn()),
InterpreterResult.class);
newParagraph.setConfig(config);
newParagraph.settings.setParams(param);
newParagraph.settings.setForms(form);
newParagraph.setText(srcParagraph.getText());
newParagraph.setTitle(srcParagraph.getTitle());
newParagraph.setReturn(result, null);
synchronized (paragraphs) {
paragraphs.add(newParagraph);
}
}
/**
* Insert paragraph in given index.
*
* @param index
* @param p
*/
public Paragraph insertParagraph(int index) {
Paragraph p = new Paragraph(this, this, replLoader);
synchronized (paragraphs) {
paragraphs.add(index, p);
}
return p;
}
/**
* Remove paragraph by id.
*
* @param paragraphId
* @return a paragraph that was deleted, or <code>null</code> otherwise
*/
public Paragraph removeParagraph(String paragraphId) {
synchronized (paragraphs) {
Iterator<Paragraph> i = paragraphs.iterator();
while (i.hasNext()) {
Paragraph p = i.next();
if (p.getId().equals(paragraphId)) {
index.deleteIndexDoc(this, p);
i.remove();
return p;
}
}
}
return null;
}
/**
* Clear paragraph output by id.
*
* @param paragraphId
* @return
*/
public Paragraph clearParagraphOutput(String paragraphId) {
synchronized (paragraphs) {
for (int i = 0; i < paragraphs.size(); i++) {
Paragraph p = paragraphs.get(i);
if (p.getId().equals(paragraphId)) {
p.setReturn(null, null);
return p;
}
}
}
return null;
}
/**
* Move paragraph into the new index (order from 0 ~ n-1).
*
* @param paragraphId
* @param index new index
*/
public void moveParagraph(String paragraphId, int index) {
moveParagraph(paragraphId, index, false);
}
/**
* Move paragraph into the new index (order from 0 ~ n-1).
*
* @param paragraphId
* @param index new index
* @param throwWhenIndexIsOutOfBound whether throw IndexOutOfBoundException
* when index is out of bound
*/
public void moveParagraph(String paragraphId, int index, boolean throwWhenIndexIsOutOfBound) {
synchronized (paragraphs) {
int oldIndex;
Paragraph p = null;
if (index < 0 || index >= paragraphs.size()) {
if (throwWhenIndexIsOutOfBound) {
throw new IndexOutOfBoundsException("paragraph size is " + paragraphs.size() +
" , index is " + index);
} else {
return;
}
}
for (int i = 0; i < paragraphs.size(); i++) {
if (paragraphs.get(i).getId().equals(paragraphId)) {
oldIndex = i;
if (oldIndex == index) {
return;
}
p = paragraphs.remove(i);
}
}
if (p != null) {
paragraphs.add(index, p);
}
}
}
public boolean isLastParagraph(String paragraphId) {
if (!paragraphs.isEmpty()) {
synchronized (paragraphs) {
if (paragraphId.equals(paragraphs.get(paragraphs.size() - 1).getId())) {
return true;
}
}
return false;
}
/** because empty list, cannot remove nothing right? */
return true;
}
public Paragraph getParagraph(String paragraphId) {
synchronized (paragraphs) {
for (Paragraph p : paragraphs) {
if (p.getId().equals(paragraphId)) {
return p;
}
}
}
return null;
}
public Paragraph getLastParagraph() {
synchronized (paragraphs) {
return paragraphs.get(paragraphs.size() - 1);
}
}
public List<Map<String, String>> generateParagraphsInfo (){
List<Map<String, String>> paragraphsInfo = new LinkedList<>();
synchronized (paragraphs) {
for (Paragraph p : paragraphs) {
Map<String, String> info = new HashMap<>();
info.put("id", p.getId());
info.put("status", p.getStatus().toString());
if (p.getDateStarted() != null) {
info.put("started", p.getDateStarted().toString());
}
if (p.getDateFinished() != null) {
info.put("finished", p.getDateFinished().toString());
}
if (p.getStatus().isRunning()) {
info.put("progress", String.valueOf(p.progress()));
}
paragraphsInfo.add(info);
}
}
return paragraphsInfo;
}
/**
* Run all paragraphs sequentially.
*
* @param jobListener
*/
public void runAll() {
synchronized (paragraphs) {
for (Paragraph p : paragraphs) {
p.setNoteReplLoader(replLoader);
p.setListener(jobListenerFactory.getParagraphJobListener(this));
Interpreter intp = replLoader.get(p.getRequiredReplName());
intp.getScheduler().submit(p);
}
}
}
/**
* Run a single paragraph.
*
* @param paragraphId
*/
public void run(String paragraphId) {
Paragraph p = getParagraph(paragraphId);
p.setNoteReplLoader(replLoader);
p.setListener(jobListenerFactory.getParagraphJobListener(this));
Interpreter intp = replLoader.get(p.getRequiredReplName());
if (intp == null) {
throw new InterpreterException("Interpreter " + p.getRequiredReplName() + " not found");
}
if (p.getConfig().get("enabled") == null || (Boolean) p.getConfig().get("enabled")) {
intp.getScheduler().submit(p);
}
}
public List<String> completion(String paragraphId, String buffer, int cursor) {
Paragraph p = getParagraph(paragraphId);
p.setNoteReplLoader(replLoader);
p.setListener(jobListenerFactory.getParagraphJobListener(this));
return p.completion(buffer, cursor);
}
public List<Paragraph> getParagraphs() {
synchronized (paragraphs) {
return new LinkedList<Paragraph>(paragraphs);
}
}
private void snapshotAngularObjectRegistry() {
angularObjects = new HashMap<>();
List<InterpreterSetting> settings = replLoader.getInterpreterSettings();
if (settings == null || settings.size() == 0) {
return;
}
for (InterpreterSetting setting : settings) {
InterpreterGroup intpGroup = setting.getInterpreterGroup();
AngularObjectRegistry registry = intpGroup.getAngularObjectRegistry();
angularObjects.put(intpGroup.getId(), registry.getAllWithGlobal(id));
}
}
public void persist() throws IOException {
snapshotAngularObjectRegistry();
index.updateIndexDoc(this);
repo.save(this);
}
public void unpersist() throws IOException {
repo.remove(id());
}
public Map<String, Object> getConfig() {
if (config == null) {
config = new HashMap<>();
}
return config;
}
public void setConfig(Map<String, Object> config) {
this.config = config;
}
public Map<String, Object> getInfo() {
if (info == null) {
info = new HashMap<>();
}
return info;
}
public void setInfo(Map<String, Object> info) {
this.info = info;
}
@Override
public void beforeStatusChange(Job job, Status before, Status after) {
}
@Override
public void afterStatusChange(Job job, Status before, Status after) {
}
@Override
public void onProgressUpdate(Job job, int progress) {}
}
| HeartSaVioR/incubator-zeppelin | zeppelin-zengine/src/main/java/org/apache/zeppelin/notebook/Note.java | Java | apache-2.0 | 12,086 |
/*
* Copyright 2016 NAVER Corp.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.navercorp.pinpoint.profiler.plugin;
import java.util.ArrayList;
import java.util.List;
/**
* @author Woonduk Kang(emeroad)
*/
public class PluginPackageFilter implements ClassNameFilter {
private final List<String> packageList;
public PluginPackageFilter(List<String> packageList) {
if (packageList == null) {
throw new NullPointerException("packageList");
}
this.packageList = new ArrayList<String>(packageList);
}
@Override
public boolean accept(String className) {
for (String packageName : packageList) {
if (className.startsWith(packageName)) {
return ACCEPT;
}
}
return REJECT;
}
@Override
public String toString() {
return "PluginPackageFilter{" +
"packageList=" + packageList +
'}';
}
}
| jaehong-kim/pinpoint | profiler/src/main/java/com/navercorp/pinpoint/profiler/plugin/PluginPackageFilter.java | Java | apache-2.0 | 1,487 |
// REVU - whitebox testing of internal comps -- OK.
package redis
import (
"bytes"
"log"
"testing"
"time"
)
// REVU: nice to test timing accuracy but it isn't really necessary.
// basic test data
type tspec_ft struct {
data []byte
delay time.Duration
}
// create the test spec (test data for now)
func testspec_ft() tspec_ft {
var testspec tspec_ft
// []byte data to be used
data := "Hello there!"
testspec.data = bytes.NewBufferString(data).Bytes()
// using a timeout of 100 (msecs)
delaysecs := 100
testspec.delay = time.Duration(delaysecs) * time.Millisecond
return testspec
}
// test FutureBytes - all aspect, expect blocking Get
// are tested. A future object is created (but not set)
// and timeout and error tests are made. Then value is set
// and test repeated.
func TestFutureContract(t *testing.T) {
// prep data
tspec := testspec_ft()
// using basic FutureBytes
fb := newFutureBytes()
/* TEST timed call to uninitialized (not Set) future value,
* expecting a timeout.
* MUST return timeout of true
* MUST return error value of nil
* MUST return value of nil
*/
fvalue1, e1, timedout1 := fb.TryGet(tspec.delay)
if !timedout1 {
t.Error("BUG: timeout expected")
}
if e1 != nil {
t.Error("Bug: unexpected error %s", e1)
}
if fvalue1 != nil {
t.Error("Bug: value returned: %s", fvalue1)
}
// set the future result
fb.set(tspec.data)
/* TEST timed call to initialized (set) future value
* expecting data, no error and no timeout
* MUST return timeout of false
* MUST return error of nil
* MUST return value equal to data
*/
fvalue2, e2, timedout2 := fb.TryGet(tspec.delay)
if timedout2 {
t.Error("BUG: should not timeout")
}
if e2 != nil {
t.Error("Bug: unexpected error %s", e2)
}
if fvalue2 == nil {
t.Error("Bug: should not return future nil")
} else if bytes.Compare(fvalue2, tspec.data) != 0 {
t.Error("Bug: future value not equal to data set")
}
}
func TestFutureWithBlockingGet(t *testing.T) {
// prep data
// prep data
tspec := testspec_ft()
// using basic FutureBytes
fb := newFutureBytes()
// test go routine will block on Get until
// value is set.
sig := make(chan bool, 1)
go func() {
/* TEST timed call to initialized (set) future value
* expecting data, no error and no timeout
* MUST return error of nil
* MUST return value equal to data
*/
fvalue, e := fb.Get()
if e != nil {
t.Error("Bug: unexpected error %s", e)
}
if fvalue == nil {
t.Error("Bug: should not return future nil")
} else if bytes.Compare(fvalue, tspec.data) != 0 {
t.Error("Bug: future value not equal to data set")
}
sig <- true
}()
// set the data
fb.set(tspec.data)
<-sig
}
func TestFutureTimedBlockingGet(t *testing.T) {
// prep data
// prep data
tspec := testspec_ft()
// using basic FutureBytes
fb := newFutureBytes()
// test go routine will block on Get until
// value is set or timeout expires
sig := make(chan bool, 1)
go func() {
/* TEST timed call to initialized (set) future value
* expecting data, no error and no timeout
* MUST return error of nil
* MUST return value equal to data
*/
fvalue, e, timedout := fb.TryGet(tspec.delay)
if timedout {
t.Error("BUG: should not timeout")
}
if e != nil {
t.Error("Bug: unexpected error %s", e)
}
if fvalue == nil {
t.Error("Bug: should not return future nil")
} else if bytes.Compare(fvalue, tspec.data) != 0 {
t.Error("Bug: future value not equal to data set")
}
sig <- true
}()
// set the data
fb.set(tspec.data)
<-sig
}
func TestEnd_future(t *testing.T) {
// nop
log.Println("-- future test completed")
}
| doomalove/Go-Redis | future_test.go | GO | apache-2.0 | 3,665 |
import defaultValue from "./defaultValue.js";
import getStringFromTypedArray from "./getStringFromTypedArray.js";
/**
* @private
*/
function getMagic(uint8Array, byteOffset) {
byteOffset = defaultValue(byteOffset, 0);
return getStringFromTypedArray(
uint8Array,
byteOffset,
Math.min(4, uint8Array.length)
);
}
export default getMagic;
| progsung/cesium | Source/Core/getMagic.js | JavaScript | apache-2.0 | 356 |
/*
* Copyright 2008 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using BarcodeFormat = com.google.zxing.BarcodeFormat;
using ReaderException = com.google.zxing.ReaderException;
using Result = com.google.zxing.Result;
using BinaryBitmap = com.google.zxing.BinaryBitmap;
using BitArray = com.google.zxing.common.BitArray;
namespace com.google.zxing.oned
{
/// <summary> <p>Implements decoding of the UPC-A format.</p>
///
/// </summary>
/// <author> [email protected] (Daniel Switkin)
/// </author>
/// <author> Sean Owen
/// </author>
/// <author>www.Redivivus.in ([email protected]) - Ported from ZXING Java Source
/// </author>
public sealed class UPCAReader:UPCEANReader
{
override internal BarcodeFormat BarcodeFormat
{
get
{
return BarcodeFormat.UPC_A;
}
}
//UPGRADE_NOTE: Final was removed from the declaration of 'ean13Reader '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'"
private UPCEANReader ean13Reader = new EAN13Reader();
public override Result decodeRow(int rowNumber, BitArray row, int[] startGuardRange, System.Collections.Hashtable hints)
{
return maybeReturnResult(ean13Reader.decodeRow(rowNumber, row, startGuardRange, hints));
}
public override Result decodeRow(int rowNumber, BitArray row, System.Collections.Hashtable hints)
{
return maybeReturnResult(ean13Reader.decodeRow(rowNumber, row, hints));
}
public override Result decode(BinaryBitmap image)
{
return maybeReturnResult(ean13Reader.decode(image));
}
public override Result decode(BinaryBitmap image, System.Collections.Hashtable hints)
{
return maybeReturnResult(ean13Reader.decode(image, hints));
}
protected internal override int decodeMiddle(BitArray row, int[] startRange, System.Text.StringBuilder resultString)
{
return ean13Reader.decodeMiddle(row, startRange, resultString);
}
private static Result maybeReturnResult(Result result)
{
System.String text = result.Text;
if (text[0] == '0')
{
return new Result(text.Substring(1), null, result.ResultPoints, BarcodeFormat.UPC_A);
}
else
{
throw ReaderException.Instance;
}
}
}
} | tupunco/ZXing-CSharp | zxing-csharp/oned/UPCAReader.cs | C# | apache-2.0 | 2,765 |
/*
* Copyright (c) 2008-2018, Hazelcast, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hazelcast.client.cache.jsr;
import com.hazelcast.test.HazelcastSerialClassRunner;
import com.hazelcast.test.annotation.QuickTest;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;
@RunWith(HazelcastSerialClassRunner.class)
@Category(QuickTest.class)
public class CacheEntryListenerClientServerTest extends org.jsr107.tck.event.CacheEntryListenerClientServerTest {
@BeforeClass
public static void setupInstance() {
JsrClientTestUtil.setupWithHazelcastInstance();
}
@AfterClass
public static void cleanup() {
JsrClientTestUtil.cleanup();
}
}
| tufangorel/hazelcast | hazelcast-client/src/test/java/com/hazelcast/client/cache/jsr/CacheEntryListenerClientServerTest.java | Java | apache-2.0 | 1,316 |
/*
* Copyright 2012 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.optaplanner.core.impl.score.director.incremental;
import org.optaplanner.core.api.domain.entity.PlanningEntity;
import org.optaplanner.core.api.domain.solution.PlanningSolution;
import org.optaplanner.core.api.domain.variable.PlanningVariable;
import org.optaplanner.core.api.score.Score;
import org.optaplanner.core.impl.heuristic.move.Move;
import org.optaplanner.core.impl.score.director.easy.EasyScoreCalculator;
/**
* Used for incremental java {@link Score} calculation.
* This is much faster than {@link EasyScoreCalculator} but requires much more code to implement too.
* <p>
* Any implementation is naturally stateful.
* @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation
* @see IncrementalScoreDirector
*/
public interface IncrementalScoreCalculator<Solution_> {
/**
* There are no {@link #beforeEntityAdded(Object)} and {@link #afterEntityAdded(Object)} calls
* for entities that are already present in the workingSolution.
* @param workingSolution never null
*/
void resetWorkingSolution(Solution_ workingSolution);
/**
* @param entity never null, an instance of a {@link PlanningEntity} class
*/
void beforeEntityAdded(Object entity);
/**
* @param entity never null, an instance of a {@link PlanningEntity} class
*/
void afterEntityAdded(Object entity);
/**
* @param entity never null, an instance of a {@link PlanningEntity} class
* @param variableName never null, either a genuine or shadow {@link PlanningVariable}
*/
void beforeVariableChanged(Object entity, String variableName);
/**
* @param entity never null, an instance of a {@link PlanningEntity} class
* @param variableName never null, either a genuine or shadow {@link PlanningVariable}
*/
void afterVariableChanged(Object entity, String variableName);
/**
* @param entity never null, an instance of a {@link PlanningEntity} class
*/
void beforeEntityRemoved(Object entity);
/**
* @param entity never null, an instance of a {@link PlanningEntity} class
*/
void afterEntityRemoved(Object entity);
/**
* This method is only called if the {@link Score} cannot be predicted.
* The {@link Score} can be predicted for example after an undo {@link Move}.
* @return never null
*/
Score calculateScore();
}
| baldimir/optaplanner | optaplanner-core/src/main/java/org/optaplanner/core/impl/score/director/incremental/IncrementalScoreCalculator.java | Java | apache-2.0 | 3,039 |
/*
* $Id: NameTable.java,v 1.4 2009-02-12 13:53:57 tomoke Exp $
*
* Copyright 2004 Sun Microsystems, Inc., 4150 Network Circle,
* Santa Clara, California 95054, U.S.A. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
package com.sun.pdfview.font.ttf;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.util.*;
/**
*
* @author jon
*/
public class NameTable extends TrueTypeTable {
/**
* Values for platformID
*/
public static final short PLATFORMID_UNICODE = 0;
public static final short PLATFORMID_MACINTOSH = 1;
public static final short PLATFORMID_MICROSOFT = 3;
/**
* Values for platformSpecificID if platform is Mac
*/
public static final short ENCODINGID_MAC_ROMAN = 0;
/**
* Values for platformSpecificID if platform is Unicode
*/
public static final short ENCODINGID_UNICODE_DEFAULT = 0;
public static final short ENCODINGID_UNICODE_V11 = 1;
public static final short ENCODINGID_UNICODE_V2 = 3;
/**
* Values for language ID if platform is Mac
*/
public static final short LANGUAGEID_MAC_ENGLISH = 0;
/**
* Values for nameID
*/
public static final short NAMEID_COPYRIGHT = 0;
public static final short NAMEID_FAMILY = 1;
public static final short NAMEID_SUBFAMILY = 2;
public static final short NAMEID_SUBFAMILY_UNIQUE = 3;
public static final short NAMEID_FULL_NAME = 4;
public static final short NAMEID_VERSION = 5;
public static final short NAMEID_POSTSCRIPT_NAME = 6;
public static final short NAMEID_TRADEMARK = 7;
/**
* The format of this table
*/
private short format;
/**
* The actual name records
*/
private SortedMap<NameRecord,String> records;
/** Creates a new instance of NameTable */
protected NameTable() {
super (TrueTypeTable.NAME_TABLE);
records = Collections.synchronizedSortedMap(new TreeMap<NameRecord,String>());
}
/**
* Add a record to the table
*/
public void addRecord(short platformID, short platformSpecificID,
short languageID, short nameID,
String value) {
NameRecord rec = new NameRecord(platformID, platformSpecificID,
languageID, nameID);
records.put(rec, value);
}
/**
* Get a record from the table
*/
public String getRecord(short platformID, short platformSpecificID,
short languageID, short nameID) {
NameRecord rec = new NameRecord(platformID, platformSpecificID,
languageID, nameID);
return (String) records.get(rec);
}
/**
* Remove a record from the table
*/
public void removeRecord(short platformID, short platformSpecificID,
short languageID, short nameID) {
NameRecord rec = new NameRecord(platformID, platformSpecificID,
languageID, nameID);
records.remove(rec);
}
/**
* Determine if we have any records with a given platform ID
*/
public boolean hasRecords(short platformID) {
for (Iterator i = records.keySet().iterator(); i.hasNext(); ) {
NameRecord rec = (NameRecord) i.next();
if (rec.platformID == platformID) {
return true;
}
}
return false;
}
/**
* Determine if we have any records with a given platform ID and
* platform-specific ID
*/
public boolean hasRecords(short platformID, short platformSpecificID) {
for (Iterator i = records.keySet().iterator(); i.hasNext(); ) {
NameRecord rec = (NameRecord) i.next();
if (rec.platformID == platformID &&
rec.platformSpecificID == platformSpecificID) {
return true;
}
}
return false;
}
/**
* Read the table from data
*/
public void setData(ByteBuffer data) {
//read table header
setFormat(data.getShort());
int count = data.getShort();
int stringOffset = data.getShort();
// read the records
for (int i = 0; i < count; i++) {
short platformID = data.getShort();
short platformSpecificID = data.getShort();
short languageID = data.getShort();
short nameID = data.getShort();
int length = data.getShort() & 0xFFFF;
int offset = data.getShort() & 0xFFFF;
// read the String data
data.mark();
data.position(stringOffset + offset);
ByteBuffer stringBuf = data.slice();
stringBuf.limit(length);
data.reset();
// choose the character set
String charsetName = getCharsetName(platformID, platformSpecificID);
Charset charset = Charset.forName(charsetName);
// parse the data as a string
String value = charset.decode(stringBuf).toString();
// add to the mix
addRecord(platformID, platformSpecificID, languageID, nameID, value);
}
}
/**
* Get the data in this table as a buffer
*/
public ByteBuffer getData() {
// alocate the output buffer
ByteBuffer buf = ByteBuffer.allocate(getLength());
// the start of string data
short headerLength = (short) (6 + (12 * getCount()));
// write the header
buf.putShort(getFormat());
buf.putShort(getCount());
buf.putShort(headerLength);
// the offset from the start of the strings table
short curOffset = 0;
// add the size of each record
for (Iterator i = records.keySet().iterator(); i.hasNext();) {
NameRecord rec = (NameRecord) i.next();
String value = (String) records.get(rec);
// choose the charset
String charsetName = getCharsetName(rec.platformID,
rec.platformSpecificID);
Charset charset = Charset.forName(charsetName);
// encode
ByteBuffer strBuf = charset.encode(value);
short strLen = (short) (strBuf.remaining() & 0xFFFF);
// write the IDs
buf.putShort(rec.platformID);
buf.putShort(rec.platformSpecificID);
buf.putShort(rec.languageID);
buf.putShort(rec.nameID);
// write the size and offset
buf.putShort(strLen);
buf.putShort(curOffset);
// remember or current position
buf.mark();
// move to the current offset and write the data
buf.position(headerLength + curOffset);
buf.put(strBuf);
// reset stuff
buf.reset();
// increment offset
curOffset += strLen;
}
// reset the pointer on the buffer
buf.position(headerLength + curOffset);
buf.flip();
return buf;
}
/**
* Get the length of this table
*/
public int getLength() {
// start with the size of the fixed header plus the size of the
// records
int length = 6 + (12 * getCount());
// add the size of each record
for (Iterator i = records.keySet().iterator(); i.hasNext();) {
NameRecord rec = (NameRecord) i.next();
String value = (String) records.get(rec);
// choose the charset
String charsetName = getCharsetName(rec.platformID,
rec.platformSpecificID);
Charset charset = Charset.forName(charsetName);
// encode
ByteBuffer buf = charset.encode(value);
// add the size of the coded buffer
length += buf.remaining();
}
return length;
}
/**
* Get the format of this table
*/
public short getFormat() {
return format;
}
/**
* Set the format of this table
*/
public void setFormat(short format) {
this.format = format;
}
/**
* Get the number of records in the table
*/
public short getCount() {
return (short) records.size();
}
/**
* Get the charset name for a given platform, encoding and language
*/
public static String getCharsetName(int platformID, int encodingID) {
String charset = "US-ASCII";
switch (platformID) {
case PLATFORMID_UNICODE:
charset = "UTF-16";
break;
case PLATFORMID_MICROSOFT:
charset = "UTF-16";
break;
}
return charset;
}
public Collection<String> getNames()
{
return Collections.unmodifiableCollection(records.values());
}
/** Get a pretty string */
public String toString() {
StringBuffer buf = new StringBuffer();
String indent = " ";
buf.append(indent + "Format: " + getFormat() + "\n");
buf.append(indent + "Count : " + getCount() + "\n");
for (Iterator i = records.keySet().iterator(); i.hasNext();) {
NameRecord rec = (NameRecord) i.next();
buf.append(indent + " platformID: " + rec.platformID);
buf.append(" platformSpecificID: " + rec.platformSpecificID);
buf.append(" languageID: " + rec.languageID);
buf.append(" nameID: " + rec.nameID + "\n");
buf.append(indent + " " + records.get(rec) + "\n");
}
return buf.toString();
}
/**
* A class to hold the data associated with each record
*/
class NameRecord implements Comparable {
/**
* Platform ID
*/
short platformID;
/**
* Platform Specific ID (Encoding)
*/
short platformSpecificID;
/**
* Language ID
*/
short languageID;
/**
* Name ID
*/
short nameID;
/**
* Create a new record
*/
NameRecord(short platformID, short platformSpecificID,
short languageID, short nameID) {
this.platformID = platformID;
this.platformSpecificID = platformSpecificID;
this.languageID = languageID;
this.nameID = nameID;
}
/**
* Compare two records
*/
public boolean equals(Object o) {
return (compareTo(o) == 0);
}
/**
* Compare two records
*/
public int compareTo(Object obj) {
if (!(obj instanceof NameRecord)) {
return -1;
}
NameRecord rec = (NameRecord) obj;
if (platformID > rec.platformID) {
return 1;
} else if (platformID < rec.platformID) {
return -1;
} else if (platformSpecificID > rec.platformSpecificID) {
return 1;
} else if (platformSpecificID < rec.platformSpecificID) {
return -1;
} else if (languageID > rec.languageID) {
return 1;
} else if (languageID < rec.languageID) {
return -1;
} else if (nameID > rec.nameID) {
return 1;
} else if (nameID < rec.nameID) {
return -1;
} else {
return 0;
}
}
}
}
| manusa/mnPrintClient | src/main/java/com/sun/pdfview/font/ttf/NameTable.java | Java | apache-2.0 | 12,963 |
/**
* Copyright 2005-2016 Red Hat, Inc.
*
* Red Hat licenses this file to you under the Apache License, version
* 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package io.fabric8.api.gravia;
/**
* A {@link PropertiesProvider} that is backed by System Properties.
*/
public class SystemPropertiesProvider extends AbstractPropertiesProvider {
@Override
public Object getProperty(String key, Object defaultValue) {
String value = SecurityActions.getSystemProperty(key, null);
return value != null ? value : defaultValue;
}
}
| jludvice/fabric8 | fabric/fabric-api/src/main/java/io/fabric8/api/gravia/SystemPropertiesProvider.java | Java | apache-2.0 | 1,034 |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Ivony.Fluent;
namespace Ivony.Html.Binding
{
/// <summary>
/// 处理{eval-list xxx}绑定表达式的绑定器
/// </summary>
public class EvalListExpressionBinder : EvalExpressionBinder, IExpressionBinder
{
string IExpressionBinder.ExpressionName
{
get { return "eval-list"; }
}
object IExpressionBinder.GetValue( HtmlBindingContext context, BindingExpression expression )
{
var dataModel = GetDataObject( context, expression );
if ( dataModel == null )
return null;
CssElementSelector elementSelector = null;
string selector;
if ( expression.TryGetValue( context, "selector", out selector ) )
elementSelector = CssParser.ParseElementSelector( selector );
ListBindingMode mode;
string modeSetting;
if ( expression.TryGetValue( context, "mode", out modeSetting ) && modeSetting.EqualsIgnoreCase( "static" ) )
mode = ListBindingMode.StaticContent;
else
mode = ListBindingMode.DynamicContent;
return new ListDataModel( (IEnumerable) dataModel, elementSelector, mode );
}
}
}
| yonglehou/Jumony | Ivony.Html.Binding/EvalListExpressionBinder.cs | C# | apache-2.0 | 1,253 |
/**
* Copyright 2005-2016 Red Hat, Inc.
*
* Red Hat licenses this file to you under the Apache License, version
* 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package io.fabric8.camel;
import java.io.IOException;
import java.net.URI;
import java.util.List;
import java.util.Map;
import io.fabric8.groups.Group;
import io.fabric8.groups.GroupListener;
import org.apache.curator.framework.CuratorFramework;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.junit.Assert.assertThat;
public class FabricPublisherEndpointOpenShiftTest {
private FabricPublisherEndpoint endpoint;
private String karafName;
@Before
public void init() throws Exception {
karafName = System.setProperty("karaf.name", "root");
FabricComponent component = new FabricComponent() {
@Override
public CuratorFramework getCurator() {
return null;
}
@Override
public Group<CamelNodeState> createGroup(String path) {
return new Group<CamelNodeState>() {
@Override
public boolean isConnected() {
return false;
}
@Override
public void start() {
}
@Override
public void close() throws IOException {
}
@Override
public void add(GroupListener<CamelNodeState> listener) {
}
@Override
public void remove(GroupListener<CamelNodeState> listener) {
}
@Override
public void update(CamelNodeState state) {
}
@Override
public Map<String, CamelNodeState> members() {
return null;
}
@Override
public boolean isMaster() {
return false;
}
@Override
public CamelNodeState master() {
return null;
}
@Override
public List<CamelNodeState> slaves() {
return null;
}
@Override
public CamelNodeState getLastState() {
return null;
}
};
}
};
endpoint = new FabricPublisherEndpoint("http://localhost", component, null, "child") {
@Override
protected int publicPort(URI uri) {
return uri.getPort() + 42;
}
};
}
@After
public void cleanup() {
if (karafName != null) {
System.setProperty("karaf.name", karafName);
}
}
@Test
public void testPortMapping() throws Exception {
assertThat(endpoint.toPublicAddress("http:jetty://localhost:1/x/y?a=b&c=d"), equalTo("http:jetty://localhost:43/x/y?a=b&c=d"));
assertThat(endpoint.toPublicAddress("http:jetty:a:b://localhost:1/x/y?a=b"), equalTo("http:jetty:a:b://localhost:43/x/y?a=b"));
assertThat(endpoint.toPublicAddress("http://localhost:1"), equalTo("http://localhost:43"));
}
}
| jludvice/fabric8 | fabric/fabric-camel/src/test/java/io/fabric8/camel/FabricPublisherEndpointOpenShiftTest.java | Java | apache-2.0 | 3,961 |
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/**
* Created by janomar on 23/07/15.
*/
$(document).ready(function () {
var config = {
jdbc: {
hidden_fields: ['port', 'schema', 'extra'],
relabeling: {'host': 'Connection URL'},
},
google_cloud_platform: {
hidden_fields: ['host', 'schema', 'login', 'password', 'port', 'extra'],
relabeling: {},
},
cloudant: {
hidden_fields: ['port', 'extra'],
relabeling: {
'host': 'Account',
'login': 'Username (or API Key)',
'schema': 'Database'
}
},
docker: {
hidden_fields: ['port', 'schema'],
relabeling: {
'host': 'Registry URL',
'login': 'Username',
},
},
qubole: {
hidden_fields: ['login', 'schema', 'port', 'extra'],
relabeling: {
'host': 'API Endpoint',
'password': 'Auth Token',
},
placeholders: {
'host': 'https://<env>.qubole.com/api'
}
},
ssh: {
hidden_fields: ['schema'],
relabeling: {
'login': 'Username',
}
},
};
function connTypeChange(connectionType) {
$(".hide").removeClass("hide");
$.each($("[id^='extra__']"), function () {
$(this).parent().parent().addClass('hide')
});
$.each($("[id^='extra__" + connectionType + "']"), function () {
$(this).parent().parent().removeClass('hide')
});
$("label[orig_text]").each(function () {
$(this).text($(this).attr("orig_text"));
});
$(".form-control").each(function(){$(this).attr('placeholder', '')});
if (config[connectionType] != undefined) {
$.each(config[connectionType].hidden_fields, function (i, field) {
$("#" + field).parent().parent().addClass('hide')
});
$.each(config[connectionType].relabeling, function (k, v) {
lbl = $("label[for='" + k + "']");
lbl.attr("orig_text", lbl.text());
$("label[for='" + k + "']").text(v);
});
$.each(config[connectionType].placeholders, function(k, v){
$("#" + k).attr('placeholder', v);
});
}
}
var connectionType = $("#conn_type").val();
$("#conn_type").on('change', function (e) {
connectionType = $("#conn_type").val();
connTypeChange(connectionType);
});
connTypeChange(connectionType);
});
| adamhaney/airflow | airflow/www/static/js/connection_form.js | JavaScript | apache-2.0 | 3,085 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!--NewPage-->
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.6.0_07) on Fri Feb 19 08:08:02 UTC 2010 -->
<TITLE>
org.apache.hadoop.filecache (Hadoop 0.20.2 API)
</TITLE>
<META NAME="date" CONTENT="2010-02-19">
<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="org.apache.hadoop.filecache (Hadoop 0.20.2 API)";
}
}
</SCRIPT>
<NOSCRIPT>
</NOSCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<HR>
<!-- ========= START OF TOP NAVBAR ======= -->
<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> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Package</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-use.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../org/apache/hadoop/examples/terasort/package-summary.html"><B>PREV PACKAGE</B></A>
<A HREF="../../../../org/apache/hadoop/fs/package-summary.html"><B>NEXT PACKAGE</B></A></FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../index.html?org/apache/hadoop/filecache/package-summary.html" target="_top"><B>FRAMES</B></A>
<A HREF="package-summary.html" target="_top"><B>NO FRAMES</B></A>
<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>
</TABLE>
<A NAME="skip-navbar_top"></A>
<!-- ========= END OF TOP NAVBAR ========= -->
<HR>
<H2>
Package org.apache.hadoop.filecache
</H2>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
<B>Class Summary</B></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD WIDTH="15%"><B><A HREF="../../../../org/apache/hadoop/filecache/DistributedCache.html" title="class in org.apache.hadoop.filecache">DistributedCache</A></B></TD>
<TD>Distribute application-specific large, read-only files efficiently.</TD>
</TR>
</TABLE>
<P>
<DL>
</DL>
<HR>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<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="navbar_bottom_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> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Package</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-use.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../org/apache/hadoop/examples/terasort/package-summary.html"><B>PREV PACKAGE</B></A>
<A HREF="../../../../org/apache/hadoop/fs/package-summary.html"><B>NEXT PACKAGE</B></A></FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../index.html?org/apache/hadoop/filecache/package-summary.html" target="_top"><B>FRAMES</B></A>
<A HREF="package-summary.html" target="_top"><B>NO FRAMES</B></A>
<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>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<HR>
Copyright © 2009 The Apache Software Foundation
</BODY>
</HTML>
| totemtang/hadoop-RHJoin | docs/api/org/apache/hadoop/filecache/package-summary.html | HTML | apache-2.0 | 6,427 |
/**
* (C) Copyright IBM Corp. 2010, 2015
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.ibm.bi.dml.runtime.instructions.cp;
import com.ibm.bi.dml.lops.MMTSJ.MMTSJType;
import com.ibm.bi.dml.parser.Expression.DataType;
import com.ibm.bi.dml.parser.Expression.ValueType;
import com.ibm.bi.dml.runtime.DMLRuntimeException;
import com.ibm.bi.dml.runtime.DMLUnsupportedOperationException;
import com.ibm.bi.dml.runtime.controlprogram.context.ExecutionContext;
import com.ibm.bi.dml.runtime.instructions.Instruction;
import com.ibm.bi.dml.runtime.instructions.InstructionUtils;
import com.ibm.bi.dml.runtime.matrix.data.MatrixBlock;
import com.ibm.bi.dml.runtime.matrix.operators.Operator;
/**
*
*
*/
public class MMTSJCPInstruction extends UnaryCPInstruction
{
private MMTSJType _type = null;
private int _numThreads = 1;
public MMTSJCPInstruction(Operator op, CPOperand in1, MMTSJType type, CPOperand out, int k, String opcode, String istr)
{
super(op, in1, out, opcode, istr);
_cptype = CPINSTRUCTION_TYPE.MMTSJ;
_type = type;
_numThreads = k;
}
/**
*
* @param str
* @return
* @throws DMLRuntimeException
*/
public static Instruction parseInstruction ( String str )
throws DMLRuntimeException
{
CPOperand in1 = new CPOperand("", ValueType.UNKNOWN, DataType.UNKNOWN);
CPOperand out = new CPOperand("", ValueType.UNKNOWN, DataType.UNKNOWN);
InstructionUtils.checkNumFields ( str, 4 );
String[] parts = InstructionUtils.getInstructionPartsWithValueType(str);
String opcode = parts[0];
in1.split(parts[1]);
out.split(parts[2]);
MMTSJType titype = MMTSJType.valueOf(parts[3]);
int k = Integer.parseInt(parts[4]);
if(!opcode.equalsIgnoreCase("tsmm"))
throw new DMLRuntimeException("Unknown opcode while parsing an MMTSJCPInstruction: " + str);
else
return new MMTSJCPInstruction(new Operator(true), in1, titype, out, k, opcode, str);
}
@Override
public void processInstruction(ExecutionContext ec)
throws DMLUnsupportedOperationException, DMLRuntimeException
{
//get inputs
MatrixBlock matBlock1 = ec.getMatrixInput(input1.getName());
//execute operations
MatrixBlock ret = (MatrixBlock) matBlock1.transposeSelfMatrixMultOperations(new MatrixBlock(), _type, _numThreads );
//set output and release inputs
ec.setMatrixOutput(output.getName(), ret);
ec.releaseMatrixInput(input1.getName());
}
public MMTSJType getMMTSJType()
{
return _type;
}
}
| wjuncdl/systemml | system-ml/src/main/java/com/ibm/bi/dml/runtime/instructions/cp/MMTSJCPInstruction.java | Java | apache-2.0 | 2,986 |
/*
* Copyright (C) 2012 www.amsoft.cn
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ab.view.pullview;
import android.util.SparseArray;
import android.view.View;
import android.view.ViewDebug;
// TODO: Auto-generated Javadoc
/**
* The Class AbViewInfo.
*/
public class AbViewInfo {
/** The view. */
private View view;
/** The width. */
private int width;
/** The height. */
private int height;
/** The top. */
private int top;
/** The bottom. */
private int bottom;
/** The tag. */
private Object tag;
/** The tag. */
private int visible;
/**
* Map used to store views' tags.
*/
private SparseArray<Object> keyedTags;
/**
* Instantiates a new ab view info.
*
* @param view the view
* @param width the width
* @param height the height
* @param top the top
* @param bottom the bottom
*/
public AbViewInfo(View view, int width, int height, int top, int bottom) {
super();
this.view = view;
this.width = width;
this.height = height;
this.top = top;
this.bottom = bottom;
}
/**
* Instantiates a new ab view info.
*
* @param view the view
* @param width the width
* @param height the height
*/
public AbViewInfo(View view, int width, int height) {
super();
this.view = view;
this.width = width;
this.height = height;
}
/**
* Instantiates a new ab view info.
*
* @param view the view
*/
public AbViewInfo(View view) {
super();
this.view = view;
}
/**
* Gets the view.
*
* @return the view
*/
public View getView() {
return view;
}
/**
* Sets the view.
*
* @param view the new view
*/
public void setView(View view) {
this.view = view;
}
/**
* Gets the width.
*
* @return the width
*/
public int getWidth() {
return width;
}
/**
* Sets the width.
*
* @param width the new width
*/
public void setWidth(int width) {
this.width = width;
}
/**
* Gets the height.
*
* @return the height
*/
public int getHeight() {
return height;
}
/**
* Sets the height.
*
* @param height the new height
*/
public void setHeight(int height) {
this.height = height;
}
/**
* Gets the top.
*
* @return the top
*/
public int getTop() {
return top;
}
/**
* Sets the top.
*
* @param top the new top
*/
public void setTop(int top) {
this.top = top;
}
/**
* Gets the bottom.
*
* @return the bottom
*/
public int getBottom() {
return bottom;
}
/**
* Sets the bottom.
*
* @param bottom the new bottom
*/
public void setBottom(int bottom) {
this.bottom = bottom;
}
/**
* Gets the tag.
*
* @return the tag
*/
@ViewDebug.ExportedProperty
public Object getTag() {
return tag;
}
/**
* Sets the tag.
*
* @param tag the new tag
*/
public void setTag(final Object tag) {
this.tag = tag;
}
/**
* Gets the tag.
*
* @param key the key
* @return the tag
*/
public Object getTag(int key) {
if (keyedTags != null) return keyedTags.get(key);
return null;
}
/**
* Sets the tag.
*
* @param key the key
* @param tag the tag
*/
public void setTag(int key, final Object tag) {
// If the package id is 0x00 or 0x01, it's either an undefined package
// or a framework id
if ((key >>> 24) < 2) {
throw new IllegalArgumentException("The key must be an application-specific "
+ "resource id.");
}
setKeyedTag(key, tag);
}
/**
* Sets the keyed tag.
*
* @param key the key
* @param tag the tag
*/
private void setKeyedTag(int key, Object tag) {
if (keyedTags == null) {
keyedTags = new SparseArray<Object>();
}
keyedTags.put(key, tag);
}
/**
* Gets the visible.
*
* @return the visible
*/
public int getVisible() {
return visible;
}
/**
* Sets the visible.
*
* @param visible the new visible
*/
public void setVisible(int visible) {
this.visible = visible;
}
}
| yangyunfeng666/AndBase | src/com/ab/view/pullview/AbViewInfo.java | Java | apache-2.0 | 4,654 |
package eightyDays.java;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
public class Bank {
final private String name;
private Map<UUID, Person> persons = new HashMap<>();
public String getName() {
return name;
}
public Bank(String pName) {
name = pName;
}
public UUID addPartner(Person pPerson) {
return persons.entrySet().stream()
.filter(entry -> entry.getValue().equals(pPerson))
.findFirst()
.map(Map.Entry::getKey)
.orElseGet(() -> {
UUID newID = UUID.randomUUID();
persons.put(newID, pPerson);
return newID;
});
}
public Optional<Person> getPerson(UUID pId) {
return Optional.ofNullable(persons.get(pId));
}
}
| finnoop/oop2017 | steps/7/main/java/eightyDays/java/Bank.java | Java | apache-2.0 | 886 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.hive.metastore;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Stack;
import org.apache.hadoop.hive.conf.HiveConf;
import org.apache.hadoop.hive.metastore.api.Database;
import org.apache.hadoop.hive.metastore.api.FieldSchema;
import org.apache.hadoop.hive.metastore.api.InvalidOperationException;
import org.apache.hadoop.hive.metastore.api.MetaException;
import org.apache.hadoop.hive.metastore.api.NoSuchObjectException;
import org.apache.hadoop.hive.metastore.api.Order;
import org.apache.hadoop.hive.metastore.api.Partition;
import org.apache.hadoop.hive.metastore.api.PartitionSpec;
import org.apache.hadoop.hive.metastore.api.PartitionsByExprRequest;
import org.apache.hadoop.hive.metastore.api.SerDeInfo;
import org.apache.hadoop.hive.metastore.api.StorageDescriptor;
import org.apache.hadoop.hive.metastore.api.Table;
import org.apache.hadoop.hive.ql.exec.FunctionRegistry;
import org.apache.hadoop.hive.ql.exec.SerializationUtilities;
import org.apache.hadoop.hive.ql.io.HiveInputFormat;
import org.apache.hadoop.hive.ql.io.HiveOutputFormat;
import org.apache.hadoop.hive.ql.plan.ExprNodeColumnDesc;
import org.apache.hadoop.hive.ql.plan.ExprNodeConstantDesc;
import org.apache.hadoop.hive.ql.plan.ExprNodeDesc;
import org.apache.hadoop.hive.ql.plan.ExprNodeGenericFuncDesc;
import org.apache.hadoop.hive.serde.serdeConstants;
import org.apache.hadoop.hive.serde2.lazy.LazySimpleSerDe;
import org.apache.hadoop.hive.serde2.typeinfo.TypeInfo;
import org.apache.hadoop.hive.serde2.typeinfo.TypeInfoFactory;
import org.apache.hadoop.util.StringUtils;
import org.apache.thrift.TException;
import com.google.common.collect.Lists;
import static org.junit.Assert.fail;
import static org.junit.Assert.assertEquals;
import org.junit.Before;
import org.junit.After;
import org.junit.Test;
/**
* Tests hive metastore expression support. This should be moved in metastore module
* as soon as we are able to use ql from metastore server (requires splitting metastore
* server and client).
* This is a "companion" test to test to TestHiveMetaStore#testPartitionFilter; thus,
* it doesn't test all the edge cases of the filter (if classes were merged, perhaps the
* filter test could be rolled into it); assumption is that they use the same path in SQL/JDO.
*/
public class TestMetastoreExpr {
protected static HiveMetaStoreClient client;
@After
public void tearDown() throws Exception {
try {
client.close();
} catch (Throwable e) {
System.err.println("Unable to close metastore");
System.err.println(StringUtils.stringifyException(e));
throw new Exception(e);
}
}
@Before
public void setUp() throws Exception {
try {
client = new HiveMetaStoreClient(new HiveConf(this.getClass()));
} catch (Throwable e) {
System.err.println("Unable to open the metastore");
System.err.println(StringUtils.stringifyException(e));
throw new Exception(e);
}
}
private static void silentDropDatabase(String dbName) throws TException {
try {
for (String tableName : client.getTables(dbName, "*")) {
client.dropTable(dbName, tableName);
}
client.dropDatabase(dbName);
} catch (NoSuchObjectException|MetaException ignore) {
} catch (InvalidOperationException ignore) {
}
}
@Test
public void testPartitionExpr() throws Exception {
String dbName = "filterdb";
String tblName = "filtertbl";
silentDropDatabase(dbName);
Database db = new Database();
db.setName(dbName);
client.createDatabase(db);
ArrayList<FieldSchema> cols = new ArrayList<FieldSchema>(2);
cols.add(new FieldSchema("c1", serdeConstants.STRING_TYPE_NAME, ""));
cols.add(new FieldSchema("c2", serdeConstants.INT_TYPE_NAME, ""));
ArrayList<FieldSchema> partCols = Lists.newArrayList(
new FieldSchema("p1", serdeConstants.STRING_TYPE_NAME, ""),
new FieldSchema("p2", serdeConstants.INT_TYPE_NAME, ""));
Table tbl = new Table();
tbl.setDbName(dbName);
tbl.setTableName(tblName);
addSd(cols, tbl);
tbl.setPartitionKeys(partCols);
client.createTable(tbl);
tbl = client.getTable(dbName, tblName);
addPartition(client, tbl, Lists.newArrayList("p11", "32"), "part1");
addPartition(client, tbl, Lists.newArrayList("p12", "32"), "part2");
addPartition(client, tbl, Lists.newArrayList("p13", "31"), "part3");
addPartition(client, tbl, Lists.newArrayList("p14", "-33"), "part4");
ExprBuilder e = new ExprBuilder(tblName);
checkExpr(3, dbName, tblName, e.val(0).intCol("p2").pred(">", 2).build(), tbl);
checkExpr(3, dbName, tblName, e.intCol("p2").val(0).pred("<", 2).build(), tbl);
checkExpr(1, dbName, tblName, e.intCol("p2").val(0).pred(">", 2).build(), tbl);
checkExpr(2, dbName, tblName, e.val(31).intCol("p2").pred("<=", 2).build(), tbl);
checkExpr(3, dbName, tblName, e.val("p11").strCol("p1").pred(">", 2).build(), tbl);
checkExpr(1, dbName, tblName, e.val("p11").strCol("p1").pred(">", 2)
.intCol("p2").val(31).pred("<", 2).pred("and", 2).build(), tbl);
checkExpr(3, dbName, tblName,
e.val(32).val(31).intCol("p2").val(false).pred("between", 4).build(), tbl);
addPartition(client, tbl, Lists.newArrayList("__HIVE_DEFAULT_PARTITION__", "36"), "part5");
addPartition(client, tbl, Lists.newArrayList("p16", "__HIVE_DEFAULT_PARTITION__"), "part6");
// Apply isnull and instr (not supported by pushdown) via name filtering.
checkExpr(5, dbName, tblName, e.val("p").strCol("p1")
.fn("instr", TypeInfoFactory.intTypeInfo, 2).val(0).pred("<=", 2).build(), tbl);
checkExpr(1, dbName, tblName, e.intCol("p2").pred("isnull", 1).build(), tbl);
checkExpr(1, dbName, tblName, e.val("__HIVE_DEFAULT_PARTITION__").intCol("p2").pred("=", 2).build(), tbl);
checkExpr(5, dbName, tblName, e.intCol("p1").pred("isnotnull", 1).build(), tbl);
checkExpr(5, dbName, tblName, e.val("__HIVE_DEFAULT_PARTITION__").strCol("p1").pred("!=", 2).build(), tbl);
// Cannot deserialize => throw the specific exception.
try {
client.listPartitionsByExpr(dbName, tblName,
new byte[] { 'f', 'o', 'o' }, null, (short)-1, new ArrayList<Partition>());
fail("Should have thrown IncompatibleMetastoreException");
} catch (IMetaStoreClient.IncompatibleMetastoreException ignore) {
}
// Invalid expression => throw some exception, but not incompatible metastore.
try {
checkExpr(-1, dbName, tblName, e.val(31).intCol("p3").pred(">", 2).build(), tbl);
fail("Should have thrown");
} catch (IMetaStoreClient.IncompatibleMetastoreException ignore) {
fail("Should not have thrown IncompatibleMetastoreException");
} catch (Exception ignore) {
}
}
public void checkExpr(int numParts,
String dbName, String tblName, ExprNodeGenericFuncDesc expr, Table t) throws Exception {
List<Partition> parts = new ArrayList<Partition>();
client.listPartitionsByExpr(dbName, tblName,
SerializationUtilities.serializeExpressionToKryo(expr), null, (short)-1, parts);
assertEquals("Partition check failed: " + expr.getExprString(), numParts, parts.size());
// check with partition spec as well
PartitionsByExprRequest req = new PartitionsByExprRequest(dbName, tblName,
ByteBuffer.wrap(SerializationUtilities.serializeExpressionToKryo(expr)));
req.setMaxParts((short)-1);
req.setId(t.getId());
List<PartitionSpec> partSpec = new ArrayList<>();
client.listPartitionsSpecByExpr(req, partSpec);
int partSpecSize = 0;
if(!partSpec.isEmpty()) {
partSpecSize = partSpec.iterator().next().getSharedSDPartitionSpec().getPartitionsSize();
}
assertEquals("Partition Spec check failed: " + expr.getExprString(), numParts, partSpecSize);
}
/**
* Helper class for building an expression.
*/
public static class ExprBuilder {
private final String tblName;
private final Stack<ExprNodeDesc> stack = new Stack<ExprNodeDesc>();
public ExprBuilder(String tblName) {
this.tblName = tblName;
}
public ExprNodeGenericFuncDesc build() throws Exception {
if (stack.size() != 1) {
throw new Exception("Bad test: " + stack.size());
}
return (ExprNodeGenericFuncDesc)stack.pop();
}
public ExprBuilder pred(String name, int args) throws Exception {
return fn(name, TypeInfoFactory.booleanTypeInfo, args);
}
private ExprBuilder fn(String name, TypeInfo ti, int args) throws Exception {
List<ExprNodeDesc> children = new ArrayList<ExprNodeDesc>();
for (int i = 0; i < args; ++i) {
children.add(stack.pop());
}
stack.push(new ExprNodeGenericFuncDesc(ti,
FunctionRegistry.getFunctionInfo(name).getGenericUDF(), children));
return this;
}
public ExprBuilder strCol(String col) {
return colInternal(TypeInfoFactory.stringTypeInfo, col, true);
}
public ExprBuilder intCol(String col) {
return colInternal(TypeInfoFactory.intTypeInfo, col, true);
}
private ExprBuilder colInternal(TypeInfo ti, String col, boolean part) {
stack.push(new ExprNodeColumnDesc(ti, col, tblName, part));
return this;
}
public ExprBuilder val(String val) {
return valInternal(TypeInfoFactory.stringTypeInfo, val);
}
public ExprBuilder val(int val) {
return valInternal(TypeInfoFactory.intTypeInfo, val);
}
public ExprBuilder val(boolean val) {
return valInternal(TypeInfoFactory.booleanTypeInfo, val);
}
private ExprBuilder valInternal(TypeInfo ti, Object val) {
stack.push(new ExprNodeConstantDesc(ti, val));
return this;
}
}
private void addSd(ArrayList<FieldSchema> cols, Table tbl) {
StorageDescriptor sd = new StorageDescriptor();
sd.setCols(cols);
sd.setCompressed(false);
sd.setNumBuckets(1);
sd.setParameters(new HashMap<String, String>());
sd.setBucketCols(new ArrayList<String>());
sd.setSerdeInfo(new SerDeInfo());
sd.getSerdeInfo().setName(tbl.getTableName());
sd.getSerdeInfo().setParameters(new HashMap<String, String>());
sd.getSerdeInfo().getParameters()
.put(serdeConstants.SERIALIZATION_FORMAT, "1");
sd.setSortCols(new ArrayList<Order>());
sd.getSerdeInfo().setSerializationLib(LazySimpleSerDe.class.getName());
sd.setInputFormat(HiveInputFormat.class.getName());
sd.setOutputFormat(HiveOutputFormat.class.getName());
tbl.setSd(sd);
}
private void addPartition(HiveMetaStoreClient client, Table table,
List<String> vals, String location) throws TException {
Partition part = new Partition();
part.setDbName(table.getDbName());
part.setTableName(table.getTableName());
part.setValues(vals);
part.setParameters(new HashMap<String, String>());
part.setSd(table.getSd().deepCopy());
part.getSd().setSerdeInfo(table.getSd().getSerdeInfo());
part.getSd().setLocation(table.getSd().getLocation() + location);
client.add_partition(part);
}
}
| sankarh/hive | ql/src/test/org/apache/hadoop/hive/metastore/TestMetastoreExpr.java | Java | apache-2.0 | 11,965 |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
import os
import sys
import mxnet as mx
mx.test_utils.set_default_device(mx.gpu(0))
curr_path = os.path.dirname(os.path.abspath(os.path.expanduser(__file__)))
sys.path.insert(0, os.path.join(curr_path, '../unittest'))
# We import all tests from ../unittest/test_deferred_compute.py
# They will be detected by test framework, as long as the current file has a different filename
from test_deferred_compute import *
| szha/mxnet | tests/python/gpu/test_deferred_compute_gpu.py | Python | apache-2.0 | 1,203 |
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Function template load</title>
<link rel="stylesheet" href="../../../../doc/src/boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.78.1">
<link rel="home" href="../../index.html" title="The Boost C++ Libraries BoostBook Documentation Subset">
<link rel="up" href="../../property_tree/reference.html#header.boost.property_tree.ptree_serialization_hpp" title="Header <boost/property_tree/ptree_serialization.hpp>">
<link rel="prev" href="save_idp216693664.html" title="Function template save">
<link rel="next" href="serialize_idp94529232.html" title="Function template serialize">
</head>
<body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF">
<table cellpadding="2" width="100%"><tr>
<td valign="top"><img alt="Boost C++ Libraries" width="277" height="86" src="../../../../boost.png"></td>
<td align="center"><a href="../../../../index.html">Home</a></td>
<td align="center"><a href="../../../../libs/libraries.htm">Libraries</a></td>
<td align="center"><a href="http://www.boost.org/users/people.html">People</a></td>
<td align="center"><a href="http://www.boost.org/users/faq.html">FAQ</a></td>
<td align="center"><a href="../../../../more/index.htm">More</a></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="save_idp216693664.html"><img src="../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../../property_tree/reference.html#header.boost.property_tree.ptree_serialization_hpp"><img src="../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../index.html"><img src="../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="serialize_idp94529232.html"><img src="../../../../doc/src/images/next.png" alt="Next"></a>
</div>
<div class="refentry">
<a name="boost.property_tree.load_idp229842432"></a><div class="titlepage"></div>
<div class="refnamediv">
<h2><span class="refentrytitle">Function template load</span></h2>
<p>boost::property_tree::load</p>
</div>
<h2 xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="refsynopsisdiv-title">Synopsis</h2>
<div xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="refsynopsisdiv"><pre class="synopsis"><span class="comment">// In header: <<a class="link" href="../../property_tree/reference.html#header.boost.property_tree.ptree_serialization_hpp" title="Header <boost/property_tree/ptree_serialization.hpp>">boost/property_tree/ptree_serialization.hpp</a>>
</span>
<span class="keyword">template</span><span class="special"><</span><span class="keyword">typename</span> Archive<span class="special">,</span> <span class="keyword">typename</span> K<span class="special">,</span> <span class="keyword">typename</span> D<span class="special">,</span> <span class="keyword">typename</span> C<span class="special">></span>
<span class="keyword">void</span> <span class="identifier">load</span><span class="special">(</span><span class="identifier">Archive</span> <span class="special">&</span> ar<span class="special">,</span> <a class="link" href="basic_ptree.html" title="Class template basic_ptree">basic_ptree</a><span class="special"><</span> <span class="identifier">K</span><span class="special">,</span> <span class="identifier">D</span><span class="special">,</span> <span class="identifier">C</span> <span class="special">></span> <span class="special">&</span> t<span class="special">,</span>
<span class="keyword">const</span> <span class="keyword">unsigned</span> <span class="keyword">int</span> file_version<span class="special">)</span><span class="special">;</span></pre></div>
<div class="refsect1">
<a name="idp351665840"></a><h2>Description</h2>
<p>De-serialize the property tree to the given archive. </p>
<div class="note"><table border="0" summary="Note">
<tr>
<td rowspan="2" align="center" valign="top" width="25"><img alt="[Note]" src="../../../../doc/src/images/note.png"></td>
<th align="left">Note</th>
</tr>
<tr><td align="left" valign="top"><p>In addition to de-serializing from regular archives, this supports loading from archives requiring name-value pairs, e.g. XML archives. The format should be that used by boost::property_tree::save. </p></td></tr>
</table></div>
<p>
</p>
<div class="variablelist"><table border="0" class="variablelist compact">
<colgroup>
<col align="left" valign="top">
<col>
</colgroup>
<tbody>
<tr>
<td><p><span class="term">Parameters:</span></p></td>
<td><div class="variablelist"><table border="0" class="variablelist compact">
<colgroup>
<col align="left" valign="top">
<col>
</colgroup>
<tbody>
<tr>
<td><p><span class="term"><code class="computeroutput">ar</code></span></p></td>
<td><p>The archive from which to load the serialized property tree. This archive should conform to the concept laid out by the Boost.Serialization library. </p></td>
</tr>
<tr>
<td><p><span class="term"><code class="computeroutput">file_version</code></span></p></td>
<td><p>file_version for the archive. </p></td>
</tr>
<tr>
<td><p><span class="term"><code class="computeroutput">t</code></span></p></td>
<td><p>The property tree to de-serialize. </p></td>
</tr>
</tbody>
</table></div></td>
</tr>
<tr>
<td><p><span class="term">Postconditions:</span></p></td>
<td><p><code class="computeroutput">t</code> will contain the de-serialized data from <code class="computeroutput">ar</code>. </p></td>
</tr>
</tbody>
</table></div>
</div>
</div>
<table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr>
<td align="left"></td>
<td align="right"><div class="copyright-footer">Copyright © 2008 Marcin Kalicinski<p>
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>)
</p>
</div></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="save_idp216693664.html"><img src="../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../../property_tree/reference.html#header.boost.property_tree.ptree_serialization_hpp"><img src="../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../index.html"><img src="../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="serialize_idp94529232.html"><img src="../../../../doc/src/images/next.png" alt="Next"></a>
</div>
</body>
</html>
| biospi/seamass-windeps | src/boost_1_57_0/doc/html/boost/property_tree/load_idp229842432.html | HTML | apache-2.0 | 6,599 |
from __future__ import print_function
from builtins import range
import sys
sys.path.insert(1,"../../../")
import h2o
from tests import pyunit_utils
import random
from h2o.estimators.gbm import H2OGradientBoostingEstimator
def cv_cars_gbm():
# read in the dataset and construct training set (and validation set)
cars = h2o.import_file(path=pyunit_utils.locate("smalldata/junit/cars_20mpg.csv"))
# choose the type model-building exercise (multinomial classification or regression). 0:regression, 1:binomial,
# 2:multinomial
problem = 1 #random.sample(list(range(3)),1)[0]
# pick the predictors and response column, along with the correct distribution
predictors = ["displacement","power","weight","acceleration","year"]
if problem == 1 :
response_col = "economy_20mpg"
distribution = "bernoulli"
cars[response_col] = cars[response_col].asfactor()
elif problem == 2 :
response_col = "cylinders"
distribution = "multinomial"
cars[response_col] = cars[response_col].asfactor()
else :
response_col = "economy"
distribution = "gaussian"
print("Distribution: {0}".format(distribution))
print("Response column: {0}".format(response_col))
## cross-validation
# 1. check that cv metrics are the same over repeated "Modulo" runs
nfolds = random.randint(3,10)
gbm1 = H2OGradientBoostingEstimator(nfolds=nfolds,
distribution=distribution,
ntrees=5,
fold_assignment="Modulo")
gbm1.train(x=predictors, y=response_col, training_frame=cars)
gbm2 = H2OGradientBoostingEstimator(nfolds=nfolds,
distribution=distribution,
ntrees=5,
fold_assignment="Modulo")
gbm2.train(x=predictors, y=response_col, training_frame=cars)
pyunit_utils.check_models(gbm1, gbm2, True)
# 2. check that cv metrics are different over repeated "Random" runs
nfolds = random.randint(3,10)
gbm1 = H2OGradientBoostingEstimator(nfolds=nfolds,
distribution=distribution,
ntrees=5,
fold_assignment="Random")
gbm1.train(x=predictors, y=response_col, training_frame=cars)
gbm2 = H2OGradientBoostingEstimator(nfolds=nfolds,
distribution=distribution,
ntrees=5,
fold_assignment="Random")
gbm2.train(x=predictors, y=response_col, training_frame=cars)
try:
pyunit_utils.check_models(gbm1, gbm2, True)
assert False, "Expected models to be different over repeated Random runs"
except AssertionError:
assert True
# 3. folds_column
num_folds = random.randint(2,5)
fold_assignments = h2o.H2OFrame([[random.randint(0,num_folds-1)] for f in range(cars.nrow)])
fold_assignments.set_names(["fold_assignments"])
cars = cars.cbind(fold_assignments)
gbm = H2OGradientBoostingEstimator(distribution=distribution,
ntrees=5,
keep_cross_validation_predictions=True)
gbm.train(x=predictors, y=response_col, training_frame=cars, fold_column="fold_assignments")
num_cv_models = len(gbm._model_json['output']['cross_validation_models'])
assert num_cv_models==num_folds, "Expected {0} cross-validation models, but got " \
"{1}".format(num_folds, num_cv_models)
cv_model1 = h2o.get_model(gbm._model_json['output']['cross_validation_models'][0]['name'])
cv_model2 = h2o.get_model(gbm._model_json['output']['cross_validation_models'][1]['name'])
# 4. keep_cross_validation_predictions
cv_predictions = gbm1._model_json['output']['cross_validation_predictions']
assert cv_predictions is None, "Expected cross-validation predictions to be None, but got {0}".format(cv_predictions)
cv_predictions = gbm._model_json['output']['cross_validation_predictions']
assert len(cv_predictions)==num_folds, "Expected the same number of cross-validation predictions " \
"as folds, but got {0}".format(len(cv_predictions))
## boundary cases
# 1. nfolds = number of observations (leave-one-out cross-validation)
gbm = H2OGradientBoostingEstimator(nfolds=cars.nrow, distribution=distribution,ntrees=5,
fold_assignment="Modulo")
gbm.train(x=predictors, y=response_col, training_frame=cars)
# 2. nfolds = 0
gbm1 = H2OGradientBoostingEstimator(nfolds=0, distribution=distribution, ntrees=5)
gbm1.train(x=predictors, y=response_col,training_frame=cars)
# check that this is equivalent to no nfolds
gbm2 = H2OGradientBoostingEstimator(distribution=distribution, ntrees=5)
gbm2.train(x=predictors, y=response_col, training_frame=cars)
pyunit_utils.check_models(gbm1, gbm2)
# 3. cross-validation and regular validation attempted
gbm = H2OGradientBoostingEstimator(nfolds=random.randint(3,10),
ntrees=5,
distribution=distribution)
gbm.train(x=predictors, y=response_col, training_frame=cars, validation_frame=cars)
## error cases
# 1. nfolds == 1 or < 0
try:
gbm = H2OGradientBoostingEstimator(nfolds=random.sample([-1,1],1)[0],
ntrees=5,
distribution=distribution)
gbm.train(x=predictors, y=response_col, training_frame=cars)
assert False, "Expected model-build to fail when nfolds is 1 or < 0"
except EnvironmentError:
assert True
# 2. more folds than observations
try:
gbm = H2OGradientBoostingEstimator(nfolds=cars.nrow+1,
distribution=distribution,
ntrees=5,
fold_assignment="Modulo")
gbm.train(x=predictors, y=response_col, training_frame=cars)
assert False, "Expected model-build to fail when nfolds > nobs"
except EnvironmentError:
assert True
# 3. fold_column and nfolds both specified
try:
gbm = H2OGradientBoostingEstimator(nfolds=3, ntrees=5, distribution=distribution)
gbm.train(x=predictors, y=response_col, training_frame=cars, fold_column="fold_assignments")
assert False, "Expected model-build to fail when fold_column and nfolds both specified"
except EnvironmentError:
assert True
# 4. fold_column and fold_assignment both specified
try:
gbm = H2OGradientBoostingEstimator(ntrees=5, fold_assignment="Random", distribution=distribution)
gbm.train(x=predictors, y=response_col, training_frame=cars, fold_column="fold_assignments")
assert False, "Expected model-build to fail when fold_column and fold_assignment both specified"
except EnvironmentError:
assert True
if __name__ == "__main__":
pyunit_utils.standalone_test(cv_cars_gbm)
else:
cv_cars_gbm()
| YzPaul3/h2o-3 | h2o-py/tests/testdir_algos/gbm/pyunit_cv_cars_gbm.py | Python | apache-2.0 | 7,071 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!--NewPage-->
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.6.0_31) on Thu Jan 31 02:04:59 UTC 2013 -->
<TITLE>
org.apache.hadoop.mapred.pipes (Hadoop 1.1.2 API)
</TITLE>
<META NAME="date" CONTENT="2013-01-31">
<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="org.apache.hadoop.mapred.pipes (Hadoop 1.1.2 API)";
}
}
</SCRIPT>
<NOSCRIPT>
</NOSCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<HR>
<!-- ========= START OF TOP NAVBAR ======= -->
<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> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Package</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-use.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../org/apache/hadoop/mapred/lib/db/package-summary.html"><B>PREV PACKAGE</B></A>
<A HREF="../../../../../org/apache/hadoop/mapred/tools/package-summary.html"><B>NEXT PACKAGE</B></A></FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../index.html?org/apache/hadoop/mapred/pipes/package-summary.html" target="_top"><B>FRAMES</B></A>
<A HREF="package-summary.html" target="_top"><B>NO FRAMES</B></A>
<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>
</TABLE>
<A NAME="skip-navbar_top"></A>
<!-- ========= END OF TOP NAVBAR ========= -->
<HR>
<H2>
Package org.apache.hadoop.mapred.pipes
</H2>
Hadoop Pipes allows C++ code to use Hadoop DFS and map/reduce.
<P>
<B>See:</B>
<BR>
<A HREF="#package_description"><B>Description</B></A>
<P>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
<B>Class Summary</B></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD WIDTH="15%"><B><A HREF="../../../../../org/apache/hadoop/mapred/pipes/Submitter.html" title="class in org.apache.hadoop.mapred.pipes">Submitter</A></B></TD>
<TD>The main entry point and job submitter.</TD>
</TR>
</TABLE>
<P>
<A NAME="package_description"><!-- --></A><H2>
Package org.apache.hadoop.mapred.pipes Description
</H2>
<P>
Hadoop Pipes allows C++ code to use Hadoop DFS and map/reduce. The
primary approach is to split the C++ code into a separate process that
does the application specific code. In many ways, the approach will be
similar to Hadoop streaming, but using Writable serialization to
convert the types into bytes that are sent to the process via a
socket.
<p>
The class org.apache.hadoop.mapred.pipes.Submitter has a public static
method to submit a job as a JobConf and a main method that takes an
application and optional configuration file, input directories, and
output directory. The cli for the main looks like:
<pre>
bin/hadoop pipes \
[-input <i>inputDir</i>] \
[-output <i>outputDir</i>] \
[-jar <i>applicationJarFile</i>] \
[-inputformat <i>class</i>] \
[-map <i>class</i>] \
[-partitioner <i>class</i>] \
[-reduce <i>class</i>] \
[-writer <i>class</i>] \
[-program <i>program url</i>] \
[-conf <i>configuration file</i>] \
[-D <i>property=value</i>] \
[-fs <i>local|namenode:port</i>] \
[-jt <i>local|jobtracker:port</i>] \
[-files <i>comma separated list of files</i>] \
[-libjars <i>comma separated list of jars</i>] \
[-archives <i>comma separated list of archives</i>]
</pre>
<p>
The application programs link against a thin C++ wrapper library that
handles the communication with the rest of the Hadoop system. The C++
interface is "swigable" so that interfaces can be generated for python
and other scripting languages. All of the C++ functions and classes
are in the HadoopPipes namespace. The job may consist of any
combination of Java and C++ RecordReaders, Mappers, Paritioner,
Combiner, Reducer, and RecordWriter.
<p>
Hadoop Pipes has a generic Java class for handling the mapper and
reducer (PipesMapRunner and PipesReducer). They fork off the
application program and communicate with it over a socket. The
communication is handled by the C++ wrapper library and the
PipesMapRunner and PipesReducer.
<p>
The application program passes in a factory object that can create
the various objects needed by the framework to the runTask
function. The framework creates the Mapper or Reducer as
appropriate and calls the map or reduce method to invoke the
application's code. The JobConf is available to the application.
<p>
The Mapper and Reducer objects get all of their inputs, outputs, and
context via context objects. The advantage of using the context
objects is that their interface can be extended with additional
methods without breaking clients. Although this interface is different
from the current Java interface, the plan is to migrate the Java
interface in this direction.
<p>
Although the Java implementation is typed, the C++ interfaces of keys
and values is just a byte buffer. Since STL strings provide precisely
the right functionality and are standard, they will be used. The
decision to not use stronger types was to simplify the interface.
<p>
The application can also define combiner functions. The combiner will
be run locally by the framework in the application process to avoid
the round trip to the Java process and back. Because the compare
function is not available in C++, the combiner will use memcmp to
sort the inputs to the combiner. This is not as general as the Java
equivalent, which uses the user's comparator, but should cover the
majority of the use cases. As the map function outputs key/value
pairs, they will be buffered. When the buffer is full, it will be
sorted and passed to the combiner. The output of the combiner will be
sent to the Java process.
<p>
The application can also set a partition function to control which key
is given to a particular reduce. If a partition function is not
defined, the Java one will be used. The partition function will be
called by the C++ framework before the key/value pair is sent back to
Java.
<p>
The application programs can also register counters with a group and a name
and also increment the counters and get the counter values. Word-count
example illustrating pipes usage with counters is available at
<a href="https://svn.apache.org/repos/asf/hadoop/core/trunk/src/examples/pipes/impl/wordcount-simple.cc">wordcount-simple.cc</a>
<P>
<P>
<DL>
</DL>
<HR>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<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="navbar_bottom_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> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Package</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-use.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../org/apache/hadoop/mapred/lib/db/package-summary.html"><B>PREV PACKAGE</B></A>
<A HREF="../../../../../org/apache/hadoop/mapred/tools/package-summary.html"><B>NEXT PACKAGE</B></A></FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../index.html?org/apache/hadoop/mapred/pipes/package-summary.html" target="_top"><B>FRAMES</B></A>
<A HREF="package-summary.html" target="_top"><B>NO FRAMES</B></A>
<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>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<HR>
Copyright © 2009 The Apache Software Foundation
</BODY>
</HTML>
| markkerzner/nn_kove | hadoop/docs/api/org/apache/hadoop/mapred/pipes/package-summary.html | HTML | apache-2.0 | 10,982 |
/*
* Copyright 2011- Per Wendel
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package spark.webserver;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import spark.Access;
import spark.ExceptionHandlerImpl;
import spark.ExceptionMapper;
import spark.FilterImpl;
import spark.HaltException;
import spark.Request;
import spark.RequestResponseFactory;
import spark.Response;
import spark.RouteImpl;
import spark.route.HttpMethod;
import spark.route.SimpleRouteMatcher;
import spark.routematch.RouteMatch;
import spark.utils.GzipUtils;
import spark.webserver.serialization.SerializerChain;
/**
* Filter for matching of filters and routes.
*
* @author Per Wendel
*/
public class MatcherFilter implements Filter {
private static final String ACCEPT_TYPE_REQUEST_MIME_HEADER = "Accept";
private static final String HTTP_METHOD_OVERRIDE_HEADER = "X-HTTP-Method-Override";
private SimpleRouteMatcher routeMatcher;
private SerializerChain serializerChain;
private boolean isServletContext;
private boolean hasOtherHandlers;
/**
* The logger.
*/
private static final org.slf4j.Logger LOG = org.slf4j.LoggerFactory.getLogger(MatcherFilter.class);
/**
* Constructor
*
* @param routeMatcher The route matcher
* @param isServletContext If true, chain.doFilter will be invoked if request is not consumed by Spark.
* @param hasOtherHandlers If true, do nothing if request is not consumed by Spark in order to let others handlers process the request.
*/
public MatcherFilter(SimpleRouteMatcher routeMatcher, boolean isServletContext, boolean hasOtherHandlers) {
this.routeMatcher = routeMatcher;
this.isServletContext = isServletContext;
this.hasOtherHandlers = hasOtherHandlers;
this.serializerChain = new SerializerChain();
}
public void init(FilterConfig filterConfig) {
//
}
/**
* TODO: Should be broken down.
*/
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, // NOSONAR
FilterChain chain) throws IOException, ServletException { // NOSONAR
HttpServletRequest httpRequest = (HttpServletRequest) servletRequest; // NOSONAR
HttpServletResponse httpResponse = (HttpServletResponse) servletResponse;
String method = httpRequest.getHeader(HTTP_METHOD_OVERRIDE_HEADER);
if (method == null) {
method = httpRequest.getMethod();
}
String httpMethodStr = method.toLowerCase(); // NOSONAR
String uri = httpRequest.getPathInfo(); // NOSONAR
String acceptType = httpRequest.getHeader(ACCEPT_TYPE_REQUEST_MIME_HEADER);
Object bodyContent = null;
RequestWrapper requestWrapper = new RequestWrapper();
ResponseWrapper responseWrapper = new ResponseWrapper();
Response response = RequestResponseFactory.create(httpResponse);
LOG.debug("httpMethod:" + httpMethodStr + ", uri: " + uri);
try {
// BEFORE filters
List<RouteMatch> matchSet = routeMatcher.findTargetsForRequestedRoute(HttpMethod.before, uri, acceptType);
for (RouteMatch filterMatch : matchSet) {
Object filterTarget = filterMatch.getTarget();
if (filterTarget instanceof FilterImpl) {
Request request = RequestResponseFactory.create(filterMatch, httpRequest);
FilterImpl filter = (FilterImpl) filterTarget;
requestWrapper.setDelegate(request);
responseWrapper.setDelegate(response);
filter.handle(requestWrapper, responseWrapper);
String bodyAfterFilter = Access.getBody(response);
if (bodyAfterFilter != null) {
bodyContent = bodyAfterFilter;
}
}
}
// BEFORE filters, END
HttpMethod httpMethod = HttpMethod.valueOf(httpMethodStr);
RouteMatch match = null;
match = routeMatcher.findTargetForRequestedRoute(httpMethod, uri, acceptType);
Object target = null;
if (match != null) {
target = match.getTarget();
} else if (httpMethod == HttpMethod.head && bodyContent == null) {
// See if get is mapped to provide default head mapping
bodyContent =
routeMatcher.findTargetForRequestedRoute(HttpMethod.get, uri, acceptType) != null ? "" : null;
}
if (target != null) {
try {
Object result = null;
if (target instanceof RouteImpl) {
RouteImpl route = ((RouteImpl) target);
if (requestWrapper.getDelegate() == null) {
Request request = RequestResponseFactory.create(match, httpRequest);
requestWrapper.setDelegate(request);
} else {
requestWrapper.changeMatch(match);
}
responseWrapper.setDelegate(response);
Object element = route.handle(requestWrapper, responseWrapper);
result = route.render(element);
// result = element.toString(); // TODO: Remove later when render fixed
}
if (result != null) {
bodyContent = result;
}
} catch (HaltException hEx) { // NOSONAR
throw hEx; // NOSONAR
}
}
// AFTER filters
matchSet = routeMatcher.findTargetsForRequestedRoute(HttpMethod.after, uri, acceptType);
for (RouteMatch filterMatch : matchSet) {
Object filterTarget = filterMatch.getTarget();
if (filterTarget instanceof FilterImpl) {
if (requestWrapper.getDelegate() == null) {
Request request = RequestResponseFactory.create(filterMatch, httpRequest);
requestWrapper.setDelegate(request);
} else {
requestWrapper.changeMatch(filterMatch);
}
responseWrapper.setDelegate(response);
FilterImpl filter = (FilterImpl) filterTarget;
filter.handle(requestWrapper, responseWrapper);
String bodyAfterFilter = Access.getBody(response);
if (bodyAfterFilter != null) {
bodyContent = bodyAfterFilter;
}
}
}
// AFTER filters, END
} catch (HaltException hEx) {
LOG.debug("halt performed");
httpResponse.setStatus(hEx.getStatusCode());
if (hEx.getBody() != null) {
bodyContent = hEx.getBody();
} else {
bodyContent = "";
}
} catch (Exception e) {
ExceptionHandlerImpl handler = ExceptionMapper.getInstance().getHandler(e);
if (handler != null) {
handler.handle(e, requestWrapper, responseWrapper);
String bodyAfterFilter = Access.getBody(responseWrapper.getDelegate());
if (bodyAfterFilter != null) {
bodyContent = bodyAfterFilter;
}
} else {
LOG.error("", e);
httpResponse.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
bodyContent = INTERNAL_ERROR;
}
}
// If redirected and content is null set to empty string to not throw NotConsumedException
if (bodyContent == null && responseWrapper.isRedirected()) {
bodyContent = "";
}
boolean consumed = bodyContent != null;
if (!consumed && hasOtherHandlers) {
if (servletRequest instanceof HttpRequestWrapper) {
((HttpRequestWrapper) servletRequest).notConsumed(true);
return;
}
}
if (!consumed && !isServletContext) {
LOG.info("The requested route [" + uri + "] has not been mapped in Spark");
httpResponse.setStatus(HttpServletResponse.SC_NOT_FOUND);
bodyContent = String.format(NOT_FOUND);
consumed = true;
}
if (consumed) {
// Write body content
if (!httpResponse.isCommitted()) {
if (httpResponse.getContentType() == null) {
httpResponse.setContentType("text/html; charset=utf-8");
}
// Check if gzip is wanted/accepted and in that case handle that
OutputStream outputStream = GzipUtils.checkAndWrap(httpRequest, httpResponse);
// serialize the body to output stream
serializerChain.process(outputStream, bodyContent);
outputStream.flush();//needed for GZIP stream. NOt sure where the HTTP response actually gets cleaned up
}
} else if (chain != null) {
chain.doFilter(httpRequest, httpResponse);
}
}
public void destroy() {
// TODO Auto-generated method stub
}
private static final String NOT_FOUND = "<html><body><h2>404 Not found</h2></body></html>";
private static final String INTERNAL_ERROR = "<html><body><h2>500 Internal Error</h2></body></html>";
}
| xdcrafts/spark | src/main/java/spark/webserver/MatcherFilter.java | Java | apache-2.0 | 10,502 |
//
// Copyright 2015 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef OPENSUBDIV3_OSD_GLSL_PATCH_SHADER_SOURCE_H
#define OPENSUBDIV3_OSD_GLSL_PATCH_SHADER_SOURCE_H
#include "../version.h"
#include <string>
#include "../far/patchDescriptor.h"
namespace OpenSubdiv {
namespace OPENSUBDIV_VERSION {
namespace Osd {
class GLSLPatchShaderSource {
public:
static std::string GetCommonShaderSource();
static std::string GetPatchBasisShaderSource();
static std::string GetVertexShaderSource(
Far::PatchDescriptor::Type type);
static std::string GetTessControlShaderSource(
Far::PatchDescriptor::Type type);
static std::string GetTessEvalShaderSource(
Far::PatchDescriptor::Type type);
};
} // end namespace Osd
} // end namespace OPENSUBDIV_VERSION
using namespace OPENSUBDIV_VERSION;
} // end namespace OpenSubdiv
#endif // OPENSUBDIV3_OSD_GLSL_PATCH_SHADER_SOURCE
| barfowl/OpenSubdiv | opensubdiv/osd/glslPatchShaderSource.h | C | apache-2.0 | 1,970 |
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 1.0 Transitional//EN">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" href="../includes/main.css" type="text/css">
<link rel="shortcut icon" href="../favicon.ico" type="image/x-icon">
<title>Apache CloudStack | The Power Behind Your Cloud</title>
</head>
<body>
<div id="insidetopbg">
<div id="inside_wrapper">
<div class="uppermenu_panel">
<div class="uppermenu_box"></div>
</div>
<div id="main_controller">
<div id="inside_header">
<div class="header_top">
<a class="cloud_logo" href="http://cloudstack.org"></a>
<div class="mainemenu_panel"></div>
</div>
</div>
<div id="main_content">
<div class="inside_apileftpanel">
<div class="inside_contentpanel" style="width:930px;">
<div class="api_titlebox">
<div class="api_titlebox_left">
<span>
Apache CloudStack 4.16.0.0 Root Admin API Reference
</span>
<p></p>
<h1>createVpnGateway</h1>
<p>Creates site to site vpn local gateway</p>
</div>
<div class="api_titlebox_right">
<a class="api_backbutton" href="../index.html"></a>
</div>
</div>
<div class="api_tablepanel">
<h2>Request parameters</h2>
<table class="apitable">
<tr class="hed">
<td style="width:200px;"><strong>Parameter Name</strong></td><td style="width:500px;">Description</td><td style="width:180px;">Required</td>
</tr>
<tr>
<td style="width:200px;"><strong>vpcid</strong></td><td style="width:500px;"><strong>public ip address id of the vpn gateway</strong></td><td style="width:180px;"><strong>true</strong></td>
</tr>
<tr>
<td style="width:200px;"><i>fordisplay</i></td><td style="width:500px;"><i>an optional field, whether to the display the vpn to the end user or not</i></td><td style="width:180px;"><i>false</i></td>
</tr>
</table>
</div>
<div class="api_tablepanel">
<h2>Response Tags</h2>
<table class="apitable">
<tr class="hed">
<td style="width:200px;"><strong>Response Name</strong></td><td style="width:500px;">Description</td>
</tr>
<tr>
<td style="width:200px;"><strong>id</strong></td><td style="width:500px;">the vpn gateway ID</td>
</tr>
<tr>
<td style="width:200px;"><strong>account</strong></td><td style="width:500px;">the owner</td>
</tr>
<tr>
<td style="width:200px;"><strong>domain</strong></td><td style="width:500px;">the domain name of the owner</td>
</tr>
<tr>
<td style="width:200px;"><strong>domainid</strong></td><td style="width:500px;">the domain id of the owner</td>
</tr>
<tr>
<td style="width:200px;"><strong>fordisplay</strong></td><td style="width:500px;">is vpn gateway for display to the regular user</td>
</tr>
<tr>
<td style="width:200px;"><strong>project</strong></td><td style="width:500px;">the project name</td>
</tr>
<tr>
<td style="width:200px;"><strong>projectid</strong></td><td style="width:500px;">the project id</td>
</tr>
<tr>
<td style="width:200px;"><strong>publicip</strong></td><td style="width:500px;">the public IP address</td>
</tr>
<tr>
<td style="width:200px;"><strong>removed</strong></td><td style="width:500px;">the date and time the host was removed</td>
</tr>
<tr>
<td style="width:200px;"><strong>vpcid</strong></td><td style="width:500px;">the vpc id of this gateway</td>
</tr>
<tr>
<td style="width:200px;"><strong>vpcname</strong></td><td style="width:500px;">the vpc name of this gateway</td>
</tr>
</table>
</div>
</div>
</div>
</div>
</div>
<div id="footer">
<div id="comments_thread">
<script type="text/javascript" src="https://comments.apache.org/show_comments.lua?site=test" async="true"></script>
<noscript>
<iframe width="930" height="500" src="https://comments.apache.org/iframe.lua?site=test&page=4.2.0/rootadmin"></iframe>
</noscript>
</div>
<div id="footer_maincontroller">
<p>
Copyright © 2015 The Apache Software Foundation, Licensed under the
<a href="http://www.apache.org/licenses/LICENSE-2.0">Apache License, Version 2.0.</a>
<br>
Apache, CloudStack, Apache CloudStack, the Apache CloudStack logo, the CloudMonkey logo and the Apache feather logo are trademarks of The Apache Software Foundation.
</p>
</div>
</div>
</div>
</div>
</body>
</html>
| apache/cloudstack-www | source/api/apidocs-4.16/apis/createVpnGateway.html | HTML | apache-2.0 | 7,638 |
package com.fincatto.nfe310.classes.nota;
import java.math.BigDecimal;
import org.simpleframework.xml.Element;
import com.fincatto.nfe310.classes.NFBase;
import com.fincatto.nfe310.classes.NFNotaInfoImpostoTributacaoICMS;
import com.fincatto.nfe310.classes.NFNotaInfoItemModalidadeBCICMS;
import com.fincatto.nfe310.classes.NFOrigem;
import com.fincatto.nfe310.validadores.BigDecimalParser;
public class NFNotaInfoItemImpostoICMS51 extends NFBase {
@Element(name = "orig", required = true)
private NFOrigem origem;
@Element(name = "CST", required = true)
private NFNotaInfoImpostoTributacaoICMS situacaoTributaria;
@Element(name = "modBC", required = false)
private NFNotaInfoItemModalidadeBCICMS modalidadeBCICMS;
@Element(name = "pRedBC", required = false)
private String percentualReducaoBC;
@Element(name = "vBC", required = false)
private String valorBCICMS;
@Element(name = "pICMS", required = false)
private String percentualICMS;
@Element(name = "vICMSOp", required = false)
private String valorICMSOperacao;
@Element(name = "pDif", required = false)
private String percentualDiferimento;
@Element(name = "vICMSDif", required = false)
private String valorICMSDiferimento;
@Element(name = "vICMS", required = false)
private String valorICMS;
public void setOrigem(final NFOrigem origem) {
this.origem = origem;
}
public void setSituacaoTributaria(final NFNotaInfoImpostoTributacaoICMS situacaoTributaria) {
this.situacaoTributaria = situacaoTributaria;
}
public void setModalidadeBCICMS(final NFNotaInfoItemModalidadeBCICMS modalidadeBCICMS) {
this.modalidadeBCICMS = modalidadeBCICMS;
}
public void setPercentualReducaoBC(final BigDecimal percentualReducaoBC) {
this.percentualReducaoBC = BigDecimalParser.tamanho7ComAte4CasasDecimais(percentualReducaoBC, "Percentual Reducao BC ICMS51 Item");
}
public void setValorBCICMS(final BigDecimal valorBCICMS) {
this.valorBCICMS = BigDecimalParser.tamanho15Com2CasasDecimais(valorBCICMS, "Valor BC ICMS ICMS51 Item");
}
public void setPercentualICMS(final BigDecimal percentualICMS) {
this.percentualICMS = BigDecimalParser.tamanho7ComAte4CasasDecimais(percentualICMS, "Percentual ICMS ICMS51 Item");
}
public void setValorICMS(final BigDecimal valorICMS) {
this.valorICMS = BigDecimalParser.tamanho15Com2CasasDecimais(valorICMS, "Valor ICMS ICMS51 Item");
}
public void setPercentualDiferimento(final BigDecimal percentualDiferimento) {
this.percentualDiferimento = BigDecimalParser.tamanho7ComAte4CasasDecimais(percentualDiferimento, "Percentual Diferimento ICMS51 Item");
}
public void setValorICMSDiferimento(final BigDecimal valorICMSDiferimento) {
this.valorICMSDiferimento = BigDecimalParser.tamanho15Com2CasasDecimais(valorICMSDiferimento, "Valor ICMS Diferimento ICMS51 Item");
}
public void setValorICMSOperacao(final BigDecimal valorICMSOperacao) {
this.valorICMSOperacao = BigDecimalParser.tamanho15Com2CasasDecimais(valorICMSOperacao, "Valor ICMS Operacao ICMS51 Item");
}
public NFOrigem getOrigem() {
return this.origem;
}
public NFNotaInfoImpostoTributacaoICMS getSituacaoTributaria() {
return this.situacaoTributaria;
}
public NFNotaInfoItemModalidadeBCICMS getModalidadeBCICMS() {
return this.modalidadeBCICMS;
}
public String getPercentualReducaoBC() {
return this.percentualReducaoBC;
}
public String getValorBCICMS() {
return this.valorBCICMS;
}
public String getPercentualICMS() {
return this.percentualICMS;
}
public String getValorICMSOperacao() {
return this.valorICMSOperacao;
}
public String getPercentualDiferimento() {
return this.percentualDiferimento;
}
public String getValorICMSDiferimento() {
return this.valorICMSDiferimento;
}
public String getValorICMS() {
return this.valorICMS;
}
} | fauker/nfe | src/main/java/com/fincatto/nfe310/classes/nota/NFNotaInfoItemImpostoICMS51.java | Java | apache-2.0 | 4,104 |
/*
* SubstCmd.java
*
* Copyright (c) 1997 Sun Microsystems, Inc.
*
* See the file "license.terms" for information on usage and
* redistribution of this file, and for a DISCLAIMER OF ALL
* WARRANTIES.
*
* RCS: @(#) $Id: SubstCmd.java,v 1.4 2005/07/22 04:47:25 mdejong Exp $
*
*/
package tcl.lang;
import java.util.*;
/**
* This class implements the built-in "subst" command in Tcl. But it doesn't ignore carriage returns.
*/
public class SubstCrCommand implements Command {
static final private String validCmds[] = {
"-nobackslashes",
"-nocommands",
"-novariables"
};
static final int OPT_NOBACKSLASHES = 0;
static final int OPT_NOCOMMANDS = 1;
static final int OPT_NOVARS = 2;
/**
* This procedure is invoked to process the "subst" Tcl command.
* See the user documentation for details on what it does.
*
* @param interp the current interpreter.
* @param argv command arguments.
* @exception TclException if wrong # of args or invalid argument(s).
*/
public void cmdProc(Interp interp, TclObject argv[])
throws TclException {
int currentObjIndex, len, i;
int objc = argv.length - 1;
boolean doBackslashes = true;
boolean doCmds = true;
boolean doVars = true;
StringBuffer result = new StringBuffer();
String s;
char c;
for (currentObjIndex = 1; currentObjIndex < objc; currentObjIndex++) {
if (!argv[currentObjIndex].toString().startsWith("-")) {
break;
}
int opt = TclIndex.get(interp, argv[currentObjIndex],
validCmds, "switch", 0);
switch (opt) {
case OPT_NOBACKSLASHES:
doBackslashes = false;
break;
case OPT_NOCOMMANDS:
doCmds = false;
break;
case OPT_NOVARS:
doVars = false;
break;
default:
throw new TclException(interp,
"SubstCrCmd.cmdProc: bad option " + opt
+ " index to cmds");
}
}
if (currentObjIndex != objc) {
throw new TclNumArgsException(interp, currentObjIndex, argv,
"?-nobackslashes? ?-nocommands? ?-novariables? string");
}
/*
* Scan through the string one character at a time, performing
* command, variable, and backslash substitutions.
*/
s = argv[currentObjIndex].toString();
len = s.length();
i = 0;
while (i < len) {
c = s.charAt(i);
if ((c == '[') && doCmds) {
ParseResult res;
try {
interp.evalFlags = Parser.TCL_BRACKET_TERM;
interp.eval(s.substring(i + 1, len));
TclObject interp_result = interp.getResult();
interp_result.preserve();
res = new ParseResult(interp_result,
i + interp.termOffset);
} catch (TclException e) {
i = e.errIndex + 1;
throw e;
}
i = res.nextIndex + 2;
result.append( res.value.toString() );
res.release();
/**
* Removed
(ToDo) may not be portable on Mac
} else if (c == '\r') {
i++;
*/
} else if ((c == '$') && doVars) {
ParseResult vres = Parser.parseVar(interp,
s.substring(i, len));
i += vres.nextIndex;
result.append( vres.value.toString() );
vres.release();
} else if ((c == '\\') && doBackslashes) {
BackSlashResult bs = Interp.backslash(s, i, len);
i = bs.nextIndex;
if (bs.isWordSep) {
break;
} else {
result.append( bs.c );
}
} else {
result.append( c );
i++;
}
}
interp.setResult(result.toString());
}
}
| delonnewman/expect4j | src/main/java/tcl/lang/SubstCrCommand.java | Java | apache-2.0 | 4,600 |
For an explanation of how to fill out the fields, please see the relevant section
in [PULL_REQUESTS.md](https://github.com/envoyproxy/envoy/blob/master/PULL_REQUESTS.md)
Description:
Risk Level:
Testing:
Docs Changes:
Release Notes:
[Optional Fixes #Issue]
[Optional Deprecated:]
| istio/envoy | PULL_REQUEST_TEMPLATE.md | Markdown | apache-2.0 | 281 |
package com.yokmama.learn10.chapter07.lesson30.fragment;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.yokmama.learn10.chapter07.lesson30.R;
/**
* A simple {@link Fragment} subclass.
*/
public class ImageButtonFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_image_button, container, false);
return rootView;
}
}
| kazuemasaki/honki-android | Chapter07/Lesson30/before/app/src/main/java/com/yokmama/learn10/chapter07/lesson30/fragment/ImageButtonFragment.java | Java | apache-2.0 | 624 |
package org.radargun.fwk;
import org.radargun.config.ConfigHelper;
import org.testng.annotations.Test;
/**
* @author [email protected]
*/
@Test
public class PropertyReplacerTest {
public void testWithDefaultNoReplacement() {
assert "aDefaultVal".equals(ConfigHelper.checkForProps("${aDefaultVal:noSuchProp}"));
}
public void testWithDefaultAndReplacement(){
System.setProperty("org.radargun.fwk.PropertyReplacerTest", "nonDefaultValue");
String received = ConfigHelper.checkForProps("${aDefaultVal:org.radargun.fwk.PropertyReplacerTest}");
assert "nonDefaultValue".equals(received) : received;
}
public void testFailureOnNonDefault() {
try {
ConfigHelper.checkForProps("${org.radargun.fwk.PropertyReplacerTest_other}");
assert false : "exception expected";
} catch (RuntimeException e) {
//expected
}
}
public void testNoDefaultAndExisting() {
System.setProperty("org.radargun.fwk.PropertyReplacerTest", "nonDefaultValue");
String received = ConfigHelper.checkForProps("${org.radargun.fwk.PropertyReplacerTest}");
assert "nonDefaultValue".equals(received) : received;
}
}
| nmldiegues/stibt | radargun/framework/src/test/java/org/radargun/fwk/PropertyReplacerTest.java | Java | apache-2.0 | 1,201 |
import { BoxGeometry } from "../../Source/Cesium.js";
import { Cartesian3 } from "../../Source/Cesium.js";
import { Color } from "../../Source/Cesium.js";
import { ColorGeometryInstanceAttribute } from "../../Source/Cesium.js";
import { destroyObject } from "../../Source/Cesium.js";
import { Ellipsoid } from "../../Source/Cesium.js";
import { GeometryInstance } from "../../Source/Cesium.js";
import { PolygonGeometry } from "../../Source/Cesium.js";
import { Rectangle } from "../../Source/Cesium.js";
import { RectangleGeometry } from "../../Source/Cesium.js";
import { ShowGeometryInstanceAttribute } from "../../Source/Cesium.js";
import { Transforms } from "../../Source/Cesium.js";
import { Pass } from "../../Source/Cesium.js";
import { RenderState } from "../../Source/Cesium.js";
import { ClassificationPrimitive } from "../../Source/Cesium.js";
import { ClassificationType } from "../../Source/Cesium.js";
import { InvertClassification } from "../../Source/Cesium.js";
import { MaterialAppearance } from "../../Source/Cesium.js";
import { PerInstanceColorAppearance } from "../../Source/Cesium.js";
import { Primitive } from "../../Source/Cesium.js";
import { StencilConstants } from "../../Source/Cesium.js";
import createScene from "../createScene.js";
import pollToPromise from "../pollToPromise.js";
describe(
"Scene/ClassificationPrimitive",
function () {
var scene;
var ellipsoid;
var rectangle;
var depthColor;
var boxColor;
var boxInstance;
var primitive;
var globePrimitive;
var tilesetPrimitive;
var reusableGlobePrimitive;
var reusableTilesetPrimitive;
function createPrimitive(rectangle, pass) {
var renderState;
if (pass === Pass.CESIUM_3D_TILE) {
renderState = RenderState.fromCache({
stencilTest: StencilConstants.setCesium3DTileBit(),
stencilMask: StencilConstants.CESIUM_3D_TILE_MASK,
depthTest: {
enabled: true,
},
});
}
var depthColorAttribute = ColorGeometryInstanceAttribute.fromColor(
new Color(0.0, 0.0, 1.0, 1.0)
);
depthColor = depthColorAttribute.value;
return new Primitive({
geometryInstances: new GeometryInstance({
geometry: new RectangleGeometry({
ellipsoid: Ellipsoid.WGS84,
rectangle: rectangle,
}),
id: "depth rectangle",
attributes: {
color: depthColorAttribute,
},
}),
appearance: new PerInstanceColorAppearance({
translucent: false,
flat: true,
renderState: renderState,
}),
asynchronous: false,
});
}
function MockPrimitive(primitive, pass) {
this._primitive = primitive;
this._pass = pass;
this.show = true;
}
MockPrimitive.prototype.update = function (frameState) {
if (!this.show) {
return;
}
var commandList = frameState.commandList;
var startLength = commandList.length;
this._primitive.update(frameState);
for (var i = startLength; i < commandList.length; ++i) {
var command = commandList[i];
command.pass = this._pass;
}
};
MockPrimitive.prototype.isDestroyed = function () {
return false;
};
MockPrimitive.prototype.destroy = function () {
return destroyObject(this);
};
beforeAll(function () {
scene = createScene();
scene.postProcessStages.fxaa.enabled = false;
ellipsoid = Ellipsoid.WGS84;
rectangle = Rectangle.fromDegrees(-75.0, 25.0, -70.0, 30.0);
reusableGlobePrimitive = createPrimitive(rectangle, Pass.GLOBE);
reusableTilesetPrimitive = createPrimitive(
rectangle,
Pass.CESIUM_3D_TILE
);
});
afterAll(function () {
reusableGlobePrimitive.destroy();
reusableTilesetPrimitive.destroy();
scene.destroyForSpecs();
});
beforeEach(function () {
scene.morphTo3D(0);
// wrap rectangle primitive so it gets executed during the globe pass and 3D Tiles pass to lay down depth
globePrimitive = new MockPrimitive(reusableGlobePrimitive, Pass.GLOBE);
tilesetPrimitive = new MockPrimitive(
reusableTilesetPrimitive,
Pass.CESIUM_3D_TILE
);
var center = Rectangle.center(rectangle);
var origin = ellipsoid.cartographicToCartesian(center);
var modelMatrix = Transforms.eastNorthUpToFixedFrame(origin);
var dimensions = new Cartesian3(1000000.0, 1000000.0, 1000000.0);
var boxColorAttribute = ColorGeometryInstanceAttribute.fromColor(
new Color(1.0, 1.0, 0.0, 1.0)
);
boxColor = boxColorAttribute.value;
boxInstance = new GeometryInstance({
geometry: BoxGeometry.fromDimensions({
dimensions: dimensions,
}),
modelMatrix: modelMatrix,
id: "box",
attributes: {
color: boxColorAttribute,
},
});
});
afterEach(function () {
scene.primitives.removeAll();
primitive = primitive && !primitive.isDestroyed() && primitive.destroy();
globePrimitive =
globePrimitive &&
!globePrimitive.isDestroyed() &&
globePrimitive.destroy();
tilesetPrimitive =
tilesetPrimitive &&
!tilesetPrimitive.isDestroyed() &&
tilesetPrimitive.destroy();
});
it("default constructs", function () {
primitive = new ClassificationPrimitive();
expect(primitive.geometryInstances).not.toBeDefined();
expect(primitive.show).toEqual(true);
expect(primitive.vertexCacheOptimize).toEqual(false);
expect(primitive.interleave).toEqual(false);
expect(primitive.compressVertices).toEqual(true);
expect(primitive.releaseGeometryInstances).toEqual(true);
expect(primitive.allowPicking).toEqual(true);
expect(primitive.asynchronous).toEqual(true);
expect(primitive.debugShowBoundingVolume).toEqual(false);
expect(primitive.debugShowShadowVolume).toEqual(false);
});
it("constructs with options", function () {
var geometryInstances = [];
primitive = new ClassificationPrimitive({
geometryInstances: geometryInstances,
show: false,
vertexCacheOptimize: true,
interleave: true,
compressVertices: false,
releaseGeometryInstances: false,
allowPicking: false,
asynchronous: false,
debugShowBoundingVolume: true,
debugShowShadowVolume: true,
});
expect(primitive.geometryInstances).toEqual(geometryInstances);
expect(primitive.show).toEqual(false);
expect(primitive.vertexCacheOptimize).toEqual(true);
expect(primitive.interleave).toEqual(true);
expect(primitive.compressVertices).toEqual(false);
expect(primitive.releaseGeometryInstances).toEqual(false);
expect(primitive.allowPicking).toEqual(false);
expect(primitive.asynchronous).toEqual(false);
expect(primitive.debugShowBoundingVolume).toEqual(true);
expect(primitive.debugShowShadowVolume).toEqual(true);
});
it("releases geometry instances when releaseGeometryInstances is true", function () {
if (!ClassificationPrimitive.isSupported(scene)) {
return;
}
primitive = new ClassificationPrimitive({
geometryInstances: boxInstance,
releaseGeometryInstances: true,
asynchronous: false,
});
expect(primitive.geometryInstances).toBeDefined();
scene.primitives.add(primitive);
scene.renderForSpecs();
expect(primitive.geometryInstances).not.toBeDefined();
});
it("does not release geometry instances when releaseGeometryInstances is false", function () {
if (!ClassificationPrimitive.isSupported(scene)) {
return;
}
primitive = new ClassificationPrimitive({
geometryInstances: boxInstance,
releaseGeometryInstances: false,
asynchronous: false,
});
expect(primitive.geometryInstances).toBeDefined();
scene.primitives.add(primitive);
scene.renderForSpecs();
expect(primitive.geometryInstances).toBeDefined();
});
it("adds afterRender promise to frame state", function () {
if (!ClassificationPrimitive.isSupported(scene)) {
return;
}
primitive = new ClassificationPrimitive({
geometryInstances: boxInstance,
releaseGeometryInstances: false,
asynchronous: false,
});
scene.primitives.add(primitive);
scene.renderForSpecs();
return primitive.readyPromise.then(function (param) {
expect(param.ready).toBe(true);
});
});
it("does not render when geometryInstances is undefined", function () {
if (!ClassificationPrimitive.isSupported(scene)) {
return;
}
primitive = new ClassificationPrimitive({
geometryInstances: undefined,
appearance: new PerInstanceColorAppearance(),
asynchronous: false,
});
scene.primitives.add(primitive);
scene.renderForSpecs();
expect(scene.frameState.commandList.length).toEqual(0);
});
it("does not render when show is false", function () {
if (!ClassificationPrimitive.isSupported(scene)) {
return;
}
primitive = new ClassificationPrimitive({
geometryInstances: boxInstance,
asynchronous: false,
});
scene.primitives.add(primitive);
scene.renderForSpecs();
expect(scene.frameState.commandList.length).toBeGreaterThan(0);
primitive.show = false;
scene.renderForSpecs();
expect(scene.frameState.commandList.length).toEqual(0);
});
it("becomes ready when show is false", function () {
if (!ClassificationPrimitive.isSupported(scene)) {
return;
}
primitive = scene.primitives.add(
new ClassificationPrimitive({
geometryInstances: boxInstance,
})
);
primitive.show = false;
var ready = false;
primitive.readyPromise.then(function () {
ready = true;
});
return pollToPromise(function () {
scene.renderForSpecs();
return ready;
}).then(function () {
expect(ready).toEqual(true);
});
});
it("does not render other than for the color or pick pass", function () {
if (!ClassificationPrimitive.isSupported(scene)) {
return;
}
primitive = new ClassificationPrimitive({
geometryInstances: boxInstance,
asynchronous: false,
});
var frameState = scene.frameState;
frameState.passes.render = false;
frameState.passes.pick = false;
primitive.update(frameState);
expect(frameState.commandList.length).toEqual(0);
});
function expectRender(color) {
expect(scene).toRender(color);
}
function expectRenderBlank() {
expect(scene).toRenderAndCall(function (rgba) {
expect(rgba).not.toEqual([0, 0, 0, 255]);
expect(rgba[0]).toEqual(0);
});
}
function verifyClassificationPrimitiveRender(primitive, color) {
scene.camera.setView({ destination: rectangle });
scene.primitives.add(globePrimitive);
scene.primitives.add(tilesetPrimitive);
expectRenderBlank();
scene.primitives.add(primitive);
primitive.classificationType = ClassificationType.BOTH;
globePrimitive.show = false;
tilesetPrimitive.show = true;
expectRender(color);
globePrimitive.show = true;
tilesetPrimitive.show = false;
expectRender(color);
primitive.classificationType = ClassificationType.CESIUM_3D_TILE;
globePrimitive.show = false;
tilesetPrimitive.show = true;
expectRender(color);
globePrimitive.show = true;
tilesetPrimitive.show = false;
expectRenderBlank();
primitive.classificationType = ClassificationType.TERRAIN;
globePrimitive.show = false;
tilesetPrimitive.show = true;
expectRenderBlank();
globePrimitive.show = true;
tilesetPrimitive.show = false;
expectRender(color);
globePrimitive.show = true;
tilesetPrimitive.show = true;
}
it("renders in 3D", function () {
if (!ClassificationPrimitive.isSupported(scene)) {
return;
}
primitive = new ClassificationPrimitive({
geometryInstances: boxInstance,
asynchronous: false,
});
verifyClassificationPrimitiveRender(primitive, boxColor);
});
// Rendering in 2D/CV is broken:
// https://github.com/CesiumGS/cesium/issues/6308
xit("renders in Columbus view when scene3DOnly is false", function () {
if (!ClassificationPrimitive.isSupported(scene)) {
return;
}
primitive = new ClassificationPrimitive({
geometryInstances: boxInstance,
asynchronous: false,
});
scene.morphToColumbusView(0);
verifyClassificationPrimitiveRender(primitive, boxColor);
});
xit("renders in 2D when scene3DOnly is false", function () {
if (!ClassificationPrimitive.isSupported(scene)) {
return;
}
primitive = new ClassificationPrimitive({
geometryInstances: boxInstance,
asynchronous: false,
});
scene.morphTo2D(0);
verifyClassificationPrimitiveRender(primitive, boxColor);
});
it("renders batched instances", function () {
if (!ClassificationPrimitive.isSupported(scene)) {
return;
}
var neCarto = Rectangle.northeast(rectangle);
var nwCarto = Rectangle.northwest(rectangle);
var ne = ellipsoid.cartographicToCartesian(neCarto);
var nw = ellipsoid.cartographicToCartesian(nwCarto);
var direction = Cartesian3.subtract(ne, nw, new Cartesian3());
var distance = Cartesian3.magnitude(direction) * 0.25;
Cartesian3.normalize(direction, direction);
Cartesian3.multiplyByScalar(direction, distance, direction);
var center = Rectangle.center(rectangle);
var origin = ellipsoid.cartographicToCartesian(center);
var origin1 = Cartesian3.add(origin, direction, new Cartesian3());
var modelMatrix = Transforms.eastNorthUpToFixedFrame(origin1);
var dimensions = new Cartesian3(500000.0, 1000000.0, 1000000.0);
var boxColorAttribute = ColorGeometryInstanceAttribute.fromColor(
new Color(0.0, 1.0, 1.0, 1.0)
);
var boxInstance1 = new GeometryInstance({
geometry: BoxGeometry.fromDimensions({
dimensions: dimensions,
}),
modelMatrix: modelMatrix,
id: "box1",
attributes: {
color: boxColorAttribute,
},
});
Cartesian3.negate(direction, direction);
var origin2 = Cartesian3.add(origin, direction, new Cartesian3());
modelMatrix = Transforms.eastNorthUpToFixedFrame(origin2);
var boxInstance2 = new GeometryInstance({
geometry: BoxGeometry.fromDimensions({
dimensions: dimensions,
}),
modelMatrix: modelMatrix,
id: "box2",
attributes: {
color: boxColorAttribute,
},
});
primitive = new ClassificationPrimitive({
geometryInstances: [boxInstance1, boxInstance2],
asynchronous: false,
});
verifyClassificationPrimitiveRender(primitive, boxColorAttribute.value);
});
it("renders with invert classification and an opaque color", function () {
if (!ClassificationPrimitive.isSupported(scene)) {
return;
}
scene.invertClassification = true;
scene.invertClassificationColor = new Color(0.25, 0.25, 0.25, 1.0);
boxInstance.attributes.show = new ShowGeometryInstanceAttribute(true);
primitive = new ClassificationPrimitive({
geometryInstances: boxInstance,
asynchronous: false,
});
scene.camera.setView({ destination: rectangle });
var invertedColor = new Array(4);
invertedColor[0] = Color.floatToByte(
Color.byteToFloat(depthColor[0]) * scene.invertClassificationColor.red
);
invertedColor[1] = Color.floatToByte(
Color.byteToFloat(depthColor[1]) * scene.invertClassificationColor.green
);
invertedColor[2] = Color.floatToByte(
Color.byteToFloat(depthColor[2]) * scene.invertClassificationColor.blue
);
invertedColor[3] = 255;
scene.primitives.add(tilesetPrimitive);
expect(scene).toRender(invertedColor);
scene.primitives.add(primitive);
expect(scene).toRender(boxColor);
primitive.getGeometryInstanceAttributes("box").show = [0];
expect(scene).toRender(depthColor);
scene.invertClassification = false;
});
it("renders with invert classification and a translucent color", function () {
if (!ClassificationPrimitive.isSupported(scene)) {
return;
}
if (!InvertClassification.isTranslucencySupported(scene.context)) {
return;
}
scene.invertClassification = true;
scene.invertClassificationColor = new Color(0.25, 0.25, 0.25, 0.25);
boxInstance.attributes.show = new ShowGeometryInstanceAttribute(true);
primitive = new ClassificationPrimitive({
geometryInstances: boxInstance,
asynchronous: false,
});
scene.camera.setView({ destination: rectangle });
var invertedColor = new Array(4);
invertedColor[0] = Color.floatToByte(
Color.byteToFloat(depthColor[0]) *
scene.invertClassificationColor.red *
scene.invertClassificationColor.alpha
);
invertedColor[1] = Color.floatToByte(
Color.byteToFloat(depthColor[1]) *
scene.invertClassificationColor.green *
scene.invertClassificationColor.alpha
);
invertedColor[2] = Color.floatToByte(
Color.byteToFloat(depthColor[2]) *
scene.invertClassificationColor.blue *
scene.invertClassificationColor.alpha
);
invertedColor[3] = 255;
scene.primitives.add(tilesetPrimitive);
expect(scene).toRender(invertedColor);
scene.primitives.add(primitive);
expect(scene).toRender(boxColor);
primitive.getGeometryInstanceAttributes("box").show = [0];
expect(scene).toRender(depthColor);
scene.invertClassification = false;
});
it("renders bounding volume with debugShowBoundingVolume", function () {
if (!ClassificationPrimitive.isSupported(scene)) {
return;
}
primitive = new ClassificationPrimitive({
geometryInstances: boxInstance,
asynchronous: false,
debugShowBoundingVolume: true,
});
scene.primitives.add(primitive);
scene.camera.setView({ destination: rectangle });
expect(scene).toRenderAndCall(function (rgba) {
expect(rgba[1]).toBeGreaterThanOrEqualTo(0);
expect(rgba[1]).toBeGreaterThanOrEqualTo(0);
expect(rgba[2]).toBeGreaterThanOrEqualTo(0);
expect(rgba[3]).toEqual(255);
});
});
it("renders shadow volume with debugShowShadowVolume", function () {
if (!ClassificationPrimitive.isSupported(scene)) {
return;
}
primitive = new ClassificationPrimitive({
geometryInstances: boxInstance,
asynchronous: false,
debugShowShadowVolume: true,
});
scene.primitives.add(primitive);
scene.camera.setView({ destination: rectangle });
expect(scene).toRenderAndCall(function (rgba) {
expect(rgba[1]).toBeGreaterThanOrEqualTo(0);
expect(rgba[1]).toBeGreaterThanOrEqualTo(0);
expect(rgba[2]).toBeGreaterThanOrEqualTo(0);
expect(rgba[3]).toEqual(255);
});
});
it("get per instance attributes", function () {
if (!ClassificationPrimitive.isSupported(scene)) {
return;
}
primitive = new ClassificationPrimitive({
geometryInstances: boxInstance,
asynchronous: false,
});
verifyClassificationPrimitiveRender(primitive, boxColor);
var attributes = primitive.getGeometryInstanceAttributes("box");
expect(attributes.color).toBeDefined();
});
it("modify color instance attribute", function () {
if (!ClassificationPrimitive.isSupported(scene)) {
return;
}
primitive = new ClassificationPrimitive({
geometryInstances: boxInstance,
asynchronous: false,
});
verifyClassificationPrimitiveRender(primitive, boxColor);
scene.primitives.destroyPrimitives = false;
scene.primitives.removeAll();
scene.primitives.destroyPrimitives = true;
scene.primitives.destroyPrimitives = false;
scene.primitives.removeAll();
scene.primitives.destroyPrimitives = true;
var newColor = [255, 255, 255, 255];
var attributes = primitive.getGeometryInstanceAttributes("box");
expect(attributes.color).toBeDefined();
attributes.color = newColor;
verifyClassificationPrimitiveRender(primitive, newColor);
});
it("modify show instance attribute", function () {
if (!ClassificationPrimitive.isSupported(scene)) {
return;
}
boxInstance.attributes.show = new ShowGeometryInstanceAttribute(true);
primitive = new ClassificationPrimitive({
geometryInstances: boxInstance,
asynchronous: false,
});
verifyClassificationPrimitiveRender(primitive, boxColor);
scene.primitives.destroyPrimitives = false;
scene.primitives.removeAll();
scene.primitives.destroyPrimitives = true;
scene.primitives.destroyPrimitives = false;
scene.primitives.removeAll();
scene.primitives.destroyPrimitives = true;
var attributes = primitive.getGeometryInstanceAttributes("box");
expect(attributes.show).toBeDefined();
attributes.show = [0];
verifyClassificationPrimitiveRender(primitive, depthColor);
});
it("get bounding sphere from per instance attribute", function () {
if (!ClassificationPrimitive.isSupported(scene)) {
return;
}
primitive = new ClassificationPrimitive({
geometryInstances: boxInstance,
asynchronous: false,
});
verifyClassificationPrimitiveRender(primitive, boxColor);
var attributes = primitive.getGeometryInstanceAttributes("box");
expect(attributes.boundingSphere).toBeDefined();
});
it("getGeometryInstanceAttributes returns same object each time", function () {
if (!ClassificationPrimitive.isSupported(scene)) {
return;
}
primitive = new ClassificationPrimitive({
geometryInstances: boxInstance,
asynchronous: false,
});
verifyClassificationPrimitiveRender(primitive, boxColor);
var attributes = primitive.getGeometryInstanceAttributes("box");
var attributes2 = primitive.getGeometryInstanceAttributes("box");
expect(attributes).toBe(attributes2);
});
it("picking", function () {
if (!ClassificationPrimitive.isSupported(scene)) {
return;
}
primitive = new ClassificationPrimitive({
geometryInstances: boxInstance,
asynchronous: false,
});
verifyClassificationPrimitiveRender(primitive, boxColor);
expect(scene).toPickAndCall(function (result) {
expect(result.id).toEqual("box");
});
});
it("drill picking", function () {
if (!ClassificationPrimitive.isSupported(scene)) {
return;
}
primitive = new ClassificationPrimitive({
geometryInstances: boxInstance,
asynchronous: false,
});
verifyClassificationPrimitiveRender(primitive, boxColor);
expect(scene).toDrillPickAndCall(function (pickedObjects) {
expect(pickedObjects.length).toEqual(3);
expect(pickedObjects[0].primitive).toEqual(primitive);
expect(pickedObjects[1].primitive).toEqual(globePrimitive._primitive);
expect(pickedObjects[2].primitive).toEqual(tilesetPrimitive._primitive);
});
});
it("does not pick when allowPicking is false", function () {
if (!ClassificationPrimitive.isSupported(scene)) {
return;
}
primitive = new ClassificationPrimitive({
geometryInstances: boxInstance,
allowPicking: false,
asynchronous: false,
});
verifyClassificationPrimitiveRender(primitive, boxColor);
expect(scene).notToPick();
});
it("internally invalid asynchronous geometry resolves promise and sets ready", function () {
if (!ClassificationPrimitive.isSupported(scene)) {
return;
}
primitive = new ClassificationPrimitive({
geometryInstances: new GeometryInstance({
geometry: PolygonGeometry.fromPositions({
positions: [],
}),
attributes: {
color: ColorGeometryInstanceAttribute.fromColor(Color.RED),
},
}),
compressVertices: false,
});
scene.primitives.add(primitive);
return pollToPromise(function () {
scene.renderForSpecs();
return primitive.ready;
}).then(function () {
return primitive.readyPromise.then(function (arg) {
expect(arg).toBe(primitive);
expect(primitive.ready).toBe(true);
});
});
});
it("internally invalid synchronous geometry resolves promise and sets ready", function () {
if (!ClassificationPrimitive.isSupported(scene)) {
return;
}
primitive = new ClassificationPrimitive({
geometryInstances: new GeometryInstance({
geometry: PolygonGeometry.fromPositions({
positions: [],
}),
attributes: {
color: ColorGeometryInstanceAttribute.fromColor(Color.RED),
},
}),
asynchronous: false,
compressVertices: false,
});
scene.primitives.add(primitive);
scene.renderForSpecs();
return primitive.readyPromise.then(function (arg) {
expect(arg).toBe(primitive);
expect(primitive.ready).toBe(true);
});
});
it("update throws when batched instance colors are different and no culling attributes are provided", function () {
if (!ClassificationPrimitive.isSupported(scene)) {
return;
}
var neCarto = Rectangle.northeast(rectangle);
var nwCarto = Rectangle.northwest(rectangle);
var ne = ellipsoid.cartographicToCartesian(neCarto);
var nw = ellipsoid.cartographicToCartesian(nwCarto);
var direction = Cartesian3.subtract(ne, nw, new Cartesian3());
var distance = Cartesian3.magnitude(direction) * 0.25;
Cartesian3.normalize(direction, direction);
Cartesian3.multiplyByScalar(direction, distance, direction);
var center = Rectangle.center(rectangle);
var origin = ellipsoid.cartographicToCartesian(center);
var origin1 = Cartesian3.add(origin, direction, new Cartesian3());
var modelMatrix = Transforms.eastNorthUpToFixedFrame(origin1);
var dimensions = new Cartesian3(500000.0, 1000000.0, 1000000.0);
var boxColorAttribute = ColorGeometryInstanceAttribute.fromColor(
new Color(0.0, 1.0, 1.0, 1.0)
);
var boxInstance1 = new GeometryInstance({
geometry: BoxGeometry.fromDimensions({
dimensions: dimensions,
}),
modelMatrix: modelMatrix,
id: "box1",
attributes: {
color: ColorGeometryInstanceAttribute.fromColor(
new Color(0.0, 1.0, 1.0, 1.0)
),
},
});
Cartesian3.negate(direction, direction);
var origin2 = Cartesian3.add(origin, direction, new Cartesian3());
modelMatrix = Transforms.eastNorthUpToFixedFrame(origin2);
var boxInstance2 = new GeometryInstance({
geometry: BoxGeometry.fromDimensions({
dimensions: dimensions,
}),
modelMatrix: modelMatrix,
id: "box2",
attributes: {
color: ColorGeometryInstanceAttribute.fromColor(
new Color(1.0, 0.0, 1.0, 1.0)
),
},
});
primitive = new ClassificationPrimitive({
geometryInstances: [boxInstance1, boxInstance2],
asynchronous: false,
});
expect(function () {
verifyClassificationPrimitiveRender(primitive, boxColorAttribute.value);
}).toThrowDeveloperError();
});
it("update throws when one batched instance color is undefined", function () {
if (!ClassificationPrimitive.isSupported(scene)) {
return;
}
var neCarto = Rectangle.northeast(rectangle);
var nwCarto = Rectangle.northwest(rectangle);
var ne = ellipsoid.cartographicToCartesian(neCarto);
var nw = ellipsoid.cartographicToCartesian(nwCarto);
var direction = Cartesian3.subtract(ne, nw, new Cartesian3());
var distance = Cartesian3.magnitude(direction) * 0.25;
Cartesian3.normalize(direction, direction);
Cartesian3.multiplyByScalar(direction, distance, direction);
var center = Rectangle.center(rectangle);
var origin = ellipsoid.cartographicToCartesian(center);
var origin1 = Cartesian3.add(origin, direction, new Cartesian3());
var modelMatrix = Transforms.eastNorthUpToFixedFrame(origin1);
var dimensions = new Cartesian3(500000.0, 1000000.0, 1000000.0);
var boxColorAttribute = ColorGeometryInstanceAttribute.fromColor(
new Color(0.0, 1.0, 1.0, 1.0)
);
var boxInstance1 = new GeometryInstance({
geometry: BoxGeometry.fromDimensions({
dimensions: dimensions,
}),
modelMatrix: modelMatrix,
id: "box1",
attributes: {
color: ColorGeometryInstanceAttribute.fromColor(
new Color(0.0, 1.0, 1.0, 1.0)
),
},
});
Cartesian3.negate(direction, direction);
var origin2 = Cartesian3.add(origin, direction, new Cartesian3());
modelMatrix = Transforms.eastNorthUpToFixedFrame(origin2);
var boxInstance2 = new GeometryInstance({
geometry: BoxGeometry.fromDimensions({
dimensions: dimensions,
}),
modelMatrix: modelMatrix,
id: "box2",
});
primitive = new ClassificationPrimitive({
geometryInstances: [boxInstance1, boxInstance2],
asynchronous: false,
});
expect(function () {
verifyClassificationPrimitiveRender(primitive, boxColorAttribute.value);
}).toThrowDeveloperError();
});
it("update throws when no batched instance colors are given for a PerInstanceColorAppearance", function () {
if (!ClassificationPrimitive.isSupported(scene)) {
return;
}
var neCarto = Rectangle.northeast(rectangle);
var nwCarto = Rectangle.northwest(rectangle);
var ne = ellipsoid.cartographicToCartesian(neCarto);
var nw = ellipsoid.cartographicToCartesian(nwCarto);
var direction = Cartesian3.subtract(ne, nw, new Cartesian3());
var distance = Cartesian3.magnitude(direction) * 0.25;
Cartesian3.normalize(direction, direction);
Cartesian3.multiplyByScalar(direction, distance, direction);
var center = Rectangle.center(rectangle);
var origin = ellipsoid.cartographicToCartesian(center);
var origin1 = Cartesian3.add(origin, direction, new Cartesian3());
var modelMatrix = Transforms.eastNorthUpToFixedFrame(origin1);
var dimensions = new Cartesian3(500000.0, 1000000.0, 1000000.0);
var boxInstance1 = new GeometryInstance({
geometry: BoxGeometry.fromDimensions({
dimensions: dimensions,
}),
modelMatrix: modelMatrix,
id: "box1",
});
primitive = new ClassificationPrimitive({
geometryInstances: [boxInstance1],
asynchronous: false,
appearance: new PerInstanceColorAppearance(),
});
var boxColorAttribute = ColorGeometryInstanceAttribute.fromColor(
new Color(0.0, 1.0, 1.0, 1.0)
);
expect(function () {
verifyClassificationPrimitiveRender(primitive, boxColorAttribute.value);
}).toThrowDeveloperError();
});
it("update throws when the given Appearance is incompatible with the geometry instance attributes", function () {
if (!ClassificationPrimitive.isSupported(scene)) {
return;
}
primitive = new ClassificationPrimitive({
geometryInstances: [boxInstance],
asynchronous: false,
appearance: new MaterialAppearance(),
});
expect(function () {
verifyClassificationPrimitiveRender(primitive, [255, 255, 255, 255]);
}).toThrowDeveloperError();
});
it("update throws when an incompatible Appearance is set", function () {
if (!ClassificationPrimitive.isSupported(scene)) {
return;
}
primitive = new ClassificationPrimitive({
geometryInstances: [boxInstance],
asynchronous: false,
appearance: new PerInstanceColorAppearance(),
});
scene.camera.setView({ destination: rectangle });
scene.primitives.add(globePrimitive);
expect(scene).toRenderAndCall(function (rgba) {
expect(rgba).not.toEqual([0, 0, 0, 255]);
expect(rgba[0]).toEqual(0);
});
scene.primitives.add(primitive);
expect(scene).toRender([255, 255, 0, 255]);
// become incompatible
primitive.appearance = new MaterialAppearance();
expect(function () {
expect(scene).toRender([255, 255, 255, 255]);
}).toThrowDeveloperError();
});
it("setting per instance attribute throws when value is undefined", function () {
if (!ClassificationPrimitive.isSupported(scene)) {
return;
}
primitive = new ClassificationPrimitive({
geometryInstances: boxInstance,
asynchronous: false,
});
verifyClassificationPrimitiveRender(primitive, boxColor);
var attributes = primitive.getGeometryInstanceAttributes("box");
expect(function () {
attributes.color = undefined;
}).toThrowDeveloperError();
});
it("can disable picking when asynchronous", function () {
if (!ClassificationPrimitive.isSupported(scene)) {
return;
}
primitive = new ClassificationPrimitive({
geometryInstances: boxInstance,
asynchronous: true,
allowPicking: false,
});
scene.primitives.add(primitive);
return pollToPromise(function () {
scene.renderForSpecs();
return primitive.ready;
}).then(function () {
var attributes = primitive.getGeometryInstanceAttributes("box");
expect(function () {
attributes.color = undefined;
}).toThrowDeveloperError();
});
});
it("getGeometryInstanceAttributes throws without id", function () {
if (!ClassificationPrimitive.isSupported(scene)) {
return;
}
primitive = new ClassificationPrimitive({
geometryInstances: boxInstance,
asynchronous: false,
});
verifyClassificationPrimitiveRender(primitive, boxColor);
expect(function () {
primitive.getGeometryInstanceAttributes();
}).toThrowDeveloperError();
});
it("getGeometryInstanceAttributes throws if update was not called", function () {
primitive = new ClassificationPrimitive({
geometryInstances: boxInstance,
asynchronous: false,
});
expect(function () {
primitive.getGeometryInstanceAttributes("box");
}).toThrowDeveloperError();
});
it("getGeometryInstanceAttributes returns undefined if id does not exist", function () {
if (!ClassificationPrimitive.isSupported(scene)) {
return;
}
primitive = new ClassificationPrimitive({
geometryInstances: boxInstance,
asynchronous: false,
});
verifyClassificationPrimitiveRender(primitive, boxColor);
expect(
primitive.getGeometryInstanceAttributes("unknown")
).not.toBeDefined();
});
it("isDestroyed", function () {
primitive = new ClassificationPrimitive();
expect(primitive.isDestroyed()).toEqual(false);
primitive.destroy();
expect(primitive.isDestroyed()).toEqual(true);
});
it("renders when using asynchronous pipeline", function () {
if (!ClassificationPrimitive.isSupported(scene)) {
return;
}
primitive = new ClassificationPrimitive({
geometryInstances: boxInstance,
});
scene.primitives.add(primitive);
return pollToPromise(function () {
scene.renderForSpecs();
return primitive.ready;
}).then(function () {
// verifyClassificationPrimitiveRender adds the primitive, so remove it to avoid being added twice.
scene.primitives.destroyPrimitives = false;
scene.primitives.removeAll();
scene.primitives.destroyPrimitives = true;
verifyClassificationPrimitiveRender(primitive, boxColor);
});
});
it("destroy before asynchronous pipeline is complete", function () {
if (!ClassificationPrimitive.isSupported(scene)) {
return;
}
primitive = new ClassificationPrimitive({
geometryInstances: boxInstance,
});
scene.primitives.add(primitive);
scene.renderForSpecs();
primitive.destroy();
expect(primitive.isDestroyed()).toEqual(true);
// The primitive has already been destroyed, so remove it from the scene so it doesn't get destroyed again.
scene.primitives.destroyPrimitives = false;
scene.primitives.removeAll();
scene.primitives.destroyPrimitives = true;
});
},
"WebGL"
);
| progsung/cesium | Specs/Scene/ClassificationPrimitiveSpec.js | JavaScript | apache-2.0 | 37,911 |
<!--
@license
Copyright 2016 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<link rel="import" href="../polymer/polymer.html">
<link rel="import" href="../iron-collapse/iron-collapse.html">
<link rel="import" href="../paper-input/paper-textarea.html">
<link rel="import" href="../paper-icon-button/paper-icon-button.html">
<link rel="import" href="../paper-tooltip/paper-tooltip.html">
<link rel="import" href="styles.html">
<dom-module id="vz-projector-bookmark-panel">
<template>
<style include="vz-projector-styles"></style>
<style>
#title {
background-color: #fafafa;
color: black;
font-weight: 500;
left: 0;
line-height: 60px;
padding-left: 24px;
position: absolute;
width: 276px;
}
#bookmark-container {
background-color: #fafafa;
}
#icon-container {
line-height: 60px;
position: absolute;
right: 0;
}
#header {
border-top: 1px solid rgba(0, 0, 0, 0.1);
position: relative;
}
#panel {
background-color: #fafafa;
position: relative;
overflow-y: scroll;
top: 60px;
max-height: 50vh;
}
paper-button {
border: 1px solid #ccc;
}
#save-container {
text-align: center;
}
.state-radio {
display: table-cell;
vertical-align: middle;
padding-top: 16px;
}
.state-label {
display: table-cell;
vertical-align: middle;
top: 14px;
}
.state-label-input {
width: 194px;
}
.state-clear {
display: table-cell;
vertical-align: middle;
padding-top: 20px;
}
#state-file {
display: none;
}
#no-bookmarks {
padding: 0 24px;
}
#action-buttons-container .add-icon-button {
background-color: #03a9f4;
color: white;
margin: 0 4px 4px auto;
right: 7px;
top: -4px;
}
.upload-download-icon-button {
padding: 0;
}
#action-buttons-container {
display: flex;
margin-left: 34px;
margin-top: 6px;
}
.ink-fab {
border-radius: 50%;
background: white;
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.3);
}
paper-textarea {
--paper-input-container-input: {
font-size: 12px;
}
--paper-font-caption: {
display: none
}
}
</style>
<!-- Bookmarking controls -->
<div id="bookmark-container">
<div id="header">
<div id="title">
BOOKMARKS ([[savedStates.length]])
<paper-icon-button icon="help" class="help-icon"></paper-icon-button>
<paper-tooltip animation-delay="0" position="top" offset="0">
Open this drawer to save a set of views of the projection, including
selected points. A file containing the bookmarks can then be saved and
later loaded to view them.
</paper-tooltip>
</div>
<div id="icon-container">
<!-- Icons and event handlers are inverted because the tray expands upwards. -->
<paper-icon-button id="expand-more"
icon="expand-less"
on-tap="_expandMore"></paper-icon-button>
<paper-icon-button id="expand-less"
style="display: none"
icon="expand-more"
on-tap="_expandLess"></paper-icon-button>
</div>
</div>
<iron-collapse id="panel">
<!-- Saving state section -->
<div id="state-section">
<template is="dom-if" if="[[!savedStates.length]]">
<p id="no-bookmarks">
No bookmarks yet, upload a bookmarks file or add a new bookmark by clicking the "+" below.
</p>
</template>
<template is="dom-repeat" items="{{savedStates}}">
<div class="state-row">
<div class="state-radio">
<template is="dom-if" if="{{item.isSelected}}">
<paper-icon-button icon="radio-button-checked"></paper-icon-button>
</template>
<template is="dom-if" if="{{!item.isSelected}}">
<paper-icon-button
icon="radio-button-unchecked"
data-index$="{{index}}"
on-tap="_radioButtonHandler"></paper-icon-button>
</template>
</div>
<div class="state-label">
<paper-textarea value="[[item.label]]"
class="state-label-input"
on-keyup="_labelChange"
data-index$="[[index]]"
autoresizing></paper-input>
</div>
<div class="state-clear">
<paper-icon-button
icon="clear"
data-index$="{{index}}"
on-tap="_clearButtonHandler"></paper-icon-button>
</div>
</div>
</template>
<div id="action-buttons-container">
<paper-icon-button
class="upload-download-icon-button"
icon="save"
title="Save bookmarks"
disabled="[[!hasStates]]"
on-tap="_downloadFile"></paper-icon-button>
<paper-icon-button
class="upload-download-icon-button"
icon="file-upload"
title="Load bookmarks"
on-tap="_uploadFile"></paper-icon-button>
<paper-icon-button
class="add-icon-button ink-fab"
icon="add"
title="Add bookmark"
on-tap="_addBookmark"></paper-icon-button>
<input type="file" id="state-file" name="state-file"/>
</div>
</div>
</iron-collapse>
</div>
</template>
</dom-module>
| tongwang01/tensorflow | tensorflow/tensorboard/components/vz_projector/vz-projector-bookmark-panel.html | HTML | apache-2.0 | 5,659 |
<?php
/*
* Copyright 2014 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
/**
* The "samples" collection of methods.
* Typical usage is:
* <code>
* $toolresultsService = new Google_Service_ToolResults(...);
* $samples = $toolresultsService->samples;
* </code>
*/
class Google_Service_ToolResults_Resource_ProjectsHistoriesExecutionsStepsPerfSampleSeriesSamples extends Google_Service_Resource
{
/**
* Creates a batch of PerfSamples - a client can submit multiple batches of Perf
* Samples through repeated calls to this method in order to split up a large
* request payload - duplicates and existing timestamp entries will be ignored.
* - the batch operation may partially succeed - the set of elements
* successfully inserted is returned in the response (omits items which already
* existed in the database). May return any of the following canonical error
* codes: - NOT_FOUND - The containing PerfSampleSeries does not exist
* (samples.batchCreate)
*
* @param string $projectId The cloud project
* @param string $historyId A tool results history ID.
* @param string $executionId A tool results execution ID.
* @param string $stepId A tool results step ID.
* @param string $sampleSeriesId A sample series id
* @param Google_Service_ToolResults_BatchCreatePerfSamplesRequest $postBody
* @param array $optParams Optional parameters.
* @return Google_Service_ToolResults_BatchCreatePerfSamplesResponse
*/
public function batchCreate($projectId, $historyId, $executionId, $stepId, $sampleSeriesId, Google_Service_ToolResults_BatchCreatePerfSamplesRequest $postBody, $optParams = array())
{
$params = array('projectId' => $projectId, 'historyId' => $historyId, 'executionId' => $executionId, 'stepId' => $stepId, 'sampleSeriesId' => $sampleSeriesId, 'postBody' => $postBody);
$params = array_merge($params, $optParams);
return $this->call('batchCreate', array($params), "Google_Service_ToolResults_BatchCreatePerfSamplesResponse");
}
/**
* Lists the Performance Samples of a given Sample Series - The list results are
* sorted by timestamps ascending - The default page size is 500 samples; and
* maximum size allowed 5000 - The response token indicates the last returned
* PerfSample timestamp - When the results size exceeds the page size, submit a
* subsequent request including the page token to return the rest of the samples
* up to the page limit May return any of the following canonical error codes: -
* OUT_OF_RANGE - The specified request page_token is out of valid range -
* NOT_FOUND - The containing PerfSampleSeries does not exist
* (samples.listProjectsHistoriesExecutionsStepsPerfSampleSeriesSamples)
*
* @param string $projectId The cloud project
* @param string $historyId A tool results history ID.
* @param string $executionId A tool results execution ID.
* @param string $stepId A tool results step ID.
* @param string $sampleSeriesId A sample series id
* @param array $optParams Optional parameters.
*
* @opt_param int pageSize The default page size is 500 samples, and the maximum
* size is 5000. If the page_size is greater than 5000, the effective page size
* will be 5000
* @opt_param string pageToken Optional, the next_page_token returned in the
* previous response
* @return Google_Service_ToolResults_ListPerfSamplesResponse
*/
public function listProjectsHistoriesExecutionsStepsPerfSampleSeriesSamples($projectId, $historyId, $executionId, $stepId, $sampleSeriesId, $optParams = array())
{
$params = array('projectId' => $projectId, 'historyId' => $historyId, 'executionId' => $executionId, 'stepId' => $stepId, 'sampleSeriesId' => $sampleSeriesId);
$params = array_merge($params, $optParams);
return $this->call('list', array($params), "Google_Service_ToolResults_ListPerfSamplesResponse");
}
}
| tsugiproject/tsugi | vendor/google/apiclient-services/src/Google/Service/ToolResults/Resource/ProjectsHistoriesExecutionsStepsPerfSampleSeriesSamples.php | PHP | apache-2.0 | 4,429 |
// This file was procedurally generated from the following sources:
// - src/top-level-await/await-expr-array-literal.case
// - src/top-level-await/syntax/export-class-decl.template
/*---
description: AwaitExpression ArrayLiteral (Valid syntax for top level await in export ClassDeclaration)
esid: prod-AwaitExpression
features: [top-level-await, class]
flags: [generated, module]
info: |
ModuleItem:
StatementListItem[~Yield, +Await, ~Return]
...
UnaryExpression[Yield, Await]
[+Await]AwaitExpression[?Yield]
AwaitExpression[Yield]:
await UnaryExpression[?Yield, +Await]
...
ExportDeclaration:
export * FromClause ;
export ExportClause FromClause ;
export ExportClause ;
export VariableStatement[~Yield, +Await]
export Declaration[~Yield, +Await]
export defaultHoistableDeclaration[~Yield, +Await, +Default]
export defaultClassDeclaration[~Yield, +Await, +Default]
export default[lookahead ∉ { function, async [no LineTerminator here] function, class }]AssignmentExpression[+In, ~Yield, ~Await];
Declaration[Yield, Await]:
HoistableDeclaration[?Yield, ?Await, ~Default]
ClassDeclaration[?Yield, ?Await, ~Default]
LexicalDeclaration[+In, ?Yield, ?Await]
ClassDeclaration[Yield, Await, Default]:
classBindingIdentifier[?Yield, ?Await] ClassTail[?Yield, ?Await]
[+Default] class ClassTail[?Yield, ?Await]
ClassTail[Yield, Await]:
ClassHeritage[?Yield, ?Await]_opt { ClassBody[?Yield, ?Await]_opt }
PrimaryExpression[Yield, Await]:
this
IdentifierReference[?Yield, ?Await]
Literal
ArrayLiteral[?Yield, ?Await]
ObjectLiteral[?Yield, ?Await]
FunctionExpression
ClassExpression[?Yield, ?Await]
GeneratorExpression
AsyncFunctionExpression
AsyncGeneratorExpression
RegularExpressionLiteral
TemplateLiteral[?Yield, ?Await, ~Tagged]
CoverParenthesizedExpressionAndArrowParameterList[?Yield, ?Await]
---*/
function fn() {
return function() {};
}
// extends CallExpression with arguments
export class C extends fn(await []) {};
| sebastienros/jint | Jint.Tests.Test262/test/language/module-code/top-level-await/syntax/export-class-decl-await-expr-array-literal.js | JavaScript | bsd-2-clause | 2,153 |
cask 'changes' do
version '1.7.3'
sha256 '64fd2d6af3f3a85fb6d172d5e9bce15ae07d4b94de5b2360181445227bcc9c1a'
# amazonaws.com is the official download host per the vendor homepage
url "https://bitbq_changes.s3.amazonaws.com/changes-#{version}.zip"
appcast 'https://bitbq_changes.s3.amazonaws.com/changes-production.xml'
name 'Changes'
homepage 'http://martiancraft.com/products/changes.html'
license :commercial
app 'Changes.app'
binary 'Changes.app/Contents/Resources/chdiff'
zap :delete => [
'~/Library/Preferences/com.bitbq.Changes.plist',
'~/Library/Application Support/Changes',
'~/Library/Caches/com.bitbq.Changes',
]
end
| mgryszko/homebrew-cask | Casks/changes.rb | Ruby | bsd-2-clause | 722 |
<?php
/**
* Cetemaster Services
* Effect Web 2 - MuOnline Suite Software
*
* Core App: Home Page - Forum Notices
* Last Update: 02/05/2012 - 02:40h
* Author: $CTM['Erick-Master']
*
* Cetemaster Services, Limited
* Copyright (c) 2010-2013. All Rights Reserved,
* www.cetemaster.com.br / www.cetemaster.com
*/
class Home_ForumNotices extends CTM_EWCore
{
private $config = array();
/**
* Init Module
*
* @return void
*/
public function initSection()
{
if($this->settings['HOME']['FORUM']['SHOW'] == true)
{
$this->config = $this->settings['HOME']['FORUM'];
switch($this->config['MODULE'])
{
case 1 : //Invision Power Board
$setData['TABLE'] = "topics";
$setData['FORUM_COLUMN'] = "forum_id";
$setData['ID_COLUMN'] = "tid";
$setData['TITLE'] = "title";
$setData['DATE'] = "start_date";
$setData['LINK'] = "index.php?showtopic";
break;
case 2 : //vBulletin
$setData['TABLE'] = "thread";
$setData['FORUM_COLUMN'] = "forumid";
$setData['ID_COLUMN'] = "threadid";
$setData['TITLE'] = "title";
$setData['DATE'] = "dateline";
$setData['LINK'] = "showthread.php?t";
break;
case 3 : //phpBB
$setData['TABLE'] = "topics";
$setData['FORUM_COLUMN'] = "forum_id";
$setData['ID_COLUMN'] = "topic_id";
$setData['TITLE'] = "topic_title";
$setData['DATE'] = "topic_time";
$setData['LINK'] = "viewtopic.php?t";
break;
case 4 : //Simple Machines Forum
$setData['TABLE'] = "topics";
$setData['FORUM_COLUMN'] = "id_board";
$setData['ID_COLUMN'] = "id_topic";
$setData['LINK'] = "index.php?topic";
$setData['POST']['TABLE'] = "messages";
$setData['POST']['TITLE'] = "subject";
$setData['POST']['DATE'] = "poster_time";
$setData['POST']['TOPIC_ID'] = "id_topic";
$setData['POST']['ID'] = "id_msg";
break;
default : //None
$setData = FALSE;
break;
}
if($setData)
{
if($loopData = $this->loadBoardNoticesData($setData))
{
$GLOBALS['home_module']['forumNotices'] = $loopData;
}
}
return NULL;
}
}
/**
* Board Notices Data
* Get notice from Board System
*
* @param array Settings
* @return array Result
*/
private function loadBoardNoticesData($data)
{
$this->DB->settings['mysql']['hostname'] = $this->config['MySQL']['HOST'];
$this->DB->settings['mysql']['hostport'] = $this->config['MySQL']['PORT'];
$this->DB->settings['mysql']['username'] = $this->config['MySQL']['USER'];
$this->DB->settings['mysql']['password'] = $this->config['MySQL']['PASS'];
$this->DB->settings['mysql']['database'] = $this->config['MySQL']['DATA'];
$this->DB->settings['mysql']['log_folder'] = "MySQL";
$this->DB->settings['mysql']['debug'] = in_array("mysql", explode(",", CTM_SQL_DEBUG_MODE));
$this->DB->settings['mysql']['hideErrors'] = TRUE;
if($this->DB->Connect("mysql"))
{
$query = "SELECT * FROM ".$this->config['PREFIX'].$data['TABLE']." WHERE ";
for($i = 1; $i <= sizeof($this->config['FORUM_ID']); $i++)
{
$this->DB->MySQL()->Arguments($this->config['FORUM_ID'][$i - 1]);
if($i < count($this->config['FORUM_ID'])) $query .= $data['FORUM_COLUMN']." = %d OR ";
else $query .= $data['FORUM_COLUMN']." = %d ";
}
$query .= "ORDER BY ".$data['ID_COLUMN']." DESC LIMIT ".$this->config['LIMIT'];
$this->DB->MySQL()->Arguments($this->config['LIMIT']);
if($topics = $this->DB->MySQL()->Query($query))
{
if($this->DB->MySQL()->CountRows($topics) > 0)
{
$notices = array();
while($notice = $this->DB->MySQL()->FetchObject($topics))
{
if(isset($data['POST']) && is_array($data['POST']))
{
$this->DB->MySQL()->Arguments($data['POST']['TITLE'], $data['POST']['DATE'], $this->config['PREFIX'].$data['POST']['TABLE']);
$this->DB->MySQL()->Arguments($data['POST']['TOPIC_ID'], $notice->{$data['ID_COLUMN']}, $data['POST']['ID']);
$query = $this->DB->MySQL()->Query("SELECT %s,%s FROM %s WHERE %s = %d ORDER BY %s ASC");
$fetch = $this->DB->MySQL()->FetchObject($query);
$title = $fetch->{$data['POST']['TITLE']};
$date = $fetch->{$data['POST']['DATE']};
}
else
{
$title = $notice->{$data['TITLE']};
$date = $notice->{$data['DATE']};
}
$link = $this->config['LINK'];
$link .= substr($this->config['LINK'], strlen($this->config['LINK']) - 1, 1) != "/" ? "/" : NULL;
$link .= $data['LINK']."=".$notice->{$data['ID_COLUMN']};
$notices[] = array
(
"title" => $this->config['UTF8_DECODE'] == true ? CTM_Text::UTF8Text($title) : $title,
"postDate" => date("d/m/Y - h:i a", $date),
"topicLink" => $link
);
}
$this->DB->Clear(true, true);
return $notices;
}
else
{
$this->DB->Clear(true, true);
return 255;
}
}
$this->DB->Clear(true, true);
$this->DB->MySQL()->Close();
}
return false;
}
} | IcaroPirazza/effectweb-project | src/modules/applications/apps_ctm/ctm.effectweb/modules/home/forumnotices.php | PHP | bsd-2-clause | 5,212 |
class Mtools < Formula
desc "Tools for manipulating MSDOS files"
homepage "https://www.gnu.org/software/mtools/"
url "https://ftp.gnu.org/gnu/mtools/mtools-4.0.24.tar.gz"
mirror "https://ftpmirror.gnu.org/mtools/mtools-4.0.24.tar.gz"
sha256 "3483bdf233e77d0cf060de31df8e9f624c4bf26bd8a38ef22e06ca799d60c74e"
license "GPL-3.0"
livecheck do
url :stable
end
bottle do
cellar :any_skip_relocation
sha256 "a5229fbfcd666abf4c79cd065be6a58801228460f999319a0234319ccb8aba3a" => :catalina
sha256 "3a9d80e7a7e9a6dd377d0030a5fbc29e509ca6dd598e24943b36169ed1512670" => :mojave
sha256 "ebed9be10002c3a8a68089ff43702b24f1f2c451be9e14778eaece3ad4e0cdc0" => :high_sierra
end
conflicts_with "multimarkdown", because: "both install `mmd` binaries"
def install
# Prevents errors such as "mainloop.c:89:15: error: expected ')'"
# Upstream issue https://lists.gnu.org/archive/html/info-mtools/2014-02/msg00000.html
if ENV.cc == "clang"
inreplace "sysincludes.h",
"# define UNUSED(x) x __attribute__ ((unused));x",
"# define UNUSED(x) x"
end
args = %W[
LIBS=-liconv
--disable-debug
--prefix=#{prefix}
--sysconfdir=#{etc}
--without-x
]
system "./configure", *args
system "make"
ENV.deparallelize
system "make", "install"
end
test do
assert_match /#{version}/, shell_output("#{bin}/mtools --version")
end
end
| jabenninghoff/homebrew-core | Formula/mtools.rb | Ruby | bsd-2-clause | 1,440 |
// Copyright (C) 2015 the V8 project authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/*---
es6id: 21.1.2.4
description: >
Returns abrupt from nextKey.
info: |
21.1.2.4 String.raw ( template , ...substitutions )
...
10. Let stringElements be a new List.
11. Let nextIndex be 0.
12. Repeat
a. Let nextKey be ToString(nextIndex).
b. Let nextSeg be ToString(Get(raw, nextKey)).
c. ReturnIfAbrupt(nextSeg).
...
---*/
var obj = {
raw: {
length: 2
}
};
Object.defineProperty(obj.raw, '0', {
get: function() {
throw new Test262Error();
},
configurable: true
});
assert.throws(Test262Error, function() {
String.raw(obj);
});
delete obj.raw['0'];
obj.raw['0'] = 'a';
Object.defineProperty(obj.raw, '1', {
get: function() {
throw new Test262Error();
}
});
assert.throws(Test262Error, function() {
String.raw(obj);
});
| sebastienros/jint | Jint.Tests.Test262/test/built-ins/String/raw/returns-abrupt-from-next-key.js | JavaScript | bsd-2-clause | 921 |
cask :v1 => 'diffmerge' do
version '4.2.0.697'
sha256 '2c6368653af2440bb4460aef9bb1b2b5d8b84b5a3f47994c4abafc4d7ddbff9e'
url "http://download-us.sourcegear.com/DiffMerge/4.2.0/DiffMerge.#{version}.intel.stable.dmg"
homepage 'http://www.sourcegear.com/diffmerge'
license :unknown # todo: improve this machine-generated value
app 'DiffMerge.app'
binary 'DiffMerge.app/Contents/MacOS/DiffMerge', :target => 'diffmerge'
caveats <<-EOS.undent
Use "diffmerge --nosplash" to hide the splash screen when using
diffmerge with external tools such as git.
EOS
end
| andyshinn/homebrew-cask | Casks/diffmerge.rb | Ruby | bsd-2-clause | 585 |
from __future__ import unicode_literals
import warnings
from future.utils import with_metaclass
from django.conf import settings
from django.contrib.auth import get_user_model as django_get_user_model
from django.core.exceptions import ImproperlyConfigured
from django.db.models import Model, Field
from django.utils.html import format_html
from mezzanine.utils.importing import import_dotted_path
def get_user_model():
warnings.warn(
"Mezzanine's get_user_model() is deprecated and will be removed in a "
"future version. Replace all uses of this function with Django's "
"django.contrib.auth.get_user_model().",
DeprecationWarning
)
return django_get_user_model()
def get_user_model_name():
"""
Returns the app_label.object_name string for the user model.
"""
return getattr(settings, "AUTH_USER_MODEL", "auth.User")
def _base_concrete_model(abstract, klass):
for kls in reversed(klass.__mro__):
if issubclass(kls, abstract) and not kls._meta.abstract:
return kls
def base_concrete_model(abstract, model):
"""
Used in methods of abstract models to find the super-most concrete
(non abstract) model in the inheritance chain that inherits from the
given abstract model. This is so the methods in the abstract model can
query data consistently across the correct concrete model.
Consider the following::
class Abstract(models.Model)
class Meta:
abstract = True
def concrete(self):
return base_concrete_model(Abstract, self)
class Super(Abstract):
pass
class Sub(Super):
pass
sub = Sub.objects.create()
sub.concrete() # returns Super
In actual Mezzanine usage, this allows methods in the ``Displayable`` and
``Orderable`` abstract models to access the ``Page`` instance when
instances of custom content types, (eg: models that inherit from ``Page``)
need to query the ``Page`` model to determine correct values for ``slug``
and ``_order`` which are only relevant in the context of the ``Page``
model and not the model of the custom content type.
"""
if hasattr(model, 'objects'):
# "model" is a model class
return (model if model._meta.abstract else
_base_concrete_model(abstract, model))
# "model" is a model instance
return (
_base_concrete_model(abstract, model.__class__) or
model.__class__)
def upload_to(field_path, default):
"""
Used as the ``upload_to`` arg for file fields - allows for custom
handlers to be implemented on a per field basis defined by the
``UPLOAD_TO_HANDLERS`` setting.
"""
from mezzanine.conf import settings
for k, v in settings.UPLOAD_TO_HANDLERS.items():
if k.lower() == field_path.lower():
return import_dotted_path(v)
return default
class AdminThumbMixin(object):
"""
Provides a thumbnail method on models for admin classes to
reference in the ``list_display`` definition.
"""
admin_thumb_field = None
def admin_thumb(self):
thumb = ""
if self.admin_thumb_field:
thumb = getattr(self, self.admin_thumb_field, "")
if not thumb:
return ""
from mezzanine.conf import settings
from mezzanine.core.templatetags.mezzanine_tags import thumbnail
x, y = settings.ADMIN_THUMB_SIZE.split('x')
thumb_url = thumbnail(thumb, x, y)
return format_html("<img src='{}{}'>", settings.MEDIA_URL, thumb_url)
admin_thumb.short_description = ""
class ModelMixinBase(type):
"""
Metaclass for ``ModelMixin`` which is used for injecting model
fields and methods into models defined outside of a project.
This currently isn't used anywhere.
"""
def __new__(cls, name, bases, attrs):
"""
Checks for an inner ``Meta`` class with a ``mixin_for``
attribute containing the model that this model will be mixed
into. Once found, copy over any model fields and methods onto
the model being mixed into, and return it as the actual class
definition for the mixin.
"""
if name == "ModelMixin":
# Actual ModelMixin class definition.
return super(ModelMixinBase, cls).__new__(cls, name, bases, attrs)
try:
mixin_for = attrs.pop("Meta").mixin_for
if not issubclass(mixin_for, Model):
raise TypeError
except (TypeError, KeyError, AttributeError):
raise ImproperlyConfigured("The ModelMixin class '%s' requires "
"an inner Meta class with the "
"``mixin_for`` attribute defined, "
"with a value that is a valid model.")
# Copy fields and methods onto the model being mixed into, and
# return it as the definition for the mixin class itself.
for k, v in attrs.items():
if isinstance(v, Field):
v.contribute_to_class(mixin_for, k)
elif k != "__module__":
setattr(mixin_for, k, v)
return mixin_for
class ModelMixin(with_metaclass(ModelMixinBase, object)):
"""
Used as a subclass for mixin models that inject their behaviour onto
models defined outside of a project. The subclass should define an
inner ``Meta`` class with a ``mixin_for`` attribute containing the
model that will be mixed into.
"""
| readevalprint/mezzanine | mezzanine/utils/models.py | Python | bsd-2-clause | 5,607 |
# Sample code from Programing Ruby, page 436
sorted = %w{ apple pear fig }.sort_by {|word| word.length}
sorted
| wkoszek/book-programming-ruby | src/ex0806.rb | Ruby | bsd-2-clause | 128 |
cask "switchhosts" do
arch = Hardware::CPU.intel? ? "x64" : "arm64"
version "4.1.0.6076"
if Hardware::CPU.intel?
sha256 "ba0e47d5d255f610a578641306d6aa8f13797d2b8da86c3b04ca08cccd774886"
else
sha256 "f7360db875930fb4065970bbab274aea98218ce2d2c85c833cd42cd03a10bdc2"
end
url "https://github.com/oldj/SwitchHosts/releases/download/v#{version.major_minor_patch}/SwitchHosts_mac_#{arch}_#{version}.dmg",
verified: "github.com/oldj/SwitchHosts/"
name "SwitchHosts"
desc "App to switch hosts"
homepage "https://oldj.github.io/SwitchHosts/"
livecheck do
url :url
strategy :github_latest
regex(%r{/SwitchHosts_mac_#{arch}[._-]v?(\d+(?:\.\d+)+)\.dmg}i)
end
app "SwitchHosts.app"
zap trash: [
"~/Library/Application Support/SwitchHosts",
"~/Library/Preferences/SwitchHosts.plist",
"~/Library/Saved Application State/SwitchHosts.savedState",
"~/.SwitchHosts",
]
end
| Amorymeltzer/homebrew-cask | Casks/switchhosts.rb | Ruby | bsd-2-clause | 930 |
// SPDX-License-Identifier: BSD-2-Clause
/*
* Copyright (c) 2001-2007, Tom St Denis
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
/* LibTomCrypt, modular cryptographic library -- Tom St Denis
*
* LibTomCrypt is a library that provides various cryptographic
* algorithms in a highly modular and flexible manner.
*
* The library is free for all purposes without any express
* guarantee it works.
*
* Tom St Denis, [email protected], http://libtom.org
*/
#include "tomcrypt.h"
/**
@file der_length_boolean.c
ASN.1 DER, get length of a BOOLEAN, Tom St Denis
*/
#ifdef LTC_DER
/**
Gets length of DER encoding of a BOOLEAN
@param outlen [out] The length of the DER encoding
@return CRYPT_OK if successful
*/
int der_length_boolean(unsigned long *outlen)
{
LTC_ARGCHK(outlen != NULL);
*outlen = 3;
return CRYPT_OK;
}
#endif
/* $Source: /cvs/libtom/libtomcrypt/src/pk/asn1/der/boolean/der_length_boolean.c,v $ */
/* $Revision: 1.3 $ */
/* $Date: 2006/12/28 01:27:24 $ */
| pascal-brand-st-dev/optee_os | core/lib/libtomcrypt/src/pk/asn1/der/boolean/der_length_boolean.c | C | bsd-2-clause | 2,282 |
// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CHROME_BROWSER_UI_CONTENT_SETTINGS_CONTENT_SETTING_IMAGE_MODEL_H_
#define CHROME_BROWSER_UI_CONTENT_SETTINGS_CONTENT_SETTING_IMAGE_MODEL_H_
#include "base/macros.h"
#include "base/memory/scoped_vector.h"
#include "base/strings/string16.h"
#include "build/build_config.h"
#include "chrome/browser/ui/content_settings/content_setting_bubble_model.h"
#include "chrome/browser/ui/content_settings/content_setting_bubble_model_delegate.h"
#include "components/content_settings/core/common/content_settings_types.h"
#include "ui/gfx/image/image.h"
namespace content {
class WebContents;
}
namespace gfx {
enum class VectorIconId;
}
// This model provides data (icon ids and tooltip) for the content setting icons
// that are displayed in the location bar.
class ContentSettingImageModel {
public:
virtual ~ContentSettingImageModel() {}
// Generates a vector of all image models to be used within one window.
static ScopedVector<ContentSettingImageModel>
GenerateContentSettingImageModels();
// Notifies this model that its setting might have changed and it may need to
// update its visibility, icon and tooltip.
virtual void UpdateFromWebContents(content::WebContents* web_contents) = 0;
// Creates the model for the bubble that will be attached to this image.
// The bubble model is owned by the caller.
virtual ContentSettingBubbleModel* CreateBubbleModel(
ContentSettingBubbleModel::Delegate* delegate,
content::WebContents* web_contents,
Profile* profile) = 0;
// Whether the animation should be run for the given |web_contents|.
virtual bool ShouldRunAnimation(content::WebContents* web_contents) = 0;
// Remembers that the animation has already run for the given |web_contents|,
// so that we do not restart it when the parent view is updated.
virtual void SetAnimationHasRun(content::WebContents* web_contents) = 0;
bool is_visible() const { return is_visible_; }
#if defined(OS_MACOSX)
// Calls UpdateFromWebContents() and returns true if the icon has changed.
bool UpdateFromWebContentsAndCheckIfIconChanged(
content::WebContents* web_contents);
#endif
gfx::Image GetIcon(SkColor nearby_text_color) const;
// Returns the resource ID of a string to show when the icon appears, or 0 if
// we don't wish to show anything.
int explanatory_string_id() const { return explanatory_string_id_; }
const base::string16& get_tooltip() const { return tooltip_; }
protected:
ContentSettingImageModel();
void set_icon_by_vector_id(gfx::VectorIconId id, gfx::VectorIconId badge_id) {
icon_id_ = id;
icon_badge_id_ = badge_id;
}
void set_visible(bool visible) { is_visible_ = visible; }
void set_explanatory_string_id(int text_id) {
explanatory_string_id_ = text_id;
}
void set_tooltip(const base::string16& tooltip) { tooltip_ = tooltip; }
private:
bool is_visible_;
gfx::VectorIconId icon_id_;
gfx::VectorIconId icon_badge_id_;
int explanatory_string_id_;
base::string16 tooltip_;
DISALLOW_COPY_AND_ASSIGN(ContentSettingImageModel);
};
// A subclass for an image model tied to a single content type.
class ContentSettingSimpleImageModel : public ContentSettingImageModel {
public:
explicit ContentSettingSimpleImageModel(ContentSettingsType content_type);
// ContentSettingImageModel implementation.
ContentSettingBubbleModel* CreateBubbleModel(
ContentSettingBubbleModel::Delegate* delegate,
content::WebContents* web_contents,
Profile* profile) override;
bool ShouldRunAnimation(content::WebContents* web_contents) override;
void SetAnimationHasRun(content::WebContents* web_contents) override;
// Factory method. Used only for testing.
static std::unique_ptr<ContentSettingImageModel>
CreateForContentTypeForTesting(ContentSettingsType content_type);
protected:
ContentSettingsType content_type() { return content_type_; }
private:
ContentSettingsType content_type_;
DISALLOW_COPY_AND_ASSIGN(ContentSettingSimpleImageModel);
};
// Image model for subresource filter icons in the location bar.
class ContentSettingSubresourceFilterImageModel
: public ContentSettingImageModel {
public:
ContentSettingSubresourceFilterImageModel();
void UpdateFromWebContents(content::WebContents* web_contents) override;
ContentSettingBubbleModel* CreateBubbleModel(
ContentSettingBubbleModel::Delegate* delegate,
content::WebContents* web_contents,
Profile* profile) override;
bool ShouldRunAnimation(content::WebContents* web_contents) override;
void SetAnimationHasRun(content::WebContents* web_contents) override;
private:
DISALLOW_COPY_AND_ASSIGN(ContentSettingSubresourceFilterImageModel);
};
#endif // CHROME_BROWSER_UI_CONTENT_SETTINGS_CONTENT_SETTING_IMAGE_MODEL_H_
| ssaroha/node-webrtc | third_party/webrtc/include/chromium/src/chrome/browser/ui/content_settings/content_setting_image_model.h | C | bsd-2-clause | 4,954 |
// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef COMPONENTS_SUBRESOURCE_FILTER_CORE_BROWSER_SUBRESOURCE_FILTER_FEATURES_TEST_SUPPORT_H_
#define COMPONENTS_SUBRESOURCE_FILTER_CORE_BROWSER_SUBRESOURCE_FILTER_FEATURES_TEST_SUPPORT_H_
#include <string>
#include "base/feature_list.h"
#include "base/macros.h"
#include "base/test/scoped_feature_list.h"
namespace subresource_filter {
namespace testing {
// Helper to override the state of the |kSafeBrowsingSubresourceFilter| feature
// and the maximum activation state during tests. Expects a pre-existing global
// base::FieldTrialList singleton.
class ScopedSubresourceFilterFeatureToggle {
public:
ScopedSubresourceFilterFeatureToggle(
base::FeatureList::OverrideState feature_state,
const std::string& maximum_activation_state,
const std::string& activation_scope);
ScopedSubresourceFilterFeatureToggle(
base::FeatureList::OverrideState feature_state,
const std::string& maximum_activation_state,
const std::string& activation_scope,
const std::string& activation_lists);
~ScopedSubresourceFilterFeatureToggle();
private:
base::test::ScopedFeatureList scoped_feature_list_;
DISALLOW_COPY_AND_ASSIGN(ScopedSubresourceFilterFeatureToggle);
};
} // namespace testing
} // namespace subresource_filter
#endif // COMPONENTS_SUBRESOURCE_FILTER_CORE_BROWSER_SUBRESOURCE_FILTER_FEATURES_TEST_SUPPORT_H_
| ssaroha/node-webrtc | third_party/webrtc/include/chromium/src/components/subresource_filter/core/browser/subresource_filter_features_test_support.h | C | bsd-2-clause | 1,537 |
// Copyright (C) 2016 the V8 project authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/*---
esid: sec-get-%typedarray%.prototype.bytelength
description: >
"byteLength" property of TypedArrayPrototype
info: |
%TypedArray%.prototype.byteLength is an accessor property whose set accessor
function is undefined.
Section 17: Every accessor property described in clauses 18 through 26 and in
Annex B.2 has the attributes {[[Enumerable]]: false, [[Configurable]]: true }
includes: [propertyHelper.js, testTypedArray.js]
features: [TypedArray]
---*/
var TypedArrayPrototype = TypedArray.prototype;
var desc = Object.getOwnPropertyDescriptor(TypedArrayPrototype, "byteLength");
assert.sameValue(desc.set, undefined);
assert.sameValue(typeof desc.get, "function");
verifyNotEnumerable(TypedArrayPrototype, "byteLength");
verifyConfigurable(TypedArrayPrototype, "byteLength");
| sebastienros/jint | Jint.Tests.Test262/test/built-ins/TypedArray/prototype/byteLength/prop-desc.js | JavaScript | bsd-2-clause | 932 |
#ifdef E_TYPEDEFS
#else
#ifndef E_WIDGET_ILIST_H
#define E_WIDGET_ILIST_H
EAPI Evas_Object *e_widget_ilist_add(Evas *evas, int icon_w, int icon_h, const char **value);
EAPI void e_widget_ilist_freeze(Evas_Object *obj);
EAPI void e_widget_ilist_thaw(Evas_Object *obj);
EAPI void e_widget_ilist_append(Evas_Object *obj, Evas_Object *icon, const char *label, void (*func) (void *data), void *data, const char *val);
EAPI void e_widget_ilist_append_relative(Evas_Object *obj, Evas_Object *icon, const char *label, void (*func) (void *data), void *data, const char *val, int relative);
EAPI void e_widget_ilist_prepend(Evas_Object *obj, Evas_Object *icon, const char *label, void (*func) (void *data), void *data, const char *val);
EAPI void e_widget_ilist_prepend_relative(Evas_Object *obj, Evas_Object *icon, const char *label, void (*func) (void *data), void *data, const char *val, int relative);
EAPI void e_widget_ilist_append_full(Evas_Object *obj, Evas_Object *icon, Evas_Object *end, const char *label, void (*func) (void *data), void *data, const char *val);
EAPI void e_widget_ilist_append_relative_full(Evas_Object *obj, Evas_Object *icon, Evas_Object *end, const char *label, void (*func) (void *data), void *data, const char *val, int relative);
EAPI void e_widget_ilist_prepend_full(Evas_Object *obj, Evas_Object *icon, Evas_Object *end, const char *label, void (*func) (void *data), void *data, const char *val);
EAPI void e_widget_ilist_prepend_relative_full(Evas_Object *obj, Evas_Object *icon, Evas_Object *end, const char *label, void (*func) (void *data), void *data, const char *val, int relative);
EAPI void e_widget_ilist_header_append_relative(Evas_Object *obj, Evas_Object *icon, const char *label, int relative);
EAPI void e_widget_ilist_header_prepend_relative(Evas_Object *obj, Evas_Object *icon, const char *label, int relative);
EAPI void e_widget_ilist_header_prepend(Evas_Object *obj, Evas_Object *icon, const char *label);
EAPI void e_widget_ilist_header_append(Evas_Object *obj, Evas_Object *icon, const char *label);
EAPI void e_widget_ilist_selector_set(Evas_Object *obj, int selector);
EAPI void e_widget_ilist_go(Evas_Object *obj);
EAPI void e_widget_ilist_clear(Evas_Object *obj);
EAPI int e_widget_ilist_count(Evas_Object *obj);
EAPI Eina_List const *e_widget_ilist_items_get(Evas_Object *obj);
EAPI Eina_Bool e_widget_ilist_nth_is_header(Evas_Object *obj, int n);
EAPI void e_widget_ilist_nth_label_set(Evas_Object *obj, int n, const char *label);
EAPI const char *e_widget_ilist_nth_label_get(Evas_Object *obj, int n);
EAPI void e_widget_ilist_nth_icon_set(Evas_Object *obj, int n, Evas_Object *icon);
EAPI Evas_Object *e_widget_ilist_nth_icon_get(Evas_Object *obj, int n);
EAPI void e_widget_ilist_nth_end_set(Evas_Object *obj, int n, Evas_Object *end);
EAPI Evas_Object *e_widget_ilist_nth_end_get(Evas_Object *obj, int n);
EAPI void *e_widget_ilist_nth_data_get(Evas_Object *obj, int n);
EAPI const char *e_widget_ilist_nth_value_get(Evas_Object *obj, int n);
EAPI Eina_Bool e_widget_ilist_item_is_header(const E_Ilist_Item *it);
EAPI const char *e_widget_ilist_item_label_get(const E_Ilist_Item *it);
EAPI Evas_Object *e_widget_ilist_item_icon_get(const E_Ilist_Item *it);
EAPI Evas_Object *e_widget_ilist_item_end_get(const E_Ilist_Item *it);
EAPI void *e_widget_ilist_item_data_get(const E_Ilist_Item *it);
EAPI const char *e_widget_ilist_item_value_get(const E_Ilist_Item *it);
EAPI void e_widget_ilist_nth_show(Evas_Object *obj, int n, int top);
EAPI void e_widget_ilist_selected_set(Evas_Object *obj, int n);
EAPI const Eina_List *e_widget_ilist_selected_items_get(Evas_Object *obj);
EAPI int e_widget_ilist_selected_get(Evas_Object *obj);
EAPI const char *e_widget_ilist_selected_label_get(Evas_Object *obj);
EAPI Evas_Object *e_widget_ilist_selected_icon_get(Evas_Object *obj);
EAPI Evas_Object *e_widget_ilist_selected_end_get(Evas_Object *obj);
EAPI void *e_widget_ilist_selected_data_get(Evas_Object *obj);
EAPI int e_widget_ilist_selected_count_get(Evas_Object *obj);
EAPI const char *e_widget_ilist_selected_value_get(Evas_Object *obj);
EAPI void e_widget_ilist_unselect(Evas_Object *obj);
EAPI void e_widget_ilist_remove_num(Evas_Object *obj, int n);
EAPI void e_widget_ilist_multi_select_set(Evas_Object *obj, Eina_Bool multi);
EAPI Eina_Bool e_widget_ilist_multi_select_get(Evas_Object *obj);
EAPI void e_widget_ilist_multi_select(Evas_Object *obj, int n);
EAPI void e_widget_ilist_range_select(Evas_Object *obj, int n);
EAPI void e_widget_ilist_preferred_size_get(Evas_Object *obj, Evas_Coord *w, Evas_Coord *h);
EAPI Eina_Bool e_widget_ilist_custom_edje_file_set(Evas_Object *obj, const char *file, const char *group);
#endif
#endif
| haxworx/Enform | src/bin/e_widget_ilist.h | C | bsd-2-clause | 4,990 |
class Dbxml < Formula
desc "Embeddable XML database with XQuery support and other advanced features"
homepage "https://www.oracle.com/us/products/database/berkeley-db/xml/overview/index.html"
url "http://download.oracle.com/berkeley-db/dbxml-6.0.18.tar.gz"
sha256 "5851f60a47920718b701752528a449f30b16ddbf5402a2a5e8cde8b4aecfabc8"
bottle do
cellar :any
sha256 "fb36c58d1ccfcbd8a64aff8f6296ada9379ade8413382b70275b6209216aed64" => :el_capitan
sha256 "2c1f4a931b7ffdf2a3a5d0a0aaf1be9434b4483549d47eda7868ee2fa4456837" => :yosemite
sha256 "c6975e34ad3640650a9da0f08e99f9f763ec47bc3532c28466233e10eaeccaa1" => :mavericks
end
depends_on "xerces-c"
depends_on "xqilla"
depends_on "berkeley-db"
def install
inreplace "dbxml/configure" do |s|
s.gsub! "lib/libdb-*.la | sed 's\/.*db-\\\(.*\\\).la", "lib/libdb-*.a | sed 's/.*db-\\(.*\\).a"
s.gsub! "lib/libdb-*.la", "lib/libdb-*.a"
end
cd "dbxml" do
system "./configure", "--disable-debug", "--disable-dependency-tracking",
"--prefix=#{prefix}",
"--with-xqilla=#{HOMEBREW_PREFIX}",
"--with-xerces=#{HOMEBREW_PREFIX}",
"--with-berkeleydb=#{HOMEBREW_PREFIX}"
system "make", "install"
end
end
test do
(testpath/"simple.xml").write <<-EOS.undent
<breakfast_menu>
<food>
<name>Belgian Waffles</name>
<calories>650</calories>
</food>
<food>
<name>Homestyle Breakfast</name>
<calories>950</calories>
</food>
</breakfast_menu>
EOS
(testpath/"dbxml.script").write <<-EOS.undent
createContainer ""
putDocument simple "simple.xml" f
cquery 'sum(//food/calories)'
print
quit
EOS
assert_equal "1600", shell_output("#{bin}/dbxml -s #{testpath}/dbxml.script").chomp
end
end
| andyjeffries/homebrew-core | Formula/dbxml.rb | Ruby | bsd-2-clause | 1,934 |
cask 'chat' do
version '1.0.3-1429112097'
sha256 '430028e75c0a01ae2f8cad9b3b2bb64ae30893c5fc4ce524b5c5dd3a9413c123'
# devmate.com is the official download host per the appcast feed
url "http://dl.devmate.com/com.perma.chat/#{version.sub(%r{-.*$},'')}/#{version.sub(%r{.*?-},'')}/Chat-#{version.sub(%r{-.*$},'')}.zip"
appcast 'http://updateinfo.devmate.com/com.perma.chat/updates.xml',
:sha256 => '8009a30326218077e451fc3e3096eb37c7eaa1c667d32f5beccdece99c6c8a4b'
name 'Chat'
homepage 'https://chatformac.com/'
license :gratis
app 'Chat.app'
end
| corbt/homebrew-cask | Casks/chat.rb | Ruby | bsd-2-clause | 575 |
# This Makefile is used under Linux
MATLABDIR ?= /usr/local/matlab
CXX ?= g++
#CXX = g++-3.3
CC ?= gcc
CFLAGS = -Wall -Wconversion -O3 -fPIC -I$(MATLABDIR)/extern/include -I.. -fopenmp
LDFLAGS += -fopenmp
MEX = $(MATLABDIR)/bin/mex
MEX_OPTION = CC="$(CXX)" CXX="$(CXX)" CFLAGS="$(CFLAGS)" CXXFLAGS="$(CFLAGS)" LDFLAGS="$(LDFLAGS)"
# comment the following line if you use MATLAB on a 32-bit computer
MEX_OPTION += -largeArrayDims
MEX_EXT = $(shell $(MATLABDIR)/bin/mexext)
all: matlab
matlab: binary
octave:
@echo "please type make under Octave"
binary: train.$(MEX_EXT) predict.$(MEX_EXT) libsvmread.$(MEX_EXT) libsvmwrite.$(MEX_EXT)
train.$(MEX_EXT): train.c ../linear.h ../tron.o ../linear.o linear_model_matlab.o ../blas/blas.a
$(MEX) $(MEX_OPTION) train.c ../tron.o ../linear.o linear_model_matlab.o ../blas/blas.a
predict.$(MEX_EXT): predict.c ../linear.h ../tron.o ../linear.o linear_model_matlab.o ../blas/blas.a
$(MEX) $(MEX_OPTION) predict.c ../tron.o ../linear.o linear_model_matlab.o ../blas/blas.a
libsvmread.$(MEX_EXT): libsvmread.c
$(MEX) $(MEX_OPTION) libsvmread.c
libsvmwrite.$(MEX_EXT): libsvmwrite.c
$(MEX) $(MEX_OPTION) libsvmwrite.c
linear_model_matlab.o: linear_model_matlab.c ../linear.h
$(CXX) $(CFLAGS) -c linear_model_matlab.c
../linear.o: ../linear.cpp ../linear.h
make -C .. linear.o
../tron.o: ../tron.cpp ../tron.h
make -C .. tron.o
../blas/blas.a: ../blas/*.c ../blas/*.h
make -C ../blas OPTFLAGS='$(CFLAGS)' CC='$(CC)';
clean:
make -C ../blas clean
rm -f *~ *.o *.mex* *.obj ../linear.o ../tron.o
| jhu-lcsr/sp_segmenter | utility/liblinear/matlab/Makefile | Makefile | bsd-2-clause | 1,554 |
class Blueharvest < Cask
url 'http://zeroonetwenty.com/downloads/BlueHarvest559.dmg'
homepage 'http://zeroonetwenty.com/blueharvest/'
version '5.5.9'
sha256 '4711a2ecdaee8364ef7e63d8bfb34d5539cd0e8f20b95fe31028bbcc6b22684f'
link 'BlueHarvest.app'
end
| okonomi/homebrew-cask | Casks/blueharvest.rb | Ruby | bsd-2-clause | 261 |
// Copyright (C) 2015 the V8 project authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/*---
es6id: 23.1.5.2.1
description: >
Throws a TypeError if `this` does not have all of the internal slots of a Map
Iterator Instance.
info: |
%MapIteratorPrototype%.next ( )
1. Let O be the this value.
2. If Type(O) is not Object, throw a TypeError exception.
3. If O does not have all of the internal slots of a Map Iterator Instance
(23.1.5.3), throw a TypeError exception.
...
features: [Symbol.iterator]
---*/
var map = new Map([[1, 11], [2, 22]]);
var iterator = map[Symbol.iterator]();
assert.throws(TypeError, function() {
iterator.next.call({});
});
iterator = map.entries();
assert.throws(TypeError, function() {
iterator.next.call({});
});
iterator = map.keys();
assert.throws(TypeError, function() {
iterator.next.call({});
});
iterator = map.values();
assert.throws(TypeError, function() {
iterator.next.call({});
});
// does not throw an Error
iterator.next.call(map[Symbol.iterator]());
| sebastienros/jint | Jint.Tests.Test262/test/built-ins/MapIteratorPrototype/next/does-not-have-mapiterator-internal-slots.js | JavaScript | bsd-2-clause | 1,072 |
cask 'lockdown' do
version '1.0.0'
sha256 '047f377e2a9495361084268c86cc80719e123bd8958d69fe51cd2be0d7ffd764'
# bitbucket.org/objective-see/ was verified as official when first introduced to the cask
url "https://bitbucket.org/objective-see/deploy/downloads/Lockdown_#{version}.zip"
appcast 'https://objective-see.com/products/changelogs/Lockdown.txt'
name 'Lockdown'
homepage 'https://objective-see.com/products/lockdown.html'
app 'Lockdown.app'
end
| sscotth/homebrew-cask | Casks/lockdown.rb | Ruby | bsd-2-clause | 468 |
// Copyright 2008 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Renderer for {@link goog.ui.style.app.MenuButton}s and
* subclasses.
*
* @author [email protected] (Attila Bodis)
* @author [email protected] (Greg Veen)
*/
goog.provide('goog.ui.style.app.MenuButtonRenderer');
goog.require('goog.array');
goog.require('goog.dom');
goog.require('goog.dom.a11y.Role');
goog.require('goog.style');
goog.require('goog.ui.ControlContent');
goog.require('goog.ui.Menu');
goog.require('goog.ui.MenuRenderer');
goog.require('goog.ui.style.app.ButtonRenderer');
/**
* Renderer for {@link goog.ui.style.app.MenuButton}s. This implementation
* overrides {@link goog.ui.style.app.ButtonRenderer#createButton} to insert a
* dropdown element into the content element after the specified content.
* @constructor
* @extends {goog.ui.style.app.ButtonRenderer}
*/
goog.ui.style.app.MenuButtonRenderer = function() {
goog.ui.style.app.ButtonRenderer.call(this);
};
goog.inherits(goog.ui.style.app.MenuButtonRenderer,
goog.ui.style.app.ButtonRenderer);
goog.addSingletonGetter(goog.ui.style.app.MenuButtonRenderer);
/**
* Default CSS class to be applied to the root element of components rendered
* by this renderer.
* @type {string}
*/
goog.ui.style.app.MenuButtonRenderer.CSS_CLASS =
goog.getCssName('goog-menu-button');
/**
* Array of arrays of CSS classes that we want composite classes added and
* removed for in IE6 and lower as a workaround for lack of multi-class CSS
* selector support.
* @type {Array.<Array.<string>>}
*/
goog.ui.style.app.MenuButtonRenderer.IE6_CLASS_COMBINATIONS = [
[goog.getCssName('goog-button-base-rtl'),
goog.getCssName('goog-menu-button')],
[goog.getCssName('goog-button-base-hover'),
goog.getCssName('goog-menu-button')],
[goog.getCssName('goog-button-base-focused'),
goog.getCssName('goog-menu-button')],
[goog.getCssName('goog-button-base-disabled'),
goog.getCssName('goog-menu-button')],
[goog.getCssName('goog-button-base-active'),
goog.getCssName('goog-menu-button')],
[goog.getCssName('goog-button-base-open'),
goog.getCssName('goog-menu-button')],
[goog.getCssName('goog-button-base-active'),
goog.getCssName('goog-button-base-open'),
goog.getCssName('goog-menu-button')]
];
/**
* Returns the ARIA role to be applied to menu buttons, which
* have a menu attached to them.
* @return {goog.dom.a11y.Role} ARIA role.
* @override
*/
goog.ui.style.app.MenuButtonRenderer.prototype.getAriaRole = function() {
// If we apply the 'button' ARIA role to the menu button, the
// screen reader keeps referring to menus as buttons, which
// might be misleading for the users. Hence the ARIA role
// 'menu' is assigned.
return goog.dom.a11y.Role.MENU;
};
/**
* Takes the button's root element and returns the parent element of the
* button's contents. Overrides the superclass implementation by taking
* the nested DIV structure of menu buttons into account.
* @param {Element} element Root element of the button whose content element
* is to be returned.
* @return {Element} The button's content element.
*/
goog.ui.style.app.MenuButtonRenderer.prototype.getContentElement =
function(element) {
return goog.ui.style.app.MenuButtonRenderer.superClass_.getContentElement
.call(this, element);
};
/**
* Takes an element, decorates it with the menu button control, and returns
* the element. Overrides {@link goog.ui.style.app.ButtonRenderer#decorate} by
* looking for a child element that can be decorated by a menu, and if it
* finds one, decorates it and attaches it to the menu button.
* @param {goog.ui.Control} control goog.ui.MenuButton to decorate the element.
* @param {Element} element Element to decorate.
* @return {Element} Decorated element.
* @override
*/
goog.ui.style.app.MenuButtonRenderer.prototype.decorate =
function(control, element) {
var button = /** @type {goog.ui.MenuButton} */ (control);
// TODO(attila): Add more robust support for subclasses of goog.ui.Menu.
var menuElem = goog.dom.getElementsByTagNameAndClass(
'*', goog.ui.MenuRenderer.CSS_CLASS, element)[0];
if (menuElem) {
// Move the menu element directly under the body (but hide it first to
// prevent flicker; see bug 1089244).
goog.style.showElement(menuElem, false);
goog.dom.appendChild(goog.dom.getOwnerDocument(menuElem).body, menuElem);
// Decorate the menu and attach it to the button.
var menu = new goog.ui.Menu();
menu.decorate(menuElem);
button.setMenu(menu);
}
// Let the superclass do the rest.
return goog.ui.style.app.MenuButtonRenderer.superClass_.decorate.call(this,
button, element);
};
/**
* Takes a text caption or existing DOM structure, and returns the content and
* a dropdown arrow element wrapped in a pseudo-rounded-corner box. Creates
* the following DOM structure:
* <div class="goog-inline-block goog-button-outer-box">
* <div class="goog-inline-block goog-button-inner-box">
* <div class="goog-button-pos">
* <div class="goog-button-top-shadow"> </div>
* <div class="goog-button-content">
* Contents...
* <div class="goog-menu-button-dropdown"> </div>
* </div>
* </div>
* </div>
* </div>
* @param {goog.ui.ControlContent} content Text caption or DOM structure to wrap
* in a box.
* @param {goog.dom.DomHelper} dom DOM helper, used for document interaction.
* @return {Element} Pseudo-rounded-corner box containing the content.
*/
goog.ui.style.app.MenuButtonRenderer.prototype.createButton = function(content,
dom) {
var contentWithDropdown = this.createContentWithDropdown(content, dom);
return goog.ui.style.app.MenuButtonRenderer.superClass_.createButton.call(
this, contentWithDropdown, dom);
};
/** @override */
goog.ui.style.app.MenuButtonRenderer.prototype.setContent = function(element,
content) {
var dom = goog.dom.getDomHelper(this.getContentElement(element));
goog.ui.style.app.MenuButtonRenderer.superClass_.setContent.call(
this, element, this.createContentWithDropdown(content, dom));
};
/**
* Inserts dropdown element as last child of existing content.
* @param {goog.ui.ControlContent} content Text caption or DOM structure.
* @param {goog.dom.DomHelper} dom DOM helper, used for document ineraction.
* @return {Array.<Node>} DOM structure to be set as the button's content.
*/
goog.ui.style.app.MenuButtonRenderer.prototype.createContentWithDropdown =
function(content, dom) {
var caption = dom.createDom('div', null, content, this.createDropdown(dom));
return goog.array.toArray(caption.childNodes);
};
/**
* Returns an appropriately-styled DIV containing a dropdown arrow.
* Creates the following DOM structure:
* <div class="goog-menu-button-dropdown"> </div>
* @param {goog.dom.DomHelper} dom DOM helper, used for document interaction.
* @return {Element} Dropdown element.
*/
goog.ui.style.app.MenuButtonRenderer.prototype.createDropdown = function(dom) {
return dom.createDom('div', goog.getCssName(this.getCssClass(), 'dropdown'));
};
/**
* Returns the CSS class to be applied to the root element of components
* rendered using this renderer.
* @return {string} Renderer-specific CSS class.
*/
goog.ui.style.app.MenuButtonRenderer.prototype.getCssClass = function() {
return goog.ui.style.app.MenuButtonRenderer.CSS_CLASS;
};
/** @override */
goog.ui.style.app.MenuButtonRenderer.prototype.getIe6ClassCombinations =
function() {
return goog.ui.style.app.MenuButtonRenderer.IE6_CLASS_COMBINATIONS;
};
| darkrsw/safe | tests/clone_detector_tests/closure-library-read-only/closure/goog/ui/style/app/menubuttonrenderer.js | JavaScript | bsd-3-clause | 8,199 |
---
title: Return Statement
localeTitle: Операция возврата
---
# Операция возврата
Оператор `return` завершает выполнение метода, внутри которого он появляется, и возвращает управление вызывающему методу. Он может или не может вернуть значение.
Если оператор `return` находится внутри блока `try` и если есть блок `finally` , тогда элемент управления передается блоку `finally` , после чего он возвращается вызывающему методу.
## пример
```
class Calc
{
static int Sum(int i, int j)
{
return i + j;
}
static void Main()
{
int a = 4;
int b = 3;
int sum = Sum(a, b);
Console.WriteLine($"The sum of {a} and {b} is {result}");
// To keep the console from closing
Console.ReadLine();
}
}
```
## Вывод:
\`\` \`
> Сумма 4 и 3 равна 7 \`\` | otavioarc/freeCodeCamp | guide/russian/csharp/return/index.md | Markdown | bsd-3-clause | 1,104 |
//////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2014, Image Engine Design Inc. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above
// copyright notice, this list of conditions and the following
// disclaimer.
//
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided with
// the distribution.
//
// * Neither the name of John Haddon nor the names of
// any other contributors to this software may be used to endorse or
// promote products derived from this software without specific prior
// written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
// IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////
#include "IECore/Timer.h"
#include "GafferScene/ScenePlug.h"
#include "GafferSceneTest/ScenePlugTest.h"
using namespace GafferScene;
void GafferSceneTest::testManyStringToPathCalls()
{
std::string s = "/i/am/a/fairly/long/string/for/testing/string/to/path";
ScenePlug::ScenePath p;
IECore::Timer t;
for( int i = 0; i < 100000; ++i )
{
ScenePlug::stringToPath( s, p );
}
// Uncomment to get timing information.
//std::cerr << t.stop() << std::endl;
}
| goddardl/gaffer | src/GafferSceneTest/ScenePlugTest.cpp | C++ | bsd-3-clause | 2,302 |
/***********************************************************************
Moses - factored phrase-based language decoder
Copyright (C) 2006 University of Edinburgh
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
***********************************************************************/
#include <cstring>
#include <iostream>
#include <memory>
#include <cstdlib>
#include <boost/shared_ptr.hpp>
#include <boost/lexical_cast.hpp>
#include "lm/binary_format.hh"
#include "lm/enumerate_vocab.hh"
#include "lm/left.hh"
#include "lm/model.hh"
#include "util/exception.hh"
#include "util/tokenize_piece.hh"
#include "util/string_stream.hh"
#include "Ken.h"
#include "Base.h"
#include "moses/FF/FFState.h"
#include "moses/TypeDef.h"
#include "moses/Util.h"
#include "moses/FactorCollection.h"
#include "moses/Phrase.h"
#include "moses/InputFileStream.h"
#include "moses/StaticData.h"
#include "moses/ChartHypothesis.h"
#include "moses/Incremental.h"
#include "moses/Syntax/SHyperedge.h"
#include "moses/Syntax/SVertex.h"
using namespace std;
namespace Moses
{
namespace
{
struct KenLMState : public FFState {
lm::ngram::State state;
virtual size_t hash() const {
size_t ret = hash_value(state);
return ret;
}
virtual bool operator==(const FFState& o) const {
const KenLMState &other = static_cast<const KenLMState &>(o);
bool ret = state == other.state;
return ret;
}
};
class MappingBuilder : public lm::EnumerateVocab
{
public:
MappingBuilder(FactorCollection &factorCollection, std::vector<lm::WordIndex> &mapping)
: m_factorCollection(factorCollection), m_mapping(mapping) {}
void Add(lm::WordIndex index, const StringPiece &str) {
std::size_t factorId = m_factorCollection.AddFactor(str)->GetId();
if (m_mapping.size() <= factorId) {
// 0 is <unk> :-)
m_mapping.resize(factorId + 1);
}
m_mapping[factorId] = index;
}
private:
FactorCollection &m_factorCollection;
std::vector<lm::WordIndex> &m_mapping;
};
} // namespace
template <class Model> void LanguageModelKen<Model>::LoadModel(const std::string &file, util::LoadMethod load_method)
{
m_lmIdLookup.clear();
lm::ngram::Config config;
if(this->m_verbosity >= 1) {
config.messages = &std::cerr;
} else {
config.messages = NULL;
}
FactorCollection &collection = FactorCollection::Instance();
MappingBuilder builder(collection, m_lmIdLookup);
config.enumerate_vocab = &builder;
config.load_method = load_method;
m_ngram.reset(new Model(file.c_str(), config));
VERBOSE(2, "LanguageModelKen " << m_description << " reset to " << file << "\n");
}
template <class Model> LanguageModelKen<Model>::LanguageModelKen(const std::string &line, const std::string &file, FactorType factorType, util::LoadMethod load_method)
:LanguageModel(line)
,m_beginSentenceFactor(FactorCollection::Instance().AddFactor(BOS_))
,m_factorType(factorType)
{
ReadParameters();
LoadModel(file, load_method);
}
template <class Model> LanguageModelKen<Model>::LanguageModelKen()
:LanguageModel("KENLM")
,m_beginSentenceFactor(FactorCollection::Instance().AddFactor(BOS_))
,m_factorType(0)
{
ReadParameters();
}
template <class Model> LanguageModelKen<Model>::LanguageModelKen(const LanguageModelKen<Model> ©_from)
:LanguageModel(copy_from.GetArgLine()),
m_ngram(copy_from.m_ngram),
// TODO: don't copy this.
m_beginSentenceFactor(copy_from.m_beginSentenceFactor),
m_factorType(copy_from.m_factorType),
m_lmIdLookup(copy_from.m_lmIdLookup)
{
}
template <class Model> const FFState * LanguageModelKen<Model>::EmptyHypothesisState(const InputType &/*input*/) const
{
KenLMState *ret = new KenLMState();
ret->state = m_ngram->BeginSentenceState();
return ret;
}
template <class Model> void LanguageModelKen<Model>::CalcScore(const Phrase &phrase, float &fullScore, float &ngramScore, size_t &oovCount) const
{
fullScore = 0;
ngramScore = 0;
oovCount = 0;
if (!phrase.GetSize()) return;
lm::ngram::ChartState discarded_sadly;
lm::ngram::RuleScore<Model> scorer(*m_ngram, discarded_sadly);
size_t position;
if (m_beginSentenceFactor == phrase.GetWord(0).GetFactor(m_factorType)) {
scorer.BeginSentence();
position = 1;
} else {
position = 0;
}
size_t ngramBoundary = m_ngram->Order() - 1;
size_t end_loop = std::min(ngramBoundary, phrase.GetSize());
for (; position < end_loop; ++position) {
const Word &word = phrase.GetWord(position);
if (word.IsNonTerminal()) {
fullScore += scorer.Finish();
scorer.Reset();
} else {
lm::WordIndex index = TranslateID(word);
scorer.Terminal(index);
if (!index) ++oovCount;
}
}
float before_boundary = fullScore + scorer.Finish();
for (; position < phrase.GetSize(); ++position) {
const Word &word = phrase.GetWord(position);
if (word.IsNonTerminal()) {
fullScore += scorer.Finish();
scorer.Reset();
} else {
lm::WordIndex index = TranslateID(word);
scorer.Terminal(index);
if (!index) ++oovCount;
}
}
fullScore += scorer.Finish();
ngramScore = TransformLMScore(fullScore - before_boundary);
fullScore = TransformLMScore(fullScore);
}
template <class Model> FFState *LanguageModelKen<Model>::EvaluateWhenApplied(const Hypothesis &hypo, const FFState *ps, ScoreComponentCollection *out) const
{
const lm::ngram::State &in_state = static_cast<const KenLMState&>(*ps).state;
std::auto_ptr<KenLMState> ret(new KenLMState());
if (!hypo.GetCurrTargetLength()) {
ret->state = in_state;
return ret.release();
}
const std::size_t begin = hypo.GetCurrTargetWordsRange().GetStartPos();
//[begin, end) in STL-like fashion.
const std::size_t end = hypo.GetCurrTargetWordsRange().GetEndPos() + 1;
const std::size_t adjust_end = std::min(end, begin + m_ngram->Order() - 1);
std::size_t position = begin;
typename Model::State aux_state;
typename Model::State *state0 = &ret->state, *state1 = &aux_state;
float score = m_ngram->Score(in_state, TranslateID(hypo.GetWord(position)), *state0);
++position;
for (; position < adjust_end; ++position) {
score += m_ngram->Score(*state0, TranslateID(hypo.GetWord(position)), *state1);
std::swap(state0, state1);
}
if (hypo.IsSourceCompleted()) {
// Score end of sentence.
std::vector<lm::WordIndex> indices(m_ngram->Order() - 1);
const lm::WordIndex *last = LastIDs(hypo, &indices.front());
score += m_ngram->FullScoreForgotState(&indices.front(), last, m_ngram->GetVocabulary().EndSentence(), ret->state).prob;
} else if (adjust_end < end) {
// Get state after adding a long phrase.
std::vector<lm::WordIndex> indices(m_ngram->Order() - 1);
const lm::WordIndex *last = LastIDs(hypo, &indices.front());
m_ngram->GetState(&indices.front(), last, ret->state);
} else if (state0 != &ret->state) {
// Short enough phrase that we can just reuse the state.
ret->state = *state0;
}
score = TransformLMScore(score);
if (OOVFeatureEnabled()) {
std::vector<float> scores(2);
scores[0] = score;
scores[1] = 0.0;
out->PlusEquals(this, scores);
} else {
out->PlusEquals(this, score);
}
return ret.release();
}
class LanguageModelChartStateKenLM : public FFState
{
public:
LanguageModelChartStateKenLM() {}
const lm::ngram::ChartState &GetChartState() const {
return m_state;
}
lm::ngram::ChartState &GetChartState() {
return m_state;
}
size_t hash() const {
size_t ret = hash_value(m_state);
return ret;
}
virtual bool operator==(const FFState& o) const {
const LanguageModelChartStateKenLM &other = static_cast<const LanguageModelChartStateKenLM &>(o);
bool ret = m_state == other.m_state;
return ret;
}
private:
lm::ngram::ChartState m_state;
};
template <class Model> FFState *LanguageModelKen<Model>::EvaluateWhenApplied(const ChartHypothesis& hypo, int featureID, ScoreComponentCollection *accumulator) const
{
LanguageModelChartStateKenLM *newState = new LanguageModelChartStateKenLM();
lm::ngram::RuleScore<Model> ruleScore(*m_ngram, newState->GetChartState());
const TargetPhrase &target = hypo.GetCurrTargetPhrase();
const AlignmentInfo::NonTermIndexMap &nonTermIndexMap =
target.GetAlignNonTerm().GetNonTermIndexMap();
const size_t size = hypo.GetCurrTargetPhrase().GetSize();
size_t phrasePos = 0;
// Special cases for first word.
if (size) {
const Word &word = hypo.GetCurrTargetPhrase().GetWord(0);
if (word.GetFactor(m_factorType) == m_beginSentenceFactor) {
// Begin of sentence
ruleScore.BeginSentence();
phrasePos++;
} else if (word.IsNonTerminal()) {
// Non-terminal is first so we can copy instead of rescoring.
const ChartHypothesis *prevHypo = hypo.GetPrevHypo(nonTermIndexMap[phrasePos]);
const lm::ngram::ChartState &prevState = static_cast<const LanguageModelChartStateKenLM*>(prevHypo->GetFFState(featureID))->GetChartState();
ruleScore.BeginNonTerminal(prevState);
phrasePos++;
}
}
for (; phrasePos < size; phrasePos++) {
const Word &word = hypo.GetCurrTargetPhrase().GetWord(phrasePos);
if (word.IsNonTerminal()) {
const ChartHypothesis *prevHypo = hypo.GetPrevHypo(nonTermIndexMap[phrasePos]);
const lm::ngram::ChartState &prevState = static_cast<const LanguageModelChartStateKenLM*>(prevHypo->GetFFState(featureID))->GetChartState();
ruleScore.NonTerminal(prevState);
} else {
ruleScore.Terminal(TranslateID(word));
}
}
float score = ruleScore.Finish();
score = TransformLMScore(score);
score -= hypo.GetTranslationOption().GetScores().GetScoresForProducer(this)[0];
if (OOVFeatureEnabled()) {
std::vector<float> scores(2);
scores[0] = score;
scores[1] = 0.0;
accumulator->PlusEquals(this, scores);
} else {
accumulator->PlusEquals(this, score);
}
return newState;
}
template <class Model> FFState *LanguageModelKen<Model>::EvaluateWhenApplied(const Syntax::SHyperedge& hyperedge, int featureID, ScoreComponentCollection *accumulator) const
{
LanguageModelChartStateKenLM *newState = new LanguageModelChartStateKenLM();
lm::ngram::RuleScore<Model> ruleScore(*m_ngram, newState->GetChartState());
const TargetPhrase &target = *hyperedge.label.translation;
const AlignmentInfo::NonTermIndexMap &nonTermIndexMap =
target.GetAlignNonTerm().GetNonTermIndexMap2();
const size_t size = target.GetSize();
size_t phrasePos = 0;
// Special cases for first word.
if (size) {
const Word &word = target.GetWord(0);
if (word.GetFactor(m_factorType) == m_beginSentenceFactor) {
// Begin of sentence
ruleScore.BeginSentence();
phrasePos++;
} else if (word.IsNonTerminal()) {
// Non-terminal is first so we can copy instead of rescoring.
const Syntax::SVertex *pred = hyperedge.tail[nonTermIndexMap[phrasePos]];
const lm::ngram::ChartState &prevState = static_cast<const LanguageModelChartStateKenLM*>(pred->states[featureID])->GetChartState();
ruleScore.BeginNonTerminal(prevState);
phrasePos++;
}
}
for (; phrasePos < size; phrasePos++) {
const Word &word = target.GetWord(phrasePos);
if (word.IsNonTerminal()) {
const Syntax::SVertex *pred = hyperedge.tail[nonTermIndexMap[phrasePos]];
const lm::ngram::ChartState &prevState = static_cast<const LanguageModelChartStateKenLM*>(pred->states[featureID])->GetChartState();
ruleScore.NonTerminal(prevState);
} else {
ruleScore.Terminal(TranslateID(word));
}
}
float score = ruleScore.Finish();
score = TransformLMScore(score);
score -= target.GetScoreBreakdown().GetScoresForProducer(this)[0];
if (OOVFeatureEnabled()) {
std::vector<float> scores(2);
scores[0] = score;
scores[1] = 0.0;
accumulator->PlusEquals(this, scores);
} else {
accumulator->PlusEquals(this, score);
}
return newState;
}
template <class Model> void LanguageModelKen<Model>::IncrementalCallback(Incremental::Manager &manager) const
{
manager.LMCallback(*m_ngram, m_lmIdLookup);
}
template <class Model> void LanguageModelKen<Model>::ReportHistoryOrder(std::ostream &out, const Phrase &phrase) const
{
out << "|lm=(";
if (!phrase.GetSize()) return;
typename Model::State aux_state;
typename Model::State start_of_sentence_state = m_ngram->BeginSentenceState();
typename Model::State *state0 = &start_of_sentence_state;
typename Model::State *state1 = &aux_state;
for (std::size_t position=0; position<phrase.GetSize(); position++) {
const lm::WordIndex idx = TranslateID(phrase.GetWord(position));
lm::FullScoreReturn ret(m_ngram->FullScore(*state0, idx, *state1));
if (position) out << ",";
out << (int) ret.ngram_length << ":" << TransformLMScore(ret.prob);
if (idx == 0) out << ":unk";
std::swap(state0, state1);
}
out << ")| ";
}
template <class Model>
bool LanguageModelKen<Model>::IsUseable(const FactorMask &mask) const
{
bool ret = mask[m_factorType];
return ret;
}
/* Instantiate LanguageModelKen here. Tells the compiler to generate code
* for the instantiations' non-inline member functions in this file.
* Otherwise, depending on the compiler, those functions may not be present
* at link time.
*/
template class LanguageModelKen<lm::ngram::ProbingModel>;
template class LanguageModelKen<lm::ngram::RestProbingModel>;
template class LanguageModelKen<lm::ngram::TrieModel>;
template class LanguageModelKen<lm::ngram::ArrayTrieModel>;
template class LanguageModelKen<lm::ngram::QuantTrieModel>;
template class LanguageModelKen<lm::ngram::QuantArrayTrieModel>;
LanguageModel *ConstructKenLM(const std::string &lineOrig)
{
FactorType factorType = 0;
string filePath;
util::LoadMethod load_method = util::POPULATE_OR_READ;
util::TokenIter<util::SingleCharacter, true> argument(lineOrig, ' ');
++argument; // KENLM
util::StringStream line;
line << "KENLM";
for (; argument; ++argument) {
const char *equals = std::find(argument->data(), argument->data() + argument->size(), '=');
UTIL_THROW_IF2(equals == argument->data() + argument->size(),
"Expected = in KenLM argument " << *argument);
StringPiece name(argument->data(), equals - argument->data());
StringPiece value(equals + 1, argument->data() + argument->size() - equals - 1);
if (name == "factor") {
factorType = boost::lexical_cast<FactorType>(value);
} else if (name == "order") {
// Ignored
} else if (name == "path") {
filePath.assign(value.data(), value.size());
} else if (name == "lazyken") {
// deprecated: use load instead.
if (value == "0" || value == "false") {
load_method = util::POPULATE_OR_READ;
} else if (value == "1" || value == "true") {
load_method = util::LAZY;
} else {
UTIL_THROW2("Can't parse lazyken argument " << value << ". Also, lazyken is deprecated. Use load with one of the arguments lazy, populate_or_lazy, populate_or_read, read, or parallel_read.");
}
} else if (name == "load") {
if (value == "lazy") {
load_method = util::LAZY;
} else if (value == "populate_or_lazy") {
load_method = util::POPULATE_OR_LAZY;
} else if (value == "populate_or_read" || value == "populate") {
load_method = util::POPULATE_OR_READ;
} else if (value == "read") {
load_method = util::READ;
} else if (value == "parallel_read") {
load_method = util::PARALLEL_READ;
} else {
UTIL_THROW2("Unknown KenLM load method " << value);
}
} else {
// pass to base class to interpret
line << " " << name << "=" << value;
}
}
return ConstructKenLM(line.str(), filePath, factorType, load_method);
}
LanguageModel *ConstructKenLM(const std::string &line, const std::string &file, FactorType factorType, util::LoadMethod load_method)
{
lm::ngram::ModelType model_type;
if (lm::ngram::RecognizeBinary(file.c_str(), model_type)) {
switch(model_type) {
case lm::ngram::PROBING:
return new LanguageModelKen<lm::ngram::ProbingModel>(line, file, factorType, load_method);
case lm::ngram::REST_PROBING:
return new LanguageModelKen<lm::ngram::RestProbingModel>(line, file, factorType, load_method);
case lm::ngram::TRIE:
return new LanguageModelKen<lm::ngram::TrieModel>(line, file, factorType, load_method);
case lm::ngram::QUANT_TRIE:
return new LanguageModelKen<lm::ngram::QuantTrieModel>(line, file, factorType, load_method);
case lm::ngram::ARRAY_TRIE:
return new LanguageModelKen<lm::ngram::ArrayTrieModel>(line, file, factorType, load_method);
case lm::ngram::QUANT_ARRAY_TRIE:
return new LanguageModelKen<lm::ngram::QuantArrayTrieModel>(line, file, factorType, load_method);
default:
UTIL_THROW2("Unrecognized kenlm model type " << model_type);
}
} else {
return new LanguageModelKen<lm::ngram::ProbingModel>(line, file, factorType, load_method);
}
}
}
| yang1fan2/nematus | mosesdecoder-master/moses/LM/Ken.cpp | C++ | bsd-3-clause | 17,711 |
// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights
// reserved. Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.
//
// ---------------------------------------------------------------------------
//
// This file was generated by the CEF translator tool. If making changes by
// hand only do so within the body of existing method and function
// implementations. See the translator.README.txt file in the tools directory
// for more information.
//
#include "libcef_dll/cpptoc/callback_cpptoc.h"
// MEMBER FUNCTIONS - Body may be edited by hand.
void CEF_CALLBACK callback_cont(struct _cef_callback_t* self) {
// AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING
DCHECK(self);
if (!self)
return;
// Execute
CefCallbackCppToC::Get(self)->Continue();
}
void CEF_CALLBACK callback_cancel(struct _cef_callback_t* self) {
// AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING
DCHECK(self);
if (!self)
return;
// Execute
CefCallbackCppToC::Get(self)->Cancel();
}
// CONSTRUCTOR - Do not edit by hand.
CefCallbackCppToC::CefCallbackCppToC(CefCallback* cls)
: CefCppToC<CefCallbackCppToC, CefCallback, cef_callback_t>(cls) {
struct_.struct_.cont = callback_cont;
struct_.struct_.cancel = callback_cancel;
}
#ifndef NDEBUG
template<> base::AtomicRefCount CefCppToC<CefCallbackCppToC, CefCallback,
cef_callback_t>::DebugObjCt = 0;
#endif
| amikey/chromium | libcef_dll/cpptoc/callback_cpptoc.cc | C++ | bsd-3-clause | 1,478 |
shared :kernel_lambda do |cmd|
describe "Kernel.#{cmd}" do
it "returns a Proc object" do
send(cmd) { true }.kind_of?(Proc).should == true
end
it "raises an ArgumentError when no block is given" do
lambda { send(cmd) }.should raise_error(ArgumentError)
end
it "raises an ArgumentError when given too many arguments" do
lambda {
send(cmd) { |a, b| a + b}.call(1,2,5).should == 3
}.should raise_error(ArgumentError)
end
it "returns from block into caller block" do
# More info in the pickaxe book pg. 359
def some_method(cmd)
p = send(cmd) { return 99 }
res = p.call
"returned #{res}"
end
# Have to pass in the cmd errors otherwise
some_method(cmd).should == "returned 99"
def some_method2(&b) b end
a_proc = send(cmd) { return true }
res = some_method2(&a_proc)
res.call.should == true
end
end
end
| chad/rubinius | spec/frozen/1.8/core/kernel/shared/lambda.rb | Ruby | bsd-3-clause | 948 |
package main
import (
"fmt"
"io"
)
var cmdBranches = &Command{
UsageLine: "branches [-v]",
Short: "list repository branches",
Long: ``,
}
func init() {
addStdFlags(cmdBranches)
cmdBranches.Run = runBranches
}
func runBranches(cmd *Command, w io.Writer, args []string) {
openRepository(args)
st := repo.NewStore()
clIndex, err := st.OpenChangeLog()
if err != nil {
fatalf("%s", err)
}
for r := clIndex.Tip(); r.FileRev() != -1; r = r.Prev() {
id := r.Id().Node()
s := branchHeads.ById[id]
for i := range s {
t := s[len(s)-i-1]
fmt.Fprintf(w, "%-26s %5d:%s\n", t, r.FileRev(), id[:12])
}
}
}
| knieriem/hgo | cmd/hgo/cmdbranches.go | GO | bsd-3-clause | 635 |
/*
** Copyright 2002, Manuel J. Petit. All rights reserved.
** Distributed under the terms of the NewOS License.
*/
#include "rld_priv.h"
int
export_load_addon(char const *name, unsigned flags)
{
(void)(name);
(void)(flags);
return -1;
}
int
export_unload_addon(int lib, unsigned flags)
{
(void)(lib);
(void)(flags);
return -1;
}
void *
export_addon_symbol(int lib, char const *sym, unsigned flags)
{
(void)(lib);
(void)(sym);
(void)(flags);
return 0;
}
| dioptre/newos | apps/rld/rldbeos.c | C | bsd-3-clause | 471 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.nativelibs4java.opencl.demos;
import java.net.MalformedURLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.bridj.BridJ;
import org.bridj.JNI;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.URL;
import javax.swing.BorderFactory;
import javax.swing.JComponent;
import javax.swing.JOptionPane;
import javax.swing.UIManager;
import javax.swing.border.Border;
import javax.swing.border.EtchedBorder;
import javax.swing.border.TitledBorder;
import com.nativelibs4java.opencl.JavaCL;
import org.bridj.Platform;
/**
*
* @author ochafik
*/
public class SetupUtils {
public enum DownloadURL {
ATI("http://developer.amd.com/tools-and-sdks/opencl-zone/amd-accelerated-parallel-processing-app-sdk"),
NVidia("http://www.nvidia.com/Download/Find.aspx");
public final URL url;
DownloadURL(String s) {
URL url;
try {
url = new URL(s);
} catch (MalformedURLException ex) {
Logger.getLogger(SetupUtils.class.getName()).log(Level.SEVERE, null, ex);
url = null;
}
this.url = url;
}
}
public static void failWithDownloadProposalsIfOpenCLNotAvailable() {
///*
try {
JavaCL.listPlatforms();
return;
} catch (Throwable ex) {
ex.printStackTrace();
} //*/
String title = "JavaCL Error: OpenCL library not found";
if (Platform.isMacOSX()) {
JOptionPane.showMessageDialog(null, "Please upgrade Mac OS X to Snow Leopard (10.6) to be able to use OpenCL.", title, JOptionPane.ERROR_MESSAGE);
return;
}
Object[] options = new Object[] {
"NVIDIA graphic card",
"ATI graphic card",
"CPU only",
"Cancel"
};
//for (;;) {
int option = JOptionPane.showOptionDialog(null,
"You don't appear to have an OpenCL implementation properly configured.\n" +
"Please choose one of the following options to proceed to the download of an appropriate OpenCL implementation :", title, JOptionPane.OK_OPTION, JOptionPane.ERROR_MESSAGE, null, options, options[2]);
if (option >= 0 && option != 3) {
DownloadURL url;
if (option == 0) {
/*String nvidiaVersion = "260.99";
boolean appendPlatform = true;
String sys;
if (JNI.isWindows()) {
if (System.getProperty("os.name").toLowerCase().contains("xp")) {
sys = "winxp";
appendPlatform = false;
} else {
sys = "win7_vista";
}
urlString = "http://www.nvidia.fr/object/" + sys + "_" + nvidiaVersion + (appendPlatform ? "_" + (JNI.is64Bits() ? "64" : "32") + "bit" : "") + "_whql.html";
} else
urlString = "http://developer.nvidia.com/object/opencl-download.html";
*/
url = DownloadURL.NVidia;
} else
url = DownloadURL.ATI;
try {
Platform.open(url.url);
} catch (Exception ex1) {
exception(ex1);
}
}
System.exit(1);
}
public static void exception(Throwable ex) {
StringWriter sout = new StringWriter();
ex.printStackTrace(new PrintWriter(sout));
JOptionPane.showMessageDialog(null, sout.toString(), "Error in JavaCL Demo", JOptionPane.ERROR_MESSAGE);
}
static Border etchedBorder;
static synchronized Border getEtchedBorder() {
if (etchedBorder == null) {
etchedBorder = UIManager.getBorder( "TitledBorder.aquaVariant" );
if (etchedBorder == null)
etchedBorder = BorderFactory.createCompoundBorder(new EtchedBorder(), BorderFactory.createEmptyBorder(5, 5, 5, 5));
}
return etchedBorder;
}
public static void setEtchedTitledBorder(JComponent comp, String title) {
comp.setBorder(new TitledBorder(getEtchedBorder(), title));
}
}
| nativelibs4java/JavaCL | Demos/src/main/java/com/nativelibs4java/opencl/demos/SetupUtils.java | Java | bsd-3-clause | 4,354 |
<?php
/**
* Created by IntelliJ IDEA.
* User: hentschel
* Date: 22.07.13
* Time: 11:37
* To change this template use File | Settings | File Templates.
*/
namespace org\camunda\php\sdk\service;
use Exception;
use org\camunda\php\sdk\entity\request\VariableInstanceRequest;
use org\camunda\php\sdk\entity\response\VariableInstance;
class VariableInstanceService extends RequestService {
/**
* Retrieves all variable instances within given context
* @link http://docs.camunda.org/api-references/rest/#!/variable-instance/get-query
* @link http://docs.camunda.org/api-references/rest/#!/variable-instance/post-query
*
* @param VariableInstanceRequest $request filter parameters
* @param bool $isPostRequest switch for GET/POST request
* @throws \Exception
* @return object list of variable instances
*/
public function getInstances(VariableInstanceRequest $request, $isPostRequest = false){
$this->setRequestUrl('/variable-instance');
$this->setRequestObject($request);
if($isPostRequest == true) {
$this->setRequestMethod('POST');
} else {
$this->setRequestMethod('GET');
}
try {
$prepare = $this->execute();
$response = array();
$variableInstance = new VariableInstance();
foreach ($prepare AS $index => $data) {
$response['instance_' . $index] = $variableInstance->cast($data);
}
return (object)$response;
} catch (Exception $e) {
throw $e;
}
}
/**
* Retrieves the amount of variable instances
* @link http://docs.camunda.org/api-references/rest/#!/variable-instance/get-query-count
* @link http://docs.camunda.org/api-references/rest/#!/variable-instance/post-query-count
*
* @param VariableInstanceRequest $request filter parameters
* @param bool $isPostRequest switch for GET/POST request
* @throws \Exception
* @return int Amount of variable instances
*/
public function getCount(VariableInstanceRequest $request, $isPostRequest = false) {
$this->setRequestUrl('/variable-instance/count');
$this->setRequestObject($request);
if($isPostRequest == true) {
$this->setRequestMethod('POST');
} else {
$this->setRequestMethod('GET');
}
try {
return $this->execute()->count;
} catch (Exception $e) {
throw $e;
}
}
} | patrickschlaepfer/camundazendphp | vendor/camunda/camunda-bpm-php-sdk/oop/main/service/VariableInstanceService.php | PHP | bsd-3-clause | 2,340 |
#pragma INPUT uint32_t
#pragma OUTPUT uint32_t
GS_GET()
{
Output = 2;
State = GS_SEND;
}
GS_SEND()
{
finish();
}
| seyedmaysamlavasani/GorillaPP | compiler/engineCompiler/multiThread/sendConst.c | C | bsd-3-clause | 122 |
<!doctype html>
<!-- This file is generated by build.py. -->
<title>Reference for img tall-viewBox.svg; overflow:hidden; -o-object-fit:contain; -o-object-position:right 100%</title>
<link rel="stylesheet" href="../../support/reftests.css">
<style>
.helper { overflow:hidden }
.helper > * { right:0; bottom:0; width:133.33333px; height:200px }
</style>
<div id="ref">
<span class="helper"><img src="../../support/tall-viewBox-none.svg"></span>
</div>
| frivoal/presto-testo | css/image-fit/reftests/img-svg-tall-viewBox/hidden_contain_right_100-ref.html | HTML | bsd-3-clause | 453 |
require 'spec_helper'
describe Spree::Calculator::TieredPercent, :type => :model do
let(:calculator) { Spree::Calculator::TieredPercent.new }
describe "#valid?" do
subject { calculator.valid? }
context "when base percent is less than zero" do
before { calculator.preferred_base_percent = -1 }
it { is_expected.to be false }
end
context "when base percent is greater than 100" do
before { calculator.preferred_base_percent = 110 }
it { is_expected.to be false }
end
context "when tiers is not a hash" do
before { calculator.preferred_tiers = ["nope"] }
it { is_expected.to be false }
end
context "when tiers is a hash" do
context "and one of the keys is not a positive number" do
before { calculator.preferred_tiers = { "nope" => 20 } }
it { is_expected.to be false }
end
context "and one of the values is not a percent" do
before { calculator.preferred_tiers = { 10 => 110 } }
it { is_expected.to be false }
end
end
end
describe "#compute" do
let(:line_item) { mock_model Spree::LineItem, amount: amount }
before do
calculator.preferred_base_percent = 10
calculator.preferred_tiers = {
100 => 15,
200 => 20
}
end
subject { calculator.compute(line_item) }
context "when amount falls within the first tier" do
let(:amount) { 50 }
it { is_expected.to eq 5 }
end
context "when amount falls within the second tier" do
let(:amount) { 150 }
it { is_expected.to eq 22 }
end
end
end
| dotandbo/spree | core/spec/models/spree/calculator/tiered_percent_spec.rb | Ruby | bsd-3-clause | 1,605 |
# -*- coding: utf-8 -*-
"""
A sample of kay settings.
:Copyright: (c) 2009 Accense Technology, Inc.
Takashi Matsuo <[email protected]>,
All rights reserved.
:license: BSD, see LICENSE for more details.
"""
DEFAULT_TIMEZONE = 'Asia/Tokyo'
DEBUG = True
PROFILE = False
SECRET_KEY = 'ReplaceItWithSecretString'
SESSION_PREFIX = 'gaesess:'
COOKIE_AGE = 1209600 # 2 weeks
COOKIE_NAME = 'KAY_SESSION'
ADD_APP_PREFIX_TO_KIND = True
ADMINS = (
)
TEMPLATE_DIRS = (
)
USE_I18N = False
DEFAULT_LANG = 'en'
INSTALLED_APPS = (
)
APP_MOUNT_POINTS = {
}
# You can remove following settings if unnecessary.
CONTEXT_PROCESSORS = (
'kay.context_processors.request',
'kay.context_processors.url_functions',
'kay.context_processors.media_url',
)
| gmist/kay-ru | settings.py | Python | bsd-3-clause | 785 |
# Distributed under the OSI-approved BSD 3-Clause License. See accompanying
# file Copyright.txt or https://cmake.org/licensing for details.
if(NOT CMAKE_SKIP_COMPATIBILITY_TESTS)
# Old CMake versions did not support OS X universal binaries anyway,
# so just get through this with at least some size for the types.
list(LENGTH CMAKE_OSX_ARCHITECTURES NUM_ARCHS)
if(${NUM_ARCHS} GREATER 1)
if(NOT DEFINED CMAKE_TRY_COMPILE_OSX_ARCHITECTURES)
message(WARNING "This module does not work with OS X universal binaries.")
set(__ERASE_CMAKE_TRY_COMPILE_OSX_ARCHITECTURES 1)
list(GET CMAKE_OSX_ARCHITECTURES 0 CMAKE_TRY_COMPILE_OSX_ARCHITECTURES)
endif()
endif()
include (CheckTypeSize)
CHECK_TYPE_SIZE(int CMAKE_SIZEOF_INT)
CHECK_TYPE_SIZE(long CMAKE_SIZEOF_LONG)
CHECK_TYPE_SIZE("void*" CMAKE_SIZEOF_VOID_P)
CHECK_TYPE_SIZE(char CMAKE_SIZEOF_CHAR)
CHECK_TYPE_SIZE(short CMAKE_SIZEOF_SHORT)
CHECK_TYPE_SIZE(float CMAKE_SIZEOF_FLOAT)
CHECK_TYPE_SIZE(double CMAKE_SIZEOF_DOUBLE)
include (CheckIncludeFile)
CHECK_INCLUDE_FILE("limits.h" CMAKE_HAVE_LIMITS_H)
CHECK_INCLUDE_FILE("unistd.h" CMAKE_HAVE_UNISTD_H)
CHECK_INCLUDE_FILE("pthread.h" CMAKE_HAVE_PTHREAD_H)
include (CheckIncludeFiles)
CHECK_INCLUDE_FILES("sys/types.h;sys/prctl.h" CMAKE_HAVE_SYS_PRCTL_H)
include (TestBigEndian)
TEST_BIG_ENDIAN(CMAKE_WORDS_BIGENDIAN)
include (FindX11)
if("${X11_X11_INCLUDE_PATH}" STREQUAL "/usr/include")
set (CMAKE_X_CFLAGS "" CACHE STRING "X11 extra flags.")
else()
set (CMAKE_X_CFLAGS "-I${X11_X11_INCLUDE_PATH}" CACHE STRING
"X11 extra flags.")
endif()
set (CMAKE_X_LIBS "${X11_LIBRARIES}" CACHE STRING
"Libraries and options used in X11 programs.")
set (CMAKE_HAS_X "${X11_FOUND}" CACHE INTERNAL "Is X11 around.")
include (FindThreads)
set (CMAKE_THREAD_LIBS "${CMAKE_THREAD_LIBS_INIT}" CACHE STRING
"Thread library used.")
set (CMAKE_USE_PTHREADS "${CMAKE_USE_PTHREADS_INIT}" CACHE BOOL
"Use the pthreads library.")
set (CMAKE_USE_WIN32_THREADS "${CMAKE_USE_WIN32_THREADS_INIT}" CACHE BOOL
"Use the win32 thread library.")
set (CMAKE_HP_PTHREADS ${CMAKE_HP_PTHREADS_INIT} CACHE BOOL
"Use HP pthreads.")
set (CMAKE_USE_SPROC ${CMAKE_USE_SPROC_INIT} CACHE BOOL
"Use sproc libs.")
if(__ERASE_CMAKE_TRY_COMPILE_OSX_ARCHITECTURES)
set(CMAKE_TRY_COMPILE_OSX_ARCHITECTURES)
set(__ERASE_CMAKE_TRY_COMPILE_OSX_ARCHITECTURES)
endif()
endif()
mark_as_advanced(
CMAKE_HP_PTHREADS
CMAKE_THREAD_LIBS
CMAKE_USE_PTHREADS
CMAKE_USE_SPROC
CMAKE_USE_WIN32_THREADS
CMAKE_X_CFLAGS
CMAKE_X_LIBS
)
| cperthuis/precomputed_atmospheric_scattering | platform/windows/external/cmake/share/cmake-3.9/Modules/CMakeBackwardCompatibilityC.cmake | CMake | bsd-3-clause | 2,704 |
<!DOCTYPE html><!-- DO NOT EDIT. This file auto-generated by generate_closure_unit_tests.js --><!--
Copyright 2017 The Closure Library Authors. All Rights Reserved.
Use of this source code is governed by the Apache License, Version 2.0.
See the COPYING file for details.
--><html><head><meta charset="UTF-8">
<script src="../base.js"></script>
<script>goog.require('fake.BaseClass');</script>
<title>Closure Unit Tests - fake.BaseClass</title></head><body></body></html> | isabela-angelo/scratch-tangible-blocks | scratch-blocks/node_modules/google-closure-library/closure/goog/testing/mockclassfactory_test.html | HTML | bsd-3-clause | 471 |
// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/renderer/media/video_capture_impl_manager.h"
#include "base/bind.h"
#include "base/stl_util.h"
#include "content/renderer/media/video_capture_impl.h"
#include "content/renderer/media/video_capture_message_filter.h"
VideoCaptureImplManager::VideoCaptureImplManager()
: thread_("VC manager") {
thread_.Start();
message_loop_proxy_ = thread_.message_loop_proxy();
filter_ = new VideoCaptureMessageFilter();
}
VideoCaptureImplManager::~VideoCaptureImplManager() {
STLDeleteContainerPairSecondPointers(devices_.begin(), devices_.end());
thread_.Stop();
}
media::VideoCapture* VideoCaptureImplManager::AddDevice(
media::VideoCaptureSessionId id,
media::VideoCapture::EventHandler* handler) {
DCHECK(handler);
base::AutoLock auto_lock(lock_);
Devices::iterator it = devices_.find(id);
if (it == devices_.end()) {
VideoCaptureImpl* vc =
new VideoCaptureImpl(id, message_loop_proxy_, filter_);
devices_[id] = new Device(vc, handler);
vc->Init();
return vc;
}
devices_[id]->clients.push_front(handler);
return it->second->vc;
}
void VideoCaptureImplManager::RemoveDevice(
media::VideoCaptureSessionId id,
media::VideoCapture::EventHandler* handler) {
DCHECK(handler);
base::AutoLock auto_lock(lock_);
Devices::iterator it = devices_.find(id);
if (it == devices_.end())
return;
size_t size = it->second->clients.size();
it->second->clients.remove(handler);
if (size == it->second->clients.size() || size > 1)
return;
devices_[id]->vc->DeInit(base::Bind(&VideoCaptureImplManager::FreeDevice,
this, devices_[id]->vc));
delete devices_[id];
devices_.erase(id);
}
void VideoCaptureImplManager::FreeDevice(VideoCaptureImpl* vc) {
delete vc;
}
VideoCaptureImplManager::Device::Device(
VideoCaptureImpl* device,
media::VideoCapture::EventHandler* handler)
: vc(device) {
clients.push_front(handler);
}
VideoCaptureImplManager::Device::~Device() {}
| aYukiSekiguchi/ACCESS-Chromium | content/renderer/media/video_capture_impl_manager.cc | C++ | bsd-3-clause | 2,182 |
---
title: APIs and Microservices Projects
localeTitle: Proyectos APIs y microservicios
---
## Proyectos APIs y microservicios
Esto es un talón. [Ayuda a nuestra comunidad a expandirla](https://github.com/freecodecamp/guides/tree/master/src/pages/mathematics/quadratic-equations/index.md) .
[Esta guía rápida de estilo ayudará a asegurar que su solicitud de extracción sea aceptada](https://github.com/freecodecamp/guides/blob/master/README.md) .
#### Más información: | otavioarc/freeCodeCamp | guide/spanish/certifications/apis-and-microservices/apis-and-microservices-projects/index.md | Markdown | bsd-3-clause | 478 |
#import <Foundation/Foundation.h>
#import <OpenGLES/EAGL.h>
#import <OpenGLES/ES2/gl.h>
#import <OpenGLES/ES2/glext.h>
#import <QuartzCore/QuartzCore.h>
#import <CoreMedia/CoreMedia.h>
#import "GLProgram.h"
#define GPUImageRotationSwapsWidthAndHeight(rotation) ((rotation) == kGPUImageRotateLeft || (rotation) == kGPUImageRotateRight || (rotation) == kGPUImageRotateRightFlipVertical)
typedef enum { kGPUImageNoRotation, kGPUImageRotateLeft, kGPUImageRotateRight, kGPUImageFlipVertical, kGPUImageFlipHorizonal, kGPUImageRotateRightFlipVertical, kGPUImageRotate180 } GPUImageRotationMode;
@interface GPUImageOpenGLESContext : NSObject
@property(readonly, retain, nonatomic) EAGLContext *context;
@property(readonly, nonatomic) dispatch_queue_t contextQueue;
@property(readwrite, retain, nonatomic) GLProgram *currentShaderProgram;
+ (GPUImageOpenGLESContext *)sharedImageProcessingOpenGLESContext;
+ (dispatch_queue_t)sharedOpenGLESQueue;
+ (void)useImageProcessingContext;
+ (void)setActiveShaderProgram:(GLProgram *)shaderProgram;
+ (GLint)maximumTextureSizeForThisDevice;
+ (GLint)maximumTextureUnitsForThisDevice;
+ (CGSize)sizeThatFitsWithinATextureForSize:(CGSize)inputSize;
- (void)presentBufferForDisplay;
- (GLProgram *)programForVertexShaderString:(NSString *)vertexShaderString fragmentShaderString:(NSString *)fragmentShaderString;
// Manage fast texture upload
+ (BOOL)supportsFastTextureUpload;
@end
@protocol GPUImageInput <NSObject>
- (void)newFrameReadyAtTime:(CMTime)frameTime atIndex:(NSInteger)textureIndex;
- (void)setInputTexture:(GLuint)newInputTexture atIndex:(NSInteger)textureIndex;
- (NSInteger)nextAvailableTextureIndex;
- (void)setInputSize:(CGSize)newSize atIndex:(NSInteger)textureIndex;
- (void)setInputRotation:(GPUImageRotationMode)newInputRotation atIndex:(NSInteger)textureIndex;
- (CGSize)maximumOutputSize;
- (void)endProcessing;
- (BOOL)shouldIgnoreUpdatesToThisTarget;
- (BOOL)enabled;
@end
| darkfall/GPUImage | framework/Source/GPUImageOpenGLESContext.h | C | bsd-3-clause | 1,939 |
//------------- accordions.js -------------//
$(document).ready(function() {
});
//sparkline in sidebar area
var positive = [1,5,3,7,8,6,10];
var negative = [10,6,8,7,3,5,1]
var negative1 = [7,6,8,7,6,5,4]
$('#stat1').sparkline(positive,{
height:15,
spotRadius: 0,
barColor: '#9FC569',
type: 'bar'
});
$('#stat2').sparkline(negative,{
height:15,
spotRadius: 0,
barColor: '#ED7A53',
type: 'bar'
});
$('#stat3').sparkline(negative1,{
height:15,
spotRadius: 0,
barColor: '#ED7A53',
type: 'bar'
});
$('#stat4').sparkline(positive,{
height:15,
spotRadius: 0,
barColor: '#9FC569',
type: 'bar'
});
//sparkline in widget
$('#stat5').sparkline(positive,{
height:15,
spotRadius: 0,
barColor: '#9FC569',
type: 'bar'
});
$('#stat6').sparkline(positive, {
width: 70,//Width of the chart - Defaults to 'auto' - May be any valid css width - 1.5em, 20px, etc (using a number without a unit specifier won't do what you want) - This option does nothing for bar and tristate chars (see barWidth)
height: 20,//Height of the chart - Defaults to 'auto' (line height of the containing tag)
lineColor: '#88bbc8',//Used by line and discrete charts to specify the colour of the line drawn as a CSS values string
fillColor: '#f2f7f9',//Specify the colour used to fill the area under the graph as a CSS value. Set to false to disable fill
spotColor: '#e72828',//The CSS colour of the final value marker. Set to false or an empty string to hide it
maxSpotColor: '#005e20',//The CSS colour of the marker displayed for the maximum value. Set to false or an empty string to hide it
minSpotColor: '#f7941d',//The CSS colour of the marker displayed for the mimum value. Set to false or an empty string to hide it
spotRadius: 3,//Radius of all spot markers, In pixels (default: 1.5) - Integer
lineWidth: 2//In pixels (default: 1) - Integer
}); | sammosampson/MessageRouteInspector | public/js/pages/accordions.js | JavaScript | bsd-3-clause | 1,933 |
<?php
/**
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @package ZendGData
*/
namespace ZendGData\Spreadsheets;
use ZendGData\App;
/**
* Assists in constructing queries for Google Spreadsheets lists
*
* @link http://code.google.com/apis/gdata/calendar/
*
* @category Zend
* @package ZendGData
* @subpackage Spreadsheets
*/
class ListQuery extends \ZendGData\Query
{
const SPREADSHEETS_LIST_FEED_URI = 'https://spreadsheets.google.com/feeds/list';
protected $_defaultFeedUri = self::SPREADSHEETS_LIST_FEED_URI;
protected $_visibility = 'private';
protected $_projection = 'full';
protected $_spreadsheetKey = null;
protected $_worksheetId = 'default';
protected $_rowId = null;
/**
* Constructs a new ZendGData\Spreadsheets\ListQuery object.
*/
public function __construct()
{
parent::__construct();
}
/**
* Sets the spreadsheet key for the query.
* @param string $value
* @return \ZendGData\Spreadsheets\CellQuery Provides a fluent interface
*/
public function setSpreadsheetKey($value)
{
$this->_spreadsheetKey = $value;
return $this;
}
/**
* Gets the spreadsheet key for the query.
* @return string spreadsheet key
*/
public function getSpreadsheetKey()
{
return $this->_spreadsheetKey;
}
/**
* Sets the worksheet id for the query.
* @param string $value
* @return \ZendGData\Spreadsheets\CellQuery Provides a fluent interface
*/
public function setWorksheetId($value)
{
$this->_worksheetId = $value;
return $this;
}
/**
* Gets the worksheet id for the query.
* @return string worksheet id
*/
public function getWorksheetId()
{
return $this->_worksheetId;
}
/**
* Sets the row id for the query.
* @param string $value row id
* @return \ZendGData\Spreadsheets\CellQuery Provides a fluent interface
*/
public function setRowId($value)
{
$this->_rowId = $value;
return $this;
}
/**
* Gets the row id for the query.
* @return string row id
*/
public function getRowId()
{
return $this->_rowId;
}
/**
* Sets the projection for the query.
* @param string $value Projection
* @return \ZendGData\Spreadsheets\ListQuery Provides a fluent interface
*/
public function setProjection($value)
{
$this->_projection = $value;
return $this;
}
/**
* Sets the visibility for this query.
* @param string $value visibility
* @return \ZendGData\Spreadsheets\ListQuery Provides a fluent interface
*/
public function setVisibility($value)
{
$this->_visibility = $value;
return $this;
}
/**
* Gets the projection for this query.
* @return string projection
*/
public function getProjection()
{
return $this->_projection;
}
/**
* Gets the visibility for this query.
* @return string visibility
*/
public function getVisibility()
{
return $this->_visibility;
}
/**
* Sets the spreadsheet key for this query.
* @param string $value
* @return \ZendGData\Spreadsheets\DocumentQuery Provides a fluent interface
*/
public function setSpreadsheetQuery($value)
{
if ($value != null) {
$this->_params['sq'] = $value;
} else {
unset($this->_params['sq']);
}
return $this;
}
/**
* Gets the spreadsheet key for this query.
* @return string spreadsheet query
*/
public function getSpreadsheetQuery()
{
if (array_key_exists('sq', $this->_params)) {
return $this->_params['sq'];
} else {
return null;
}
}
/**
* Sets the orderby attribute for this query.
* @param string $value
* @return \ZendGData\Spreadsheets\DocumentQuery Provides a fluent interface
*/
public function setOrderBy($value)
{
if ($value != null) {
$this->_params['orderby'] = $value;
} else {
unset($this->_params['orderby']);
}
return $this;
}
/**
* Gets the orderby attribute for this query.
* @return string orderby
*/
public function getOrderBy()
{
if (array_key_exists('orderby', $this->_params)) {
return $this->_params['orderby'];
} else {
return null;
}
}
/**
* Sets the reverse attribute for this query.
* @param string $value
* @return \ZendGData\Spreadsheets\DocumentQuery Provides a fluent interface
*/
public function setReverse($value)
{
if ($value != null) {
$this->_params['reverse'] = $value;
} else {
unset($this->_params['reverse']);
}
return $this;
}
/**
* Gets the reverse attribute for this query.
* @return string reverse
*/
public function getReverse()
{
if (array_key_exists('reverse', $this->_params)) {
return $this->_params['reverse'];
} else {
return null;
}
}
/**
* Gets the full query URL for this query.
* @return string url
*/
public function getQueryUrl()
{
$uri = $this->_defaultFeedUri;
if ($this->_spreadsheetKey != null) {
$uri .= '/'.$this->_spreadsheetKey;
} else {
throw new App\Exception('A spreadsheet key must be provided for list queries.');
}
if ($this->_worksheetId != null) {
$uri .= '/'.$this->_worksheetId;
} else {
throw new App\Exception('A worksheet id must be provided for list queries.');
}
if ($this->_visibility != null) {
$uri .= '/'.$this->_visibility;
} else {
throw new App\Exception('A visibility must be provided for list queries.');
}
if ($this->_projection != null) {
$uri .= '/'.$this->_projection;
} else {
throw new App\Exception('A projection must be provided for list queries.');
}
if ($this->_rowId != null) {
$uri .= '/'.$this->_rowId;
}
$uri .= $this->getQueryString();
return $uri;
}
/**
* Gets the attribute query string for this query.
* @return string query string
*/
public function getQueryString()
{
return parent::getQueryString();
}
}
| asdf0577/wufan | vendor/zendgdata/library/ZendGData/Spreadsheets/ListQuery.php | PHP | bsd-3-clause | 6,892 |
from __future__ import absolute_import
import six
from sentry.app import tsdb
from sentry.testutils import APITestCase
class ProjectGroupStatsTest(APITestCase):
def test_simple(self):
self.login_as(user=self.user)
project = self.create_project()
group1 = self.create_group(project=project)
group2 = self.create_group(project=project)
url = '/api/0/projects/{}/{}/issues/stats/'.format(
project.organization.slug,
project.slug,
)
response = self.client.get('%s?id=%s&id=%s' % (url, group1.id, group2.id), format='json')
tsdb.incr(tsdb.models.group, group1.id, count=3)
response = self.client.get('%s?id=%s&id=%s' % (url, group1.id, group2.id), format='json')
assert response.status_code == 200, response.content
assert len(response.data) == 2
assert six.text_type(group1.id) in response.data
assert six.text_type(group2.id) in response.data
group_data = response.data[six.text_type(group1.id)]
assert group_data[-1][1] == 3, response.data
for point in group_data[:-1]:
assert point[1] == 0
assert len(group_data) == 24
| ifduyue/sentry | tests/sentry/api/endpoints/test_project_group_stats.py | Python | bsd-3-clause | 1,204 |
{% extends "users/users_base.html" %}
{% load hqstyle_tags %}
{% load i18n %}
{% block subsection-title %}
<li class="active">
<a href="#">Copy From Snapshot</a>
</li>
{% endblock %}
{% block user-view %}
<form class="form-horizontal" method="post">
<fieldset>
<legend>Create new project from snapshot</legend>
<div class="control-group{% if error_message %} error{% endif %}">
<label class="control-label" for="new_domain_name">{% trans 'New project name' %}</label>
<div class="controls">
<input type="text" class="span3" id="new_domain_name"
name="new_domain_name" value="{{ new_domain_name }}">
{% if error_message %}
<span class="help-inline">{{ error_message }}</span>
{% endif %}
</div>
</div>
<div class="form-actions"><button type="submit" class="btn btn-primary">Create New Project</button></div>
</fieldset>
</form>
{% endblock %}> | gmimano/commcaretest | corehq/apps/domain/templates/domain/copy_snapshot.html | HTML | bsd-3-clause | 1,015 |
// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "media/base/decoder_factory.h"
#include "base/single_thread_task_runner.h"
namespace media {
DecoderFactory::DecoderFactory() {}
DecoderFactory::~DecoderFactory() {}
void DecoderFactory::CreateAudioDecoders(
scoped_refptr<base::SingleThreadTaskRunner> task_runner,
ScopedVector<AudioDecoder>* audio_decoders) {}
void DecoderFactory::CreateVideoDecoders(
scoped_refptr<base::SingleThreadTaskRunner> task_runner,
ScopedVector<VideoDecoder>* video_decoders) {}
} // namespace media
| axinging/chromium-crosswalk | media/base/decoder_factory.cc | C++ | bsd-3-clause | 678 |
# -*- coding: utf-8 -*-
from socialoauth import socialsites
from socialoauth.utils import import_oauth_class
from .utils import LazyList
# add 'social_login.context_processors.social_sites' in TEMPLATE_CONTEXT_PROCESSORS
# then in template, you can get this sites via {% for s in social_sites %} ... {% endfor %}
# Don't worry about the performance,
# `social_sites` is a lazy object, it readly called just access the `social_sites`
def social_sites(request):
def _social_sites():
def make_site(s):
s = import_oauth_class(s)()
return {
'site_id': s.site_id,
'site_name': s.site_name,
'site_name_zh': s.site_name_zh,
'authorize_url': s.authorize_url,
}
return [make_site(s) for s in socialsites.list_sites()]
return {'social_sites': LazyList(_social_sites)}
| triplekill/django-social-login | social_login/context_processors.py | Python | bsd-3-clause | 891 |
var _curry1 = /*#__PURE__*/require('./internal/_curry1');
var _makeFlat = /*#__PURE__*/require('./internal/_makeFlat');
/**
* Returns a new list by pulling every item out of it (and all its sub-arrays)
* and putting them in a new array, depth-first.
*
* @func
* @memberOf R
* @since v0.1.0
* @category List
* @sig [a] -> [b]
* @param {Array} list The array to consider.
* @return {Array} The flattened list.
* @see R.unnest
* @example
*
* R.flatten([1, 2, [3, 4], 5, [6, [7, 8, [9, [10, 11], 12]]]]);
* //=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
*/
var flatten = /*#__PURE__*/_curry1( /*#__PURE__*/_makeFlat(true));
module.exports = flatten; | endlessm/chromium-browser | third_party/devtools-frontend/src/node_modules/ramda/src/flatten.js | JavaScript | bsd-3-clause | 673 |
/*
* Copyright (c) 2014, Texas Instruments Incorporated - http://www.ti.com/
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*---------------------------------------------------------------------------*/
/**
* \addtogroup sensortag-cc26xx-buzzer
* @{
*
* \file
* Driver for the Sensortag Buzzer
*/
/*---------------------------------------------------------------------------*/
#include "contiki-conf.h"
#include "buzzer.h"
#include "ti-lib.h"
#include "lpm.h"
#include <stdint.h>
#include <string.h>
#include <stdio.h>
/*---------------------------------------------------------------------------*/
static uint8_t buzzer_on;
LPM_MODULE(buzzer_module, NULL, NULL, NULL, LPM_DOMAIN_PERIPH);
/*---------------------------------------------------------------------------*/
void
buzzer_init()
{
buzzer_on = 0;
}
/*---------------------------------------------------------------------------*/
uint8_t
buzzer_state()
{
return buzzer_on;
}
/*---------------------------------------------------------------------------*/
void
buzzer_start(int freq)
{
uint32_t load;
/* Enable GPT0 clocks under active, sleep, deep sleep */
ti_lib_prcm_peripheral_run_enable(PRCM_PERIPH_TIMER0);
ti_lib_prcm_peripheral_sleep_enable(PRCM_PERIPH_TIMER0);
ti_lib_prcm_peripheral_deep_sleep_enable(PRCM_PERIPH_TIMER0);
ti_lib_prcm_load_set();
while(!ti_lib_prcm_load_get());
/* Drive the I/O ID with GPT0 / Timer A */
ti_lib_ioc_port_configure_set(BOARD_IOID_BUZZER, IOC_PORT_MCU_PORT_EVENT0,
IOC_STD_OUTPUT);
/* GPT0 / Timer A: PWM, Interrupt Enable */
HWREG(GPT0_BASE + GPT_O_TAMR) = (TIMER_CFG_A_PWM & 0xFF) | GPT_TAMR_TAPWMIE;
buzzer_on = 1;
/*
* Register ourself with LPM. This will keep the PERIPH PD powered on
* during deep sleep, allowing the buzzer to keep working while the chip is
* being power-cycled
*/
lpm_register_module(&buzzer_module);
/* Stop the timer */
ti_lib_timer_disable(GPT0_BASE, TIMER_A);
if(freq > 0) {
load = (GET_MCU_CLOCK / freq);
ti_lib_timer_load_set(GPT0_BASE, TIMER_A, load);
ti_lib_timer_match_set(GPT0_BASE, TIMER_A, load / 2);
/* Start */
ti_lib_timer_enable(GPT0_BASE, TIMER_A);
}
}
/*---------------------------------------------------------------------------*/
void
buzzer_stop()
{
buzzer_on = 0;
/*
* Unregister the buzzer module from LPM. This will effectively release our
* lock for the PERIPH PD allowing it to be powered down (unless some other
* module keeps it on)
*/
lpm_unregister_module(&buzzer_module);
/* Stop the timer */
ti_lib_timer_disable(GPT0_BASE, TIMER_A);
/*
* Stop the module clock:
*
* Currently GPT0 is in use by clock_delay_usec (GPT0/TB) and by this
* module here (GPT0/TA).
*
* clock_delay_usec
* - is definitely not running when we enter here and
* - handles the module clock internally
*
* Thus, we can safely change the state of module clocks here.
*/
ti_lib_prcm_peripheral_run_disable(PRCM_PERIPH_TIMER0);
ti_lib_prcm_peripheral_sleep_disable(PRCM_PERIPH_TIMER0);
ti_lib_prcm_peripheral_deep_sleep_disable(PRCM_PERIPH_TIMER0);
ti_lib_prcm_load_set();
while(!ti_lib_prcm_load_get());
/* Un-configure the pin */
ti_lib_ioc_pin_type_gpio_input(BOARD_IOID_BUZZER);
ti_lib_ioc_io_input_set(BOARD_IOID_BUZZER, IOC_INPUT_DISABLE);
}
/*---------------------------------------------------------------------------*/
/** @} */
| arurke/contiki | platform/srf06-cc26xx/sensortag/buzzer.c | C | bsd-3-clause | 4,957 |
#region license
// Copyright (c) 2005 - 2007 Ayende Rahien ([email protected])
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
// * Neither the name of Ayende Rahien nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion
using System;
using System.Collections.Generic;
using Xunit;
namespace Rhino.Mocks.Tests.FieldsProblem
{
using Castle.Core.Interceptor;
using Castle.DynamicProxy;
public class FieldProblem_James
{
private MockRepository m_mockery;
public FieldProblem_James()
{
m_mockery = new MockRepository();
}
[Fact]
public void ShouldBeAbleToMockGenericMethod()
{
ILookupMapper<int> mapper = m_mockery.StrictMock<ILookupMapper<int>>();
List<Foo<int>> retval = new List<Foo<int>>();
retval.Add(new Foo<int>());
Expect.Call(mapper.FindAllFoo()).Return(retval);
m_mockery.ReplayAll();
IList<Foo<int>> listOfFoo = mapper.FindAllFoo();
m_mockery.VerifyAll();
}
[Fact]
public void ShouldBeAbleToMockGenericMethod2()
{
ILookupMapper<int> mapper = m_mockery.StrictMock<ILookupMapper<int>>();
Foo<int> retval = new Foo<int>();
Expect.Call(mapper.FindOneFoo()).Return(retval);
m_mockery.ReplayAll();
Foo<int> oneFoo = mapper.FindOneFoo();
m_mockery.VerifyAll();
}
[Fact]
public void CanMockMethodsReturnIntPtr()
{
IFooWithIntPtr mock = m_mockery.StrictMock<IFooWithIntPtr>();
using(m_mockery.Record())
{
Expect.Call(mock.Buffer(15)).Return(IntPtr.Zero);
}
using(m_mockery.Playback())
{
IntPtr buffer = mock.Buffer(15);
Assert.Equal(IntPtr.Zero, buffer);
}
}
[Fact]
public void ShouldGetValidErrorWhenGenericTypeMismatchOccurs()
{
ILookupMapper<int> mapper = m_mockery.StrictMock<ILookupMapper<int>>();
Foo<string> retval = new Foo<string>();
Assert.Throws<InvalidOperationException>(
"Type 'Rhino.Mocks.Tests.FieldsProblem.Foo`1[[System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]' doesn't match the return type 'Rhino.Mocks.Tests.FieldsProblem.Foo`1[System.Int32]' for method 'ILookupMapper`1.FindOneFoo();'",
() => Expect.Call<object>(mapper.FindOneFoo()).Return(retval));
}
}
public interface ILookupMapper<T>
{
IList<Foo<T>> FindAllFoo();
Foo<T> FindOneFoo();
}
public class Foo<T>
{
public T GetOne()
{
return default(T);
}
}
public interface IFooWithIntPtr
{
IntPtr Buffer(UInt32 index);
}
} | hibernating-rhinos/rhino-mocks | Rhino.Mocks.Tests/FieldsProblem/FieldProblem_James.cs | C# | bsd-3-clause | 3,943 |
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule getEventKey
*/
'use strict';
const {
__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED,
} = require('ReactDOM-fb');
module.exports = __SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.getEventKey;
| flipactual/react | scripts/rollup/shims/facebook-www/getEventKey.js | JavaScript | bsd-3-clause | 527 |
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/browser/renderer_host/media/video_capture_host.h"
#include <memory>
#include "base/bind.h"
#include "base/bind_helpers.h"
#include "content/browser/browser_main_loop.h"
#include "content/browser/renderer_host/media/media_stream_manager.h"
#include "content/browser/renderer_host/media/video_capture_manager.h"
#include "content/common/media/video_capture_messages.h"
namespace content {
VideoCaptureHost::VideoCaptureHost(MediaStreamManager* media_stream_manager)
: BrowserMessageFilter(VideoCaptureMsgStart),
media_stream_manager_(media_stream_manager) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
}
VideoCaptureHost::~VideoCaptureHost() {}
void VideoCaptureHost::OnChannelClosing() {
// Since the IPC sender is gone, close all requested VideoCaptureDevices.
for (EntryMap::iterator it = entries_.begin(); it != entries_.end(); ) {
const base::WeakPtr<VideoCaptureController>& controller = it->second;
if (controller) {
const VideoCaptureControllerID controller_id(it->first);
media_stream_manager_->video_capture_manager()->StopCaptureForClient(
controller.get(), controller_id, this, false);
++it;
} else {
// Remove the entry for this controller_id so that when the controller
// is added, the controller will be notified to stop for this client
// in DoControllerAdded.
entries_.erase(it++);
}
}
}
void VideoCaptureHost::OnDestruct() const {
BrowserThread::DeleteOnIOThread::Destruct(this);
}
///////////////////////////////////////////////////////////////////////////////
// Implements VideoCaptureControllerEventHandler.
void VideoCaptureHost::OnError(VideoCaptureControllerID controller_id) {
DVLOG(1) << "VideoCaptureHost::OnError";
DCHECK_CURRENTLY_ON(BrowserThread::IO);
BrowserThread::PostTask(
BrowserThread::IO, FROM_HERE,
base::Bind(&VideoCaptureHost::DoError, this, controller_id));
}
void VideoCaptureHost::OnBufferCreated(VideoCaptureControllerID controller_id,
base::SharedMemoryHandle handle,
int length,
int buffer_id) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
if (entries_.find(controller_id) == entries_.end())
return;
Send(new VideoCaptureMsg_NewBuffer(controller_id, handle, length, buffer_id));
}
void VideoCaptureHost::OnBufferCreated2(
VideoCaptureControllerID controller_id,
const std::vector<gfx::GpuMemoryBufferHandle>& handles,
const gfx::Size& size,
int buffer_id) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
if (entries_.find(controller_id) == entries_.end())
return;
Send(new VideoCaptureMsg_NewBuffer2(controller_id, handles, size, buffer_id));
}
void VideoCaptureHost::OnBufferDestroyed(VideoCaptureControllerID controller_id,
int buffer_id) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
if (entries_.find(controller_id) == entries_.end())
return;
Send(new VideoCaptureMsg_FreeBuffer(controller_id, buffer_id));
}
void VideoCaptureHost::OnBufferReady(
VideoCaptureControllerID controller_id,
int buffer_id,
const scoped_refptr<media::VideoFrame>& video_frame,
const base::TimeTicks& timestamp) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
if (entries_.find(controller_id) == entries_.end())
return;
VideoCaptureMsg_BufferReady_Params params;
params.device_id = controller_id;
params.buffer_id = buffer_id;
params.timestamp = timestamp;
video_frame->metadata()->MergeInternalValuesInto(¶ms.metadata);
params.pixel_format = video_frame->format();
params.storage_type = video_frame->storage_type();
params.coded_size = video_frame->coded_size();
params.visible_rect = video_frame->visible_rect();
Send(new VideoCaptureMsg_BufferReady(params));
}
void VideoCaptureHost::OnEnded(VideoCaptureControllerID controller_id) {
DVLOG(1) << "VideoCaptureHost::OnEnded";
DCHECK_CURRENTLY_ON(BrowserThread::IO);
BrowserThread::PostTask(
BrowserThread::IO, FROM_HERE,
base::Bind(&VideoCaptureHost::DoEnded, this, controller_id));
}
void VideoCaptureHost::DoError(VideoCaptureControllerID controller_id) {
DVLOG(1) << "VideoCaptureHost::DoError";
DCHECK_CURRENTLY_ON(BrowserThread::IO);
if (entries_.find(controller_id) == entries_.end())
return;
Send(new VideoCaptureMsg_StateChanged(controller_id,
VIDEO_CAPTURE_STATE_ERROR));
DeleteVideoCaptureController(controller_id, true);
}
void VideoCaptureHost::DoEnded(VideoCaptureControllerID controller_id) {
DVLOG(1) << "VideoCaptureHost::DoEnded";
DCHECK_CURRENTLY_ON(BrowserThread::IO);
if (entries_.find(controller_id) == entries_.end())
return;
Send(new VideoCaptureMsg_StateChanged(controller_id,
VIDEO_CAPTURE_STATE_ENDED));
DeleteVideoCaptureController(controller_id, false);
}
///////////////////////////////////////////////////////////////////////////////
// IPC Messages handler.
bool VideoCaptureHost::OnMessageReceived(const IPC::Message& message) {
bool handled = true;
IPC_BEGIN_MESSAGE_MAP(VideoCaptureHost, message)
IPC_MESSAGE_HANDLER(VideoCaptureHostMsg_Start, OnStartCapture)
IPC_MESSAGE_HANDLER(VideoCaptureHostMsg_Pause, OnPauseCapture)
IPC_MESSAGE_HANDLER(VideoCaptureHostMsg_Resume, OnResumeCapture)
IPC_MESSAGE_HANDLER(VideoCaptureHostMsg_RequestRefreshFrame,
OnRequestRefreshFrame)
IPC_MESSAGE_HANDLER(VideoCaptureHostMsg_Stop, OnStopCapture)
IPC_MESSAGE_HANDLER(VideoCaptureHostMsg_BufferReady,
OnRendererFinishedWithBuffer)
IPC_MESSAGE_HANDLER(VideoCaptureHostMsg_GetDeviceSupportedFormats,
OnGetDeviceSupportedFormats)
IPC_MESSAGE_HANDLER(VideoCaptureHostMsg_GetDeviceFormatsInUse,
OnGetDeviceFormatsInUse)
IPC_MESSAGE_UNHANDLED(handled = false)
IPC_END_MESSAGE_MAP()
return handled;
}
void VideoCaptureHost::OnStartCapture(int device_id,
media::VideoCaptureSessionId session_id,
const media::VideoCaptureParams& params) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
DVLOG(1) << "VideoCaptureHost::OnStartCapture:"
<< " session_id=" << session_id << ", device_id=" << device_id
<< ", format="
<< media::VideoCaptureFormat::ToString(params.requested_format)
<< "@" << params.requested_format.frame_rate << " ("
<< (params.resolution_change_policy ==
media::RESOLUTION_POLICY_FIXED_RESOLUTION
? "fixed resolution"
: (params.resolution_change_policy ==
media::RESOLUTION_POLICY_FIXED_ASPECT_RATIO
? "fixed aspect ratio"
: "variable resolution")) << ")";
VideoCaptureControllerID controller_id(device_id);
if (entries_.find(controller_id) != entries_.end()) {
Send(new VideoCaptureMsg_StateChanged(device_id,
VIDEO_CAPTURE_STATE_ERROR));
return;
}
entries_[controller_id] = base::WeakPtr<VideoCaptureController>();
media_stream_manager_->video_capture_manager()->StartCaptureForClient(
session_id,
params,
PeerHandle(),
controller_id,
this,
base::Bind(&VideoCaptureHost::OnControllerAdded, this, device_id));
}
void VideoCaptureHost::OnControllerAdded(
int device_id,
const base::WeakPtr<VideoCaptureController>& controller) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
VideoCaptureControllerID controller_id(device_id);
EntryMap::iterator it = entries_.find(controller_id);
if (it == entries_.end()) {
if (controller) {
media_stream_manager_->video_capture_manager()->StopCaptureForClient(
controller.get(), controller_id, this, false);
}
return;
}
if (!controller) {
Send(new VideoCaptureMsg_StateChanged(device_id,
VIDEO_CAPTURE_STATE_ERROR));
entries_.erase(controller_id);
return;
}
DCHECK(!it->second);
it->second = controller;
}
void VideoCaptureHost::OnStopCapture(int device_id) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
DVLOG(1) << "VideoCaptureHost::OnStopCapture, device_id " << device_id;
VideoCaptureControllerID controller_id(device_id);
Send(new VideoCaptureMsg_StateChanged(device_id,
VIDEO_CAPTURE_STATE_STOPPED));
DeleteVideoCaptureController(controller_id, false);
}
void VideoCaptureHost::OnPauseCapture(int device_id) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
DVLOG(1) << "VideoCaptureHost::OnPauseCapture, device_id " << device_id;
VideoCaptureControllerID controller_id(device_id);
EntryMap::iterator it = entries_.find(controller_id);
if (it == entries_.end())
return;
if (it->second) {
media_stream_manager_->video_capture_manager()->PauseCaptureForClient(
it->second.get(), controller_id, this);
}
}
void VideoCaptureHost::OnResumeCapture(
int device_id,
media::VideoCaptureSessionId session_id,
const media::VideoCaptureParams& params) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
DVLOG(1) << "VideoCaptureHost::OnResumeCapture, device_id " << device_id;
VideoCaptureControllerID controller_id(device_id);
EntryMap::iterator it = entries_.find(controller_id);
if (it == entries_.end())
return;
if (it->second) {
media_stream_manager_->video_capture_manager()->ResumeCaptureForClient(
session_id, params, it->second.get(), controller_id, this);
}
}
void VideoCaptureHost::OnRequestRefreshFrame(int device_id) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
DVLOG(1) << "VideoCaptureHost::OnRequestRefreshFrame, device_id "
<< device_id;
VideoCaptureControllerID controller_id(device_id);
EntryMap::iterator it = entries_.find(controller_id);
if (it == entries_.end())
return;
if (VideoCaptureController* controller = it->second.get()) {
media_stream_manager_->video_capture_manager()
->RequestRefreshFrameForClient(controller);
}
}
void VideoCaptureHost::OnRendererFinishedWithBuffer(
int device_id,
int buffer_id,
const gpu::SyncToken& sync_token,
double consumer_resource_utilization) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
VideoCaptureControllerID controller_id(device_id);
EntryMap::iterator it = entries_.find(controller_id);
if (it != entries_.end()) {
const base::WeakPtr<VideoCaptureController>& controller = it->second;
if (controller) {
controller->ReturnBuffer(controller_id, this, buffer_id, sync_token,
consumer_resource_utilization);
}
}
}
void VideoCaptureHost::OnGetDeviceSupportedFormats(
int device_id,
media::VideoCaptureSessionId capture_session_id) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
DVLOG(1) << "VideoCaptureHost::OnGetDeviceFormats, capture_session_id "
<< capture_session_id;
media::VideoCaptureFormats device_supported_formats;
if (!media_stream_manager_->video_capture_manager()
->GetDeviceSupportedFormats(capture_session_id,
&device_supported_formats)) {
DLOG(WARNING)
<< "Could not retrieve device supported formats for device_id="
<< device_id << " capture_session_id=" << capture_session_id;
}
Send(new VideoCaptureMsg_DeviceSupportedFormatsEnumerated(
device_id, device_supported_formats));
}
void VideoCaptureHost::OnGetDeviceFormatsInUse(
int device_id,
media::VideoCaptureSessionId capture_session_id) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
DVLOG(1) << "VideoCaptureHost::OnGetDeviceFormatsInUse, capture_session_id "
<< capture_session_id;
media::VideoCaptureFormats formats_in_use;
if (!media_stream_manager_->video_capture_manager()->GetDeviceFormatsInUse(
capture_session_id, &formats_in_use)) {
DVLOG(1) << "Could not retrieve device format(s) in use for device_id="
<< device_id << " capture_session_id=" << capture_session_id;
}
Send(new VideoCaptureMsg_DeviceFormatsInUseReceived(device_id,
formats_in_use));
}
void VideoCaptureHost::DeleteVideoCaptureController(
VideoCaptureControllerID controller_id, bool on_error) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
EntryMap::iterator it = entries_.find(controller_id);
if (it == entries_.end())
return;
if (it->second) {
media_stream_manager_->video_capture_manager()->StopCaptureForClient(
it->second.get(), controller_id, this, on_error);
}
entries_.erase(it);
}
} // namespace content
| axinging/chromium-crosswalk | content/browser/renderer_host/media/video_capture_host.cc | C++ | bsd-3-clause | 13,015 |
import os
from doctest import ELLIPSIS, NORMALIZE_WHITESPACE
from scrapy.http.response.html import HtmlResponse
from sybil import Sybil
from sybil.parsers.codeblock import CodeBlockParser
from sybil.parsers.doctest import DocTestParser
from sybil.parsers.skip import skip
def load_response(url, filename):
input_path = os.path.join(os.path.dirname(__file__), '_tests', filename)
with open(input_path, 'rb') as input_file:
return HtmlResponse(url, body=input_file.read())
def setup(namespace):
namespace['load_response'] = load_response
pytest_collect_file = Sybil(
parsers=[
DocTestParser(optionflags=ELLIPSIS | NORMALIZE_WHITESPACE),
CodeBlockParser(future_imports=['print_function']),
skip,
],
pattern='*.rst',
setup=setup,
).pytest()
| starrify/scrapy | docs/conftest.py | Python | bsd-3-clause | 804 |
/*
* Copyright © 2011,2012 Google, Inc.
*
* This is part of HarfBuzz, a text shaping library.
*
* Permission is hereby granted, without written agreement and without
* license or royalty fees, to use, copy, modify, and distribute this
* software and its documentation for any purpose, provided that the
* above copyright notice and the following two paragraphs appear in
* all copies of this software.
*
* IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE TO ANY PARTY FOR
* DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES
* ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN
* IF THE COPYRIGHT HOLDER HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*
* THE COPYRIGHT HOLDER SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING,
* BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS
* ON AN "AS IS" BASIS, AND THE COPYRIGHT HOLDER HAS NO OBLIGATION TO
* PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
*
* Google Author(s): Behdad Esfahbod
*/
#include "hb-ot-shape-complex-indic-private.hh"
#include "hb-ot-layout-private.hh"
/* buffer var allocations */
#define indic_category() complex_var_u8_0() /* indic_category_t */
#define indic_position() complex_var_u8_1() /* indic_position_t */
/*
* Indic shaper.
*/
#define IN_HALF_BLOCK(u, Base) (((u) & ~0x7Fu) == (Base))
#define IS_DEVA(u) (IN_HALF_BLOCK (u, 0x0900u))
#define IS_BENG(u) (IN_HALF_BLOCK (u, 0x0980u))
#define IS_GURU(u) (IN_HALF_BLOCK (u, 0x0A00u))
#define IS_GUJR(u) (IN_HALF_BLOCK (u, 0x0A80u))
#define IS_ORYA(u) (IN_HALF_BLOCK (u, 0x0B00u))
#define IS_TAML(u) (IN_HALF_BLOCK (u, 0x0B80u))
#define IS_TELU(u) (IN_HALF_BLOCK (u, 0x0C00u))
#define IS_KNDA(u) (IN_HALF_BLOCK (u, 0x0C80u))
#define IS_MLYM(u) (IN_HALF_BLOCK (u, 0x0D00u))
#define IS_SINH(u) (IN_HALF_BLOCK (u, 0x0D80u))
#define IS_KHMR(u) (IN_HALF_BLOCK (u, 0x1780u))
#define MATRA_POS_LEFT(u) POS_PRE_M
#define MATRA_POS_RIGHT(u) ( \
IS_DEVA(u) ? POS_AFTER_SUB : \
IS_BENG(u) ? POS_AFTER_POST : \
IS_GURU(u) ? POS_AFTER_POST : \
IS_GUJR(u) ? POS_AFTER_POST : \
IS_ORYA(u) ? POS_AFTER_POST : \
IS_TAML(u) ? POS_AFTER_POST : \
IS_TELU(u) ? (u <= 0x0C42u ? POS_BEFORE_SUB : POS_AFTER_SUB) : \
IS_KNDA(u) ? (u < 0x0CC3u || u > 0xCD6u ? POS_BEFORE_SUB : POS_AFTER_SUB) : \
IS_MLYM(u) ? POS_AFTER_POST : \
IS_SINH(u) ? POS_AFTER_SUB : \
IS_KHMR(u) ? POS_AFTER_POST : \
/*default*/ POS_AFTER_SUB \
)
#define MATRA_POS_TOP(u) ( /* BENG and MLYM don't have top matras. */ \
IS_DEVA(u) ? POS_AFTER_SUB : \
IS_GURU(u) ? POS_AFTER_POST : /* Deviate from spec */ \
IS_GUJR(u) ? POS_AFTER_SUB : \
IS_ORYA(u) ? POS_AFTER_MAIN : \
IS_TAML(u) ? POS_AFTER_SUB : \
IS_TELU(u) ? POS_BEFORE_SUB : \
IS_KNDA(u) ? POS_BEFORE_SUB : \
IS_SINH(u) ? POS_AFTER_SUB : \
IS_KHMR(u) ? POS_AFTER_POST : \
/*default*/ POS_AFTER_SUB \
)
#define MATRA_POS_BOTTOM(u) ( \
IS_DEVA(u) ? POS_AFTER_SUB : \
IS_BENG(u) ? POS_AFTER_SUB : \
IS_GURU(u) ? POS_AFTER_POST : \
IS_GUJR(u) ? POS_AFTER_POST : \
IS_ORYA(u) ? POS_AFTER_SUB : \
IS_TAML(u) ? POS_AFTER_POST : \
IS_TELU(u) ? POS_BEFORE_SUB : \
IS_KNDA(u) ? POS_BEFORE_SUB : \
IS_MLYM(u) ? POS_AFTER_POST : \
IS_SINH(u) ? POS_AFTER_SUB : \
IS_KHMR(u) ? POS_AFTER_POST : \
/*default*/ POS_AFTER_SUB \
)
static inline indic_position_t
matra_position (hb_codepoint_t u, indic_position_t side)
{
switch ((int) side)
{
case POS_PRE_C: return MATRA_POS_LEFT (u);
case POS_POST_C: return MATRA_POS_RIGHT (u);
case POS_ABOVE_C: return MATRA_POS_TOP (u);
case POS_BELOW_C: return MATRA_POS_BOTTOM (u);
};
return side;
}
/* XXX
* This is a hack for now. We should move this data into the main Indic table.
* Or completely remove it and just check in the tables.
*/
static const hb_codepoint_t ra_chars[] = {
0x0930u, /* Devanagari */
0x09B0u, /* Bengali */
0x09F0u, /* Bengali */
0x0A30u, /* Gurmukhi */ /* No Reph */
0x0AB0u, /* Gujarati */
0x0B30u, /* Oriya */
0x0BB0u, /* Tamil */ /* No Reph */
0x0C30u, /* Telugu */ /* Reph formed only with ZWJ */
0x0CB0u, /* Kannada */
0x0D30u, /* Malayalam */ /* No Reph, Logical Repha */
0x0DBBu, /* Sinhala */ /* Reph formed only with ZWJ */
0x179Au, /* Khmer */ /* No Reph, Visual Repha */
};
static inline bool
is_ra (hb_codepoint_t u)
{
for (unsigned int i = 0; i < ARRAY_LENGTH (ra_chars); i++)
if (u == ra_chars[i])
return true;
return false;
}
static inline bool
is_one_of (const hb_glyph_info_t &info, unsigned int flags)
{
/* If it ligated, all bets are off. */
if (_hb_glyph_info_ligated (&info)) return false;
return !!(FLAG_SAFE (info.indic_category()) & flags);
}
static inline bool
is_joiner (const hb_glyph_info_t &info)
{
return is_one_of (info, JOINER_FLAGS);
}
static inline bool
is_consonant (const hb_glyph_info_t &info)
{
return is_one_of (info, CONSONANT_FLAGS);
}
static inline bool
is_halant_or_coeng (const hb_glyph_info_t &info)
{
return is_one_of (info, HALANT_OR_COENG_FLAGS);
}
static inline void
set_indic_properties (hb_glyph_info_t &info)
{
hb_codepoint_t u = info.codepoint;
unsigned int type = hb_indic_get_categories (u);
indic_category_t cat = (indic_category_t) (type & 0x7Fu);
indic_position_t pos = (indic_position_t) (type >> 8);
/*
* Re-assign category
*/
/* The following act more like the Bindus. */
if (unlikely (hb_in_range (u, 0x0953u, 0x0954u)))
cat = OT_SM;
/* The following act like consonants. */
else if (unlikely (hb_in_ranges (u, 0x0A72u, 0x0A73u,
0x1CF5u, 0x1CF6u)))
cat = OT_C;
/* TODO: The following should only be allowed after a Visarga.
* For now, just treat them like regular tone marks. */
else if (unlikely (hb_in_range (u, 0x1CE2u, 0x1CE8u)))
cat = OT_A;
/* TODO: The following should only be allowed after some of
* the nasalization marks, maybe only for U+1CE9..U+1CF1.
* For now, just treat them like tone marks. */
else if (unlikely (u == 0x1CEDu))
cat = OT_A;
/* The following take marks in standalone clusters, similar to Avagraha. */
else if (unlikely (hb_in_ranges (u, 0xA8F2u, 0xA8F7u,
0x1CE9u, 0x1CECu,
0x1CEEu, 0x1CF1u)))
{
cat = OT_Symbol;
ASSERT_STATIC ((int) INDIC_SYLLABIC_CATEGORY_AVAGRAHA == OT_Symbol);
}
else if (unlikely (u == 0x17DDu)) /* https://github.com/roozbehp/unicode-data/issues/2 */
{
cat = OT_M;
pos = POS_ABOVE_C;
}
else if (unlikely (u == 0x17C6u)) cat = OT_N; /* Khmer Bindu doesn't like to be repositioned. */
else if (unlikely (hb_in_range (u, 0x2010u, 0x2011u)))
cat = OT_PLACEHOLDER;
else if (unlikely (u == 0x25CCu)) cat = OT_DOTTEDCIRCLE;
else if (unlikely (u == 0xA982u)) cat = OT_SM; /* Javanese repha. */
else if (unlikely (u == 0xA9BEu)) cat = OT_CM2; /* Javanese medial ya. */
else if (unlikely (u == 0xA9BDu)) { cat = OT_M; pos = POS_POST_C; } /* Javanese vocalic r. */
/*
* Re-assign position.
*/
if ((FLAG_SAFE (cat) & CONSONANT_FLAGS))
{
pos = POS_BASE_C;
if (is_ra (u))
cat = OT_Ra;
}
else if (cat == OT_M)
{
pos = matra_position (u, pos);
}
else if ((FLAG_SAFE (cat) & (FLAG (OT_SM) | FLAG (OT_VD) | FLAG (OT_A) | FLAG (OT_Symbol))))
{
pos = POS_SMVD;
}
if (unlikely (u == 0x0B01u)) pos = POS_BEFORE_SUB; /* Oriya Bindu is BeforeSub in the spec. */
info.indic_category() = cat;
info.indic_position() = pos;
}
/*
* Things above this line should ideally be moved to the Indic table itself.
*/
/*
* Indic configurations. Note that we do not want to keep every single script-specific
* behavior in these tables necessarily. This should mainly be used for per-script
* properties that are cheaper keeping here, than in the code. Ie. if, say, one and
* only one script has an exception, that one script can be if'ed directly in the code,
* instead of adding a new flag in these structs.
*/
enum base_position_t {
BASE_POS_FIRST,
BASE_POS_LAST_SINHALA,
BASE_POS_LAST
};
enum reph_position_t {
REPH_POS_AFTER_MAIN = POS_AFTER_MAIN,
REPH_POS_BEFORE_SUB = POS_BEFORE_SUB,
REPH_POS_AFTER_SUB = POS_AFTER_SUB,
REPH_POS_BEFORE_POST = POS_BEFORE_POST,
REPH_POS_AFTER_POST = POS_AFTER_POST,
REPH_POS_DONT_CARE = POS_RA_TO_BECOME_REPH
};
enum reph_mode_t {
REPH_MODE_IMPLICIT, /* Reph formed out of initial Ra,H sequence. */
REPH_MODE_EXPLICIT, /* Reph formed out of initial Ra,H,ZWJ sequence. */
REPH_MODE_VIS_REPHA, /* Encoded Repha character, no reordering needed. */
REPH_MODE_LOG_REPHA /* Encoded Repha character, needs reordering. */
};
enum blwf_mode_t {
BLWF_MODE_PRE_AND_POST, /* Below-forms feature applied to pre-base and post-base. */
BLWF_MODE_POST_ONLY /* Below-forms feature applied to post-base only. */
};
enum pref_len_t {
PREF_LEN_1 = 1,
PREF_LEN_2 = 2,
PREF_LEN_DONT_CARE = PREF_LEN_2
};
struct indic_config_t
{
hb_script_t script;
bool has_old_spec;
hb_codepoint_t virama;
base_position_t base_pos;
reph_position_t reph_pos;
reph_mode_t reph_mode;
blwf_mode_t blwf_mode;
pref_len_t pref_len;
};
static const indic_config_t indic_configs[] =
{
/* Default. Should be first. */
{HB_SCRIPT_INVALID, false, 0,BASE_POS_LAST, REPH_POS_BEFORE_POST,REPH_MODE_IMPLICIT, BLWF_MODE_PRE_AND_POST, PREF_LEN_1},
{HB_SCRIPT_DEVANAGARI,true, 0x094Du,BASE_POS_LAST, REPH_POS_BEFORE_POST,REPH_MODE_IMPLICIT, BLWF_MODE_PRE_AND_POST, PREF_LEN_DONT_CARE},
{HB_SCRIPT_BENGALI, true, 0x09CDu,BASE_POS_LAST, REPH_POS_AFTER_SUB, REPH_MODE_IMPLICIT, BLWF_MODE_PRE_AND_POST, PREF_LEN_DONT_CARE},
{HB_SCRIPT_GURMUKHI, true, 0x0A4Du,BASE_POS_LAST, REPH_POS_BEFORE_SUB, REPH_MODE_IMPLICIT, BLWF_MODE_PRE_AND_POST, PREF_LEN_DONT_CARE},
{HB_SCRIPT_GUJARATI, true, 0x0ACDu,BASE_POS_LAST, REPH_POS_BEFORE_POST,REPH_MODE_IMPLICIT, BLWF_MODE_PRE_AND_POST, PREF_LEN_DONT_CARE},
{HB_SCRIPT_ORIYA, true, 0x0B4Du,BASE_POS_LAST, REPH_POS_AFTER_MAIN, REPH_MODE_IMPLICIT, BLWF_MODE_PRE_AND_POST, PREF_LEN_DONT_CARE},
{HB_SCRIPT_TAMIL, true, 0x0BCDu,BASE_POS_LAST, REPH_POS_AFTER_POST, REPH_MODE_IMPLICIT, BLWF_MODE_PRE_AND_POST, PREF_LEN_2},
{HB_SCRIPT_TELUGU, true, 0x0C4Du,BASE_POS_LAST, REPH_POS_AFTER_POST, REPH_MODE_EXPLICIT, BLWF_MODE_POST_ONLY, PREF_LEN_2},
{HB_SCRIPT_KANNADA, true, 0x0CCDu,BASE_POS_LAST, REPH_POS_AFTER_POST, REPH_MODE_IMPLICIT, BLWF_MODE_POST_ONLY, PREF_LEN_2},
{HB_SCRIPT_MALAYALAM, true, 0x0D4Du,BASE_POS_LAST, REPH_POS_AFTER_MAIN, REPH_MODE_LOG_REPHA,BLWF_MODE_PRE_AND_POST, PREF_LEN_2},
{HB_SCRIPT_SINHALA, false,0x0DCAu,BASE_POS_LAST_SINHALA,
REPH_POS_AFTER_MAIN, REPH_MODE_EXPLICIT, BLWF_MODE_PRE_AND_POST, PREF_LEN_DONT_CARE},
{HB_SCRIPT_KHMER, false,0x17D2u,BASE_POS_FIRST,REPH_POS_DONT_CARE, REPH_MODE_VIS_REPHA,BLWF_MODE_PRE_AND_POST, PREF_LEN_2},
{HB_SCRIPT_JAVANESE, false,0xA9C0u,BASE_POS_FIRST,REPH_POS_DONT_CARE, REPH_MODE_VIS_REPHA,BLWF_MODE_PRE_AND_POST, PREF_LEN_1},
};
/*
* Indic shaper.
*/
struct feature_list_t {
hb_tag_t tag;
hb_ot_map_feature_flags_t flags;
};
static const feature_list_t
indic_features[] =
{
/*
* Basic features.
* These features are applied in order, one at a time, after initial_reordering.
*/
{HB_TAG('n','u','k','t'), F_GLOBAL},
{HB_TAG('a','k','h','n'), F_GLOBAL},
{HB_TAG('r','p','h','f'), F_NONE},
{HB_TAG('r','k','r','f'), F_GLOBAL},
{HB_TAG('p','r','e','f'), F_NONE},
{HB_TAG('b','l','w','f'), F_NONE},
{HB_TAG('a','b','v','f'), F_NONE},
{HB_TAG('h','a','l','f'), F_NONE},
{HB_TAG('p','s','t','f'), F_NONE},
{HB_TAG('v','a','t','u'), F_GLOBAL},
{HB_TAG('c','j','c','t'), F_GLOBAL},
{HB_TAG('c','f','a','r'), F_NONE},
/*
* Other features.
* These features are applied all at once, after final_reordering.
* Default Bengali font in Windows for example has intermixed
* lookups for init,pres,abvs,blws features.
*/
{HB_TAG('i','n','i','t'), F_NONE},
{HB_TAG('p','r','e','s'), F_GLOBAL},
{HB_TAG('a','b','v','s'), F_GLOBAL},
{HB_TAG('b','l','w','s'), F_GLOBAL},
{HB_TAG('p','s','t','s'), F_GLOBAL},
{HB_TAG('h','a','l','n'), F_GLOBAL},
/* Positioning features, though we don't care about the types. */
{HB_TAG('d','i','s','t'), F_GLOBAL},
{HB_TAG('a','b','v','m'), F_GLOBAL},
{HB_TAG('b','l','w','m'), F_GLOBAL},
};
/*
* Must be in the same order as the indic_features array.
*/
enum {
_NUKT,
_AKHN,
RPHF,
_RKRF,
PREF,
BLWF,
ABVF,
HALF,
PSTF,
_VATU,
_CJCT,
CFAR,
INIT,
_PRES,
_ABVS,
_BLWS,
_PSTS,
_HALN,
_DIST,
_ABVM,
_BLWM,
INDIC_NUM_FEATURES,
INDIC_BASIC_FEATURES = INIT /* Don't forget to update this! */
};
static void
setup_syllables (const hb_ot_shape_plan_t *plan,
hb_font_t *font,
hb_buffer_t *buffer);
static void
initial_reordering (const hb_ot_shape_plan_t *plan,
hb_font_t *font,
hb_buffer_t *buffer);
static void
final_reordering (const hb_ot_shape_plan_t *plan,
hb_font_t *font,
hb_buffer_t *buffer);
static void
clear_syllables (const hb_ot_shape_plan_t *plan,
hb_font_t *font,
hb_buffer_t *buffer);
static void
collect_features_indic (hb_ot_shape_planner_t *plan)
{
hb_ot_map_builder_t *map = &plan->map;
/* Do this before any lookups have been applied. */
map->add_gsub_pause (setup_syllables);
map->add_global_bool_feature (HB_TAG('l','o','c','l'));
/* The Indic specs do not require ccmp, but we apply it here since if
* there is a use of it, it's typically at the beginning. */
map->add_global_bool_feature (HB_TAG('c','c','m','p'));
unsigned int i = 0;
map->add_gsub_pause (initial_reordering);
for (; i < INDIC_BASIC_FEATURES; i++) {
map->add_feature (indic_features[i].tag, 1, indic_features[i].flags | F_MANUAL_ZWJ);
map->add_gsub_pause (NULL);
}
map->add_gsub_pause (final_reordering);
for (; i < INDIC_NUM_FEATURES; i++) {
map->add_feature (indic_features[i].tag, 1, indic_features[i].flags | F_MANUAL_ZWJ);
}
map->add_global_bool_feature (HB_TAG('c','a','l','t'));
map->add_global_bool_feature (HB_TAG('c','l','i','g'));
map->add_gsub_pause (clear_syllables);
}
static void
override_features_indic (hb_ot_shape_planner_t *plan)
{
/* Uniscribe does not apply 'kern' in Khmer. */
if (hb_options ().uniscribe_bug_compatible)
{
switch ((hb_tag_t) plan->props.script)
{
case HB_SCRIPT_KHMER:
plan->map.add_feature (HB_TAG('k','e','r','n'), 0, F_GLOBAL);
break;
}
}
plan->map.add_feature (HB_TAG('l','i','g','a'), 0, F_GLOBAL);
}
struct would_substitute_feature_t
{
inline void init (const hb_ot_map_t *map, hb_tag_t feature_tag, bool zero_context_)
{
zero_context = zero_context_;
map->get_stage_lookups (0/*GSUB*/,
map->get_feature_stage (0/*GSUB*/, feature_tag),
&lookups, &count);
}
inline bool would_substitute (const hb_codepoint_t *glyphs,
unsigned int glyphs_count,
hb_face_t *face) const
{
for (unsigned int i = 0; i < count; i++)
if (hb_ot_layout_lookup_would_substitute_fast (face, lookups[i].index, glyphs, glyphs_count, zero_context))
return true;
return false;
}
private:
const hb_ot_map_t::lookup_map_t *lookups;
unsigned int count;
bool zero_context;
};
struct indic_shape_plan_t
{
ASSERT_POD ();
inline bool get_virama_glyph (hb_font_t *font, hb_codepoint_t *pglyph) const
{
hb_codepoint_t glyph = virama_glyph;
if (unlikely (virama_glyph == (hb_codepoint_t) -1))
{
if (!config->virama || !font->get_glyph (config->virama, 0, &glyph))
glyph = 0;
/* Technically speaking, the spec says we should apply 'locl' to virama too.
* Maybe one day... */
/* Our get_glyph() function needs a font, so we can't get the virama glyph
* during shape planning... Instead, overwrite it here. It's safe. Don't worry! */
(const_cast<indic_shape_plan_t *> (this))->virama_glyph = glyph;
}
*pglyph = glyph;
return glyph != 0;
}
const indic_config_t *config;
bool is_old_spec;
hb_codepoint_t virama_glyph;
would_substitute_feature_t rphf;
would_substitute_feature_t pref;
would_substitute_feature_t blwf;
would_substitute_feature_t pstf;
hb_mask_t mask_array[INDIC_NUM_FEATURES];
};
static void *
data_create_indic (const hb_ot_shape_plan_t *plan)
{
indic_shape_plan_t *indic_plan = (indic_shape_plan_t *) calloc (1, sizeof (indic_shape_plan_t));
if (unlikely (!indic_plan))
return NULL;
indic_plan->config = &indic_configs[0];
for (unsigned int i = 1; i < ARRAY_LENGTH (indic_configs); i++)
if (plan->props.script == indic_configs[i].script) {
indic_plan->config = &indic_configs[i];
break;
}
indic_plan->is_old_spec = indic_plan->config->has_old_spec && ((plan->map.chosen_script[0] & 0x000000FFu) != '2');
indic_plan->virama_glyph = (hb_codepoint_t) -1;
/* Use zero-context would_substitute() matching for new-spec of the main
* Indic scripts, and scripts with one spec only, but not for old-specs.
* The new-spec for all dual-spec scripts says zero-context matching happens.
*
* However, testing with Malayalam shows that old and new spec both allow
* context. Testing with Bengali new-spec however shows that it doesn't.
* So, the heuristic here is the way it is. It should *only* be changed,
* as we discover more cases of what Windows does. DON'T TOUCH OTHERWISE.
*/
bool zero_context = !indic_plan->is_old_spec && plan->props.script != HB_SCRIPT_MALAYALAM;
indic_plan->rphf.init (&plan->map, HB_TAG('r','p','h','f'), zero_context);
indic_plan->pref.init (&plan->map, HB_TAG('p','r','e','f'), zero_context);
indic_plan->blwf.init (&plan->map, HB_TAG('b','l','w','f'), zero_context);
indic_plan->pstf.init (&plan->map, HB_TAG('p','s','t','f'), zero_context);
for (unsigned int i = 0; i < ARRAY_LENGTH (indic_plan->mask_array); i++)
indic_plan->mask_array[i] = (indic_features[i].flags & F_GLOBAL) ?
0 : plan->map.get_1_mask (indic_features[i].tag);
return indic_plan;
}
static void
data_destroy_indic (void *data)
{
free (data);
}
static indic_position_t
consonant_position_from_face (const indic_shape_plan_t *indic_plan,
const hb_codepoint_t consonant,
const hb_codepoint_t virama,
hb_face_t *face)
{
/* For old-spec, the order of glyphs is Consonant,Virama,
* whereas for new-spec, it's Virama,Consonant. However,
* some broken fonts (like Free Sans) simply copied lookups
* from old-spec to new-spec without modification.
* And oddly enough, Uniscribe seems to respect those lookups.
* Eg. in the sequence U+0924,U+094D,U+0930, Uniscribe finds
* base at 0. The font however, only has lookups matching
* 930,94D in 'blwf', not the expected 94D,930 (with new-spec
* table). As such, we simply match both sequences. Seems
* to work. */
hb_codepoint_t glyphs[3] = {virama, consonant, virama};
if (indic_plan->blwf.would_substitute (glyphs , 2, face) ||
indic_plan->blwf.would_substitute (glyphs+1, 2, face))
return POS_BELOW_C;
if (indic_plan->pstf.would_substitute (glyphs , 2, face) ||
indic_plan->pstf.would_substitute (glyphs+1, 2, face))
return POS_POST_C;
unsigned int pref_len = indic_plan->config->pref_len;
if ((pref_len == PREF_LEN_2 &&
(indic_plan->pref.would_substitute (glyphs , 2, face) ||
indic_plan->pref.would_substitute (glyphs+1, 2, face)))
|| (pref_len == PREF_LEN_1 &&
indic_plan->pref.would_substitute (glyphs+1, 1, face)))
return POS_POST_C;
return POS_BASE_C;
}
enum syllable_type_t {
consonant_syllable,
vowel_syllable,
standalone_cluster,
symbol_cluster,
broken_cluster,
non_indic_cluster,
};
#include "hb-ot-shape-complex-indic-machine.hh"
static void
setup_masks_indic (const hb_ot_shape_plan_t *plan HB_UNUSED,
hb_buffer_t *buffer,
hb_font_t *font HB_UNUSED)
{
HB_BUFFER_ALLOCATE_VAR (buffer, indic_category);
HB_BUFFER_ALLOCATE_VAR (buffer, indic_position);
/* We cannot setup masks here. We save information about characters
* and setup masks later on in a pause-callback. */
unsigned int count = buffer->len;
hb_glyph_info_t *info = buffer->info;
for (unsigned int i = 0; i < count; i++)
set_indic_properties (info[i]);
}
static void
setup_syllables (const hb_ot_shape_plan_t *plan HB_UNUSED,
hb_font_t *font HB_UNUSED,
hb_buffer_t *buffer)
{
find_syllables (buffer);
}
static int
compare_indic_order (const hb_glyph_info_t *pa, const hb_glyph_info_t *pb)
{
int a = pa->indic_position();
int b = pb->indic_position();
return a < b ? -1 : a == b ? 0 : +1;
}
static void
update_consonant_positions (const hb_ot_shape_plan_t *plan,
hb_font_t *font,
hb_buffer_t *buffer)
{
const indic_shape_plan_t *indic_plan = (const indic_shape_plan_t *) plan->data;
if (indic_plan->config->base_pos != BASE_POS_LAST)
return;
hb_codepoint_t virama;
if (indic_plan->get_virama_glyph (font, &virama))
{
hb_face_t *face = font->face;
unsigned int count = buffer->len;
hb_glyph_info_t *info = buffer->info;
for (unsigned int i = 0; i < count; i++)
if (info[i].indic_position() == POS_BASE_C)
{
hb_codepoint_t consonant = info[i].codepoint;
info[i].indic_position() = consonant_position_from_face (indic_plan, consonant, virama, face);
}
}
}
/* Rules from:
* https://www.microsoft.com/typography/otfntdev/devanot/shaping.aspx */
static void
initial_reordering_consonant_syllable (const hb_ot_shape_plan_t *plan,
hb_face_t *face,
hb_buffer_t *buffer,
unsigned int start, unsigned int end)
{
const indic_shape_plan_t *indic_plan = (const indic_shape_plan_t *) plan->data;
hb_glyph_info_t *info = buffer->info;
/* 1. Find base consonant:
*
* The shaping engine finds the base consonant of the syllable, using the
* following algorithm: starting from the end of the syllable, move backwards
* until a consonant is found that does not have a below-base or post-base
* form (post-base forms have to follow below-base forms), or that is not a
* pre-base reordering Ra, or arrive at the first consonant. The consonant
* stopped at will be the base.
*
* o If the syllable starts with Ra + Halant (in a script that has Reph)
* and has more than one consonant, Ra is excluded from candidates for
* base consonants.
*/
unsigned int base = end;
bool has_reph = false;
{
/* -> If the syllable starts with Ra + Halant (in a script that has Reph)
* and has more than one consonant, Ra is excluded from candidates for
* base consonants. */
unsigned int limit = start;
if (indic_plan->config->reph_pos != REPH_POS_DONT_CARE &&
indic_plan->mask_array[RPHF] &&
start + 3 <= end &&
(
(indic_plan->config->reph_mode == REPH_MODE_IMPLICIT && !is_joiner (info[start + 2])) ||
(indic_plan->config->reph_mode == REPH_MODE_EXPLICIT && info[start + 2].indic_category() == OT_ZWJ)
))
{
/* See if it matches the 'rphf' feature. */
hb_codepoint_t glyphs[3] = {info[start].codepoint,
info[start + 1].codepoint,
indic_plan->config->reph_mode == REPH_MODE_EXPLICIT ?
info[start + 2].codepoint : 0};
if (indic_plan->rphf.would_substitute (glyphs, 2, face) ||
(indic_plan->config->reph_mode == REPH_MODE_EXPLICIT &&
indic_plan->rphf.would_substitute (glyphs, 3, face)))
{
limit += 2;
while (limit < end && is_joiner (info[limit]))
limit++;
base = start;
has_reph = true;
}
} else if (indic_plan->config->reph_mode == REPH_MODE_LOG_REPHA && info[start].indic_category() == OT_Repha)
{
limit += 1;
while (limit < end && is_joiner (info[limit]))
limit++;
base = start;
has_reph = true;
}
switch (indic_plan->config->base_pos)
{
default:
assert (false);
HB_FALLTHROUGH;
case BASE_POS_LAST:
{
/* -> starting from the end of the syllable, move backwards */
unsigned int i = end;
bool seen_below = false;
do {
i--;
/* -> until a consonant is found */
if (is_consonant (info[i]))
{
/* -> that does not have a below-base or post-base form
* (post-base forms have to follow below-base forms), */
if (info[i].indic_position() != POS_BELOW_C &&
(info[i].indic_position() != POS_POST_C || seen_below))
{
base = i;
break;
}
if (info[i].indic_position() == POS_BELOW_C)
seen_below = true;
/* -> or that is not a pre-base reordering Ra,
*
* IMPLEMENTATION NOTES:
*
* Our pre-base reordering Ra's are marked POS_POST_C, so will be skipped
* by the logic above already.
*/
/* -> or arrive at the first consonant. The consonant stopped at will
* be the base. */
base = i;
}
else
{
/* A ZWJ after a Halant stops the base search, and requests an explicit
* half form.
* A ZWJ before a Halant, requests a subjoined form instead, and hence
* search continues. This is particularly important for Bengali
* sequence Ra,H,Ya that should form Ya-Phalaa by subjoining Ya. */
if (start < i &&
info[i].indic_category() == OT_ZWJ &&
info[i - 1].indic_category() == OT_H)
break;
}
} while (i > limit);
}
break;
case BASE_POS_LAST_SINHALA:
{
/* Sinhala base positioning is slightly different from main Indic, in that:
* 1. Its ZWJ behavior is different,
* 2. We don't need to look into the font for consonant positions.
*/
if (!has_reph)
base = limit;
/* Find the last base consonant that is not blocked by ZWJ. If there is
* a ZWJ right before a base consonant, that would request a subjoined form. */
for (unsigned int i = limit; i < end; i++)
if (is_consonant (info[i]))
{
if (limit < i && info[i - 1].indic_category() == OT_ZWJ)
break;
else
base = i;
}
/* Mark all subsequent consonants as below. */
for (unsigned int i = base + 1; i < end; i++)
if (is_consonant (info[i]))
info[i].indic_position() = POS_BELOW_C;
}
break;
case BASE_POS_FIRST:
{
/* The first consonant is always the base. */
assert (indic_plan->config->reph_mode == REPH_MODE_VIS_REPHA);
assert (!has_reph);
base = start;
/* Mark all subsequent consonants as below. */
for (unsigned int i = base + 1; i < end; i++)
if (is_consonant (info[i]))
info[i].indic_position() = POS_BELOW_C;
}
break;
}
/* -> If the syllable starts with Ra + Halant (in a script that has Reph)
* and has more than one consonant, Ra is excluded from candidates for
* base consonants.
*
* Only do this for unforced Reph. (ie. not for Ra,H,ZWJ. */
if (has_reph && base == start && limit - base <= 2) {
/* Have no other consonant, so Reph is not formed and Ra becomes base. */
has_reph = false;
}
}
/* 2. Decompose and reorder Matras:
*
* Each matra and any syllable modifier sign in the cluster are moved to the
* appropriate position relative to the consonant(s) in the cluster. The
* shaping engine decomposes two- or three-part matras into their constituent
* parts before any repositioning. Matra characters are classified by which
* consonant in a conjunct they have affinity for and are reordered to the
* following positions:
*
* o Before first half form in the syllable
* o After subjoined consonants
* o After post-form consonant
* o After main consonant (for above marks)
*
* IMPLEMENTATION NOTES:
*
* The normalize() routine has already decomposed matras for us, so we don't
* need to worry about that.
*/
/* 3. Reorder marks to canonical order:
*
* Adjacent nukta and halant or nukta and vedic sign are always repositioned
* if necessary, so that the nukta is first.
*
* IMPLEMENTATION NOTES:
*
* We don't need to do this: the normalize() routine already did this for us.
*/
/* Reorder characters */
for (unsigned int i = start; i < base; i++)
info[i].indic_position() = MIN (POS_PRE_C, (indic_position_t) info[i].indic_position());
if (base < end)
info[base].indic_position() = POS_BASE_C;
/* Mark final consonants. A final consonant is one appearing after a matra,
* like in Khmer. */
for (unsigned int i = base + 1; i < end; i++)
if (info[i].indic_category() == OT_M) {
for (unsigned int j = i + 1; j < end; j++)
if (is_consonant (info[j])) {
info[j].indic_position() = POS_FINAL_C;
break;
}
break;
}
/* Handle beginning Ra */
if (has_reph)
info[start].indic_position() = POS_RA_TO_BECOME_REPH;
/* For old-style Indic script tags, move the first post-base Halant after
* last consonant.
*
* Reports suggest that in some scripts Uniscribe does this only if there
* is *not* a Halant after last consonant already (eg. Kannada), while it
* does it unconditionally in other scripts (eg. Malayalam). We don't
* currently know about other scripts, so we single out Malayalam for now.
*
* Kannada test case:
* U+0C9A,U+0CCD,U+0C9A,U+0CCD
* With some versions of Lohit Kannada.
* https://bugs.freedesktop.org/show_bug.cgi?id=59118
*
* Malayalam test case:
* U+0D38,U+0D4D,U+0D31,U+0D4D,U+0D31,U+0D4D
* With lohit-ttf-20121122/Lohit-Malayalam.ttf
*/
if (indic_plan->is_old_spec)
{
bool disallow_double_halants = buffer->props.script != HB_SCRIPT_MALAYALAM;
for (unsigned int i = base + 1; i < end; i++)
if (info[i].indic_category() == OT_H)
{
unsigned int j;
for (j = end - 1; j > i; j--)
if (is_consonant (info[j]) ||
(disallow_double_halants && info[j].indic_category() == OT_H))
break;
if (info[j].indic_category() != OT_H && j > i) {
/* Move Halant to after last consonant. */
hb_glyph_info_t t = info[i];
memmove (&info[i], &info[i + 1], (j - i) * sizeof (info[0]));
info[j] = t;
}
break;
}
}
/* Attach misc marks to previous char to move with them. */
{
indic_position_t last_pos = POS_START;
for (unsigned int i = start; i < end; i++)
{
if ((FLAG_SAFE (info[i].indic_category()) & (JOINER_FLAGS | FLAG (OT_N) | FLAG (OT_RS) | MEDIAL_FLAGS | HALANT_OR_COENG_FLAGS)))
{
info[i].indic_position() = last_pos;
if (unlikely (info[i].indic_category() == OT_H &&
info[i].indic_position() == POS_PRE_M))
{
/*
* Uniscribe doesn't move the Halant with Left Matra.
* TEST: U+092B,U+093F,U+094DE
* We follow. This is important for the Sinhala
* U+0DDA split matra since it decomposes to U+0DD9,U+0DCA
* where U+0DD9 is a left matra and U+0DCA is the virama.
* We don't want to move the virama with the left matra.
* TEST: U+0D9A,U+0DDA
*/
for (unsigned int j = i; j > start; j--)
if (info[j - 1].indic_position() != POS_PRE_M) {
info[i].indic_position() = info[j - 1].indic_position();
break;
}
}
} else if (info[i].indic_position() != POS_SMVD) {
last_pos = (indic_position_t) info[i].indic_position();
}
}
}
/* For post-base consonants let them own anything before them
* since the last consonant or matra. */
{
unsigned int last = base;
for (unsigned int i = base + 1; i < end; i++)
if (is_consonant (info[i]))
{
for (unsigned int j = last + 1; j < i; j++)
if (info[j].indic_position() < POS_SMVD)
info[j].indic_position() = info[i].indic_position();
last = i;
} else if (info[i].indic_category() == OT_M)
last = i;
}
{
/* Use syllable() for sort accounting temporarily. */
unsigned int syllable = info[start].syllable();
for (unsigned int i = start; i < end; i++)
info[i].syllable() = i - start;
/* Sit tight, rock 'n roll! */
hb_stable_sort (info + start, end - start, compare_indic_order);
/* Find base again */
base = end;
for (unsigned int i = start; i < end; i++)
if (info[i].indic_position() == POS_BASE_C)
{
base = i;
break;
}
/* Things are out-of-control for post base positions, they may shuffle
* around like crazy. In old-spec mode, we move halants around, so in
* that case merge all clusters after base. Otherwise, check the sort
* order and merge as needed.
* For pre-base stuff, we handle cluster issues in final reordering.
*
* We could use buffer->sort() for this, if there was no special
* reordering of pre-base stuff happening later...
*/
if (indic_plan->is_old_spec || end - base > 127)
buffer->merge_clusters (base, end);
else
{
/* Note! syllable() is a one-byte field. */
for (unsigned int i = base; i < end; i++)
if (info[i].syllable() != 255)
{
unsigned int max = i;
unsigned int j = start + info[i].syllable();
while (j != i)
{
max = MAX (max, j);
unsigned int next = start + info[j].syllable();
info[j].syllable() = 255; /* So we don't process j later again. */
j = next;
}
if (i != max)
buffer->merge_clusters (i, max + 1);
}
}
/* Put syllable back in. */
for (unsigned int i = start; i < end; i++)
info[i].syllable() = syllable;
}
/* Setup masks now */
{
hb_mask_t mask;
/* Reph */
for (unsigned int i = start; i < end && info[i].indic_position() == POS_RA_TO_BECOME_REPH; i++)
info[i].mask |= indic_plan->mask_array[RPHF];
/* Pre-base */
mask = indic_plan->mask_array[HALF];
if (!indic_plan->is_old_spec &&
indic_plan->config->blwf_mode == BLWF_MODE_PRE_AND_POST)
mask |= indic_plan->mask_array[BLWF];
for (unsigned int i = start; i < base; i++)
info[i].mask |= mask;
/* Base */
mask = 0;
if (base < end)
info[base].mask |= mask;
/* Post-base */
mask = indic_plan->mask_array[BLWF] | indic_plan->mask_array[ABVF] | indic_plan->mask_array[PSTF];
for (unsigned int i = base + 1; i < end; i++)
info[i].mask |= mask;
}
if (indic_plan->is_old_spec &&
buffer->props.script == HB_SCRIPT_DEVANAGARI)
{
/* Old-spec eye-lash Ra needs special handling. From the
* spec:
*
* "The feature 'below-base form' is applied to consonants
* having below-base forms and following the base consonant.
* The exception is vattu, which may appear below half forms
* as well as below the base glyph. The feature 'below-base
* form' will be applied to all such occurrences of Ra as well."
*
* Test case: U+0924,U+094D,U+0930,U+094d,U+0915
* with Sanskrit 2003 font.
*
* However, note that Ra,Halant,ZWJ is the correct way to
* request eyelash form of Ra, so we wouldbn't inhibit it
* in that sequence.
*
* Test case: U+0924,U+094D,U+0930,U+094d,U+200D,U+0915
*/
for (unsigned int i = start; i + 1 < base; i++)
if (info[i ].indic_category() == OT_Ra &&
info[i+1].indic_category() == OT_H &&
(i + 2 == base ||
info[i+2].indic_category() != OT_ZWJ))
{
info[i ].mask |= indic_plan->mask_array[BLWF];
info[i+1].mask |= indic_plan->mask_array[BLWF];
}
}
unsigned int pref_len = indic_plan->config->pref_len;
if (indic_plan->mask_array[PREF] && base + pref_len < end)
{
assert (1 <= pref_len && pref_len <= 2);
/* Find a Halant,Ra sequence and mark it for pre-base reordering processing. */
for (unsigned int i = base + 1; i + pref_len - 1 < end; i++) {
hb_codepoint_t glyphs[2];
for (unsigned int j = 0; j < pref_len; j++)
glyphs[j] = info[i + j].codepoint;
if (indic_plan->pref.would_substitute (glyphs, pref_len, face))
{
for (unsigned int j = 0; j < pref_len; j++)
info[i++].mask |= indic_plan->mask_array[PREF];
/* Mark the subsequent stuff with 'cfar'. Used in Khmer.
* Read the feature spec.
* This allows distinguishing the following cases with MS Khmer fonts:
* U+1784,U+17D2,U+179A,U+17D2,U+1782
* U+1784,U+17D2,U+1782,U+17D2,U+179A
*/
if (indic_plan->mask_array[CFAR])
for (; i < end; i++)
info[i].mask |= indic_plan->mask_array[CFAR];
break;
}
}
}
/* Apply ZWJ/ZWNJ effects */
for (unsigned int i = start + 1; i < end; i++)
if (is_joiner (info[i])) {
bool non_joiner = info[i].indic_category() == OT_ZWNJ;
unsigned int j = i;
do {
j--;
/* ZWJ/ZWNJ should disable CJCT. They do that by simply
* being there, since we don't skip them for the CJCT
* feature (ie. F_MANUAL_ZWJ) */
/* A ZWNJ disables HALF. */
if (non_joiner)
info[j].mask &= ~indic_plan->mask_array[HALF];
} while (j > start && !is_consonant (info[j]));
}
}
static void
initial_reordering_standalone_cluster (const hb_ot_shape_plan_t *plan,
hb_face_t *face,
hb_buffer_t *buffer,
unsigned int start, unsigned int end)
{
/* We treat placeholder/dotted-circle as if they are consonants, so we
* should just chain. Only if not in compatibility mode that is... */
if (hb_options ().uniscribe_bug_compatible)
{
/* For dotted-circle, this is what Uniscribe does:
* If dotted-circle is the last glyph, it just does nothing.
* Ie. It doesn't form Reph. */
if (buffer->info[end - 1].indic_category() == OT_DOTTEDCIRCLE)
return;
}
initial_reordering_consonant_syllable (plan, face, buffer, start, end);
}
static void
initial_reordering_syllable (const hb_ot_shape_plan_t *plan,
hb_face_t *face,
hb_buffer_t *buffer,
unsigned int start, unsigned int end)
{
syllable_type_t syllable_type = (syllable_type_t) (buffer->info[start].syllable() & 0x0F);
switch (syllable_type)
{
case vowel_syllable: /* We made the vowels look like consonants. So let's call the consonant logic! */
case consonant_syllable:
initial_reordering_consonant_syllable (plan, face, buffer, start, end);
break;
case broken_cluster: /* We already inserted dotted-circles, so just call the standalone_cluster. */
case standalone_cluster:
initial_reordering_standalone_cluster (plan, face, buffer, start, end);
break;
case symbol_cluster:
case non_indic_cluster:
break;
}
}
static inline void
insert_dotted_circles (const hb_ot_shape_plan_t *plan HB_UNUSED,
hb_font_t *font,
hb_buffer_t *buffer)
{
/* Note: This loop is extra overhead, but should not be measurable. */
bool has_broken_syllables = false;
unsigned int count = buffer->len;
hb_glyph_info_t *info = buffer->info;
for (unsigned int i = 0; i < count; i++)
if ((info[i].syllable() & 0x0F) == broken_cluster)
{
has_broken_syllables = true;
break;
}
if (likely (!has_broken_syllables))
return;
hb_codepoint_t dottedcircle_glyph;
if (!font->get_glyph (0x25CCu, 0, &dottedcircle_glyph))
return;
hb_glyph_info_t dottedcircle = {0};
dottedcircle.codepoint = 0x25CCu;
set_indic_properties (dottedcircle);
dottedcircle.codepoint = dottedcircle_glyph;
buffer->clear_output ();
buffer->idx = 0;
unsigned int last_syllable = 0;
while (buffer->idx < buffer->len && !buffer->in_error)
{
unsigned int syllable = buffer->cur().syllable();
syllable_type_t syllable_type = (syllable_type_t) (syllable & 0x0F);
if (unlikely (last_syllable != syllable && syllable_type == broken_cluster))
{
last_syllable = syllable;
hb_glyph_info_t ginfo = dottedcircle;
ginfo.cluster = buffer->cur().cluster;
ginfo.mask = buffer->cur().mask;
ginfo.syllable() = buffer->cur().syllable();
/* TODO Set glyph_props? */
/* Insert dottedcircle after possible Repha. */
while (buffer->idx < buffer->len && !buffer->in_error &&
last_syllable == buffer->cur().syllable() &&
buffer->cur().indic_category() == OT_Repha)
buffer->next_glyph ();
buffer->output_info (ginfo);
}
else
buffer->next_glyph ();
}
buffer->swap_buffers ();
}
static void
initial_reordering (const hb_ot_shape_plan_t *plan,
hb_font_t *font,
hb_buffer_t *buffer)
{
update_consonant_positions (plan, font, buffer);
insert_dotted_circles (plan, font, buffer);
foreach_syllable (buffer, start, end)
initial_reordering_syllable (plan, font->face, buffer, start, end);
}
static void
final_reordering_syllable (const hb_ot_shape_plan_t *plan,
hb_buffer_t *buffer,
unsigned int start, unsigned int end)
{
const indic_shape_plan_t *indic_plan = (const indic_shape_plan_t *) plan->data;
hb_glyph_info_t *info = buffer->info;
/* This function relies heavily on halant glyphs. Lots of ligation
* and possibly multiplication substitutions happened prior to this
* phase, and that might have messed up our properties. Recover
* from a particular case of that where we're fairly sure that a
* class of OT_H is desired but has been lost. */
if (indic_plan->virama_glyph)
{
unsigned int virama_glyph = indic_plan->virama_glyph;
for (unsigned int i = start; i < end; i++)
if (info[i].codepoint == virama_glyph &&
_hb_glyph_info_ligated (&info[i]) &&
_hb_glyph_info_multiplied (&info[i]))
{
/* This will make sure that this glyph passes is_halant_or_coeng() test. */
info[i].indic_category() = OT_H;
_hb_glyph_info_clear_ligated_and_multiplied (&info[i]);
}
}
/* 4. Final reordering:
*
* After the localized forms and basic shaping forms GSUB features have been
* applied (see below), the shaping engine performs some final glyph
* reordering before applying all the remaining font features to the entire
* cluster.
*/
bool try_pref = !!indic_plan->mask_array[PREF];
/* Find base again */
unsigned int base;
for (base = start; base < end; base++)
if (info[base].indic_position() >= POS_BASE_C)
{
if (try_pref && base + 1 < end && indic_plan->config->pref_len == 2)
{
for (unsigned int i = base + 1; i < end; i++)
if ((info[i].mask & indic_plan->mask_array[PREF]) != 0)
{
if (!(_hb_glyph_info_substituted (&info[i]) &&
_hb_glyph_info_ligated_and_didnt_multiply (&info[i])))
{
/* Ok, this was a 'pref' candidate but didn't form any.
* Base is around here... */
base = i;
while (base < end && is_halant_or_coeng (info[base]))
base++;
info[base].indic_position() = POS_BASE_C;
try_pref = false;
}
break;
}
}
/* For Malayalam, skip over unformed below- (but NOT post-) forms. */
if (buffer->props.script == HB_SCRIPT_MALAYALAM)
{
for (unsigned int i = base + 1; i < end; i++)
{
while (i < end && is_joiner (info[i]))
i++;
if (i == end || !is_halant_or_coeng (info[i]))
break;
i++; /* Skip halant. */
while (i < end && is_joiner (info[i]))
i++;
if (i < end && is_consonant (info[i]) && info[i].indic_position() == POS_BELOW_C)
{
base = i;
info[base].indic_position() = POS_BASE_C;
}
}
}
if (start < base && info[base].indic_position() > POS_BASE_C)
base--;
break;
}
if (base == end && start < base &&
is_one_of (info[base - 1], FLAG (OT_ZWJ)))
base--;
if (base < end)
while (start < base &&
is_one_of (info[base], (FLAG (OT_N) | HALANT_OR_COENG_FLAGS)))
base--;
/* o Reorder matras:
*
* If a pre-base matra character had been reordered before applying basic
* features, the glyph can be moved closer to the main consonant based on
* whether half-forms had been formed. Actual position for the matra is
* defined as “after last standalone halant glyph, after initial matra
* position and before the main consonant”. If ZWJ or ZWNJ follow this
* halant, position is moved after it.
*/
if (start + 1 < end && start < base) /* Otherwise there can't be any pre-base matra characters. */
{
/* If we lost track of base, alas, position before last thingy. */
unsigned int new_pos = base == end ? base - 2 : base - 1;
/* Malayalam / Tamil do not have "half" forms or explicit virama forms.
* The glyphs formed by 'half' are Chillus or ligated explicit viramas.
* We want to position matra after them.
*/
if (buffer->props.script != HB_SCRIPT_MALAYALAM && buffer->props.script != HB_SCRIPT_TAMIL)
{
while (new_pos > start &&
!(is_one_of (info[new_pos], (FLAG (OT_M) | HALANT_OR_COENG_FLAGS))))
new_pos--;
/* If we found no Halant we are done.
* Otherwise only proceed if the Halant does
* not belong to the Matra itself! */
if (is_halant_or_coeng (info[new_pos]) &&
info[new_pos].indic_position() != POS_PRE_M)
{
/* -> If ZWJ or ZWNJ follow this halant, position is moved after it. */
if (new_pos + 1 < end && is_joiner (info[new_pos + 1]))
new_pos++;
}
else
new_pos = start; /* No move. */
}
if (start < new_pos && info[new_pos].indic_position () != POS_PRE_M)
{
/* Now go see if there's actually any matras... */
for (unsigned int i = new_pos; i > start; i--)
if (info[i - 1].indic_position () == POS_PRE_M)
{
unsigned int old_pos = i - 1;
if (old_pos < base && base <= new_pos) /* Shouldn't actually happen. */
base--;
hb_glyph_info_t tmp = info[old_pos];
memmove (&info[old_pos], &info[old_pos + 1], (new_pos - old_pos) * sizeof (info[0]));
info[new_pos] = tmp;
/* Note: this merge_clusters() is intentionally *after* the reordering.
* Indic matra reordering is special and tricky... */
buffer->merge_clusters (new_pos, MIN (end, base + 1));
new_pos--;
}
} else {
for (unsigned int i = start; i < base; i++)
if (info[i].indic_position () == POS_PRE_M) {
buffer->merge_clusters (i, MIN (end, base + 1));
break;
}
}
}
/* o Reorder reph:
*
* Reph’s original position is always at the beginning of the syllable,
* (i.e. it is not reordered at the character reordering stage). However,
* it will be reordered according to the basic-forms shaping results.
* Possible positions for reph, depending on the script, are; after main,
* before post-base consonant forms, and after post-base consonant forms.
*/
/* Two cases:
*
* - If repha is encoded as a sequence of characters (Ra,H or Ra,H,ZWJ), then
* we should only move it if the sequence ligated to the repha form.
*
* - If repha is encoded separately and in the logical position, we should only
* move it if it did NOT ligate. If it ligated, it's probably the font trying
* to make it work without the reordering.
*/
if (start + 1 < end &&
info[start].indic_position() == POS_RA_TO_BECOME_REPH &&
((info[start].indic_category() == OT_Repha) ^
_hb_glyph_info_ligated_and_didnt_multiply (&info[start])))
{
unsigned int new_reph_pos;
reph_position_t reph_pos = indic_plan->config->reph_pos;
assert (reph_pos != REPH_POS_DONT_CARE);
/* 1. If reph should be positioned after post-base consonant forms,
* proceed to step 5.
*/
if (reph_pos == REPH_POS_AFTER_POST)
{
goto reph_step_5;
}
/* 2. If the reph repositioning class is not after post-base: target
* position is after the first explicit halant glyph between the
* first post-reph consonant and last main consonant. If ZWJ or ZWNJ
* are following this halant, position is moved after it. If such
* position is found, this is the target position. Otherwise,
* proceed to the next step.
*
* Note: in old-implementation fonts, where classifications were
* fixed in shaping engine, there was no case where reph position
* will be found on this step.
*/
{
new_reph_pos = start + 1;
while (new_reph_pos < base && !is_halant_or_coeng (info[new_reph_pos]))
new_reph_pos++;
if (new_reph_pos < base && is_halant_or_coeng (info[new_reph_pos]))
{
/* ->If ZWJ or ZWNJ are following this halant, position is moved after it. */
if (new_reph_pos + 1 < base && is_joiner (info[new_reph_pos + 1]))
new_reph_pos++;
goto reph_move;
}
}
/* 3. If reph should be repositioned after the main consonant: find the
* first consonant not ligated with main, or find the first
* consonant that is not a potential pre-base reordering Ra.
*/
if (reph_pos == REPH_POS_AFTER_MAIN)
{
new_reph_pos = base;
while (new_reph_pos + 1 < end && info[new_reph_pos + 1].indic_position() <= POS_AFTER_MAIN)
new_reph_pos++;
if (new_reph_pos < end)
goto reph_move;
}
/* 4. If reph should be positioned before post-base consonant, find
* first post-base classified consonant not ligated with main. If no
* consonant is found, the target position should be before the
* first matra, syllable modifier sign or vedic sign.
*/
/* This is our take on what step 4 is trying to say (and failing, BADLY). */
if (reph_pos == REPH_POS_AFTER_SUB)
{
new_reph_pos = base;
while (new_reph_pos < end &&
!( FLAG_SAFE (info[new_reph_pos + 1].indic_position()) & (FLAG (POS_POST_C) | FLAG (POS_AFTER_POST) | FLAG (POS_SMVD))))
new_reph_pos++;
if (new_reph_pos < end)
goto reph_move;
}
/* 5. If no consonant is found in steps 3 or 4, move reph to a position
* immediately before the first post-base matra, syllable modifier
* sign or vedic sign that has a reordering class after the intended
* reph position. For example, if the reordering position for reph
* is post-main, it will skip above-base matras that also have a
* post-main position.
*/
reph_step_5:
{
/* Copied from step 2. */
new_reph_pos = start + 1;
while (new_reph_pos < base && !is_halant_or_coeng (info[new_reph_pos]))
new_reph_pos++;
if (new_reph_pos < base && is_halant_or_coeng (info[new_reph_pos]))
{
/* ->If ZWJ or ZWNJ are following this halant, position is moved after it. */
if (new_reph_pos + 1 < base && is_joiner (info[new_reph_pos + 1]))
new_reph_pos++;
goto reph_move;
}
}
/* 6. Otherwise, reorder reph to the end of the syllable.
*/
{
new_reph_pos = end - 1;
while (new_reph_pos > start && info[new_reph_pos].indic_position() == POS_SMVD)
new_reph_pos--;
/*
* If the Reph is to be ending up after a Matra,Halant sequence,
* position it before that Halant so it can interact with the Matra.
* However, if it's a plain Consonant,Halant we shouldn't do that.
* Uniscribe doesn't do this.
* TEST: U+0930,U+094D,U+0915,U+094B,U+094D
*/
if (!hb_options ().uniscribe_bug_compatible &&
unlikely (is_halant_or_coeng (info[new_reph_pos]))) {
for (unsigned int i = base + 1; i < new_reph_pos; i++)
if (info[i].indic_category() == OT_M) {
/* Ok, got it. */
new_reph_pos--;
}
}
goto reph_move;
}
reph_move:
{
/* Move */
buffer->merge_clusters (start, new_reph_pos + 1);
hb_glyph_info_t reph = info[start];
memmove (&info[start], &info[start + 1], (new_reph_pos - start) * sizeof (info[0]));
info[new_reph_pos] = reph;
if (start < base && base <= new_reph_pos)
base--;
}
}
/* o Reorder pre-base reordering consonants:
*
* If a pre-base reordering consonant is found, reorder it according to
* the following rules:
*/
if (try_pref && base + 1 < end) /* Otherwise there can't be any pre-base reordering Ra. */
{
unsigned int pref_len = indic_plan->config->pref_len;
for (unsigned int i = base + 1; i < end; i++)
if ((info[i].mask & indic_plan->mask_array[PREF]) != 0)
{
/* 1. Only reorder a glyph produced by substitution during application
* of the <pref> feature. (Note that a font may shape a Ra consonant with
* the feature generally but block it in certain contexts.)
*/
/* Note: We just check that something got substituted. We don't check that
* the <pref> feature actually did it...
*
* If pref len is longer than one, then only reorder if it ligated. If
* pref len is one, only reorder if it didn't ligate with other things. */
if (_hb_glyph_info_substituted (&info[i]) &&
((pref_len == 1) ^ _hb_glyph_info_ligated_and_didnt_multiply (&info[i])))
{
/*
* 2. Try to find a target position the same way as for pre-base matra.
* If it is found, reorder pre-base consonant glyph.
*
* 3. If position is not found, reorder immediately before main
* consonant.
*/
unsigned int new_pos = base;
/* Malayalam / Tamil do not have "half" forms or explicit virama forms.
* The glyphs formed by 'half' are Chillus or ligated explicit viramas.
* We want to position matra after them.
*/
if (buffer->props.script != HB_SCRIPT_MALAYALAM && buffer->props.script != HB_SCRIPT_TAMIL)
{
while (new_pos > start &&
!(is_one_of (info[new_pos - 1], FLAG(OT_M) | HALANT_OR_COENG_FLAGS)))
new_pos--;
/* In Khmer coeng model, a H,Ra can go *after* matras. If it goes after a
* split matra, it should be reordered to *before* the left part of such matra. */
if (new_pos > start && info[new_pos - 1].indic_category() == OT_M)
{
unsigned int old_pos = i;
for (unsigned int j = base + 1; j < old_pos; j++)
if (info[j].indic_category() == OT_M)
{
new_pos--;
break;
}
}
}
if (new_pos > start && is_halant_or_coeng (info[new_pos - 1]))
{
/* -> If ZWJ or ZWNJ follow this halant, position is moved after it. */
if (new_pos < end && is_joiner (info[new_pos]))
new_pos++;
}
{
unsigned int old_pos = i;
buffer->merge_clusters (new_pos, old_pos + 1);
hb_glyph_info_t tmp = info[old_pos];
memmove (&info[new_pos + 1], &info[new_pos], (old_pos - new_pos) * sizeof (info[0]));
info[new_pos] = tmp;
if (new_pos <= base && base < old_pos)
base++;
}
}
break;
}
}
/* Apply 'init' to the Left Matra if it's a word start. */
if (info[start].indic_position () == POS_PRE_M &&
(!start ||
!(FLAG_SAFE (_hb_glyph_info_get_general_category (&info[start - 1])) &
FLAG_RANGE (HB_UNICODE_GENERAL_CATEGORY_FORMAT, HB_UNICODE_GENERAL_CATEGORY_NON_SPACING_MARK))))
info[start].mask |= indic_plan->mask_array[INIT];
/*
* Finish off the clusters and go home!
*/
if (hb_options ().uniscribe_bug_compatible)
{
switch ((hb_tag_t) plan->props.script)
{
case HB_SCRIPT_TAMIL:
case HB_SCRIPT_SINHALA:
break;
default:
/* Uniscribe merges the entire cluster... Except for Tamil & Sinhala.
* This means, half forms are submerged into the main consonants cluster.
* This is unnecessary, and makes cursor positioning harder, but that's what
* Uniscribe does. */
buffer->merge_clusters (start, end);
break;
}
}
}
static void
final_reordering (const hb_ot_shape_plan_t *plan,
hb_font_t *font HB_UNUSED,
hb_buffer_t *buffer)
{
unsigned int count = buffer->len;
if (unlikely (!count)) return;
foreach_syllable (buffer, start, end)
final_reordering_syllable (plan, buffer, start, end);
HB_BUFFER_DEALLOCATE_VAR (buffer, indic_category);
HB_BUFFER_DEALLOCATE_VAR (buffer, indic_position);
}
static void
clear_syllables (const hb_ot_shape_plan_t *plan HB_UNUSED,
hb_font_t *font HB_UNUSED,
hb_buffer_t *buffer)
{
hb_glyph_info_t *info = buffer->info;
unsigned int count = buffer->len;
for (unsigned int i = 0; i < count; i++)
info[i].syllable() = 0;
}
static bool
decompose_indic (const hb_ot_shape_normalize_context_t *c,
hb_codepoint_t ab,
hb_codepoint_t *a,
hb_codepoint_t *b)
{
switch (ab)
{
/* Don't decompose these. */
case 0x0931u : return false;
case 0x0B94u : return false;
/*
* Decompose split matras that don't have Unicode decompositions.
*/
case 0x0F77u : *a = 0x0FB2u; *b= 0x0F81u; return true;
case 0x0F79u : *a = 0x0FB3u; *b= 0x0F81u; return true;
case 0x17BEu : *a = 0x17C1u; *b= 0x17BEu; return true;
case 0x17BFu : *a = 0x17C1u; *b= 0x17BFu; return true;
case 0x17C0u : *a = 0x17C1u; *b= 0x17C0u; return true;
case 0x17C4u : *a = 0x17C1u; *b= 0x17C4u; return true;
case 0x17C5u : *a = 0x17C1u; *b= 0x17C5u; return true;
case 0x1925u : *a = 0x1920u; *b= 0x1923u; return true;
case 0x1926u : *a = 0x1920u; *b= 0x1924u; return true;
case 0x1B3Cu : *a = 0x1B42u; *b= 0x1B3Cu; return true;
case 0x1112Eu : *a = 0x11127u; *b= 0x11131u; return true;
case 0x1112Fu : *a = 0x11127u; *b= 0x11132u; return true;
#if 0
/* This one has no decomposition in Unicode, but needs no decomposition either. */
/* case 0x0AC9u : return false; */
case 0x0B57u : *a = no decomp, -> RIGHT; return true;
case 0x1C29u : *a = no decomp, -> LEFT; return true;
case 0xA9C0u : *a = no decomp, -> RIGHT; return true;
case 0x111BuF : *a = no decomp, -> ABOVE; return true;
#endif
}
if ((ab == 0x0DDAu || hb_in_range (ab, 0x0DDCu, 0x0DDEu)))
{
/*
* Sinhala split matras... Let the fun begin.
*
* These four characters have Unicode decompositions. However, Uniscribe
* decomposes them "Khmer-style", that is, it uses the character itself to
* get the second half. The first half of all four decompositions is always
* U+0DD9.
*
* Now, there are buggy fonts, namely, the widely used lklug.ttf, that are
* broken with Uniscribe. But we need to support them. As such, we only
* do the Uniscribe-style decomposition if the character is transformed into
* its "sec.half" form by the 'pstf' feature. Otherwise, we fall back to
* Unicode decomposition.
*
* Note that we can't unconditionally use Unicode decomposition. That would
* break some other fonts, that are designed to work with Uniscribe, and
* don't have positioning features for the Unicode-style decomposition.
*
* Argh...
*
* The Uniscribe behavior is now documented in the newly published Sinhala
* spec in 2012:
*
* http://www.microsoft.com/typography/OpenTypeDev/sinhala/intro.htm#shaping
*/
const indic_shape_plan_t *indic_plan = (const indic_shape_plan_t *) c->plan->data;
hb_codepoint_t glyph;
if (hb_options ().uniscribe_bug_compatible ||
(c->font->get_glyph (ab, 0, &glyph) &&
indic_plan->pstf.would_substitute (&glyph, 1, c->font->face)))
{
/* Ok, safe to use Uniscribe-style decomposition. */
*a = 0x0DD9u;
*b = ab;
return true;
}
}
return (bool) c->unicode->decompose (ab, a, b);
}
static bool
compose_indic (const hb_ot_shape_normalize_context_t *c,
hb_codepoint_t a,
hb_codepoint_t b,
hb_codepoint_t *ab)
{
/* Avoid recomposing split matras. */
if (HB_UNICODE_GENERAL_CATEGORY_IS_MARK (c->unicode->general_category (a)))
return false;
/* Composition-exclusion exceptions that we want to recompose. */
if (a == 0x09AFu && b == 0x09BCu) { *ab = 0x09DFu; return true; }
return (bool) c->unicode->compose (a, b, ab);
}
const hb_ot_complex_shaper_t _hb_ot_complex_shaper_indic =
{
"indic",
collect_features_indic,
override_features_indic,
data_create_indic,
data_destroy_indic,
NULL, /* preprocess_text */
NULL, /* postprocess_glyphs */
HB_OT_SHAPE_NORMALIZATION_MODE_COMPOSED_DIACRITICS_NO_SHORT_CIRCUIT,
decompose_indic,
compose_indic,
setup_masks_indic,
HB_OT_SHAPE_ZERO_WIDTH_MARKS_NONE,
false, /* fallback_position */
};
| ds-hwang/chromium-crosswalk | third_party/harfbuzz-ng/src/hb-ot-shape-complex-indic.cc | C++ | bsd-3-clause | 60,394 |
<!--
/*
** Copyright (c) 2012 The Khronos Group Inc.
**
** Permission is hereby granted, free of charge, to any person obtaining a
** copy of this software and/or associated documentation files (the
** "Materials"), to deal in the Materials without restriction, including
** without limitation the rights to use, copy, modify, merge, publish,
** distribute, sublicense, and/or sell copies of the Materials, and to
** permit persons to whom the Materials are furnished to do so, subject to
** the following conditions:
**
** The above copyright notice and this permission notice shall be included
** in all copies or substantial portions of the Materials.
**
** THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
** EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
** MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
** IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
** CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
** TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
** MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS.
*/
-->
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>GLSL length function test</title>
<link rel="stylesheet" href="./resources/js-test-style.css"/>
<link rel="stylesheet" href="./resources/glsl-feature-tests.css"/>
<script src="./resources/js-test-pre.js"></script>
<script src="./resources/webgl-test.js"> </script>
<script src="./resources/webgl-test-utils.js"> </script>
<script src="./resources/glsl-generator.js"> </script>
</head>
<body>
<div id="description"></div>
<div id="console"></div>
<script>
"use strict";
GLSLGenerator.runFeatureTest({
feature: "length",
args: "$(type) value",
baseArgs: "value$(field)",
testFunc: "$(func)($(type))",
fragmentTolerance: 1,
emuFuncs: [
{ type: "float",
code: [
"float $(func)_emu($(args)) {",
" return abs($(baseArgs));",
"}"].join("\n")
},
{ type: "vec2",
code: [
"float $(func)_emu($(args)) {",
" return sqrt(",
" $(baseArgsX) * $(baseArgsX) + ",
" $(baseArgsY) * $(baseArgsY));",
"}"].join("\n")
},
{ type: "vec3",
code: [
"float $(func)_emu($(args)) {",
" return sqrt(",
" $(baseArgsX) * $(baseArgsX) + ",
" $(baseArgsY) * $(baseArgsY) + ",
" $(baseArgsZ) * $(baseArgsZ));",
"}"].join("\n")
},
{ type: "vec4",
code: [
"float $(func)_emu($(args)) {",
" return sqrt(",
" $(baseArgsX) * $(baseArgsX) + ",
" $(baseArgsY) * $(baseArgsY) + ",
" $(baseArgsZ) * $(baseArgsZ) + ",
" $(baseArgsW) * $(baseArgsW));",
"}"].join("\n")
}
],
gridRes: 8,
tests: [
["$(output) = vec4(",
" $(func)($(input).x * 8.0 - 4.0) / 4.0,",
" $(func)($(input).y * 8.0 - 4.0) / 4.0,",
" 0,",
" 1);"].join("\n"),
["$(output) = vec4(",
" $(func)($(input).xy * 8.0 - 4.0) / 4.0,",
" 0, 0, 1);"].join("\n"),
["$(output) = vec4(",
" $(func)($(input).xyz * 8.0 - 4.0) / 4.0,",
" 0, 0, 1);"].join("\n"),
["$(output) = vec4(",
" $(func)($(input) * 8.0 - 4.0) / 4.0, 0, 0, 1);",
].join("\n")
]
});
var successfullyParsed = true;
</script>
</body>
</html>
| wanghongjuan/crosswalk-test-suite | webapi/tct-webgl-nonw3c-tests/webgl/khronos/glsl-function-length.html | HTML | bsd-3-clause | 3,446 |
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script src="../../../../../tools/svgweb/src/svg.js" data-path="../../../../../tools/svgweb/src"></script>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<meta name="keywords" content="W3C SVG 1.1 2nd Edition Test Suite"/>
<meta name="description" content="W3C SVG 1.1 2nd Edition SVGWeb Test Suite"/>
<title>
SVG 1.1 2nd Edition Test (svgweb): coords-trans-07-t.svg
</title>
<style type="text/css">
<!--
.bodytext { font-family:verdana, helvetica, sans-serif; font-size: 12pt; line-height: 125%; text-align: Left; margin-top: 0; margin-bottom: 0 }
.pageTitle { line-height: 150%; font-size: 20pt; font-weight : 900; margin-bottom: 20pt }
.pageSubTitle { color : blue; line-height: 100%; font-size: 24pt; font-weight : 900 }
.openChapter { color : blue; line-height: 125%; font-weight : 900 }
.openSection { color : blue; line-height: 125%; font-weight : 900 }
.info { color : black; line-height: 110%; font-size: 10pt; font-weight : 100 }
p { margin-top:0; margin-bottom:0; padding-top:0; padding-bottom:0 }
blockquote { margin-top:0; margin-bottom:0; padding-top:0; padding-bottom:0 }
.opscript { margin-left: 3%; margin-right: 3%; }
.opscript p { margin-top: 0.7em }
.navbar { background: black; color: white; font-weight: bold }
.warning { color: red; text-align: Center;}
a,a:visited { color: blue }
-->
</style>
<link rel="prev" href="coords-trans-06-t.html" />
<link rel="index" href="index.html" />
<link rel="next" href="coords-trans-08-t.html" />
<script src="../resources/testharnessreport.js"></script>
</head>
<body class="bodytext">
<div class="linkbar">
<p>Specification link: <a target="spec" href="http://www.w3.org/TR/SVG11/coords.html#EstablishingANewUserSpace">7.4 Coordinate system transformations</a></p>
<p>
<a href="coords-trans-06-t.html" rel="prev">coords-trans-06-t ←</a>
<a href="index.html" rel="index">index</a>
<a href="coords-trans-08-t.html" rel="next">→ coords-trans-08-t</a>
</p>
</div>
<div>
<br />
<p class="warning">
Tests that contain the draft-watermark are under development and may be incorrectly testing a feature.
</p>
</div>
<table align="center" border="0" cellspacing="0" cellpadding="10">
<tr>
<td align="center" colspan="3">
<table border="0" cellpadding="8">
<tr>
<td align="center" colspan="2" class="pageTitle">
<h1>coords-trans-07-t.svg</h1>
</td>
</tr>
<tr class="navbar">
<td align="center">
SVG Image
</td>
<td align="center">
PNG Image
</td>
</tr>
<tr>
<td align="right">
<!--[if IE]>
<object src="../../svg/coords-trans-07-t.svg" width="480" height="360" classid="image/svg+xml"><p style="font-size:300%;color:red">FAIL</p>
<![endif]-->
<!--[if !IE]>-->
<object data="../../svg/coords-trans-07-t.svg" width="480" height="360" type="image/svg+xml"><p style="font-size:300%;color:red">FAIL</p>
<!--<![endif]-->
</object>
</td>
<td align="left">
<img alt="raster image of coords-trans-07-t.svg" src="../../png/coords-trans-07-t.png" width="480" height="360"/>
</td>
</tr>
</table>
</td>
</tr>
</table>
<div class="opscript">
<h2 id="operatorscript">
Operator Script
</h2>
<div>
<p>
Run the test. No interaction required.
</p>
</div>
<h2 id="passcriteria">
Pass Criteria
</h2>
<div>
<p>
The rendered picture should match the reference image exactly except for variations in the labeling text - a long blue line at four o'clock and a short red line at seven o'clock below the text "translate+rotate", and, below and to the left of that, a long green line at four o'clock and a short red line at seven o'clock below the text "rotate+translate".
</p>
</div>
<h2 id="testdescription">
Test Description
</h2>
<div>
<p>
This test verifies the implementation of transforms. It tests elementary transforms
and transform nesting.
Note that for layout purposes, this test uses nesting of translation with the elementary transforms.
</p><p>
The test uses the rect element, the fill color (solid primary colors) and transforms.
</p>
</div>
</div>
<br/>
<div class="linkbar">
<p>
<a href="coords-trans-06-t.html" rel="prev">coords-trans-06-t ←</a>
<a href="index.html" rel="index">index</a>
<a href="coords-trans-08-t.html" rel="next">→ coords-trans-08-t</a>
</p>
</div>
</body>
</html>
| frivoal/presto-testo | SVG/Testsuites/W3C-1_1F2/harness/htmlSVGWeb/coords-trans-07-t.html | HTML | bsd-3-clause | 5,129 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.