repo_name
stringlengths 6
101
| path
stringlengths 4
300
| text
stringlengths 7
1.31M
|
|---|---|---|
zhoutao0712/rtn11pb1
|
release/src/router/rc/pc.h
|
#define MIN_DAY 1
#define MAX_DAY 7
#define MIN_HOUR 0
#define MAX_HOUR 23
typedef struct pc_event pc_event_s;
struct pc_event{
char e_name[32];
int start_day;
int end_day;
int start_hour;
int end_hour;
pc_event_s *next;
};
typedef struct pc pc_s;
struct pc{
int enabled;
char device[32];
char mac[18];
pc_event_s *events;
pc_s *next;
};
extern const char iptables_chk_mac[];
|
acionescu/commons
|
src/main/java/net/segoia/util/data/LfuSet.java
|
<reponame>acionescu/commons
/**
* commons - Various Java Utils
* Copyright (C) 2009 <NAME> - https://github.com/acionescu
*
* 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 net.segoia.util.data;
import java.util.Collection;
import java.util.Comparator;
import java.util.Iterator;
import java.util.Set;
import java.util.TreeMap;
public class LfuSet implements Set{
/**
*
*/
private static final long serialVersionUID = 3899301974769690116L;
private int maxSize;
private TreeMap treeMap;
public LfuSet(){
}
public LfuSet(int maxSize){
this.maxSize = maxSize;
}
public boolean add(Object arg0) {
// TODO Auto-generated method stub
return false;
}
public boolean addAll(Collection arg0) {
// TODO Auto-generated method stub
return false;
}
public void clear() {
// TODO Auto-generated method stub
}
public boolean contains(Object o) {
// TODO Auto-generated method stub
return false;
}
public boolean containsAll(Collection arg0) {
// TODO Auto-generated method stub
return false;
}
public boolean isEmpty() {
// TODO Auto-generated method stub
return false;
}
public Iterator iterator() {
// TODO Auto-generated method stub
return null;
}
public boolean remove(Object o) {
// TODO Auto-generated method stub
return false;
}
public boolean removeAll(Collection arg0) {
// TODO Auto-generated method stub
return false;
}
public boolean retainAll(Collection arg0) {
// TODO Auto-generated method stub
return false;
}
public int size() {
// TODO Auto-generated method stub
return 0;
}
public Object[] toArray() {
// TODO Auto-generated method stub
return null;
}
public Object[] toArray(Object[] arg0) {
// TODO Auto-generated method stub
return null;
}
}
final class LfuComparator implements Comparator{
public int compare(Object arg0, Object arg1) {
// TODO Auto-generated method stub
return 0;
}
}
|
Ornibyl/Windflower
|
Windflower/src/Validator.cpp
|
<gh_stars>0
#include "Validator.hpp"
#include <exception>
#include <algorithm>
#include <set>
#include "Utils/Format.hpp"
#include "Utils/Helpers.hpp"
namespace wf
{
Validator::Validator(TypeInformation& type_info, SymbolTable& symbol_table)
: type_info(type_info), current_table(&symbol_table)
{
}
bool Validator::statement_list_can_return(std::shared_ptr<StatementListNode> node)
{
for(size_t i = 0; i < node->statements.size(); i++)
{
std::shared_ptr<Node> statement = node->statements[i];
if(statement->type == Node::Type::RETURN) return true;
else if(statement->type == Node::Type::IF)
{
std::shared_ptr<IfNode> statement_as_if = std::static_pointer_cast<IfNode>(statement);
if(statement_as_if->else_case == nullptr) continue;
bool does_return = true;
for(auto& if_case : statement_as_if->if_cases)
{
does_return = does_return && statement_list_can_return(if_case.statements);
if(!does_return) break;
}
does_return = does_return && statement_list_can_return(statement_as_if->else_case);
if(does_return) return true;
}
}
return false;
}
void Validator::validate_ast(std::shared_ptr<Node> ast)
{
validate_node(ast);
}
bool Validator::validate_node(std::shared_ptr<Node> node)
{
switch(node->type)
{
case Node::Type::PROGRAM:
return validate_program_node(std::static_pointer_cast<ProgramNode>(node));
case Node::Type::MODULE:
return validate_module_node(std::static_pointer_cast<ModuleNode>(node));
case Node::Type::STATEMENT_LIST:
return validate_statement_list_node(std::static_pointer_cast<StatementListNode>(node));
case Node::Type::WHILE:
return validate_while_node(std::static_pointer_cast<WhileNode>(node));
case Node::Type::IF:
return validate_if_node(std::static_pointer_cast<IfNode>(node));
case Node::Type::TYPE_ALIAS:
return validate_type_alias_node(std::static_pointer_cast<TypeAliasNode>(node));
case Node::Type::CLASS:
return validate_class_node(std::static_pointer_cast<ClassNode>(node));
case Node::Type::VAR:
return validate_var_node(std::static_pointer_cast<VarNode>(node));
case Node::Type::EXTERN_FUNC:
return validate_extern_func_node(std::static_pointer_cast<ExternFuncNode>(node));
case Node::Type::FUNC:
return validate_func_node(std::static_pointer_cast<FuncNode>(node));
case Node::Type::RETURN:
return validate_return_node(std::static_pointer_cast<ReturnNode>(node));
case Node::Type::CONTINUE:
return validate_continue_node(std::static_pointer_cast<ContinueNode>(node));
case Node::Type::BREAK:
return validate_break_node(std::static_pointer_cast<BreakNode>(node));
case Node::Type::LAMBDA:
return validate_lambda_node(std::static_pointer_cast<LambdaNode>(node));
case Node::Type::ASSIGN:
return validate_assign_node(std::static_pointer_cast<AssignNode>(node));
case Node::Type::SYM_ACCESS:
return validate_sym_access_node(std::static_pointer_cast<SymAccessNode>(node));
case Node::Type::MEMBER_ACCESS:
return validate_member_access_node(std::static_pointer_cast<MemberAccessNode>(node));
case Node::Type::CALL:
return validate_call_node(std::static_pointer_cast<CallNode>(node));
case Node::Type::STRING:
return validate_string_node(std::static_pointer_cast<StringNode>(node));
case Node::Type::INT:
return validate_int_node(std::static_pointer_cast<IntNode>(node));
case Node::Type::FLOAT:
return validate_float_node(std::static_pointer_cast<FloatNode>(node));
case Node::Type::BOOL:
return validate_bool_node(std::static_pointer_cast<BoolNode>(node));
case Node::Type::NIL:
return validate_nil_node(std::static_pointer_cast<NilNode>(node));
case Node::Type::BINARY_OP:
return validate_binary_op_node(std::static_pointer_cast<BinaryOpNode>(node));
case Node::Type::UNARY_OP:
return validate_unary_op_node(std::static_pointer_cast<UnaryOpNode>(node));
case Node::Type::CAST:
return validate_cast_node(std::static_pointer_cast<CastNode>(node));
}
throw std::runtime_error("Compiler bug: Validator::validate_node is not fully implemented.");
}
bool Validator::validate_program_node(std::shared_ptr<ProgramNode> node)
{
bool is_success = true;
for(auto loaded_module : node->loaded_modules)
{
is_success = validate_node(loaded_module) && is_success;
}
is_success = validate_node(node->main_module) && is_success;
return is_success;
}
bool Validator::validate_module_node(std::shared_ptr<ModuleNode> node)
{
return validate_statement_list_node(node->statements);
}
bool Validator::validate_statement_list_node(std::shared_ptr<StatementListNode> node)
{
bool is_success = true;
for(auto statement : node->statements)
{
is_success = validate_node(statement) && is_success;
}
return is_success;
}
bool Validator::validate_while_node(std::shared_ptr<WhileNode> node)
{
bool is_success = true;
bool condition_success = validate_node(node->condition);
bool saved_in_loop = in_loop;
in_loop = true;
node->table_index = current_table->create_sub_table();
current_table = current_table->get_sub_table(node->table_index);
uint32_t saved_loop_variable_top = loop_variable_top;
loop_variable_top = current_table->symbols.size();
if(condition_success && node->condition->evaluated_type != TYPE_BOOL)
{
errors.push_error(node->position, "The condition of an while loop must evaluate to a bool value.");
is_success = false;
}
loop_variable_top = saved_loop_variable_top;
is_success = validate_node(node->statements) && is_success;
current_table = current_table->get_parent();
in_loop = saved_in_loop;
return is_success;
}
bool Validator::validate_if_node(std::shared_ptr<IfNode> node)
{
bool is_success = true;
for(auto& if_case : node->if_cases)
{
bool condition_success = validate_node(if_case.condition);
is_success = condition_success && is_success;
if_case.table_index = current_table->create_sub_table();
current_table = current_table->get_sub_table(if_case.table_index);
if(condition_success && if_case.condition->evaluated_type != TYPE_BOOL)
{
errors.push_error(if_case.position, "The condition of an if case must evaluate to a bool value.");
is_success = false;
}
is_success = validate_node(if_case.statements) && is_success;
current_table = current_table->get_parent();
}
if(node->else_case != nullptr)
{
node->else_table_index = current_table->create_sub_table();
current_table = current_table->get_sub_table(node->else_table_index);
is_success = validate_node(node->else_case) && is_success;
current_table = current_table->get_parent();
}
return is_success;
}
bool Validator::validate_type_alias_node(std::shared_ptr<TypeAliasNode> node)
{
if(type_info.string_to_type_id(node->alias) != TYPE_UNDEFINED)
{
errors.push_error(node->position, "Cannot alias a type that already exists.");
return false;
}
if(current_table->is_symbol_defined(node->alias))
{
errors.push_error(node->position,
format::format("{0} is already defined.", node->alias));
return false;
}
TypeID aliased_type = type_info.string_to_type_id(node->aliased_type_string);
if(aliased_type == TYPE_UNDEFINED)
{
errors.push_error(node->position, format::format("The type being aliased ({0}) is not defined.",
node->aliased_type_string));
return false;
}
auto it = type_info.type_aliases.find(type_info.type_infos.at(aliased_type).name);
if(it != type_info.type_aliases.end())
{
aliased_type = it->second;
}
type_info.type_aliases[node->alias] = aliased_type;
return true;
}
bool Validator::validate_class_node(std::shared_ptr<ClassNode> node)
{
if(current_table->is_symbol_defined(node->name) || type_info.string_to_type_id(node->name) != TYPE_UNDEFINED)
{
errors.push_error(node->position, format::format("'{0}' is already defined.", node->name));
return false;
}
node->class_type_id = type_info.type_infos.size();
TypeInfo& class_type = type_info.type_infos[node->class_type_id];
class_type.name = "class " + node->name;
ClassTypeInfo& class_type_info = type_info.class_type_infos[node->class_type_id];
class_type_info.class_name = node->name;
TypeID instance_type_id = type_info.type_infos.size();
TypeInfo& instance_type_info = type_info.type_infos[instance_type_id];
instance_type_info.name = node->name;
type_info.instance_types.insert(instance_type_id);
Symbol& symbol = current_table->create_symbol(node->name);
symbol.symbol_type = SymbolType::CLASS;
symbol.is_readonly = true;
symbol.type_id = node->class_type_id;
ClassSymbolInfo& class_symbol_info = current_table->class_symbol_info[node->name];
auto[symbol_new, method_symbol_new] = class_symbol_info.create_static_method("new");
symbol_new.is_private = false;
symbol_new.is_readonly = true;
symbol_new.symbol_type = SymbolType::FUNCTION;
symbol_new.type_id = type_info.define_function_type(instance_type_id, {});
node->static_new_table_index = current_table->create_sub_root();
current_table = current_table->get_sub_table(node->static_new_table_index);
current_table->make_upvalue(node->name);
for(auto property : node->properties)
{
if(class_symbol_info.is_member_defined(property->name)
|| type_info.string_to_type_id(property->name) != TYPE_UNDEFINED)
{
errors.push_error(property->position,
format::format("{0} is already defined in class '{1}'.", property->name, node->name));
return false;
}
ClassMember& member = class_symbol_info.create_instance_property(property->name);
member.type_id = type_info.string_to_type_id(property->type_annotation);
if(member.type_id == TYPE_UNDEFINED)
{
errors.push_error(node->position, format::format("Type '{0}' is not defined.", property->type_annotation));
return false;
}
member.is_readonly = property->is_readonly;
member.symbol_type = SymbolType::VARIABLE;
if(property->initial_value != nullptr)
{
if(!validate_node(property->initial_value)) return false;
if(property->initial_value->evaluated_type != member.type_id
&& member.type_id != TYPE_ANY && !(property->initial_value->evaluated_type == TYPE_INT
&& member.type_id == TYPE_FLOAT))
{
errors.push_error(node->position,
format::format("Cannot assign a value of type '{0}' to a property of type '{1}'.",
type_info.prettify_type(property->initial_value->evaluated_type), type_info.prettify_type(member.type_id)));
return false;
}
}
else if(member.is_readonly)
{
errors.push_error(node->position,
"A property marked as const must be assigned a value on declaration.");
return false;
}
else
{
switch(member.type_id)
{
case TYPE_ANY:
case TYPE_INT:
case TYPE_FLOAT:
case TYPE_STRING:
case TYPE_BOOL:
break;
default:
errors.push_error(property->position,
format::format("A variable of type '{0}' must be assigned a value on declaration.",
type_info.prettify_type(member.type_id)));
return false;
}
}
}
current_table = current_table->get_parent();
return true;
}
bool Validator::validate_var_node(std::shared_ptr<VarNode> node)
{
if(current_table->is_symbol_defined(node->name) || type_info.string_to_type_id(node->name) != TYPE_UNDEFINED)
{
errors.push_error(node->position,
format::format("{0} is already defined.", node->name));
return false;
}
Symbol& symbol = current_table->create_symbol(node->name);
symbol.type_id = type_info.string_to_type_id(node->type_annotation);
if(symbol.type_id == TYPE_UNDEFINED)
{
errors.push_error(node->position, format::format("Type '{0}' is not defined.", node->type_annotation));
return false;
}
symbol.is_readonly = node->is_readonly;
symbol.symbol_type = SymbolType::VARIABLE;
if(node->initial_value != nullptr)
{
if(!validate_node(node->initial_value)) return false;
if(node->initial_value->evaluated_type != symbol.type_id
&& symbol.type_id != TYPE_ANY && !(node->initial_value->evaluated_type == TYPE_INT
&& symbol.type_id == TYPE_FLOAT))
{
errors.push_error(node->position,
format::format("Cannot assign a value of type '{0}' to a variable of type '{1}'.",
type_info.prettify_type(node->initial_value->evaluated_type), type_info.prettify_type(symbol.type_id)));
return false;
}
}
else if(symbol.is_readonly)
{
errors.push_error(node->position,
"A variable marked as const must be assigned a value on declaration.");
return false;
}
else
{
switch(symbol.type_id)
{
case TYPE_ANY:
case TYPE_INT:
case TYPE_FLOAT:
case TYPE_STRING:
case TYPE_BOOL:
break;
default:
errors.push_error(node->position,
format::format("A variable of type '{0}' must be assigned a value on declaration.",
type_info.prettify_type(symbol.type_id)));
return false;
}
}
return true;
}
bool Validator::validate_extern_func_node(std::shared_ptr<ExternFuncNode> node)
{
if(current_table->is_symbol_defined(node->name) || type_info.string_to_type_id(node->name) != TYPE_UNDEFINED)
{
errors.push_error(node->position,
format::format("'{0}' is already defined.", node->name));
return false;
}
std::vector<FuncSymbolInfo::ParamInfo> param_infos;
std::vector<TypeID> parameter_types(node->parameters.size());
for(size_t i = 0; i < parameter_types.size(); i++)
{
const FuncParamInfo& parameter = node->parameters[i];
parameter_types[i] = type_info.string_to_type_id(parameter.type_annotation);
if(parameter_types[i] == TYPE_UNDEFINED)
{
errors.push_error(node->position, format::format("Type '{0}' is not defined.", parameter.type_annotation));
return false;
}
FuncSymbolInfo::ParamInfo& param_info = param_infos.emplace_back();
param_info.label = parameter.label;
param_info.name = parameter.name;
}
TypeID return_type = type_info.string_to_type_id(node->return_type_annotation);
if(return_type == TYPE_UNDEFINED)
{
errors.push_error(node->position, format::format("Type '{0}' is not defined.", node->return_type_annotation));
return false;
}
auto[symbol, func_symbol] = current_table->create_func_symbol(node->name);
symbol.is_readonly = true;
symbol.symbol_type = SymbolType::FUNCTION;
func_symbol.parameters = param_infos;
symbol.type_id = type_info.define_function_type(return_type, parameter_types);
return true;
}
bool Validator::validate_func_node(std::shared_ptr<FuncNode> node)
{
if(current_table->is_symbol_defined(node->name) || type_info.string_to_type_id(node->name) != TYPE_UNDEFINED)
{
errors.push_error(node->position,
format::format("'{0}' is already defined.", node->name));
return false;
}
node->table_index = current_table->create_sub_root();
current_table = current_table->get_sub_table(node->table_index);
bool is_success = true;
std::vector<FuncSymbolInfo::ParamInfo> param_infos;
std::vector<TypeID> parameter_types(node->parameters.size());
for(size_t i = 0; i < parameter_types.size(); i++)
{
const FuncParamInfo& parameter = node->parameters[i];
parameter_types[i] = type_info.string_to_type_id(parameter.type_annotation);
if(parameter_types[i] == TYPE_UNDEFINED)
{
errors.push_error(node->position, format::format("Type '{0}' is not defined.", parameter.type_annotation));
is_success = false;
continue;
}
bool symbol_is_defined = current_table->is_symbol_defined(parameter.name);
if(symbol_is_defined)
{
errors.push_error(node->position,
format::format("'{0}' is already defined.", parameter.name));
is_success = false;
}
else
{
Symbol& param_symbol = current_table->create_symbol(parameter.name);
param_symbol.is_readonly = false;
param_symbol.type_id = parameter_types[i];
param_symbol.symbol_type = SymbolType::VARIABLE;
}
FuncSymbolInfo::ParamInfo& param_info = param_infos.emplace_back();
param_info.label = parameter.label;
param_info.name = parameter.name;
}
TypeID return_type = type_info.string_to_type_id(node->return_type_annotation);
if(return_type == TYPE_UNDEFINED)
{
errors.push_error(node->position, format::format("Type '{0}' is not defined.", node->return_type_annotation));
return false;
}
auto[symbol, func_symbol] = current_table->get_parent()->create_func_symbol(node->name);
symbol.is_readonly = true;
symbol.symbol_type = SymbolType::FUNCTION;
func_symbol.parameters = param_infos;
symbol.type_id = type_info.define_function_type(return_type, parameter_types);
if(!is_success)
{
current_table = current_table->get_parent();
return false;
}
bool saved_in_function = in_function;
TypeID saved_function_return_type = function_return_type;
bool saved_in_loop = in_loop;
in_loop = false;
function_return_type = return_type;
in_function = true;
if(!validate_node(node->statements))
{
current_table = current_table->get_parent();
in_function = saved_in_function;
function_return_type = saved_function_return_type;
in_loop = saved_in_loop;
return false;
}
current_table = current_table->get_parent();
in_function = saved_in_function;
function_return_type = saved_function_return_type;
in_loop = saved_in_loop;
if(return_type != TYPE_VOID && !statement_list_can_return(node->statements))
{
errors.push_error(node->position, "A non-void function must return on all paths.");
return false;
}
return true;
}
bool Validator::validate_return_node(std::shared_ptr<ReturnNode> node)
{
if(!in_function)
{
errors.push_error(node->position, "Cannot return outside of a function.");
return false;
}
if(node->value == nullptr)
{
if(function_return_type != TYPE_VOID)
{
errors.push_error(node->position, "A value must be returned inside of a non-void function.");
return false;
}
return false;
}
if(function_return_type == TYPE_VOID)
{
errors.push_error(node->position, "A value cannot be returned inside of a void function.");
return false;
}
if(!validate_node(node->value)) return false;
if(node->value->evaluated_type != function_return_type
&& function_return_type != TYPE_ANY && !(node->value->evaluated_type == TYPE_INT
&& function_return_type == TYPE_FLOAT))
{
errors.push_error(node->position,
format::format("Cannot return a value of type '{0}' with a function of return type '{1}'.",
type_info.prettify_type(node->value->evaluated_type), type_info.prettify_type(function_return_type)));
return false;
}
return true;
}
bool Validator::validate_continue_node(std::shared_ptr<ContinueNode> node)
{
if(!in_loop)
{
errors.push_error(node->position, "Cannot continue outside of a loop.");
return false;
}
node->pop_count = current_table->symbols.size() - loop_variable_top;
return true;
}
bool Validator::validate_break_node(std::shared_ptr<BreakNode> node)
{
if(!in_loop)
{
errors.push_error(node->position, "Cannot break outside of a loop.");
return false;
}
node->pop_count = current_table->symbols.size() - loop_variable_top;
return true;
}
bool Validator::validate_lambda_node(std::shared_ptr<LambdaNode> node)
{
node->table_index = current_table->create_sub_root();
current_table = current_table->get_sub_table(node->table_index);
bool is_success = true;
std::vector<TypeID> parameter_types(node->parameters.size());
for(size_t i = 0; i < parameter_types.size(); i++)
{
const FuncParamInfo& parameter = node->parameters[i];
parameter_types[i] = type_info.string_to_type_id(parameter.type_annotation);
if(parameter_types[i] == TYPE_UNDEFINED)
{
errors.push_error(node->position, format::format("Type '{0}' is not defined.", parameter.type_annotation));
is_success = false;
continue;
}
bool symbol_is_defined = current_table->is_symbol_defined(parameter.name);
if(symbol_is_defined)
{
errors.push_error(node->position,
format::format("'{0}' is already defined.", parameter.name));
is_success = false;
}
else
{
Symbol& param_symbol = current_table->create_symbol(parameter.name);
param_symbol.is_readonly = false;
param_symbol.type_id = parameter_types[i];
param_symbol.symbol_type = SymbolType::VARIABLE;
}
}
TypeID return_type = type_info.string_to_type_id(node->return_type_annotation);
if(return_type == TYPE_UNDEFINED)
{
errors.push_error(node->position, format::format("Type '{0}' is not defined.", node->return_type_annotation));
return false;
}
node->evaluated_type = type_info.define_function_type(return_type, parameter_types);
if(!is_success)
{
current_table = current_table->get_parent();
return false;
}
bool saved_in_function = in_function;
TypeID saved_function_return_type = function_return_type;
function_return_type = return_type;
in_function = true;
if(!validate_node(node->statements))
{
current_table = current_table->get_parent();
in_function = saved_in_function;
function_return_type = saved_function_return_type;
return false;
}
current_table = current_table->get_parent();
in_function = saved_in_function;
function_return_type = saved_function_return_type;
if(return_type != TYPE_VOID && !statement_list_can_return(node->statements))
{
errors.push_error(node->position, "A non-void function must return on all paths.");
return false;
}
return true;
}
bool Validator::validate_assign_node(std::shared_ptr<AssignNode> node)
{
if(node->assignee->type == Node::Type::MEMBER_ACCESS)
{
std::shared_ptr<MemberAccessNode> assignee = std::static_pointer_cast<MemberAccessNode>(node->assignee);
if(!validate_node(assignee->base)) return false;
if(type_info.is_class_type(assignee->base->evaluated_type))
{
ClassTypeInfo& class_type_info = type_info.class_type_infos.at(assignee->base->evaluated_type);
ClassSymbolInfo& class_symbol = current_table->get_class(class_type_info.class_name);
if(class_symbol.static_member_infos.find(assignee->member_name) == class_symbol.static_member_infos.end())
{
errors.push_error(assignee->position,
format::format("'{0}' is not defined on class '{1}'.", assignee->member_name, class_type_info.class_name));
return false;
}
ClassMember& member = class_symbol.static_member_infos.at(assignee->member_name);
if(member.is_private)
{
errors.push_error(assignee->position,
format::format("'{0}' on class '{1}' is private and is not accessible here.", assignee->member_name, class_type_info.class_name));
return false;
}
if(member.symbol_type != SymbolType::VARIABLE || member.is_readonly)
{
errors.push_error(node->position, "Can only assign to non-const properties.");
return false;
}
if(!validate_node(node->new_value)) return false;
if(node->new_value->evaluated_type != member.type_id
&& member.type_id != TYPE_ANY && !(node->new_value->evaluated_type == TYPE_INT
&& member.type_id == TYPE_FLOAT))
{
errors.push_error(node->position,
format::format("Cannot assign a value of type '{0}' to a variable of type '{1}'.",
type_info.prettify_type(node->new_value->evaluated_type), type_info.prettify_type(member.type_id)));
return false;
}
node->evaluated_type = member.type_id;
return true;
}
else if(type_info.is_instance_type(assignee->base->evaluated_type))
{
const std::string& type_name = type_info.type_infos.at(assignee->base->evaluated_type).name;
ClassSymbolInfo& class_symbol = current_table->get_class(type_name);
if(class_symbol.instance_member_infos.find(assignee->member_name) == class_symbol.instance_member_infos.end())
{
errors.push_error(assignee->position,
format::format("'{0}' is not defined on class '{1}'.", assignee->member_name, type_name));
return false;
}
ClassMember& member = class_symbol.instance_member_infos.at(assignee->member_name);
if(member.is_private)
{
errors.push_error(assignee->position,
format::format("'{0}' on class '{1}' is private and is not accessible here.", assignee->member_name, type_name));
return false;
}
if(member.symbol_type != SymbolType::VARIABLE || member.is_readonly)
{
errors.push_error(node->position, "Can only assign to non-const properties.");
return false;
}
if(!validate_node(node->new_value)) return false;
if(node->new_value->evaluated_type != member.type_id
&& member.type_id != TYPE_ANY && !(node->new_value->evaluated_type == TYPE_INT
&& member.type_id == TYPE_FLOAT))
{
errors.push_error(node->position,
format::format("Cannot assign a value of type '{0}' to a variable of type '{1}'.",
type_info.prettify_type(node->new_value->evaluated_type), type_info.prettify_type(member.type_id)));
return false;
}
node->evaluated_type = member.type_id;
return true;
}
errors.push_error(assignee->position, format::format("Cannot access a member with a value of type '{0}'.",
type_info.prettify_type(assignee->base->evaluated_type)));
return false;
}
std::shared_ptr<SymAccessNode> assignee = std::static_pointer_cast<SymAccessNode>(node->assignee);
if(!current_table->is_symbol_defined(assignee->sym_name))
{
errors.push_error(node->position,
format::format("'{0}' is not defined when referenced here.", assignee->sym_name));
return false;
}
if(!current_table->is_symbol_defined_in_frame(assignee->sym_name)
&& !current_table->upvalue_is_captured(assignee->sym_name))
{
current_table->make_upvalue(assignee->sym_name);
}
Symbol& symbol = current_table->get_symbol(assignee->sym_name);
if(symbol.symbol_type != SymbolType::VARIABLE || symbol.is_readonly)
{
errors.push_error(node->position, "Can only assign to non-const variables.");
return false;
}
if(!validate_node(node->new_value)) return false;
if(node->new_value->evaluated_type != symbol.type_id
&& symbol.type_id != TYPE_ANY && !(node->new_value->evaluated_type == TYPE_INT
&& symbol.type_id == TYPE_FLOAT))
{
errors.push_error(node->position,
format::format("Cannot assign a value of type '{0}' to a variable of type '{1}'.",
type_info.prettify_type(node->new_value->evaluated_type), type_info.prettify_type(symbol.type_id)));
return false;
}
node->evaluated_type = symbol.type_id;
return true;
}
bool Validator::validate_sym_access_node(std::shared_ptr<SymAccessNode> node)
{
if(type_info.string_to_type_id(node->sym_name) != TYPE_UNDEFINED && !current_table->is_symbol_defined(node->sym_name))
{
errors.push_error(node->position,
format::format("'{0}' is a type and cannot be used here.", node->sym_name));
return false;
}
else if(!current_table->is_symbol_defined(node->sym_name))
{
errors.push_error(node->position,
format::format("'{0}' is not defined when referenced here.", node->sym_name));
return false;
}
if(!current_table->is_symbol_defined_in_frame(node->sym_name)
&& !current_table->upvalue_is_captured(node->sym_name))
{
current_table->make_upvalue(node->sym_name);
}
Symbol& symbol = current_table->get_symbol(node->sym_name);
node->evaluated_type = symbol.type_id;
return true;
}
bool Validator::validate_member_access_node(std::shared_ptr<MemberAccessNode> node)
{
if(!validate_node(node->base)) return false;
if(type_info.is_class_type(node->base->evaluated_type))
{
ClassTypeInfo& class_type_info = type_info.class_type_infos.at(node->base->evaluated_type);
ClassSymbolInfo& class_symbol = current_table->get_class(class_type_info.class_name);
if(class_symbol.static_member_infos.find(node->member_name) == class_symbol.static_member_infos.end())
{
errors.push_error(node->position,
format::format("'{0}' is not defined on class '{1}'.", node->member_name, class_type_info.class_name));
return false;
}
ClassMember& member = class_symbol.static_member_infos.at(node->member_name);
if(member.is_private)
{
errors.push_error(node->position,
format::format("'{0}' on class '{1}' is private and is not accessible here.", node->member_name, class_type_info.class_name));
return false;
}
node->evaluated_type = member.type_id;
return true;
}
else if(type_info.is_instance_type(node->base->evaluated_type))
{
const std::string& type_name = type_info.type_infos.at(node->base->evaluated_type).name;
ClassSymbolInfo& class_symbol = current_table->get_class(type_name);
if(class_symbol.instance_member_infos.find(node->member_name) == class_symbol.instance_member_infos.end())
{
errors.push_error(node->position,
format::format("'{0}' is not defined on class '{1}'.", node->member_name, type_name));
return false;
}
ClassMember& member = class_symbol.instance_member_infos.at(node->member_name);
if(member.is_private)
{
errors.push_error(node->position,
format::format("'{0}' on class '{1}' is private and is not accessible here.", node->member_name, type_name));
return false;
}
node->evaluated_type = member.type_id;
return true;
}
errors.push_error(node->position, format::format("Cannot access a member with a value of type '{0}'.",
type_info.prettify_type(node->base->evaluated_type)));
return false;
}
bool Validator::validate_call_node(std::shared_ptr<CallNode> node)
{
if(node->callee->type == Node::Type::SYM_ACCESS)
{
std::shared_ptr<SymAccessNode> callee = std::static_pointer_cast<SymAccessNode>(node->callee);
if(type_info.string_to_type_id(callee->sym_name) != TYPE_UNDEFINED
&& !current_table->is_symbol_defined(callee->sym_name))
{
errors.push_error(node->position,
format::format("'{0}' is a type and cannot be used here.", callee->sym_name));
return false;
}
else if(!current_table->is_symbol_defined(callee->sym_name))
{
errors.push_error(callee->position,
format::format("'{0}' is not defined when referenced here.", callee->sym_name));
return false;
}
if(!current_table->is_symbol_defined_in_frame(callee->sym_name)
&& !current_table->upvalue_is_captured(callee->sym_name))
{
current_table->make_upvalue(callee->sym_name);
}
Symbol& symbol = current_table->get_symbol(callee->sym_name);
if(symbol.symbol_type == SymbolType::FUNCTION)
{
FuncSymbolInfo& info = current_table->get_func_symbol(callee->sym_name);
TypeID func_type_id = symbol.type_id;
FuncTypeInfo& func_type_info = type_info.func_type_infos.at(func_type_id);
if(info.parameters.size() != node->arguments.size())
{
errors.push_error(node->position,
format::format("Function being called expected {0} {1}, but {2} {3} provided",
info.parameters.size(), info.parameters.size() == 1? "argument" : "arguments",
node->arguments.size(), node->arguments.size() == 1? "was" : "were"));
return false;
}
for(size_t i = 0; i < info.parameters.size(); i++)
{
if(!validate_node(node->arguments[i].value)) return false;
if(info.parameters[i].label == "_")
{
if(node->arguments[i].label != "")
{
errors.push_error(node->arguments[i].position,
"An argument label cannot be used here as the called function does not define one at this argument position.");
return false;
}
}
else if(info.parameters[i].label != node->arguments[i].label)
{
errors.push_error(node->arguments[i].position,
format::format("Argument label '{0}' does not match the expected label '{1}'.",
node->arguments[i].label, info.parameters[i].label));
return false;
}
if(func_type_info.parameter_types[i] != node->arguments[i].value->evaluated_type
&& func_type_info.parameter_types[i] != TYPE_ANY
&& !(node->arguments[i].value->evaluated_type == TYPE_INT
&& func_type_info.parameter_types[i] == TYPE_FLOAT))
{
errors.push_error(node->arguments[i].position,
format::format("Expected an argument of type '{0}', but the type provided is '{1}'.",
type_info.prettify_type(func_type_info.parameter_types[i]),
type_info.prettify_type(node->arguments[i].value->evaluated_type)));
return false;
}
}
node->evaluated_type = func_type_info.return_type;
return true;
}
}
if(!validate_node(node->callee)) return false;
if(!type_info.is_function_type(node->callee->evaluated_type))
{
errors.push_error(node->callee->position,
format::format("Only a value that is a function type can be called. Type provided: '{0}'.",
type_info.prettify_type(node->callee->evaluated_type)));
return false;
}
FuncTypeInfo& func_type_info = type_info.func_type_infos.at(node->callee->evaluated_type);
if(func_type_info.parameter_types.size() != node->arguments.size())
{
errors.push_error(node->position,
format::format("Function being called expected {0} {1}, but {2} {3} provided",
func_type_info.parameter_types.size(), func_type_info.parameter_types.size() == 1? "argument" : "arguments",
node->arguments.size(), node->arguments.size() == 1? "was" : "were"));
return false;
}
for(size_t i = 0; i < func_type_info.parameter_types.size(); i++)
{
if(!validate_node(node->arguments[i].value)) return false;
if(node->arguments[i].label != "")
{
errors.push_error(node->arguments[i].position, "Argument labels cannot be used when calling a function reference.");
return false;
}
if(func_type_info.parameter_types[i] != node->arguments[i].value->evaluated_type
&& func_type_info.parameter_types[i] != TYPE_ANY
&& !(node->arguments[i].value->evaluated_type == TYPE_INT
&& func_type_info.parameter_types[i] == TYPE_FLOAT))
{
errors.push_error(node->arguments[i].position,
format::format("Expected an argument of type '{0}', but the type provided is '{1}'.",
type_info.prettify_type(func_type_info.parameter_types[i]),
type_info.prettify_type(node->arguments[i].value->evaluated_type)));
return false;
}
}
node->evaluated_type = func_type_info.return_type;
return true;
}
bool Validator::validate_string_node(std::shared_ptr<StringNode> node)
{
node->evaluated_type = TYPE_STRING;
return true;
}
bool Validator::validate_int_node(std::shared_ptr<IntNode> node)
{
node->evaluated_type = TYPE_INT;
return true;
}
bool Validator::validate_float_node(std::shared_ptr<FloatNode> node)
{
node->evaluated_type = TYPE_FLOAT;
return true;
}
bool Validator::validate_bool_node(std::shared_ptr<BoolNode> node)
{
node->evaluated_type = TYPE_BOOL;
return true;
}
bool Validator::validate_nil_node(std::shared_ptr<NilNode> node)
{
node->evaluated_type = TYPE_NIL;
return true;
}
bool Validator::validate_binary_op_node(std::shared_ptr<BinaryOpNode> node)
{
if(!validate_node(node->left_operand)) return false;
if(!validate_node(node->right_operand)) return false;
switch(node->operation)
{
case BinaryOpNode::OpType::ADD:
if(node->left_operand->evaluated_type == TYPE_STRING && node->right_operand->evaluated_type == TYPE_STRING)
{
node->evaluated_type = TYPE_STRING;
node->operand_promotion_type = TYPE_STRING;
break;
}
case BinaryOpNode::OpType::SUB:
case BinaryOpNode::OpType::MUL:
case BinaryOpNode::OpType::DIV:
case BinaryOpNode::OpType::MOD:
if((node->left_operand->evaluated_type == TYPE_FLOAT && node->right_operand->evaluated_type == TYPE_FLOAT)
||(node->left_operand->evaluated_type == TYPE_FLOAT && node->right_operand->evaluated_type == TYPE_INT)
|| (node->left_operand->evaluated_type == TYPE_INT && node->right_operand->evaluated_type == TYPE_FLOAT))
{
node->evaluated_type = TYPE_FLOAT;
node->operand_promotion_type = TYPE_FLOAT;
}
else if(node->left_operand->evaluated_type == TYPE_INT && node->right_operand->evaluated_type == TYPE_INT)
{
node->evaluated_type = TYPE_INT;
node->operand_promotion_type = TYPE_INT;
}
else
{
errors.push_error(node->position,
format::format("An arithmetic operation can only be performed on two numeric types. Types provided: '{0}' and '{1}'.",
type_info.prettify_type(node->left_operand->evaluated_type),
type_info.prettify_type(node->right_operand->evaluated_type)));
return false;
}
break;
case BinaryOpNode::OpType::EQ:
case BinaryOpNode::OpType::NEQ:
node->evaluated_type = TYPE_BOOL;
if((node->left_operand->evaluated_type == TYPE_FLOAT && node->right_operand->evaluated_type == TYPE_FLOAT)
|| (node->left_operand->evaluated_type == TYPE_FLOAT && node->right_operand->evaluated_type == TYPE_INT)
|| (node->left_operand->evaluated_type == TYPE_INT && node->right_operand->evaluated_type == TYPE_FLOAT))
{
node->operand_promotion_type = TYPE_FLOAT;
}
else if((node->left_operand->evaluated_type == TYPE_ANY && node->right_operand->evaluated_type == TYPE_NIL)
|| (node->left_operand->evaluated_type == TYPE_NIL && node->right_operand->evaluated_type == TYPE_ANY))
{
// TODO: Once optionals are added, comparisons between any and nil should be removed
node->operand_promotion_type = TYPE_NIL;
}
else if(node->left_operand->evaluated_type == TYPE_INT && node->right_operand->evaluated_type == TYPE_INT)
{
node->operand_promotion_type = TYPE_INT;
}
else if(node->left_operand->evaluated_type == TYPE_STRING && node->right_operand->evaluated_type == TYPE_STRING)
{
node->operand_promotion_type = TYPE_STRING;
}
else if(node->left_operand->evaluated_type == TYPE_BOOL && node->right_operand->evaluated_type == TYPE_BOOL)
{
node->operand_promotion_type = TYPE_BOOL;
}
else
{
errors.push_error(node->position,
format::format("Cannot compare for equality with types '{0}' and '{1}'.",
type_info.prettify_type(node->left_operand->evaluated_type),
type_info.prettify_type(node->right_operand->evaluated_type)));
return false;
}
break;
case BinaryOpNode::OpType::LT:
case BinaryOpNode::OpType::GT:
case BinaryOpNode::OpType::LTE:
case BinaryOpNode::OpType::GTE:
node->evaluated_type = TYPE_BOOL;
if((node->left_operand->evaluated_type == TYPE_FLOAT && node->right_operand->evaluated_type == TYPE_FLOAT)
|| (node->left_operand->evaluated_type == TYPE_FLOAT && node->right_operand->evaluated_type == TYPE_INT)
|| (node->left_operand->evaluated_type == TYPE_INT && node->right_operand->evaluated_type == TYPE_FLOAT))
{
node->operand_promotion_type = TYPE_FLOAT;
}
else if(node->left_operand->evaluated_type == TYPE_INT && node->right_operand->evaluated_type == TYPE_INT)
{
node->operand_promotion_type = TYPE_INT;
}
else
{
errors.push_error(node->position,
format::format("A comparison operation can only be performed on two numeric types. Types provided: '{0}' and '{1}'.",
type_info.prettify_type(node->left_operand->evaluated_type),
type_info.prettify_type(node->right_operand->evaluated_type)));
return false;
}
break;
case BinaryOpNode::OpType::BIT_AND:
case BinaryOpNode::OpType::BIT_OR:
case BinaryOpNode::OpType::BIT_XOR:
if(node->left_operand->evaluated_type == TYPE_INT && node->right_operand->evaluated_type == TYPE_INT)
{
node->evaluated_type = TYPE_INT;
node->operand_promotion_type = TYPE_INT;
}
else
{
errors.push_error(node->position,
format::format("Bitwise operations can only be performed on two ints. Types provided: '{0}' and '{1}'.",
type_info.prettify_type(node->left_operand->evaluated_type),
type_info.prettify_type(node->right_operand->evaluated_type)));
return false;
}
break;
case BinaryOpNode::OpType::AND:
case BinaryOpNode::OpType::OR:
if(node->left_operand->evaluated_type == TYPE_BOOL && node->right_operand->evaluated_type == TYPE_BOOL)
{
node->evaluated_type = TYPE_BOOL;
node->operand_promotion_type = TYPE_BOOL;
}
else
{
errors.push_error(node->position,
format::format("Logical operations can only be performed on two bools. Types provided: '{0}' and '{1}'.",
type_info.prettify_type(node->left_operand->evaluated_type),
type_info.prettify_type(node->right_operand->evaluated_type)));
return false;
}
break;
default:
throw std::runtime_error("Compiler bug: Validator::validate_binary_op_node is not fully implemented.");
}
return true;
}
bool Validator::validate_unary_op_node(std::shared_ptr<UnaryOpNode> node)
{
if(!validate_node(node->operand)) return false;
switch(node->operation)
{
case UnaryOpNode::OpType::NOT:
if(node->operand->evaluated_type != TYPE_BOOL)
{
node->evaluated_type = TYPE_BOOL;
}
else
{
errors.push_error(node->position,
format::format("Only bools can be used in a logical not operation, but a value of type '{0}' was used.",
type_info.prettify_type(node->operand->evaluated_type)));
return false;
}
break;
case UnaryOpNode::OpType::BIT_NOT:
if(node->operand->evaluated_type != TYPE_INT)
{
node->evaluated_type = TYPE_INT;
}
else
{
errors.push_error(node->position,
format::format("Only ints can be used in a bitwise not operation, but a value of type '{0}' was used.",
type_info.prettify_type(node->operand->evaluated_type)));
return false;
}
break;
case UnaryOpNode::OpType::NEGATION:
if(node->operand->evaluated_type != TYPE_INT || node->operand->evaluated_type != TYPE_FLOAT)
{
node->evaluated_type = node->operand->evaluated_type;
}
else
{
errors.push_error(node->position,
format::format("Only numeric types can be negated, but a value of type '{0}' was used.",
type_info.prettify_type(node->operand->evaluated_type)));
return false;
}
break;
default:
throw std::runtime_error("Compiler bug: Validator::validate_unary_op_node is not fully implemented.");
}
return true;
}
bool Validator::validate_cast_node(std::shared_ptr<CastNode> node)
{
static std::set<std::pair<TypeID, TypeID>> valid_type_conversions = {
{ TYPE_INT, TYPE_FLOAT },
{ TYPE_FLOAT, TYPE_INT }
};
if(!validate_node(node->operand)) return false;
TypeID cast_type = type_info.string_to_type_id(node->cast_type_string);
if(cast_type == TYPE_UNDEFINED)
{
errors.push_error(node->position, format::format("Type '{0}' is undefined.", node->cast_type_string));
return false;
}
if(node->operand->evaluated_type != cast_type
&& node->operand->evaluated_type != TYPE_ANY
&& valid_type_conversions.find({node->evaluated_type, cast_type}) == valid_type_conversions.end())
{
errors.push_error(node->position, format::format("Cannot cast a value of type '{0}' to '{1}.",
type_info.prettify_type(node->evaluated_type), type_info.prettify_type(cast_type)));
return false;
}
node->evaluated_type = cast_type;
return true;
}
} // namespace wf
|
wieker/spring-boot-netty
|
src/main/java/org/kgusarov/integration/spring/netty/support/invoke/GeneratedClassLoader.java
|
package org.kgusarov.integration.spring.netty.support.invoke;
import java.lang.invoke.MethodHandle;
/**
* Internal API: fast invocation support
*/
final class GeneratedClassLoader {
private static final MethodHandle DEFINE_CLASS_HANDLE;
static {
try {
DEFINE_CLASS_HANDLE = MethodHandleCreator.create(ClassLoader.class, "defineClass",
String.class, byte[].class, int.class, int.class);
} catch (final IllegalAccessException | NoSuchMethodException e) {
throw new IllegalStateException(e);
}
}
@SuppressWarnings("unchecked")
<T> Class<T> load(final byte[] bytecode, final String fqcn) {
final ClassLoader classLoader = getClass().getClassLoader();
try {
return (Class<T>) DEFINE_CLASS_HANDLE.invokeExact(classLoader, fqcn, bytecode, 0, bytecode.length);
} catch (final Throwable t) {
throw new IllegalStateException(t);
}
}
}
|
noway0032/warehouse
|
src/main/java/hu/unideb/inf/warehouse/controller/dataHandling/PlaceController.java
|
<gh_stars>1-10
package hu.unideb.inf.warehouse.controller.dataHandling;
import hu.unideb.inf.warehouse.model.PlaceModel;
import hu.unideb.inf.warehouse.pojo.Place;
import hu.unideb.inf.warehouse.utility.TextListenerUtil;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.*;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.control.cell.TextFieldTableCell;
import javafx.scene.input.MouseEvent;
import javafx.util.Callback;
import javafx.util.converter.NumberStringConverter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.net.URL;
import java.util.ResourceBundle;
/**
* A telephelyek megjelenítéséért felelős osztály.
*
*/
public class PlaceController implements Initializable {
/**
* Itt kerül inicializálásra a telephelyek panel.
* A megjelenő táblázat adatai trölődnek majd a lekérdezett adatokkal feltöltésre kerülnek.
* Beállításra kerül a beviteli mező korlátozásainak figyelése.
*
* @param location inicializálás URL objektuma
* @param resources inicializálás ResourceBundle objektuma
*/
@Override
public void initialize(URL location, ResourceBundle resources) {
pm = new PlaceModel();
table.getColumns().removeAll();
updateTableData();
new TextListenerUtil().numberMaxMinTextFieldListener(inputWeighting, 0,100);
table.setOnMouseClicked((MouseEvent event) -> {
log.info("Táblázat sorának megjelölése.");
editedRow();
});
}
/**
* {@link Logger} osztály egy példánya.
*/
private static final Logger log = LoggerFactory.getLogger(PlaceController.class);
/**
* {@link PlaceModel} osztály egy példánya.
*/
private PlaceModel pm;
/**
* A {@link Place} osztály elemeinek listája.
*/
private ObservableList<Place> data = FXCollections.observableArrayList();
/**
* A {@link Place} osztály táblázatban megjelölt eleme.
*/
private Place selectedPlace = null;
/**
* TableView objektum egy példánya, táblázat az adatok megjelenítéséhez.
*/
@FXML
private TableView table;
/**
* TextField objektum egy példánya, beviteli mező a megnevezés módosításához.
*/
@FXML
private TextField inputLabel;
/**
* TextField objektum egy példánya, beviteli mező az elérhetőség módosításához.
*/
@FXML
private TextField inputAvailability;
/**
* TextField objektum egy példánya, beviteli mező a súlyozás módosításához.
*/
@FXML
private TextField inputWeighting;
/**
* Button objektum egy példánya, gomb elem a beviteli mezők adatainak törléséhez.
*/
@FXML
private Button cleanPlaceTextFieldButton;
/**
* Button objektum egy példánya, gomb elem új példány betöltéséhez.
*/
@FXML
private Button addPlaceButton;
/**
* Button objektum egy példánya, gomb elem a kiválasztott példány törléséhez.
*/
@FXML
private Button delPlaceButton;
/**
* Button objektum egy példánya, gomb elem a kiválasztott példány adatainak módosításához.
*/
@FXML
private Button modPlaceButton;
/**
* TableColumn objektum egy példánya, táblázat oszlop a megnevezés megjelenítéséhez.
* Tartalma egy {@link Place} objektum elérhetőség adatát.
*/
@FXML
private TableColumn<Place, String> labelColumn = null;
/**
* TableColumn objektum egy példánya, táblázat oszlop az elérhetőség megjelenítéséhez.
* Tartalma egy {@link Place} objektum elérhetőség adatát.
*/
@FXML
private TableColumn<Place, String> addressColumn = null;
/**
* TableColumn objektum egy példánya, táblázat oszlop a súlyozás megjelenítéséhez.
* Tartalma egy {@link Place} objektum súlyozás adatát. Értéke {@code int}.
*/
@FXML
private TableColumn<Place, Number> weightingColumn = null;
/**
* Egérkattintást kezelő metódus, használatával a beviteli mezők értékei
* törlődnek és a gombok láthatósága alapállapotba kerül.
*
* @param event egéresemény aktuális eseményobjektuma
*/
@FXML
public void actionCleanPlaceTextField(MouseEvent event){
log.info("Gomb használva: Takarít.");
clearInputBox();
cleanPlaceTextFieldButton.setVisible(true);
addPlaceButton.setVisible(true);
delPlaceButton.setVisible(false);
modPlaceButton.setVisible(false);
selectedPlace = null;
}
/**
* Beviteli mezők értékeinek törlését végző metódus.
*/
private void clearInputBox() {
inputLabel.clear();
inputWeighting.clear();
inputAvailability.clear();
log.info("Beviteli mezők törölve.");
}
/**
* Egérkattintást kezelő metódus, használatával törlésre kerül
* a kiválasztott telephely objektum és frissül a táblázat.
*
* @param event egéresemény aktuális eseményobjektuma
*/
@FXML
public void actionDelPlaceContact(MouseEvent event){
log.info("Gomb használva: Töröl.");
if (selectedPlace != null){
pm.removePlace(selectedPlace);
actionCleanPlaceTextField(event);
updateTableData();
log.info("Telephely törölve.");
}
}
/**
* Egérkattintást kezelő metódus, használatával törlésre kerül
* a kiválasztott telephely objektum.
*
* @param event egéresemény aktuális eseményobjektuma
*/
@FXML
public void actionModPlaceContact(MouseEvent event){
log.info("Gomb használva: Módosítás.");
if (selectedPlace != null){
selectedPlace.setLabel(inputLabel.getText());
selectedPlace.setAvailability(inputAvailability.getText());
selectedPlace.setWeighting(Integer.parseInt(inputWeighting.getText().trim()));
pm.modPlace(selectedPlace);
actionCleanPlaceTextField(event);
updateTableData();
log.info("Telephely adatai módosítva.");
}
}
/**
* Egérkattintást kezelő metódus, használatával tárolásra kerül
* a mezőkben rögzített adatokból létrehozott telephely objektum.
*
* @param event egéresemény aktuális eseményobjektuma
*/
@FXML
public void actionAddPlaceContact(MouseEvent event){
log.info("Gomb használva: Hozzáadás.");
if (inputLabel != null && inputAvailability != null && inputWeighting != null){
Place newPureyor = new Place(
inputLabel.getText(),
inputAvailability.getText(),
Integer.parseInt(inputWeighting.getText().trim())
);
data.add(newPureyor);
pm.addPlace(newPureyor);
clearInputBox();
log.info("Telephely betőltve.");
}
}
/**
* Táblázat adatait frissítő metódus.
*/
private void updateTableData() {
table.getItems().clear();
table.getColumns().clear();
labelColumn = new TableColumn("Megnevezés");
labelColumn.setMinWidth(200);
addressColumn = new TableColumn("Elérhetőség");
addressColumn.setMinWidth(100);
weightingColumn = new TableColumn("Súlyozás");
weightingColumn.setMinWidth(100);
labelColumn.setCellFactory(TextFieldTableCell.forTableColumn());
labelColumn.setCellValueFactory(new PropertyValueFactory<Place, String>("label"));
addressColumn.setCellFactory(TextFieldTableCell.forTableColumn());
addressColumn.setCellValueFactory(new PropertyValueFactory<Place, String>("availability"));
weightingColumn.setCellFactory(TextFieldTableCell.<Place, Number>forTableColumn(new NumberStringConverter()));
weightingColumn.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<Place, Number>, ObservableValue<Number>>() {
@Override
public ObservableValue<Number> call(TableColumn.CellDataFeatures<Place, Number> param) {
return new SimpleIntegerProperty(param.getValue().getWeighting());
}
});
table.getColumns().addAll(labelColumn, addressColumn, weightingColumn);
data.addAll(pm.getPlace());
table.setItems(data);
log.info("Táblázat adatai frissítésre kerültek.");
}
/**
* Táblázat sorának kiválasztását kezelő metódis.
* A kiválasztott sor adatait beviteli mezőbe másolja és szerkesztési gombokra vált.
*/
public void editedRow() {
if (table.getSelectionModel().getSelectedItem() != null) {
selectedPlace = (Place) table.getSelectionModel().getSelectedItem();
cleanPlaceTextFieldButton.setVisible(true);
addPlaceButton.setVisible(false);
delPlaceButton.setVisible(true);
modPlaceButton.setVisible(true);
inputLabel.setText(selectedPlace.getLabel());
inputAvailability.setText(selectedPlace.getAvailability());
inputWeighting.setText(String.valueOf(selectedPlace.getWeighting()));
log.info("Táblázat adatai beviteli mezőkbe másolódtak.");
}
}
}
|
KenG98/magma
|
lte/gateway/c/oai/tasks/nas/esm/esm_data_context.c
|
<gh_stars>1-10
/*
* Licensed to the OpenAirInterface (OAI) Software Alliance under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The OpenAirInterface Software Alliance 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.
*-------------------------------------------------------------------------------
* For more information about the OpenAirInterface (OAI) Software Alliance:
* <EMAIL>
*/
#include <string.h>
#include <stdlib.h>
#include "common_types.h"
#include "3gpp_24.008.h"
#include "emm_data.h"
#include "nas_timer.h"
#include "esm_data.h"
#include "log.h"
#include "dynamic_memory_check.h"
#include "common_defs.h"
#include "mme_app_ue_context.h"
#include "mme_config.h"
#include "3gpp_36.401.h"
// free allocated structs
//------------------------------------------------------------------------------
void free_esm_bearer_context(esm_ebr_context_t *esm_ebr_context)
{
if (esm_ebr_context) {
if (esm_ebr_context->pco) {
free_protocol_configuration_options(&esm_ebr_context->pco);
}
if (esm_ebr_context->tft) {
free_traffic_flow_template(&esm_ebr_context->tft);
}
if (NAS_TIMER_INACTIVE_ID != esm_ebr_context->timer.id) {
esm_ebr_timer_data_t *esm_ebr_timer_data = NULL;
esm_ebr_context->timer.id = nas_timer_stop(
esm_ebr_context->timer.id, (void **) &esm_ebr_timer_data);
/*
* Release the retransmisison timer parameters
*/
if (esm_ebr_timer_data) {
if (esm_ebr_timer_data->msg) {
bdestroy_wrapper(&esm_ebr_timer_data->msg);
}
free_wrapper((void **) &esm_ebr_timer_data);
}
}
}
}
//------------------------------------------------------------------------------
void esm_bearer_context_init(esm_ebr_context_t *esm_ebr_context)
{
if (esm_ebr_context) {
memset(esm_ebr_context, 0, sizeof(*esm_ebr_context));
esm_ebr_context->status = ESM_EBR_INACTIVE;
esm_ebr_context->timer.id = NAS_TIMER_INACTIVE_ID;
}
}
// free allocated structs
//------------------------------------------------------------------------------
//void free_esm_pdn(esm_pdn_t * pdn)
//{
// if (pdn) {
// bdestroy_wrapper (&pdn->apn);
// unsigned int i;
// for (i=0; i < ESM_DATA_EPS_BEARER_MAX; i++) {
// free_esm_bearer(pdn->bearer[i]);
// }
// free_wrapper((void**)&pdn);
// }
//}
//------------------------------------------------------------------------------
void nas_stop_T3489(esm_context_t *const esm_ctx)
{
if ((esm_ctx) && (esm_ctx->T3489.id != NAS_TIMER_INACTIVE_ID)) {
emm_context_t *emm_context =
PARENT_STRUCT(esm_ctx, struct emm_context_s, esm_ctx);
ue_mm_context_t *ue_mm_context =
PARENT_STRUCT(emm_context, struct ue_mm_context_s, emm_context);
mme_ue_s1ap_id_t ue_id = ue_mm_context->mme_ue_s1ap_id;
void *nas_timer_callback_args;
esm_ctx->T3489.id =
nas_timer_stop(esm_ctx->T3489.id, (void **) &nas_timer_callback_args);
if (NAS_TIMER_INACTIVE_ID == esm_ctx->T3489.id) {
OAILOG_INFO(
LOG_NAS_EMM, "T3489 stopped UE " MME_UE_S1AP_ID_FMT "\n", ue_id);
} else {
OAILOG_ERROR(
LOG_NAS_EMM, "Could not stop T3489 UE " MME_UE_S1AP_ID_FMT "\n", ue_id);
}
}
}
// free allocated structs
//------------------------------------------------------------------------------
void free_esm_context_content(esm_context_t *esm_ctx)
{
if (esm_ctx) {
nas_stop_T3489(esm_ctx);
}
}
//------------------------------------------------------------------------------
void esm_init_context(struct esm_context_s *esm_context)
{
emm_context_t *emm_context =
PARENT_STRUCT(esm_context, struct emm_context_s, esm_ctx);
ue_mm_context_t *ue_mm_context =
PARENT_STRUCT(emm_context, struct ue_mm_context_s, emm_context);
OAILOG_DEBUG(
LOG_NAS_ESM,
"ESM-CTX - Init UE id " MME_UE_S1AP_ID_FMT "\n",
ue_mm_context->mme_ue_s1ap_id);
memset(esm_context, 0, sizeof(*esm_context));
esm_context->T3489.id = NAS_TIMER_INACTIVE_ID;
esm_context->T3489.sec = mme_config.nas_config.t3489_sec;
}
|
temporalio/temporal-aws-sdk-go
|
clients/databasemigrationservicestub/stub.go
|
<gh_stars>1-10
// Generated by github.com/temporalio/temporal-aws-sdk-generator
// from github.com/aws/aws-sdk-go version 1.35.7
// Copyright (c) 2020 Temporal Technologies Inc. All rights reserved.
package databasemigrationservicestub
import (
"github.com/aws/aws-sdk-go/service/databasemigrationservice"
"go.temporal.io/sdk/workflow"
"go.temporal.io/aws-sdk/clients"
)
// ensure that imports are valid even if not used by the generated code
var _ clients.VoidFuture
type stub struct{}
type AddTagsToResourceFuture struct {
// public to support Selector.addFuture
Future workflow.Future
}
func (r *AddTagsToResourceFuture) Get(ctx workflow.Context) (*databasemigrationservice.AddTagsToResourceOutput, error) {
var output databasemigrationservice.AddTagsToResourceOutput
err := r.Future.Get(ctx, &output)
return &output, err
}
type ApplyPendingMaintenanceActionFuture struct {
// public to support Selector.addFuture
Future workflow.Future
}
func (r *ApplyPendingMaintenanceActionFuture) Get(ctx workflow.Context) (*databasemigrationservice.ApplyPendingMaintenanceActionOutput, error) {
var output databasemigrationservice.ApplyPendingMaintenanceActionOutput
err := r.Future.Get(ctx, &output)
return &output, err
}
type CancelReplicationTaskAssessmentRunFuture struct {
// public to support Selector.addFuture
Future workflow.Future
}
func (r *CancelReplicationTaskAssessmentRunFuture) Get(ctx workflow.Context) (*databasemigrationservice.CancelReplicationTaskAssessmentRunOutput, error) {
var output databasemigrationservice.CancelReplicationTaskAssessmentRunOutput
err := r.Future.Get(ctx, &output)
return &output, err
}
type CreateEndpointFuture struct {
// public to support Selector.addFuture
Future workflow.Future
}
func (r *CreateEndpointFuture) Get(ctx workflow.Context) (*databasemigrationservice.CreateEndpointOutput, error) {
var output databasemigrationservice.CreateEndpointOutput
err := r.Future.Get(ctx, &output)
return &output, err
}
type CreateEventSubscriptionFuture struct {
// public to support Selector.addFuture
Future workflow.Future
}
func (r *CreateEventSubscriptionFuture) Get(ctx workflow.Context) (*databasemigrationservice.CreateEventSubscriptionOutput, error) {
var output databasemigrationservice.CreateEventSubscriptionOutput
err := r.Future.Get(ctx, &output)
return &output, err
}
type CreateReplicationInstanceFuture struct {
// public to support Selector.addFuture
Future workflow.Future
}
func (r *CreateReplicationInstanceFuture) Get(ctx workflow.Context) (*databasemigrationservice.CreateReplicationInstanceOutput, error) {
var output databasemigrationservice.CreateReplicationInstanceOutput
err := r.Future.Get(ctx, &output)
return &output, err
}
type CreateReplicationSubnetGroupFuture struct {
// public to support Selector.addFuture
Future workflow.Future
}
func (r *CreateReplicationSubnetGroupFuture) Get(ctx workflow.Context) (*databasemigrationservice.CreateReplicationSubnetGroupOutput, error) {
var output databasemigrationservice.CreateReplicationSubnetGroupOutput
err := r.Future.Get(ctx, &output)
return &output, err
}
type CreateReplicationTaskFuture struct {
// public to support Selector.addFuture
Future workflow.Future
}
func (r *CreateReplicationTaskFuture) Get(ctx workflow.Context) (*databasemigrationservice.CreateReplicationTaskOutput, error) {
var output databasemigrationservice.CreateReplicationTaskOutput
err := r.Future.Get(ctx, &output)
return &output, err
}
type DeleteCertificateFuture struct {
// public to support Selector.addFuture
Future workflow.Future
}
func (r *DeleteCertificateFuture) Get(ctx workflow.Context) (*databasemigrationservice.DeleteCertificateOutput, error) {
var output databasemigrationservice.DeleteCertificateOutput
err := r.Future.Get(ctx, &output)
return &output, err
}
type DeleteConnectionFuture struct {
// public to support Selector.addFuture
Future workflow.Future
}
func (r *DeleteConnectionFuture) Get(ctx workflow.Context) (*databasemigrationservice.DeleteConnectionOutput, error) {
var output databasemigrationservice.DeleteConnectionOutput
err := r.Future.Get(ctx, &output)
return &output, err
}
type DeleteEndpointFuture struct {
// public to support Selector.addFuture
Future workflow.Future
}
func (r *DeleteEndpointFuture) Get(ctx workflow.Context) (*databasemigrationservice.DeleteEndpointOutput, error) {
var output databasemigrationservice.DeleteEndpointOutput
err := r.Future.Get(ctx, &output)
return &output, err
}
type DeleteEventSubscriptionFuture struct {
// public to support Selector.addFuture
Future workflow.Future
}
func (r *DeleteEventSubscriptionFuture) Get(ctx workflow.Context) (*databasemigrationservice.DeleteEventSubscriptionOutput, error) {
var output databasemigrationservice.DeleteEventSubscriptionOutput
err := r.Future.Get(ctx, &output)
return &output, err
}
type DeleteReplicationInstanceFuture struct {
// public to support Selector.addFuture
Future workflow.Future
}
func (r *DeleteReplicationInstanceFuture) Get(ctx workflow.Context) (*databasemigrationservice.DeleteReplicationInstanceOutput, error) {
var output databasemigrationservice.DeleteReplicationInstanceOutput
err := r.Future.Get(ctx, &output)
return &output, err
}
type DeleteReplicationSubnetGroupFuture struct {
// public to support Selector.addFuture
Future workflow.Future
}
func (r *DeleteReplicationSubnetGroupFuture) Get(ctx workflow.Context) (*databasemigrationservice.DeleteReplicationSubnetGroupOutput, error) {
var output databasemigrationservice.DeleteReplicationSubnetGroupOutput
err := r.Future.Get(ctx, &output)
return &output, err
}
type DeleteReplicationTaskFuture struct {
// public to support Selector.addFuture
Future workflow.Future
}
func (r *DeleteReplicationTaskFuture) Get(ctx workflow.Context) (*databasemigrationservice.DeleteReplicationTaskOutput, error) {
var output databasemigrationservice.DeleteReplicationTaskOutput
err := r.Future.Get(ctx, &output)
return &output, err
}
type DeleteReplicationTaskAssessmentRunFuture struct {
// public to support Selector.addFuture
Future workflow.Future
}
func (r *DeleteReplicationTaskAssessmentRunFuture) Get(ctx workflow.Context) (*databasemigrationservice.DeleteReplicationTaskAssessmentRunOutput, error) {
var output databasemigrationservice.DeleteReplicationTaskAssessmentRunOutput
err := r.Future.Get(ctx, &output)
return &output, err
}
type DescribeAccountAttributesFuture struct {
// public to support Selector.addFuture
Future workflow.Future
}
func (r *DescribeAccountAttributesFuture) Get(ctx workflow.Context) (*databasemigrationservice.DescribeAccountAttributesOutput, error) {
var output databasemigrationservice.DescribeAccountAttributesOutput
err := r.Future.Get(ctx, &output)
return &output, err
}
type DescribeApplicableIndividualAssessmentsFuture struct {
// public to support Selector.addFuture
Future workflow.Future
}
func (r *DescribeApplicableIndividualAssessmentsFuture) Get(ctx workflow.Context) (*databasemigrationservice.DescribeApplicableIndividualAssessmentsOutput, error) {
var output databasemigrationservice.DescribeApplicableIndividualAssessmentsOutput
err := r.Future.Get(ctx, &output)
return &output, err
}
type DescribeCertificatesFuture struct {
// public to support Selector.addFuture
Future workflow.Future
}
func (r *DescribeCertificatesFuture) Get(ctx workflow.Context) (*databasemigrationservice.DescribeCertificatesOutput, error) {
var output databasemigrationservice.DescribeCertificatesOutput
err := r.Future.Get(ctx, &output)
return &output, err
}
type DescribeConnectionsFuture struct {
// public to support Selector.addFuture
Future workflow.Future
}
func (r *DescribeConnectionsFuture) Get(ctx workflow.Context) (*databasemigrationservice.DescribeConnectionsOutput, error) {
var output databasemigrationservice.DescribeConnectionsOutput
err := r.Future.Get(ctx, &output)
return &output, err
}
type DescribeEndpointTypesFuture struct {
// public to support Selector.addFuture
Future workflow.Future
}
func (r *DescribeEndpointTypesFuture) Get(ctx workflow.Context) (*databasemigrationservice.DescribeEndpointTypesOutput, error) {
var output databasemigrationservice.DescribeEndpointTypesOutput
err := r.Future.Get(ctx, &output)
return &output, err
}
type DescribeEndpointsFuture struct {
// public to support Selector.addFuture
Future workflow.Future
}
func (r *DescribeEndpointsFuture) Get(ctx workflow.Context) (*databasemigrationservice.DescribeEndpointsOutput, error) {
var output databasemigrationservice.DescribeEndpointsOutput
err := r.Future.Get(ctx, &output)
return &output, err
}
type DescribeEventCategoriesFuture struct {
// public to support Selector.addFuture
Future workflow.Future
}
func (r *DescribeEventCategoriesFuture) Get(ctx workflow.Context) (*databasemigrationservice.DescribeEventCategoriesOutput, error) {
var output databasemigrationservice.DescribeEventCategoriesOutput
err := r.Future.Get(ctx, &output)
return &output, err
}
type DescribeEventSubscriptionsFuture struct {
// public to support Selector.addFuture
Future workflow.Future
}
func (r *DescribeEventSubscriptionsFuture) Get(ctx workflow.Context) (*databasemigrationservice.DescribeEventSubscriptionsOutput, error) {
var output databasemigrationservice.DescribeEventSubscriptionsOutput
err := r.Future.Get(ctx, &output)
return &output, err
}
type DescribeEventsFuture struct {
// public to support Selector.addFuture
Future workflow.Future
}
func (r *DescribeEventsFuture) Get(ctx workflow.Context) (*databasemigrationservice.DescribeEventsOutput, error) {
var output databasemigrationservice.DescribeEventsOutput
err := r.Future.Get(ctx, &output)
return &output, err
}
type DescribeOrderableReplicationInstancesFuture struct {
// public to support Selector.addFuture
Future workflow.Future
}
func (r *DescribeOrderableReplicationInstancesFuture) Get(ctx workflow.Context) (*databasemigrationservice.DescribeOrderableReplicationInstancesOutput, error) {
var output databasemigrationservice.DescribeOrderableReplicationInstancesOutput
err := r.Future.Get(ctx, &output)
return &output, err
}
type DescribePendingMaintenanceActionsFuture struct {
// public to support Selector.addFuture
Future workflow.Future
}
func (r *DescribePendingMaintenanceActionsFuture) Get(ctx workflow.Context) (*databasemigrationservice.DescribePendingMaintenanceActionsOutput, error) {
var output databasemigrationservice.DescribePendingMaintenanceActionsOutput
err := r.Future.Get(ctx, &output)
return &output, err
}
type DescribeRefreshSchemasStatusFuture struct {
// public to support Selector.addFuture
Future workflow.Future
}
func (r *DescribeRefreshSchemasStatusFuture) Get(ctx workflow.Context) (*databasemigrationservice.DescribeRefreshSchemasStatusOutput, error) {
var output databasemigrationservice.DescribeRefreshSchemasStatusOutput
err := r.Future.Get(ctx, &output)
return &output, err
}
type DescribeReplicationInstanceTaskLogsFuture struct {
// public to support Selector.addFuture
Future workflow.Future
}
func (r *DescribeReplicationInstanceTaskLogsFuture) Get(ctx workflow.Context) (*databasemigrationservice.DescribeReplicationInstanceTaskLogsOutput, error) {
var output databasemigrationservice.DescribeReplicationInstanceTaskLogsOutput
err := r.Future.Get(ctx, &output)
return &output, err
}
type DescribeReplicationInstancesFuture struct {
// public to support Selector.addFuture
Future workflow.Future
}
func (r *DescribeReplicationInstancesFuture) Get(ctx workflow.Context) (*databasemigrationservice.DescribeReplicationInstancesOutput, error) {
var output databasemigrationservice.DescribeReplicationInstancesOutput
err := r.Future.Get(ctx, &output)
return &output, err
}
type DescribeReplicationSubnetGroupsFuture struct {
// public to support Selector.addFuture
Future workflow.Future
}
func (r *DescribeReplicationSubnetGroupsFuture) Get(ctx workflow.Context) (*databasemigrationservice.DescribeReplicationSubnetGroupsOutput, error) {
var output databasemigrationservice.DescribeReplicationSubnetGroupsOutput
err := r.Future.Get(ctx, &output)
return &output, err
}
type DescribeReplicationTaskAssessmentResultsFuture struct {
// public to support Selector.addFuture
Future workflow.Future
}
func (r *DescribeReplicationTaskAssessmentResultsFuture) Get(ctx workflow.Context) (*databasemigrationservice.DescribeReplicationTaskAssessmentResultsOutput, error) {
var output databasemigrationservice.DescribeReplicationTaskAssessmentResultsOutput
err := r.Future.Get(ctx, &output)
return &output, err
}
type DescribeReplicationTaskAssessmentRunsFuture struct {
// public to support Selector.addFuture
Future workflow.Future
}
func (r *DescribeReplicationTaskAssessmentRunsFuture) Get(ctx workflow.Context) (*databasemigrationservice.DescribeReplicationTaskAssessmentRunsOutput, error) {
var output databasemigrationservice.DescribeReplicationTaskAssessmentRunsOutput
err := r.Future.Get(ctx, &output)
return &output, err
}
type DescribeReplicationTaskIndividualAssessmentsFuture struct {
// public to support Selector.addFuture
Future workflow.Future
}
func (r *DescribeReplicationTaskIndividualAssessmentsFuture) Get(ctx workflow.Context) (*databasemigrationservice.DescribeReplicationTaskIndividualAssessmentsOutput, error) {
var output databasemigrationservice.DescribeReplicationTaskIndividualAssessmentsOutput
err := r.Future.Get(ctx, &output)
return &output, err
}
type DescribeReplicationTasksFuture struct {
// public to support Selector.addFuture
Future workflow.Future
}
func (r *DescribeReplicationTasksFuture) Get(ctx workflow.Context) (*databasemigrationservice.DescribeReplicationTasksOutput, error) {
var output databasemigrationservice.DescribeReplicationTasksOutput
err := r.Future.Get(ctx, &output)
return &output, err
}
type DescribeSchemasFuture struct {
// public to support Selector.addFuture
Future workflow.Future
}
func (r *DescribeSchemasFuture) Get(ctx workflow.Context) (*databasemigrationservice.DescribeSchemasOutput, error) {
var output databasemigrationservice.DescribeSchemasOutput
err := r.Future.Get(ctx, &output)
return &output, err
}
type DescribeTableStatisticsFuture struct {
// public to support Selector.addFuture
Future workflow.Future
}
func (r *DescribeTableStatisticsFuture) Get(ctx workflow.Context) (*databasemigrationservice.DescribeTableStatisticsOutput, error) {
var output databasemigrationservice.DescribeTableStatisticsOutput
err := r.Future.Get(ctx, &output)
return &output, err
}
type ImportCertificateFuture struct {
// public to support Selector.addFuture
Future workflow.Future
}
func (r *ImportCertificateFuture) Get(ctx workflow.Context) (*databasemigrationservice.ImportCertificateOutput, error) {
var output databasemigrationservice.ImportCertificateOutput
err := r.Future.Get(ctx, &output)
return &output, err
}
type ListTagsForResourceFuture struct {
// public to support Selector.addFuture
Future workflow.Future
}
func (r *ListTagsForResourceFuture) Get(ctx workflow.Context) (*databasemigrationservice.ListTagsForResourceOutput, error) {
var output databasemigrationservice.ListTagsForResourceOutput
err := r.Future.Get(ctx, &output)
return &output, err
}
type ModifyEndpointFuture struct {
// public to support Selector.addFuture
Future workflow.Future
}
func (r *ModifyEndpointFuture) Get(ctx workflow.Context) (*databasemigrationservice.ModifyEndpointOutput, error) {
var output databasemigrationservice.ModifyEndpointOutput
err := r.Future.Get(ctx, &output)
return &output, err
}
type ModifyEventSubscriptionFuture struct {
// public to support Selector.addFuture
Future workflow.Future
}
func (r *ModifyEventSubscriptionFuture) Get(ctx workflow.Context) (*databasemigrationservice.ModifyEventSubscriptionOutput, error) {
var output databasemigrationservice.ModifyEventSubscriptionOutput
err := r.Future.Get(ctx, &output)
return &output, err
}
type ModifyReplicationInstanceFuture struct {
// public to support Selector.addFuture
Future workflow.Future
}
func (r *ModifyReplicationInstanceFuture) Get(ctx workflow.Context) (*databasemigrationservice.ModifyReplicationInstanceOutput, error) {
var output databasemigrationservice.ModifyReplicationInstanceOutput
err := r.Future.Get(ctx, &output)
return &output, err
}
type ModifyReplicationSubnetGroupFuture struct {
// public to support Selector.addFuture
Future workflow.Future
}
func (r *ModifyReplicationSubnetGroupFuture) Get(ctx workflow.Context) (*databasemigrationservice.ModifyReplicationSubnetGroupOutput, error) {
var output databasemigrationservice.ModifyReplicationSubnetGroupOutput
err := r.Future.Get(ctx, &output)
return &output, err
}
type ModifyReplicationTaskFuture struct {
// public to support Selector.addFuture
Future workflow.Future
}
func (r *ModifyReplicationTaskFuture) Get(ctx workflow.Context) (*databasemigrationservice.ModifyReplicationTaskOutput, error) {
var output databasemigrationservice.ModifyReplicationTaskOutput
err := r.Future.Get(ctx, &output)
return &output, err
}
type RebootReplicationInstanceFuture struct {
// public to support Selector.addFuture
Future workflow.Future
}
func (r *RebootReplicationInstanceFuture) Get(ctx workflow.Context) (*databasemigrationservice.RebootReplicationInstanceOutput, error) {
var output databasemigrationservice.RebootReplicationInstanceOutput
err := r.Future.Get(ctx, &output)
return &output, err
}
type RefreshSchemasFuture struct {
// public to support Selector.addFuture
Future workflow.Future
}
func (r *RefreshSchemasFuture) Get(ctx workflow.Context) (*databasemigrationservice.RefreshSchemasOutput, error) {
var output databasemigrationservice.RefreshSchemasOutput
err := r.Future.Get(ctx, &output)
return &output, err
}
type ReloadTablesFuture struct {
// public to support Selector.addFuture
Future workflow.Future
}
func (r *ReloadTablesFuture) Get(ctx workflow.Context) (*databasemigrationservice.ReloadTablesOutput, error) {
var output databasemigrationservice.ReloadTablesOutput
err := r.Future.Get(ctx, &output)
return &output, err
}
type RemoveTagsFromResourceFuture struct {
// public to support Selector.addFuture
Future workflow.Future
}
func (r *RemoveTagsFromResourceFuture) Get(ctx workflow.Context) (*databasemigrationservice.RemoveTagsFromResourceOutput, error) {
var output databasemigrationservice.RemoveTagsFromResourceOutput
err := r.Future.Get(ctx, &output)
return &output, err
}
type StartReplicationTaskFuture struct {
// public to support Selector.addFuture
Future workflow.Future
}
func (r *StartReplicationTaskFuture) Get(ctx workflow.Context) (*databasemigrationservice.StartReplicationTaskOutput, error) {
var output databasemigrationservice.StartReplicationTaskOutput
err := r.Future.Get(ctx, &output)
return &output, err
}
type StartReplicationTaskAssessmentFuture struct {
// public to support Selector.addFuture
Future workflow.Future
}
func (r *StartReplicationTaskAssessmentFuture) Get(ctx workflow.Context) (*databasemigrationservice.StartReplicationTaskAssessmentOutput, error) {
var output databasemigrationservice.StartReplicationTaskAssessmentOutput
err := r.Future.Get(ctx, &output)
return &output, err
}
type StartReplicationTaskAssessmentRunFuture struct {
// public to support Selector.addFuture
Future workflow.Future
}
func (r *StartReplicationTaskAssessmentRunFuture) Get(ctx workflow.Context) (*databasemigrationservice.StartReplicationTaskAssessmentRunOutput, error) {
var output databasemigrationservice.StartReplicationTaskAssessmentRunOutput
err := r.Future.Get(ctx, &output)
return &output, err
}
type StopReplicationTaskFuture struct {
// public to support Selector.addFuture
Future workflow.Future
}
func (r *StopReplicationTaskFuture) Get(ctx workflow.Context) (*databasemigrationservice.StopReplicationTaskOutput, error) {
var output databasemigrationservice.StopReplicationTaskOutput
err := r.Future.Get(ctx, &output)
return &output, err
}
type TestConnectionFuture struct {
// public to support Selector.addFuture
Future workflow.Future
}
func (r *TestConnectionFuture) Get(ctx workflow.Context) (*databasemigrationservice.TestConnectionOutput, error) {
var output databasemigrationservice.TestConnectionOutput
err := r.Future.Get(ctx, &output)
return &output, err
}
func (a *stub) AddTagsToResource(ctx workflow.Context, input *databasemigrationservice.AddTagsToResourceInput) (*databasemigrationservice.AddTagsToResourceOutput, error) {
var output databasemigrationservice.AddTagsToResourceOutput
err := workflow.ExecuteActivity(ctx, "aws.databasemigrationservice.AddTagsToResource", input).Get(ctx, &output)
return &output, err
}
func (a *stub) AddTagsToResourceAsync(ctx workflow.Context, input *databasemigrationservice.AddTagsToResourceInput) *AddTagsToResourceFuture {
future := workflow.ExecuteActivity(ctx, "aws.databasemigrationservice.AddTagsToResource", input)
return &AddTagsToResourceFuture{Future: future}
}
func (a *stub) ApplyPendingMaintenanceAction(ctx workflow.Context, input *databasemigrationservice.ApplyPendingMaintenanceActionInput) (*databasemigrationservice.ApplyPendingMaintenanceActionOutput, error) {
var output databasemigrationservice.ApplyPendingMaintenanceActionOutput
err := workflow.ExecuteActivity(ctx, "aws.databasemigrationservice.ApplyPendingMaintenanceAction", input).Get(ctx, &output)
return &output, err
}
func (a *stub) ApplyPendingMaintenanceActionAsync(ctx workflow.Context, input *databasemigrationservice.ApplyPendingMaintenanceActionInput) *ApplyPendingMaintenanceActionFuture {
future := workflow.ExecuteActivity(ctx, "aws.databasemigrationservice.ApplyPendingMaintenanceAction", input)
return &ApplyPendingMaintenanceActionFuture{Future: future}
}
func (a *stub) CancelReplicationTaskAssessmentRun(ctx workflow.Context, input *databasemigrationservice.CancelReplicationTaskAssessmentRunInput) (*databasemigrationservice.CancelReplicationTaskAssessmentRunOutput, error) {
var output databasemigrationservice.CancelReplicationTaskAssessmentRunOutput
err := workflow.ExecuteActivity(ctx, "aws.databasemigrationservice.CancelReplicationTaskAssessmentRun", input).Get(ctx, &output)
return &output, err
}
func (a *stub) CancelReplicationTaskAssessmentRunAsync(ctx workflow.Context, input *databasemigrationservice.CancelReplicationTaskAssessmentRunInput) *CancelReplicationTaskAssessmentRunFuture {
future := workflow.ExecuteActivity(ctx, "aws.databasemigrationservice.CancelReplicationTaskAssessmentRun", input)
return &CancelReplicationTaskAssessmentRunFuture{Future: future}
}
func (a *stub) CreateEndpoint(ctx workflow.Context, input *databasemigrationservice.CreateEndpointInput) (*databasemigrationservice.CreateEndpointOutput, error) {
var output databasemigrationservice.CreateEndpointOutput
err := workflow.ExecuteActivity(ctx, "aws.databasemigrationservice.CreateEndpoint", input).Get(ctx, &output)
return &output, err
}
func (a *stub) CreateEndpointAsync(ctx workflow.Context, input *databasemigrationservice.CreateEndpointInput) *CreateEndpointFuture {
future := workflow.ExecuteActivity(ctx, "aws.databasemigrationservice.CreateEndpoint", input)
return &CreateEndpointFuture{Future: future}
}
func (a *stub) CreateEventSubscription(ctx workflow.Context, input *databasemigrationservice.CreateEventSubscriptionInput) (*databasemigrationservice.CreateEventSubscriptionOutput, error) {
var output databasemigrationservice.CreateEventSubscriptionOutput
err := workflow.ExecuteActivity(ctx, "aws.databasemigrationservice.CreateEventSubscription", input).Get(ctx, &output)
return &output, err
}
func (a *stub) CreateEventSubscriptionAsync(ctx workflow.Context, input *databasemigrationservice.CreateEventSubscriptionInput) *CreateEventSubscriptionFuture {
future := workflow.ExecuteActivity(ctx, "aws.databasemigrationservice.CreateEventSubscription", input)
return &CreateEventSubscriptionFuture{Future: future}
}
func (a *stub) CreateReplicationInstance(ctx workflow.Context, input *databasemigrationservice.CreateReplicationInstanceInput) (*databasemigrationservice.CreateReplicationInstanceOutput, error) {
var output databasemigrationservice.CreateReplicationInstanceOutput
err := workflow.ExecuteActivity(ctx, "aws.databasemigrationservice.CreateReplicationInstance", input).Get(ctx, &output)
return &output, err
}
func (a *stub) CreateReplicationInstanceAsync(ctx workflow.Context, input *databasemigrationservice.CreateReplicationInstanceInput) *CreateReplicationInstanceFuture {
future := workflow.ExecuteActivity(ctx, "aws.databasemigrationservice.CreateReplicationInstance", input)
return &CreateReplicationInstanceFuture{Future: future}
}
func (a *stub) CreateReplicationSubnetGroup(ctx workflow.Context, input *databasemigrationservice.CreateReplicationSubnetGroupInput) (*databasemigrationservice.CreateReplicationSubnetGroupOutput, error) {
var output databasemigrationservice.CreateReplicationSubnetGroupOutput
err := workflow.ExecuteActivity(ctx, "aws.databasemigrationservice.CreateReplicationSubnetGroup", input).Get(ctx, &output)
return &output, err
}
func (a *stub) CreateReplicationSubnetGroupAsync(ctx workflow.Context, input *databasemigrationservice.CreateReplicationSubnetGroupInput) *CreateReplicationSubnetGroupFuture {
future := workflow.ExecuteActivity(ctx, "aws.databasemigrationservice.CreateReplicationSubnetGroup", input)
return &CreateReplicationSubnetGroupFuture{Future: future}
}
func (a *stub) CreateReplicationTask(ctx workflow.Context, input *databasemigrationservice.CreateReplicationTaskInput) (*databasemigrationservice.CreateReplicationTaskOutput, error) {
var output databasemigrationservice.CreateReplicationTaskOutput
err := workflow.ExecuteActivity(ctx, "aws.databasemigrationservice.CreateReplicationTask", input).Get(ctx, &output)
return &output, err
}
func (a *stub) CreateReplicationTaskAsync(ctx workflow.Context, input *databasemigrationservice.CreateReplicationTaskInput) *CreateReplicationTaskFuture {
future := workflow.ExecuteActivity(ctx, "aws.databasemigrationservice.CreateReplicationTask", input)
return &CreateReplicationTaskFuture{Future: future}
}
func (a *stub) DeleteCertificate(ctx workflow.Context, input *databasemigrationservice.DeleteCertificateInput) (*databasemigrationservice.DeleteCertificateOutput, error) {
var output databasemigrationservice.DeleteCertificateOutput
err := workflow.ExecuteActivity(ctx, "aws.databasemigrationservice.DeleteCertificate", input).Get(ctx, &output)
return &output, err
}
func (a *stub) DeleteCertificateAsync(ctx workflow.Context, input *databasemigrationservice.DeleteCertificateInput) *DeleteCertificateFuture {
future := workflow.ExecuteActivity(ctx, "aws.databasemigrationservice.DeleteCertificate", input)
return &DeleteCertificateFuture{Future: future}
}
func (a *stub) DeleteConnection(ctx workflow.Context, input *databasemigrationservice.DeleteConnectionInput) (*databasemigrationservice.DeleteConnectionOutput, error) {
var output databasemigrationservice.DeleteConnectionOutput
err := workflow.ExecuteActivity(ctx, "aws.databasemigrationservice.DeleteConnection", input).Get(ctx, &output)
return &output, err
}
func (a *stub) DeleteConnectionAsync(ctx workflow.Context, input *databasemigrationservice.DeleteConnectionInput) *DeleteConnectionFuture {
future := workflow.ExecuteActivity(ctx, "aws.databasemigrationservice.DeleteConnection", input)
return &DeleteConnectionFuture{Future: future}
}
func (a *stub) DeleteEndpoint(ctx workflow.Context, input *databasemigrationservice.DeleteEndpointInput) (*databasemigrationservice.DeleteEndpointOutput, error) {
var output databasemigrationservice.DeleteEndpointOutput
err := workflow.ExecuteActivity(ctx, "aws.databasemigrationservice.DeleteEndpoint", input).Get(ctx, &output)
return &output, err
}
func (a *stub) DeleteEndpointAsync(ctx workflow.Context, input *databasemigrationservice.DeleteEndpointInput) *DeleteEndpointFuture {
future := workflow.ExecuteActivity(ctx, "aws.databasemigrationservice.DeleteEndpoint", input)
return &DeleteEndpointFuture{Future: future}
}
func (a *stub) DeleteEventSubscription(ctx workflow.Context, input *databasemigrationservice.DeleteEventSubscriptionInput) (*databasemigrationservice.DeleteEventSubscriptionOutput, error) {
var output databasemigrationservice.DeleteEventSubscriptionOutput
err := workflow.ExecuteActivity(ctx, "aws.databasemigrationservice.DeleteEventSubscription", input).Get(ctx, &output)
return &output, err
}
func (a *stub) DeleteEventSubscriptionAsync(ctx workflow.Context, input *databasemigrationservice.DeleteEventSubscriptionInput) *DeleteEventSubscriptionFuture {
future := workflow.ExecuteActivity(ctx, "aws.databasemigrationservice.DeleteEventSubscription", input)
return &DeleteEventSubscriptionFuture{Future: future}
}
func (a *stub) DeleteReplicationInstance(ctx workflow.Context, input *databasemigrationservice.DeleteReplicationInstanceInput) (*databasemigrationservice.DeleteReplicationInstanceOutput, error) {
var output databasemigrationservice.DeleteReplicationInstanceOutput
err := workflow.ExecuteActivity(ctx, "aws.databasemigrationservice.DeleteReplicationInstance", input).Get(ctx, &output)
return &output, err
}
func (a *stub) DeleteReplicationInstanceAsync(ctx workflow.Context, input *databasemigrationservice.DeleteReplicationInstanceInput) *DeleteReplicationInstanceFuture {
future := workflow.ExecuteActivity(ctx, "aws.databasemigrationservice.DeleteReplicationInstance", input)
return &DeleteReplicationInstanceFuture{Future: future}
}
func (a *stub) DeleteReplicationSubnetGroup(ctx workflow.Context, input *databasemigrationservice.DeleteReplicationSubnetGroupInput) (*databasemigrationservice.DeleteReplicationSubnetGroupOutput, error) {
var output databasemigrationservice.DeleteReplicationSubnetGroupOutput
err := workflow.ExecuteActivity(ctx, "aws.databasemigrationservice.DeleteReplicationSubnetGroup", input).Get(ctx, &output)
return &output, err
}
func (a *stub) DeleteReplicationSubnetGroupAsync(ctx workflow.Context, input *databasemigrationservice.DeleteReplicationSubnetGroupInput) *DeleteReplicationSubnetGroupFuture {
future := workflow.ExecuteActivity(ctx, "aws.databasemigrationservice.DeleteReplicationSubnetGroup", input)
return &DeleteReplicationSubnetGroupFuture{Future: future}
}
func (a *stub) DeleteReplicationTask(ctx workflow.Context, input *databasemigrationservice.DeleteReplicationTaskInput) (*databasemigrationservice.DeleteReplicationTaskOutput, error) {
var output databasemigrationservice.DeleteReplicationTaskOutput
err := workflow.ExecuteActivity(ctx, "aws.databasemigrationservice.DeleteReplicationTask", input).Get(ctx, &output)
return &output, err
}
func (a *stub) DeleteReplicationTaskAsync(ctx workflow.Context, input *databasemigrationservice.DeleteReplicationTaskInput) *DeleteReplicationTaskFuture {
future := workflow.ExecuteActivity(ctx, "aws.databasemigrationservice.DeleteReplicationTask", input)
return &DeleteReplicationTaskFuture{Future: future}
}
func (a *stub) DeleteReplicationTaskAssessmentRun(ctx workflow.Context, input *databasemigrationservice.DeleteReplicationTaskAssessmentRunInput) (*databasemigrationservice.DeleteReplicationTaskAssessmentRunOutput, error) {
var output databasemigrationservice.DeleteReplicationTaskAssessmentRunOutput
err := workflow.ExecuteActivity(ctx, "aws.databasemigrationservice.DeleteReplicationTaskAssessmentRun", input).Get(ctx, &output)
return &output, err
}
func (a *stub) DeleteReplicationTaskAssessmentRunAsync(ctx workflow.Context, input *databasemigrationservice.DeleteReplicationTaskAssessmentRunInput) *DeleteReplicationTaskAssessmentRunFuture {
future := workflow.ExecuteActivity(ctx, "aws.databasemigrationservice.DeleteReplicationTaskAssessmentRun", input)
return &DeleteReplicationTaskAssessmentRunFuture{Future: future}
}
func (a *stub) DescribeAccountAttributes(ctx workflow.Context, input *databasemigrationservice.DescribeAccountAttributesInput) (*databasemigrationservice.DescribeAccountAttributesOutput, error) {
var output databasemigrationservice.DescribeAccountAttributesOutput
err := workflow.ExecuteActivity(ctx, "aws.databasemigrationservice.DescribeAccountAttributes", input).Get(ctx, &output)
return &output, err
}
func (a *stub) DescribeAccountAttributesAsync(ctx workflow.Context, input *databasemigrationservice.DescribeAccountAttributesInput) *DescribeAccountAttributesFuture {
future := workflow.ExecuteActivity(ctx, "aws.databasemigrationservice.DescribeAccountAttributes", input)
return &DescribeAccountAttributesFuture{Future: future}
}
func (a *stub) DescribeApplicableIndividualAssessments(ctx workflow.Context, input *databasemigrationservice.DescribeApplicableIndividualAssessmentsInput) (*databasemigrationservice.DescribeApplicableIndividualAssessmentsOutput, error) {
var output databasemigrationservice.DescribeApplicableIndividualAssessmentsOutput
err := workflow.ExecuteActivity(ctx, "aws.databasemigrationservice.DescribeApplicableIndividualAssessments", input).Get(ctx, &output)
return &output, err
}
func (a *stub) DescribeApplicableIndividualAssessmentsAsync(ctx workflow.Context, input *databasemigrationservice.DescribeApplicableIndividualAssessmentsInput) *DescribeApplicableIndividualAssessmentsFuture {
future := workflow.ExecuteActivity(ctx, "aws.databasemigrationservice.DescribeApplicableIndividualAssessments", input)
return &DescribeApplicableIndividualAssessmentsFuture{Future: future}
}
func (a *stub) DescribeCertificates(ctx workflow.Context, input *databasemigrationservice.DescribeCertificatesInput) (*databasemigrationservice.DescribeCertificatesOutput, error) {
var output databasemigrationservice.DescribeCertificatesOutput
err := workflow.ExecuteActivity(ctx, "aws.databasemigrationservice.DescribeCertificates", input).Get(ctx, &output)
return &output, err
}
func (a *stub) DescribeCertificatesAsync(ctx workflow.Context, input *databasemigrationservice.DescribeCertificatesInput) *DescribeCertificatesFuture {
future := workflow.ExecuteActivity(ctx, "aws.databasemigrationservice.DescribeCertificates", input)
return &DescribeCertificatesFuture{Future: future}
}
func (a *stub) DescribeConnections(ctx workflow.Context, input *databasemigrationservice.DescribeConnectionsInput) (*databasemigrationservice.DescribeConnectionsOutput, error) {
var output databasemigrationservice.DescribeConnectionsOutput
err := workflow.ExecuteActivity(ctx, "aws.databasemigrationservice.DescribeConnections", input).Get(ctx, &output)
return &output, err
}
func (a *stub) DescribeConnectionsAsync(ctx workflow.Context, input *databasemigrationservice.DescribeConnectionsInput) *DescribeConnectionsFuture {
future := workflow.ExecuteActivity(ctx, "aws.databasemigrationservice.DescribeConnections", input)
return &DescribeConnectionsFuture{Future: future}
}
func (a *stub) DescribeEndpointTypes(ctx workflow.Context, input *databasemigrationservice.DescribeEndpointTypesInput) (*databasemigrationservice.DescribeEndpointTypesOutput, error) {
var output databasemigrationservice.DescribeEndpointTypesOutput
err := workflow.ExecuteActivity(ctx, "aws.databasemigrationservice.DescribeEndpointTypes", input).Get(ctx, &output)
return &output, err
}
func (a *stub) DescribeEndpointTypesAsync(ctx workflow.Context, input *databasemigrationservice.DescribeEndpointTypesInput) *DescribeEndpointTypesFuture {
future := workflow.ExecuteActivity(ctx, "aws.databasemigrationservice.DescribeEndpointTypes", input)
return &DescribeEndpointTypesFuture{Future: future}
}
func (a *stub) DescribeEndpoints(ctx workflow.Context, input *databasemigrationservice.DescribeEndpointsInput) (*databasemigrationservice.DescribeEndpointsOutput, error) {
var output databasemigrationservice.DescribeEndpointsOutput
err := workflow.ExecuteActivity(ctx, "aws.databasemigrationservice.DescribeEndpoints", input).Get(ctx, &output)
return &output, err
}
func (a *stub) DescribeEndpointsAsync(ctx workflow.Context, input *databasemigrationservice.DescribeEndpointsInput) *DescribeEndpointsFuture {
future := workflow.ExecuteActivity(ctx, "aws.databasemigrationservice.DescribeEndpoints", input)
return &DescribeEndpointsFuture{Future: future}
}
func (a *stub) DescribeEventCategories(ctx workflow.Context, input *databasemigrationservice.DescribeEventCategoriesInput) (*databasemigrationservice.DescribeEventCategoriesOutput, error) {
var output databasemigrationservice.DescribeEventCategoriesOutput
err := workflow.ExecuteActivity(ctx, "aws.databasemigrationservice.DescribeEventCategories", input).Get(ctx, &output)
return &output, err
}
func (a *stub) DescribeEventCategoriesAsync(ctx workflow.Context, input *databasemigrationservice.DescribeEventCategoriesInput) *DescribeEventCategoriesFuture {
future := workflow.ExecuteActivity(ctx, "aws.databasemigrationservice.DescribeEventCategories", input)
return &DescribeEventCategoriesFuture{Future: future}
}
func (a *stub) DescribeEventSubscriptions(ctx workflow.Context, input *databasemigrationservice.DescribeEventSubscriptionsInput) (*databasemigrationservice.DescribeEventSubscriptionsOutput, error) {
var output databasemigrationservice.DescribeEventSubscriptionsOutput
err := workflow.ExecuteActivity(ctx, "aws.databasemigrationservice.DescribeEventSubscriptions", input).Get(ctx, &output)
return &output, err
}
func (a *stub) DescribeEventSubscriptionsAsync(ctx workflow.Context, input *databasemigrationservice.DescribeEventSubscriptionsInput) *DescribeEventSubscriptionsFuture {
future := workflow.ExecuteActivity(ctx, "aws.databasemigrationservice.DescribeEventSubscriptions", input)
return &DescribeEventSubscriptionsFuture{Future: future}
}
func (a *stub) DescribeEvents(ctx workflow.Context, input *databasemigrationservice.DescribeEventsInput) (*databasemigrationservice.DescribeEventsOutput, error) {
var output databasemigrationservice.DescribeEventsOutput
err := workflow.ExecuteActivity(ctx, "aws.databasemigrationservice.DescribeEvents", input).Get(ctx, &output)
return &output, err
}
func (a *stub) DescribeEventsAsync(ctx workflow.Context, input *databasemigrationservice.DescribeEventsInput) *DescribeEventsFuture {
future := workflow.ExecuteActivity(ctx, "aws.databasemigrationservice.DescribeEvents", input)
return &DescribeEventsFuture{Future: future}
}
func (a *stub) DescribeOrderableReplicationInstances(ctx workflow.Context, input *databasemigrationservice.DescribeOrderableReplicationInstancesInput) (*databasemigrationservice.DescribeOrderableReplicationInstancesOutput, error) {
var output databasemigrationservice.DescribeOrderableReplicationInstancesOutput
err := workflow.ExecuteActivity(ctx, "aws.databasemigrationservice.DescribeOrderableReplicationInstances", input).Get(ctx, &output)
return &output, err
}
func (a *stub) DescribeOrderableReplicationInstancesAsync(ctx workflow.Context, input *databasemigrationservice.DescribeOrderableReplicationInstancesInput) *DescribeOrderableReplicationInstancesFuture {
future := workflow.ExecuteActivity(ctx, "aws.databasemigrationservice.DescribeOrderableReplicationInstances", input)
return &DescribeOrderableReplicationInstancesFuture{Future: future}
}
func (a *stub) DescribePendingMaintenanceActions(ctx workflow.Context, input *databasemigrationservice.DescribePendingMaintenanceActionsInput) (*databasemigrationservice.DescribePendingMaintenanceActionsOutput, error) {
var output databasemigrationservice.DescribePendingMaintenanceActionsOutput
err := workflow.ExecuteActivity(ctx, "aws.databasemigrationservice.DescribePendingMaintenanceActions", input).Get(ctx, &output)
return &output, err
}
func (a *stub) DescribePendingMaintenanceActionsAsync(ctx workflow.Context, input *databasemigrationservice.DescribePendingMaintenanceActionsInput) *DescribePendingMaintenanceActionsFuture {
future := workflow.ExecuteActivity(ctx, "aws.databasemigrationservice.DescribePendingMaintenanceActions", input)
return &DescribePendingMaintenanceActionsFuture{Future: future}
}
func (a *stub) DescribeRefreshSchemasStatus(ctx workflow.Context, input *databasemigrationservice.DescribeRefreshSchemasStatusInput) (*databasemigrationservice.DescribeRefreshSchemasStatusOutput, error) {
var output databasemigrationservice.DescribeRefreshSchemasStatusOutput
err := workflow.ExecuteActivity(ctx, "aws.databasemigrationservice.DescribeRefreshSchemasStatus", input).Get(ctx, &output)
return &output, err
}
func (a *stub) DescribeRefreshSchemasStatusAsync(ctx workflow.Context, input *databasemigrationservice.DescribeRefreshSchemasStatusInput) *DescribeRefreshSchemasStatusFuture {
future := workflow.ExecuteActivity(ctx, "aws.databasemigrationservice.DescribeRefreshSchemasStatus", input)
return &DescribeRefreshSchemasStatusFuture{Future: future}
}
func (a *stub) DescribeReplicationInstanceTaskLogs(ctx workflow.Context, input *databasemigrationservice.DescribeReplicationInstanceTaskLogsInput) (*databasemigrationservice.DescribeReplicationInstanceTaskLogsOutput, error) {
var output databasemigrationservice.DescribeReplicationInstanceTaskLogsOutput
err := workflow.ExecuteActivity(ctx, "aws.databasemigrationservice.DescribeReplicationInstanceTaskLogs", input).Get(ctx, &output)
return &output, err
}
func (a *stub) DescribeReplicationInstanceTaskLogsAsync(ctx workflow.Context, input *databasemigrationservice.DescribeReplicationInstanceTaskLogsInput) *DescribeReplicationInstanceTaskLogsFuture {
future := workflow.ExecuteActivity(ctx, "aws.databasemigrationservice.DescribeReplicationInstanceTaskLogs", input)
return &DescribeReplicationInstanceTaskLogsFuture{Future: future}
}
func (a *stub) DescribeReplicationInstances(ctx workflow.Context, input *databasemigrationservice.DescribeReplicationInstancesInput) (*databasemigrationservice.DescribeReplicationInstancesOutput, error) {
var output databasemigrationservice.DescribeReplicationInstancesOutput
err := workflow.ExecuteActivity(ctx, "aws.databasemigrationservice.DescribeReplicationInstances", input).Get(ctx, &output)
return &output, err
}
func (a *stub) DescribeReplicationInstancesAsync(ctx workflow.Context, input *databasemigrationservice.DescribeReplicationInstancesInput) *DescribeReplicationInstancesFuture {
future := workflow.ExecuteActivity(ctx, "aws.databasemigrationservice.DescribeReplicationInstances", input)
return &DescribeReplicationInstancesFuture{Future: future}
}
func (a *stub) DescribeReplicationSubnetGroups(ctx workflow.Context, input *databasemigrationservice.DescribeReplicationSubnetGroupsInput) (*databasemigrationservice.DescribeReplicationSubnetGroupsOutput, error) {
var output databasemigrationservice.DescribeReplicationSubnetGroupsOutput
err := workflow.ExecuteActivity(ctx, "aws.databasemigrationservice.DescribeReplicationSubnetGroups", input).Get(ctx, &output)
return &output, err
}
func (a *stub) DescribeReplicationSubnetGroupsAsync(ctx workflow.Context, input *databasemigrationservice.DescribeReplicationSubnetGroupsInput) *DescribeReplicationSubnetGroupsFuture {
future := workflow.ExecuteActivity(ctx, "aws.databasemigrationservice.DescribeReplicationSubnetGroups", input)
return &DescribeReplicationSubnetGroupsFuture{Future: future}
}
func (a *stub) DescribeReplicationTaskAssessmentResults(ctx workflow.Context, input *databasemigrationservice.DescribeReplicationTaskAssessmentResultsInput) (*databasemigrationservice.DescribeReplicationTaskAssessmentResultsOutput, error) {
var output databasemigrationservice.DescribeReplicationTaskAssessmentResultsOutput
err := workflow.ExecuteActivity(ctx, "aws.databasemigrationservice.DescribeReplicationTaskAssessmentResults", input).Get(ctx, &output)
return &output, err
}
func (a *stub) DescribeReplicationTaskAssessmentResultsAsync(ctx workflow.Context, input *databasemigrationservice.DescribeReplicationTaskAssessmentResultsInput) *DescribeReplicationTaskAssessmentResultsFuture {
future := workflow.ExecuteActivity(ctx, "aws.databasemigrationservice.DescribeReplicationTaskAssessmentResults", input)
return &DescribeReplicationTaskAssessmentResultsFuture{Future: future}
}
func (a *stub) DescribeReplicationTaskAssessmentRuns(ctx workflow.Context, input *databasemigrationservice.DescribeReplicationTaskAssessmentRunsInput) (*databasemigrationservice.DescribeReplicationTaskAssessmentRunsOutput, error) {
var output databasemigrationservice.DescribeReplicationTaskAssessmentRunsOutput
err := workflow.ExecuteActivity(ctx, "aws.databasemigrationservice.DescribeReplicationTaskAssessmentRuns", input).Get(ctx, &output)
return &output, err
}
func (a *stub) DescribeReplicationTaskAssessmentRunsAsync(ctx workflow.Context, input *databasemigrationservice.DescribeReplicationTaskAssessmentRunsInput) *DescribeReplicationTaskAssessmentRunsFuture {
future := workflow.ExecuteActivity(ctx, "aws.databasemigrationservice.DescribeReplicationTaskAssessmentRuns", input)
return &DescribeReplicationTaskAssessmentRunsFuture{Future: future}
}
func (a *stub) DescribeReplicationTaskIndividualAssessments(ctx workflow.Context, input *databasemigrationservice.DescribeReplicationTaskIndividualAssessmentsInput) (*databasemigrationservice.DescribeReplicationTaskIndividualAssessmentsOutput, error) {
var output databasemigrationservice.DescribeReplicationTaskIndividualAssessmentsOutput
err := workflow.ExecuteActivity(ctx, "aws.databasemigrationservice.DescribeReplicationTaskIndividualAssessments", input).Get(ctx, &output)
return &output, err
}
func (a *stub) DescribeReplicationTaskIndividualAssessmentsAsync(ctx workflow.Context, input *databasemigrationservice.DescribeReplicationTaskIndividualAssessmentsInput) *DescribeReplicationTaskIndividualAssessmentsFuture {
future := workflow.ExecuteActivity(ctx, "aws.databasemigrationservice.DescribeReplicationTaskIndividualAssessments", input)
return &DescribeReplicationTaskIndividualAssessmentsFuture{Future: future}
}
func (a *stub) DescribeReplicationTasks(ctx workflow.Context, input *databasemigrationservice.DescribeReplicationTasksInput) (*databasemigrationservice.DescribeReplicationTasksOutput, error) {
var output databasemigrationservice.DescribeReplicationTasksOutput
err := workflow.ExecuteActivity(ctx, "aws.databasemigrationservice.DescribeReplicationTasks", input).Get(ctx, &output)
return &output, err
}
func (a *stub) DescribeReplicationTasksAsync(ctx workflow.Context, input *databasemigrationservice.DescribeReplicationTasksInput) *DescribeReplicationTasksFuture {
future := workflow.ExecuteActivity(ctx, "aws.databasemigrationservice.DescribeReplicationTasks", input)
return &DescribeReplicationTasksFuture{Future: future}
}
func (a *stub) DescribeSchemas(ctx workflow.Context, input *databasemigrationservice.DescribeSchemasInput) (*databasemigrationservice.DescribeSchemasOutput, error) {
var output databasemigrationservice.DescribeSchemasOutput
err := workflow.ExecuteActivity(ctx, "aws.databasemigrationservice.DescribeSchemas", input).Get(ctx, &output)
return &output, err
}
func (a *stub) DescribeSchemasAsync(ctx workflow.Context, input *databasemigrationservice.DescribeSchemasInput) *DescribeSchemasFuture {
future := workflow.ExecuteActivity(ctx, "aws.databasemigrationservice.DescribeSchemas", input)
return &DescribeSchemasFuture{Future: future}
}
func (a *stub) DescribeTableStatistics(ctx workflow.Context, input *databasemigrationservice.DescribeTableStatisticsInput) (*databasemigrationservice.DescribeTableStatisticsOutput, error) {
var output databasemigrationservice.DescribeTableStatisticsOutput
err := workflow.ExecuteActivity(ctx, "aws.databasemigrationservice.DescribeTableStatistics", input).Get(ctx, &output)
return &output, err
}
func (a *stub) DescribeTableStatisticsAsync(ctx workflow.Context, input *databasemigrationservice.DescribeTableStatisticsInput) *DescribeTableStatisticsFuture {
future := workflow.ExecuteActivity(ctx, "aws.databasemigrationservice.DescribeTableStatistics", input)
return &DescribeTableStatisticsFuture{Future: future}
}
func (a *stub) ImportCertificate(ctx workflow.Context, input *databasemigrationservice.ImportCertificateInput) (*databasemigrationservice.ImportCertificateOutput, error) {
var output databasemigrationservice.ImportCertificateOutput
err := workflow.ExecuteActivity(ctx, "aws.databasemigrationservice.ImportCertificate", input).Get(ctx, &output)
return &output, err
}
func (a *stub) ImportCertificateAsync(ctx workflow.Context, input *databasemigrationservice.ImportCertificateInput) *ImportCertificateFuture {
future := workflow.ExecuteActivity(ctx, "aws.databasemigrationservice.ImportCertificate", input)
return &ImportCertificateFuture{Future: future}
}
func (a *stub) ListTagsForResource(ctx workflow.Context, input *databasemigrationservice.ListTagsForResourceInput) (*databasemigrationservice.ListTagsForResourceOutput, error) {
var output databasemigrationservice.ListTagsForResourceOutput
err := workflow.ExecuteActivity(ctx, "aws.databasemigrationservice.ListTagsForResource", input).Get(ctx, &output)
return &output, err
}
func (a *stub) ListTagsForResourceAsync(ctx workflow.Context, input *databasemigrationservice.ListTagsForResourceInput) *ListTagsForResourceFuture {
future := workflow.ExecuteActivity(ctx, "aws.databasemigrationservice.ListTagsForResource", input)
return &ListTagsForResourceFuture{Future: future}
}
func (a *stub) ModifyEndpoint(ctx workflow.Context, input *databasemigrationservice.ModifyEndpointInput) (*databasemigrationservice.ModifyEndpointOutput, error) {
var output databasemigrationservice.ModifyEndpointOutput
err := workflow.ExecuteActivity(ctx, "aws.databasemigrationservice.ModifyEndpoint", input).Get(ctx, &output)
return &output, err
}
func (a *stub) ModifyEndpointAsync(ctx workflow.Context, input *databasemigrationservice.ModifyEndpointInput) *ModifyEndpointFuture {
future := workflow.ExecuteActivity(ctx, "aws.databasemigrationservice.ModifyEndpoint", input)
return &ModifyEndpointFuture{Future: future}
}
func (a *stub) ModifyEventSubscription(ctx workflow.Context, input *databasemigrationservice.ModifyEventSubscriptionInput) (*databasemigrationservice.ModifyEventSubscriptionOutput, error) {
var output databasemigrationservice.ModifyEventSubscriptionOutput
err := workflow.ExecuteActivity(ctx, "aws.databasemigrationservice.ModifyEventSubscription", input).Get(ctx, &output)
return &output, err
}
func (a *stub) ModifyEventSubscriptionAsync(ctx workflow.Context, input *databasemigrationservice.ModifyEventSubscriptionInput) *ModifyEventSubscriptionFuture {
future := workflow.ExecuteActivity(ctx, "aws.databasemigrationservice.ModifyEventSubscription", input)
return &ModifyEventSubscriptionFuture{Future: future}
}
func (a *stub) ModifyReplicationInstance(ctx workflow.Context, input *databasemigrationservice.ModifyReplicationInstanceInput) (*databasemigrationservice.ModifyReplicationInstanceOutput, error) {
var output databasemigrationservice.ModifyReplicationInstanceOutput
err := workflow.ExecuteActivity(ctx, "aws.databasemigrationservice.ModifyReplicationInstance", input).Get(ctx, &output)
return &output, err
}
func (a *stub) ModifyReplicationInstanceAsync(ctx workflow.Context, input *databasemigrationservice.ModifyReplicationInstanceInput) *ModifyReplicationInstanceFuture {
future := workflow.ExecuteActivity(ctx, "aws.databasemigrationservice.ModifyReplicationInstance", input)
return &ModifyReplicationInstanceFuture{Future: future}
}
func (a *stub) ModifyReplicationSubnetGroup(ctx workflow.Context, input *databasemigrationservice.ModifyReplicationSubnetGroupInput) (*databasemigrationservice.ModifyReplicationSubnetGroupOutput, error) {
var output databasemigrationservice.ModifyReplicationSubnetGroupOutput
err := workflow.ExecuteActivity(ctx, "aws.databasemigrationservice.ModifyReplicationSubnetGroup", input).Get(ctx, &output)
return &output, err
}
func (a *stub) ModifyReplicationSubnetGroupAsync(ctx workflow.Context, input *databasemigrationservice.ModifyReplicationSubnetGroupInput) *ModifyReplicationSubnetGroupFuture {
future := workflow.ExecuteActivity(ctx, "aws.databasemigrationservice.ModifyReplicationSubnetGroup", input)
return &ModifyReplicationSubnetGroupFuture{Future: future}
}
func (a *stub) ModifyReplicationTask(ctx workflow.Context, input *databasemigrationservice.ModifyReplicationTaskInput) (*databasemigrationservice.ModifyReplicationTaskOutput, error) {
var output databasemigrationservice.ModifyReplicationTaskOutput
err := workflow.ExecuteActivity(ctx, "aws.databasemigrationservice.ModifyReplicationTask", input).Get(ctx, &output)
return &output, err
}
func (a *stub) ModifyReplicationTaskAsync(ctx workflow.Context, input *databasemigrationservice.ModifyReplicationTaskInput) *ModifyReplicationTaskFuture {
future := workflow.ExecuteActivity(ctx, "aws.databasemigrationservice.ModifyReplicationTask", input)
return &ModifyReplicationTaskFuture{Future: future}
}
func (a *stub) RebootReplicationInstance(ctx workflow.Context, input *databasemigrationservice.RebootReplicationInstanceInput) (*databasemigrationservice.RebootReplicationInstanceOutput, error) {
var output databasemigrationservice.RebootReplicationInstanceOutput
err := workflow.ExecuteActivity(ctx, "aws.databasemigrationservice.RebootReplicationInstance", input).Get(ctx, &output)
return &output, err
}
func (a *stub) RebootReplicationInstanceAsync(ctx workflow.Context, input *databasemigrationservice.RebootReplicationInstanceInput) *RebootReplicationInstanceFuture {
future := workflow.ExecuteActivity(ctx, "aws.databasemigrationservice.RebootReplicationInstance", input)
return &RebootReplicationInstanceFuture{Future: future}
}
func (a *stub) RefreshSchemas(ctx workflow.Context, input *databasemigrationservice.RefreshSchemasInput) (*databasemigrationservice.RefreshSchemasOutput, error) {
var output databasemigrationservice.RefreshSchemasOutput
err := workflow.ExecuteActivity(ctx, "aws.databasemigrationservice.RefreshSchemas", input).Get(ctx, &output)
return &output, err
}
func (a *stub) RefreshSchemasAsync(ctx workflow.Context, input *databasemigrationservice.RefreshSchemasInput) *RefreshSchemasFuture {
future := workflow.ExecuteActivity(ctx, "aws.databasemigrationservice.RefreshSchemas", input)
return &RefreshSchemasFuture{Future: future}
}
func (a *stub) ReloadTables(ctx workflow.Context, input *databasemigrationservice.ReloadTablesInput) (*databasemigrationservice.ReloadTablesOutput, error) {
var output databasemigrationservice.ReloadTablesOutput
err := workflow.ExecuteActivity(ctx, "aws.databasemigrationservice.ReloadTables", input).Get(ctx, &output)
return &output, err
}
func (a *stub) ReloadTablesAsync(ctx workflow.Context, input *databasemigrationservice.ReloadTablesInput) *ReloadTablesFuture {
future := workflow.ExecuteActivity(ctx, "aws.databasemigrationservice.ReloadTables", input)
return &ReloadTablesFuture{Future: future}
}
func (a *stub) RemoveTagsFromResource(ctx workflow.Context, input *databasemigrationservice.RemoveTagsFromResourceInput) (*databasemigrationservice.RemoveTagsFromResourceOutput, error) {
var output databasemigrationservice.RemoveTagsFromResourceOutput
err := workflow.ExecuteActivity(ctx, "aws.databasemigrationservice.RemoveTagsFromResource", input).Get(ctx, &output)
return &output, err
}
func (a *stub) RemoveTagsFromResourceAsync(ctx workflow.Context, input *databasemigrationservice.RemoveTagsFromResourceInput) *RemoveTagsFromResourceFuture {
future := workflow.ExecuteActivity(ctx, "aws.databasemigrationservice.RemoveTagsFromResource", input)
return &RemoveTagsFromResourceFuture{Future: future}
}
func (a *stub) StartReplicationTask(ctx workflow.Context, input *databasemigrationservice.StartReplicationTaskInput) (*databasemigrationservice.StartReplicationTaskOutput, error) {
var output databasemigrationservice.StartReplicationTaskOutput
err := workflow.ExecuteActivity(ctx, "aws.databasemigrationservice.StartReplicationTask", input).Get(ctx, &output)
return &output, err
}
func (a *stub) StartReplicationTaskAsync(ctx workflow.Context, input *databasemigrationservice.StartReplicationTaskInput) *StartReplicationTaskFuture {
future := workflow.ExecuteActivity(ctx, "aws.databasemigrationservice.StartReplicationTask", input)
return &StartReplicationTaskFuture{Future: future}
}
func (a *stub) StartReplicationTaskAssessment(ctx workflow.Context, input *databasemigrationservice.StartReplicationTaskAssessmentInput) (*databasemigrationservice.StartReplicationTaskAssessmentOutput, error) {
var output databasemigrationservice.StartReplicationTaskAssessmentOutput
err := workflow.ExecuteActivity(ctx, "aws.databasemigrationservice.StartReplicationTaskAssessment", input).Get(ctx, &output)
return &output, err
}
func (a *stub) StartReplicationTaskAssessmentAsync(ctx workflow.Context, input *databasemigrationservice.StartReplicationTaskAssessmentInput) *StartReplicationTaskAssessmentFuture {
future := workflow.ExecuteActivity(ctx, "aws.databasemigrationservice.StartReplicationTaskAssessment", input)
return &StartReplicationTaskAssessmentFuture{Future: future}
}
func (a *stub) StartReplicationTaskAssessmentRun(ctx workflow.Context, input *databasemigrationservice.StartReplicationTaskAssessmentRunInput) (*databasemigrationservice.StartReplicationTaskAssessmentRunOutput, error) {
var output databasemigrationservice.StartReplicationTaskAssessmentRunOutput
err := workflow.ExecuteActivity(ctx, "aws.databasemigrationservice.StartReplicationTaskAssessmentRun", input).Get(ctx, &output)
return &output, err
}
func (a *stub) StartReplicationTaskAssessmentRunAsync(ctx workflow.Context, input *databasemigrationservice.StartReplicationTaskAssessmentRunInput) *StartReplicationTaskAssessmentRunFuture {
future := workflow.ExecuteActivity(ctx, "aws.databasemigrationservice.StartReplicationTaskAssessmentRun", input)
return &StartReplicationTaskAssessmentRunFuture{Future: future}
}
func (a *stub) StopReplicationTask(ctx workflow.Context, input *databasemigrationservice.StopReplicationTaskInput) (*databasemigrationservice.StopReplicationTaskOutput, error) {
var output databasemigrationservice.StopReplicationTaskOutput
err := workflow.ExecuteActivity(ctx, "aws.databasemigrationservice.StopReplicationTask", input).Get(ctx, &output)
return &output, err
}
func (a *stub) StopReplicationTaskAsync(ctx workflow.Context, input *databasemigrationservice.StopReplicationTaskInput) *StopReplicationTaskFuture {
future := workflow.ExecuteActivity(ctx, "aws.databasemigrationservice.StopReplicationTask", input)
return &StopReplicationTaskFuture{Future: future}
}
func (a *stub) TestConnection(ctx workflow.Context, input *databasemigrationservice.TestConnectionInput) (*databasemigrationservice.TestConnectionOutput, error) {
var output databasemigrationservice.TestConnectionOutput
err := workflow.ExecuteActivity(ctx, "aws.databasemigrationservice.TestConnection", input).Get(ctx, &output)
return &output, err
}
func (a *stub) TestConnectionAsync(ctx workflow.Context, input *databasemigrationservice.TestConnectionInput) *TestConnectionFuture {
future := workflow.ExecuteActivity(ctx, "aws.databasemigrationservice.TestConnection", input)
return &TestConnectionFuture{Future: future}
}
func (a *stub) WaitUntilEndpointDeleted(ctx workflow.Context, input *databasemigrationservice.DescribeEndpointsInput) error {
return workflow.ExecuteActivity(ctx, "aws.databasemigrationservice.WaitUntilEndpointDeleted", input).Get(ctx, nil)
}
func (a *stub) WaitUntilEndpointDeletedAsync(ctx workflow.Context, input *databasemigrationservice.DescribeEndpointsInput) *clients.VoidFuture {
future := workflow.ExecuteActivity(ctx, "aws.databasemigrationservice.WaitUntilEndpointDeleted", input)
return clients.NewVoidFuture(future)
}
func (a *stub) WaitUntilReplicationInstanceAvailable(ctx workflow.Context, input *databasemigrationservice.DescribeReplicationInstancesInput) error {
return workflow.ExecuteActivity(ctx, "aws.databasemigrationservice.WaitUntilReplicationInstanceAvailable", input).Get(ctx, nil)
}
func (a *stub) WaitUntilReplicationInstanceAvailableAsync(ctx workflow.Context, input *databasemigrationservice.DescribeReplicationInstancesInput) *clients.VoidFuture {
future := workflow.ExecuteActivity(ctx, "aws.databasemigrationservice.WaitUntilReplicationInstanceAvailable", input)
return clients.NewVoidFuture(future)
}
func (a *stub) WaitUntilReplicationInstanceDeleted(ctx workflow.Context, input *databasemigrationservice.DescribeReplicationInstancesInput) error {
return workflow.ExecuteActivity(ctx, "aws.databasemigrationservice.WaitUntilReplicationInstanceDeleted", input).Get(ctx, nil)
}
func (a *stub) WaitUntilReplicationInstanceDeletedAsync(ctx workflow.Context, input *databasemigrationservice.DescribeReplicationInstancesInput) *clients.VoidFuture {
future := workflow.ExecuteActivity(ctx, "aws.databasemigrationservice.WaitUntilReplicationInstanceDeleted", input)
return clients.NewVoidFuture(future)
}
func (a *stub) WaitUntilReplicationTaskDeleted(ctx workflow.Context, input *databasemigrationservice.DescribeReplicationTasksInput) error {
return workflow.ExecuteActivity(ctx, "aws.databasemigrationservice.WaitUntilReplicationTaskDeleted", input).Get(ctx, nil)
}
func (a *stub) WaitUntilReplicationTaskDeletedAsync(ctx workflow.Context, input *databasemigrationservice.DescribeReplicationTasksInput) *clients.VoidFuture {
future := workflow.ExecuteActivity(ctx, "aws.databasemigrationservice.WaitUntilReplicationTaskDeleted", input)
return clients.NewVoidFuture(future)
}
func (a *stub) WaitUntilReplicationTaskReady(ctx workflow.Context, input *databasemigrationservice.DescribeReplicationTasksInput) error {
return workflow.ExecuteActivity(ctx, "aws.databasemigrationservice.WaitUntilReplicationTaskReady", input).Get(ctx, nil)
}
func (a *stub) WaitUntilReplicationTaskReadyAsync(ctx workflow.Context, input *databasemigrationservice.DescribeReplicationTasksInput) *clients.VoidFuture {
future := workflow.ExecuteActivity(ctx, "aws.databasemigrationservice.WaitUntilReplicationTaskReady", input)
return clients.NewVoidFuture(future)
}
func (a *stub) WaitUntilReplicationTaskRunning(ctx workflow.Context, input *databasemigrationservice.DescribeReplicationTasksInput) error {
return workflow.ExecuteActivity(ctx, "aws.databasemigrationservice.WaitUntilReplicationTaskRunning", input).Get(ctx, nil)
}
func (a *stub) WaitUntilReplicationTaskRunningAsync(ctx workflow.Context, input *databasemigrationservice.DescribeReplicationTasksInput) *clients.VoidFuture {
future := workflow.ExecuteActivity(ctx, "aws.databasemigrationservice.WaitUntilReplicationTaskRunning", input)
return clients.NewVoidFuture(future)
}
func (a *stub) WaitUntilReplicationTaskStopped(ctx workflow.Context, input *databasemigrationservice.DescribeReplicationTasksInput) error {
return workflow.ExecuteActivity(ctx, "aws.databasemigrationservice.WaitUntilReplicationTaskStopped", input).Get(ctx, nil)
}
func (a *stub) WaitUntilReplicationTaskStoppedAsync(ctx workflow.Context, input *databasemigrationservice.DescribeReplicationTasksInput) *clients.VoidFuture {
future := workflow.ExecuteActivity(ctx, "aws.databasemigrationservice.WaitUntilReplicationTaskStopped", input)
return clients.NewVoidFuture(future)
}
func (a *stub) WaitUntilTestConnectionSucceeds(ctx workflow.Context, input *databasemigrationservice.DescribeConnectionsInput) error {
return workflow.ExecuteActivity(ctx, "aws.databasemigrationservice.WaitUntilTestConnectionSucceeds", input).Get(ctx, nil)
}
func (a *stub) WaitUntilTestConnectionSucceedsAsync(ctx workflow.Context, input *databasemigrationservice.DescribeConnectionsInput) *clients.VoidFuture {
future := workflow.ExecuteActivity(ctx, "aws.databasemigrationservice.WaitUntilTestConnectionSucceeds", input)
return clients.NewVoidFuture(future)
}
|
cmcormack/gcam-core
|
cvs/objects/target_finder/source/emissions_stabalization_target.cpp
|
<filename>cvs/objects/target_finder/source/emissions_stabalization_target.cpp
/*
* LEGAL NOTICE
* This computer software was prepared by Battelle Memorial Institute,
* hereinafter the Contractor, under Contract No. DE-AC05-76RL0 1830
* with the Department of Energy (DOE). NEITHER THE GOVERNMENT NOR THE
* CONTRACTOR MAKES ANY WARRANTY, EXPRESS OR IMPLIED, OR ASSUMES ANY
* LIABILITY FOR THE USE OF THIS SOFTWARE. This notice including this
* sentence must appear on any copies of this computer software.
*
* EXPORT CONTROL
* User agrees that the Software will not be shipped, transferred or
* exported into any country or used in any manner prohibited by the
* United States Export Administration Act or any other applicable
* export laws, restrictions or regulations (collectively the "Export Laws").
* Export of the Software may require some form of license or other
* authority from the U.S. Government, and failure to obtain such
* export control license may result in criminal liability under
* U.S. laws. In addition, if the Software is identified as export controlled
* items under the Export Laws, User represents and warrants that User
* is not a citizen, or otherwise located within, an embargoed nation
* (including without limitation Iran, Syria, Sudan, Cuba, and North Korea)
* and that User is not otherwise prohibited
* under the Export Laws from receiving the Software.
*
* Copyright 2011 Battelle Memorial Institute. All Rights Reserved.
* Distributed as open-source under the terms of the Educational Community
* License version 2.0 (ECL 2.0). http://www.opensource.org/licenses/ecl2.php
*
* For further details, see: http://www.globalchange.umd.edu/models/gcam/
*
*/
/*!
* \file emissions_stabalization_target.cpp
* \ingroup Objects
* \brief EmissionsStabalizationTarget class source file.
* \author <NAME>
*/
#include "util/base/include/definitions.h"
#include <cassert>
#include <string>
#include "containers/include/scenario.h"
#include "util/base/include/model_time.h"
#include "climate/include/iclimate_model.h"
#include "target_finder/include/emissions_stabalization_target.h"
#include "util/logger/include/ilogger.h"
#include "util/base/include/configuration.h"
#include "util/base/include/util.h"
extern Scenario* scenario;
using namespace std;
/*!
* \brief Constructor
* \param aClimateModel The climate model.
* \param aTargetValue The value of the target.
* \param aFirstTaxYear The first tax year.
*/
EmissionsStabalizationTarget::EmissionsStabalizationTarget(
const IClimateModel* aClimateModel,
const double aTargetValue,
const int aFirstTaxYear ):
mClimateModel( aClimateModel ),
mFirstTaxYear( aFirstTaxYear )
{
// Store configuration variables.
const Configuration* conf = Configuration::getInstance();
// FYI: the target gas read from the configuration appears to be
// ignored in the rest of this class.
mTargetGas = conf->getString( "concentration-target-gas", "CO2" );
}
/*!
* \brief Return the static name of the object.
* \return The static name of the object.
*/
const string& EmissionsStabalizationTarget::getXMLNameStatic(){
static const string XML_NAME = "emissions-balance-target";
return XML_NAME;
}
double EmissionsStabalizationTarget::getStatus( const int aYear ) const
{
// Determine the total system emissions. NOTE: Net terrestrial uptake
// includes land use emissions as a negative, so they are not added here as
// that would double account.
// NOTE: Assumes that net terrestrial uptake is not removed from industrial
// emissions.
// Make sure we are using the correct year.
const int year = aYear == ITarget::getUseMaxTargetYearFlag() ? getYearOfMaxTargetValue()
: aYear;
/*!
* \pre year must be greater than mFirstTaxYear otherwise we will have no
* ability to change the status in that year.
*/
assert( year >= mFirstTaxYear );
// Note that mClimateModel->getEmissions will not contain values until GCAM
// has solved for a given year.
double totalEmissions = mClimateModel->getEmissions( "CO2", year );
// Year can be between two years
double netOceanUp = mClimateModel->getNetOceanUptake( year );
double netTerrUp = mClimateModel->getNetTerrestrialUptake( year );
double totalNetUptake = netOceanUp + netTerrUp;
// Determine how how far away from the target the current estimate is.
double percentOff = objects::percentDiff( totalNetUptake, totalEmissions );
// Print an information message.
ILogger& targetLog = ILogger::getLogger( "target_finder_log" );
targetLog.setLevel( ILogger::NOTICE );
targetLog << "Currently " << percentOff
<< " percent away from the stabilization target. "
<< "Emissions: " << totalEmissions << " Total net uptake: "
<< totalNetUptake << endl;
return percentOff;
}
int EmissionsStabalizationTarget::getYearOfMaxTargetValue() const {
// TODO: I think realistically this is always the last year.
double minDiff = numeric_limits<double>::max();
const int finalYearToCheck = scenario->getModeltime()->getEndYear();
int minYear = mFirstTaxYear - 1;
// Loop over possible year and find the min difference in emisssions and the
// year it occurs in.
for( int year = mFirstTaxYear; year <= finalYearToCheck; ++year ) {
// Note that mClimateModel->getEmissions will not contain values until GCAM
// has solved for a given year.
double totalEmissions = mClimateModel->getEmissions( "CO2", year );
double netOceanUp = mClimateModel->getNetOceanUptake( year );
double netTerrUp = mClimateModel->getNetTerrestrialUptake( year );
double totalNetUptake = netOceanUp + netTerrUp;
double percentOff = objects::percentDiff( totalNetUptake, totalEmissions );
if( percentOff < minDiff ) {
minDiff = percentOff;
minYear = year;
}
}
return minYear;
}
|
anonfse/COSAL_Anonymized
|
code/src/main/python/haskell/blocks/haskell_function.py
|
import sys
import os
sys.path.append(os.path.abspath("."))
sys.dont_write_bytecode = True
__author__ = "COSAL"
from haskell.type_checking import haskell_type_checker
from analysis.helpers import execution_utils, helper
from utils import cache
from utils.lib import O
class HaskellFunction(O):
def __init__(self, **kwargs):
O.__init__(self, **kwargs)
self.name = helper.generate_function_name()
self.source_code_function_name = None
self.module = None
self.file_path = None
self.def_string = None
self.parameters = None
self.return_type = None
self.input_key = None
self.args_permutation = None
def clone(self):
cloned = HaskellFunction()
for k, v in self.__dict__.items():
cloned.__dict__[k] = v
cloned.name = helper.generate_function_name()
return cloned
def to_bson(self):
d = {
"name": self.name,
"isWholeMethod": True,
"sourceCodeFunctionName": self.source_code_function_name,
"module": self.module,
"filePath": cache.get_repo_local_path(self.file_path),
"defString": self.def_string,
"parameters": None,
"returnType": None,
"inputKey": self.input_key,
"argsPermutation": None
}
if self.parameters:
d["parameters"] = {str(index): typ.to_bson() if typ else None for index, typ in self.parameters.items()}
if self.args_permutation:
d["argsPermutation"] = HaskellFunction.encode_args_permutation(self.args_permutation)
if self.return_type:
d["returnType"] = self.return_type.to_bson()
return d
@staticmethod
def from_bson(bson_dict):
hs_func = HaskellFunction()
hs_func.name = bson_dict["name"]
hs_func.source_code_function_name = bson_dict.get("sourceCodeFunctionName", None)
hs_func.module = bson_dict.get("module", None)
hs_func.file_path = bson_dict.get("filePath", None)
hs_func.def_string = bson_dict.get("defString", None)
hs_func.input_key = bson_dict.get("inputKey", None)
params_json = bson_dict.get("parameters", None)
if params_json:
hs_func.parameters = {
int(index): from_types_bson(type_json) for index, type_json in params_json.items()
}
args_permutation = cache.get_absolute_path(bson_dict.get("argsPermutation", None))
if args_permutation:
hs_func.args_permutation = HaskellFunction.decode_args_permutation(args_permutation)
return hs_func
def is_valid(self):
return self.parameters is not None and self.return_type is not None
# @staticmethod
# def parse
def get_input_args_types_as_str(self, format_type="dict"):
"""
:param format_type: dict | lst | str
:return:
"""
if not self.parameters:
return None
if format_type == "dict":
return {i: haskell_type_checker.BaseType.to_type_key(arg_type) for i, arg_type in self.parameters.items()}
as_lst = [haskell_type_checker.BaseType.to_type_key(self.parameters[arg_index]) for arg_index in sorted(self.parameters.keys())]
if format_type == "str":
return str(as_lst)
return as_lst
def set_types(self, function_def_string):
self.def_string = function_def_string.replace("\\n'", "")
type_meta = haskell_type_checker.parse_type(self.def_string)
# print(function_def_string)
if not type_meta:
return
if type_meta["arg_types"]:
self.parameters = {i: arg_type for i, arg_type in enumerate(type_meta["arg_types"])}
self.return_type = type_meta["return_type"]
self.input_key = self.get_input_key()
# print(self.types)
# print(self.return_type)
# print("")
def get_args_and_keys(self):
input_arg_types = self.get_input_args_types_as_str(format_type="dict")
if not input_arg_types:
return None
return [{"name": i, "key": arg_type} for i, arg_type in input_arg_types.items()]
def _get_grouped_arg_keys(self):
args_and_keys = self.get_args_and_keys()
if not args_and_keys:
return args_and_keys
for arg_and_key in args_and_keys:
if not arg_and_key["key"]:
return None
return execution_utils.group_arg_and_key(args_and_keys)
def get_input_key(self):
grouped_arg_keys = self._get_grouped_arg_keys()
if not grouped_arg_keys or execution_utils.has_too_many_arguments(grouped_arg_keys):
return None
return execution_utils.get_function_args_key(grouped_arg_keys)
def permutate_args(self):
grouped_arg_keys = self._get_grouped_arg_keys()
if grouped_arg_keys:
return execution_utils.permutate_args_and_key(grouped_arg_keys)
return None
def __repr__(self):
return """
Name: %s
Definition: %s
Types: %s
Return Type: %s
Input Key: %s
Args Permutation: %s
""" % (self.name, self.def_string, self.get_input_args_types_as_str("str"),
haskell_type_checker.BaseType.to_type_key(self.return_type) if self.return_type else None,
self.input_key, self.args_permutation)
@staticmethod
def encode_args_permutation(permutation):
return {k.replace(".", "$"): v for k, v in permutation.items()}
@staticmethod
def decode_args_permutation(permutation):
return {k.replace("$", "."): v for k, v in permutation.items()}
def from_types_bson(bson_dict):
if not bson_dict:
return None
slacc_type = bson_dict.get("slacc_type", None)
if not slacc_type:
raise RuntimeError("'slacc_type' key not found in bson_dict: %s" % bson_dict)
method_name = "from_%s_bson" % slacc_type
method_to_call = getattr(sys.modules[__name__], method_name, None)
if not method_to_call:
raise RuntimeError("@COSAL: Invalid slacc_type: '%s'" % slacc_type)
return method_to_call(bson_dict)
def from_BaseType_bson(bson_dict):
o = haskell_type_checker.BaseType(bson_dict["name"])
o.is_valid = bson_dict['is_valid']
return o
def from_PrimitiveType_bson(bson_dict):
o = haskell_type_checker.PrimitiveType(bson_dict["name"])
o.is_valid = bson_dict['is_valid']
return o
def from_ArrayType_bson(bson_dict):
type_bson = bson_dict.get("type", None)
typ = None
if type_bson:
typ = from_types_bson(type_bson)
o = haskell_type_checker.ArrayType(typ)
o.is_valid = bson_dict['is_valid']
return o
def from_TupleType_bson(bson_dict):
o = haskell_type_checker.TupleType()
o.is_valid = bson_dict['is_valid']
o.types = [from_types_bson(t) for t in bson_dict['types']] if 'types' in bson_dict else None
return o
def permutate_function(haskell_function):
args_permutations = haskell_function.permutate_args()
if args_permutations is None:
return [haskell_function]
permutations = []
for args_permutation in args_permutations:
cloned = haskell_function.clone()
cloned.args_permutation = args_permutation
permutations.append(cloned)
return permutations
|
sakshamsingh1/fleet-sim
|
src/agent/dispatch_policy.py
|
from common import vehicle_status_codes
# from .services.demand_prediction_service import DemandPredictionService
from config.settings import TIMESTEP, MIN_DISPATCH_CYCLE, MAX_DISPATCH_CYCLE
import numpy as np
class DispatchPolicy(object):
def __init__(self):
# self.demand_predictor = DemandPredictionService()
self.updated_at = {}
def dispatch(self, current_time, vehicles):
self.update_state(current_time, vehicles)
tbd_vehicles = self.get_tbd_vehicles(vehicles, current_time)
if len(tbd_vehicles) == 0:
return []
commands = self.get_commands(tbd_vehicles)
self.record_dispatch(tbd_vehicles.index, current_time)
return commands
def update_state(self, current_time, vehicles):
pass
def get_commands(self, tbd_vehicles):
return []
def get_tbd_vehicles(self, vehicles, current_time):
idle_vehicles = vehicles[vehicles.status == vehicle_status_codes.IDLE]
cruising_vehicles = vehicles[vehicles.status == vehicle_status_codes.CRUISING]
tbd_idle_vehicles = idle_vehicles.loc[[
vehicle_id for vehicle_id in idle_vehicles.index
if current_time - self.updated_at.get(vehicle_id, 0) >= MIN_DISPATCH_CYCLE
]]
tbd_cruising_vehicles = cruising_vehicles.loc[[
vehicle_id for vehicle_id in cruising_vehicles.index
if current_time - self.updated_at.get(vehicle_id, 0) >= MAX_DISPATCH_CYCLE
]]
tbd_vehicles = tbd_idle_vehicles.append(tbd_cruising_vehicles)
max_n = int(len(vehicles) / MIN_DISPATCH_CYCLE * TIMESTEP)
if len(tbd_vehicles) > max_n:
p = np.random.permutation(len(tbd_vehicles))
tbd_vehicles = tbd_vehicles.iloc[p[:max_n]]
return tbd_vehicles
def record_dispatch(self, vehicle_ids, current_time):
for vehicle_id in vehicle_ids:
self.updated_at[vehicle_id] = current_time
def create_command(self, vehicle_id, destination=None, offduty=False, cache_key=None):
command = {}
command["vehicle_id"] = vehicle_id
if offduty:
command["offduty"] = True
elif cache_key is not None:
command["cache"] = cache_key
else:
command["destination"] = destination
return command
|
roscopecoltran/SniperKit-Core
|
Toolkits/Discovery/meta/searx/searx/engines/qwant.py
|
"""
Qwant (Web, Images, News, Social)
@website https://qwant.com/
@provide-api not officially (https://api.qwant.com/api/search/)
@using-api yes
@results JSON
@stable yes
@parse url, title, content
"""
from datetime import datetime
from json import loads
from searx.utils import html_to_text
from searx.url_utils import urlencode
# engine dependent config
categories = None
paging = True
language_support = True
supported_languages_url = 'https://qwant.com/region'
category_to_keyword = {'general': 'web',
'images': 'images',
'news': 'news',
'social media': 'social'}
# search-url
url = 'https://api.qwant.com/api/search/{keyword}?count=10&offset={offset}&f=&{query}'
# do search-request
def request(query, params):
offset = (params['pageno'] - 1) * 10
if categories[0] and categories[0] in category_to_keyword:
params['url'] = url.format(keyword=category_to_keyword[categories[0]],
query=urlencode({'q': query}),
offset=offset)
else:
params['url'] = url.format(keyword='web',
query=urlencode({'q': query}),
offset=offset)
# add language tag if specified
if params['language'] != 'all':
if params['language'] == 'no' or params['language'].startswith('no-'):
params['language'] = params['language'].replace('no', 'nb', 1)
if params['language'].find('-') < 0:
# tries to get a country code from language
for lang in supported_languages:
lc = lang.split('-')
if params['language'] == lc[0]:
params['language'] = lang
break
params['url'] += '&locale=' + params['language'].replace('-', '_').lower()
return params
# get response from search-request
def response(resp):
results = []
search_results = loads(resp.text)
# return empty array if there are no results
if 'data' not in search_results:
return []
data = search_results.get('data', {})
res = data.get('result', {})
# parse results
for result in res.get('items', {}):
title = html_to_text(result['title'])
res_url = result['url']
content = html_to_text(result['desc'])
if category_to_keyword.get(categories[0], '') == 'web':
results.append({'title': title,
'content': content,
'url': res_url})
elif category_to_keyword.get(categories[0], '') == 'images':
thumbnail_src = result['thumbnail']
img_src = result['media']
results.append({'template': 'images.html',
'url': res_url,
'title': title,
'content': '',
'thumbnail_src': thumbnail_src,
'img_src': img_src})
elif category_to_keyword.get(categories[0], '') == 'social':
published_date = datetime.fromtimestamp(result['date'], None)
img_src = result.get('img', None)
results.append({'url': res_url,
'title': title,
'publishedDate': published_date,
'content': content,
'img_src': img_src})
elif category_to_keyword.get(categories[0], '') == 'news':
published_date = datetime.fromtimestamp(result['date'], None)
media = result.get('media', [])
if len(media) > 0:
img_src = media[0].get('pict', {}).get('url', None)
else:
img_src = None
results.append({'url': res_url,
'title': title,
'publishedDate': published_date,
'content': content,
'img_src': img_src})
return results
# get supported languages from their site
def _fetch_supported_languages(resp):
# list of regions is embedded in page as a js object
response_text = resp.text
response_text = response_text[response_text.find('regionalisation'):]
response_text = response_text[response_text.find('{'):response_text.find(');')]
regions_json = loads(response_text)
supported_languages = []
for lang in regions_json['languages'].values():
if lang['code'] == 'nb':
lang['code'] = 'no'
for country in lang['countries']:
supported_languages.append(lang['code'] + '-' + country)
return supported_languages
|
Milerius/bsf
|
Source/Foundation/bsfUtility/ThirdParty/simdpp/detail/insn/f_reduce_max.h
|
<filename>Source/Foundation/bsfUtility/ThirdParty/simdpp/detail/insn/f_reduce_max.h<gh_stars>1000+
/* Copyright (C) 2016 <NAME> <<EMAIL>>
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef LIBSIMDPP_SIMDPP_DETAIL_INSN_F_REDUCE_MAX_H
#define LIBSIMDPP_SIMDPP_DETAIL_INSN_F_REDUCE_MAX_H
#ifndef LIBSIMDPP_SIMD_H
#error "This file must be included through simd.h"
#endif
#include <simdpp/types.h>
#include <simdpp/core/extract.h>
#include <simdpp/core/f_max.h>
#include <simdpp/core/permute2.h>
#include <simdpp/detail/extract128.h>
#include <simdpp/detail/workarounds.h>
namespace simdpp {
namespace SIMDPP_ARCH_NAMESPACE {
namespace detail {
namespace insn {
static SIMDPP_INL
float i_reduce_max(const float32x4& a)
{
#if SIMDPP_USE_NULL || SIMDPP_USE_NEON_NO_FLT_SP
float r = a.el(0);
for (unsigned i = 1; i < a.length; i++) {
r = r > a.el(i) ? r : a.el(i); // TODO nan
}
return r;
#elif SIMDPP_USE_SSE2
float32x4 b = _mm_movehl_ps(a.native(), a.native());
b = max(a, b);
b = max(b, permute2<1,1>(b));
return _mm_cvtss_f32(b.native());
#elif SIMDPP_USE_NEON64
return vmaxnmvq_f32(a.native());
#elif SIMDPP_USE_NEON_FLT_SP
float32x2_t a2 = vpmax_f32(vget_low_f32(a.native()), vget_high_f32(a.native()));
a2 = vpmax_f32(a2, a2);
return vget_lane_f32(a2, 0);
#elif SIMDPP_USE_ALTIVEC || SIMDPP_USE_MSA
float32x4 b = a;
b = max(b, move4_l<1>(b));
b = max(b, move4_l<2>(b));
return extract<0>(b);
#endif
}
#if SIMDPP_USE_AVX
static SIMDPP_INL
float i_reduce_max(const float32x8& a)
{
float32x4 ah = detail::extract128<1>(a);
float32x4 al = detail::extract128<0>(a);
al = max(al, ah);
return i_reduce_max(al);
}
#endif
#if SIMDPP_USE_AVX512F
static SIMDPP_INL
float i_reduce_max(const float32<16>& a)
{
return i_reduce_max(max(extract256<0>(a), extract256<1>(a)));
}
#endif
template<unsigned N>
SIMDPP_INL float i_reduce_max(const float32<N>& a)
{
float32v r = a.vec(0);
for (unsigned i = 1; i < a.vec_length; ++i)
r = max(r, a.vec(i));
return i_reduce_max(r);
}
// -----------------------------------------------------------------------------
static SIMDPP_INL
double i_reduce_max(const float64x2& a)
{
#if SIMDPP_USE_SSE2
float64x2 b = max(a, permute2<1,1>(a));
return _mm_cvtsd_f64(b.native());
#elif SIMDPP_USE_NEON64
return vmaxnmvq_f64(a.native());
#elif SIMDPP_USE_VSX_206 || SIMDPP_USE_MSA
float64x2 b = max(a, permute2<1,1>(a));
return extract<0>(b);
#elif SIMDPP_USE_NULL || SIMDPP_USE_NEON32 || SIMDPP_USE_ALTIVEC
double r = a.el(0);
for (unsigned i = 1; i < a.length; i++) {
r = r > a.el(i) ? r : a.el(i); // TODO nan
}
return r;
#endif
}
#if SIMDPP_USE_AVX
static SIMDPP_INL
double i_reduce_max(const float64x4& a)
{
float64x2 ah = detail::extract128<1>(a);
float64x2 al = detail::extract128<0>(a);
al = max(al, ah);
return i_reduce_max(al);
}
#endif
#if SIMDPP_USE_AVX512F
static SIMDPP_INL
double i_reduce_max(const float64<8>& a)
{
return i_reduce_max(max(extract256<0>(a), extract256<1>(a)));
}
#endif
template<unsigned N>
SIMDPP_INL double i_reduce_max(const float64<N>& a)
{
float64v r = a.vec(0);
for (unsigned i = 1; i < a.vec_length; ++i)
r = max(r, a.vec(i));
return i_reduce_max(r);
}
} // namespace insn
} // namespace detail
} // namespace SIMDPP_ARCH_NAMESPACE
} // namespace simdpp
#endif
|
18106960985/qiyue-framework
|
framework-common/src/main/java/com/qiyue/common/request/BaseController.java
|
package com.qiyue.common.request;
import com.qiyue.orm.jpa.dao.BaseService;
import com.qiyue.utils.ResultUtils;
import com.qiyue.vo.Result;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
/**
* Created by y747718944 on 2018/1/23
*/
public class BaseController<Biz extends BaseService,Entity> {
private final static Logger logger= LoggerFactory.getLogger(BaseController.class);
@Autowired
protected HttpServletRequest request;
@Autowired
protected Biz baseBiz;
@ApiOperation(value = "主键查询",notes = "主键查询")
@GetMapping("/{id}")
public Result<Entity> get(
@ApiParam(name = "id", value ="主键", defaultValue = "")
@PathVariable Long id){
Object o= baseBiz.findOne(id);
return ResultUtils.getResult((Entity)o);
}
@ApiOperation(value = "新增",notes = "新增")
@PostMapping("/{id}")
public Result save(
@ApiParam(name = "entity", value ="实体类", defaultValue = "")
@RequestBody Entity entity){
baseBiz.save(entity);
return ResultUtils.success("新增成功!") ;
}
@ApiOperation(value = "更新",notes = "更新")
@PutMapping("/{id}")
public Result update(
@ApiParam(name = "entity", value ="实体类", defaultValue = "")
@RequestBody Entity entity){
baseBiz.save(entity);
return ResultUtils.success("更新成功!");
}
@ApiOperation(value = "单个删除",notes = "主键删除")
@DeleteMapping("/{id}")
public Result remove(
@ApiParam(name = "id", value ="主键删除", defaultValue = "")
@PathVariable Long id){
baseBiz.delete(id);
return ResultUtils.success("删除成功!");
}
@ApiOperation(value = "分页查询",notes = "根据条件进行分页查询")
@GetMapping("/all")
public Result<Entity> searchAll(
@ApiParam(name = "filters", value = "过滤器,为空检索所有条件", defaultValue = "")
@RequestParam(value = "filters", required = false) String filters){
List<Entity> result=baseBiz.search(filters);
return ResultUtils.getResult(result);
}
@ApiOperation(value = "分页查询",notes = "根据条件进行分页查询")
@GetMapping("/page")
public Result<Entity> searchPage(
@ApiParam(name = "filters", value = "过滤器,为空检索所有条件", defaultValue = "")
@RequestParam(value = "filters", required = false) String filters,
@ApiParam(name = "sorts", value = "排序,规则参见说明文档", defaultValue = "")
@RequestParam(value = "sorts", required = false) String sorts,
@ApiParam(name = "size", value = "分页大小", defaultValue = "15")
@RequestParam(value = "size", required = false) int size,
@ApiParam(name = "page", value = "页码", defaultValue = "1")
@RequestParam(value = "page", required = false) int page){
Page<Entity> result=baseBiz.search(filters,sorts,page,size);
return ResultUtils.getResult(result);
}
}
|
TeamSPoon/CYC_JRTL_with_CommonLisp_OLD
|
platform/main/telnetd-2.0/net/wimpi/telnetd/io/Templates.java
|
/***
* Java TelnetD library (embeddable telnet daemon)
* Copyright (c) <NAME>
* 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 the author 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 HOLDER 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 REGENTS 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.
***/
package net.wimpi.telnetd.io;
import java.util.Iterator;
import java.util.Locale;
/**
* Defines an interface for working with templates.
* <p>
* Implementations provide utility methods to help
* with localized, formatted and styled terminal output:
* <ul>
* <li>Template (static, no runtime attributes)</li>
* <li>Template (dynamic, with runtime attributes)</li>
* <li>Style (a template that <em>just</em> applies style to)</li>
* </ul>
* Note that templates might call and emply style templates. The two are
* just separated to break down the complexity.
* </p>
*
* @author <NAME> (wimpi)
* @version @version@ (@date@)
* @see TemplatesUpdateListener
*/
public interface Templates {
/**
* Reloads all available template files.
*
* @return true if successfull, false otherwise.
*/
public boolean reloadTemplates();
/**
* Reloads the styles.
*
* @return true if successful, false otherwise.
*/
public boolean reloadStyles();
/**
* Register a {@link TemplatesUpdateListener} that
* will be notified on template updates.
*
* @param l a {@link TemplatesUpdateListener} instance.
*/
public void registerUpdateListener(TemplatesUpdateListener l);
/**
* Removes a formerly registered {@link TemplatesUpdateListener}
* instance.
*
* @param l a {@link TemplatesUpdateListener} instance.
*/
public void removeUpdateListener(TemplatesUpdateListener l);
/**
* Returns an iterator over available languages.
*
* @return an <tt>Iterator</tt> instance.
*/
public Iterator getLanguages();
/**
* Returns the index of the given language, or
* -1 if the language is not found.
* <p/>
* Note that the returned String should be an ISO
* two letter language code, as accepted by
* the Locale.
* </p>
*
* @param str the ISO two letter language code.
* @return the index of the language as <tt>int</tt>.
*/
public int getIndexOfLanguage(String str);
/**
* Returns the index of the given language, or
* -1 if the language is not found.
* <p/>
* Note that the returned String should be an ISO
* two letter language code, as accepted by
* the Locale.
* </p>
*
* @param l a <tt>Locale</tt> instance that can return the ISO
* two letter language code.
* @return the index of the language as <tt>int</tt>.
*/
public int getIndexOfLanguage(Locale l);
/**
* Returns the ISO two letter code of the
* language at the given index.
*
* @param i the index of the language.
* @return the ISO two letter code of the language.
* @throws IndexOutOfBoundsException if the index is
* out of bounds.
*/
public String getLanguageCode(int i);
/**
* Fetches the templates for all available languages and
* returns an array of formatted strings.
*
* @param tkey the template key.
* @param attr the attributes for the template.
* @return an array of formatted strings with markups (if required).
*/
public String[] formatAll(String tkey, TemplateAttributes attr);
/**
* Fetches the templates for all available languages and
* returns an array of formatted strings.
* <p/>
* This is a convenience method that will call
* {@link #formatAll(String,TemplateAttributes)}
* with <tt>null</tt> for the attributes reference.
*
* @param tkey the template key.
* @return an array of formatted strings with markups (if required).
*/
public String[] formatAll(String tkey);
/**
* Fetches the template specified by the given key and
* language and returns a formatted string.
* Note that the language will automatically fall back to the
* default if a wrong language is specified.
* This is a convenience method that will call
* {@link #formatAll(String,net.wimpi.telnetd.io.TemplateAttributes)}
* with <tt>null</tt> for the attributes reference.
*
* @param lang the language index.
* @param tkey the template key.
* @return the string formatted with markups (if required).
*/
public String format(int lang, String tkey);
/**
* Fetches the template specified by the given key and
* language, fills in the attributes and returns a formatted
* string.
* <p/>
* Note that dynamic templates will be pooled and that the operation
* will automatically release the template attributes, that should have been
* obtained using {@link #leaseAttributes()}.<br/>
* Static templates will not cost more then the lookup for a String reference
* in a hashmap (they are cached).
* </p>
* Note also that the language will automatically fall back to the
* default if a wrong language is specified.<br/>
*
* @param lang the language index.
* @param tkey the template key.
* @param attr the attributes for the template.
* @return the string formatted with markups (if required).
* @see #leaseAttributes()
*/
public String format(int lang, String tkey, TemplateAttributes attr);
/**
* Tests if a given style is defined.
*
* @param name the name of the style.
* @return true if defined, false otherwise.
*/
public boolean isStyleDefined(String name);
/**
* Formats a given content with the given style.
* If the style is not defined, the content will be returned
* unmodified.
*
* @param content the content to be formatted.
* @param style the style to be used.
* @return the formatted content.
*/
public String formatStyle(String content, String style);
/**
* Returns a leased {@link TemplateAttributes} instance.
* This instance should be used immediately and passed to
* {@link #format(int,String,TemplateAttributes)}, which will
* recycle the instance returning it to the originating pool.
*
* @return a {@link net.wimpi.telnetd.io.TemplateAttributes} instance.
*/
public TemplateAttributes leaseAttributes();
}//interface Templates
|
michael-hampton/tamtamcrm
|
resources/assets/js/components/models/InvoiceCalculations.js
|
import axios from 'axios'
import moment from 'moment'
import BaseModel, { LineItem } from './BaseModel'
import { consts } from '../utils/_consts'
import { roundNumber } from '../utils/_formatting'
export const invoice_pdf_fields = ['$invoice.number', '$invoice.po_number', '$invoice.invoice_date', '$invoice.invoice_datetime', '$invoice.invoice_status', '$invoice.invoice_agent', '$invoice.due_date',
'$invoice.balance', '$invoice.invoice_total', '$invoice.partial_due', '$invoice.custom1', '$invoice.custom2', '$invoice.custom3',
'$invoice.custom4', '$invoice.surcharge1', '$invoice.surcharge2', '$invoice.surcharge3', '$invoice.surcharge4'
]
export default {
_calculateTaxAmount (amount, rate, useInclusiveTaxes, precision = 2) {
let taxAmount
if (useInclusiveTaxes) {
taxAmount = amount - (amount / (1 + (rate / 100)))
} else {
taxAmount = amount * rate / 100
}
return roundNumber(taxAmount, precision)
},
calculateSubtotal (precision = 2) {
let total = 0.0
this.fields.line_items.map((item) => {
const qty = roundNumber(item.quantity, 4)
const cost = roundNumber(item.unit_price, 4)
if (!qty || !cost) {
return 0
}
const discount = roundNumber(item.unit_discount, precision)
let lineTotal = qty * cost
if (discount !== 0) {
if (this.fields.is_amount_discount) {
lineTotal -= discount
} else {
lineTotal -= roundNumber(lineTotal * discount / 100, 4)
}
}
total += roundNumber(lineTotal, precision)
})
return total
},
getItemTaxable (item, invoiceTotal, precision = 2) {
const qty = roundNumber(item.quantity, 4)
const cost = roundNumber(item.unit_price, 4)
const itemDiscount = roundNumber(item.unit_discount, precision)
let lineTotal = qty * cost
if (this.fields.discount > 0) {
if (this.fields.is_amount_discount) {
if (invoiceTotal > 0) {
lineTotal -= roundNumber(lineTotal / invoiceTotal * this.fields.discount, 4)
}
}
}
if (itemDiscount > 0) {
if (this.fields.is_amount_discount) {
lineTotal -= itemDiscount
} else {
lineTotal -= roundNumber(lineTotal * itemDiscount / 100, 4)
}
}
return lineTotal
},
calculateTaxes (usesInclusiveTaxes, precision = 2) {
let total = this.calculateSubtotal(precision)
let taxAmount = 0
this.fields.line_items.map((item) => {
const taxRate1 = roundNumber(item.unit_tax, 3)
const taxRate2 = roundNumber(item.tax_2, 3)
const taxRate3 = roundNumber(item.tax_3, 3)
const lineTotal = this.getItemTaxable(item, total, precision)
if (taxRate1 > 0) {
taxAmount += this._calculateTaxAmount(
lineTotal, taxRate1, this.settings.inclusive_taxes, precision)
}
if (taxRate2 > 0) {
taxAmount += this._calculateTaxAmount(
lineTotal, taxRate2, this.settings.inclusive_taxes, precision)
}
if (taxRate3 > 0) {
taxAmount += this._calculateTaxAmount(
lineTotal, taxRate3, this.settings.inclusive_taxes, precision)
}
})
if (this.fields.discount > 0) {
if (this.fields.is_amount_discount) {
total -= roundNumber(this.fields.discount, precision)
} else {
total -= roundNumber(total * this.fields.discount / 100, precision)
}
}
if (this.fields.shipping_cost > 0 && this.fields.shipping_cost_tax > 0) {
total += roundNumber(this.fields.shipping_cost, precision)
}
if (this.fields.transaction_fee > 0 && this.fields.transaction_fee_tax > 0) {
total += roundNumber(this.fields.transaction_fee, precision)
}
if (this.fields.tax_rate > 0) {
taxAmount +=
this._calculateTaxAmount(total, this.fields.tax_rate, this.settings.inclusive_taxes, precision)
}
if (this.fields.tax_2 > 0) {
taxAmount +=
this._calculateTaxAmount(total, this.fields.tax_2, this.settings.inclusive_taxes, precision)
}
if (this.fields.tax_3 > 0) {
taxAmount +=
this._calculateTaxAmount(total, this.fields.tax_3, this.settings.inclusive_taxes, precision)
}
return roundNumber(taxAmount, precision)
},
calculateTax (tax_amount) {
const a_total = parseFloat(this.fields.total)
const tax_percentage = parseFloat(a_total) * parseFloat(tax_amount) / 100
const precision = this.currency.precision || 2
return Math.round(tax_percentage, precision)
},
calculateTotal (precision = 2) {
let total = this.calculateSubtotal(precision)
const sub_total = total
let itemTax = 0.0
let discount_total = 0
this.fields.line_items.map((item) => {
const qty = roundNumber(item.quantity, 4)
const cost = roundNumber(item.unit_price, 4)
const itemDiscount = roundNumber(item.unit_discount, precision)
const taxRate1 = roundNumber(item.unit_tax, 3)
const taxRate2 = roundNumber(item.tax_2, 3)
const taxRate3 = roundNumber(item.tax_3, 3)
let lineTotal = qty * cost
if (itemDiscount > 0) {
if (this.fields.is_amount_discount) {
discount_total += itemDiscount
lineTotal -= itemDiscount
} else {
const discount = roundNumber(lineTotal * itemDiscount / 100, 4)
discount_total += discount
lineTotal -= discount
}
}
if (this.fields.discount > 0) {
if (this.fields.is_amount_discount) {
if (total > 0) {
const discount = roundNumber(lineTotal / total * this.fields.discount, 4)
discount_total += discount
lineTotal -= discount
}
}
}
if (taxRate1 > 0) {
itemTax += roundNumber(lineTotal * taxRate1 / 100, precision)
}
if (taxRate2 > 0) {
itemTax += roundNumber(lineTotal * taxRate2 / 100, precision)
}
if (taxRate3 > 0) {
itemTax += roundNumber(lineTotal * taxRate2 / 100, precision)
}
})
if (this.fields.discount > 0) {
if (this.fields.is_amount_discount) {
const discount = roundNumber(this.fields.discount, precision)
discount_total += discount
total -= discount
} else {
const discount = roundNumber(total * this.fields.discount / 100, precision)
discount_total += discount
total -= discount
}
}
if (this.fields.shipping_cost > 0 && this.fields.shipping_cost_tax) {
total += roundNumber(this.fields.shipping_cost, precision)
}
if (this.fields.transaction_fee > 0 && this.fields.transaction_fee_tax) {
total += roundNumber(this.fields.transaction_fee, precision)
}
if (!this.settings.inclusive_taxes) {
const taxAmount1 = roundNumber(total * this.fields.tax_rate / 100, precision)
const taxAmount2 = roundNumber(total * this.fields.tax_2 / 100, precision)
const taxAmount3 = roundNumber(total * this.fields.tax_3 / 100, precision)
total += itemTax + taxAmount1 + taxAmount2 + taxAmount3
}
if (this.fields.shipping_cost > 0 && !this.fields.shipping_cost_tax) {
total += roundNumber(this.fields.shipping_cost, precision)
}
if (this.fields.transaction_fee > 0 && !this.fields.transaction_fee_tax) {
total += roundNumber(this.fields.transaction_fee, precision)
}
return {
total: total,
sub_total: sub_total,
discount_total: discount_total
}
}
}
|
dksan23/Nucleus
|
src/mme-app/procedureStats.cpp
|
<reponame>dksan23/Nucleus<filename>src/mme-app/procedureStats.cpp
/*
* Copyright (c) 2019, Infosys Ltd.
*
* SPDX-License-Identifier: Apache-2.0
*/
#include "procedureStats.h"
using namespace mme;
int ProcedureStats::num_of_air_sent = 0;
int ProcedureStats::num_of_ulr_sent = 0;
int ProcedureStats::num_of_processed_aia = 0;
int ProcedureStats::num_of_processed_ula = 0;
int ProcedureStats::num_of_auth_req_to_ue_sent = 0;
int ProcedureStats::num_of_processed_auth_response = 0;
int ProcedureStats::num_of_sec_mode_cmd_to_ue_sent = 0;
int ProcedureStats::num_of_processed_sec_mode_resp = 0;
int ProcedureStats::num_of_esm_info_req_to_ue_sent = 0;
int ProcedureStats::num_of_handled_esm_info_resp = 0;
int ProcedureStats::num_of_cs_req_to_sgw_sent = 0;
int ProcedureStats::num_of_processed_cs_resp = 0;
int ProcedureStats::num_of_init_ctxt_req_to_ue_sent = 0;
int ProcedureStats::num_of_processed_init_ctxt_resp = 0;
int ProcedureStats::num_of_mb_req_to_sgw_sent = 0;
int ProcedureStats::num_of_processed_attach_cmp_from_ue = 0;
int ProcedureStats::num_of_processed_mb_resp = 0;
int ProcedureStats::num_of_attach_done = 0;
int ProcedureStats::num_of_del_session_req_sent = 0;
int ProcedureStats::num_of_purge_req_sent = 0;
int ProcedureStats::num_of_processed_del_session_resp = 0;
int ProcedureStats::num_of_processed_pur_resp = 0;
int ProcedureStats::num_of_detach_accept_to_ue_sent = 0;
int ProcedureStats::num_of_processed_detach_accept = 0;
int ProcedureStats::num_of_ue_ctxt_release = 0;
int ProcedureStats::num_of_processed_ctxt_rel_resp = 0;
int ProcedureStats::num_of_subscribers_attached = 0;
int ProcedureStats::num_of_rel_access_bearer_req_sent = 0;
int ProcedureStats::num_of_rel_access_bearer_resp_received = 0;
int ProcedureStats::num_of_s1_rel_req_received = 0;
int ProcedureStats::num_of_s1_rel_cmd_sent = 0;
int ProcedureStats::num_of_s1_rel_comp_received = 0;
int ProcedureStats::num_of_clr_received = 0;
int ProcedureStats::num_of_cla_sent = 0;
int ProcedureStats::num_of_detach_req_to_ue_sent = 0;
int ProcedureStats::num_of_detach_accept_from_ue = 0;
int ProcedureStats::total_num_of_subscribers = 0;
int ProcedureStats::num_of_subscribers_detached = 0;
int ProcedureStats::num_of_ddn_received = 0;
int ProcedureStats::num_of_service_request_received = 0;
int ProcedureStats::num_of_ddn_ack_sent = 0;
int ProcedureStats::num_of_tau_response_to_ue_sent = 0;
int ProcedureStats::num_of_service_reject_sent = 0;
int ProcedureStats::num_of_attach_reject_sent = 0;
int ProcedureStats::num_of_emm_info_sent = 0;
int ProcedureStats::num_of_attach_req_received = 0;
int ProcedureStats::num_of_detach_req_received = 0;
int ProcedureStats::num_of_tau_req_received = 0;
int ProcedureStats::num_of_paging_request_sent = 0;
int ProcedureStats::num_of_id_req_sent = 0;
int ProcedureStats::num_of_id_resp_received = 0;
int ProcedureStats::num_of_auth_reject_sent = 0;
int ProcedureStats::num_of_ho_required_received = 0;
int ProcedureStats::num_of_ho_request_to_target_enb_sent = 0;
int ProcedureStats::num_of_ho_request_ack_received = 0;
int ProcedureStats::num_of_ho_command_to_src_enb_sent = 0;
int ProcedureStats::num_of_ho_notify_received = 0;
int ProcedureStats::num_of_ho_complete = 0;
int ProcedureStats::num_of_ho_failure_received = 0;
int ProcedureStats::num_of_ho_prep_failure_sent = 0;
int ProcedureStats::num_of_ho_cancel_received = 0;
int ProcedureStats::num_of_ho_cancel_ack_sent = 0;
int ProcedureStats::num_of_erab_mod_ind_received = 0;
int ProcedureStats::num_of_erab_mod_conf_sent = 0;
int ProcedureStats::num_of_erab_mod_ind_timeout = 0;
int ProcedureStats::num_of_abort_erab_mod_indication = 0;
int ProcedureStats::num_of_erab_setup_req_sent = 0;
int ProcedureStats::num_of_erab_setup_resp_received = 0;
int ProcedureStats::num_of_create_bearer_req_received = 0;
int ProcedureStats::num_of_create_bearer_resp_sent = 0;
int ProcedureStats::num_of_act_ded_br_ctxt_req_sent = 0;
int ProcedureStats::num_of_ded_bearer_ctxt_acpt_received = 0;
int ProcedureStats::num_of_ded_bearer_ctxt_reject_received = 0;
int ProcedureStats::num_of_abort_ded_activation = 0;
int ProcedureStats::num_of_ded_act_complete = 0;
int ProcedureStats::num_of_create_bearer_proc_complete = 0;
int ProcedureStats::num_of_identification_req_sent = 0;
int ProcedureStats::num_of_identification_resp_sent = 0;
int ProcedureStats::num_of_processed_identification_resp = 0;
int ProcedureStats::num_of_fwd_relocation_req_sent = 0;
int ProcedureStats::num_of_fwd_relocation_resp_sent = 0;
int ProcedureStats::num_of_fwd_relocation_complete_sent = 0;
int ProcedureStats::num_of_fwd_access_context_notify_sent = 0;
int ProcedureStats::num_of_fwd_access_context_ack_sent = 0;
int ProcedureStats::num_of_identification_req_received = 0;
int ProcedureStats::num_of_identification_resp_received = 0;
int ProcedureStats::num_of_processed_identification_received = 0;
int ProcedureStats::num_of_fwd_relocation_req_received = 0;
int ProcedureStats::num_of_fwd_relocation_resp_received = 0;
int ProcedureStats::num_of_fwd_relocation_complete_received = 0;
int ProcedureStats::num_of_fwd_access_context_notify_received = 0;
int ProcedureStats::num_of_fwd_access_context_ack_received = 0;
|
fartherp/framework
|
framework-security/src/main/java/com/github/fartherp/framework/security/dissymmetry/DisSymmetry.java
|
/**
* Copyright (c) 2014-2019 CK.
*
* 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.github.fartherp.framework.security.dissymmetry;
import javax.crypto.Cipher;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.security.Key;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
/**
* Created by IntelliJ IDEA.
*
* @author CK
* @date 2017/11/30
*/
public class DisSymmetry {
/**
* KEY_SIZE
*/
private static final int KEY_SIZE = 1024;
/**
* RSA 最大加密
*/
private static final int MAX_ENCRYPT_BLOCK = 117;
/**
* RSA 最大解密
*/
private static final int MAX_DECRYPT_BLOCK = 128;
private static final String SEED = "<KEY>";
/**
* <p>创建公钥&私钥</p>
*
* @return the Map
*/
public static DisSymmetryKey initKey(String algorithm) {
DisSymmetryKey disSymmetryKey = new DisSymmetryKey();
KeyPairGenerator keyPairGen = null;
try {
keyPairGen = getKeyPairGenerator(algorithm);
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException("[" + algorithm + "]获取自增密钥错误", e);
}
SecureRandom secureRandom = new SecureRandom();
secureRandom.setSeed(SEED.getBytes());
keyPairGen.initialize(KEY_SIZE, secureRandom);
KeyPair keyPair = keyPairGen.generateKeyPair();
disSymmetryKey.setPublicKey(keyPair.getPublic().getEncoded());
disSymmetryKey.setPrivateKey(keyPair.getPrivate().getEncoded());
return disSymmetryKey;
}
public static KeyPairGenerator getKeyPairGenerator(String algorithm) throws NoSuchAlgorithmException {
return KeyPairGenerator.getInstance(algorithm);
}
public static KeyFactory getKeyFactory(String algorithm) throws NoSuchAlgorithmException {
return KeyFactory.getInstance(algorithm);
}
/**
* <p>公钥加密</p>
*
* @param algorithm 加密算法
* @param data 明文信息
* @param publicKey 公钥
* @return byte[]
*/
public static byte[] encryptByPublicKey(String algorithm, byte[] data, byte[] publicKey) {
ByteArrayOutputStream out = null;
try {
KeyFactory keyFactory = getKeyFactory(algorithm);
X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(publicKey);
Key publicK = keyFactory.generatePublic(x509KeySpec);
Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
cipher.init(Cipher.ENCRYPT_MODE, publicK);
int inputLen = data.length;
out = new ByteArrayOutputStream();
int offSet = 0;
byte[] cache;
int i = 0;
while (inputLen - offSet > 0) {
if (inputLen - offSet > MAX_ENCRYPT_BLOCK) {
cache = cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK);
} else {
cache = cipher.doFinal(data, offSet, inputLen - offSet);
}
out.write(cache, 0, cache.length);
i++;
offSet = i * MAX_ENCRYPT_BLOCK;
}
byte[] encryptedData = out.toByteArray();
return encryptedData;
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException("[" + algorithm + "]获取密钥工厂错误", e);
} catch (Exception e) {
throw new RuntimeException("[" + algorithm + "]公钥加密错误", e);
} finally {
try {
if (out != null) {
out.close();
}
} catch (IOException e) {
out = null;
e.printStackTrace();
}
}
}
/**
* <P>私钥解密</p>
*
* @param algorithm 加密算法
* @param data 密文信息
* @param privateKey 私钥
* @return byte[]
*/
public static byte[] decryptByPrivateKey(String algorithm, byte[] data, byte[] privateKey) {
ByteArrayOutputStream out = null;
try {
KeyFactory keyFactory = getKeyFactory(algorithm);
PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(privateKey);
Key privateK = keyFactory.generatePrivate(pkcs8KeySpec);
Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
cipher.init(Cipher.DECRYPT_MODE, privateK);
int inputLen = data.length;
out = new ByteArrayOutputStream();
int offSet = 0;
byte[] cache;
int i = 0;
while (inputLen - offSet > 0) {
if (inputLen - offSet > MAX_DECRYPT_BLOCK) {
cache = cipher.doFinal(data, offSet, MAX_DECRYPT_BLOCK);
} else {
cache = cipher.doFinal(data, offSet, inputLen - offSet);
}
out.write(cache, 0, cache.length);
i++;
offSet = i * MAX_DECRYPT_BLOCK;
}
byte[] decryptedData = out.toByteArray();
return decryptedData;
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException("[" + algorithm + "]获取密钥工厂错误", e);
} catch (Exception e) {
throw new RuntimeException("[" + algorithm + "]私钥解密错误", e);
} finally {
try {
if (out != null) {
out.close();
}
} catch (IOException e) {
out = null;
e.printStackTrace();
}
}
}
}
|
pocokhc/metaheuristics
|
tests/problems/test_LifeGame.py
|
import unittest
import random
import time
import numpy as np
import os
import sys
sys.path.append(os.path.join(os.path.dirname(__file__), '../../'))
from codes.problems.LifeGame import LifeGame
class Test(unittest.TestCase):
def test_1(self):
p = LifeGame(5, 49)
p.init()
# ブリンカー
arr = np.asarray([
0, 0, 0, 0, 0,
0, 0, 1, 0, 0,
0, 0, 1, 0, 0,
0, 0, 1, 0, 0,
0, 0, 0, 0, 0,
])
score = p.eval(arr)
self.assertEqual(score, 3)
#p.view(arr)
if __name__ == "__main__":
unittest.main()
|
bmob/BmobTiQiuBa
|
Android/ZuQiuBa/app/src/main/java/cn/bmob/zuqiu/ui/base/BaseNavigationDrawerActivity.java
|
<reponame>bmob/BmobTiQiuBa
package cn.bmob.zuqiu.ui.base;
import cn.bmob.v3.BmobPushManager;
import cn.bmob.v3.BmobUser;
import cn.bmob.zuqiu.R;
import cn.bmob.zuqiu.utils.LogUtil;
import cn.bmob.zuqiu.utils.ToastUtil;
import cn.bmob.zuqiuj.bean.User;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
public abstract class BaseNavigationDrawerActivity extends FragmentActivity implements OnClickListener{
protected String TAG ;
protected Context mContext;
protected TextView mActionBarTitle;
protected TextView mActionBarLeftMenu;
protected TextView mActionBarRightMenu;
protected ProgressDialog progressDialog;
@Override
protected void onCreate(Bundle arg0) {
// TODO Auto-generated method stub
super.onCreate(arg0);
setContentView(R.layout.activity_navigation_drawer_empty);
TAG = getClass().getSimpleName();
LogUtil.i("base", TAG);
mContext = this;
findViews();
setListenter();
}
private void findViews() {
mActionBarTitle = (TextView)findViewById(R.id.actionbar_title);
mActionBarLeftMenu = (TextView)findViewById(R.id.actionbar_left_menu);
mActionBarRightMenu = (TextView)findViewById(R.id.actionbar_right_menu);
}
private void setListenter() {
mActionBarTitle.setOnClickListener(this);
mActionBarLeftMenu.setOnClickListener(this);
mActionBarRightMenu.setOnClickListener(this);
}
/**
* 设置布局内容
* @param layoutId
*/
protected void setViewContent(int layoutId){
FrameLayout baseContent = (FrameLayout)findViewById(R.id.content_frame);
View contentView = LayoutInflater.from(this).inflate(layoutId, null);
baseContent.addView(contentView,new RelativeLayout
.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT,
RelativeLayout.LayoutParams.MATCH_PARENT));
findViews(contentView);
}
protected abstract void findViews(View contentView);
/**
* 设置action上左右菜单与标题
* @param tv
* @param text
* @param drawableId
* @param visibility
*/
protected void setUpAction(TextView tv,String text,int drawableId,int visibility){
if(!TextUtils.isEmpty(text)){
tv.setText(text);
}
if(drawableId!=0){
tv.setCompoundDrawablesWithIntrinsicBounds(drawableId, 0, 0, 0);
}
if(tv.getVisibility()!=visibility){
tv.setVisibility(visibility);
}
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch(v.getId()) {
case R.id.actionbar_title:
onTitleClick();
break;
case R.id.actionbar_left_menu:
onLeftMenuClick();
break;
case R.id.actionbar_right_menu:
onRightMenuClick();
break;
default:
break;
}
}
protected void onTitleClick() {
// TODO Auto-generated method stub
}
protected void onLeftMenuClick() {
// TODO Auto-generated method stub
}
protected void onRightMenuClick() {
// TODO Auto-generated method stub
}
public void showToast(String text){
ToastUtil.showToast(this, text);
}
public void redictTo(Context context,Class<? extends Activity> activity,Bundle bundle){
Intent intent = new Intent();
intent.setClass(context, activity);
if(bundle!=null){
intent.putExtra("data", bundle);
}
startActivity(intent);
}
protected void initProgressDialog(int loadingMsgId) {
if(progressDialog==null){
progressDialog = new ProgressDialog(mContext);
}
progressDialog.setMessage(getString(loadingMsgId));
progressDialog.show();
}
protected void dismissDialog(){
if(progressDialog!=null){
progressDialog.dismiss();
}
}
protected void hideSoftInput(EditText input){
InputMethodManager imm = (InputMethodManager)this.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(input.getWindowToken(), 0);
}
/**
* 显示键盘
*/
protected void showSoftInput() {
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
View view = getCurrentFocus() != null ? getCurrentFocus() : findViewById(android.R.id.content);
imm.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT);
}
/**
* 隐藏键盘
*/
protected void hideSoftInput() {
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
View view = getCurrentFocus() != null ? getCurrentFocus() : findViewById(android.R.id.content);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
protected BmobPushManager getPushManager(){
BmobPushManager manager = new BmobPushManager(mContext);
return manager;
}
protected User getUser(){
User user = BmobUser.getCurrentUser(mContext, User.class);
return user;
}
}
|
chrisdrackett/atom-ide-ui
|
modules/nuclide-commons-atom/__atom_tests__/text-editor-test.js
|
/**
* Copyright (c) 2017-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.
*
* @flow
* @format
* @emails oncall+nuclide
*/
import {existingEditorForUri} from '../text-editor';
describe('existingEditorForUri', () => {
const file1 = '/tmp/file1.txt';
const file2 = '/tmp/file2.txt';
const file3 = '/tmp/file3.txt';
let file1Editor: atom$TextEditor = (null: any);
let file2Editor: atom$TextEditor = (null: any);
let secondFile2Editor: atom$TextEditor = (null: any);
beforeEach(async () => {
file1Editor = await atom.workspace.open(file1);
file2Editor = await atom.workspace.open(file2);
secondFile2Editor = await atom.workspace.open(file2);
});
it('should find the one editor for a file', () => {
expect(existingEditorForUri(file1)).toBe(file1Editor);
});
it('should find one of the editors for a file', () => {
const editor = existingEditorForUri(file2);
expect(editor === file2Editor || editor === secondFile2Editor).toBeTruthy();
});
it('should return null if no editor exists', () => {
expect(existingEditorForUri(file3)).toBeNull();
});
});
|
angell007/testDanilo
|
public/Select/js/src/plugins/FloatingLabelPlugin.js
|
import {composeSync} from '../ToolsJs';
import {toggleStyling} from '../ToolsStyling';
export function FloatingLabelPlugin(pluginData){
let {configuration, picksList, picksDom, filterDom, staticDom, updateDataAspect,
resetFilterListAspect, floatingLabelAspect} = pluginData;
let {css, getDefaultLabel} = configuration;
let initialElement = staticDom.initialElement;
if (floatingLabelAspect.isFloatingLabel() ){
let labelElement = getDefaultLabel(initialElement);
let picksElement = picksDom.picksElement;
var liftToggleStyling1 = toggleStyling(labelElement, css.label_floating_lifted);
var liftToggleStyling2 = toggleStyling(picksElement, css.picks_floating_lifted);
function liftedLabel(isEmpty){
liftToggleStyling1(isEmpty);
liftToggleStyling2(isEmpty);
}
let isEmpty = () => picksList.isEmpty() && filterDom.isEmpty() && !picksDom.getIsFocusIn();;
function updateLiftedLabel(){
liftedLabel(!isEmpty());
};
updateLiftedLabel();
resetFilterListAspect.forceResetFilter = composeSync(resetFilterListAspect.forceResetFilter, updateLiftedLabel);
let origAdd = picksList.add;
picksList.add = (pick) => {
let returnValue = origAdd(pick);
if (picksList.getCount()==1)
updateLiftedLabel()
pick.dispose = composeSync(pick.dispose, ()=>
{
if (picksList.getCount()==0)
updateLiftedLabel()
})
return returnValue;
};
var origToggleFocusStyling = picksDom.toggleFocusStyling;
picksDom.toggleFocusStyling = () => {
var isFocusIn = picksDom.getIsFocusIn();
origToggleFocusStyling(isFocusIn);
updateLiftedLabel();
}
updateDataAspect.updateData = composeSync(updateDataAspect.updateData, updateLiftedLabel);
}
}
FloatingLabelPlugin.plugStaticDom = (aspects) => {
aspects.floatingLabelAspect = FloatingLabelAspect();
}
function FloatingLabelAspect() {
return {
isFloatingLabel(){},
}
}
|
sebastien-riou/lightweight-crypto
|
src/individual/Elephant/elephant.h
|
/*
* Copyright (C) 2020 Southern Storm Software, Pty Ltd.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is 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 Software.
*
* THE SOFTWARE IS 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 SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
#ifndef LWCRYPTO_ELEPHANT_H
#define LWCRYPTO_ELEPHANT_H
#include "aead-common.h"
/**
* \file elephant.h
* \brief Elephant authenticated encryption algorithm family.
*
* Elephant is a family of authenticated encryption algorithms based
* around the Spongent-pi and Keccak permutations.
*
* \li Dumbo has a 128-bit key, a 96-bit nonce, and a 64-bit authentication
* tag. It is based around the Spongent-pi[160] permutation. This is
* the primary member of the family.
* \li Jumbo has a 128-bit key, a 96-bit nonce, and a 64-bit authentication
* tag. It is based around the Spongent-pi[176] permutation.
* \li Delirium has a 128-bit key, a 96-bit nonce, and a 128-bit authentication
* tag. It is based around the Keccak[200] permutation.
*
* References: https://www.esat.kuleuven.be/cosic/elephant/
*/
#ifdef __cplusplus
extern "C" {
#endif
/**
* \brief Size of the key for Dumbo.
*/
#define DUMBO_KEY_SIZE 16
/**
* \brief Size of the authentication tag for Dumbo.
*/
#define DUMBO_TAG_SIZE 8
/**
* \brief Size of the nonce for Dumbo.
*/
#define DUMBO_NONCE_SIZE 12
/**
* \brief Size of the key for Jumbo.
*/
#define JUMBO_KEY_SIZE 16
/**
* \brief Size of the authentication tag for Jumbo.
*/
#define JUMBO_TAG_SIZE 8
/**
* \brief Size of the nonce for Jumbo.
*/
#define JUMBO_NONCE_SIZE 12
/**
* \brief Size of the key for Delirium.
*/
#define DELIRIUM_KEY_SIZE 16
/**
* \brief Size of the authentication tag for Delirium.
*/
#define DELIRIUM_TAG_SIZE 16
/**
* \brief Size of the nonce for Delirium.
*/
#define DELIRIUM_NONCE_SIZE 12
/**
* \brief Meta-information block for the Dumbo cipher.
*/
extern aead_cipher_t const dumbo_cipher;
/**
* \brief Meta-information block for the Jumbo cipher.
*/
extern aead_cipher_t const jumbo_cipher;
/**
* \brief Meta-information block for the Delirium cipher.
*/
extern aead_cipher_t const delirium_cipher;
/**
* \brief Encrypts and authenticates a packet with Dumbo.
*
* \param c Buffer to receive the output.
* \param clen On exit, set to the length of the output which includes
* the ciphertext and the 8 byte authentication tag.
* \param m Buffer that contains the plaintext message to encrypt.
* \param mlen Length of the plaintext message in bytes.
* \param ad Buffer that contains associated data to authenticate
* along with the packet but which does not need to be encrypted.
* \param adlen Length of the associated data in bytes.
* \param nsec Secret nonce - not used by this algorithm.
* \param npub Points to the public nonce for the packet which must
* be 12 bytes in length.
* \param k Points to the 16 bytes of the key to use to encrypt the packet.
*
* \return 0 on success, or a negative value if there was an error in
* the parameters.
*
* \sa dumbo_aead_decrypt()
*/
int dumbo_aead_encrypt
(unsigned char *c, unsigned long long *clen,
const unsigned char *m, unsigned long long mlen,
const unsigned char *ad, unsigned long long adlen,
const unsigned char *nsec,
const unsigned char *npub,
const unsigned char *k);
/**
* \brief Decrypts and authenticates a packet with Dumbo.
*
* \param m Buffer to receive the plaintext message on output.
* \param mlen Receives the length of the plaintext message on output.
* \param nsec Secret nonce - not used by this algorithm.
* \param c Buffer that contains the ciphertext and authentication
* tag to decrypt.
* \param clen Length of the input data in bytes, which includes the
* ciphertext and the 8 byte authentication tag.
* \param ad Buffer that contains associated data to authenticate
* along with the packet but which does not need to be encrypted.
* \param adlen Length of the associated data in bytes.
* \param npub Points to the public nonce for the packet which must
* be 12 bytes in length.
* \param k Points to the 16 bytes of the key to use to decrypt the packet.
*
* \return 0 on success, -1 if the authentication tag was incorrect,
* or some other negative number if there was an error in the parameters.
*
* \sa dumbo_aead_encrypt()
*/
int dumbo_aead_decrypt
(unsigned char *m, unsigned long long *mlen,
unsigned char *nsec,
const unsigned char *c, unsigned long long clen,
const unsigned char *ad, unsigned long long adlen,
const unsigned char *npub,
const unsigned char *k);
/**
* \brief Encrypts and authenticates a packet with Jumbo.
*
* \param c Buffer to receive the output.
* \param clen On exit, set to the length of the output which includes
* the ciphertext and the 8 byte authentication tag.
* \param m Buffer that contains the plaintext message to encrypt.
* \param mlen Length of the plaintext message in bytes.
* \param ad Buffer that contains associated data to authenticate
* along with the packet but which does not need to be encrypted.
* \param adlen Length of the associated data in bytes.
* \param nsec Secret nonce - not used by this algorithm.
* \param npub Points to the public nonce for the packet which must
* be 12 bytes in length.
* \param k Points to the 16 bytes of the key to use to encrypt the packet.
*
* \return 0 on success, or a negative value if there was an error in
* the parameters.
*
* \sa jumbo_aead_decrypt()
*/
int jumbo_aead_encrypt
(unsigned char *c, unsigned long long *clen,
const unsigned char *m, unsigned long long mlen,
const unsigned char *ad, unsigned long long adlen,
const unsigned char *nsec,
const unsigned char *npub,
const unsigned char *k);
/**
* \brief Decrypts and authenticates a packet with Jumbo.
*
* \param m Buffer to receive the plaintext message on output.
* \param mlen Receives the length of the plaintext message on output.
* \param nsec Secret nonce - not used by this algorithm.
* \param c Buffer that contains the ciphertext and authentication
* tag to decrypt.
* \param clen Length of the input data in bytes, which includes the
* ciphertext and the 8 byte authentication tag.
* \param ad Buffer that contains associated data to authenticate
* along with the packet but which does not need to be encrypted.
* \param adlen Length of the associated data in bytes.
* \param npub Points to the public nonce for the packet which must
* be 12 bytes in length.
* \param k Points to the 16 bytes of the key to use to decrypt the packet.
*
* \return 0 on success, -1 if the authentication tag was incorrect,
* or some other negative number if there was an error in the parameters.
*
* \sa jumbo_aead_encrypt()
*/
int jumbo_aead_decrypt
(unsigned char *m, unsigned long long *mlen,
unsigned char *nsec,
const unsigned char *c, unsigned long long clen,
const unsigned char *ad, unsigned long long adlen,
const unsigned char *npub,
const unsigned char *k);
/**
* \brief Encrypts and authenticates a packet with Delirium.
*
* \param c Buffer to receive the output.
* \param clen On exit, set to the length of the output which includes
* the ciphertext and the 16 byte authentication tag.
* \param m Buffer that contains the plaintext message to encrypt.
* \param mlen Length of the plaintext message in bytes.
* \param ad Buffer that contains associated data to authenticate
* along with the packet but which does not need to be encrypted.
* \param adlen Length of the associated data in bytes.
* \param nsec Secret nonce - not used by this algorithm.
* \param npub Points to the public nonce for the packet which must
* be 12 bytes in length.
* \param k Points to the 16 bytes of the key to use to encrypt the packet.
*
* \return 0 on success, or a negative value if there was an error in
* the parameters.
*
* \sa delirium_aead_decrypt()
*/
int delirium_aead_encrypt
(unsigned char *c, unsigned long long *clen,
const unsigned char *m, unsigned long long mlen,
const unsigned char *ad, unsigned long long adlen,
const unsigned char *nsec,
const unsigned char *npub,
const unsigned char *k);
/**
* \brief Decrypts and authenticates a packet with Delirium.
*
* \param m Buffer to receive the plaintext message on output.
* \param mlen Receives the length of the plaintext message on output.
* \param nsec Secret nonce - not used by this algorithm.
* \param c Buffer that contains the ciphertext and authentication
* tag to decrypt.
* \param clen Length of the input data in bytes, which includes the
* ciphertext and the 16 byte authentication tag.
* \param ad Buffer that contains associated data to authenticate
* along with the packet but which does not need to be encrypted.
* \param adlen Length of the associated data in bytes.
* \param npub Points to the public nonce for the packet which must
* be 12 bytes in length.
* \param k Points to the 16 bytes of the key to use to decrypt the packet.
*
* \return 0 on success, -1 if the authentication tag was incorrect,
* or some other negative number if there was an error in the parameters.
*
* \sa delirium_aead_encrypt()
*/
int delirium_aead_decrypt
(unsigned char *m, unsigned long long *mlen,
unsigned char *nsec,
const unsigned char *c, unsigned long long clen,
const unsigned char *ad, unsigned long long adlen,
const unsigned char *npub,
const unsigned char *k);
#ifdef __cplusplus
}
#endif
#endif
|
lordakshaya/Locker
|
Connectors/Tumblr/lib.js
|
/*
*
* Copyright (C) 2011, The Locker Project
* All rights reserved.
*
* Please see the LICENSE file for more information.
*
*/
var fs = require('fs'),
request = require('request'),
async = require('async'),
url = require('url'),
crypto = require("crypto");
var tumblr;
var auth;
var base = 'http://api.tumblr.com/v2';
exports.init = function(theAuth) {
auth = theAuth;
tumblr = require('./tumblr_client')(auth.consumerKey, auth.consumerSecret);
};
exports.getMe = function(arg, cbEach, cbDone) {
arg.path = '/user/info';
getOne(arg,function(err,me){
if(err || !me || !me.user) return cbDone(err);
// do this for convenience
for(var i in me.user.blogs){
if(!me.user.blogs[i].primary) continue;
var u = url.parse(me.user.blogs[i].url);
if(u && u.hostname) me.host = u.hostname;
break;
}
cbEach(me);
cbDone();
});
}
exports.getFollowing = function(arg, cbEach, cbDone) {
var me = this;
arg.path = '/user/following';
arg.field = 'blogs';
var q = async.queue(function(js,cb){ // use a queue to process each block of ids
me.getBlog({url:js.url}, cbEach, cb);
},3);
getPages(arg, q.push, function(err){
if(err) return cbDone(err);
if(q.length() == 0) return cbDone(); // queue could be done, but likely not
q.drain = cbDone; // whenever it finishes...
});
}
exports.getBlog = function(arg, cbEach, cbDone) {
if(!arg.url) return cbDone("no url");
var u = url.parse(arg.url);
if(!u || !u.hostname) return cbDone("no hostname found in url");
arg.path = '/blog/'+u.hostname+'/info';
delete arg.url;
arg.field = 'blog';
getOneKey(arg, function(err, js){
if(err) return cbDone(err);
if(!js.avatar) js.avatar = base + '/blog/' + u.hostname + '/avatar';
cbEach(js);
cbDone();
});
}
exports.getDashboard = function(arg, cbEach, cbDone) {
arg.path = '/user/dashboard';
arg.field = 'posts';
arg.reblog_info = true;
arg.notes_info = true;
getPages(arg, cbEach, cbDone);
}
exports.getPosts = function(arg, cbEach, cbDone) {
if(!arg.blog) return cbDone("no blog");
arg.path = '/blog/'+arg.blog+'/posts';
delete arg.blog;
arg.field = 'posts';
arg.reblog_info = true;
arg.notes_info = true;
getPagesKey(arg, cbEach, cbDone);
}
function getOneKey(arg, cb)
{
if(!arg.path) return cb("no path");
if(!arg.field) return cb("no field");
var api = url.parse(base+arg.path);
delete arg.path;
arg.api_key = auth.consumerKey;
api.query = arg;
var field = arg.field;
delete arg.field;
request.get({uri:url.format(api)}, function(err, resp, body) {
var js;
try{
if(err) throw err;
js = JSON.parse(body);
}catch(E){
return cb(E);
}
if(js && js.meta && js.meta.status === 200 && js.response && js.response[field]) return cb(null, js.response[field]);
cb("couldn't understand reponse");
});
}
function getOne(arg, cb)
{
if(!arg.path) return cb("no path");
arg.token = auth.token;
tumblr.apiCall('GET', arg.path, arg, function(err, js){
if(!err && js && js.meta && js.meta.status === 200 && js.response) return cb(null, js.response);
cb(err);
});
}
function getPages(arg, cbEach, cbDone)
{
if(!arg.path) return cbDone("no path");
if(!arg.field) return cbDone("no field");
arg.token = <PASSWORD>.token;
if(!arg.offset) arg.offset = 0;
if(!arg.limit) arg.limit = 20;
if(arg.since_id == 0) delete arg.since_id; // apparently sending a 0 drastically changes the result set selection, for dashboard at least
tumblr.apiCall('GET', arg.path, arg, function(err, js){
if(err || !js || !js.meta || js.meta.status != 200 || !js.response || !Array.isArray(js.response[arg.field]) || js.response[arg.field].length == 0) return cbDone(err);
var hash = crypto.createHash("sha1").update(JSON.stringify(js.response[arg.field][0])).digest('hex');
if(arg.dup === hash) return cbDone(); // tumblr keeps returning stuff even when increasing offset, have to dup check
arg.dup = hash;
for(var i = 0; i < js.response[arg.field].length; i++) cbEach(js.response[arg.field][i]);
if(js.response[arg.field].length < arg.limit) return cbDone(); // at the end
arg.offset += arg.limit;
return getPages(arg,cbEach,cbDone);
});
}
function getPagesKey(arg, cbEach, cbDone)
{
if(!arg.offset) arg.offset = 0;
if(!arg.limit) arg.limit = 20;
getOneKey(arg, function(err, arr){
if(err || !arr || !Array.isArray(arr) || arr.length == 0) return cbDone(err);
for(var i = 0; i < arr.length; i++) cbEach(arr[i]);
if(arr.length < arg.limit) return cbDone(); // at the end
arg.offset += arg.limit;
return getPagesKey(arg,cbEach,cbDone);
});
}
|
samokhinv/deep_pipe
|
dpipe/medim/shape_ops.py
|
from dpipe.im.shape_ops import *
|
gunnarmorling/infinispan
|
scripting/src/main/java/org/infinispan/scripting/impl/MapperScript.java
|
package org.infinispan.scripting.impl;
import javax.script.SimpleBindings;
import org.infinispan.distexec.mapreduce.Collector;
import org.infinispan.distexec.mapreduce.Mapper;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.scripting.ScriptingManager;
/**
* MapperScript.
*
* @author <NAME>
* @since 7.2
*/
public class MapperScript<KIn, VIn, KOut, VOut> implements Mapper<KIn, VIn, KOut, VOut>, EnvironmentAware {
private final ScriptMetadata metadata;
private transient ScriptingManagerImpl scriptManager;
private transient SimpleBindings bindings;
public MapperScript(ScriptMetadata metadata) {
this.metadata = metadata;
}
@Override
public void map(KIn key, VIn value, Collector<KOut, VOut> collector) {
bindings.put("key", key);
bindings.put("value", value);
bindings.put("collector", collector);
scriptManager.execute(metadata, bindings);
}
@Override
public void setEnvironment(EmbeddedCacheManager cacheManager) {
scriptManager = (ScriptingManagerImpl) SecurityActions.getGlobalComponentRegistry(cacheManager).getComponent(ScriptingManager.class);
bindings = new SimpleBindings();
bindings.put("cacheManager", cacheManager);
}
}
|
IHTSDO/snow-owl
|
snomed/com.b2international.snowowl.snomed.datastore/src/com/b2international/snowowl/snomed/datastore/request/SnomedDescriptionAcceptabilityUpdateRequest.java
|
/*
* Copyright 2011-2019 B2i Healthcare Pte Ltd, http://b2i.sg
*
* 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.b2international.snowowl.snomed.datastore.request;
import static com.google.common.collect.Lists.newArrayList;
import static com.google.common.collect.Maps.newHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.b2international.snowowl.core.domain.TransactionContext;
import com.b2international.snowowl.core.events.Request;
import com.b2international.snowowl.snomed.Description;
import com.b2international.snowowl.snomed.core.domain.Acceptability;
import com.b2international.snowowl.snomed.core.store.SnomedComponents;
import com.b2international.snowowl.snomed.datastore.model.SnomedModelExtensions;
import com.b2international.snowowl.snomed.snomedrefset.SnomedLanguageRefSetMember;
import com.b2international.snowowl.snomed.snomedrefset.SnomedRefSetMember;
/**
* @since 4.5
*/
final class SnomedDescriptionAcceptabilityUpdateRequest implements Request<TransactionContext, Void> {
private static final Logger LOG = LoggerFactory.getLogger(SnomedDescriptionAcceptabilityUpdateRequest.class);
private String descriptionId;
private Map<String, Acceptability> newAcceptabilityMap;
@Override
public Void execute(TransactionContext context) {
// Null leaves lang. members unchanged, empty map clears all lang. members
if (newAcceptabilityMap == null) {
return null;
} else {
final Description description = context.lookup(descriptionId, Description.class);
updateAcceptabilityMap(context, description, newAcceptabilityMap);
return null;
}
}
public void setDescriptionId(String descriptionId) {
this.descriptionId = descriptionId;
}
public void setAcceptability(Map<String, Acceptability> acceptability) {
this.newAcceptabilityMap = acceptability;
}
private void removeOrDeactivate(final TransactionContext context, final SnomedLanguageRefSetMember existingMember) {
if (!existingMember.isReleased()) {
if (LOG.isDebugEnabled()) { LOG.debug("Removing language member {}.", existingMember.getUuid()); }
SnomedModelExtensions.remove(existingMember);
} else if (existingMember.isActive()) {
if (LOG.isDebugEnabled()) { LOG.debug("Inactivating language member {}.", existingMember.getUuid()); }
existingMember.setActive(false);
unsetEffectiveTime(existingMember);
} else {
if (LOG.isDebugEnabled()) { LOG.debug("Language member {} already inactive, not updating.", existingMember.getUuid()); }
}
}
private void updateAcceptabilityMap(final TransactionContext context, final Description description, Map<String, Acceptability> acceptabilityMap) {
final List<SnomedLanguageRefSetMember> existingMembers = newArrayList(description.getLanguageRefSetMembers());
final Map<String, Acceptability> newLanguageMembersToCreate = newHashMap(acceptabilityMap);
// check if there are existing matches
for (SnomedLanguageRefSetMember existingMember : existingMembers) {
final Acceptability acceptability = Acceptability.getByConceptId(existingMember.getAcceptabilityId());
final String languageReferenceSetId = existingMember.getRefSetIdentifierId();
if (null == acceptability) {
continue;
}
if (acceptability.equals(newLanguageMembersToCreate.get(languageReferenceSetId))) {
ensureMemberActive(context, existingMember);
newLanguageMembersToCreate.remove(languageReferenceSetId);
} else if (newLanguageMembersToCreate.containsKey(languageReferenceSetId)) {
final Acceptability newAcceptability = newLanguageMembersToCreate.get(languageReferenceSetId);
ensureMemberActive(context, existingMember);
existingMember.setAcceptabilityId(newAcceptability.getConceptId());
unsetEffectiveTime(existingMember);
newLanguageMembersToCreate.remove(languageReferenceSetId);
} else {
removeOrDeactivate(context, existingMember);
}
}
for (final Entry<String, Acceptability> languageMemberEntry : newLanguageMembersToCreate.entrySet()) {
SnomedComponents
.newLanguageMember()
.withAcceptability(languageMemberEntry.getValue())
.withRefSet(languageMemberEntry.getKey())
.withModule(description.getModule().getId())
.withReferencedComponent(description.getId())
.addTo(context);
}
}
private void ensureMemberActive(final TransactionContext context, final SnomedLanguageRefSetMember existingMember) {
if (!existingMember.isActive()) {
if (LOG.isDebugEnabled()) { LOG.debug("Reactivating language member {}.", existingMember.getUuid()); }
existingMember.setActive(true);
unsetEffectiveTime(existingMember);
} else {
if (LOG.isDebugEnabled()) { LOG.debug("Language member {} already active, not updating.", existingMember.getUuid()); }
}
}
private void unsetEffectiveTime(SnomedRefSetMember existingMember) {
if (existingMember.isSetEffectiveTime()) {
if (LOG.isDebugEnabled()) { LOG.debug("Unsetting effective time on language member {}.", existingMember.getUuid()); }
existingMember.unsetEffectiveTime();
} else {
if (LOG.isDebugEnabled()) { LOG.debug("Effective time on language member {} already unset, not updating.", existingMember.getUuid()); }
}
}
}
|
DazEB2/SimplePyScripts
|
html_parsing/get_video_list__xcadr.com.py
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = 'ipetrash'
def get_video_list(url):
import requests
rs = requests.get(url)
from bs4 import BeautifulSoup
root = BeautifulSoup(rs.content, 'lxml')
import re
pattern_get_duration = re.compile('(\d+).:(\d+).')
items = []
for item in root.select('#playlist_view_playlist_view_items > .item'):
url = item.a['href']
title = item.a['title']
url_thumb = item.select_one('img')['src']
# Example: "60%", "80%"
rating = item.select_one('.rating').text
rating = int(rating.replace('%', ''))
# Example: "0м:31с", "6м:32с"
duration = item.select_one('.duration').text
minutes, seconds = map(int, pattern_get_duration.findall(duration)[0])
duration = minutes * 60 + seconds
items.append({
'title': title,
'url': url,
'duration': duration,
'rating': rating,
'url_thumb': url_thumb
})
return items
if __name__ == '__main__':
items = get_video_list('http://xcadr.com/collection/seks-v-poze-naezdnicy/')
print('Total:', len(items))
items = get_video_list('http://xcadr.com/collection/sceny-bdsm-v-filmah/')
print('Total:', len(items))
print()
items = get_video_list('http://xcadr.com/collection/luchshie-sceny-v-bane/')
print('Total:', len(items))
def print_items(items):
for i, item in enumerate(items, 1):
print('{0:2}. "{title}" ({duration} secs, rating: {rating}): {url} [{url_thumb}]'.format(i, **item))
print('Sorted by duration (top 5):')
new_items = sorted(items, key=lambda x: x['duration'], reverse=True)[:5]
print_items(new_items)
print()
print('Sorted by duration:')
new_items = sorted(items, key=lambda x: x['duration'], reverse=True)
print_items(new_items)
print()
print('Sorted by rating:')
new_items = sorted(items, key=lambda x: x['rating'], reverse=True)
print_items(new_items)
|
caseman/ism.nodejs
|
lib/localserver.js
|
<reponame>caseman/ism.nodejs
/*
* Local server child process module
*/
var server = require('./server')
, logging = require('./logging')
, db = require('./db')
var localServer
function start() {
var dbPath = process.argv[process.argv.length - 1]
var serverDb = db.open(dbPath || db.defaultPath(), function(err) {
if (err) {
logging.log.error('Error opening database: ' + err);
process.send({error: err.toString()})
process.exit(1)
} else {
localServer = new server.Server(serverDb)
localServer.start(0, '127.0.0.1', function(info) {
process.title = 'ism server ' + info.host + ':' + info.port
process.send(info)
})
}
})
}
process.on('message', function(msg) {
if (msg.logging) logging.configure(msg)
if (msg == 'start') start()
})
|
francoiscolombo/fc-automation
|
automaton/src/main/java/net/francoiscolombo/tools/automaton/actions/Debug.java
|
package net.francoiscolombo.tools.automaton.actions;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.logging.Logger;
public class Debug extends AbstractAction {
// global logger
private final static Logger LOGGER = Logger.getLogger(Logger.GLOBAL_LOGGER_NAME);
@Override
protected void execute() {
this.exitCode = 1;
String msg = getParameter("message");
if(!msg.equals("")) {
LOGGER.info(String.format("DBG: %s", msg));
this.exitCode = 0;
} else {
String path = getParameter("file");
if(!path.equals("")) {
try {
Files.lines(Paths.get(path)).forEach(line -> {
LOGGER.info(String.format("DBG: %s", line));
});
this.exitCode = 0;
} catch (IOException ioex) {
LOGGER.warning(String.format("An exception happened while trying to show content of file %s, the message is '%s'", path, ioex.getMessage()));
}
} else {
LOGGER.warning("Action debug need parameter <message> or <file>, none provided, no action done.");
}
}
}
}
|
luispedro/Coelho2021_GMGCv1_analysis
|
gmgc.analysis/Statement-ecoli-rare.py
|
<gh_stars>1-10
from taxonomic import ncbi
import pandas as pd
fraction_rare = pd.read_table('tables/fraction-rare.tsv', index_col=0)
specIs = pd.read_table('/g/scb2/bork/mocat/freezer/prok-refdb/v12.0.0/combinedVsearch3.50p.20n.norm.opt.0.042.clustering.map', header=None, names=['specI', 'genome'])
n = ncbi.NCBI()
fr = fraction_rare.loc[specIs.query('specI == "specI_v3_Cluster95"').genome]
print("Using specI_v3_95")
print("Nr genomes: {}".format(len(fr)))
print("Mean: {}".format(fr.fraction_rare.mean()))
fr = fr.groupby(fr.index.map(lambda ix: ix.split('.')[0])).first()
print("Just 1 strain")
print("Nr genomes: {}".format(len(fr)))
print("Mean: {}".format(fr.fraction_rare.mean()))
fr = fraction_rare.loc[fraction_rare.index.map(lambda x: '562' in n.path(x.split('.')[0]))]
print("Using taxid <- 562")
print("Nr genomes: {}".format(len(fr)))
print("Mean: {}".format(fr.fraction_rare.mean()))
fr = fr.groupby(fr.index.map(lambda ix: ix.split('.')[0])).first()
print("Just 1 strain")
print("Nr genomes: {}".format(len(fr)))
print("Mean: {}".format(fr.fraction_rare.mean()))
|
alex-d-bondarev/logic-tasks-practice
|
src/main/java/org/parctice/app/hackerrank/java/data_structures/JavaHashSet.java
|
<filename>src/main/java/org/parctice/app/hackerrank/java/data_structures/JavaHashSet.java<gh_stars>0
package org.parctice.app.hackerrank.java.data_structures;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
public class JavaHashSet {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int t = s.nextInt();
String [] pair_left = new String[t];
String [] pair_right = new String[t];
for (int i = 0; i < t; i++) {
pair_left[i] = s.next();
pair_right[i] = s.next();
}
//Write your code here
Set<String> pairs = new HashSet();
for (int i = 0; i < t; i++) {
pairs.add(pair_left[i]+" "+pair_right[i]);
System.out.println(pairs.size());
}
}
}
|
onct/LearnCode
|
truth_hold/server/controllers/createrecord.js
|
<filename>truth_hold/server/controllers/createrecord.js<gh_stars>0
const {mysql} = require('../qcloud')
module.exports = async (ctx) => {
const {openid,add} = ctx.request.body
try{
//查找出最后一条记录
const res = await mysql('records')
.where("openid",openid)
.select('mark')
.orderBy('id','desc').first()
//得到最后一条记录的分数
if(res){
var mark = res.mark
}else{
var mark = 0
}
//当前总分 = 最后一条记录的分数 + 本次操作的分数
mark = mark + add
console.log("当前分数为:",mark)
//将openid、本次操作的分数、当前总分
await mysql('records').insert({
openid, add, mark
})
//执行成功返回到前端的数据
ctx.state.data = {
code: 0,
msg: 'success'
}
console.log("执行成功")
}catch(e){
console.log("执行错误:",e)
//执行失败返回到前端的数据
ctx.state = {
code: -1,
data: {
msg: '添加失败' + e.sqlMessage
}
}
}
}
|
ahn/mideaas
|
mideaas-codeeditor/src/main/java/org/vaadin/mideaas/editor/SharedDoc.java
|
<filename>mideaas-codeeditor/src/main/java/org/vaadin/mideaas/editor/SharedDoc.java<gh_stars>1-10
package org.vaadin.mideaas.editor;
import java.util.LinkedList;
import java.util.concurrent.CopyOnWriteArrayList;
import org.vaadin.aceeditor.AceEditor;
import org.vaadin.aceeditor.AceEditor.DiffEvent;
import org.vaadin.aceeditor.AceEditor.DiffListener;
import org.vaadin.aceeditor.ServerSideDocDiff;
import org.vaadin.aceeditor.client.AceDoc;
/**
* An {@link AceDoc} to be collaboratively edited by {@link AceEditor}s.
*
*/
public class SharedDoc implements DiffListener {
public interface Listener {
public void changed();
}
private final CopyOnWriteArrayList<Listener> listeners = new CopyOnWriteArrayList<Listener>();
private LinkedList<AceEditor> editors = new LinkedList<AceEditor>();
private AceDoc doc;
public SharedDoc(AceDoc doc) {
this.doc = doc;
}
public synchronized void attachEditor(final AceEditor editor) {
boolean wasReadonly = editor.isReadOnly();
editor.setReadOnly(false);
editor.setDoc(getDoc());
editor.setReadOnly(wasReadonly);
editors.add(editor);
editor.addDiffListener(this);
}
public synchronized void detachEditor(AceEditor editor) {
editors.remove(editor);
editor.removeDiffListener(this);
}
public void applyDiff(ServerSideDocDiff diff) {
if (diff.isIdentity()) {
return;
}
AceDoc newDoc = applyDiffNoFire(diff);
if (newDoc!=null) {
fireChanged();
}
}
private synchronized AceDoc applyDiffNoFire(ServerSideDocDiff diff) {
return setDocNoFire(diff.applyTo(doc));
}
synchronized AceDoc setDocNoFire(final AceDoc doc) {
if (this.doc.equals(doc)) {
return null;
}
// XXX
// try {
// Thread.sleep(new Random().nextInt(1000));
// } catch (InterruptedException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
this.doc = doc;
for (final AceEditor editor : editors) {
editor.getUI().access(new Runnable() {
@Override
public void run() {
editor.setDoc(doc);
}
});
}
return doc;
}
public void setDoc(AceDoc doc) {
AceDoc newDoc = setDocNoFire(doc);
if (newDoc!=null) {
fireChanged();
}
}
public synchronized AceDoc getDoc() {
return doc;
}
public void addListener(Listener li) {
listeners.add(li);
}
public void removeListener(Listener li) {
listeners.remove(li);
}
public void fireChanged() {
for (Listener li : listeners) {
li.changed();
}
}
@Override
public void diff(DiffEvent e) {
applyDiff(e.getDiff());
}
public DocDiffMediator fork() {
SharedDoc fork = new SharedDoc(getDoc());
return new DocDiffMediator(this, fork);
}
}
|
FellegaraR/cosmoscout-vr
|
src/cs-utils/utils.hpp
|
////////////////////////////////////////////////////////////////////////////////////////////////////
// This file is part of CosmoScout VR //
// and may be used under the terms of the MIT license. See the LICENSE file for details. //
// Copyright: (c) 2019 German Aerospace Center (DLR) //
////////////////////////////////////////////////////////////////////////////////////////////////////
#ifndef CS_UTILS_UTILS_HPP
#define CS_UTILS_UTILS_HPP
#include "cs_utils_export.hpp"
#include <algorithm>
#include <limits>
#include <map>
#include <sstream>
#include <string>
#include <type_traits>
#include <unordered_map>
#include <vector>
/// These macros can be used to selectively disable specific gcc / clang or msvc warnings.
#if defined(__clang__) || defined(__GNUC__)
#define CS_DO_PRAGMA(X) _Pragma(#X)
#define CS_WARNINGS_PUSH _Pragma("GCC diagnostic push")
#define CS_WARNINGS_POP _Pragma("GCC diagnostic pop")
#define CS_DISABLE_GCC_WARNING(warningName) CS_DO_PRAGMA(GCC diagnostic ignored warningName)
#define CS_DISABLE_MSVC_WARNING(warningNumber)
#elif defined(_MSC_VER)
#define CS_WARNINGS_PUSH __pragma(warning(push))
#define CS_WARNINGS_POP __pragma(warning(pop))
#define CS_DISABLE_MSVC_WARNING(warningNumber) __pragma(warning(disable : warningNumber))
#define CS_DISABLE_GCC_WARNING(warningName)
#endif
/// Utility functions for all sorts of stuff.
namespace cs::utils {
/// Defines the order in which objects will be rendered.
enum class CS_UTILS_EXPORT DrawOrder : int {
eClearHDRBuffer = 100,
ePlanets = 200,
eOpaqueItems = 300,
eStars = 400,
eAtmospheres = 500,
eToneMapping = 600,
eOpaqueNonHDR = 650,
eTransparentItems = 700,
eRay = 800,
eGui = 900
};
template <typename T>
bool contains(T const& container, typename T::value_type const& item) {
return std::find(std::begin(container), std::end(container), item) != std::end(container);
}
template <typename K, typename V>
bool contains(std::map<K, V> const& map, K const& key) {
return map.find(key) != map.end();
}
template <typename K, typename V>
bool contains(std::unordered_map<K, V> const& map, K const& key) {
return map.find(key) != map.end();
}
/// Returns true if the given string contains at least once the given value.
CS_UTILS_EXPORT bool contains(std::string const& string, std::string const& value);
/// Returns true if the start of the given string fully contains the given prefix.
CS_UTILS_EXPORT bool startsWith(std::string const& string, std::string const& prefix);
/// Returns true if the end of the given string fully contains the given postfix.
CS_UTILS_EXPORT bool endsWith(std::string const& string, std::string const& postfix);
/// Replaces all occurrences of the sPlaceHolder parameter in sInput by sNewString.
CS_UTILS_EXPORT void replaceString(
std::string& sInput, std::string const& sPlaceHolder, std::string const& sNewString);
template <typename T>
std::string toString(T const& v) {
std::ostringstream oss;
oss << v;
return oss.str();
}
template <>
CS_UTILS_EXPORT std::string toString(float const& v);
template <>
CS_UTILS_EXPORT std::string toString(double const& v);
template <>
CS_UTILS_EXPORT std::string toString(std::string const& v);
CS_UTILS_EXPORT std::string toString(char const* v);
template <typename T>
T fromString(std::string const& v) {
std::istringstream iss(v);
T r;
iss >> r;
return r;
}
/// Splits the given string into chunks separated by the delim character.
CS_UTILS_EXPORT std::vector<std::string> splitString(std::string const& s, char delim);
/// A template to cast an enum class to its underlying type.
template <typename T>
constexpr typename std::underlying_type<T>::type enumCast(T val) {
return static_cast<typename std::underlying_type<T>::type>(val);
}
/// Well, does what is says.
float CS_UTILS_EXPORT getCurrentFarClipDistance();
/// Executes a system command and returns the output.
std::string exec(std::string const& cmd);
/// Can be used to check the operating system at compile time.
enum class OS { eLinux, eWindows };
#ifdef __linux__
constexpr OS HostOS = OS::eLinux;
#elif _WIN32
constexpr OS HostOS = OS::eWindows;
#endif
} // namespace cs::utils
#endif // CS_UTILS_UTILS_HPP
|
grend3d/grend
|
include/grend/gameMain.hpp
|
#pragma once
#include <grend/gameState.hpp> // TODO: rename to gameState.h
#include <grend/engine.hpp> // TODO: rename to renderer.h
#include <grend/glManager.hpp> // TODO: rename
#include <grend/gameView.hpp>
#include <grend/jobQueue.hpp>
#include <grend/timers.hpp>
#include <grend/audioMixer.hpp>
#include <grend/camera.hpp>
#include <grend/ecs/ecs.hpp>
#include <grend/ecs/serializer.hpp>
#include <memory>
#include <stdint.h>
namespace grendx {
// gameView takes gameMain pointers
class gameView;
// abstract class, should be derived from
class gameMain {
public:
gameMain(std::string name="grendx");
virtual ~gameMain();
virtual int step(void);
virtual int run(void);
virtual void setView(std::shared_ptr<gameView> nview);
virtual void handleInput(void);
virtual void clearMetrics(void);
bool running = false;
context ctx;
// state objects
// TODO: these might as well be unique_ptrs
std::shared_ptr<gameState> state = nullptr;
std::shared_ptr<gameView> view = nullptr;
std::shared_ptr<renderContext> rend = nullptr;
std::shared_ptr<physics> phys = nullptr;
std::shared_ptr<audioMixer> audio = nullptr;
std::shared_ptr<jobQueue> jobs = nullptr;
// ECS state
std::shared_ptr<ecs::entityManager> entities = nullptr;
std::shared_ptr<ecs::factories> factories = nullptr;
// FPS info
sma_counter frame_timer;
uint32_t last_frame_time = 0;
struct {
unsigned drawnMeshes = 0;
} metrics;
};
// common world-drawing function
void renderWorld(gameMain *game, camera::ptr cam, renderFlags& flags);
void renderWorld(gameMain *game, camera::ptr cam,
renderQueue& base, renderFlags& flags);
// namespace grendx
}
|
etenel/MovieTest
|
app/src/main/java/com/eternel/wlsmv/mvp/contract/TagImageContract.java
|
package com.eternel.wlsmv.mvp.contract;
import com.eternel.wlsmv.mvp.model.entity.TagDetailListEntity;
import com.jess.arms.mvp.IView;
import com.jess.arms.mvp.IModel;
import io.reactivex.Observable;
public interface TagImageContract {
//对于经常使用的关于UI的方法可以定义到IView中,如显示隐藏进度条,和显示文字消息
interface View extends IView {
void endLoadMore();
String getTagName();
String getOrder();
}
//Model层定义接口,外部只需关心Model返回的数据,无需关心内部细节,即是否使用缓存
interface Model extends IModel {
Observable<TagDetailListEntity> getTagDetailList(String tag, int page, int count, String order);
}
}
|
django-doctor/lite-api
|
api/organisations/tests/tests_sites.py
|
from faker import Faker
from rest_framework import status
from rest_framework.reverse import reverse
from api.audit_trail.models import Audit
from lite_content.lite_api import strings
from api.organisations.models import Site
from api.organisations.tests.factories import OrganisationFactory
from test_helpers.clients import DataTestClient
from api.users.models import UserOrganisationRelationship
faker = Faker()
class OrganisationSitesTests(DataTestClient):
def test_site_list(self):
self.exporter_user.set_role(self.organisation, self.exporter_super_user_role)
url = reverse("organisations:sites", kwargs={"org_pk": self.organisation.id})
# Create an additional organisation and site to ensure that only sites from the first organisation are shown
OrganisationFactory()
response = self.client.get(url, **self.exporter_headers)
response_data = response.json()
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(len(response_data["sites"]), 1)
response_site = response_data["sites"][0]
primary_site = self.organisation.primary_site
self.assertEqual(response_site["id"], str(primary_site.id))
self.assertEqual(response_site["name"], str(primary_site.name))
self.assertEqual(response_site["address"]["id"], str(primary_site.address.id))
def test_get_site_list_with_total_users(self):
self.exporter_user.set_role(self.organisation, self.exporter_super_user_role)
url = reverse("organisations:sites", kwargs={"org_pk": self.organisation.id}) + "?get_total_users=True"
response = self.client.get(url, **self.exporter_headers)
response_data = response.json()
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(len(response_data["sites"]), 1)
self.assertEqual(response_data["sites"][0]["assigned_users_count"], 1)
def test_view_site(self):
user = self.create_exporter_user(self.organisation)
UserOrganisationRelationship.objects.get(user=user).sites.add(self.organisation.primary_site)
self.exporter_user.set_role(self.organisation, self.exporter_super_user_role)
url = reverse(
"organisations:site", kwargs={"org_pk": self.organisation.id, "pk": self.organisation.primary_site_id}
)
response = self.client.get(url, **self.exporter_headers)
response_data = response.json()
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(response_data["name"], self.organisation.primary_site.name)
self.assertEqual(
response_data["users"],
[{"id": str(user.pk), "first_name": user.first_name, "last_name": user.last_name, "email": user.email,}],
)
self.assertEqual(
response_data["admin_users"],
[
{
"id": str(self.exporter_user.pk),
"first_name": self.exporter_user.first_name,
"last_name": self.exporter_user.last_name,
"email": self.exporter_user.email,
}
],
)
def test_add_uk_site(self):
url = reverse("organisations:sites", kwargs={"org_pk": self.organisation.id})
data = {
"name": "regional site",
"records_located_step": True,
"site_records_stored_here": True,
"address": {
"address_line_1": "a street",
"city": "london",
"postcode": "E14GH",
"region": "Hertfordshire",
},
}
response = self.client.post(url, data, **self.gov_headers)
response_data = response.json()["site"]
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
self.assertEqual(Site.objects.filter(organisation=self.organisation).count(), 2)
site = Site.objects.get(name=data["name"])
# Assert that "records_located_at" is set to the site being created
self.assertEqual(
response_data["records_located_at"],
{
"id": str(site.id),
"name": site.name,
"address": {
"address_line_1": site.address.address_line_1,
"address_line_2": site.address.address_line_2,
"city": site.address.city,
"country": {"name": site.address.country.name},
"postcode": site.address.postcode,
"region": site.address.region,
},
},
)
self.assertEqual(Audit.objects.count(), 1)
def test_add_uk_site_no_site_record_location_error(self):
url = reverse("organisations:sites", kwargs={"org_pk": self.organisation.id})
data = {
"name": "regional site",
"records_located_step": True,
"address": {
"address_line_1": "a street",
"city": "london",
"postcode": "E14GH",
"region": "Hertfordshire",
},
}
response = self.client.post(url, data, **self.gov_headers)
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
self.assertEqual(response.json()["errors"], {"site_records_stored_here": [strings.Site.NO_RECORDS_LOCATED_AT]})
self.assertEqual(Site.objects.filter(organisation=self.organisation).count(), 1)
self.assertEqual(Audit.objects.count(), 0)
def test_add_uk_site_site_record_location_no_and_not_selected_error(self):
url = reverse("organisations:sites", kwargs={"org_pk": self.organisation.id})
data = {
"name": "regional site",
"records_located_step": True,
"site_records_stored_here": False,
"address": {
"address_line_1": "a street",
"city": "london",
"postcode": "E14GH",
"region": "Hertfordshire",
},
}
response = self.client.post(url, data, **self.gov_headers)
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
self.assertEqual(response.json()["errors"], {"site_records_located_at": [strings.Site.NO_SITE_SELECTED]})
self.assertEqual(Site.objects.filter(organisation=self.organisation).count(), 1)
self.assertEqual(Audit.objects.count(), 0)
def test_add_uk_site_with_records_held_at_another_site_success(self):
url = reverse("organisations:sites", kwargs={"org_pk": self.organisation.id})
data = {
"name": "regional site",
"records_located_step": True,
"site_records_stored_here": "False",
"site_records_located_at": self.organisation.primary_site.id,
"address": {
"address_line_1": "a street",
"city": "london",
"postcode": "E14GH",
"region": "Hertfordshire",
},
}
response = self.client.post(url, data, **self.gov_headers)
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
self.assertEqual(Site.objects.filter(organisation=self.organisation).count(), 2)
self.assertEqual(response.json()["site"]["records_located_at"]["name"], self.organisation.primary_site.name)
self.assertEqual(Audit.objects.count(), 1)
def test_add_uk_site_and_assign_users(self):
exporter_user = self.create_exporter_user(self.organisation)
exporter_user_2 = self.create_exporter_user(self.organisation)
url = reverse("organisations:sites", kwargs={"org_pk": self.organisation.id})
data = {
"name": "regional site",
"address": {
"address_line_1": "a street",
"city": "london",
"postcode": "E14GH",
"region": "Hertfordshire",
},
"users": [exporter_user.pk, exporter_user_2.pk],
}
response = self.client.post(url, data, **self.gov_headers)
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
site = Site.objects.get(name=data["name"])
self.assertEqual(site.users.count(), 2)
def test_add_foreign_site(self):
url = reverse("organisations:sites", kwargs={"org_pk": self.organisation.id})
data = {
"name": "regional site",
"address": {"address": "a street", "country": "PL",},
}
response = self.client.post(url, data, **self.gov_headers)
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
self.assertEqual(Site.objects.filter(organisation=self.organisation).count(), 2)
def test_add_foreign_site_failure(self):
"""
Fail as only supplying an address field with country set to GB
"""
url = reverse("organisations:sites", kwargs={"org_pk": self.organisation.id})
data = {
"name": "regional site",
"address": {"address": "a street", "country": "GB",},
}
response = self.client.post(url, data, **self.gov_headers)
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
self.assertEqual(Site.objects.filter(organisation=self.organisation).count(), 1)
def test_add_uk_and_foreign_site_failure(self):
url = reverse("organisations:sites", kwargs={"org_pk": self.organisation.id})
data = {
"name": "regional site",
"address": {
"address_line_1": "a street",
"city": "london",
"postcode": "E14GH",
"region": "Hertfordshire",
"country": "GB",
"address": "a street",
},
}
response = self.client.post(url, data, **self.gov_headers)
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
self.assertEqual(Site.objects.filter(organisation=self.organisation).count(), 1)
def test_cannot_add_site_without_permission(self):
number_of_initial_sites = Site.objects.count()
url = reverse("organisations:sites", kwargs={"org_pk": self.organisation.id})
data = {}
response = self.client.post(url, data, **self.exporter_headers)
self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
self.assertEqual(Site.objects.count(), number_of_initial_sites)
class SitesUpdateTests(DataTestClient):
def setUp(self):
super().setUp()
self.data = {"name": faker.word()}
self.url = reverse(
"organisations:site", kwargs={"org_pk": self.organisation.id, "pk": self.organisation.primary_site.id}
)
def test_edit_site_name_success(self):
self.exporter_user.set_role(self.organisation, self.exporter_super_user_role)
response = self.client.patch(self.url, self.data, **self.exporter_headers)
self.organisation.primary_site.refresh_from_db()
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(self.organisation.primary_site.name, self.data["name"])
def test_edit_site_without_permission_failure(self):
response = self.client.patch(self.url, self.data, **self.exporter_headers)
self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
self.assertNotEqual(self.organisation.primary_site.name, self.data["name"])
def test_edit_site_records_location_not_set_failure(self):
self.data = {}
response = self.client.patch(self.url, self.data, **self.exporter_headers)
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
self.assertEqual(response.json()["errors"], {"site_records_stored_here": [strings.Site.NO_RECORDS_LOCATED_AT]})
def test_edit_site_records_held_at_another_location_site_not_chosen_failure(self):
self.data = {"site_records_stored_here": False}
response = self.client.patch(self.url, self.data, **self.exporter_headers)
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
self.assertEqual(response.json()["errors"], {"site_records_located_at": [strings.Site.NO_SITE_SELECTED]})
def test_edit_site_name_site_already_used_on_an_application_failure(self):
self.exporter_user.set_role(self.organisation, self.exporter_super_user_role)
self.organisation.primary_site.is_used_on_application = True
self.organisation.primary_site.save()
response = self.client.patch(self.url, self.data, **self.exporter_headers)
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
self.assertNotEqual(self.organisation.primary_site.name, self.data["name"])
self.assertEqual(
response.json()["errors"], {"site_records_stored_here": [strings.Site.CANNOT_CHANGE_SITE_IF_ALREADY_IN_USE]}
)
def test_edit_site_records_location_site_already_used_on_an_application_failure(self):
self.exporter_user.set_role(self.organisation, self.exporter_super_user_role)
self.organisation.primary_site.is_used_on_application = True
self.organisation.primary_site.save()
self.data = {"records_located_step": True, "site_records_stored_here": True}
response = self.client.patch(self.url, self.data, **self.exporter_headers)
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
self.assertEqual(
response.json()["errors"], {"site_records_stored_here": [strings.Site.CANNOT_CHANGE_SITE_IF_ALREADY_IN_USE]}
)
|
Robbbert/messui
|
src/mame/drivers/cvs.cpp
|
<reponame>Robbbert/messui<filename>src/mame/drivers/cvs.cpp
// license:BSD-3-Clause
// copyright-holders:<NAME>, Couriersud
/***************************************************************************
Century CVS System
MAIN BOARD:
FLAG LOW | FLAG HIGH
------------------------------------+-----------------------------------
1C00-1FFF SYSTEM RAM | SYSTEM RAM
|
|
1800-1BFF ATTRIBUTE RAM 32X28 | SCREEN RAM 32X28
1700 2636 1 | CHARACTER RAM 1 256BYTES OF 1K*
1600 2636 2 | CHARACTER RAM 2 256BYTES OF 1K*
1500 2636 3 | CHARACTER RAM 3 256BYTES OF 1K*
1400 BULLET RAM | PALETTE RAM 16BYTES
|
|
0000-13FF PROGRAM ROM'S | PROGRAM ROM'S
* Note the upper two address lines are latched using an I/O read. The I/O map only has
space for 128 character bit maps
The CPU CANNOT read the character PROMs
------
CVS I/O MAP
-----------
ADR14 ADR13 | READ | WRITE
------------+-------------------------------------------+-----------------------------
1 0 | COLLISION RESET | D0 = STARS ON
| | D1 = SHADE BRIGHTER TO RIGHT
| | D2 = SCREEN ROTATE
read/write | | D3 = SHADE BRIGHTER TO LEFT
Data | | D4 = LAMP 1 (CN1 1)
| | D5 = LAMP 2 (CN1 2)
| | D6 = SHADE BRIGHTER TO BOTTOM
| | D7 = SHADE BRIGHTER TO TOP
------------+-------------------------------------------+------------------------------
X 1 | A0-2: 0 STROBE CN2 1 | VERTICAL SCROLL OFFSET
| 1 STROBE CN2 11 |
| 2 STROBE CN2 2 |
| 3 STROBE CN2 3 |
| 4 STROBE CN2 4 |
| 5 STROBE CN2 12 |
| 6 STROBE DIP SW3 |
| 7 STROBE DIP SW2 |
| |
read/write | A4-5: CHARACTER PROM/RAM SELECTION MODE |
extended | There are 256 characters in total. The |
| higher ones can be user defined in RAM. |
| The split between PROM and RAM characters |
| is variable. |
| ROM RAM |
| A4 A5 MODE CHARACTERS CHARACTERS |
| 0 0 0 224 (0-223) 32 (224-255)|
| 0 1 1 192 (0-191) 64 (192-255)|
| 1 0 2 256 (0-255) 0 |
| 1 1 3 128 (0-127) 128 (128-255)|
| |
| |
| A6-7: SELECT CHARACTER RAM's |
| UPPER ADDRESS BITS A8-9 |
| (see memory map) |
------------+-------------------------------------------+-------------------------------
0 0 | COLLISION DATA BYTE: | SOUND CONTROL PORT
| D0 = OBJECT 1 AND 2 |
| D1 = OBJECT 2 AND 3 |
read/write | D2 = OBJECT 1 AND 3 |
control | D3 = ANY OBJECT AND BULLET |
| D4 = OBJECT 1 AND CP1 OR CP2 |
| D5 = OBJECT 2 AND CP1 OR CP2 |
| D6 = OBJECT 3 AND CP1 OR CP2 |
| D7 = BULLET AND CP1 OR CP2 |
------------+-------------------------------------------+-------------------------------
Driver by
<NAME>
Hardware Info
Malcolm & Darren
Additional work
2009 Couriersud
Todo & FIXME:
- Emulate protection properly in later games (reads area 0x73fx);
- Superbike hangs indefinitely when collecting balloon bonus the
second time around, protection or s2650 core bug?
- the board most probably has discrete circuits. The 393Hz tone used
for shots (superbike) and collisions (8ball) is just a guess.
***************************************************************************/
#include "emu.h"
#include "includes/cvs.h"
#include "speaker.h"
/* Turn to 1 so all inputs are always available (this shall only be a debug feature) */
#define CVS_SHOW_ALL_INPUTS 0
#define VERBOSE 0
#define LOG(x) do { if (VERBOSE) logerror x; } while (0)
/*************************************
*
* Multiplexed memory access
*
*************************************/
WRITE_LINE_MEMBER(cvs_state::write_s2650_flag)
{
m_s2650_flag = state;
}
uint8_t cvs_state::cvs_video_or_color_ram_r(offs_t offset)
{
if (m_s2650_flag)
return m_video_ram[offset];
else
return m_color_ram[offset];
}
void cvs_state::cvs_video_or_color_ram_w(offs_t offset, uint8_t data)
{
if (m_s2650_flag)
m_video_ram[offset] = data;
else
m_color_ram[offset] = data;
}
uint8_t cvs_state::cvs_bullet_ram_or_palette_r(offs_t offset)
{
if (m_s2650_flag)
return m_palette_ram[offset & 0x0f];
else
return m_bullet_ram[offset];
}
void cvs_state::cvs_bullet_ram_or_palette_w(offs_t offset, uint8_t data)
{
if (m_s2650_flag)
m_palette_ram[offset & 0x0f] = data;
else
m_bullet_ram[offset] = data;
}
uint8_t cvs_state::cvs_s2636_0_or_character_ram_r(offs_t offset)
{
if (m_s2650_flag)
return m_character_ram[(0 * 0x800) | 0x400 | m_character_ram_page_start | offset];
else
return m_s2636[0]->read_data(offset);
}
void cvs_state::cvs_s2636_0_or_character_ram_w(offs_t offset, uint8_t data)
{
if (m_s2650_flag)
{
offset |= (0 * 0x800) | 0x400 | m_character_ram_page_start;
m_character_ram[offset] = data;
m_gfxdecode->gfx(1)->mark_dirty((offset / 8) % 256);
}
else
m_s2636[0]->write_data(offset, data);
}
uint8_t cvs_state::cvs_s2636_1_or_character_ram_r(offs_t offset)
{
if (m_s2650_flag)
return m_character_ram[(1 * 0x800) | 0x400 | m_character_ram_page_start | offset];
else
return m_s2636[1]->read_data(offset);
}
void cvs_state::cvs_s2636_1_or_character_ram_w(offs_t offset, uint8_t data)
{
if (m_s2650_flag)
{
offset |= (1 * 0x800) | 0x400 | m_character_ram_page_start;
m_character_ram[offset] = data;
m_gfxdecode->gfx(1)->mark_dirty((offset / 8) % 256);
}
else
m_s2636[1]->write_data(offset, data);
}
uint8_t cvs_state::cvs_s2636_2_or_character_ram_r(offs_t offset)
{
if (m_s2650_flag)
return m_character_ram[(2 * 0x800) | 0x400 | m_character_ram_page_start | offset];
else
return m_s2636[2]->read_data(offset);
}
void cvs_state::cvs_s2636_2_or_character_ram_w(offs_t offset, uint8_t data)
{
if (m_s2650_flag)
{
offset |= (2 * 0x800) | 0x400 | m_character_ram_page_start;
m_character_ram[offset] = data;
m_gfxdecode->gfx(1)->mark_dirty((offset / 8) % 256);
}
else
m_s2636[2]->write_data(offset, data);
}
/*************************************
*
* Interrupt generation
*
*************************************/
INTERRUPT_GEN_MEMBER(cvs_state::cvs_main_cpu_interrupt)
{
m_maincpu->pulse_input_line(0, m_maincpu->minimum_quantum_time());
cvs_scroll_stars();
}
WRITE_LINE_MEMBER(cvs_state::cvs_slave_cpu_interrupt)
{
m_audiocpu->set_input_line(0, state ? ASSERT_LINE : CLEAR_LINE);
}
/*************************************
*
* Input port access
*
*************************************/
uint8_t cvs_state::cvs_input_r(offs_t offset)
{
uint8_t ret = 0;
/* the upper 4 bits of the address is used to select the character banking attributes */
m_character_banking_mode = (offset >> 4) & 0x03;
m_character_ram_page_start = (offset << 2) & 0x300;
/* the lower 4 (or 3?) bits select the port to read */
switch (offset & 0x0f) /* might be 0x07 */
{
case 0x00: ret = ioport("IN0")->read(); break;
case 0x02: ret = ioport("IN1")->read(); break;
case 0x03: ret = ioport("IN2")->read(); break;
case 0x04: ret = ioport("IN3")->read(); break;
case 0x06: ret = ioport("DSW3")->read(); break;
case 0x07: ret = ioport("DSW2")->read(); break;
default: logerror("%04x : CVS: Reading unmapped input port 0x%02x\n", m_maincpu->pc(), offset & 0x0f); break;
}
return ret;
}
/*************************************
*
* Timing
*
*************************************/
#if 0
READ_LINE_MEMBER(cvs_state::cvs_393hz_clock_r)
{
return m_cvs_393hz_clock;
}
#endif
TIMER_CALLBACK_MEMBER(cvs_state::cvs_393hz_timer_cb)
{
m_cvs_393hz_clock = !m_cvs_393hz_clock;
/* quasar.c games use this timer but have no dac3! */
if (m_dac3 != nullptr)
{
if (m_dac3_state[2])
m_dac3->write(m_cvs_393hz_clock);
}
}
void cvs_state::start_393hz_timer()
{
m_cvs_393hz_timer = machine().scheduler().timer_alloc(timer_expired_delegate(FUNC(cvs_state::cvs_393hz_timer_cb),this));
m_cvs_393hz_timer->adjust(attotime::from_hz(30*393), 0, attotime::from_hz(30*393));
}
/*************************************
*
* 4-bit DAC
*
*************************************/
void cvs_state::cvs_4_bit_dac_data_w(offs_t offset, uint8_t data)
{
uint8_t dac_value;
static int old_data[4] = {0,0,0,0};
if (data != old_data[offset])
{
LOG(("4BIT: %02x %02x\n", offset, data));
old_data[offset] = data;
}
m_cvs_4_bit_dac_data[offset] = data >> 7;
/* merge into D0-D3 */
dac_value = (m_cvs_4_bit_dac_data[0] << 0) |
(m_cvs_4_bit_dac_data[1] << 1) |
(m_cvs_4_bit_dac_data[2] << 2) |
(m_cvs_4_bit_dac_data[3] << 3);
/* output */
m_dac2->write(dac_value);
}
void cvs_state::cvs_unknown_w(offs_t offset, uint8_t data)
{
/* offset 2 is used in 8ball
* offset 0 is used in spacefrt
* offset 3 is used in darkwar
*
* offset 1 is not used (no trace in disassembly)
*/
if (data != m_dac3_state[offset])
{
if (VERBOSE && offset != 2)
popmessage("Unknown: %02x %02x\n", offset, data);
m_dac3_state[offset] = data;
}
}
/*************************************
*
* Speech hardware
*
*************************************/
void cvs_state::cvs_speech_rom_address_lo_w(uint8_t data)
{
/* assuming that d0-d2 are cleared here */
m_speech_rom_bit_address = (m_speech_rom_bit_address & 0xf800) | (data << 3);
LOG(("%04x : CVS: Speech Lo %02x Address = %04x\n", m_speechcpu->pc(), data, m_speech_rom_bit_address >> 3));
}
void cvs_state::cvs_speech_rom_address_hi_w(uint8_t data)
{
m_speech_rom_bit_address = (m_speech_rom_bit_address & 0x07ff) | (data << 11);
LOG(("%04x : CVS: Speech Hi %02x Address = %04x\n", m_speechcpu->pc(), data, m_speech_rom_bit_address >> 3));
}
uint8_t cvs_state::cvs_speech_command_r()
{
/* FIXME: this was by observation on board ???
* -bit 7 is TMS status (active LO) */
return ((m_tms5110->ctl_r() ^ 1) << 7) | (m_soundlatch->read() & 0x7f);
}
void cvs_state::cvs_tms5110_ctl_w(offs_t offset, uint8_t data)
{
uint8_t ctl;
/*
* offset 0: CS ?
*/
m_tms5110_ctl_data[offset] = (~data >> 7) & 0x01;
ctl = 0 | /* CTL1 */
(m_tms5110_ctl_data[1] << 1) | /* CTL2 */
(m_tms5110_ctl_data[2] << 2) | /* CTL4 */
(m_tms5110_ctl_data[1] << 3); /* CTL8 */
LOG(("CVS: Speech CTL = %04x %02x %02x\n", ctl, offset, data));
m_tms5110->ctl_w(ctl);
}
void cvs_state::cvs_tms5110_pdc_w(offs_t offset, uint8_t data)
{
uint8_t out = ((~data) >> 7) & 1;
LOG(("CVS: Speech PDC = %02x %02x\n", offset, out));
m_tms5110->pdc_w(out);
}
READ_LINE_MEMBER(cvs_state::speech_rom_read_bit)
{
int bit;
uint8_t *ROM = memregion("speechdata")->base();
/* before reading the bit, clamp the address to the region length */
m_speech_rom_bit_address &= ((memregion("speechdata")->bytes() * 8) - 1);
bit = BIT(ROM[m_speech_rom_bit_address >> 3], m_speech_rom_bit_address & 0x07);
/* prepare for next bit */
m_speech_rom_bit_address++;
return bit;
}
/*************************************
*
* Inter-CPU communications
*
*************************************/
void cvs_state::audio_command_w(uint8_t data)
{
LOG(("data %02x\n", data));
/* cause interrupt on audio CPU if bit 7 set */
m_soundlatch->write(data);
cvs_slave_cpu_interrupt(data & 0x80 ? 1 : 0);
}
/*************************************
*
* Main CPU memory/IO handlers
*
*************************************/
void cvs_state::cvs_main_cpu_map(address_map &map)
{
map.global_mask(0x7fff);
map(0x0000, 0x13ff).rom();
map(0x1400, 0x14ff).mirror(0x6000).rw(FUNC(cvs_state::cvs_bullet_ram_or_palette_r), FUNC(cvs_state::cvs_bullet_ram_or_palette_w)).share("bullet_ram");
map(0x1500, 0x15ff).mirror(0x6000).rw(FUNC(cvs_state::cvs_s2636_2_or_character_ram_r), FUNC(cvs_state::cvs_s2636_2_or_character_ram_w));
map(0x1600, 0x16ff).mirror(0x6000).rw(FUNC(cvs_state::cvs_s2636_1_or_character_ram_r), FUNC(cvs_state::cvs_s2636_1_or_character_ram_w));
map(0x1700, 0x17ff).mirror(0x6000).rw(FUNC(cvs_state::cvs_s2636_0_or_character_ram_r), FUNC(cvs_state::cvs_s2636_0_or_character_ram_w));
map(0x1800, 0x1bff).mirror(0x6000).rw(FUNC(cvs_state::cvs_video_or_color_ram_r), FUNC(cvs_state::cvs_video_or_color_ram_w)).share("video_ram");
map(0x1c00, 0x1fff).mirror(0x6000).ram();
map(0x2000, 0x33ff).rom();
map(0x4000, 0x53ff).rom();
map(0x6000, 0x73ff).rom();
}
void cvs_state::cvs_main_cpu_io_map(address_map &map)
{
map(0x00, 0xff).rw(FUNC(cvs_state::cvs_input_r), FUNC(cvs_state::cvs_scroll_w));
}
void cvs_state::cvs_main_cpu_data_map(address_map &map)
{
map(S2650_CTRL_PORT, S2650_CTRL_PORT).rw(FUNC(cvs_state::cvs_collision_r), FUNC(cvs_state::audio_command_w));
map(S2650_DATA_PORT, S2650_DATA_PORT).rw(FUNC(cvs_state::cvs_collision_clear), FUNC(cvs_state::cvs_video_fx_w));
}
/*************************************
*
* DAC driving CPU memory/IO handlers
*
*************************************/
void cvs_state::cvs_dac_cpu_map(address_map &map)
{
map.global_mask(0x7fff);
map(0x0000, 0x0fff).rom();
map(0x1000, 0x107f).ram();
map(0x1800, 0x1800).r(m_soundlatch, FUNC(generic_latch_8_device::read));
map(0x1840, 0x1840).w("dac1", FUNC(dac_byte_interface::data_w));
map(0x1880, 0x1883).w(FUNC(cvs_state::cvs_4_bit_dac_data_w)).share("4bit_dac");
map(0x1884, 0x1887).w(FUNC(cvs_state::cvs_unknown_w)).share("dac3_state"); /* ???? not connected to anything */
}
/*************************************
*
* Speech driving CPU memory/IO handlers
*
*************************************/
void cvs_state::cvs_speech_cpu_map(address_map &map)
{
map.global_mask(0x7fff);
map(0x0000, 0x07ff).rom();
map(0x1d00, 0x1d00).w(FUNC(cvs_state::cvs_speech_rom_address_lo_w));
map(0x1d40, 0x1d40).w(FUNC(cvs_state::cvs_speech_rom_address_hi_w));
map(0x1d80, 0x1d80).r(FUNC(cvs_state::cvs_speech_command_r));
map(0x1ddc, 0x1dde).w(FUNC(cvs_state::cvs_tms5110_ctl_w)).share("tms5110_ctl");
map(0x1ddf, 0x1ddf).w(FUNC(cvs_state::cvs_tms5110_pdc_w));
}
/*************************************
*
* Standard CVS port definitions
*
*************************************/
static INPUT_PORTS_START( cvs )
PORT_START("IN0") /* Matrix 0 */
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_START1 )
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_START2 )
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_COIN2 )
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_COIN1 )
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_BUTTON1 ) PORT_COCKTAIL /* "Red button" */
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_BUTTON1 ) /* "Red button" */
PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_START("IN1")
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_BUTTON2 ) PORT_COCKTAIL /* "Green button" */
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_BUTTON2 ) /* "Green button" */
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT ) PORT_COCKTAIL
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT ) PORT_COCKTAIL
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT )
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT )
PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_START("IN2")
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_SERVICE1 ) /* not sure it's SERVICE1 : it uses "Coin B" coinage and doesn't say "CREDIT" */
PORT_BIT( 0xfe, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_START("IN3")
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_JOYSTICK_UP ) PORT_COCKTAIL
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN ) PORT_COCKTAIL
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_JOYSTICK_UP )
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN )
PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_START("DSW3")
PORT_DIPUNUSED( 0x01, IP_ACTIVE_HIGH ) /* can't tell if it's ACTIVE_HIGH or ACTIVE_LOW */
PORT_DIPUNUSED( 0x02, IP_ACTIVE_HIGH ) /* can't tell if it's ACTIVE_HIGH or ACTIVE_LOW */
PORT_DIPUNUSED( 0x04, IP_ACTIVE_HIGH ) /* can't tell if it's ACTIVE_HIGH or ACTIVE_LOW */
PORT_DIPUNUSED( 0x08, IP_ACTIVE_HIGH ) /* can't tell if it's ACTIVE_HIGH or ACTIVE_LOW */
PORT_DIPNAME( 0x10, 0x00, DEF_STR( Cabinet ) )
PORT_DIPSETTING( 0x00, DEF_STR( Upright ) )
PORT_DIPSETTING( 0x10, DEF_STR( Cocktail ) )
PORT_DIPUNUSED( 0x20, IP_ACTIVE_HIGH ) /* can't tell if it's ACTIVE_HIGH or ACTIVE_LOW */
PORT_START("DSW2")
PORT_DIPNAME( 0x03, 0x00, DEF_STR( Coin_A ) )
PORT_DIPSETTING( 0x03, DEF_STR( 4C_1C ) )
PORT_DIPSETTING( 0x01, DEF_STR( 3C_1C ) )
PORT_DIPSETTING( 0x02, DEF_STR( 2C_1C ) )
PORT_DIPSETTING( 0x00, DEF_STR( 1C_1C ) )
PORT_DIPNAME( 0x0c, 0x0c, DEF_STR( Coin_B ) )
PORT_DIPSETTING( 0x0c, DEF_STR( 1C_2C ) )
PORT_DIPSETTING( 0x04, DEF_STR( 1C_3C ) )
PORT_DIPSETTING( 0x08, DEF_STR( 1C_4C ) )
PORT_DIPSETTING( 0x00, DEF_STR( 1C_5C ) )
PORT_DIPNAME( 0x10, 0x00, DEF_STR( Lives ) )
PORT_DIPSETTING( 0x00, "3" )
PORT_DIPSETTING( 0x10, "5" )
PORT_DIPUNUSED( 0x20, IP_ACTIVE_HIGH ) /* can't tell if it's ACTIVE_HIGH or ACTIVE_LOW */
INPUT_PORTS_END
static INPUT_PORTS_START( cvs_registration )
PORT_INCLUDE(cvs)
PORT_MODIFY("DSW3")
PORT_DIPNAME( 0x01, 0x01, "Registration" ) /* can't tell what shall be the default value */
PORT_DIPSETTING( 0x00, DEF_STR( Off ) )
PORT_DIPSETTING( 0x01, DEF_STR( On ) )
PORT_DIPNAME( 0x02, 0x02, "Registration Length" ) /* can't tell what shall be the default value */
PORT_DIPSETTING( 0x02, "3" )
PORT_DIPSETTING( 0x00, "10" )
/* bits 2 and 3 determine bonus life settings but they might change from game to game - they are sometimes unused */
PORT_MODIFY("DSW2")
/* Told to be "Meter Pulses" but I don't know what this means */
PORT_DIPNAME( 0x20, 0x00, DEF_STR( Unknown ) ) /* has an effect when COIN2 is pressed (when COIN1 is pressed, value always 1 */
PORT_DIPSETTING( 0x00, "2" )
PORT_DIPSETTING( 0x20, "5" )
INPUT_PORTS_END
/*************************************
*
* Games port definitions
*
*************************************/
static INPUT_PORTS_START( cosmos )
PORT_INCLUDE(cvs)
#if !CVS_SHOW_ALL_INPUTS
PORT_MODIFY("IN2")
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_UNUSED ) /* IPT_SERVICE1 */
PORT_MODIFY("IN3")
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_UNUSED ) /* IPT_JOYSTICK_UP PORT_COCKTAIL */
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_UNUSED ) /* IPT_JOYSTICK_DOWN PORT_COCKTAIL */
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_UNUSED ) /* IPT_JOYSTICK_UP */
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_UNUSED ) /* IPT_JOYSTICK_DOWN */
#endif
PORT_MODIFY("DSW3")
/* DSW3 bits 0 and 1 stored at 0x7d55 (0, 2, 1, 3) - code at 0x66f3 - not read back */
PORT_DIPNAME( 0x0c, 0x0c, DEF_STR( Bonus_Life ) )
PORT_DIPSETTING( 0x0c, "10k only" ) /* displays "10000" */
PORT_DIPSETTING( 0x08, "20k only" ) /* displays "20000" */
PORT_DIPSETTING( 0x04, "30k only" ) /* displays "30000" */
PORT_DIPSETTING( 0x00, "40k only" ) /* displays "40000" */
INPUT_PORTS_END
static INPUT_PORTS_START( darkwar )
PORT_INCLUDE(cvs)
#if !CVS_SHOW_ALL_INPUTS
PORT_MODIFY("IN1")
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_UNUSED ) /* IPT_BUTTON2 PORT_COCKTAIL */
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_UNUSED ) /* IPT_BUTTON2 */
PORT_MODIFY("IN2")
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_UNUSED ) /* IPT_SERVICE1 */
PORT_MODIFY("IN3")
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_UNUSED ) /* IPT_JOYSTICK_UP PORT_COCKTAIL */
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_UNUSED ) /* IPT_JOYSTICK_DOWN PORT_COCKTAIL */
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_UNUSED ) /* IPT_JOYSTICK_UP */
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_UNUSED ) /* IPT_JOYSTICK_DOWN */
#endif
/* DSW3 bits 0 to 3 are not read */
INPUT_PORTS_END
static INPUT_PORTS_START( spacefrt )
PORT_INCLUDE(cvs)
#if !CVS_SHOW_ALL_INPUTS
PORT_MODIFY("IN2")
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_UNUSED ) /* IPT_SERVICE1 */
PORT_MODIFY("IN3")
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_UNUSED ) /* IPT_JOYSTICK_UP PORT_COCKTAIL */
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_UNUSED ) /* IPT_JOYSTICK_DOWN PORT_COCKTAIL */
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_UNUSED ) /* IPT_JOYSTICK_UP */
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_UNUSED ) /* IPT_JOYSTICK_DOWN */
#endif
PORT_MODIFY("DSW3")
/* DSW3 bits 0 and 1 stored at 0x7d3f (0, 2, 1, 3) - code at 0x6895 - not read back */
PORT_DIPNAME( 0x0c, 0x0c, DEF_STR( Bonus_Life ) )
PORT_DIPSETTING( 0x0c, "100k only" ) /* displays "50000" */
PORT_DIPSETTING( 0x08, "150k only" ) /* displays "110000" */
PORT_DIPSETTING( 0x04, "200k only" ) /* displays "200000" */
PORT_DIPSETTING( 0x00, DEF_STR( None ) ) /* displays "200000" */
INPUT_PORTS_END
static INPUT_PORTS_START( 8ball )
PORT_INCLUDE(cvs_registration)
#if !CVS_SHOW_ALL_INPUTS
PORT_MODIFY("IN1")
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_UNUSED ) /* IPT_BUTTON2 PORT_COCKTAIL */
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_UNUSED ) /* IPT_BUTTON2 */
#endif
PORT_MODIFY("DSW3")
PORT_DIPNAME( 0x0c, 0x0c, DEF_STR( Bonus_Life ) )
PORT_DIPSETTING( 0x0c, "10k only" ) /* displays "10000" */
PORT_DIPSETTING( 0x08, "20k only" ) /* displays "20000" */
PORT_DIPSETTING( 0x04, "40k only" ) /* displays "80000" */
PORT_DIPSETTING( 0x00, "80k only" ) /* displays "80000" */
PORT_DIPNAME( 0x20, 0x00, "Colors" ) /* stored at 0x1ed4 - code at 0x0847 ('8ball') or 0x08af ('8ball1') */
PORT_DIPSETTING( 0x00, "Palette 1" ) /* table at 0x0781 ('8ball') or 0x07e9 ('8ball1') - 16 bytes */
PORT_DIPSETTING( 0x20, "Palette 2" ) /* table at 0x0791 ('8ball') or 0x07f9 ('8ball1') - 16 bytes */
/* DSW2 bit 5 stored at 0x1d93 - code at 0x0858 ('8ball') or 0x08c0 ('8ball1') - read back code at 0x0073 */
INPUT_PORTS_END
static INPUT_PORTS_START( logger )
PORT_INCLUDE(cvs_registration)
#if !CVS_SHOW_ALL_INPUTS
PORT_MODIFY("IN1")
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_UNUSED ) /* IPT_BUTTON2 PORT_COCKTAIL */
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_UNUSED ) /* IPT_BUTTON2 */
#endif
PORT_MODIFY("DSW3")
PORT_DIPNAME( 0x0c, 0x0c, DEF_STR( Bonus_Life ) )
PORT_DIPSETTING( 0x0c, "10k only" ) /* displays "10000" */
PORT_DIPSETTING( 0x08, "20k only" ) /* displays "20000" */
PORT_DIPSETTING( 0x04, "40k only" ) /* displays "40000" */
PORT_DIPSETTING( 0x00, "80k only" ) /* displays "80000" */
/* DSW3 bit 5 stored at 0x7dc8 - code at 0x6eb6 - not read back */
/* DSW2 bit 5 stored at 0x7da1 - code at 0x6ec7 - read back code at 0x0073 */
INPUT_PORTS_END
static INPUT_PORTS_START( dazzler )
PORT_INCLUDE(cvs_registration)
#if !CVS_SHOW_ALL_INPUTS
PORT_MODIFY("IN1")
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_UNUSED ) /* IPT_BUTTON2 PORT_COCKTAIL */
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_UNUSED ) /* IPT_BUTTON2 */
#endif
PORT_MODIFY("DSW3")
PORT_DIPNAME( 0x0c, 0x0c, DEF_STR( Bonus_Life ) )
PORT_DIPSETTING( 0x0c, "10k only" ) /* displays "10000" */
PORT_DIPSETTING( 0x04, "20k only" ) /* displays "20000" */
PORT_DIPSETTING( 0x08, "40k only" ) /* displays "40000" */
PORT_DIPSETTING( 0x00, "80k only" ) /* displays "80000" */
/* DSW2 bit 5 stored at 0x7d9c - code at 0x6b51 - read back code at 0x0099 */
INPUT_PORTS_END
static INPUT_PORTS_START( wallst )
PORT_INCLUDE(cvs_registration)
#if !CVS_SHOW_ALL_INPUTS
PORT_MODIFY("IN1")
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_UNUSED ) /* IPT_BUTTON2 PORT_COCKTAIL */
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_UNUSED ) /* IPT_BUTTON2 */
#endif
PORT_MODIFY("DSW3")
PORT_DIPNAME( 0x0c, 0x0c, DEF_STR( Bonus_Life ) )
PORT_DIPSETTING( 0x0c, "10k only" ) /* displays "10000" */
PORT_DIPSETTING( 0x04, "20k only" ) /* displays "20000" */
PORT_DIPSETTING( 0x08, "40k only" ) /* displays "40000" */
PORT_DIPSETTING( 0x00, "80k only" ) /* displays "80000" */
/* DSW2 bit 5 stored at 0x1e95 - code at 0x1232 - read back code at 0x6054 */
INPUT_PORTS_END
static INPUT_PORTS_START( radarzon )
PORT_INCLUDE(cvs_registration)
#if !CVS_SHOW_ALL_INPUTS
PORT_MODIFY("IN1")
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_UNUSED ) /* IPT_BUTTON2 PORT_COCKTAIL */
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_UNUSED ) /* IPT_BUTTON2 */
#endif
PORT_MODIFY("DSW3")
PORT_DIPNAME( 0x0c, 0x0c, DEF_STR( Bonus_Life ) )
PORT_DIPSETTING( 0x0c, "100k only" ) /* displays "100000" */
PORT_DIPSETTING( 0x04, "200k only" ) /* displays "200000" */
PORT_DIPSETTING( 0x08, "400k only" ) /* displays "400000" */
PORT_DIPSETTING( 0x00, "800k only" ) /* displays "800000" */
/* DSW2 bit 5 stored at 0x3d6e - code at 0x22aa - read back code at 0x00e4 */
INPUT_PORTS_END
static INPUT_PORTS_START( goldbug )
PORT_INCLUDE(cvs_registration)
#if !CVS_SHOW_ALL_INPUTS
PORT_MODIFY("IN1")
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_UNUSED ) /* IPT_BUTTON2 PORT_COCKTAIL */
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_UNUSED ) /* IPT_BUTTON2 */
#endif
PORT_MODIFY("DSW3")
PORT_DIPNAME( 0x0c, 0x0c, DEF_STR( Bonus_Life ) )
PORT_DIPSETTING( 0x0c, "100k only" ) /* displays "100000" */
PORT_DIPSETTING( 0x04, "200k only" ) /* displays "200000" */
PORT_DIPSETTING( 0x08, "400k only" ) /* displays "400000" */
PORT_DIPSETTING( 0x00, "800k only" ) /* displays "800000" */
/* DSW2 bit 5 stored at 0x3d89 - code at 0x3377 - read back code at 0x6054 */
INPUT_PORTS_END
static INPUT_PORTS_START( diggerc )
PORT_INCLUDE(cvs_registration)
#if !CVS_SHOW_ALL_INPUTS
PORT_MODIFY("IN1")
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_UNUSED ) /* IPT_BUTTON2 PORT_COCKTAIL */
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_UNUSED ) /* IPT_BUTTON2 */
#endif
PORT_MODIFY("DSW3")
PORT_DIPNAME( 0x0c, 0x0c, DEF_STR( Bonus_Life ) )
PORT_DIPSETTING( 0x0c, "50k only" ) /* displays "50000" */
PORT_DIPSETTING( 0x04, "100k only" ) /* displays "100000" */
PORT_DIPSETTING( 0x08, "150k only" ) /* displays "150000" */
PORT_DIPSETTING( 0x00, "200k only" ) /* displays "200000" */
/* DSW2 bit 5 stored at 0x3db3 - code at 0x22ad - read back code at 0x00e4 */
INPUT_PORTS_END
static INPUT_PORTS_START( heartatk )
PORT_INCLUDE(cvs_registration)
/* DSW3 bits 2 and 3 stored at 0x1c61 (0, 2, 1, 3) - code at 0x0c52
read back code at 0x2197 but untested value : bonus life always at 100000 */
/* DSW2 bit 5 stored at 0x1e76 - code at 0x0c5c - read back code at 0x00e4 */
INPUT_PORTS_END
static INPUT_PORTS_START( hunchbak )
PORT_INCLUDE(cvs_registration)
#if !CVS_SHOW_ALL_INPUTS
PORT_MODIFY("IN1")
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_UNUSED ) /* IPT_BUTTON2 PORT_COCKTAIL */
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_UNUSED ) /* IPT_BUTTON2 */
PORT_MODIFY("IN3")
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_UNUSED ) /* IPT_JOYSTICK_UP PORT_COCKTAIL */
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_UNUSED ) /* IPT_JOYSTICK_DOWN PORT_COCKTAIL */
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_UNUSED ) /* IPT_JOYSTICK_UP */
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_UNUSED ) /* IPT_JOYSTICK_DOWN */
#endif
PORT_MODIFY("DSW3")
PORT_DIPNAME( 0x0c, 0x0c, DEF_STR( Bonus_Life ) )
PORT_DIPSETTING( 0x0c, "10k only" ) /* displays "10000" */
PORT_DIPSETTING( 0x04, "20k only" ) /* displays "20000" */
PORT_DIPSETTING( 0x08, "40k only" ) /* displays "40000" */
PORT_DIPSETTING( 0x00, "80k only" ) /* displays "80000" */
/* hunchbak : DSW2 bit 5 stored at 0x5e97 - code at 0x516c - read back code at 0x6054 */
/* hunchbaka : DSW2 bit 5 stored at 0x1e97 - code at 0x0c0c - read back code at 0x6054 */
INPUT_PORTS_END
static INPUT_PORTS_START( superbik )
PORT_INCLUDE(cvs_registration)
/* DSW3 bits 2 and 3 are not read : bonus life alaways at 5000 */
/* DSW2 bit 5 stored at 0x1e79 - code at 0x060f - read back code at 0x25bf */
INPUT_PORTS_END
static INPUT_PORTS_START( raiders )
PORT_INCLUDE(cvs_registration)
/* DSW3 bits 2 and 3 are not read : bonus life alaways at 100000 */
PORT_MODIFY("DSW2")
PORT_DIPUNUSED( 0x10, IP_ACTIVE_HIGH ) /* always 4 lives - table at 0x4218 - 2 bytes */
/* DSW2 bit 5 stored at 0x1e79 - code at 0x1307 - read back code at 0x251d */
INPUT_PORTS_END
static INPUT_PORTS_START( hero )
PORT_INCLUDE(cvs_registration)
#if !CVS_SHOW_ALL_INPUTS
PORT_MODIFY("IN1")
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_UNUSED ) /* IPT_BUTTON2 PORT_COCKTAIL */
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_UNUSED ) /* IPT_BUTTON2 */
#endif
/* DSW3 bits 2 and 3 are not read : bonus life alaways at 150000 */
PORT_MODIFY("DSW2")
PORT_DIPUNUSED( 0x10, IP_ACTIVE_HIGH ) /* always 3 lives - table at 0x4ebb - 2 bytes */
/* DSW2 bit 5 stored at 0x1e99 - code at 0x0fdd - read back code at 0x0352 */
INPUT_PORTS_END
static INPUT_PORTS_START( huncholy )
PORT_INCLUDE(cvs_registration)
#if !CVS_SHOW_ALL_INPUTS
PORT_MODIFY("IN1")
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_UNUSED ) /* IPT_BUTTON2 PORT_COCKTAIL */
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_UNUSED ) /* IPT_BUTTON2 */
#endif
/* DSW3 bits 2 and 3 are not read : bonus life alaways at 20000 */
PORT_MODIFY("DSW2")
PORT_DIPUNUSED( 0x10, IP_ACTIVE_HIGH ) /* always 3 lives - table at 0x4531 - 2 bytes */
/* DSW2 bit 5 stored at 0x1e7c - code at 0x067d - read back code at 0x2f95 */
INPUT_PORTS_END
/*************************************
*
* Graphics definitions
*
*************************************/
static const gfx_layout charlayout =
{
8,8, /* 8*8 characters */
256, /* 256 characters */
3, /* 3 bits per pixel */
{ 0, 0x800*8, 0x1000*8 }, /* the bitplanes are separated */
{ 0, 1, 2, 3, 4, 5, 6, 7 },
{ 0*8, 1*8, 2*8, 3*8, 4*8, 5*8, 6*8, 7*8 },
8*8 /* every char takes 8 consecutive bytes */
};
static GFXDECODE_START( gfx_cvs )
GFXDECODE_ENTRY( "gfx1", 0x0000, charlayout, 0, 256+4 )
GFXDECODE_ENTRY( nullptr, 0x0000, charlayout, 0, 256+4 )
GFXDECODE_END
/*************************************
*
* Machine driver
*
*************************************/
void cvs_state::machine_start()
{
m_lamps.resolve();
/* allocate memory */
if (m_gfxdecode->gfx(1) != nullptr)
m_gfxdecode->gfx(1)->set_source(m_character_ram);
start_393hz_timer();
/* register state save */
save_item(NAME(m_character_banking_mode));
save_item(NAME(m_character_ram_page_start));
save_item(NAME(m_speech_rom_bit_address));
save_item(NAME(m_s2650_flag));
save_item(NAME(m_cvs_393hz_clock));
save_item(NAME(m_collision_register));
save_item(NAME(m_total_stars));
save_item(NAME(m_stars_on));
save_item(NAME(m_scroll_reg));
save_item(NAME(m_stars_scroll));
}
void cvs_state::machine_reset()
{
m_character_banking_mode = 0;
m_character_ram_page_start = 0;
m_speech_rom_bit_address = 0;
m_cvs_393hz_clock = 0;
m_collision_register = 0;
m_stars_on = 0;
m_scroll_reg = 0;
m_stars_scroll = 0;
m_s2650_flag = 0;
}
void cvs_state::cvs(machine_config &config)
{
/* basic machine hardware */
S2650(config, m_maincpu, XTAL(14'318'181)/16);
m_maincpu->set_addrmap(AS_PROGRAM, &cvs_state::cvs_main_cpu_map);
m_maincpu->set_addrmap(AS_IO, &cvs_state::cvs_main_cpu_io_map);
m_maincpu->set_addrmap(AS_DATA, &cvs_state::cvs_main_cpu_data_map);
m_maincpu->set_vblank_int("screen", FUNC(cvs_state::cvs_main_cpu_interrupt));
m_maincpu->sense_handler().set("screen", FUNC(screen_device::vblank));
m_maincpu->flag_handler().set(FUNC(cvs_state::write_s2650_flag));
m_maincpu->intack_handler().set_constant(0x03);
S2650(config, m_audiocpu, XTAL(14'318'181)/16);
m_audiocpu->set_addrmap(AS_PROGRAM, &cvs_state::cvs_dac_cpu_map);
m_audiocpu->intack_handler().set([this] { m_audiocpu->set_input_line(0, CLEAR_LINE); return 0x03; });
/* doesn't look like it is used at all */
//m_audiocpu->sense_handler().set(FUNC(cvs_state::cvs_393hz_clock_r));
S2650(config, m_speechcpu, XTAL(14'318'181)/16);
m_speechcpu->set_addrmap(AS_PROGRAM, &cvs_state::cvs_speech_cpu_map);
/* romclk is much more probable, 393 Hz results in timing issues */
//m_speechcpu->sense_handler().set(FUNC(cvs_state::cvs_393hz_clock_r));
m_speechcpu->sense_handler().set("tms", FUNC(tms5110_device::romclk_hack_r));
/* video hardware */
GFXDECODE(config, m_gfxdecode, m_palette, gfx_cvs);
PALETTE(config, m_palette, FUNC(cvs_state::cvs_palette), (256 + 4) * 8 + 8 + 1, 16);
SCREEN(config, m_screen, SCREEN_TYPE_RASTER);
m_screen->set_video_attributes(VIDEO_ALWAYS_UPDATE);
m_screen->set_size(32*8, 32*8);
m_screen->set_visarea(0*8, 30*8-1, 1*8, 32*8-1);
m_screen->set_refresh_hz(60);
m_screen->set_vblank_time(ATTOSECONDS_IN_USEC(1000));
m_screen->set_screen_update(FUNC(cvs_state::screen_update_cvs));
m_screen->set_palette(m_palette);
S2636(config, m_s2636[0], 0);
m_s2636[0]->set_offsets(CVS_S2636_Y_OFFSET, CVS_S2636_X_OFFSET);
S2636(config, m_s2636[1], 0);
m_s2636[1]->set_offsets(CVS_S2636_Y_OFFSET, CVS_S2636_X_OFFSET);
S2636(config, m_s2636[2], 0);
m_s2636[2]->set_offsets(CVS_S2636_Y_OFFSET, CVS_S2636_X_OFFSET);
/* audio hardware */
SPEAKER(config, "speaker").front_center();
GENERIC_LATCH_8(config, m_soundlatch);
DAC_8BIT_R2R(config, "dac1", 0).add_route(ALL_OUTPUTS, "speaker", 0.25); // unknown DAC
DAC_4BIT_R2R(config, m_dac2, 0).add_route(ALL_OUTPUTS, "speaker", 0.25); // unknown DAC
DAC_1BIT(config, m_dac3, 0).add_route(ALL_OUTPUTS, "speaker", 0.5);
TMS5100(config, m_tms5110, XTAL(640'000));
m_tms5110->data().set(FUNC(cvs_state::speech_rom_read_bit));
m_tms5110->add_route(ALL_OUTPUTS, "speaker", 0.5);
}
/*************************************
*
* ROM definitions
*
*************************************/
#define CVS_COMMON_ROMS \
ROM_REGION( 0x8000, "speechcpu", 0 ) \
ROM_LOAD( "5b.bin", 0x0000, 0x0800, CRC(f055a624) SHA1(5dfe89d7271092e665cdd5cd59d15a2b70f92f43) ) \
\
ROM_REGION( 0x0820, "proms", 0 ) \
ROM_LOAD( "82s185.10h", 0x0000, 0x0800, CRC(c205bca6) SHA1(ec9bd220e75f7b067ede6139763ef8aca0fb7a29) ) \
ROM_LOAD( "82s123.10k", 0x0800, 0x0020, CRC(b5221cec) SHA1(71d9830b33b1a8140b0fe1a2ba8024ba8e6e48e0) )
#define CVS_ROM_REGION_SPEECH_DATA(name, len, hash) \
ROM_REGION( 0x1000, "speechdata", 0 ) \
ROM_LOAD( name, 0x0000, len, hash )
#define ROM_LOAD_STAGGERED(name, offs, hash) \
ROM_LOAD( name, 0x0000 + offs, 0x0400, hash ) \
ROM_CONTINUE( 0x2000 + offs, 0x0400 ) \
ROM_CONTINUE( 0x4000 + offs, 0x0400 ) \
ROM_CONTINUE( 0x6000 + offs, 0x0400 )
ROM_START( huncholy )
ROM_REGION( 0x8000, "maincpu", 0 )
ROM_LOAD_STAGGERED( "ho-gp1.bin", 0x0000, CRC(4f17cda7) SHA1(ae6fe495c723042c6e060d4ada50aaef1019d5eb) )
ROM_LOAD_STAGGERED( "ho-gp2.bin", 0x0400, CRC(70fa52c7) SHA1(179813fdc204870d72c0bfa8cd5dbf277e1f67c4) )
ROM_LOAD_STAGGERED( "ho-gp3.bin", 0x0800, CRC(931934b1) SHA1(08fe5ad3459862246e9ea845abab4e01e1dbd62d) )
ROM_LOAD_STAGGERED( "ho-gp4.bin", 0x0c00, CRC(af5cd501) SHA1(9a79b173aa41a82faa9f19210d3e18bfa6c593fa) )
ROM_LOAD_STAGGERED( "ho-gp5.bin", 0x1000, CRC(658e8974) SHA1(30d0ada1cce99a842bad8f5a58630bc1b7048b03) )
ROM_REGION( 0x8000, "audiocpu", 0 )
ROM_LOAD( "ho-sdp1.bin", 0x0000, 0x1000, CRC(3efb3ffd) SHA1(be4807c8b4fe23f2247aa3b6ac02285bee1a0520) )
CVS_ROM_REGION_SPEECH_DATA( "ho-sp1.bin", 0x1000, CRC(3fd39b1e) SHA1(f5d0b2cfaeda994762403f039a6f7933c5525234) )
ROM_REGION( 0x1800, "gfx1", 0 )
ROM_LOAD( "ho-cp1.bin", 0x0000, 0x0800, CRC(c6c73d46) SHA1(63aba92f77105fedf46337b591b074020bec05d0) )
ROM_LOAD( "ho-cp2.bin", 0x0800, 0x0800, CRC(e596371c) SHA1(93a0d0ccdf830ae72d070b03b7e2222f4a737ead) )
ROM_LOAD( "ho-cp3.bin", 0x1000, 0x0800, CRC(11fae1cf) SHA1(5ceabfb1ff1a6f76d1649512f57d7151f5258ecb) )
CVS_COMMON_ROMS
ROM_END
ROM_START( darkwar )
ROM_REGION( 0x8000, "maincpu", 0 )
ROM_LOAD_STAGGERED( "dw-gp1.bin", 0x0000, CRC(f10ccf24) SHA1(f694a9016fc935798e5342598e4fd60fbdbc2829) )
ROM_LOAD_STAGGERED( "dw-gp2.bin", 0x0400, CRC(b77d0483) SHA1(47d126b9ceaf07267c9078a342a860295320b01c) )
ROM_LOAD_STAGGERED( "dw-gp3.bin", 0x0800, CRC(c01c3281) SHA1(3c272f424f8a35d08b58f203718b579c1abbe63f) )
ROM_LOAD_STAGGERED( "dw-gp4.bin", 0x0c00, CRC(0b0bffaf) SHA1(48db78d86dc249fb4d7d93b79b2ac269a0c6698e) )
ROM_LOAD_STAGGERED( "dw-gp5.bin", 0x1000, CRC(7fdbcaff) SHA1(db80d0d8690105ca72df359c1dc1a43952709111) )
ROM_REGION( 0x8000, "audiocpu", 0 )
ROM_LOAD( "dw-sdp1.bin", 0x0000, 0x0800, CRC(b385b669) SHA1(79621d3fb3eb4ea6fa8a733faa6f21edeacae186) )
CVS_ROM_REGION_SPEECH_DATA( "dw-sp1.bin", 0x1000, CRC(ce815074) SHA1(105f24fb776131b30e35488cca29954298559518) )
ROM_REGION( 0x1800, "gfx1", 0 )
ROM_LOAD( "dw-cp1.bin", 0x0000, 0x0800, CRC(7a0f9f3e) SHA1(0aa787923fbb614f15016d99c03093a59a0bfb88) )
ROM_LOAD( "dw-cp2.bin", 0x0800, 0x0800, CRC(232e5120) SHA1(76e4d6d17e8108306761604bd56d6269bfc431e1) )
ROM_LOAD( "dw-cp3.bin", 0x1000, 0x0800, CRC(573e0a17) SHA1(9c7991eac625b287bafb6cf722ffb405a9627e09) )
CVS_COMMON_ROMS
ROM_END
ROM_START( 8ball )
ROM_REGION( 0x8000, "maincpu", 0 )
ROM_LOAD_STAGGERED( "8b-gp1.bin", 0x0000, CRC(1b4fb37f) SHA1(df6dd2766a3b70eec0bde0ae1932b35abdab3735) )
ROM_LOAD_STAGGERED( "8b-gp2.bin", 0x0400, CRC(f193cdb5) SHA1(54fd1a10c1b9da0f9c4d190f95acc11b3c6e7907) )
ROM_LOAD_STAGGERED( "8b-gp3.bin", 0x0800, CRC(191989bf) SHA1(dea129a4ed06aac453ab1fbbfae14d8048ef270d) )
ROM_LOAD_STAGGERED( "8b-gp4.bin", 0x0c00, CRC(9c64519e) SHA1(9a5cad7ccf8f1f289da9a6de0edd4e6d4f0b12fb) )
ROM_LOAD_STAGGERED( "8b-gp5.bin", 0x1000, CRC(c50d0f9d) SHA1(31b6ea6282fec96d9d2fb74129a215d10f12cc9b) )
ROM_REGION( 0x8000, "audiocpu", 0 )
ROM_LOAD( "8b-sdp1.bin", 0x0000, 0x1000, CRC(a571daf4) SHA1(0db5b95db9da27216bbfa8fff84491a7755f9f1a) )
CVS_ROM_REGION_SPEECH_DATA( "8b-sp1.bin", 0x0800, CRC(1ee167f3) SHA1(40c876a60832456a27108252ba0b9963f9fe70b0) )
ROM_REGION( 0x1800, "gfx1", 0 )
ROM_LOAD( "8b-cp1.bin", 0x0000, 0x0800, CRC(c1f68754) SHA1(481c8e3dc35300f779b7925fa8a54320688dac54) )
ROM_LOAD( "8b-cp2.bin", 0x0800, 0x0800, CRC(6ec1d711) SHA1(768df8e621a7b110a963c93402ee01b1c9009286) )
ROM_LOAD( "8b-cp3.bin", 0x1000, 0x0800, CRC(4a9afce4) SHA1(187e5106aa2d0bdebf6ec9f2b7c2c2f67d47d221) )
CVS_COMMON_ROMS
ROM_END
ROM_START( 8ball1 )
ROM_REGION( 0x8000, "maincpu", 0 )
ROM_LOAD_STAGGERED( "8a-gp1.bin", 0x0000, CRC(b5d3b763) SHA1(23a01bcbd536ba7f773934ea9dedc7dd9f698100) )
ROM_LOAD_STAGGERED( "8a-gp2.bin", 0x0400, CRC(5e4aa61a) SHA1(aefa79b4c63d1ac5cb000f2c7c5d06e85d58a547) )
ROM_LOAD_STAGGERED( "8a-gp3.bin", 0x0800, CRC(3dc272fe) SHA1(303184f7c3557be91d6b8e62a9685080444a78c5) )
ROM_LOAD_STAGGERED( "8a-gp4.bin", 0x0c00, CRC(33afedbf) SHA1(857c743fd81fbd439c204b6adb251db68465cfc3) )
ROM_LOAD_STAGGERED( "8a-gp5.bin", 0x1000, CRC(b8b3f373) SHA1(e808db4dcac6d8a454e20b561bb4f3a3bb9c6200) )
ROM_REGION( 0x8000, "audiocpu", 0 )
ROM_LOAD( "8b-sdp1.bin", 0x0000, 0x1000, CRC(a571daf4) SHA1(0db5b95db9da27216bbfa8fff84491a7755f9f1a) )
CVS_ROM_REGION_SPEECH_DATA( "8b-sp1.bin", 0x0800, CRC(1ee167f3) SHA1(40c876a60832456a27108252ba0b9963f9fe70b0) )
ROM_REGION( 0x1800, "gfx1", 0 )
ROM_LOAD( "8a-cp1.bin", 0x0000, 0x0800, CRC(d9b36c16) SHA1(dbb496102fa2344f19b5d9a3eecdb29c433e4c08) )
ROM_LOAD( "8a-cp2.bin", 0x0800, 0x0800, CRC(6f66f0ff) SHA1(1e91474973356e97f89b4d9093565747a8331f50) )
ROM_LOAD( "8a-cp3.bin", 0x1000, 0x0800, CRC(baee8b17) SHA1(9f86f1d5903aeead17cc75dac8a2b892bb375dad) )
CVS_COMMON_ROMS
ROM_END
ROM_START( hunchbak ) // actual ROM label has "Century Elect. Ltd. (c)1981", and some label has HB/HB2 handwritten
ROM_REGION( 0x8000, "maincpu", 0 )
ROM_LOAD_STAGGERED( "hb-gp1.bin", 0x0000, CRC(af801d54) SHA1(68e31561e98f7e2caa337dd764941d08f075b559) )
ROM_LOAD_STAGGERED( "hb-gp2.bin", 0x0400, CRC(b448cc8e) SHA1(ed94f662c0e08a3a0aca073fbec29ae1fbd0328e) )
ROM_LOAD_STAGGERED( "hb-gp3.bin", 0x0800, CRC(57c6ea7b) SHA1(8c3ba01ab1917a8c24180ed1c0011dbfed36d406) )
ROM_LOAD_STAGGERED( "hb-gp4.bin", 0x0c00, CRC(7f91287b) SHA1(9383d885c142417de73879905cbce272ba9514c7) )
ROM_LOAD_STAGGERED( "hb-gp5.bin", 0x1000, CRC(1dd5755c) SHA1(b1e158d52bd9a238e3e32ed3024e495df2292dcb) )
ROM_REGION( 0x8000, "audiocpu", 0 )
ROM_LOAD( "6c.sdp1", 0x0000, 0x1000, CRC(f9ba2854) SHA1(d041198e2e8b8c3e668bd1610310f8d25c5b1119) )
CVS_ROM_REGION_SPEECH_DATA( "8a.sp1", 0x0800, CRC(ed1cd201) SHA1(6cc3842dda1bfddc06ffb436c55d14276286bd67) )
ROM_REGION( 0x1800, "gfx1", 0 )
ROM_LOAD( "11a.cp1", 0x0000, 0x0800, CRC(f256b047) SHA1(02d79882bad37ffdd58ef478e2658a1369c32ebc) )
ROM_LOAD( "10a.cp2", 0x0800, 0x0800, CRC(b870c64f) SHA1(ce4f8de87568782ce02bba754edff85df7f5c393) )
ROM_LOAD( "9a.cp3", 0x1000, 0x0800, CRC(9a7dab88) SHA1(cd39a9d4f982a7f49c478db1408d7e07335f2ddc) )
CVS_COMMON_ROMS
ROM_END
ROM_START( hunchbaka )
ROM_REGION( 0x8000, "maincpu", 0 )
ROM_LOAD_STAGGERED( "1b.gp1", 0x0000, CRC(c816860b) SHA1(1109639645496d4644564d21c816b8baf8c84cf7) )
ROM_LOAD_STAGGERED( "2a.gp2", 0x0400, CRC(cab1e524) SHA1(c3fd7ac9ce5893fd2602a15ad0f6e3267a4ca122) )
ROM_LOAD_STAGGERED( "3a.gp3", 0x0800, CRC(b2adcfeb) SHA1(3090e2c6b945857c1e48dea395015a05c6165cd9) )
ROM_LOAD_STAGGERED( "4c.gp4", 0x0c00, CRC(229a8b71) SHA1(ea3815eb69d4927da356eada0add8382735feb48) )
ROM_LOAD_STAGGERED( "5a.gp5", 0x1000, CRC(cb4f0313) SHA1(1ef63cbe62e7a54d45e0afbc398c9d9b601e6403) )
ROM_REGION( 0x8000, "audiocpu", 0 )
ROM_LOAD( "6c.sdp1", 0x0000, 0x1000, CRC(f9ba2854) SHA1(d041198e2e8b8c3e668bd1610310f8d25c5b1119) )
CVS_ROM_REGION_SPEECH_DATA( "8a.sp1", 0x0800, CRC(ed1cd201) SHA1(6cc3842dda1bfddc06ffb436c55d14276286bd67) )
ROM_REGION( 0x1800, "gfx1", 0 )
ROM_LOAD( "11a.cp1", 0x0000, 0x0800, CRC(f256b047) SHA1(02d79882bad37ffdd58ef478e2658a1369c32ebc) )
ROM_LOAD( "10a.cp2", 0x0800, 0x0800, CRC(b870c64f) SHA1(ce4f8de87568782ce02bba754edff85df7f5c393) )
ROM_LOAD( "9a.cp3", 0x1000, 0x0800, CRC(9a7dab88) SHA1(cd39a9d4f982a7f49c478db1408d7e07335f2ddc) )
CVS_COMMON_ROMS
ROM_END
ROM_START( wallst )
ROM_REGION( 0x8000, "maincpu", 0 )
ROM_LOAD_STAGGERED( "ws-gp1.bin", 0x0000, CRC(bdac81b6) SHA1(6ce865d8902e815742a9ecf10d6f9495f376dede) )
ROM_LOAD_STAGGERED( "ws-gp2.bin", 0x0400, CRC(9ca67cdd) SHA1(575a4d8d037d2a3c07a8f49d93c7cf6781349ec1) )
ROM_LOAD_STAGGERED( "ws-gp3.bin", 0x0800, CRC(c2f407f2) SHA1(8208064fd0138a6ccacf03275b8d28793245bfd9) )
ROM_LOAD_STAGGERED( "ws-gp4.bin", 0x0c00, CRC(1e4b2fe1) SHA1(28eda70cc9cf619452729092e68734ab1a5dc7fb) )
ROM_LOAD_STAGGERED( "ws-gp5.bin", 0x1000, CRC(eec7bfd0) SHA1(6485e9e2e1624118e38892e74f80431820fd9672) )
ROM_REGION( 0x8000, "audiocpu", 0 )
ROM_LOAD( "ws-sdp1.bin", 0x0000, 0x1000, CRC(faed2ac0) SHA1(c2c48e24a560d918531e5c17fb109d68bdec850f) )
CVS_ROM_REGION_SPEECH_DATA( "ws-sp1.bin", 0x0800, CRC(84b72637) SHA1(9c5834320f39545403839fb7088c37177a6c8861) )
ROM_REGION( 0x1800, "gfx1", 0 )
ROM_LOAD( "ws-cp1.bin", 0x0000, 0x0800, CRC(5aca11df) SHA1(5ef815b5b09445515ff8b958c4ea29f1a221cee1) )
ROM_LOAD( "ws-cp2.bin", 0x0800, 0x0800, CRC(ca530d85) SHA1(e5a78667c3583d06d8387848323b11e4a91091ec) )
ROM_LOAD( "ws-cp3.bin", 0x1000, 0x0800, CRC(1e0225d6) SHA1(410795046c64c24de6711b167315308808b54291) )
CVS_COMMON_ROMS
ROM_END
ROM_START( dazzler )
ROM_REGION( 0x8000, "maincpu", 0 )
ROM_LOAD_STAGGERED( "dz-gp1.bin", 0x0000, CRC(2c5d75de) SHA1(d121de662e95f2fc362e367cef57e5e70bafd197) )
ROM_LOAD_STAGGERED( "dz-gp2.bin", 0x0400, CRC(d0db80d6) SHA1(ca57d3a1d516e0afd750a8f05ae51d4ddee60ca0) )
ROM_LOAD_STAGGERED( "dz-gp3.bin", 0x0800, CRC(d5f07796) SHA1(110bb0e1613db3634513e8456770dd9d43ad7d34) )
ROM_LOAD_STAGGERED( "dz-gp4.bin", 0x0c00, CRC(84e41a46) SHA1(a1c1fd9ecacf3357f5c7916cf05dc0b79e975137) )
ROM_LOAD_STAGGERED( "dz-gp5.bin", 0x1000, CRC(2ae59c41) SHA1(a17e9535409e9e91c41f26a3543f44f20c1b07a5) )
ROM_REGION( 0x8000, "audiocpu", 0 )
ROM_LOAD( "dz-sdp1.bin", 0x0000, 0x1000, CRC(89847352) SHA1(54037a4d95958c4c3383467d7f4c2c9416b2eb4a) )
CVS_ROM_REGION_SPEECH_DATA( "dz-sp1.bin", 0x0800, CRC(25da1fc1) SHA1(c14717ec3399ce7dc47a9d42c8ac8f585db770e9) )
ROM_REGION( 0x1800, "gfx1", 0 )
ROM_LOAD( "dz-cp1.bin", 0x0000, 0x0800, CRC(0a8a9034) SHA1(9df3d4f387bd5ce3d3580ba678aeda1b65634ac2) )
ROM_LOAD( "dz-cp2.bin", 0x0800, 0x0800, CRC(3868dd82) SHA1(844584c5a80fb8f1797b4aa4e22024e75726293d) )
ROM_LOAD( "dz-cp3.bin", 0x1000, 0x0800, CRC(755d9ed2) SHA1(a7165a1d12a5a81d8bb941d8ad073e2097c90beb) )
CVS_COMMON_ROMS
ROM_END
ROM_START( radarzon )
ROM_REGION( 0x8000, "maincpu", 0 )
ROM_LOAD_STAGGERED( "rd-gp1.bin", 0x0000, CRC(775786ba) SHA1(5ad0f4e774821a7ed73615118ea42132d3b5424b) )
ROM_LOAD_STAGGERED( "rd-gp2.bin", 0x0400, CRC(9f6be426) SHA1(24b6cf3d826f3aec0e928881f259a5bc6229232b) )
ROM_LOAD_STAGGERED( "rd-gp3.bin", 0x0800, CRC(61d11b29) SHA1(fe321c1c912b93bbb098d591e5c4ed0b5b72c88e) )
ROM_LOAD_STAGGERED( "rd-gp4.bin", 0x0c00, CRC(2fbc778c) SHA1(e45ba08156cf03a1c4a1bdfb8569476d0eb05847) )
ROM_LOAD_STAGGERED( "rd-gp5.bin", 0x1000, CRC(692a99d5) SHA1(122ae802914cb9a41713536f9030cd9377cf3468) )
ROM_REGION( 0x8000, "audiocpu", 0 )
ROM_LOAD( "rd-sdp1.bin", 0x0000, 0x0800, CRC(cd5aea6d) SHA1(f7545b87e71e3108c0dec24a4e91620d006e0602) )
CVS_ROM_REGION_SPEECH_DATA( "rd-sp1.bin", 0x0800, CRC(43b17734) SHA1(59960f0c48ed24cedb4b4655f97f6f1fdac4445e) )
ROM_REGION( 0x1800, "gfx1", 0 )
ROM_LOAD( "rd-cp1.bin", 0x0000, 0x0800, CRC(ed601677) SHA1(efe2b6033f319603ee80ed4ba66d3b3607537b13) )
ROM_LOAD( "rd-cp2.bin", 0x0800, 0x0800, CRC(35e317ff) SHA1(458550b431ec66006e2966d86a2286905c0495ed) )
ROM_LOAD( "rd-cp3.bin", 0x1000, 0x0800, CRC(90f2c43f) SHA1(406215217f6f20c1a78f31b2ae3c0a97391e3371) )
CVS_COMMON_ROMS
ROM_END
ROM_START( radarzon1 )
ROM_REGION( 0x8000, "maincpu", 0 )
ROM_LOAD_STAGGERED( "r1-gp1.bin", 0x0000, CRC(7c73c21f) SHA1(1113025ea16cfcc500b9624a031f3d25290db163) )
ROM_LOAD_STAGGERED( "r1-gp2.bin", 0x0400, CRC(dedbd2ce) SHA1(ef80bf1b4a9561ad7f54e795c78e72664abf0501) )
ROM_LOAD_STAGGERED( "r1-gp3.bin", 0x0800, CRC(966a49e7) SHA1(6c769ac12fbfb65184131f1ab16240e422125c04) )
ROM_LOAD_STAGGERED( "r1-gp4.bin", 0x0c00, CRC(f3175bee) SHA1(f4927eea856ae56b1854263666a48e2cfb3ab60d) )
ROM_LOAD_STAGGERED( "r1-gp5.bin", 0x1000, CRC(7484927b) SHA1(89a67baa91075d2777f2ecd1667ed79175ad57ca) )
ROM_REGION( 0x8000, "audiocpu", 0 )
ROM_LOAD( "rd-sdp1.bin", 0x0000, 0x0800, CRC(cd5aea6d) SHA1(f7545b87e71e3108c0dec24a4e91620d006e0602) )
CVS_ROM_REGION_SPEECH_DATA( "rd-sp1.bin", 0x0800, CRC(43b17734) SHA1(59960f0c48ed24cedb4b4655f97f6f1fdac4445e) )
ROM_REGION( 0x1800, "gfx1", 0 )
ROM_LOAD( "rd-cp1.bin", 0x0000, 0x0800, CRC(ed601677) SHA1(efe2b6033f319603ee80ed4ba66d3b3607537b13) )
ROM_LOAD( "rd-cp2.bin", 0x0800, 0x0800, CRC(35e317ff) SHA1(458550b431ec66006e2966d86a2286905c0495ed) )
ROM_LOAD( "rd-cp3.bin", 0x1000, 0x0800, CRC(90f2c43f) SHA1(406215217f6f20c1a78f31b2ae3c0a97391e3371) )
CVS_COMMON_ROMS
ROM_END
ROM_START( radarzont )
ROM_REGION( 0x8000, "maincpu", 0 )
ROM_LOAD_STAGGERED( "rt-gp1.bin", 0x0000, CRC(43573974) SHA1(854fe7022e9bdd94bb119c014156e9ffdb6682fa) )
ROM_LOAD_STAGGERED( "rt-gp2.bin", 0x0400, CRC(257a11ce) SHA1(ca7f9260d9879ebce202f83a41838cb6dc9a6480) )
ROM_LOAD_STAGGERED( "rt-gp3.bin", 0x0800, CRC(e00f3552) SHA1(156765809e4016527039e3d5cc1c320cfce06834) )
ROM_LOAD_STAGGERED( "rt-gp4.bin", 0x0c00, CRC(d1e824ac) SHA1(f996813f02d32ddcde7f394740bdb3444eacda76) )
ROM_LOAD_STAGGERED( "rt-gp5.bin", 0x1000, CRC(bc770af8) SHA1(79599b5f2f4d692986862076be1d487b45783c00) )
ROM_REGION( 0x8000, "audiocpu", 0 )
ROM_LOAD( "rd-sdp1.bin", 0x0000, 0x0800, CRC(cd5aea6d) SHA1(f7545b87e71e3108c0dec24a4e91620d006e0602) )
CVS_ROM_REGION_SPEECH_DATA( "rd-sp1.bin", 0x0800, CRC(43b17734) SHA1(59960f0c48ed24cedb4b4655f97f6f1fdac4445e) )
ROM_REGION( 0x1800, "gfx1", 0 )
ROM_LOAD( "rd-cp1.bin", 0x0000, 0x0800, CRC(ed601677) SHA1(efe2b6033f319603ee80ed4ba66d3b3607537b13) )
ROM_LOAD( "rd-cp2.bin", 0x0800, 0x0800, CRC(35e317ff) SHA1(458550b431ec66006e2966d86a2286905c0495ed) )
ROM_LOAD( "rd-cp3.bin", 0x1000, 0x0800, CRC(90f2c43f) SHA1(406215217f6f20c1a78f31b2ae3c0a97391e3371) )
CVS_COMMON_ROMS
ROM_END
ROM_START( outline )
ROM_REGION( 0x8000, "maincpu", 0 )
ROM_LOAD_STAGGERED( "rt-gp1.bin", 0x0000, CRC(43573974) SHA1(854fe7022e9bdd94bb119c014156e9ffdb6682fa) )
ROM_LOAD_STAGGERED( "rt-gp2.bin", 0x0400, CRC(257a11ce) SHA1(ca7f9260d9879ebce202f83a41838cb6dc9a6480) )
ROM_LOAD_STAGGERED( "ot-gp3.bin", 0x0800, CRC(699489e1) SHA1(d4b21c294254ee0a451c29ac91028582a52f5ba3) )
ROM_LOAD_STAGGERED( "ot-gp4.bin", 0x0c00, CRC(c94aca17) SHA1(ea4ab93c52fee37afc7033b4b2acddcdce308f6b) )
ROM_LOAD_STAGGERED( "ot-gp5.bin", 0x1000, CRC(154712f4) SHA1(90f69e30e1c1d2348d6644406d83d2b2bcfe8171) )
ROM_REGION( 0x8000, "audiocpu", 0 )
ROM_LOAD( "ot-sdp1.bin", 0x0000, 0x0800, CRC(739066a9) SHA1(7b3ba8a163d341931bc0385c298d2061fa75e644) )
CVS_ROM_REGION_SPEECH_DATA( "ot-sp1.bin", 0x1000, CRC(fa21422a) SHA1(a75d13455c65e5a77db02fc87f0c112e329d0d6d) )
ROM_REGION( 0x1800, "gfx1", 0 )
ROM_LOAD( "rd-cp1.bin", 0x0000, 0x0800, CRC(ed601677) SHA1(efe2b6033f319603ee80ed4ba66d3b3607537b13) )
ROM_LOAD( "rd-cp2.bin", 0x0800, 0x0800, CRC(35e317ff) SHA1(458550b431ec66006e2966d86a2286905c0495ed) )
ROM_LOAD( "rd-cp3.bin", 0x1000, 0x0800, CRC(90f2c43f) SHA1(406215217f6f20c1a78f31b2ae3c0a97391e3371) )
CVS_COMMON_ROMS
ROM_END
ROM_START( goldbug )
ROM_REGION( 0x8000, "maincpu", 0 )
ROM_LOAD_STAGGERED( "gb-gp1.bin", 0x0000, CRC(8deb7761) SHA1(35f27fb6b5e3f76ddaf2c074b3391931e679df6e) )
ROM_LOAD_STAGGERED( "gb-gp2.bin", 0x0400, CRC(135036c1) SHA1(9868eae2486687772bf0bf71b82e461a882ae1ab) )
ROM_LOAD_STAGGERED( "gb-gp3.bin", 0x0800, CRC(d48b1090) SHA1(b3cbfeb4fc2bf1bbe0befab793fcc5e7e6ff804c) )
ROM_LOAD_STAGGERED( "gb-gp4.bin", 0x0c00, CRC(c8053205) SHA1(7f814b059f6b9c62e8a83c1753da5e8780b09411) )
ROM_LOAD_STAGGERED( "gb-gp5.bin", 0x1000, CRC(eca17472) SHA1(25c4ca59b4c96a22bc42b41adbf3cc33373cf85e) )
ROM_REGION( 0x8000, "audiocpu", 0 )
ROM_LOAD( "gb-sdp1.bin", 0x0000, 0x1000, CRC(c8a4b39d) SHA1(29fffaa12639f3b19db818ad374d09fbf9c7fb98) )
CVS_ROM_REGION_SPEECH_DATA( "gb-sp1.bin", 0x0800, CRC(5d0205c3) SHA1(578937058d56e5c9fba8a2204ddbb59a6d23dec7) )
ROM_REGION( 0x1800, "gfx1", 0 )
ROM_LOAD( "gb-cp1.bin", 0x0000, 0x0800, CRC(80e1ad5a) SHA1(0a577b0faffd9d6807c39175ce213f017a5cc7f8) )
ROM_LOAD( "gb-cp2.bin", 0x0800, 0x0800, CRC(0a288b29) SHA1(0c6471a3517805a5c873857ff21ca94dfe91c24e) )
ROM_LOAD( "gb-cp3.bin", 0x1000, 0x0800, CRC(e5bcf8cf) SHA1(7f53b8ee6f87e6c8761d2200e8194a7d16d8c7ac) )
CVS_COMMON_ROMS
ROM_END
ROM_START( diggerc )
ROM_REGION( 0x8000, "maincpu", 0 )
ROM_LOAD_STAGGERED( "dig-gp1.bin", 0x0000, CRC(6a67662f) SHA1(70e9814259c1fbaf195004e1d8ce0ab1125d62d0) )
ROM_LOAD_STAGGERED( "dig-gp2.bin", 0x0400, CRC(aa9f93b5) SHA1(e118ecb9160b7ba4a81b75b6cca56c0f01a9a3af) )
ROM_LOAD_STAGGERED( "dig-gp3.bin", 0x0800, CRC(4aa4c87c) SHA1(bcbe291e2ca060ecc623702cba1f4189dfa9c105) )
ROM_LOAD_STAGGERED( "dig-gp4.bin", 0x0c00, CRC(127e6520) SHA1(a4f1813a297616b7f864e235f40a432881fe252b) )
ROM_LOAD_STAGGERED( "dig-gp5.bin", 0x1000, CRC(76786827) SHA1(43e33c47a42878a58d72051c1edeccf944db4a17) )
ROM_REGION( 0x8000, "audiocpu", 0 )
ROM_LOAD( "dig-sdp1.bin", 0x0000, 0x1000, CRC(f82e51f0) SHA1(52903c19cdf7754894cbae57a16533579737b3d5) )
CVS_ROM_REGION_SPEECH_DATA( "dig-sp1.bin", 0x0800, CRC(db526ee1) SHA1(afe319e64350b0c54b72394294a6369c885fdb7f) )
ROM_REGION( 0x1800, "gfx1", 0 )
ROM_LOAD( "dig-cp1.bin", 0x0000, 0x0800, CRC(ca30fb97) SHA1(148f3a6f20b1f256a73e7a1992262116d77cc0a8) )
ROM_LOAD( "dig-cp2.bin", 0x0800, 0x0800, CRC(bed2334c) SHA1(c93902d01174e13fb9265194e5e44f67b38c5970) )
ROM_LOAD( "dig-cp3.bin", 0x1000, 0x0800, CRC(46db9b65) SHA1(1c655b4611ab182b6e4a3cdd3ef930e0d4dad0d9) )
CVS_COMMON_ROMS
ROM_END
ROM_START( superbik )
ROM_REGION( 0x8000, "maincpu", 0 )
ROM_LOAD_STAGGERED( "sb-gp1.bin", 0x0000, CRC(f0209700) SHA1(7843e8ebcbecb93814863ddd135f5acb0d481043) )
ROM_LOAD_STAGGERED( "sb-gp2.bin", 0x0400, CRC(1956d687) SHA1(00e261c5b1e1414b45661310c47daeceb3d5f4bf) )
ROM_LOAD_STAGGERED( "sb-gp3.bin", 0x0800, CRC(ceb27b75) SHA1(56fecc72746113a6611c18663d1b9e0e2daf57b4) )
ROM_LOAD_STAGGERED( "sb-gp4.bin", 0x0c00, CRC(430b70b3) SHA1(207c4939331c1561d145cbee0538da072aa51f5b) )
ROM_LOAD_STAGGERED( "sb-gp5.bin", 0x1000, CRC(013615a3) SHA1(1795a4dcc98255ad185503a99f48b7bacb5edc9d) )
ROM_REGION( 0x8000, "audiocpu", 0 )
ROM_LOAD( "sb-sdp1.bin", 0x0000, 0x0800, CRC(e977c090) SHA1(24bd4165434c745c1514d49cc90bcb621fb3a0f8) )
CVS_ROM_REGION_SPEECH_DATA( "sb-sp1.bin", 0x0800, CRC(0aeb9ccd) SHA1(e7123eed21e4e758bbe1cebfd5aad44a5de45c27) )
ROM_REGION( 0x1800, "gfx1", 0 )
ROM_LOAD( "sb-cp1.bin", 0x0000, 0x0800, CRC(03ba7760) SHA1(4ed252e2c4ec7cea2199524f7c35a1dc7c44f8d8) )
ROM_LOAD( "sb-cp2.bin", 0x0800, 0x0800, CRC(04de69f2) SHA1(3ef3b3c159d47230622b6cc45baad8737bd93a90) )
ROM_LOAD( "sb-cp3.bin", 0x1000, 0x0800, CRC(bb7d0b9a) SHA1(94c72d6961204be9cab351ac854ac9c69b51e79a) )
CVS_COMMON_ROMS
ROM_END
ROM_START( hero )
ROM_REGION( 0x8000, "maincpu", 0 )
ROM_LOAD_STAGGERED( "hr-gp1.bin", 0x0000, CRC(82f39788) SHA1(44217dc2312d10fceeb35adf3999cd6f240b60be) )
ROM_LOAD_STAGGERED( "hr-gp2.bin", 0x0400, CRC(79607812) SHA1(eaab829a2f5bcb8ec92c3f4122cffae31a4a77cb) )
ROM_LOAD_STAGGERED( "hr-gp3.bin", 0x0800, CRC(2902715c) SHA1(cf63f72681d1dcbdabdf7673ad8f61b5969e4bd1) )
ROM_LOAD_STAGGERED( "hr-gp4.bin", 0x0c00, CRC(696d2f8e) SHA1(73dd57f0f84e37ae707a89e17253aa3dd0c8b48b) )
ROM_LOAD_STAGGERED( "hr-gp5.bin", 0x1000, CRC(936a4ba6) SHA1(86cddcfafbd93dcdad3a1f26e280ceb96f779ab0) )
ROM_REGION( 0x8000, "audiocpu", 0 )
ROM_LOAD( "hr-sdp1.bin", 0x0000, 0x0800, CRC(c34ecf79) SHA1(07c96283410b1e7401140094db95800708cf310f) )
CVS_ROM_REGION_SPEECH_DATA( "hr-sp1.bin", 0x0800, CRC(a5c33cb1) SHA1(447ffb193b0dc4985bae5d8c214a893afd08664b) )
ROM_REGION( 0x1800, "gfx1", 0 )
ROM_LOAD( "hr-cp1.bin", 0x0000, 0x0800, CRC(2d201496) SHA1(f195aa1b231a0e1752c7da824a10321f0527f8c9) )
ROM_LOAD( "hr-cp2.bin", 0x0800, 0x0800, CRC(21b61fe3) SHA1(31882003f0557ffc4ec38ae6ee07b5d294b4162c) )
ROM_LOAD( "hr-cp3.bin", 0x1000, 0x0800, CRC(9c8e3f9e) SHA1(9d949a4d12b45da12b434677670b2b109568564a) )
CVS_COMMON_ROMS
ROM_END
ROM_START( logger ) // actual ROM label has "Century Elect. Ltd. (c)1981", and LOG3 is handwritten
ROM_REGION( 0x8000, "maincpu", 0 )
ROM_LOAD_STAGGERED( "1clog3.gp1", 0x0000, CRC(0022b9ed) SHA1(4b94d2663f802a8140e8eae1b66ee78fdfa654f5) )
ROM_LOAD_STAGGERED( "2clog3.gp2", 0x0400, CRC(23c5c8dc) SHA1(37fb6a62cb798d96de20078fe4a3af74a2be0e66) )
ROM_LOAD_STAGGERED( "3clog3.gp3", 0x0800, CRC(f9288f74) SHA1(8bb588194186fc0e0c2d61ed2746542c978ebb76) )
ROM_LOAD_STAGGERED( "4clog3.gp4", 0x0c00, CRC(e52ef7bf) SHA1(df5509b6847d6b9520a9d83b15083546898a981e) )
ROM_LOAD_STAGGERED( "5clog3.gp5", 0x1000, CRC(4ee04359) SHA1(a592d4b280ac0ad5f06d68a7809092548261f123) )
ROM_REGION( 0x8000, "audiocpu", 0 )
ROM_LOAD( "6clog3.sdp1", 0x0000, 0x1000, CRC(5af8da17) SHA1(357f02cdf38c6659aca51fa0a8534542fc29623c) )
CVS_ROM_REGION_SPEECH_DATA( "8clog3.sp1", 0x0800, CRC(74f67815) SHA1(6a26a16c27a7e4d58b611e5127115005a60cff91) )
ROM_REGION( 0x1800, "gfx1", 0 )
ROM_LOAD( "11clog3.cp1", 0x0000, 0x0800, CRC(e4ede80e) SHA1(62f2bc78106a057b6a8420d40421908df609bf29) )
ROM_LOAD( "10clog3.cp2", 0x0800, 0x0800, CRC(d3de8e5b) SHA1(f95320e001869c42e51195d9cc11e4f2555e153f) )
ROM_LOAD( "9clog3.cp3", 0x1000, 0x0800, CRC(9b8d1031) SHA1(87ef12aeae80cc0f240dead651c6222848f8dccc) )
CVS_COMMON_ROMS
ROM_END
ROM_START( loggerr2 )
ROM_REGION( 0x8000, "maincpu", 0 )
ROM_LOAD_STAGGERED( "logger_r2_gp1_11ce.1", 0x0000, CRC(02b0a75e) SHA1(06fbfa3a31e104da86f21ef8f600715224b7f332) ) // hand written LOGGER R2 GP1 11CE
ROM_LOAD_STAGGERED( "logger_r2_gp2_5265.2", 0x0400, CRC(3285aa08) SHA1(f5c8496b2d33229572d4442f703a2aaf93f1403f) ) // hand written LOGGER R2 GP2 5265
ROM_LOAD_STAGGERED( "logger_r2_gp3_da04.3", 0x0800, CRC(d6a2a442) SHA1(7da009f8d3d4fb0b6624cd46ecae08675c317905) ) // hand written LOGGER R2 GP3 DA04
ROM_LOAD_STAGGERED( "logger_r2_gp4_657b.4", 0x0c00, CRC(608b551c) SHA1(f2fde14860606f501ab0046fbe4dca0b97eb2481) ) // hand written LOGGER R2 GP4 657B
ROM_LOAD_STAGGERED( "logger_r2_gp5_c2d5.5", 0x1000, CRC(3d8ecdcd) SHA1(c9ea38aee898a4ac6cb6409da819d1a053088526) ) // hand written LOGGER R2 GP5 C2D5
ROM_REGION( 0x8000, "audiocpu", 0 )
ROM_LOAD( "logger_sdp1_414a.6", 0x0000, 0x1000, CRC(5af8da17) SHA1(357f02cdf38c6659aca51fa0a8534542fc29623c) ) // hand written LOGGER SDP1 414A
CVS_ROM_REGION_SPEECH_DATA( "logger_sp1_4626.8", 0x0800, CRC(74f67815) SHA1(6a26a16c27a7e4d58b611e5127115005a60cff91) ) // hand written LOGGER SP1 4626
ROM_REGION( 0x1800, "gfx1", 0 )
ROM_LOAD( "logger_r2_cp1_d9cf.11", 0x0000, 0x0800, CRC(a1c1eb8c) SHA1(9fa2495b1b245f5889006cfc8857f51e57379cef) ) // hand written LOGGER R2 CP1 D9CF
ROM_LOAD( "logger_r2_cp2_cd1e.10", 0x0800, 0x0800, CRC(432d28d0) SHA1(30b9ec84fe04c5e48f4a1f9f7ab86a6a222db4cf) ) // hand written LOGGER R2 CP2 CD1E
ROM_LOAD( "logger_r2_cp3_5535.9", 0x1000, 0x0800, CRC(c87fcfcd) SHA1(eb937a6aa04ebe873cf46c4b3abf7bb02766eedf) ) // hand written LOGGER R2 CP3 5535
CVS_COMMON_ROMS
ROM_END
ROM_START( cosmos )
ROM_REGION( 0x8000, "maincpu", 0 )
ROM_LOAD_STAGGERED( "cs-gp1.bin", 0x0000, CRC(7eb96ddf) SHA1(f7456ee1ace03ab98c4e8128d375464122c4df01) )
ROM_LOAD_STAGGERED( "cs-gp2.bin", 0x0400, CRC(6975a8f7) SHA1(13192d4eedd843c0c1d7e5c54a3086f71b09fbcb) )
ROM_LOAD_STAGGERED( "cs-gp3.bin", 0x0800, CRC(76904b13) SHA1(de219999e4a1b72142e71ea707b6250f4732ccb3) )
ROM_LOAD_STAGGERED( "cs-gp4.bin", 0x0c00, CRC(bdc89719) SHA1(668267d0b05990ff83a9e38a62950d3d725a53b3) )
ROM_LOAD_STAGGERED( "cs-gp5.bin", 0x1000, CRC(94be44ea) SHA1(e496ea79d177c6d2d79d59f7d45c86b547469c6f) )
ROM_REGION( 0x8000, "audiocpu", 0 )
ROM_LOAD( "cs-sdp1.bin", 0x0000, 0x0800, CRC(b385b669) SHA1(79621d3fb3eb4ea6fa8a733faa6f21edeacae186) )
CVS_ROM_REGION_SPEECH_DATA( "cs-sp1.bin", 0x1000, CRC(3c7fe86d) SHA1(9ae0b63b231a7092820650a196cde60588bc6b58) )
ROM_REGION( 0x1800, "gfx1", 0 )
ROM_LOAD( "cs-cp1.bin", 0x0000, 0x0800, CRC(6a48c898) SHA1(c27f7bcdb2fe042ec52d1b9b4b9a4e47c288862d) )
ROM_LOAD( "cs-cp2.bin", 0x0800, 0x0800, CRC(db0dfd8c) SHA1(f2b0dd43f0e514fdae54e4066606187f45b98e38) )
ROM_LOAD( "cs-cp3.bin", 0x1000, 0x0800, CRC(01eee875) SHA1(6c41d716b5795f085229d855518862fb85f395a4) )
CVS_COMMON_ROMS
ROM_END
ROM_START( heartatk )
ROM_REGION( 0x8000, "maincpu", 0 )
ROM_LOAD_STAGGERED( "ha-gp1.bin", 0x0000, CRC(e8297c23) SHA1(e79ae7e99f904afe90b43a54df7b0e257d65ac0b) )
ROM_LOAD_STAGGERED( "ha-gp2.bin", 0x0400, CRC(f7632afc) SHA1(ebfc6e12c8b5078e8c448aa25d9de9d39c0baa5e) )
ROM_LOAD_STAGGERED( "ha-gp3.bin", 0x0800, CRC(a9ce3c6a) SHA1(86ddb27c1c132f3cf5ad4268ea9a458e0da23677) )
ROM_LOAD_STAGGERED( "ha-gp4.bin", 0x0c00, CRC(090f30a9) SHA1(acd6b0c7358bf4664d0de668853076326e82fd04) )
ROM_LOAD_STAGGERED( "ha-gp5.bin", 0x1000, CRC(163b3d2d) SHA1(275275b54533e0ce2df6d189619be05a99c68b6d) )
ROM_REGION( 0x8000, "audiocpu", 0 )
ROM_LOAD( "ha-sdp1.bin", 0x0000, 0x1000, CRC(b9c466a0) SHA1(f28c21a15cf6d52123ed7feac4eea2a42ea5e93d) )
CVS_ROM_REGION_SPEECH_DATA( "ha-sp1.bin", 0x1000, CRC(fa21422a) SHA1(a75d13455c65e5a77db02fc87f0c112e329d0d6d) )
ROM_REGION( 0x1800, "gfx1", 0 )
ROM_LOAD( "ha-cp1.bin", 0x0000, 0x0800, CRC(2d0f6d13) SHA1(55e45eaf1bf24a7a78a2f34ffc0d99a4c191d138) )
ROM_LOAD( "ha-cp2.bin", 0x0800, 0x0800, CRC(7f5671bd) SHA1(7f4ae92a96c5a847c113f6f7e8d67d3e5ee0bcb0) )
ROM_LOAD( "ha-cp3.bin", 0x1000, 0x0800, CRC(35b05ab4) SHA1(f336eb0c674c3d52e84be0f37b70953cce6112dc) )
CVS_COMMON_ROMS
ROM_END
ROM_START( spacefrt )
ROM_REGION( 0x8000, "maincpu", 0 )
ROM_LOAD_STAGGERED( "sf-gp1.bin", 0x0000, CRC(1158fc3a) SHA1(c1f470324b6ec65c3061f78a6ff8620154f20c09) )
ROM_LOAD_STAGGERED( "sf-gp2.bin", 0x0400, CRC(8b4e1582) SHA1(5b92082d67f32197c0c61ddd8e1e3feb742195f4) )
ROM_LOAD_STAGGERED( "sf-gp3.bin", 0x0800, CRC(48f05102) SHA1(72d40cdd0bbc4cfeb6ddf550de0dafc61270d382) )
ROM_LOAD_STAGGERED( "sf-gp4.bin", 0x0c00, CRC(c5b14631) SHA1(360bed649185a090f7c96adadd7f045ef574865a) )
ROM_LOAD_STAGGERED( "sf-gp5.bin", 0x1000, CRC(d7eca1b6) SHA1(8444e61827f0153d04c4f9c08416e7ab753d6918) )
ROM_REGION( 0x8000, "audiocpu", 0 )
ROM_LOAD( "sf-sdp1.bin", 0x0000, 0x0800, CRC(339a327f) SHA1(940887cd4660e37537fd9b57aa1ec3a4717ea0cf) )
CVS_ROM_REGION_SPEECH_DATA( "sf-sp1.bin", 0x1000, CRC(c5628d30) SHA1(d29a5852a1762cbd5f3eba29ae2bf49b3a26f894) )
ROM_REGION( 0x1800, "gfx1", 0 )
ROM_LOAD( "sf-cp1.bin", 0x0000, 0x0800, CRC(da194a68) SHA1(4215267e91644cf1e1f32f898bc9562bfba711f3) )
ROM_LOAD( "sf-cp2.bin", 0x0800, 0x0800, CRC(b96977c7) SHA1(8f0fab044f16787bce83562e2b22d962d0a2c209) )
ROM_LOAD( "sf-cp3.bin", 0x1000, 0x0800, CRC(f5d67b9a) SHA1(a492b41c53b1f28ac5f70969e5f06afa948c1a7d) )
CVS_COMMON_ROMS
ROM_END
ROM_START( raiders )
ROM_REGION( 0x8000, "maincpu", 0 )
ROM_LOAD_STAGGERED( "raid4-5a.bin", 0x0000, CRC(1a92a5aa) SHA1(7f6dbbc0ac5ee2ba3efb3a9120cbee89c659b712) )
ROM_LOAD_STAGGERED( "raid4-4b.bin", 0x0400, CRC(da69e4b9) SHA1(8a2c4130a5db2cd7dbadb220440bb94ed4513bca) )
ROM_LOAD_STAGGERED( "raid4-3b.bin", 0x0800, CRC(ca794f92) SHA1(f281d88ffc6b7a84f9bcabc06eed99b8ae045eec) )
ROM_LOAD_STAGGERED( "raid4-2c.bin", 0x0c00, CRC(9de2c085) SHA1(be6157904afd0dc6ef8d97ec01a9557021ac8f3a) )
ROM_LOAD_STAGGERED( "raid4-1a.bin", 0x1000, CRC(f4db83ed) SHA1(7d519dc628c93f153ccede85e3cf77c012430f38) )
ROM_REGION( 0x8000, "audiocpu", 0 )
ROM_LOAD( "raidr1-6.bin", 0x0000, 0x0800, CRC(6f827e49) SHA1(4fb272616b60fcd468ed4074b94125e30aa46fd3) )
CVS_ROM_REGION_SPEECH_DATA( "raidr1-8.bin", 0x0800, CRC(b6b90d2e) SHA1(a966fa208b72aec358b7fb277e603e47b6984aa7) )
ROM_REGION( 0x1800, "gfx1", 0 )
ROM_LOAD( "raid4-11.bin", 0x0000, 0x0800, CRC(5eb7143b) SHA1(a19e803c15593b37ae2e61789f6e16f319620a37) )
ROM_LOAD( "raid4-10.bin", 0x0800, 0x0800, CRC(391948a4) SHA1(7e20ad4f7e5bf7ad5dcb08ba6475313e2b8b1f03) )
ROM_LOAD( "raid4-9b.bin", 0x1000, 0x0800, CRC(fecfde80) SHA1(23ea63080b8292fb00a743743cdff1a7ad0a8c6d) )
CVS_COMMON_ROMS
ROM_END
ROM_START( raidersr3 )
ROM_REGION( 0x8000, "maincpu", 0 )
ROM_LOAD_STAGGERED( "raid3gp5.bin", 0x0000, CRC(e169b71c) SHA1(4e8cc8ee3032ab5a7cfc1caba83f01d6a062d0ae) )
ROM_LOAD_STAGGERED( "raid3gp4.bin", 0x0400, CRC(9bf717ca) SHA1(7109232b7f72a325538fe6d25b8ef55747d1948d) )
ROM_LOAD_STAGGERED( "raid3gp3.bin", 0x0800, CRC(ac304782) SHA1(01597c2808d8e33bf9f6510fa9d7a5520eebf179) )
ROM_LOAD_STAGGERED( "raid3gp2.bin", 0x0c00, CRC(1c0fd350) SHA1(df7e64ad77755da4abdc66b08c470dff018d4592) )
ROM_LOAD_STAGGERED( "raid3gp1.bin", 0x1000, CRC(5ea24ebf) SHA1(96f9b1f26d8f35a1505cf4d45e5d960a9bb8fb74) )
ROM_REGION( 0x8000, "audiocpu", 0 )
ROM_LOAD( "raidr1-6.bin", 0x0000, 0x0800, CRC(6f827e49) SHA1(4fb272616b60fcd468ed4074b94125e30aa46fd3) )
CVS_ROM_REGION_SPEECH_DATA( "raidr1-8.bin", 0x0800, CRC(b6b90d2e) SHA1(a966fa208b72aec358b7fb277e603e47b6984aa7) )
ROM_REGION( 0x1800, "gfx1", 0 )
ROM_LOAD( "raid4-11.bin", 0x0000, 0x0800, CRC(5eb7143b) SHA1(a19e803c15593b37ae2e61789f6e16f319620a37) )
ROM_LOAD( "raid4-10.bin", 0x0800, 0x0800, CRC(391948a4) SHA1(7e20ad4f7e5bf7ad5dcb08ba6475313e2b8b1f03) )
ROM_LOAD( "raid4-9b.bin", 0x1000, 0x0800, CRC(fecfde80) SHA1(23ea63080b8292fb00a743743cdff1a7ad0a8c6d) )
CVS_COMMON_ROMS
ROM_END
/*************************************
*
* Game specific initialization
*
*************************************/
uint8_t cvs_state::huncholy_prot_r(offs_t offset)
{
if (offset == 1)
{
m_protection_counter++;
if ((m_protection_counter & 0x0f) == 0x01) return 0x00;
return 0xff;
}
return 0; // offset 0
}
void cvs_state::init_huncholy()
{
m_maincpu->space(AS_PROGRAM).install_read_handler(0x6ff1, 0x6ff2, read8sm_delegate(*this, FUNC(cvs_state::huncholy_prot_r)));
save_item(NAME(m_protection_counter));
m_protection_counter = 0;
}
void cvs_state::init_hunchbaka()
{
uint8_t *ROM = memregion("maincpu")->base();
/* data lines D2 and D5 swapped */
for (offs_t offs = 0; offs < 0x7400; offs++)
ROM[offs] = bitswap<8>(ROM[offs],7,6,2,4,3,5,1,0);
}
uint8_t cvs_state::superbik_prot_r()
{
m_protection_counter++;
if ((m_protection_counter & 0x0f) == 0x02) return 0;
return 0xff;
}
void cvs_state::init_superbik()
{
m_protection_counter = 0;
m_maincpu->space(AS_PROGRAM).install_read_handler(0x73f1, 0x73f2, read8smo_delegate(*this, FUNC(cvs_state::superbik_prot_r)));
save_item(NAME(m_protection_counter));
}
uint8_t cvs_state::hero_prot_r(offs_t offset)
{
u8 *ROM = memregion("maincpu")->base() + 0x73f0;
switch (offset + 0x73f0)
{
case 0x73f0: // pc: 7d, ab9
return 0xff; // 0x03 at this address in ROM
case 0x73f1: // pc: 83, read and then overwritten by 0x73f2 read
return 0; // 0x02 at this address in ROM
case 0x73f2: // pc: 86, needs to match read from 0x73f0
return 0xff & 0x7e; // 0x04 at this address in ROM
case 0x73f9: // pc: A9f, not sure what this is suppose to do?
return 0x00; // 0x1e at this address in ROM
case 0x73fe: // aa8
return 0xff; // 0x5e at this address in ROM
}
return ROM[offset];
}
void cvs_state::init_hero()
{
m_maincpu->space(AS_PROGRAM).install_read_handler(0x73f0, 0x73ff, read8sm_delegate(*this, FUNC(cvs_state::hero_prot_r)));
}
void cvs_state::init_raiders()
{
uint8_t *ROM = memregion("maincpu")->base();
/* data lines D1 and D6 swapped */
for (offs_t offs = 0; offs < 0x7400; offs++)
ROM[offs] = bitswap<8>(ROM[offs],7,1,5,4,3,2,6,0);
/* patch out protection */
ROM[0x010a] = 0xc0;
ROM[0x010b] = 0xc0;
ROM[0x010c] = 0xc0;
}
/*************************************
*
* Game drivers
*
*************************************/
GAME( 1981, cosmos, 0, cvs, cosmos, cvs_state, empty_init, ROT90, "Century Electronics", "Cosmos", MACHINE_NO_COCKTAIL | MACHINE_IMPERFECT_SOUND | MACHINE_SUPPORTS_SAVE )
GAME( 1981, darkwar, 0, cvs, darkwar, cvs_state, empty_init, ROT90, "Century Electronics", "Dark Warrior", MACHINE_NO_COCKTAIL | MACHINE_IMPERFECT_SOUND | MACHINE_SUPPORTS_SAVE )
GAME( 1981, spacefrt, 0, cvs, spacefrt, cvs_state, empty_init, ROT90, "Century Electronics", "Space Fortress (CVS)", MACHINE_NO_COCKTAIL | MACHINE_IMPERFECT_SOUND | MACHINE_SUPPORTS_SAVE )
GAME( 1982, 8ball, 0, cvs, 8ball, cvs_state, empty_init, ROT90, "Century Electronics", "Video Eight Ball", MACHINE_NO_COCKTAIL | MACHINE_IMPERFECT_SOUND | MACHINE_SUPPORTS_SAVE )
GAME( 1982, 8ball1, 8ball, cvs, 8ball, cvs_state, empty_init, ROT90, "Century Electronics", "Video Eight Ball (Rev.1)", MACHINE_NO_COCKTAIL | MACHINE_IMPERFECT_SOUND | MACHINE_SUPPORTS_SAVE )
GAME( 1982, logger, 0, cvs, logger, cvs_state, empty_init, ROT90, "Century Electronics", "Logger (Rev.3)", MACHINE_NO_COCKTAIL | MACHINE_IMPERFECT_SOUND | MACHINE_SUPPORTS_SAVE )
GAME( 1982, loggerr2, logger, cvs, logger, cvs_state, empty_init, ROT90, "E T Marketing", "Logger (Rev.2)", MACHINE_NO_COCKTAIL | MACHINE_IMPERFECT_SOUND | MACHINE_SUPPORTS_SAVE )
GAME( 1982, dazzler, 0, cvs, dazzler, cvs_state, empty_init, ROT90, "Century Electronics", "Dazzler", MACHINE_NO_COCKTAIL | MACHINE_IMPERFECT_SOUND | MACHINE_SUPPORTS_SAVE )
GAME( 1982, wallst, 0, cvs, wallst, cvs_state, empty_init, ROT90, "Century Electronics", "Wall Street", MACHINE_NO_COCKTAIL | MACHINE_IMPERFECT_SOUND | MACHINE_SUPPORTS_SAVE )
GAME( 1982, radarzon, 0, cvs, radarzon, cvs_state, empty_init, ROT90, "Century Electronics", "Radar Zone", MACHINE_NO_COCKTAIL | MACHINE_IMPERFECT_SOUND | MACHINE_SUPPORTS_SAVE )
GAME( 1982, radarzon1, radarzon, cvs, radarzon, cvs_state, empty_init, ROT90, "Century Electronics", "Radar Zone (Rev.1)", MACHINE_NO_COCKTAIL | MACHINE_IMPERFECT_SOUND | MACHINE_SUPPORTS_SAVE )
GAME( 1982, radarzont, radarzon, cvs, radarzon, cvs_state, empty_init, ROT90, "Century Electronics (Tuni Electro Service Inc)", "Radar Zone (Tuni)", MACHINE_NO_COCKTAIL | MACHINE_IMPERFECT_SOUND | MACHINE_SUPPORTS_SAVE )
GAME( 1982, outline, radarzon, cvs, radarzon, cvs_state, empty_init, ROT90, "Century Electronics", "Outline", MACHINE_NO_COCKTAIL | MACHINE_IMPERFECT_SOUND | MACHINE_SUPPORTS_SAVE )
GAME( 1982, goldbug, 0, cvs, goldbug, cvs_state, empty_init, ROT90, "Century Electronics", "Gold Bug", MACHINE_NO_COCKTAIL | MACHINE_IMPERFECT_SOUND | MACHINE_SUPPORTS_SAVE )
GAME( 1982, diggerc, 0, cvs, diggerc, cvs_state, empty_init, ROT90, "Century Electronics", "Digger (CVS)", MACHINE_NO_COCKTAIL | MACHINE_IMPERFECT_SOUND | MACHINE_SUPPORTS_SAVE )
GAME( 1983, heartatk, 0, cvs, heartatk, cvs_state, empty_init, ROT90, "Century Electronics", "Heart Attack", MACHINE_NO_COCKTAIL | MACHINE_IMPERFECT_SOUND | MACHINE_SUPPORTS_SAVE )
GAME( 1983, hunchbak, 0, cvs, hunchbak, cvs_state, empty_init, ROT90, "Century Electronics", "Hunchback (set 1)", MACHINE_NO_COCKTAIL | MACHINE_IMPERFECT_SOUND | MACHINE_SUPPORTS_SAVE )
GAME( 1983, hunchbaka, hunchbak, cvs, hunchbak, cvs_state, init_hunchbaka, ROT90, "Century Electronics", "Hunchback (set 2)", MACHINE_NO_COCKTAIL | MACHINE_IMPERFECT_SOUND | MACHINE_SUPPORTS_SAVE )
GAME( 1983, superbik, 0, cvs, superbik, cvs_state, init_superbik, ROT90, "Century Electronics", "Superbike", MACHINE_NO_COCKTAIL | MACHINE_IMPERFECT_SOUND | MACHINE_SUPPORTS_SAVE )
GAME( 1983, raiders, 0, cvs, raiders, cvs_state, init_raiders, ROT90, "Century Electronics", "Raiders", MACHINE_NO_COCKTAIL | MACHINE_IMPERFECT_SOUND | MACHINE_UNEMULATED_PROTECTION| MACHINE_SUPPORTS_SAVE )
GAME( 1983, raidersr3, raiders, cvs, raiders, cvs_state, init_raiders, ROT90, "Century Electronics", "Raiders (Rev.3)", MACHINE_NO_COCKTAIL | MACHINE_IMPERFECT_SOUND | MACHINE_UNEMULATED_PROTECTION| MACHINE_SUPPORTS_SAVE )
GAME( 1984, hero, 0, cvs, hero, cvs_state, init_hero, ROT90, "Century Electronics / Seatongrove Ltd", "Hero", MACHINE_NO_COCKTAIL | MACHINE_IMPERFECT_SOUND | MACHINE_SUPPORTS_SAVE ) // (C) 1984 CVS on titlescreen, (C) 1983 Seatongrove on highscore screen
GAME( 1984, huncholy, 0, cvs, huncholy, cvs_state, init_huncholy, ROT90, "Century Electronics / Seatongrove Ltd", "Hunchback Olympic", MACHINE_NO_COCKTAIL | MACHINE_IMPERFECT_SOUND | MACHINE_SUPPORTS_SAVE )
|
MorganConrad/runequest-discordbot
|
commands/attack_dodge.js
|
/**
* Determine the result of a given attack vs. a dodge
* args = [ attack level (e.g. "Special"), dodge level (e.g. "Failure")]
*
* @see config.successAliases
*/
const HELP = `Please supply an attack and a dodge result from [cr,sp,n,m,fu]
e.g. cr m means critical attack vs. a missed dodge.`;
const ATTACK_MAX_SPECIAL = "Attack does maximum special success damage";
const ATTACK_SPECIALS = "Attack does special success damage";
const ATTACK_NORMAL = "Attack does normal damage";
const ATTACK_DODGED = "Attack is dodged";
const ATTACK_MISSES = "Attack Misses";
const IGNORE_ARMOR = ", ignoring armor";
const ATTACKER_FUMBLES = "Attacker rolls on Fumble table";
const DEFENDER_FUMBLES = "Defender rolls on Fumble table";
const RESULTS = {
critical: {
critical: [ATTACK_DODGED],
special: [ATTACK_SPECIALS],
normal: [ATTACK_SPECIALS + IGNORE_ARMOR],
failure: [ATTACK_MAX_SPECIAL + IGNORE_ARMOR],
fumble: [ATTACK_MAX_SPECIAL + IGNORE_ARMOR, DEFENDER_FUMBLES],
},
special: {
critical: [ATTACK_DODGED],
special: [ATTACK_DODGED],
normal: [ATTACK_SPECIALS],
failure: [ATTACK_SPECIALS],
fumble: [ATTACK_SPECIALS, DEFENDER_FUMBLES]
},
normal: {
critical: [ATTACK_DODGED],
special: [ATTACK_DODGED],
normal: [ATTACK_DODGED],
failure: [ATTACK_NORMAL],
fumble: [ATTACK_NORMAL, DEFENDER_FUMBLES],
},
failure: {
critical: [ATTACK_MISSES],
special: [ATTACK_MISSES],
normal: [ATTACK_MISSES],
failure: [ATTACK_MISSES],
fumble: [ATTACK_NORMAL, DEFENDER_FUMBLES]
},
fumble: {
critical: [ATTACKER_FUMBLES],
special: [ATTACKER_FUMBLES],
normal: [ATTACKER_FUMBLES],
failure: [ATTACKER_FUMBLES],
fumble: [ATTACKER_FUMBLES, DEFENDER_FUMBLES]
}
};
function doHandle(userCommand, args, utils, commandIgnored) {
if (args.length < 2)
return HELP;
let attackerSuccess = utils.levelOfSuccess(args[0]);
let defenderSuccess = utils.levelOfSuccess(args[1]);
if (!attackerSuccess || !defenderSuccess)
return HELP;
let result = RESULTS[attackerSuccess][defenderSuccess].join(".\n");
return `Attack ${attackerSuccess} vs. Dodge ${defenderSuccess}:\n${result}.`;
}
module.exports = {
name: "Attack and Dodge Results",
aliases: ['meleedodge', 'ad', 'avd', 'attackdodgeresults'],
data: [],
doHandle,
help: HELP,
};
|
usert5432/vlne
|
scripts/eval/make_energy_hist_plots.py
|
import argparse
import os
from vlne.presets import PRESETS_EVAL
from vlne.plot.hist import plot_energy_hists
from vlne.utils.eval import standard_eval_prologue, parse_binning
from vlne.utils.log import setup_logging
from vlne.utils.parsers import (
add_basic_eval_args, add_concurrency_parser, add_hist_binning_parser
)
from vlne.eval.predict import (
get_true_energies, get_base_energies, predict_energies
)
from vlne.plot.plot_spec import PlotSpec
def make_hist_specs(cmdargs, preset):
binning = parse_binning(cmdargs, suffix = '_x')
return {
label : PlotSpec(
title = None,
label_x = f'{name} Energy [{preset.units_map[label]}]',
label_y = 'Events',
**binning
)
for (label, name) in preset.name_map.items()
}
def parse_cmdargs():
parser = argparse.ArgumentParser("Make Energy Hist plots")
add_basic_eval_args(parser, PRESETS_EVAL)
add_concurrency_parser(parser)
add_hist_binning_parser(
parser,
default_range_lo = 0,
default_range_hi = 5,
default_bins = 100,
)
return parser.parse_args()
def make_hist_plots(
pred_model_dict, pred_base_dict, true_dict, weights, hist_specs,
plotdir, ext
):
"""Make plots of energy histograms"""
plot_energy_hists(
[
(true_dict, weights, 'True', 'C3'),
(pred_base_dict, weights, 'Base', 'C0'),
(pred_model_dict, weights, 'Model', 'C1'),
],
hist_specs, os.path.join(plotdir, "plot_hist"), ext
)
def main():
setup_logging()
cmdargs = parse_cmdargs()
dgen, args, model, _outdir, plotdir, preset = \
standard_eval_prologue(cmdargs, PRESETS_EVAL)
hist_specs = make_hist_specs(cmdargs, preset)
pred_model_dict = predict_energies(args, dgen, model)
true_dict = get_true_energies(dgen)
pred_base_dict = get_base_energies(dgen, preset.base_map)
make_hist_plots(
pred_model_dict, pred_base_dict, true_dict, dgen.weights,
hist_specs, plotdir, cmdargs.ext
)
if __name__ == '__main__':
main()
|
rtoengi/transfer-learning-for-sign-language-recognition
|
baseline_model/learning_curves.py
|
<filename>baseline_model/learning_curves.py
from pathlib import Path
from baseline_model.constants import TRAINING_RUNS
from core.utils import load_dataframe
from plotting.plot import loss_accuracy_plot
from training.utils import history_path
def plot_learning_curves():
for training_run in TRAINING_RUNS:
path = history_path(Path(), training_run)
df = load_dataframe(path)
loss_accuracy_plot(df)
if __name__ == '__main__':
plot_learning_curves()
|
rockspoon/soajs.controller
|
test/unit/mw/keyACL/index.js
|
"use strict";
const helper = require("../../../helper.js");
const mw = helper.requireModule('./mw/keyACL/index');
const assert = require('assert');
let req = {
method: "get",
soajs: {
controller: {
serviceParams: {
service_v: 2,
name: 'urac'
}
},
log: {
debug: (msg) => {
console.log(msg);
}
}
}
};
let res = {};
describe("Unit test for: mw - keyACL", function () {
req.soajs.controller.serviceParams.keyObj = require('../../../data/sample/keyObj.json');
req.soajs.controller.serviceParams.packObj = require('../../../data/sample/packObj.json');
it("Install & Use the MW", function (done) {
let mw_use = mw({});
mw_use(req, res, () => {
assert.ok(req.soajs.controller.serviceParams.finalAcl);
done();
});
});
});
|
tortibulle/mpdx
|
spec/serializers/user_serializer_spec.rb
|
require 'spec_helper'
describe UserSerializer do
let(:user) { create(:user_with_account) }
subject { UserSerializer.new(user).as_json }
it { should include :account_lists }
it { should include :designation_accounts }
end
|
Kris-LIBIS/ingester
|
lib/teneo/ingester/tasks/file_grouper_from_mapping.rb
|
<filename>lib/teneo/ingester/tasks/file_grouper_from_mapping.rb
# frozen_string_literal: true
require 'teneo/ingester'
require_relative 'base/mapping'
module Teneo
module Ingester
module Tasks
class FileGrouperFromMapping < Teneo::Ingester::Tasks::Base::Task
include Base::Mapping
taskgroup :pre_ingest
description 'Groups files into object based on mapping file.'
help_text <<~STR
Files can be grouped together with this task by using a mapping file (e.g. CSV).
The mapping file should contain the file name, the name of the group it belongs to. Optionally it can also have
a label for the group.
STR
parameter group_field: nil,
description: 'The name of the column in the mapping table that contains the name of the group.',
help: 'Optional. If omitted, the files will not be grouped.'
parameter label_field: nil,
description: 'The name of the column in the mapping table that contains the label of the group.',
help: 'Optional. If omitted, the group label will not be set and defaults to the group name.'
recursive true
item_types Teneo::DataModel::FileItem
def configure(opts)
super
required = Set.new(parameter(:required_fields))
required << parameter(:group_field) if parameter(:group_field)
required << parameter(:label_field) if parameter(:label_field)
set = Set.new(parameter(:mapping_headers))
set += required
required = [parameter(:mapping_key)] + required.to_a
parameter(:mapping_headers, set.to_a)
parameter(:required_fields, required)
end
protected
def process(item, *_args)
target_parent = item.parent
if (group_field = parameter(:group_field))
if (group_name = lookup(item.filename, group_field))
group = target_parent.items.where(name: group_name, type: Teneo::DataModel::ItemGroup.name).first
unless group
group = Teneo::DataModel::ItemGroup.new
group.name = group_name
group.label = lookup(item.filename, parameter(:label_field)) if parameter(:label_field)
group.label ||= group_name
target_parent.add_item(group)
debug 'Created new item group: %s', group, group_name
group.save!
set_item_status(status: :done, item: group)
end
target_parent = group
end
end
unless target_parent == item.parent
debug 'Moving item to %s', item, target_parent.name
item = target_parent.move_item(item)
end
item.save!
item
end
end
end
end
end
|
isabella232/gapid
|
gapis/api/vulkan/query_timestamps.go
|
// Copyright (C) 2018 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.
package vulkan
import (
"bytes"
"context"
"fmt"
"github.com/google/gapid/core/data/endian"
"github.com/google/gapid/core/log"
"github.com/google/gapid/gapir"
"github.com/google/gapid/gapis/api"
"github.com/google/gapid/gapis/api/transform"
"github.com/google/gapid/gapis/capture"
"github.com/google/gapid/gapis/memory"
"github.com/google/gapid/gapis/replay"
"github.com/google/gapid/gapis/replay/builder"
"github.com/google/gapid/gapis/replay/value"
"github.com/google/gapid/gapis/service"
"github.com/google/gapid/gapis/service/path"
)
// Default query pool size
const queryPoolSize = 256
type timestampRecord struct {
timestamp service.TimestampsItem
// Is this timestamp from the last command in the commandbuffer
IsEoC bool
}
type queryResults []timestampRecord
// queryPoolInfo contains the information about the query pool
type queryPoolInfo struct {
queryPool VkQueryPool
queryPoolSize uint32
device VkDevice
queue VkQueue
queryCount uint32
results queryResults
}
// commandPoolKey is used to find a command pool suitable for a specific queue family
type commandPoolKey struct {
device VkDevice
queueFamily uint32
}
type queryTimestamps struct {
replay.EndOfReplay
cmds []api.Cmd
commandPools map[commandPoolKey]VkCommandPool
queryPools map[VkQueue]*queryPoolInfo
timestampPeriod float32
replayResult []replay.Result
allocated []*api.AllocResult
willLoop bool
readyToLoop bool
handler service.TimeStampsHandler
results map[uint64]queryResults
}
func newQueryTimestamps(ctx context.Context, c *capture.GraphicsCapture, Cmds []api.Cmd, willLoop bool, handler service.TimeStampsHandler) *queryTimestamps {
transform := &queryTimestamps{
cmds: Cmds,
commandPools: make(map[commandPoolKey]VkCommandPool),
queryPools: make(map[VkQueue]*queryPoolInfo),
willLoop: willLoop,
handler: handler,
results: make(map[uint64]queryResults),
}
return transform
}
func max(x, y uint32) uint32 {
if x > y {
return x
}
return y
}
func (t *queryTimestamps) mustAllocData(ctx context.Context, s *api.GlobalState, v ...interface{}) api.AllocResult {
res := s.AllocDataOrPanic(ctx, v...)
t.allocated = append(t.allocated, &res)
return res
}
func (t *queryTimestamps) createQueryPoolIfNeeded(ctx context.Context,
cb CommandBuilder,
out transform.Writer,
queue VkQueue,
device VkDevice,
numQuery uint32) *queryPoolInfo {
s := out.State()
qSize := uint32(0)
info, ok := t.queryPools[queue]
if ok && GetState(s).QueryPools().Contains(info.queryPool) {
if numQuery <= info.queryPoolSize {
return info
}
// Get the results back before destroy the old querypool
t.GetQueryResults(ctx, cb, out, info)
newCmd := cb.VkDestroyQueryPool(
info.device,
info.queryPool,
memory.Nullptr)
out.MutateAndWrite(ctx, api.CmdNoID, newCmd)
// Increase the size of pool to 1.5 times of previous size or set it to numQuery whichever is larger.
qSize = max(numQuery, info.queryPoolSize*3/2)
} else {
qSize = queryPoolSize
}
log.I(ctx, "Create query pool of size %d", qSize)
queryPool := VkQueryPool(newUnusedID(false, func(id uint64) bool {
return GetState(s).QueryPools().Contains(VkQueryPool(id))
}))
queryPoolHandleData := t.mustAllocData(ctx, s, queryPool)
queryPoolCreateInfo := t.mustAllocData(ctx, s, NewVkQueryPoolCreateInfo(s.Arena,
VkStructureType_VK_STRUCTURE_TYPE_QUERY_POOL_CREATE_INFO, // sType
0, // pNext
0, // flags
VkQueryType_VK_QUERY_TYPE_TIMESTAMP, // queryType
qSize, // queryCount
0, // pipelineStatistics
))
newCmd := cb.VkCreateQueryPool(
device,
queryPoolCreateInfo.Ptr(),
memory.Nullptr,
queryPoolHandleData.Ptr(),
VkResult_VK_SUCCESS)
newCmd.AddRead(queryPoolCreateInfo.Data()).AddWrite(queryPoolHandleData.Data())
info = &queryPoolInfo{queryPool, qSize, device, queue, 0, []timestampRecord{}}
t.queryPools[queue] = info
out.MutateAndWrite(ctx, api.CmdNoID, newCmd)
return info
}
func (t *queryTimestamps) createCommandpoolIfNeeded(ctx context.Context,
cb CommandBuilder,
out transform.Writer,
device VkDevice,
queueFamilyIndex uint32) VkCommandPool {
key := commandPoolKey{device, queueFamilyIndex}
s := out.State()
if cp, ok := t.commandPools[key]; ok {
if GetState(s).CommandPools().Contains(VkCommandPool(cp)) {
return cp
}
}
commandPoolID := VkCommandPool(newUnusedID(false,
func(x uint64) bool {
ok := GetState(s).CommandPools().Contains(VkCommandPool(x))
return ok
}))
commandPoolCreateInfo := NewVkCommandPoolCreateInfo(s.Arena,
VkStructureType_VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO, // sType
NewVoidᶜᵖ(memory.Nullptr), // pNext
VkCommandPoolCreateFlags(VkCommandPoolCreateFlagBits_VK_COMMAND_POOL_CREATE_TRANSIENT_BIT), // flags
queueFamilyIndex, // queueFamilyIndex
)
commandPoolCreateInfoData := t.mustAllocData(ctx, s, commandPoolCreateInfo)
commandPoolData := t.mustAllocData(ctx, s, commandPoolID)
newCmd := cb.VkCreateCommandPool(
device,
commandPoolCreateInfoData.Ptr(),
memory.Nullptr,
commandPoolData.Ptr(),
VkResult_VK_SUCCESS,
).AddRead(
commandPoolCreateInfoData.Data(),
).AddWrite(
commandPoolData.Data(),
)
out.MutateAndWrite(ctx, api.CmdNoID, newCmd)
t.commandPools[key] = commandPoolID
return commandPoolID
}
func (t *queryTimestamps) generateQueryCommand(ctx context.Context,
cb CommandBuilder,
out transform.Writer,
device VkDevice,
queryPool VkQueryPool,
commandPool VkCommandPool,
query uint32) VkCommandBuffer {
s := out.State()
commandBufferAllocateInfo := NewVkCommandBufferAllocateInfo(s.Arena,
VkStructureType_VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO, // sType
NewVoidᶜᵖ(memory.Nullptr), // pNext
commandPool, // commandPool
VkCommandBufferLevel_VK_COMMAND_BUFFER_LEVEL_PRIMARY, // level
1, // commandBufferCount
)
commandBufferAllocateInfoData := t.mustAllocData(ctx, s, commandBufferAllocateInfo)
commandBufferID := VkCommandBuffer(newUnusedID(true,
func(x uint64) bool {
ok := GetState(s).CommandBuffers().Contains(VkCommandBuffer(x))
return ok
}))
commandBufferData := t.mustAllocData(ctx, s, commandBufferID)
beginCommandBufferInfo := NewVkCommandBufferBeginInfo(s.Arena,
VkStructureType_VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO, // sType
0, // pNext
VkCommandBufferUsageFlags(VkCommandBufferUsageFlagBits_VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT), // flags
0, // pInheritanceInfo
)
beginCommandBufferInfoData := t.mustAllocData(ctx, s, beginCommandBufferInfo)
writeEach(ctx, out,
cb.VkAllocateCommandBuffers(
device,
commandBufferAllocateInfoData.Ptr(),
commandBufferData.Ptr(),
VkResult_VK_SUCCESS,
).AddRead(
commandBufferAllocateInfoData.Data(),
).AddWrite(
commandBufferData.Data(),
),
cb.VkBeginCommandBuffer(
commandBufferID,
beginCommandBufferInfoData.Ptr(),
VkResult_VK_SUCCESS,
).AddRead(
beginCommandBufferInfoData.Data(),
),
cb.VkCmdResetQueryPool(commandBufferID, queryPool, query, 1),
cb.VkCmdWriteTimestamp(commandBufferID,
VkPipelineStageFlagBits_VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT,
queryPool,
query),
cb.VkEndCommandBuffer(
commandBufferID,
VkResult_VK_SUCCESS,
),
)
return commandBufferID
}
func (t *queryTimestamps) rewriteQueueSubmit(ctx context.Context,
cb CommandBuilder,
out transform.Writer,
id api.CmdID,
device VkDevice,
queryPoolInfo *queryPoolInfo,
commandPool VkCommandPool,
cmd *VkQueueSubmit) error {
s := out.State()
l := s.MemoryLayout
reads := []api.AllocResult{}
allocAndRead := func(v ...interface{}) api.AllocResult {
res := t.mustAllocData(ctx, s, v)
reads = append(reads, res)
return res
}
cmd.Extras().Observations().ApplyReads(s.Memory.ApplicationPool())
submitCount := cmd.SubmitCount()
submitInfos := cmd.pSubmits.Slice(0, uint64(submitCount), s.MemoryLayout).MustRead(ctx, cmd, s, nil)
newSubmitInfos := make([]VkSubmitInfo, submitCount)
for i := uint32(0); i < submitCount; i++ {
si := submitInfos[i]
waitSemPtr := memory.Nullptr
waitDstStagePtr := memory.Nullptr
if count := uint64(si.WaitSemaphoreCount()); count > 0 {
waitSemPtr = allocAndRead(si.PWaitSemaphores().
Slice(0, count, l).
MustRead(ctx, cmd, s, nil)).Ptr()
waitDstStagePtr = allocAndRead(si.PWaitDstStageMask().
Slice(0, count, l).
MustRead(ctx, cmd, s, nil)).Ptr()
}
signalSemPtr := memory.Nullptr
if count := uint64(si.SignalSemaphoreCount()); count > 0 {
signalSemPtr = allocAndRead(si.PSignalSemaphores().
Slice(0, count, l).
MustRead(ctx, cmd, s, nil)).Ptr()
}
cmdBuffers := si.PCommandBuffers().Slice(0, uint64(si.CommandBufferCount()), s.MemoryLayout).MustRead(ctx, cmd, s, nil)
cmdCount := si.CommandBufferCount()
cmdBufferPtr := memory.Nullptr
newCmdCount := uint32(0)
if cmdCount != 0 {
newCmdCount = cmdCount*2 + 1
commandbuffer := t.generateQueryCommand(ctx,
cb,
out,
device,
queryPoolInfo.queryPool,
commandPool,
queryPoolInfo.queryCount)
queryPoolInfo.queryCount++
newCmdBuffers := make([]VkCommandBuffer, newCmdCount)
newCmdBuffers[0] = commandbuffer
for j := uint32(0); j < cmdCount; j++ {
buf := cmdBuffers[j]
newCmdBuffers[j*2+1] = buf
commandbuffer = t.generateQueryCommand(ctx,
cb,
out,
device,
queryPoolInfo.queryPool,
commandPool,
queryPoolInfo.queryCount)
queryPoolInfo.queryCount++
newCmdBuffers[j*2+2] = commandbuffer
begin := &path.Command{
Indices: []uint64{uint64(id), uint64(i), uint64(j), 0},
}
c, ok := GetState(s).CommandBuffers().Lookup(buf)
if !ok {
fmt.Errorf("Invalid command buffer %v", buf)
}
n := c.CommandReferences().Len()
k := 0
if n > 0 {
k = n - 1
}
end := &path.Command{
Indices: []uint64{uint64(id), uint64(i), uint64(j), uint64(k)},
}
timestampItem := service.TimestampsItem{Begin: begin, End: end, TimeInNanoseconds: 0}
queryPoolInfo.results = append(queryPoolInfo.results,
timestampRecord{timestamp: timestampItem, IsEoC: j == cmdCount-1})
}
cmdBufferPtr = allocAndRead(newCmdBuffers).Ptr()
}
newSubmitInfos[i] = NewVkSubmitInfo(s.Arena,
VkStructureType_VK_STRUCTURE_TYPE_SUBMIT_INFO,
0, // pNext
si.WaitSemaphoreCount(), // waitSemaphoreCount
NewVkSemaphoreᶜᵖ(waitSemPtr), // pWaitSemaphores
NewVkPipelineStageFlagsᶜᵖ(waitDstStagePtr), // pWaitDstStageMask
newCmdCount, // commandBufferCount
NewVkCommandBufferᶜᵖ(cmdBufferPtr), // pCommandBuffers
si.SignalSemaphoreCount(), // signalSemaphoreCount
NewVkSemaphoreᶜᵖ(signalSemPtr), // pSignalSemaphores
)
}
submitInfoPtr := allocAndRead(newSubmitInfos).Ptr()
newCmd := cb.VkQueueSubmit(
cmd.Queue(),
cmd.SubmitCount(),
submitInfoPtr,
cmd.Fence(),
VkResult_VK_SUCCESS,
)
for _, read := range reads {
newCmd.AddRead(read.Data())
}
return out.MutateAndWrite(ctx, id, newCmd)
}
func (t *queryTimestamps) GetQueryResults(ctx context.Context,
cb CommandBuilder,
out transform.Writer,
queryPoolInfo *queryPoolInfo) {
if queryPoolInfo == nil {
log.E(ctx, "queryPoolInfo is invalid")
return
}
queryCount := queryPoolInfo.queryCount
queue := queryPoolInfo.queue
if queryCount == 0 {
return
}
s := out.State()
waitCmd := cb.VkQueueWaitIdle(queue, VkResult_VK_SUCCESS)
out.MutateAndWrite(ctx, api.CmdNoID, waitCmd)
buflen := uint64(queryCount * 8)
tmp := s.AllocOrPanic(ctx, buflen)
flags := VkQueryResultFlags(VkQueryResultFlagBits_VK_QUERY_RESULT_64_BIT | VkQueryResultFlagBits_VK_QUERY_RESULT_WAIT_BIT)
newCmd := cb.VkGetQueryPoolResults(
queryPoolInfo.device,
queryPoolInfo.queryPool,
0,
queryCount,
memory.Size(buflen),
tmp.Ptr(),
8,
flags,
VkResult_VK_SUCCESS)
out.MutateAndWrite(ctx, api.CmdNoID, newCmd)
out.MutateAndWrite(ctx, api.CmdNoID, cb.Custom(func(ctx context.Context, s *api.GlobalState, b *builder.Builder) error {
b.ReserveMemory(tmp.Range())
notificationID := b.GetNotificationID()
t.results[notificationID] = queryPoolInfo.results
b.Notification(notificationID, value.ObservedPointer(tmp.Address()), buflen)
return b.RegisterNotificationReader(notificationID, func(n gapir.Notification) {
t.processNotification(ctx, s, n)
})
}))
queryPoolInfo.queryCount = 0
queryPoolInfo.results = []timestampRecord{}
tmp.Free()
}
func (t *queryTimestamps) processNotification(ctx context.Context, s *api.GlobalState, n gapir.Notification) {
notificationData := n.GetData()
notificationID := n.GetId()
timestampsData := notificationData.GetData()
res, ok := t.results[notificationID]
if !ok {
log.I(ctx, "Invalid notificationID %d", notificationID)
return
}
byteOrder := s.MemoryLayout.GetEndian()
r := endian.Reader(bytes.NewReader(timestampsData), byteOrder)
tStart := r.Uint64()
var timestamps service.Timestamps
resultCount := uint32(len(timestampsData) / 8)
resIdx := 0
for i := uint32(1); i < resultCount; i++ {
tEnd := r.Uint64()
record := res[resIdx]
record.timestamp.TimeInNanoseconds = uint64(float32(tEnd-tStart) * t.timestampPeriod)
if record.IsEoC {
tStart = r.Uint64()
i++
} else {
tStart = tEnd
}
timestamps.Timestamps = append(timestamps.Timestamps, &record.timestamp)
resIdx++
}
t.handler(&service.GetTimestampsResponse{
Res: &service.GetTimestampsResponse_Timestamps{
Timestamps: ×tamps,
},
})
}
func (t *queryTimestamps) Transform(ctx context.Context, id api.CmdID, cmd api.Cmd, out transform.Writer) error {
ctx = log.Enter(ctx, "queryTimestamps")
if t.willLoop && !t.readyToLoop {
return out.MutateAndWrite(ctx, id, cmd)
}
s := out.State()
cb := CommandBuilder{Thread: cmd.Thread(), Arena: s.Arena}
defer func() {
for _, d := range t.allocated {
d.Free()
}
}()
switch cmd := cmd.(type) {
case *VkQueueSubmit:
cmd.Extras().Observations().ApplyReads(s.Memory.ApplicationPool())
vkQueue := cmd.Queue()
queue := GetState(s).Queues().Get(vkQueue)
queueFamilyIndex := queue.Family()
vkDevice := queue.Device()
device := GetState(s).Devices().Get(vkDevice)
vkPhysicalDevice := device.PhysicalDevice()
physicalDevice := GetState(s).PhysicalDevices().Get(vkPhysicalDevice)
t.timestampPeriod = physicalDevice.PhysicalDeviceProperties().Limits().TimestampPeriod()
submitCount := cmd.SubmitCount()
submitInfos := cmd.pSubmits.Slice(0, uint64(submitCount), s.MemoryLayout).MustRead(ctx, cmd, s, nil)
cmdBufferCount := uint32(0)
for i := uint32(0); i < submitCount; i++ {
si := submitInfos[i]
cmdBufferCount += si.CommandBufferCount()
}
queryCount := cmdBufferCount * 2
commandPool := t.createCommandpoolIfNeeded(ctx, cb, out, vkDevice, queueFamilyIndex)
queryPoolInfo := t.createQueryPoolIfNeeded(ctx, cb, out, vkQueue, vkDevice, queryCount)
numSlotAvailable := queryPoolInfo.queryPoolSize - queryPoolInfo.queryCount
if numSlotAvailable < queryCount {
t.GetQueryResults(ctx, cb, out, queryPoolInfo)
}
return t.rewriteQueueSubmit(ctx, cb, out, id, vkDevice, queryPoolInfo, commandPool, cmd)
default:
return out.MutateAndWrite(ctx, id, cmd)
}
return nil
}
func (t *queryTimestamps) Flush(ctx context.Context, out transform.Writer) error {
s := out.State()
cb := CommandBuilder{Thread: 0, Arena: s.Arena}
for _, queryPoolInfo := range t.queryPools {
t.GetQueryResults(ctx, cb, out, queryPoolInfo)
}
t.cleanup(ctx, out)
t.AddNotifyInstruction(ctx, out, func() interface{} { return t.replayResult })
return nil
}
func (t *queryTimestamps) PreLoop(ctx context.Context, out transform.Writer) {
t.readyToLoop = true
}
func (t *queryTimestamps) PostLoop(ctx context.Context, out transform.Writer) {
t.readyToLoop = false
s := out.State()
cb := CommandBuilder{Thread: 0, Arena: s.Arena}
for _, queryPoolInfo := range t.queryPools {
t.GetQueryResults(ctx, cb, out, queryPoolInfo)
}
t.cleanup(ctx, out)
}
func (t *queryTimestamps) cleanup(ctx context.Context, out transform.Writer) {
s := out.State()
cb := CommandBuilder{Thread: 0, Arena: s.Arena}
// Destroy query pool created in this transform.
for _, info := range t.queryPools {
cmd := cb.VkDestroyQueryPool(
info.device,
info.queryPool,
memory.Nullptr,
)
out.MutateAndWrite(ctx, api.CmdNoID, cmd)
}
t.queryPools = make(map[VkQueue]*queryPoolInfo)
// Free commandpool allocated in this transform.
for commandPoolkey, commandPool := range t.commandPools {
cmd := cb.VkDestroyCommandPool(
commandPoolkey.device,
commandPool,
memory.Nullptr,
)
out.MutateAndWrite(ctx, api.CmdNoID, cmd)
}
t.commandPools = make(map[commandPoolKey]VkCommandPool)
}
func (t *queryTimestamps) BuffersCommands() bool { return false }
|
StarStuffSteve/masters-research-project
|
Simulation/OMNeT++/inet/src/inet/linklayer/ieee80211/mac/DuplicateDetectors.cc
|
<reponame>StarStuffSteve/masters-research-project
//
// Copyright (C) 2015 <NAME>
//
// This program 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 3 of the License, or
// (at your option) any later version.
//
// This program 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 program. If not, see http://www.gnu.org/licenses/.
//
// Author: <NAME>, <NAME>
//
#include "DuplicateDetectors.h"
#include "Ieee80211Frame_m.h"
#include "inet/common/stlutils.h"
namespace inet {
namespace ieee80211 {
void LegacyDuplicateDetector::assignSequenceNumber(Ieee80211DataOrMgmtFrame *frame)
{
ASSERT(frame->getType() != ST_DATA_WITH_QOS);
lastSeqNum = (lastSeqNum + 1) % 4096;
frame->setSequenceNumber(lastSeqNum);
}
bool LegacyDuplicateDetector::isDuplicate(Ieee80211DataOrMgmtFrame *frame)
{
ASSERT(frame->getType() != ST_DATA_WITH_QOS);
const MACAddress& address = frame->getTransmitterAddress();
SeqVal seqVal;
seqVal.seqNum = frame->getSequenceNumber();
seqVal.fragNum = frame->getFragmentNumber();
auto it = lastSeenSeqNumCache.find(address);
if (it == lastSeenSeqNumCache.end())
lastSeenSeqNumCache[address] = seqVal;
else if (it->second.seqNum == seqVal.seqNum && it->second.fragNum == seqVal.fragNum && frame->getRetry())
return true;
else
it->second = seqVal;
return false;
}
//---
void NonQoSDuplicateDetector::assignSequenceNumber(Ieee80211DataOrMgmtFrame *frame)
{
ASSERT(frame->getType() != ST_DATA_WITH_QOS);
lastSeqNum = (lastSeqNum + 1) % 4096;
const MACAddress& address = frame->getReceiverAddress();
auto it = lastSentSeqNums.find(address);
if (it == lastSentSeqNums.end())
lastSentSeqNums[address] = lastSeqNum;
else {
if (it->second == lastSeqNum)
lastSeqNum = (lastSeqNum + 1) % 4096; // make it different from the last sequence number sent to that RA (spec: "add 2")
it->second = lastSeqNum;
}
frame->setSequenceNumber(lastSeqNum);
}
//---
QoSDuplicateDetector::CacheType QoSDuplicateDetector::getCacheType(Ieee80211DataOrMgmtFrame *frame, bool incoming)
{
bool isTimePriorityFrame = false; // TODO
const MACAddress& address = incoming ? frame->getTransmitterAddress() : frame->getReceiverAddress();
if (isTimePriorityFrame)
return TIME_PRIORITY;
else if (frame->getType() != ST_DATA_WITH_QOS || address.isMulticast())
return SHARED;
else
return DATA;
}
void QoSDuplicateDetector::assignSequenceNumber(Ieee80211DataOrMgmtFrame *frame)
{
CacheType type = getCacheType(frame, false);
int seqNum;
MACAddress address = frame->getReceiverAddress();
if (type == TIME_PRIORITY)
{
// Error in spec?
// "QoS STA may use values from additional modulo-4096 counters per <Address 1, TID> for sequence numbers assigned to
// time priority management frames." 9.3.2.10 Duplicate detection and recovery, But management frames don't have QoS Control field.
auto it = lastSentTimePrioritySeqNums.find(address);
if (it == lastSentTimePrioritySeqNums.end())
lastSentTimePrioritySeqNums[address] = seqNum = 0;
else
it->second = seqNum = (it->second + 1) % 4096;
}
if (type == SHARED)
{
auto it = lastSentSharedSeqNums.find(address);
if (it == lastSentSharedSeqNums.end())
lastSentSharedSeqNums[address] = seqNum = lastSentSharedCounterSeqNum;
else {
if (it->second == lastSentSharedCounterSeqNum)
lastSentSharedCounterSeqNum = (lastSentSharedCounterSeqNum + 1) % 4096; // make it different from the last sequence number sent to that RA (spec: "add 2")
it->second = seqNum = lastSentSharedCounterSeqNum;
}
}
else if (type == DATA)
{
Ieee80211DataFrame *qosDataFrame = check_and_cast<Ieee80211DataFrame *>(frame);
Key key(frame->getReceiverAddress(), qosDataFrame->getTid());
auto it = lastSentSeqNums.find(key);
if (it == lastSentSeqNums.end())
lastSentSeqNums[key] = seqNum = 0;
else
it->second = seqNum = (it->second + 1) % 4096;
}
else
ASSERT(false);
frame->setSequenceNumber(seqNum);
}
bool QoSDuplicateDetector::isDuplicate(Ieee80211DataOrMgmtFrame *frame)
{
SeqVal seqVal;
seqVal.seqNum = frame->getSequenceNumber();
seqVal.fragNum = frame->getFragmentNumber();
bool isManagementFrame = dynamic_cast<Ieee80211ManagementFrame *>(frame);
bool isTimePriorityManagementFrame = isManagementFrame && false; // TODO: hack
if (isTimePriorityManagementFrame || isManagementFrame)
{
MACAddress transmitterAddr = frame->getTransmitterAddress();
Mac2SeqValMap& cache = isTimePriorityManagementFrame ? lastSeenTimePriorityManagementSeqNumCache : lastSeenSharedSeqNumCache;
auto it = cache.find(transmitterAddr);
if (it == cache.end())
cache[transmitterAddr] = seqVal;
if (it->second.seqNum == seqVal.seqNum && it->second.fragNum == seqVal.fragNum && frame->getRetry())
return true;
else
it->second = seqVal;
return false;
}
else
{
Ieee80211DataFrame *qosDataFrame = check_and_cast<Ieee80211DataFrame *>(frame);
Key key(frame->getTransmitterAddress(), qosDataFrame->getTid());
auto it = lastSeenSeqNumCache.find(key);
if (it == lastSeenSeqNumCache.end())
lastSeenSeqNumCache[key] = seqVal;
if (it->second.seqNum == seqVal.seqNum && it->second.fragNum == seqVal.fragNum && frame->getRetry())
return true;
else
it->second = seqVal;
return false;
}
}
} // namespace ieee80211
} // namespace inet
|
andremourato/programacao
|
programacao-2/guiao1/ex6/g1e6.java
|
import java.util.*;
public class g1e6 {
public static void main (String[] args) {
Scanner read = new Scanner(System.in);
int random = (int) (Math.random()*(101));
int guess;
int score=0;
System.out.println("---------------------");
System.out.println("| ADIVINHA O NUMERO |");
System.out.println("---------------------");
System.out.println();
do{
System.out.print("Tentativa: ");
guess = read.nextInt();
if(guess>random) System.out.println("A tentativa e maior do que o numero");
else if(guess<random) System.out.println("A tentativa e menor do que o numero");
System.out.println();
score++;
}while(guess!=random);
if(score==1)System.out.println("Conseguiste acertar no numero numa tentativa!\n");
else System.out.printf("Conseguiste acertar no numero em %d tentativas\n",score);
}
}
|
FoxDenStudio/FoxCore-Common
|
src/main/java/net/foxdenstudio/foxsuite/foxcore/content/command/CommandSave.java
|
<filename>src/main/java/net/foxdenstudio/foxsuite/foxcore/content/command/CommandSave.java
package net.foxdenstudio.foxsuite.foxcore.content.command;
import net.foxdenstudio.foxsuite.foxcore.api.annotation.guice.FoxLogger;
import net.foxdenstudio.foxsuite.foxcore.api.command.result.FoxCommandResult;
import net.foxdenstudio.foxsuite.foxcore.api.command.standard.FoxStandardCommandBase;
import net.foxdenstudio.foxsuite.foxcore.api.exception.command.FoxCommandException;
import net.foxdenstudio.foxsuite.foxcore.api.object.index.FoxMainIndex;
import net.foxdenstudio.foxsuite.foxcore.api.object.index.FoxObjectIndex;
import net.foxdenstudio.foxsuite.foxcore.api.object.index.types.StorageIndex;
import net.foxdenstudio.foxsuite.foxcore.api.world.FoxWorldManager;
import net.foxdenstudio.foxsuite.foxcore.platform.command.source.CommandSource;
import org.slf4j.Logger;
import javax.annotation.Nonnull;
import javax.inject.Inject;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
public class CommandSave extends FoxStandardCommandBase {
private final FoxMainIndex mainIndex;
private final FoxWorldManager worldManager;
@FoxLogger("command.save")
private Logger logger;
private Map<String, Target> targetMap;
@Inject
private CommandSave(FoxMainIndex mainIndex, FoxWorldManager worldManager) {
this.mainIndex = mainIndex;
this.worldManager = worldManager;
this.targetMap = new HashMap<>();
this.addTarget("all", new Target() {
@Override
public void save(CommandSource source, String arg) throws FoxCommandException {
logger.info("Source \"{}\" started complete save.", source.getName());
for (Map.Entry<String, Target> entry : CommandSave.this.targetMap.entrySet()) {
Target target = entry.getValue();
if (target == this) continue;
target.save(source, null);
}
}
});
this.addTarget("index", (source, arg) -> {
if (arg == null || arg.isEmpty()) {
logger.info("Source \"{}\" started full index save.", source.getName());
int counter = 0;
for (FoxObjectIndex index : this.mainIndex.getIndices().values()) {
if (index instanceof StorageIndex) {
((StorageIndex) index).save();
counter++;
}
}
if (logger.isInfoEnabled())
logger.info("Source \"{}\" saved {} ind{}.", source.getName(), counter, counter == 1 ? "ex" : "ices");
} else {
Optional<FoxObjectIndex> indexOpt = this.mainIndex.getObjectIndex(arg);
if (indexOpt.isPresent()) {
FoxObjectIndex index = indexOpt.get();
if (index instanceof StorageIndex) {
logger.info("Source \"{}\" started save of index \"{}\".", source.getName(), index.getIndexName());
((StorageIndex) index).save();
} else {
throw new FoxCommandException("Index \"" + index.getIndexName()
+ "\" is not a storage index and cannot be saved.");
}
} else {
throw new FoxCommandException("There is no index with name \"" + arg + "\"");
}
}
});
this.addTarget("world", (source, arg) -> {
logger.info("Source \"{}\" started world index save.", source.getName());
this.worldManager.save();
});
}
@Override
public FoxCommandResult process(@Nonnull CommandSource source, @Nonnull String arguments) throws FoxCommandException {
if (!source.hasPermission("fox.save")) return resultFactory.failure();
String[] parts = arguments.trim().split(" +", 3);
String targetStr = null;
String arg = null;
Target target = null;
if (parts.length < 1 || parts[0].isEmpty()) {
targetStr = "all";
} else {
targetStr = parts[0];
if (parts.length > 1) {
parts[1] = parts[1].trim();
if (!parts[1].isEmpty())
arg = parts[1];
}
}
target = this.targetMap.get(targetStr.toLowerCase());
if (target == null)
throw new FoxCommandException("There is no target with name \"" + targetStr + "\"");
target.save(source, arg);
if (logger.isInfoEnabled())
logger.info("Finished save operation on target \"{}{}\"", targetStr, arg == null ? "" : "\" with argument \"" + arg);
String message = "Saved successfully!";
source.sendMessage(tf.of(message));
return resultFactory.empty();
}
public boolean addTarget(String name, Target target) {
if (this.targetMap.containsKey(name)) return false;
this.targetMap.put(name.toLowerCase(), target);
return true;
}
public interface Target {
void save(CommandSource source, String arg) throws FoxCommandException;
}
}
|
heyImDrew/edupro
|
frontend/src/actions/desks.js
|
<filename>frontend/src/actions/desks.js
import {authConstants} from "./types"
import axios from "axios";
const HOST = "http://localhost:9000/api/"
export const load_desks = () => async dispatch => {
const config = {
headers: {
'Content-Type': "application/json",
'Authorization': 'Bearer ' + localStorage.getItem('token')
}
};
try {
const res = await axios.get(HOST + "desks/", config)
dispatch({
type: authConstants.GET_DESKS_SUCCESS,
payload: res.data
})
} catch (err) {
dispatch({
type: authConstants.GET_DESKS_FAIL
})
}
}
|
whitefancy/AlgorthmSolution
|
basicKnowledge/dataStructure/treeGraph/SerializeAndSeserializeBST.java
|
<gh_stars>0
package Algorithm.basicKnowledge.dataStructure.treeGraph;
import java.util.ArrayDeque;
/**
* 序列化是将数据结构或对象转换为一系列位的过程,以便它可以存储在文件或内存缓冲区中,或通过网络连接链路传输,以便稍后在同一个或另一个计算机环境中重建。
* <p>
* 设计一个算法来序列化和反序列化二叉搜索树。 对序列化/反序列化算法的工作方式没有限制。 您只需确保二叉搜索树可以序列化为字符串,并且可以将该字符串反序列化为最初的二叉搜索树。
* <p>
* 编码的字符串应尽可能紧凑。
* <p>
* 注意:不要使用类成员/全局/静态变量来存储状态。 你的序列化和反序列化算法应该是无状态的。
* <p>
* 执行结果:
* 通过
*/
public class SerializeAndSeserializeBST {
// Encodes a tree to a single string.
public String serialize(TreeNode root) {
if (root == null) {
return "";
}
StringBuilder sb = postOrder(root, new StringBuilder());
sb.deleteCharAt(sb.length() - 1);
return sb.toString();
}
/**
* 二叉搜索树能只够通过前序序列或后序序列构造,是因为以下两个因素:
* <p>
* 二叉树可以通过前序序列或后序序列和中序序列构造。
* 二叉搜索树的中序序列是递增排序的序列,inorder = sorted(preorder)。
* 说明我们只需要直到了前序序列或后序序列相当于我们也知道了中序序列,可以通过排序获得。
*
* @param node
* @param sb
* @return
*/
StringBuilder postOrder(TreeNode node, StringBuilder sb) {
if (node.left != null) {
postOrder(node.left, sb);
}
if (node.right != null) {
postOrder(node.right, sb);
}
sb.append(node.val);
sb.append(' ');
return sb;
}
// Decodes your encoded data to tree.
public TreeNode deserialize(String data) {
String[] vals = data.split("\\s+");
if (data.trim().length() == 0) {
return null;
}
ArrayDeque<Integer> stack = new ArrayDeque<>(vals.length);
for (String s : vals) {
stack.offerLast(Integer.parseInt(s));
}
return helper(Integer.MIN_VALUE, Integer.MAX_VALUE, stack);
}
TreeNode helper(int lower, int upper, ArrayDeque<Integer> stack) {
if (stack.isEmpty()) {
return null;
}
Integer val = stack.peekLast();
if (val < lower || val > upper) {
return null;
}
TreeNode node = new TreeNode(val);
stack.pollLast();
node.right = helper(val, upper, stack);
node.left = helper(lower, val, stack);
return node;
}
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
}
|
smtcrms/Blazar
|
BlazarService/src/main/java/com/hubspot/blazar/visitor/repositorybuild/SlackDmNotificationVisitor.java
|
<reponame>smtcrms/Blazar<gh_stars>10-100
package com.hubspot.blazar.visitor.repositorybuild;
import static com.hubspot.blazar.base.RepositoryBuild.State.FAILED;
import static com.hubspot.blazar.base.RepositoryBuild.State.UNSTABLE;
import java.util.Collections;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Sets;
import com.google.inject.Inject;
import com.hubspot.blazar.base.BuildTrigger;
import com.hubspot.blazar.base.GitInfo;
import com.hubspot.blazar.base.RepositoryBuild;
import com.hubspot.blazar.base.visitor.RepositoryBuildVisitor;
import com.hubspot.blazar.config.BlazarConfiguration;
import com.hubspot.blazar.config.BlazarSlackDirectMessageConfiguration;
import com.hubspot.blazar.data.service.BranchService;
import com.hubspot.blazar.util.BlazarSlackClient;
import com.hubspot.blazar.util.SlackMessageBuildingUtils;
/**
* Direct messages slack users about the state of builds caused by their pushes
*/
public class SlackDmNotificationVisitor implements RepositoryBuildVisitor {
// Cancelled requires a user action - likely the user who would be slacked anyway so it is not worth messaging about
private static final Set<RepositoryBuild.State> SLACK_WORTHY_FAILING_STATES = ImmutableSet.of(FAILED, UNSTABLE);
private static final Logger LOG = LoggerFactory.getLogger(SlackDmNotificationVisitor.class);
private final BlazarSlackDirectMessageConfiguration slackDirectMessageConfig;
private final BranchService branchService;
private final SlackMessageBuildingUtils slackMessageBuildingUtils;
private final BlazarSlackClient blazarSlackClient;
@Inject
public SlackDmNotificationVisitor(BlazarConfiguration blazarConfiguration,
BranchService branchService,
SlackMessageBuildingUtils slackMessageBuildingUtils,
BlazarSlackClient blazarSlackClient) {
this.branchService = branchService;
this.slackMessageBuildingUtils = slackMessageBuildingUtils;
this.blazarSlackClient = blazarSlackClient;
this.slackDirectMessageConfig = blazarConfiguration.getSlackConfiguration().get().getDirectMessageConfiguration();
}
@Override
public void visit(RepositoryBuild build) throws Exception {
if (!build.getState().isComplete()) {
return;
}
Set<String> userEmailsToSendMessagesTo = getUserEmailsToDirectlyNotify(build);
boolean shouldSendMessage = shouldSendMessage(build, userEmailsToSendMessagesTo);
if (shouldSendMessage) {
for (String email : userEmailsToSendMessagesTo) {
String message = "A build started by your code push was not successful";
blazarSlackClient.sendMessageToUser(email, message, slackMessageBuildingUtils.buildSlackAttachment(build));
}
}
}
private Set<String> getUserEmailsToDirectlyNotify(RepositoryBuild build) {
if (!build.getCommitInfo().isPresent()) {
LOG.info("No commit info present cannot determine user to slack");
return Collections.emptySet();
}
Set<String> directNotifyEmails = Sets.newHashSet(
build.getCommitInfo().get().getCurrent().getAuthor().getEmail(), // Author Email
build.getCommitInfo().get().getCurrent().getAuthor().getEmail()); // Committer Email
directNotifyEmails.removeAll(slackDirectMessageConfig.getBlacklistedUserEmails());
// If the white list is empty we send to author/committer
// else we only send to the whitelisted members
if (slackDirectMessageConfig.getWhitelistedUserEmails().isEmpty()) {
return directNotifyEmails;
} else {
return Sets.intersection(directNotifyEmails, slackDirectMessageConfig.getWhitelistedUserEmails());
}
}
private boolean shouldSendMessage(RepositoryBuild build, Set<String> userEmailsToSendMessagesTo) {
if (userEmailsToSendMessagesTo.isEmpty()) {
return false;
}
// Do not send notifications for builds of branches that are explicitly ignored
GitInfo branch = branchService.get(build.getBranchId()).get();
if (slackDirectMessageConfig.getIgnoredBranches().contains(branch.getBranch())) {
LOG.info("Not sending messages for build {} because the branch is in the list of ignored branches {}", build, slackDirectMessageConfig.getIgnoredBranches());
return false;
}
if (!branch.isActive()) {
LOG.info("Branch {} is no longer active, probably was deleted before build finished. Not sending notification for build {}", branch, build);
return false;
}
boolean wasPush = build.getBuildTrigger().getType() == BuildTrigger.Type.PUSH;
boolean wasBranchCreation = build.getBuildTrigger().getType() == BuildTrigger.Type.BRANCH_CREATION;
if (!(wasPush || wasBranchCreation)) {
LOG.info("Not sending messages for triggers other than push or branch creation at this time.");
return false;
}
if (!SLACK_WORTHY_FAILING_STATES.contains(build.getState())) {
LOG.info("Build {} in state {} does not merit direct-slack-message", build.getId().get(), build.getState());
return false;
}
return true;
}
}
|
champ-cargosystems-gmbh/champ.cargojson.aero
|
src/main/java/aero/champ/cargojson/common/FlightNumber.java
|
package aero.champ.cargojson.common;
import aero.champ.cargojson.docgen.annotations.JsonDocExample;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonValue;
import javax.validation.constraints.Pattern;
import java.util.Optional;
import java.util.regex.Matcher;
public class FlightNumber {
@JsonIgnore
public final String flightNumber;
@JsonCreator
public FlightNumber(@Pattern(regexp = "[0-9]{1,4}[A-Z]?") String flightNumber) {
this.flightNumber = flightNumber;
}
@JsonValue
@JsonDocExample("116")
public String flightNumber() {
return flightNumber;
}
static final java.util.regex.Pattern EXTRACT_FLIGHTNUMBER = java.util.regex.Pattern.compile("([0-9]+)");
public int flightNumberWithoutOperationalSuffix() {
Matcher m = EXTRACT_FLIGHTNUMBER.matcher(flightNumber);
if (m.find()) {
return Integer.parseInt(m.group(1));
}
throw new IllegalStateException("Flight number corrupted: '"+flightNumber+"'");
}
static final java.util.regex.Pattern EXTRACT_SUFFIX = java.util.regex.Pattern.compile("[0-9]+([A-Z])");
public Optional<String> operationalSuffix() {
Matcher m = EXTRACT_SUFFIX.matcher(flightNumber);
if (m.find()) {
return Optional.of(m.group(1));
}
return Optional.empty();
}
}
|
kuzzleio/quickmatch
|
test/keywords/geospatial.test.js
|
<gh_stars>10-100
const should = require('should/as-function');
const { Koncorde } = require('../../');
/**
* Mutualizes filter removal for all 4 geospatial keywords
*/
describe('Koncorde.keyword.geospatial', () => {
let koncorde;
let engine;
const geoFilter = {
geoBoundingBox: {
foo: {
bottom: 43.5810609,
left: 3.8433703,
top: 43.6331979,
right: 3.9282093
}
}
};
beforeEach(() => {
koncorde = new Koncorde();
engine = koncorde.engines.get(null);
});
describe('#removal', () => {
it('should destroy the whole structure when removing the last item', () => {
const id = koncorde.register(geoFilter);
koncorde.remove(id);
should(engine.foPairs).be.empty();
});
it('should remove the entire field if its last condition is removed', () => {
koncorde.register({
geoDistance: {
bar: {
lat: 13,
lon: 42,
},
distance: '1km',
},
});
const id = koncorde.register(geoFilter);
koncorde.remove(id);
const storage = engine.foPairs.get('geospatial');
should(storage.fields.get('bar')).be.an.Object();
should(storage.fields.get('foo')).be.undefined();
});
it('should remove a single condition from a field if other conditions exist', () => {
const id1 = koncorde.register({
geoDistance: {
foo: {
lat: 13,
lon: 42,
},
distance: '1km',
},
});
const id2 = koncorde.register(geoFilter);
const sf = Array.from(engine.filters.get(id1).subfilters)[0];
const cond = Array.from(sf.conditions)[0].id;
koncorde.remove(id2);
const storage = engine.foPairs.get('geospatial');
should(storage.fields.get('foo').get(cond)).match(new Set([sf]));
});
it('should remove a subfilter from a condition if other subfilters exist', () => {
const id1 = koncorde.register(geoFilter);
const sf = Array.from(engine.filters.get(id1).subfilters)[0];
const cond = Array.from(sf.conditions)[0].id;
const id2 = koncorde.register({
and: [
geoFilter,
{ exists: { field: 'bar' } },
],
});
koncorde.remove(id2);
const storage = engine.foPairs.get('geospatial');
should(storage.fields.get('foo').get(cond)).match(new Set([sf]));
});
});
});
|
prafullkotecha/waltz
|
waltz-integration-test/src/test/java/org/finos/waltz/integration_test/inmem/helpers/LogicalFlowHelper.java
|
<reponame>prafullkotecha/waltz<filename>waltz-integration-test/src/test/java/org/finos/waltz/integration_test/inmem/helpers/LogicalFlowHelper.java
package org.finos.waltz.integration_test.inmem.helpers;
import org.finos.waltz.data.datatype_decorator.LogicalFlowDecoratorDao;
import org.finos.waltz.data.logical_flow.LogicalFlowDao;
import org.finos.waltz.model.EntityKind;
import org.finos.waltz.model.EntityReference;
import org.finos.waltz.model.datatype.DataTypeDecorator;
import org.finos.waltz.model.datatype.ImmutableDataTypeDecorator;
import org.finos.waltz.model.logical_flow.ImmutableLogicalFlow;
import org.finos.waltz.model.logical_flow.LogicalFlow;
import org.finos.waltz.model.rating.AuthoritativenessRatingValue;
import org.jooq.DSLContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Set;
import static org.finos.waltz.common.DateTimeUtilities.nowUtc;
import static org.finos.waltz.common.ListUtilities.map;
import static org.finos.waltz.model.EntityReference.mkRef;
import static org.finos.waltz.schema.Tables.LOGICAL_FLOW;
@Service
public class LogicalFlowHelper {
@Autowired
private DSLContext dsl;
@Autowired
private LogicalFlowDao logicalFlowDao;
@Autowired
private LogicalFlowDecoratorDao logicalFlowDecoratorDao;
public LogicalFlow createLogicalFlow(EntityReference refA, EntityReference refB) {
return logicalFlowDao.addFlow(ImmutableLogicalFlow
.builder()
.source(refA)
.target(refB)
.lastUpdatedBy("admin")
.build());
}
public void createLogicalFlowDecorators(EntityReference flowRef, Set<Long> dtIds) {
List<DataTypeDecorator> decorators = map(dtIds, dtId -> ImmutableDataTypeDecorator.builder()
.rating(AuthoritativenessRatingValue.NO_OPINION)
.entityReference(flowRef)
.decoratorEntity(mkRef(EntityKind.DATA_TYPE, dtId))
.provenance("waltz")
.lastUpdatedAt(nowUtc())
.lastUpdatedBy("test")
.build());
logicalFlowDecoratorDao.addDecorators(decorators);
}
public List<DataTypeDecorator> fetchDecoratorsForFlow(Long flowId) {
return logicalFlowDecoratorDao.findByEntityId(flowId);
}
public void clearAllFlows(){
dsl.deleteFrom(LOGICAL_FLOW).execute();
}
}
|
alrs/acyl
|
vendor/github.com/hashicorp/vault/vault/router_ext_test.go
|
<filename>vendor/github.com/hashicorp/vault/vault/router_ext_test.go
package vault_test
import (
"testing"
"github.com/hashicorp/vault/api"
"github.com/hashicorp/vault/builtin/credential/userpass"
vaulthttp "github.com/hashicorp/vault/http"
"github.com/hashicorp/vault/logical"
"github.com/hashicorp/vault/vault"
)
func TestRouter_MountSubpath_Checks(t *testing.T) {
testRouter_MountSubpath(t, []string{"auth/abcd/123", "abcd/123"})
testRouter_MountSubpath(t, []string{"abcd/123", "auth/abcd/123"})
testRouter_MountSubpath(t, []string{"auth/abcd/123", "abcd/123"})
}
func testRouter_MountSubpath(t *testing.T, mountPoints []string) {
coreConfig := &vault.CoreConfig{
CredentialBackends: map[string]logical.Factory{
"userpass": userpass.Factory,
},
}
cluster := vault.NewTestCluster(t, coreConfig, &vault.TestClusterOptions{
HandlerFunc: vaulthttp.Handler,
})
cluster.Start()
defer cluster.Cleanup()
vault.TestWaitActive(t, cluster.Cores[0].Core)
client := cluster.Cores[0].Client
authInput := &api.EnableAuthOptions{
Type: "userpass",
}
for _, mp := range mountPoints {
t.Logf("mounting %s", mp)
var err error
err = client.Sys().EnableAuthWithOptions(mp, authInput)
if err != nil {
t.Fatalf("err: %v", err)
}
}
cluster.EnsureCoresSealed(t)
cluster.UnsealCores(t)
t.Logf("Done: %#v", mountPoints)
}
|
rubengomex/backend-api-starter
|
src/cron_jobs/index.js
|
<filename>src/cron_jobs/index.js
const schedule = require('node-schedule')
const jobs = require('./jobs')
// Runs a schedule job
exports.initialize = function () {
schedule.scheduleJob('* * * * * *', () => jobs.exampleJob())
}
|
fzyzcjy/ncnn
|
src/layer/vulkan/normalize_vulkan.h
|
// Tencent is pleased to support the open source community by making ncnn available.
//
// Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
//
// Licensed under the BSD 3-Clause License (the "License"); you may not use this file except
// in compliance with the License. You may obtain a copy of the License at
//
// https://opensource.org/licenses/BSD-3-Clause
//
// 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.
#ifndef LAYER_NORMALIZE_VULKAN_H
#define LAYER_NORMALIZE_VULKAN_H
#include "normalize.h"
namespace ncnn {
class Normalize_vulkan : virtual public Normalize
{
public:
Normalize_vulkan();
virtual int create_pipeline(const Option& opt);
virtual int destroy_pipeline(const Option& opt);
virtual int upload_model(VkTransfer& cmd, const Option& opt);
using Normalize::forward_inplace;
virtual int forward_inplace(VkMat& bottom_top_blob, VkCompute& cmd, const Option& opt) const;
virtual int forward_inplace(VkImageMat& bottom_top_blob, VkCompute& cmd, const Option& opt) const;
public:
VkMat scale_data_gpu;
VkImageMat scale_data_gpu_image;
Pipeline* pipeline_normalize_reduce_sum4_fp16_to_fp32;
Pipeline* pipeline_normalize_reduce_sum4_fp32[2];
Pipeline* pipeline_normalize_coeffs;
Pipeline* pipeline_normalize_norm;
Pipeline* pipeline_normalize_reduce_sum4_fp16_to_fp32_pack4;
Pipeline* pipeline_normalize_reduce_sum4_fp32_pack4[2];
Pipeline* pipeline_normalize_coeffs_pack4;
Pipeline* pipeline_normalize_norm_pack4;
Pipeline* pipeline_normalize_reduce_sum4_fp16_to_fp32_pack8;
Pipeline* pipeline_normalize_reduce_sum4_fp32_pack8[2];
Pipeline* pipeline_normalize_coeffs_pack8;
Pipeline* pipeline_normalize_norm_pack8;
};
} // namespace ncnn
#endif // LAYER_NORMALIZE_VULKAN_H
|
vsoftco/snippets
|
range.cpp
|
<filename>range.cpp
// Python-like simple range in C++14
#include <iostream>
#include <type_traits>
template <typename T>
class Range {
private:
T first, last, iter, step;
public:
Range(T first, T last, T step = 1)
: first(first), last(last), iter(first), step(step) {}
// Iterable functions
const Range& begin() const noexcept { return *this; }
const Range& end() const noexcept { return *this; }
const Range& cbegin() const noexcept { return begin(); }
const Range& cend() const noexcept { return end(); }
// Iterator functions
bool operator!=(const Range&) const noexcept { return iter < last; }
Range& operator++() noexcept {
iter += step;
return *this;
}
Range operator++(int) noexcept {
Range cpy{*this};
this->operator++();
return cpy;
}
T operator*() const noexcept { return iter; }
};
// Convenience function for automatic type deduction
template <typename T>
auto make_range(T fist, T last, T step = 1) {
return Range<T>{fist, last, step};
}
int main() {
for (auto i : make_range(10, 20, 2)) {
std::cout << i << std::endl;
}
auto it = make_range(-0.5, 0.5, 0.1);
std::cout << *(it++) << std::endl;
std::cout << *(++it) << std::endl;
std::cout << *it << std::endl;
}
|
nmousouros/Arduino-Source
|
Common/Qt/Options/EditableTable/EditableTableBaseWidget.h
|
<gh_stars>0
/* Editable Table Option
*
* From: https://github.com/PokemonAutomation/Arduino-Source
*
*/
#ifndef PokemonAutomation_EditableTableBaseWidget_H
#define PokemonAutomation_EditableTableBaseWidget_H
#include <QTableWidget>
#include "Common/Qt/AutoHeightTable.h"
#include "EditableTableBaseOption.h"
namespace PokemonAutomation{
class EditableTableBaseWidget : public QWidget{
public:
EditableTableBaseWidget(QWidget& parent, EditableTableBaseOption& value);
void restore_defaults();
void update_column_sizes();
private:
void redraw_table();
void insert_row(int index, std::unique_ptr<EditableTableRow> row);
void delete_row(int index);
QWidget* make_insert_button(EditableTableRow& row);
QWidget* make_delete_button(EditableTableRow& row);
private:
EditableTableBaseOption& m_value;
AutoHeightTableWidget* m_table;
};
}
#endif
|
uzzz/cli
|
plugin/fakes/fake_cli_connection.go
|
<reponame>uzzz/cli<filename>plugin/fakes/fake_cli_connection.go
// This file was generated by counterfeiter
package fakes
import (
"sync"
"github.com/cloudfoundry/cli/plugin"
"github.com/cloudfoundry/cli/plugin/models"
)
type FakeCliConnection struct {
CliCommandWithoutTerminalOutputStub func(args ...string) ([]string, error)
cliCommandWithoutTerminalOutputMutex sync.RWMutex
cliCommandWithoutTerminalOutputArgsForCall []struct {
args []string
}
cliCommandWithoutTerminalOutputReturns struct {
result1 []string
result2 error
}
CliCommandStub func(args ...string) ([]string, error)
cliCommandMutex sync.RWMutex
cliCommandArgsForCall []struct {
args []string
}
cliCommandReturns struct {
result1 []string
result2 error
}
GetCurrentOrgStub func() (plugin_models.Organization, error)
getCurrentOrgMutex sync.RWMutex
getCurrentOrgArgsForCall []struct{}
getCurrentOrgReturns struct {
result1 plugin_models.Organization
result2 error
}
GetCurrentSpaceStub func() (plugin_models.Space, error)
getCurrentSpaceMutex sync.RWMutex
getCurrentSpaceArgsForCall []struct{}
getCurrentSpaceReturns struct {
result1 plugin_models.Space
result2 error
}
UsernameStub func() (string, error)
usernameMutex sync.RWMutex
usernameArgsForCall []struct{}
usernameReturns struct {
result1 string
result2 error
}
UserGuidStub func() (string, error)
userGuidMutex sync.RWMutex
userGuidArgsForCall []struct{}
userGuidReturns struct {
result1 string
result2 error
}
UserEmailStub func() (string, error)
userEmailMutex sync.RWMutex
userEmailArgsForCall []struct{}
userEmailReturns struct {
result1 string
result2 error
}
IsLoggedInStub func() (bool, error)
isLoggedInMutex sync.RWMutex
isLoggedInArgsForCall []struct{}
isLoggedInReturns struct {
result1 bool
result2 error
}
IsSSLDisabledStub func() (bool, error)
isSSLDisabledMutex sync.RWMutex
isSSLDisabledArgsForCall []struct{}
isSSLDisabledReturns struct {
result1 bool
result2 error
}
HasOrganizationStub func() (bool, error)
hasOrganizationMutex sync.RWMutex
hasOrganizationArgsForCall []struct{}
hasOrganizationReturns struct {
result1 bool
result2 error
}
HasSpaceStub func() (bool, error)
hasSpaceMutex sync.RWMutex
hasSpaceArgsForCall []struct{}
hasSpaceReturns struct {
result1 bool
result2 error
}
ApiEndpointStub func() (string, error)
apiEndpointMutex sync.RWMutex
apiEndpointArgsForCall []struct{}
apiEndpointReturns struct {
result1 string
result2 error
}
ApiVersionStub func() (string, error)
apiVersionMutex sync.RWMutex
apiVersionArgsForCall []struct{}
apiVersionReturns struct {
result1 string
result2 error
}
HasAPIEndpointStub func() (bool, error)
hasAPIEndpointMutex sync.RWMutex
hasAPIEndpointArgsForCall []struct{}
hasAPIEndpointReturns struct {
result1 bool
result2 error
}
LoggregatorEndpointStub func() (string, error)
loggregatorEndpointMutex sync.RWMutex
loggregatorEndpointArgsForCall []struct{}
loggregatorEndpointReturns struct {
result1 string
result2 error
}
DopplerEndpointStub func() (string, error)
dopplerEndpointMutex sync.RWMutex
dopplerEndpointArgsForCall []struct{}
dopplerEndpointReturns struct {
result1 string
result2 error
}
AccessTokenStub func() (string, error)
accessTokenMutex sync.RWMutex
accessTokenArgsForCall []struct{}
accessTokenReturns struct {
result1 string
result2 error
}
}
func (fake *FakeCliConnection) CliCommandWithoutTerminalOutput(args ...string) ([]string, error) {
fake.cliCommandWithoutTerminalOutputMutex.Lock()
fake.cliCommandWithoutTerminalOutputArgsForCall = append(fake.cliCommandWithoutTerminalOutputArgsForCall, struct {
args []string
}{args})
fake.cliCommandWithoutTerminalOutputMutex.Unlock()
if fake.CliCommandWithoutTerminalOutputStub != nil {
return fake.CliCommandWithoutTerminalOutputStub(args...)
} else {
return fake.cliCommandWithoutTerminalOutputReturns.result1, fake.cliCommandWithoutTerminalOutputReturns.result2
}
}
func (fake *FakeCliConnection) CliCommandWithoutTerminalOutputCallCount() int {
fake.cliCommandWithoutTerminalOutputMutex.RLock()
defer fake.cliCommandWithoutTerminalOutputMutex.RUnlock()
return len(fake.cliCommandWithoutTerminalOutputArgsForCall)
}
func (fake *FakeCliConnection) CliCommandWithoutTerminalOutputArgsForCall(i int) []string {
fake.cliCommandWithoutTerminalOutputMutex.RLock()
defer fake.cliCommandWithoutTerminalOutputMutex.RUnlock()
return fake.cliCommandWithoutTerminalOutputArgsForCall[i].args
}
func (fake *FakeCliConnection) CliCommandWithoutTerminalOutputReturns(result1 []string, result2 error) {
fake.CliCommandWithoutTerminalOutputStub = nil
fake.cliCommandWithoutTerminalOutputReturns = struct {
result1 []string
result2 error
}{result1, result2}
}
func (fake *FakeCliConnection) CliCommand(args ...string) ([]string, error) {
fake.cliCommandMutex.Lock()
fake.cliCommandArgsForCall = append(fake.cliCommandArgsForCall, struct {
args []string
}{args})
fake.cliCommandMutex.Unlock()
if fake.CliCommandStub != nil {
return fake.CliCommandStub(args...)
} else {
return fake.cliCommandReturns.result1, fake.cliCommandReturns.result2
}
}
func (fake *FakeCliConnection) CliCommandCallCount() int {
fake.cliCommandMutex.RLock()
defer fake.cliCommandMutex.RUnlock()
return len(fake.cliCommandArgsForCall)
}
func (fake *FakeCliConnection) CliCommandArgsForCall(i int) []string {
fake.cliCommandMutex.RLock()
defer fake.cliCommandMutex.RUnlock()
return fake.cliCommandArgsForCall[i].args
}
func (fake *FakeCliConnection) CliCommandReturns(result1 []string, result2 error) {
fake.CliCommandStub = nil
fake.cliCommandReturns = struct {
result1 []string
result2 error
}{result1, result2}
}
func (fake *FakeCliConnection) GetCurrentOrg() (plugin_models.Organization, error) {
fake.getCurrentOrgMutex.Lock()
fake.getCurrentOrgArgsForCall = append(fake.getCurrentOrgArgsForCall, struct{}{})
fake.getCurrentOrgMutex.Unlock()
if fake.GetCurrentOrgStub != nil {
return fake.GetCurrentOrgStub()
} else {
return fake.getCurrentOrgReturns.result1, fake.getCurrentOrgReturns.result2
}
}
func (fake *FakeCliConnection) GetCurrentOrgCallCount() int {
fake.getCurrentOrgMutex.RLock()
defer fake.getCurrentOrgMutex.RUnlock()
return len(fake.getCurrentOrgArgsForCall)
}
func (fake *FakeCliConnection) GetCurrentOrgReturns(result1 plugin_models.Organization, result2 error) {
fake.GetCurrentOrgStub = nil
fake.getCurrentOrgReturns = struct {
result1 plugin_models.Organization
result2 error
}{result1, result2}
}
func (fake *FakeCliConnection) GetCurrentSpace() (plugin_models.Space, error) {
fake.getCurrentSpaceMutex.Lock()
fake.getCurrentSpaceArgsForCall = append(fake.getCurrentSpaceArgsForCall, struct{}{})
fake.getCurrentSpaceMutex.Unlock()
if fake.GetCurrentSpaceStub != nil {
return fake.GetCurrentSpaceStub()
} else {
return fake.getCurrentSpaceReturns.result1, fake.getCurrentSpaceReturns.result2
}
}
func (fake *FakeCliConnection) GetCurrentSpaceCallCount() int {
fake.getCurrentSpaceMutex.RLock()
defer fake.getCurrentSpaceMutex.RUnlock()
return len(fake.getCurrentSpaceArgsForCall)
}
func (fake *FakeCliConnection) GetCurrentSpaceReturns(result1 plugin_models.Space, result2 error) {
fake.GetCurrentSpaceStub = nil
fake.getCurrentSpaceReturns = struct {
result1 plugin_models.Space
result2 error
}{result1, result2}
}
func (fake *FakeCliConnection) Username() (string, error) {
fake.usernameMutex.Lock()
fake.usernameArgsForCall = append(fake.usernameArgsForCall, struct{}{})
fake.usernameMutex.Unlock()
if fake.UsernameStub != nil {
return fake.UsernameStub()
} else {
return fake.usernameReturns.result1, fake.usernameReturns.result2
}
}
func (fake *FakeCliConnection) UsernameCallCount() int {
fake.usernameMutex.RLock()
defer fake.usernameMutex.RUnlock()
return len(fake.usernameArgsForCall)
}
func (fake *FakeCliConnection) UsernameReturns(result1 string, result2 error) {
fake.UsernameStub = nil
fake.usernameReturns = struct {
result1 string
result2 error
}{result1, result2}
}
func (fake *FakeCliConnection) UserGuid() (string, error) {
fake.userGuidMutex.Lock()
fake.userGuidArgsForCall = append(fake.userGuidArgsForCall, struct{}{})
fake.userGuidMutex.Unlock()
if fake.UserGuidStub != nil {
return fake.UserGuidStub()
} else {
return fake.userGuidReturns.result1, fake.userGuidReturns.result2
}
}
func (fake *FakeCliConnection) UserGuidCallCount() int {
fake.userGuidMutex.RLock()
defer fake.userGuidMutex.RUnlock()
return len(fake.userGuidArgsForCall)
}
func (fake *FakeCliConnection) UserGuidReturns(result1 string, result2 error) {
fake.UserGuidStub = nil
fake.userGuidReturns = struct {
result1 string
result2 error
}{result1, result2}
}
func (fake *FakeCliConnection) UserEmail() (string, error) {
fake.userEmailMutex.Lock()
fake.userEmailArgsForCall = append(fake.userEmailArgsForCall, struct{}{})
fake.userEmailMutex.Unlock()
if fake.UserEmailStub != nil {
return fake.UserEmailStub()
} else {
return fake.userEmailReturns.result1, fake.userEmailReturns.result2
}
}
func (fake *FakeCliConnection) UserEmailCallCount() int {
fake.userEmailMutex.RLock()
defer fake.userEmailMutex.RUnlock()
return len(fake.userEmailArgsForCall)
}
func (fake *FakeCliConnection) UserEmailReturns(result1 string, result2 error) {
fake.UserEmailStub = nil
fake.userEmailReturns = struct {
result1 string
result2 error
}{result1, result2}
}
func (fake *FakeCliConnection) IsLoggedIn() (bool, error) {
fake.isLoggedInMutex.Lock()
fake.isLoggedInArgsForCall = append(fake.isLoggedInArgsForCall, struct{}{})
fake.isLoggedInMutex.Unlock()
if fake.IsLoggedInStub != nil {
return fake.IsLoggedInStub()
} else {
return fake.isLoggedInReturns.result1, fake.isLoggedInReturns.result2
}
}
func (fake *FakeCliConnection) IsLoggedInCallCount() int {
fake.isLoggedInMutex.RLock()
defer fake.isLoggedInMutex.RUnlock()
return len(fake.isLoggedInArgsForCall)
}
func (fake *FakeCliConnection) IsLoggedInReturns(result1 bool, result2 error) {
fake.IsLoggedInStub = nil
fake.isLoggedInReturns = struct {
result1 bool
result2 error
}{result1, result2}
}
func (fake *FakeCliConnection) IsSSLDisabled() (bool, error) {
fake.isSSLDisabledMutex.Lock()
fake.isSSLDisabledArgsForCall = append(fake.isSSLDisabledArgsForCall, struct{}{})
fake.isSSLDisabledMutex.Unlock()
if fake.IsSSLDisabledStub != nil {
return fake.IsSSLDisabledStub()
} else {
return fake.isSSLDisabledReturns.result1, fake.isSSLDisabledReturns.result2
}
}
func (fake *FakeCliConnection) IsSSLDisabledCallCount() int {
fake.isSSLDisabledMutex.RLock()
defer fake.isSSLDisabledMutex.RUnlock()
return len(fake.isSSLDisabledArgsForCall)
}
func (fake *FakeCliConnection) IsSSLDisabledReturns(result1 bool, result2 error) {
fake.IsSSLDisabledStub = nil
fake.isSSLDisabledReturns = struct {
result1 bool
result2 error
}{result1, result2}
}
func (fake *FakeCliConnection) HasOrganization() (bool, error) {
fake.hasOrganizationMutex.Lock()
fake.hasOrganizationArgsForCall = append(fake.hasOrganizationArgsForCall, struct{}{})
fake.hasOrganizationMutex.Unlock()
if fake.HasOrganizationStub != nil {
return fake.HasOrganizationStub()
} else {
return fake.hasOrganizationReturns.result1, fake.hasOrganizationReturns.result2
}
}
func (fake *FakeCliConnection) HasOrganizationCallCount() int {
fake.hasOrganizationMutex.RLock()
defer fake.hasOrganizationMutex.RUnlock()
return len(fake.hasOrganizationArgsForCall)
}
func (fake *FakeCliConnection) HasOrganizationReturns(result1 bool, result2 error) {
fake.HasOrganizationStub = nil
fake.hasOrganizationReturns = struct {
result1 bool
result2 error
}{result1, result2}
}
func (fake *FakeCliConnection) HasSpace() (bool, error) {
fake.hasSpaceMutex.Lock()
fake.hasSpaceArgsForCall = append(fake.hasSpaceArgsForCall, struct{}{})
fake.hasSpaceMutex.Unlock()
if fake.HasSpaceStub != nil {
return fake.HasSpaceStub()
} else {
return fake.hasSpaceReturns.result1, fake.hasSpaceReturns.result2
}
}
func (fake *FakeCliConnection) HasSpaceCallCount() int {
fake.hasSpaceMutex.RLock()
defer fake.hasSpaceMutex.RUnlock()
return len(fake.hasSpaceArgsForCall)
}
func (fake *FakeCliConnection) HasSpaceReturns(result1 bool, result2 error) {
fake.HasSpaceStub = nil
fake.hasSpaceReturns = struct {
result1 bool
result2 error
}{result1, result2}
}
func (fake *FakeCliConnection) ApiEndpoint() (string, error) {
fake.apiEndpointMutex.Lock()
fake.apiEndpointArgsForCall = append(fake.apiEndpointArgsForCall, struct{}{})
fake.apiEndpointMutex.Unlock()
if fake.ApiEndpointStub != nil {
return fake.ApiEndpointStub()
} else {
return fake.apiEndpointReturns.result1, fake.apiEndpointReturns.result2
}
}
func (fake *FakeCliConnection) ApiEndpointCallCount() int {
fake.apiEndpointMutex.RLock()
defer fake.apiEndpointMutex.RUnlock()
return len(fake.apiEndpointArgsForCall)
}
func (fake *FakeCliConnection) ApiEndpointReturns(result1 string, result2 error) {
fake.ApiEndpointStub = nil
fake.apiEndpointReturns = struct {
result1 string
result2 error
}{result1, result2}
}
func (fake *FakeCliConnection) ApiVersion() (string, error) {
fake.apiVersionMutex.Lock()
fake.apiVersionArgsForCall = append(fake.apiVersionArgsForCall, struct{}{})
fake.apiVersionMutex.Unlock()
if fake.ApiVersionStub != nil {
return fake.ApiVersionStub()
} else {
return fake.apiVersionReturns.result1, fake.apiVersionReturns.result2
}
}
func (fake *FakeCliConnection) ApiVersionCallCount() int {
fake.apiVersionMutex.RLock()
defer fake.apiVersionMutex.RUnlock()
return len(fake.apiVersionArgsForCall)
}
func (fake *FakeCliConnection) ApiVersionReturns(result1 string, result2 error) {
fake.ApiVersionStub = nil
fake.apiVersionReturns = struct {
result1 string
result2 error
}{result1, result2}
}
func (fake *FakeCliConnection) HasAPIEndpoint() (bool, error) {
fake.hasAPIEndpointMutex.Lock()
fake.hasAPIEndpointArgsForCall = append(fake.hasAPIEndpointArgsForCall, struct{}{})
fake.hasAPIEndpointMutex.Unlock()
if fake.HasAPIEndpointStub != nil {
return fake.HasAPIEndpointStub()
} else {
return fake.hasAPIEndpointReturns.result1, fake.hasAPIEndpointReturns.result2
}
}
func (fake *FakeCliConnection) HasAPIEndpointCallCount() int {
fake.hasAPIEndpointMutex.RLock()
defer fake.hasAPIEndpointMutex.RUnlock()
return len(fake.hasAPIEndpointArgsForCall)
}
func (fake *FakeCliConnection) HasAPIEndpointReturns(result1 bool, result2 error) {
fake.HasAPIEndpointStub = nil
fake.hasAPIEndpointReturns = struct {
result1 bool
result2 error
}{result1, result2}
}
func (fake *FakeCliConnection) LoggregatorEndpoint() (string, error) {
fake.loggregatorEndpointMutex.Lock()
fake.loggregatorEndpointArgsForCall = append(fake.loggregatorEndpointArgsForCall, struct{}{})
fake.loggregatorEndpointMutex.Unlock()
if fake.LoggregatorEndpointStub != nil {
return fake.LoggregatorEndpointStub()
} else {
return fake.loggregatorEndpointReturns.result1, fake.loggregatorEndpointReturns.result2
}
}
func (fake *FakeCliConnection) LoggregatorEndpointCallCount() int {
fake.loggregatorEndpointMutex.RLock()
defer fake.loggregatorEndpointMutex.RUnlock()
return len(fake.loggregatorEndpointArgsForCall)
}
func (fake *FakeCliConnection) LoggregatorEndpointReturns(result1 string, result2 error) {
fake.LoggregatorEndpointStub = nil
fake.loggregatorEndpointReturns = struct {
result1 string
result2 error
}{result1, result2}
}
func (fake *FakeCliConnection) DopplerEndpoint() (string, error) {
fake.dopplerEndpointMutex.Lock()
fake.dopplerEndpointArgsForCall = append(fake.dopplerEndpointArgsForCall, struct{}{})
fake.dopplerEndpointMutex.Unlock()
if fake.DopplerEndpointStub != nil {
return fake.DopplerEndpointStub()
} else {
return fake.dopplerEndpointReturns.result1, fake.dopplerEndpointReturns.result2
}
}
func (fake *FakeCliConnection) DopplerEndpointCallCount() int {
fake.dopplerEndpointMutex.RLock()
defer fake.dopplerEndpointMutex.RUnlock()
return len(fake.dopplerEndpointArgsForCall)
}
func (fake *FakeCliConnection) DopplerEndpointReturns(result1 string, result2 error) {
fake.DopplerEndpointStub = nil
fake.dopplerEndpointReturns = struct {
result1 string
result2 error
}{result1, result2}
}
func (fake *FakeCliConnection) AccessToken() (string, error) {
fake.accessTokenMutex.Lock()
fake.accessTokenArgsForCall = append(fake.accessTokenArgsForCall, struct{}{})
fake.accessTokenMutex.Unlock()
if fake.AccessTokenStub != nil {
return fake.AccessTokenStub()
} else {
return fake.accessTokenReturns.result1, fake.accessTokenReturns.result2
}
}
func (fake *FakeCliConnection) AccessTokenCallCount() int {
fake.accessTokenMutex.RLock()
defer fake.accessTokenMutex.RUnlock()
return len(fake.accessTokenArgsForCall)
}
func (fake *FakeCliConnection) AccessTokenReturns(result1 string, result2 error) {
fake.AccessTokenStub = nil
fake.accessTokenReturns = struct {
result1 string
result2 error
}{result1, result2}
}
var _ plugin.CliConnection = new(FakeCliConnection)
|
lovely3x/smalidea
|
src/main/java/org/jf/smalidea/psi/impl/SmaliClassTypeElement.java
|
/*
* Copyright 2014, Google 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 Google Inc. 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.
*/
package org.jf.smalidea.psi.impl;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.*;
import com.intellij.psi.impl.source.codeStyle.CodeEditUtil;
import com.intellij.psi.infos.CandidateInfo;
import com.intellij.psi.scope.PsiScopeProcessor;
import com.intellij.util.IncorrectOperationException;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jf.smalidea.psi.SmaliCompositeElementFactory;
import org.jf.smalidea.psi.SmaliElementTypes;
import org.jf.smalidea.psi.leaf.SmaliClassDescriptor;
import org.jf.smalidea.util.NameUtils;
public class SmaliClassTypeElement extends SmaliTypeElement implements PsiJavaCodeReferenceElement {
public static final SmaliClassTypeElement[] EMPTY_ARRAY = new SmaliClassTypeElement[0];
public static final SmaliCompositeElementFactory FACTORY = new SmaliCompositeElementFactory() {
@Override public SmaliCompositeElement createElement() {
return new SmaliClassTypeElement();
}
};
@Nullable private SmaliClassType classType = null;
public SmaliClassTypeElement() {
super(SmaliElementTypes.CLASS_TYPE);
}
@NotNull @Override public SmaliClassType getType() {
if (classType == null) {
classType = new SmaliClassType(this);
}
return classType;
}
@Override public String getName() {
return NameUtils.shortNameFromQualifiedName(getCanonicalText());
}
@Nullable @Override public SmaliClassTypeElement getInnermostComponentReferenceElement() {
return this;
}
@Override public PsiElement getElement() {
return this;
}
@Override public PsiReference getReference() {
return this;
}
@Override public TextRange getRangeInElement() {
return new TextRange(0, getTextLength());
}
@Nullable @Override public PsiClass resolve() {
return NameUtils.resolveSmaliType(this, getText());
}
@NotNull @Override public String getCanonicalText() {
return getQualifiedName();
}
@Override public PsiElement handleElementRename(String newElementName) throws IncorrectOperationException {
SmaliClassDescriptor descriptor = getReferenceNameElement();
if (descriptor == null) {
throw new IncorrectOperationException();
}
SmaliClassDescriptor newDescriptor = new SmaliClassDescriptor(NameUtils.javaToSmaliType(newElementName));
CodeEditUtil.setNodeGenerated(newDescriptor, true);
this.replaceChild(descriptor, newDescriptor);
return this;
}
@Override public PsiElement bindToElement(@NotNull PsiElement element) throws IncorrectOperationException {
if (element instanceof PsiClass) {
handleElementRename(((PsiClass) element).getQualifiedName());
return this;
}
throw new IncorrectOperationException();
}
@Override public boolean isReferenceTo(PsiElement element) {
if (!(element instanceof PsiClass)) {
return false;
}
return element.getManager().areElementsEquivalent(element, resolve());
}
@NotNull @Override public Object[] getVariants() {
// TODO: implement this?
return new Object[0];
}
@Override public boolean isSoft() {
return false;
}
// ***************************************************************************
// Below are the PsiJavaCodeReferenceElement-specific methods
@Override public void processVariants(@NotNull PsiScopeProcessor processor) {
// TODO: maybe just do nothing?
throw new UnsupportedOperationException();
}
@Nullable @Override public SmaliClassDescriptor getReferenceNameElement() {
return findChildByClass(SmaliClassDescriptor.class);
}
@Nullable @Override public PsiReferenceParameterList getParameterList() {
// TODO: (generics) implement this
return null;
}
@NotNull @Override public PsiType[] getTypeParameters() {
// TODO: (generics) implement this
return new PsiType[0];
}
@Override public boolean isQualified() {
// TODO: should this return false for classes in the top level package?
return true;
}
@Override public String getQualifiedName() {
PsiClass psiClass = resolve();
if (psiClass != null) {
return psiClass.getQualifiedName();
}
return NameUtils.smaliToJavaType(getText());
}
@NotNull @Override public JavaResolveResult advancedResolve(boolean incompleteCode) {
PsiClass element = resolve();
if (element == null) {
return JavaResolveResult.EMPTY;
}
return new CandidateInfo(element, PsiSubstitutor.EMPTY);
}
@NotNull @Override public JavaResolveResult[] multiResolve(boolean incompleteCode) {
PsiClass element = resolve();
if (element == null) {
return JavaResolveResult.EMPTY_ARRAY;
}
return new CandidateInfo[] { new CandidateInfo(element, PsiSubstitutor.EMPTY) };
}
@Nullable @Override public PsiElement getQualifier() {
return null;
}
@Nullable @Override public String getReferenceName() {
return getName();
}
}
|
woollybogger/node-mysql-plus
|
test/integration/MySQLPlus.test.js
|
<filename>test/integration/MySQLPlus.test.js
'use strict';
const CallbackManager = require('es6-callback-manager');
const MySQLPlus = require('../../lib/MySQLPlus');
const config = require('../config');
const sinon = require('sinon');
const {ColTypes, KeyTypes} = MySQLPlus;
describe('MySQLPlus', function() {
this.timeout(10000);
const bigTableName = 'big_table';
const bigTableSchema = {
columns: {
id: ColTypes.bigint().unsigned().notNull().primaryKey().autoIncrement(),
name: ColTypes.varchar(63),
email: ColTypes.varchar(255).notNull().unique(),
password: ColTypes.char(40).notNull(),
letter: ColTypes.char(1).default('a').index(),
created: ColTypes.datetime().defaultCurrentTimestamp(),
updated: ColTypes.datetime().onUpdateCurrentTimestamp(),
weirdtext: ColTypes.tinytext().charset('ascii').collate('ascii_bin'),
zfill: ColTypes.smallint().zerofill(),
myenum: ColTypes.enum('A', 'B', 'C').default('A'),
myset: ColTypes.set('ONE', 'TWO'),
jdoc: ColTypes.json(),
location: ColTypes.point().notNull().spatialIndex(),
line: ColTypes.linestring(),
description: ColTypes.text().fulltextIndex(),
},
keys: [
KeyTypes.uniqueIndex('name', 'letter'),
KeyTypes.uniqueIndex('created'),
],
engine: 'InnoDB',
};
const bigTableExpectedSQL =
'CREATE TABLE `big_table` (\n' +
' `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,\n' +
' `name` varchar(63) DEFAULT NULL,\n' +
' `email` varchar(255) NOT NULL,\n' +
' `password` char(40) NOT NULL,\n' +
' `letter` char(1) DEFAULT \'a\',\n' +
' `created` datetime DEFAULT CURRENT_TIMESTAMP,\n' +
' `updated` datetime DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP,\n' +
' `weirdtext` tinytext CHARACTER SET ascii COLLATE ascii_bin,\n' +
' `zfill` smallint(5) unsigned zerofill DEFAULT NULL,\n' +
' `myenum` enum(\'A\',\'B\',\'C\') DEFAULT \'A\',\n' +
' `myset` set(\'ONE\',\'TWO\') DEFAULT NULL,\n' +
' `jdoc` json DEFAULT NULL,\n' +
' `location` point NOT NULL,\n' +
' `line` linestring DEFAULT NULL,\n' +
' `description` text,\n' +
' PRIMARY KEY (`id`),\n' +
' UNIQUE KEY `uniq_email` (`email`),\n' +
' UNIQUE KEY `uniq_name_letter` (`name`,`letter`),\n' +
' UNIQUE KEY `uniq_created` (`created`),\n' +
' KEY `idx_letter` (`letter`),\n' +
' SPATIAL KEY `sptl_location` (`location`),\n' +
' FULLTEXT KEY `fltxt_description` (`description`)\n' +
') ENGINE=InnoDB DEFAULT CHARSET=utf8';
const autoIncTableName = 'auto_inc_table';
const autoIncTableSchema = {
columns: {
id: ColTypes.bigint().unsigned().primaryKey().autoIncrement(),
number: ColTypes.mediumint(),
},
keys: [
KeyTypes.index('number'),
],
autoIncrement: 5000000000,
};
const autoIncTableExpectedSQL =
'CREATE TABLE `auto_inc_table` (\n' +
' `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,\n' +
' `number` mediumint(9) DEFAULT NULL,\n' +
' PRIMARY KEY (`id`),\n' +
' KEY `idx_number` (`number`)\n' +
') ENGINE=InnoDB AUTO_INCREMENT=5000000000 DEFAULT CHARSET=utf8';
const autoIncTableMigratedSchema = {
columns: {
id: ColTypes.bigint().unsigned().primaryKey().autoIncrement(),
number: ColTypes.mediumint(),
},
keys: [
KeyTypes.index('number'),
],
autoIncrement: 6000000000,
};
const autoIncTableMigratedExpectedSQL =
'CREATE TABLE `auto_inc_table` (\n' +
' `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,\n' +
' `number` mediumint(9) DEFAULT NULL,\n' +
' PRIMARY KEY (`id`),\n' +
' KEY `idx_number` (`number`)\n' +
') ENGINE=InnoDB AUTO_INCREMENT=6000000000 DEFAULT CHARSET=utf8';
const pivotTableName = 'pivot_table';
const pivotTableSchema = {
columns: {
autoID: ColTypes.bigint().unsigned(),
autoNumber: ColTypes.mediumint(),
bigID: ColTypes.bigint().unsigned().index(),
},
primaryKey: ['autoID', 'autoNumber'],
keys: [
KeyTypes.index('autoNumber'),
KeyTypes.foreignKey('autoID').references('auto_inc_table', 'id'),
KeyTypes.foreignKey('autoNumber').references('auto_inc_table', 'number'),
KeyTypes.foreignKey('bigID').references('big_table', 'id').onDelete('CASCADE').onUpdate('SET NULL'),
],
};
const pivotTableExpectedSQL =
'CREATE TABLE `pivot_table` (\n' +
' `autoID` bigint(20) unsigned NOT NULL,\n' +
' `autoNumber` mediumint(9) NOT NULL,\n' +
' `bigID` bigint(20) unsigned DEFAULT NULL,\n' +
' PRIMARY KEY (`autoID`,`autoNumber`),\n' +
' KEY `idx_autoNumber` (`autoNumber`),\n' +
' KEY `idx_bigID` (`bigID`),\n' +
' CONSTRAINT `fk_autoID_pivot_table` FOREIGN KEY (`autoID`) REFERENCES `auto_inc_table` (`id`),\n' +
' CONSTRAINT `fk_autoNumber_pivot_table` FOREIGN KEY (`autoNumber`) REFERENCES `auto_inc_table` (`number`),\n' +
' CONSTRAINT `fk_bigID_pivot_table` FOREIGN KEY (`bigID`) REFERENCES `big_table` (`id`) ON DELETE CASCADE ON UPDATE SET NULL\n' +
') ENGINE=InnoDB DEFAULT CHARSET=utf8';
const columnsTableName = 'columns_table';
const columnsTableSchema = {
columns: {
id: ColTypes.int().unsigned().notNull().default(1),
uuid: ColTypes.char(44).unique(),
email: ColTypes.char(255),
fp: ColTypes.float(7, 4),
dropme: ColTypes.blob(),
renameme: ColTypes.tinyint(),
changeme: ColTypes.tinyint(),
neverchange: ColTypes.tinyint().oldName('fake_column'),
norename: ColTypes.tinyint().oldName('fake_column'),
},
keys: [
KeyTypes.index('email'),
KeyTypes.index('id', 'email'),
],
};
const columnsTableExpectedSQL =
'CREATE TABLE `columns_table` (\n' +
' `id` int(10) unsigned NOT NULL DEFAULT \'1\',\n' +
' `uuid` char(44) DEFAULT NULL,\n' +
' `email` char(255) DEFAULT NULL,\n' +
' `fp` float(7,4) DEFAULT NULL,\n' +
' `dropme` blob,\n' +
' `renameme` tinyint(4) DEFAULT NULL,\n' +
' `changeme` tinyint(4) DEFAULT NULL,\n' +
' `neverchange` tinyint(4) DEFAULT NULL,\n' +
' `norename` tinyint(4) DEFAULT NULL,\n' +
' UNIQUE KEY `uniq_uuid` (`uuid`),\n' +
' KEY `idx_email` (`email`),\n' +
' KEY `idx_id_email` (`id`,`email`)\n' +
') ENGINE=InnoDB DEFAULT CHARSET=utf8';
const columnsTableMigratedSchema = {
columns: {
id: ColTypes.bigint(5).unsigned().notNull().primaryKey().default(2),
uuid: ColTypes.char(44).unique(),
email: ColTypes.varchar(255).notNull(),
fp: ColTypes.float(8, 3),
renamed: ColTypes.tinyint().oldName('renameme'),
changed: ColTypes.smallint().oldName('changeme'),
neverchange: ColTypes.tinyint().oldName('fake_column'),
norename: ColTypes.smallint().oldName('fake_column'),
added: ColTypes.text(),
},
keys: [
KeyTypes.uniqueIndex('email'),
KeyTypes.index('id', 'email'),
],
};
const columnsTableMigratedExpectedSQL =
'CREATE TABLE `columns_table` (\n' +
' `id` bigint(5) unsigned NOT NULL DEFAULT \'2\',\n' +
' `uuid` char(44) DEFAULT NULL,\n' +
' `email` varchar(255) NOT NULL,\n' +
' `fp` float(8,3) DEFAULT NULL,\n' +
' `renamed` tinyint(4) DEFAULT NULL,\n' +
' `changed` smallint(6) DEFAULT NULL,\n' +
' `neverchange` tinyint(4) DEFAULT NULL,\n' +
' `norename` smallint(6) DEFAULT NULL,\n' +
' `added` text,\n' +
' PRIMARY KEY (`id`),\n' +
' UNIQUE KEY `uniq_email` (`email`),\n' +
' UNIQUE KEY `uniq_uuid` (`uuid`),\n' +
' KEY `idx_id_email` (`id`,`email`)\n' +
') ENGINE=InnoDB DEFAULT CHARSET=utf8';
const primaryKeyTableName = 'pk_table';
const primaryKeyTableSchema = {
columns: {
a: ColTypes.int(),
b: ColTypes.char(1),
},
primaryKey: ['a', 'b'],
};
const primaryKeyTableExpectedSQL =
'CREATE TABLE `pk_table` (\n' +
' `a` int(11) NOT NULL,\n' +
' `b` char(1) NOT NULL,\n' +
' PRIMARY KEY (`a`,`b`)\n' +
') ENGINE=InnoDB DEFAULT CHARSET=utf8';
const primaryKeyTableMigratedSchema = {
columns: {
a: ColTypes.int(),
b: ColTypes.char(1),
},
primaryKey: 'a',
};
const primaryKeyTableMigratedExpectedSQL =
'CREATE TABLE `pk_table` (\n' +
' `a` int(11) NOT NULL,\n' +
' `b` char(1) DEFAULT NULL,\n' +
' PRIMARY KEY (`a`)\n' +
') ENGINE=InnoDB DEFAULT CHARSET=utf8';
const uniqueKeysTableName = 'unique_table';
const uniqueKeysTableSchema = {
columns: {
a: ColTypes.int(),
b: ColTypes.bigint(),
c: ColTypes.char(1),
},
keys: [
KeyTypes.uniqueIndex('a', 'b'),
KeyTypes.uniqueIndex('c'),
],
};
const uniqueKeysTableExpectedSQL =
'CREATE TABLE `unique_table` (\n' +
' `a` int(11) DEFAULT NULL,\n' +
' `b` bigint(20) DEFAULT NULL,\n' +
' `c` char(1) DEFAULT NULL,\n' +
' UNIQUE KEY `uniq_a_b` (`a`,`b`),\n' +
' UNIQUE KEY `uniq_c` (`c`)\n' +
') ENGINE=InnoDB DEFAULT CHARSET=utf8';
const uniqueKeysTableMigragedSchema = {
columns: {
a: ColTypes.int(),
b: ColTypes.bigint(),
c: ColTypes.char(1),
},
keys: [
KeyTypes.uniqueIndex('a', 'c'),
KeyTypes.uniqueIndex('b'),
],
};
const uniqueKeysTableMigratedExpectedSQL =
'CREATE TABLE `unique_table` (\n' +
' `a` int(11) DEFAULT NULL,\n' +
' `b` bigint(20) DEFAULT NULL,\n' +
' `c` char(1) DEFAULT NULL,\n' +
' UNIQUE KEY `uniq_a_c` (`a`,`c`),\n' +
' UNIQUE KEY `uniq_b` (`b`)\n' +
') ENGINE=InnoDB DEFAULT CHARSET=utf8';
const indexesTableName = 'indexes_table';
const indexesTableSchema = {
columns: {
a: ColTypes.int(),
b: ColTypes.bigint(),
c: ColTypes.char(1),
},
keys: [
KeyTypes.index('a', 'b'),
KeyTypes.index('c'),
],
};
const indexesTableExpectedSQL =
'CREATE TABLE `indexes_table` (\n' +
' `a` int(11) DEFAULT NULL,\n' +
' `b` bigint(20) DEFAULT NULL,\n' +
' `c` char(1) DEFAULT NULL,\n' +
' KEY `idx_a_b` (`a`,`b`),\n' +
' KEY `idx_c` (`c`)\n' +
') ENGINE=InnoDB DEFAULT CHARSET=utf8';
const indexesTableMigragedSchema = {
columns: {
a: ColTypes.int(),
b: ColTypes.bigint(),
c: ColTypes.char(1),
},
keys: [
KeyTypes.index('a', 'c'),
KeyTypes.index('b'),
],
};
const indexesTableMigratedExpectedSQL =
'CREATE TABLE `indexes_table` (\n' +
' `a` int(11) DEFAULT NULL,\n' +
' `b` bigint(20) DEFAULT NULL,\n' +
' `c` char(1) DEFAULT NULL,\n' +
' KEY `idx_a_c` (`a`,`c`),\n' +
' KEY `idx_b` (`b`)\n' +
') ENGINE=InnoDB DEFAULT CHARSET=utf8';
const spatialIndexesTableName = 'spatial_table';
const spatialIndexesTableSchema = {
columns: {
a: ColTypes.geometry().notNull(),
b: ColTypes.point().notNull(),
c: ColTypes.multipolygon().notNull(),
},
keys: [
KeyTypes.spatialIndex('a'),
KeyTypes.spatialIndex('b'),
],
};
const spatialIndexesTableExpectedSQL =
'CREATE TABLE `spatial_table` (\n' +
' `a` geometry NOT NULL,\n' +
' `b` point NOT NULL,\n' +
' `c` multipolygon NOT NULL,\n' +
' SPATIAL KEY `sptl_a` (`a`),\n' +
' SPATIAL KEY `sptl_b` (`b`)\n' +
') ENGINE=InnoDB DEFAULT CHARSET=utf8';
const spatialIndexesTableMigragedSchema = {
columns: {
a: ColTypes.geometry().notNull(),
b: ColTypes.point().notNull(),
c: ColTypes.multipolygon().notNull(),
},
keys: [
KeyTypes.spatialIndex('a'),
KeyTypes.spatialIndex('c'),
],
};
const spatialIndexesTableMigratedExpectedSQL =
'CREATE TABLE `spatial_table` (\n' +
' `a` geometry NOT NULL,\n' +
' `b` point NOT NULL,\n' +
' `c` multipolygon NOT NULL,\n' +
' SPATIAL KEY `sptl_a` (`a`),\n' +
' SPATIAL KEY `sptl_c` (`c`)\n' +
') ENGINE=InnoDB DEFAULT CHARSET=utf8';
const fulltextIndexesTableName = 'fulltext_table';
const fulltextIndexesTableSchema = {
columns: {
a: ColTypes.char(32).notNull(),
b: ColTypes.varchar(255).notNull(),
c: ColTypes.text().notNull(),
},
keys: [
KeyTypes.fulltextIndex('a'),
KeyTypes.fulltextIndex('b'),
],
};
const fulltextIndexesTableExpectedSQL =
'CREATE TABLE `fulltext_table` (\n' +
' `a` char(32) NOT NULL,\n' +
' `b` varchar(255) NOT NULL,\n' +
' `c` text NOT NULL,\n' +
' FULLTEXT KEY `fltxt_a` (`a`),\n' +
' FULLTEXT KEY `fltxt_b` (`b`)\n' +
') ENGINE=InnoDB DEFAULT CHARSET=utf8';
const fulltextIndexesTableMigragedSchema = {
columns: {
a: ColTypes.char(32).notNull(),
b: ColTypes.varchar(255).notNull(),
c: ColTypes.text().notNull(),
},
keys: [
KeyTypes.fulltextIndex('a'),
KeyTypes.fulltextIndex('c'),
],
};
const fulltextIndexesTableMigratedExpectedSQL =
'CREATE TABLE `fulltext_table` (\n' +
' `a` char(32) NOT NULL,\n' +
' `b` varchar(255) NOT NULL,\n' +
' `c` text NOT NULL,\n' +
' FULLTEXT KEY `fltxt_a` (`a`),\n' +
' FULLTEXT KEY `fltxt_c` (`c`)\n' +
') ENGINE=InnoDB DEFAULT CHARSET=utf8';
const foreignKeysTableName = 'fk_table';
const foreignKeysTableSchema = {
columns: {
a: ColTypes.bigint().unsigned(),
b: ColTypes.bigint().unsigned(),
c: ColTypes.bigint().unsigned(),
d: ColTypes.int().unsigned().notNull(),
ai: ColTypes.int(),
bi: ColTypes.bigint(),
eb: ColTypes.varchar(63),
fb: ColTypes.char(1).default('a'),
gc: ColTypes.int().unsigned().notNull(),
hc: ColTypes.char(255),
},
keys: [
KeyTypes.index('b'),
KeyTypes.index('c'),
KeyTypes.index('d'),
KeyTypes.index('ai', 'bi'),
KeyTypes.index('eb', 'fb'),
KeyTypes.index('gc', 'hc'),
KeyTypes.foreignKey('ai', 'bi').references('indexes_table', ['a', 'b']),
KeyTypes.foreignKey('b').references('big_table', ['id']),
KeyTypes.foreignKey('c').references('big_table', 'id').onDelete('CASCADE').onUpdate('NO ACTION'),
KeyTypes.foreignKey('d').references('columns_table', 'id'),
KeyTypes.foreignKey('eb').references('big_table', 'name').onDelete('NO ACTION').onUpdate('NO ACTION'),
KeyTypes.foreignKey('eb', 'fb').references('big_table', ['name', 'letter']),
KeyTypes.foreignKey('gc').references('columns_table', 'id').onDelete('RESTRICT').onUpdate('RESTRICT'),
KeyTypes.foreignKey('gc', 'hc').references('columns_table', ['id', 'email']),
],
};
const foreignKeysTableExpectedSQL =
'CREATE TABLE `fk_table` (\n' +
' `a` bigint(20) unsigned DEFAULT NULL,\n' +
' `b` bigint(20) unsigned DEFAULT NULL,\n' +
' `c` bigint(20) unsigned DEFAULT NULL,\n' +
' `d` int(10) unsigned NOT NULL,\n' +
' `ai` int(11) DEFAULT NULL,\n' +
' `bi` bigint(20) DEFAULT NULL,\n' +
' `eb` varchar(63) DEFAULT NULL,\n' +
' `fb` char(1) DEFAULT \'a\',\n' +
' `gc` int(10) unsigned NOT NULL,\n' +
' `hc` char(255) DEFAULT NULL,\n' +
' KEY `idx_b` (`b`),\n' +
' KEY `idx_c` (`c`),\n' +
' KEY `idx_d` (`d`),\n' +
' KEY `idx_ai_bi` (`ai`,`bi`),\n' +
' KEY `idx_eb_fb` (`eb`,`fb`),\n' +
' KEY `idx_gc_hc` (`gc`,`hc`),\n' +
' CONSTRAINT `fk_ai_bi_fk_table` FOREIGN KEY (`ai`, `bi`) REFERENCES `indexes_table` (`a`, `b`),\n' +
' CONSTRAINT `fk_b_fk_table` FOREIGN KEY (`b`) REFERENCES `big_table` (`id`),\n' +
' CONSTRAINT `fk_c_fk_table` FOREIGN KEY (`c`) REFERENCES `big_table` (`id`) ON DELETE CASCADE ON UPDATE NO ACTION,\n' +
' CONSTRAINT `fk_d_fk_table` FOREIGN KEY (`d`) REFERENCES `columns_table` (`id`),\n' +
' CONSTRAINT `fk_eb_fb_fk_table` FOREIGN KEY (`eb`, `fb`) REFERENCES `big_table` (`name`, `letter`),\n' +
' CONSTRAINT `fk_eb_fk_table` FOREIGN KEY (`eb`) REFERENCES `big_table` (`name`) ON DELETE NO ACTION ON UPDATE NO ACTION,\n' +
' CONSTRAINT `fk_gc_fk_table` FOREIGN KEY (`gc`) REFERENCES `columns_table` (`id`),\n' +
' CONSTRAINT `fk_gc_hc_fk_table` FOREIGN KEY (`gc`, `hc`) REFERENCES `columns_table` (`id`, `email`)\n' +
') ENGINE=InnoDB DEFAULT CHARSET=utf8';
const foreignKeysTableMigratedSchema = {
columns: {
a: ColTypes.bigint().unsigned(),
b: ColTypes.bigint().unsigned(),
c: ColTypes.bigint().unsigned(),
d: ColTypes.bigint(5).unsigned().notNull(),
ai: ColTypes.int(),
ci: ColTypes.char(1),
eb: ColTypes.varchar(63),
fb: ColTypes.char(1).default('a'),
gc: ColTypes.bigint(5).unsigned().notNull(),
hc: ColTypes.varchar(255).notNull(),
},
keys: [
KeyTypes.index('a'),
KeyTypes.index('c'),
KeyTypes.index('d'),
KeyTypes.index('ai', 'ci'),
KeyTypes.index('gc', 'hc'),
KeyTypes.uniqueIndex('eb', 'fb'),
KeyTypes.foreignKey('a').references('big_table', ['id']),
KeyTypes.foreignKey('ai', 'ci').references('indexes_table', ['a', 'c']),
KeyTypes.foreignKey('c').references('big_table', 'id').onDelete('SET NULL').onUpdate('CASCADE'),
KeyTypes.foreignKey('d').references('columns_table', 'id'),
KeyTypes.foreignKey('eb', 'fb').references('big_table', ['name', 'letter']),
KeyTypes.foreignKey('gc').references('columns_table', 'id').cascade(),
KeyTypes.foreignKey('gc', 'hc').references('columns_table', ['id', 'email']),
],
};
const foreignKeysTableMigratedExpectedSQL =
'CREATE TABLE `fk_table` (\n' +
' `a` bigint(20) unsigned DEFAULT NULL,\n' +
' `b` bigint(20) unsigned DEFAULT NULL,\n' +
' `c` bigint(20) unsigned DEFAULT NULL,\n' +
' `d` bigint(5) unsigned NOT NULL,\n' +
' `ai` int(11) DEFAULT NULL,\n' +
' `ci` char(1) DEFAULT NULL,\n' +
' `eb` varchar(63) DEFAULT NULL,\n' +
' `fb` char(1) DEFAULT \'a\',\n' +
' `gc` bigint(5) unsigned NOT NULL,\n' +
' `hc` varchar(255) NOT NULL,\n' +
' UNIQUE KEY `uniq_eb_fb` (`eb`,`fb`),\n' +
' KEY `idx_c` (`c`),\n' +
' KEY `idx_d` (`d`),\n' +
' KEY `idx_gc_hc` (`gc`,`hc`),\n' +
' KEY `idx_a` (`a`),\n' +
' KEY `idx_ai_ci` (`ai`,`ci`),\n' +
' CONSTRAINT `fk_a_fk_table` FOREIGN KEY (`a`) REFERENCES `big_table` (`id`),\n' +
' CONSTRAINT `fk_ai_ci_fk_table` FOREIGN KEY (`ai`, `ci`) REFERENCES `indexes_table` (`a`, `c`),\n' +
' CONSTRAINT `fk_c_fk_table` FOREIGN KEY (`c`) REFERENCES `big_table` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,\n' +
' CONSTRAINT `fk_d_fk_table` FOREIGN KEY (`d`) REFERENCES `columns_table` (`id`),\n' +
' CONSTRAINT `fk_eb_fb_fk_table` FOREIGN KEY (`eb`, `fb`) REFERENCES `big_table` (`name`, `letter`),\n' +
' CONSTRAINT `fk_gc_fk_table` FOREIGN KEY (`gc`) REFERENCES `columns_table` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,\n' +
' CONSTRAINT `fk_gc_hc_fk_table` FOREIGN KEY (`gc`, `hc`) REFERENCES `columns_table` (`id`, `email`)\n' +
') ENGINE=InnoDB DEFAULT CHARSET=utf8';
const optionsTableName = 'options_table';
const optionsTableSchema = {
columns: {
id: ColTypes.int(),
},
engine: 'MyISAM',
autoIncrement: 10,
charset: 'ascii',
collate: 'ascii_bin',
compression: 'zlib',
rowFormat: 'REDUNDANT',
};
const optionsTableExpectedSQL =
'CREATE TABLE `options_table` (\n' +
' `id` int(11) DEFAULT NULL\n' +
') ENGINE=MyISAM AUTO_INCREMENT=10 DEFAULT CHARSET=ascii COLLATE=ascii_bin ROW_FORMAT=REDUNDANT COMPRESSION=\'zlib\'';
const optionsTableMigratedSchema = {
columns: {
id: ColTypes.int(),
},
engine: 'InnoDB',
charset: 'latin1',
collate: 'latin1_bin',
compression: 'LZ4',
rowFormat: 'DEFAULT',
};
const optionsTableMigratedExpectedSQL =
'CREATE TABLE `options_table` (\n' +
' `id` int(11) DEFAULT NULL\n' +
') ENGINE=InnoDB DEFAULT CHARSET=latin1 COLLATE=latin1_bin COMPRESSION=\'LZ4\'';
const textTableName = 'text_table';
const textTableSchema = {
columns: {
a: ColTypes.char(1),
b: ColTypes.char(1).charset('utf8mb4'),
c: ColTypes.char(1).charset('utf8mb4').collate('utf8mb4_unicode_520_ci'),
d: ColTypes.char(1).collate('utf8mb4_unicode_520_ci'),
e: ColTypes.char(1).collate('utf8mb4_bin'),
},
charset: 'utf8mb4',
collate: 'utf8mb4_unicode_520_ci',
};
const textTableExpectedSQL =
'CREATE TABLE `text_table` (\n' +
' `a` char(1) COLLATE utf8mb4_unicode_520_ci DEFAULT NULL,\n' +
' `b` char(1) CHARACTER SET utf8mb4 DEFAULT NULL,\n' +
' `c` char(1) COLLATE utf8mb4_unicode_520_ci DEFAULT NULL,\n' +
' `d` char(1) COLLATE utf8mb4_unicode_520_ci DEFAULT NULL,\n' +
' `e` char(1) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL\n' +
') ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_520_ci';
const keyPartsTableName = 'key_parts_table';
const keyPartsTableSchema = {
columns: {
a: ColTypes.char(7).notNull(),
b: ColTypes.varchar(30),
c: ColTypes.text(),
},
primaryKey: 'a(5)',
keys: [
KeyTypes.index('b(20)'),
KeyTypes.uniqueIndex('c(42)'),
],
};
const keyPartsTableExpectedSQL =
'CREATE TABLE `key_parts_table` (\n' +
' `a` char(7) NOT NULL,\n' +
' `b` varchar(30) DEFAULT NULL,\n' +
' `c` text,\n' +
' PRIMARY KEY (`a`(5)),\n' +
' UNIQUE KEY `uniq_c` (`c`(42)),\n' +
' KEY `idx_b` (`b`(20))\n' +
') ENGINE=InnoDB DEFAULT CHARSET=utf8';
const timestampTableName = 'timestamp_table';
const timestampTableSchema = {
columns: {
a: ColTypes.timestamp().notNull(),
b: ColTypes.timestamp().notNull().defaultCurrentTimestamp(),
c: ColTypes.timestamp(),
d: ColTypes.timestamp().default(null),
e: ColTypes.timestamp().default('2017-03-25 12:46:05'),
},
};
const timestampTableExpectedSQL =
'CREATE TABLE `timestamp_table` (\n' +
' `a` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,\n' +
' `b` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,\n' +
' `c` timestamp NULL DEFAULT NULL,\n' +
' `d` timestamp NULL DEFAULT NULL,\n' +
" `e` timestamp NULL DEFAULT '2017-03-25 12:46:05'\n" +
') ENGINE=InnoDB DEFAULT CHARSET=utf8';
const synonymTableName = 'synonym_table';
const synonymTableSchema = {
columns: {
a: ColTypes.integer(),
b: ColTypes.dec(),
c: ColTypes.numeric(),
d: ColTypes.fixed(),
e: ColTypes.bool(),
f: ColTypes.boolean(),
},
};
const synonymTableExpectedSQL =
'CREATE TABLE `synonym_table` (\n' +
' `a` int(11) DEFAULT NULL,\n' +
' `b` decimal(10,0) DEFAULT NULL,\n' +
' `c` decimal(10,0) DEFAULT NULL,\n' +
' `d` decimal(10,0) DEFAULT NULL,\n' +
' `e` tinyint(1) DEFAULT NULL,\n' +
' `f` tinyint(1) DEFAULT NULL\n' +
') ENGINE=InnoDB DEFAULT CHARSET=utf8';
describe('when creating new tables', () => {
const pool = MySQLPlus.createPool(config);
before((done) => {
pool.defineTable(bigTableName, bigTableSchema);
pool.defineTable(autoIncTableName, autoIncTableSchema);
pool.defineTable(pivotTableName, pivotTableSchema);
pool.defineTable(columnsTableName, columnsTableSchema);
pool.defineTable(primaryKeyTableName, primaryKeyTableSchema);
pool.defineTable(uniqueKeysTableName, uniqueKeysTableSchema);
pool.defineTable(indexesTableName, indexesTableSchema);
pool.defineTable(spatialIndexesTableName, spatialIndexesTableSchema);
pool.defineTable(fulltextIndexesTableName, fulltextIndexesTableSchema);
pool.defineTable(foreignKeysTableName, foreignKeysTableSchema);
pool.defineTable(optionsTableName, optionsTableSchema);
pool.defineTable(textTableName, textTableSchema);
pool.defineTable(keyPartsTableName, keyPartsTableSchema);
pool.defineTable(timestampTableName, timestampTableSchema);
pool.defineTable(synonymTableName, synonymTableSchema);
pool.sync(done);
});
after((done) => {
pool.end(done);
});
it('should create the tables with the correct structure', (done) => {
const cbManager = new CallbackManager(done);
const cb1 = cbManager.registerCallback();
pool.query(`SHOW CREATE TABLE \`${bigTableName}\``, (err, result) => {
if (err) throw err;
result[0]['Create Table'].should.equal(bigTableExpectedSQL);
cb1();
});
const cb2 = cbManager.registerCallback();
pool.query(`SHOW CREATE TABLE \`${autoIncTableName}\``, (err, result) => {
if (err) throw err;
result[0]['Create Table'].should.equal(autoIncTableExpectedSQL);
cb2();
});
const cb3 = cbManager.registerCallback();
pool.query(`SHOW CREATE TABLE \`${pivotTableName}\``, (err, result) => {
if (err) throw err;
result[0]['Create Table'].should.equal(pivotTableExpectedSQL);
cb3();
});
const cb4 = cbManager.registerCallback();
pool.query(`SHOW CREATE TABLE \`${columnsTableName}\``, (err, result) => {
if (err) throw err;
result[0]['Create Table'].should.equal(columnsTableExpectedSQL);
cb4();
});
const cb5 = cbManager.registerCallback();
pool.query(`SHOW CREATE TABLE \`${primaryKeyTableName}\``, (err, result) => {
if (err) throw err;
result[0]['Create Table'].should.equal(primaryKeyTableExpectedSQL);
cb5();
});
const cb6 = cbManager.registerCallback();
pool.query(`SHOW CREATE TABLE \`${uniqueKeysTableName}\``, (err, result) => {
if (err) throw err;
result[0]['Create Table'].should.equal(uniqueKeysTableExpectedSQL);
cb6();
});
const cb7 = cbManager.registerCallback();
pool.query(`SHOW CREATE TABLE \`${indexesTableName}\``, (err, result) => {
if (err) throw err;
result[0]['Create Table'].should.equal(indexesTableExpectedSQL);
cb7();
});
const cbSpatial = cbManager.registerCallback();
pool.query(`SHOW CREATE TABLE \`${spatialIndexesTableName}\``, (err, result) => {
if (err) throw err;
result[0]['Create Table'].should.equal(spatialIndexesTableExpectedSQL);
cbSpatial();
});
const cbFulltext = cbManager.registerCallback();
pool.query(`SHOW CREATE TABLE \`${fulltextIndexesTableName}\``, (err, result) => {
if (err) throw err;
result[0]['Create Table'].should.equal(fulltextIndexesTableExpectedSQL);
cbFulltext();
});
const cb8 = cbManager.registerCallback();
pool.query(`SHOW CREATE TABLE \`${foreignKeysTableName}\``, (err, result) => {
if (err) throw err;
result[0]['Create Table'].should.equal(foreignKeysTableExpectedSQL);
cb8();
});
const cb9 = cbManager.registerCallback();
pool.query(`SHOW CREATE TABLE \`${optionsTableName}\``, (err, result) => {
if (err) throw err;
result[0]['Create Table'].should.equal(optionsTableExpectedSQL);
cb9();
});
const cb10 = cbManager.registerCallback();
pool.query(`SHOW CREATE TABLE \`${textTableName}\``, (err, result) => {
if (err) throw err;
result[0]['Create Table'].should.equal(textTableExpectedSQL);
cb10();
});
const cbKeyParts = cbManager.registerCallback();
pool.query(`SHOW CREATE TABLE \`${keyPartsTableName}\``, (err, result) => {
if (err) throw err;
result[0]['Create Table'].should.equal(keyPartsTableExpectedSQL);
cbKeyParts();
});
const cbTimestamp = cbManager.registerCallback();
pool.query(`SHOW CREATE TABLE \`${timestampTableName}\``, (err, result) => {
if (err) throw err;
result[0]['Create Table'].should.equal(timestampTableExpectedSQL);
cbTimestamp();
});
const cbSynonym = cbManager.registerCallback();
pool.query(`SHOW CREATE TABLE \`${synonymTableName}\``, (err, result) => {
if (err) throw err;
result[0]['Create Table'].should.equal(synonymTableExpectedSQL);
cbSynonym();
});
});
});
describe('when re-defining existing tables without changing them and migrationStrategy = "alter"', () => {
const pool = MySQLPlus.createPool(config);
before((done) => {
sinon.spy(pool, '_runOperations');
pool.defineTable(bigTableName, bigTableSchema);
pool.defineTable(autoIncTableName, autoIncTableSchema);
pool.defineTable(pivotTableName, pivotTableSchema);
pool.defineTable(columnsTableName, columnsTableSchema);
pool.defineTable(primaryKeyTableName, primaryKeyTableSchema);
pool.defineTable(uniqueKeysTableName, uniqueKeysTableSchema);
pool.defineTable(indexesTableName, indexesTableSchema);
pool.defineTable(spatialIndexesTableName, spatialIndexesTableSchema);
pool.defineTable(fulltextIndexesTableName, fulltextIndexesTableSchema);
pool.defineTable(foreignKeysTableName, foreignKeysTableSchema);
pool.defineTable(optionsTableName, optionsTableSchema);
pool.defineTable(textTableName, textTableSchema);
pool.defineTable(keyPartsTableName, keyPartsTableSchema);
pool.defineTable(timestampTableName, timestampTableSchema);
pool.defineTable(synonymTableName, synonymTableSchema);
pool.sync(done);
});
after((done) => {
pool._runOperations.restore();
pool.end(done);
});
it('should not run any table-altering operations', () => {
pool._runOperations.should.be.calledOnce().and.be.calledWith([]);
});
it('should not alter any tables\' structure', (done) => {
const cbManager = new CallbackManager(done);
const cb1 = cbManager.registerCallback();
pool.query(`SHOW CREATE TABLE \`${bigTableName}\``, (err, result) => {
if (err) throw err;
result[0]['Create Table'].should.equal(bigTableExpectedSQL);
cb1();
});
const cb2 = cbManager.registerCallback();
pool.query(`SHOW CREATE TABLE \`${autoIncTableName}\``, (err, result) => {
if (err) throw err;
result[0]['Create Table'].should.equal(autoIncTableExpectedSQL);
cb2();
});
const cb3 = cbManager.registerCallback();
pool.query(`SHOW CREATE TABLE \`${pivotTableName}\``, (err, result) => {
if (err) throw err;
result[0]['Create Table'].should.equal(pivotTableExpectedSQL);
cb3();
});
const cb4 = cbManager.registerCallback();
pool.query(`SHOW CREATE TABLE \`${columnsTableName}\``, (err, result) => {
if (err) throw err;
result[0]['Create Table'].should.equal(columnsTableExpectedSQL);
cb4();
});
const cb5 = cbManager.registerCallback();
pool.query(`SHOW CREATE TABLE \`${primaryKeyTableName}\``, (err, result) => {
if (err) throw err;
result[0]['Create Table'].should.equal(primaryKeyTableExpectedSQL);
cb5();
});
const cb6 = cbManager.registerCallback();
pool.query(`SHOW CREATE TABLE \`${uniqueKeysTableName}\``, (err, result) => {
if (err) throw err;
result[0]['Create Table'].should.equal(uniqueKeysTableExpectedSQL);
cb6();
});
const cb7 = cbManager.registerCallback();
pool.query(`SHOW CREATE TABLE \`${indexesTableName}\``, (err, result) => {
if (err) throw err;
result[0]['Create Table'].should.equal(indexesTableExpectedSQL);
cb7();
});
const cbSpatial = cbManager.registerCallback();
pool.query(`SHOW CREATE TABLE \`${spatialIndexesTableName}\``, (err, result) => {
if (err) throw err;
result[0]['Create Table'].should.equal(spatialIndexesTableExpectedSQL);
cbSpatial();
});
const cbFulltext = cbManager.registerCallback();
pool.query(`SHOW CREATE TABLE \`${fulltextIndexesTableName}\``, (err, result) => {
if (err) throw err;
result[0]['Create Table'].should.equal(fulltextIndexesTableExpectedSQL);
cbFulltext();
});
const cb8 = cbManager.registerCallback();
pool.query(`SHOW CREATE TABLE \`${foreignKeysTableName}\``, (err, result) => {
if (err) throw err;
result[0]['Create Table'].should.equal(foreignKeysTableExpectedSQL);
cb8();
});
const cb9 = cbManager.registerCallback();
pool.query(`SHOW CREATE TABLE \`${optionsTableName}\``, (err, result) => {
if (err) throw err;
result[0]['Create Table'].should.equal(optionsTableExpectedSQL);
cb9();
});
const cb10 = cbManager.registerCallback();
pool.query(`SHOW CREATE TABLE \`${textTableName}\``, (err, result) => {
if (err) throw err;
result[0]['Create Table'].should.equal(textTableExpectedSQL);
cb10();
});
const cbKeyParts = cbManager.registerCallback();
pool.query(`SHOW CREATE TABLE \`${keyPartsTableName}\``, (err, result) => {
if (err) throw err;
result[0]['Create Table'].should.equal(keyPartsTableExpectedSQL);
cbKeyParts();
});
const cbTimestamp = cbManager.registerCallback();
pool.query(`SHOW CREATE TABLE \`${timestampTableName}\``, (err, result) => {
if (err) throw err;
result[0]['Create Table'].should.equal(timestampTableExpectedSQL);
cbTimestamp();
});
const cbSynonym = cbManager.registerCallback();
pool.query(`SHOW CREATE TABLE \`${synonymTableName}\``, (err, result) => {
if (err) throw err;
result[0]['Create Table'].should.equal(synonymTableExpectedSQL);
cbSynonym();
});
});
});
describe('when re-defining existing tables and migrationStrategy = "drop"', () => {
const dropConfig = Object.assign({plusOptions: {migrationStrategy: 'drop'}}, config);
const pool = MySQLPlus.createPool(dropConfig);
before((done) => {
pool.defineTable(bigTableName, bigTableSchema);
pool.defineTable(autoIncTableName, autoIncTableSchema);
pool.defineTable(pivotTableName, pivotTableSchema);
pool.defineTable(columnsTableName, columnsTableSchema);
pool.defineTable(primaryKeyTableName, primaryKeyTableSchema);
pool.defineTable(uniqueKeysTableName, uniqueKeysTableSchema);
pool.defineTable(indexesTableName, indexesTableSchema);
pool.defineTable(spatialIndexesTableName, spatialIndexesTableSchema);
pool.defineTable(fulltextIndexesTableName, fulltextIndexesTableSchema);
pool.defineTable(foreignKeysTableName, foreignKeysTableSchema);
pool.defineTable(optionsTableName, optionsTableSchema);
pool.defineTable(textTableName, textTableSchema);
pool.defineTable(keyPartsTableName, keyPartsTableSchema);
pool.defineTable(timestampTableName, timestampTableSchema);
pool.defineTable(synonymTableName, synonymTableSchema);
pool.sync(done);
});
after((done) => {
pool.end(done);
});
it('should not alter any tables\' structure', (done) => {
const cbManager = new CallbackManager(done);
const cb1 = cbManager.registerCallback();
pool.query(`SHOW CREATE TABLE \`${bigTableName}\``, (err, result) => {
if (err) throw err;
result[0]['Create Table'].should.equal(bigTableExpectedSQL);
cb1();
});
const cb2 = cbManager.registerCallback();
pool.query(`SHOW CREATE TABLE \`${autoIncTableName}\``, (err, result) => {
if (err) throw err;
result[0]['Create Table'].should.equal(autoIncTableExpectedSQL);
cb2();
});
const cb3 = cbManager.registerCallback();
pool.query(`SHOW CREATE TABLE \`${pivotTableName}\``, (err, result) => {
if (err) throw err;
result[0]['Create Table'].should.equal(pivotTableExpectedSQL);
cb3();
});
const cb4 = cbManager.registerCallback();
pool.query(`SHOW CREATE TABLE \`${columnsTableName}\``, (err, result) => {
if (err) throw err;
result[0]['Create Table'].should.equal(columnsTableExpectedSQL);
cb4();
});
const cb5 = cbManager.registerCallback();
pool.query(`SHOW CREATE TABLE \`${primaryKeyTableName}\``, (err, result) => {
if (err) throw err;
result[0]['Create Table'].should.equal(primaryKeyTableExpectedSQL);
cb5();
});
const cb6 = cbManager.registerCallback();
pool.query(`SHOW CREATE TABLE \`${uniqueKeysTableName}\``, (err, result) => {
if (err) throw err;
result[0]['Create Table'].should.equal(uniqueKeysTableExpectedSQL);
cb6();
});
const cb7 = cbManager.registerCallback();
pool.query(`SHOW CREATE TABLE \`${indexesTableName}\``, (err, result) => {
if (err) throw err;
result[0]['Create Table'].should.equal(indexesTableExpectedSQL);
cb7();
});
const cbSpatial = cbManager.registerCallback();
pool.query(`SHOW CREATE TABLE \`${spatialIndexesTableName}\``, (err, result) => {
if (err) throw err;
result[0]['Create Table'].should.equal(spatialIndexesTableExpectedSQL);
cbSpatial();
});
const cbFulltext = cbManager.registerCallback();
pool.query(`SHOW CREATE TABLE \`${fulltextIndexesTableName}\``, (err, result) => {
if (err) throw err;
result[0]['Create Table'].should.equal(fulltextIndexesTableExpectedSQL);
cbFulltext();
});
const cb8 = cbManager.registerCallback();
pool.query(`SHOW CREATE TABLE \`${foreignKeysTableName}\``, (err, result) => {
if (err) throw err;
result[0]['Create Table'].should.equal(foreignKeysTableExpectedSQL);
cb8();
});
const cb9 = cbManager.registerCallback();
pool.query(`SHOW CREATE TABLE \`${optionsTableName}\``, (err, result) => {
if (err) throw err;
result[0]['Create Table'].should.equal(optionsTableExpectedSQL);
cb9();
});
const cb10 = cbManager.registerCallback();
pool.query(`SHOW CREATE TABLE \`${textTableName}\``, (err, result) => {
if (err) throw err;
result[0]['Create Table'].should.equal(textTableExpectedSQL);
cb10();
});
const cbKeyParts = cbManager.registerCallback();
pool.query(`SHOW CREATE TABLE \`${keyPartsTableName}\``, (err, result) => {
if (err) throw err;
result[0]['Create Table'].should.equal(keyPartsTableExpectedSQL);
cbKeyParts();
});
const cbTimestamp = cbManager.registerCallback();
pool.query(`SHOW CREATE TABLE \`${timestampTableName}\``, (err, result) => {
if (err) throw err;
result[0]['Create Table'].should.equal(timestampTableExpectedSQL);
cbTimestamp();
});
const cbSynonym = cbManager.registerCallback();
pool.query(`SHOW CREATE TABLE \`${synonymTableName}\``, (err, result) => {
if (err) throw err;
result[0]['Create Table'].should.equal(synonymTableExpectedSQL);
cbSynonym();
});
});
});
describe('when migrating existing tables', () => {
const pool = MySQLPlus.createPool(config);
before((done) => {
pool.defineTable(bigTableName, bigTableSchema);
pool.defineTable(autoIncTableName, autoIncTableMigratedSchema);
pool.defineTable(pivotTableName, pivotTableSchema);
pool.defineTable(columnsTableName, columnsTableMigratedSchema);
pool.defineTable(primaryKeyTableName, primaryKeyTableMigratedSchema);
pool.defineTable(uniqueKeysTableName, uniqueKeysTableMigragedSchema);
pool.defineTable(indexesTableName, indexesTableMigragedSchema);
pool.defineTable(spatialIndexesTableName, spatialIndexesTableMigragedSchema);
pool.defineTable(fulltextIndexesTableName, fulltextIndexesTableMigragedSchema);
pool.defineTable(foreignKeysTableName, foreignKeysTableMigratedSchema);
pool.defineTable(optionsTableName, optionsTableMigratedSchema);
// Insert data into the columns table before syncing the table changes so
// we can check if the data is still there after some columns get renamed
pool.query(
`INSERT INTO ${columnsTableName} (id, email, renameme, changeme) VALUES (1, 'a', 1, 2), (2, 'b', 3, 4)`,
(err) => {
if (err) throw err;
pool.sync(done);
}
);
});
after((done) => {
pool.end(done);
});
it('should migrate the tables to the correct new structure', (done) => {
const cbManager = new CallbackManager(done);
const cb1 = cbManager.registerCallback();
pool.query(`SHOW CREATE TABLE \`${bigTableName}\``, (err, result) => {
if (err) throw err;
result[0]['Create Table'].should.equal(bigTableExpectedSQL);
cb1();
});
const cb2 = cbManager.registerCallback();
pool.query(`SHOW CREATE TABLE \`${autoIncTableName}\``, (err, result) => {
if (err) throw err;
result[0]['Create Table'].should.equal(autoIncTableMigratedExpectedSQL);
cb2();
});
const cb3 = cbManager.registerCallback();
pool.query(`SHOW CREATE TABLE \`${pivotTableName}\``, (err, result) => {
if (err) throw err;
result[0]['Create Table'].should.equal(pivotTableExpectedSQL);
cb3();
});
const cb4 = cbManager.registerCallback();
pool.query(`SHOW CREATE TABLE \`${columnsTableName}\``, (err, result) => {
if (err) throw err;
result[0]['Create Table'].should.equal(columnsTableMigratedExpectedSQL);
cb4();
});
const cb5 = cbManager.registerCallback();
pool.query(`SHOW CREATE TABLE \`${primaryKeyTableName}\``, (err, result) => {
if (err) throw err;
result[0]['Create Table'].should.equal(primaryKeyTableMigratedExpectedSQL);
cb5();
});
const cb6 = cbManager.registerCallback();
pool.query(`SHOW CREATE TABLE \`${uniqueKeysTableName}\``, (err, result) => {
if (err) throw err;
result[0]['Create Table'].should.equal(uniqueKeysTableMigratedExpectedSQL);
cb6();
});
const cb7 = cbManager.registerCallback();
pool.query(`SHOW CREATE TABLE \`${indexesTableName}\``, (err, result) => {
if (err) throw err;
result[0]['Create Table'].should.equal(indexesTableMigratedExpectedSQL);
cb7();
});
const cbSpatial = cbManager.registerCallback();
pool.query(`SHOW CREATE TABLE \`${spatialIndexesTableName}\``, (err, result) => {
if (err) throw err;
result[0]['Create Table'].should.equal(spatialIndexesTableMigratedExpectedSQL);
cbSpatial();
});
const cbFulltext = cbManager.registerCallback();
pool.query(`SHOW CREATE TABLE \`${fulltextIndexesTableName}\``, (err, result) => {
if (err) throw err;
result[0]['Create Table'].should.equal(fulltextIndexesTableMigratedExpectedSQL);
cbFulltext();
});
const cb8 = cbManager.registerCallback();
pool.query(`SHOW CREATE TABLE \`${foreignKeysTableName}\``, (err, result) => {
if (err) throw err;
result[0]['Create Table'].should.equal(foreignKeysTableMigratedExpectedSQL);
cb8();
});
const cb9 = cbManager.registerCallback();
pool.query(`SHOW CREATE TABLE \`${optionsTableName}\``, (err, result) => {
if (err) throw err;
result[0]['Create Table'].should.equal(optionsTableMigratedExpectedSQL);
cb9();
});
});
it('should not decrease the AUTO_INCREMENT table option', (done) => {
const tempPool = MySQLPlus.createPool(config);
// Try to go back to the original schema
tempPool.defineTable(autoIncTableName, autoIncTableSchema);
tempPool.sync((err) => {
if (err) throw err;
tempPool.query(`SHOW CREATE TABLE \`${autoIncTableName}\``, (err, result) => {
if (err) throw err;
// The schema should not have changed from the migrated version
result[0]['Create Table'].should.equal(autoIncTableMigratedExpectedSQL);
tempPool.end(done);
});
});
});
it('should not lose data when renaming columns', (done) => {
pool.query(`SELECT renamed, changed FROM ${columnsTableName}`, (err, rows) => {
if (err) throw err;
rows.should.have.length(2);
rows[0].renamed.should.equal(1);
rows[0].changed.should.equal(2);
rows[1].renamed.should.equal(3);
rows[1].changed.should.equal(4);
done();
});
});
});
});
|
AllBestBets/async-http-client
|
client/src/test/java/org/asynchttpclient/oauth/StaticOAuthSignatureCalculator.java
|
/*
* Copyright (c) 2017 AsyncHttpClient Project. All rights reserved.
*
* This program is licensed to you under the Apache License Version 2.0,
* and you may not use this file except in compliance with the Apache License Version 2.0.
* You may obtain a copy of the Apache License Version 2.0 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 Version 2.0 is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Apache License Version 2.0 for the specific language governing permissions and limitations there under.
*/
package org.asynchttpclient.oauth;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import org.asynchttpclient.Request;
import org.asynchttpclient.RequestBuilderBase;
import org.asynchttpclient.SignatureCalculator;
class StaticOAuthSignatureCalculator implements SignatureCalculator {
private final ConsumerKey consumerKey;
private final RequestToken requestToken;
private final String nonce;
private final long timestamp;
public StaticOAuthSignatureCalculator(ConsumerKey consumerKey, RequestToken requestToken, String nonce, long timestamp) {
this.consumerKey = consumerKey;
this.requestToken = requestToken;
this.nonce = nonce;
this.timestamp = timestamp;
}
@Override
public void calculateAndAddSignature(Request request, RequestBuilderBase<?> requestBuilder) {
try {
new OAuthSignatureCalculatorInstance().sign(consumerKey, requestToken, request, requestBuilder, timestamp, nonce);
} catch (InvalidKeyException | NoSuchAlgorithmException e) {
throw new IllegalArgumentException(e);
}
}
}
|
J1effrey/LC1
|
new/2021/11/27/jian-lc658.java
|
//Time: nlogn
//Space: O(n)
class Solution {
public List<Integer> findClosestElements(int[] arr, int k, int x) {
List<Integer> res = new ArrayList<>();
if (arr == null || arr.length == 0 || k <= 0) {
return res;
}
int closetIndex = getIndexOfOneClosestElement(arr, x);
res.add(arr[closetIndex]);
int left = closetIndex - 1;
int right = closetIndex + 1;
while (res.size() < k && left >= 0 && right < arr.length) {
int disOfLeft = Math.abs(arr[left] - x);
int disOfRight = Math.abs(arr[right] - x);
if (disOfLeft <= disOfRight) {
res.add(arr[left]);
left--;
} else {
res.add(arr[right]);
right++;
}
}
while (res.size() < k) {
if (left < 0) {
while (res.size() < k) {
res.add(arr[right++]);
}
break;
}
while (res.size() < k) {
res.add(arr[left--]);
}
}
Collections.sort(res);
return res;
}
private int getIndexOfOneClosestElement(int[] arr, int x) {
int start = 0;
int end = arr.length - 1;
while (start + 1 < end) {
int mid = start + (end - start) / 2;
if (arr[mid] == x) {
return mid;
} else if (arr[mid] > x) {
end = mid;
} else {
start = mid;
}
}
int disOfStart = Math.abs(arr[start] - x);
int disOfEnd = Math.abs(arr[end] - x);
return disOfStart <= disOfEnd ? start : end;
}
}
|
festival-app/npm-festival
|
test/domain/coordinatesTest.js
|
var chai = require('chai');
var should = chai.should();
var coordinates = require('../../lib/domain/coordinates');
describe('coordinates model test', function () {
var lat = 'lat';
var lon = 'lon';
it('should create model', function (done) {
var coordinatesModel = new coordinates.Coordinates(
lat,
lon
);
should.exist(coordinatesModel);
coordinatesModel.lat.should.be.equal(lat);
coordinatesModel.lon.should.be.equal(lon);
done();
});
it('should create model by builder', function (done) {
var coordinatesModel = new coordinates.CoordinatesBuilder()
.withLat(lat)
.withLon(lon)
.build();
should.exist(coordinatesModel);
coordinatesModel.lat.should.be.equal(lat);
coordinatesModel.lon.should.be.equal(lon);
done();
});
});
|
iaakhter/MYZ3
|
src/nlsat/tactic/goal2nlsat.h
|
/*++
Copyright (c) 2012 Microsoft Corporation
Module Name:
goal2nlsat.h
Abstract:
"Compile" a goal into the nonlinear arithmetic engine.
Non-arithmetic atoms are "abstracted" into boolean variables.
Non-supported terms are "abstracted" into variables.
The mappings can be used to convert back the state of the
engine into a goal.
Author:
Leonardo (leonardo) 2012-01-02
Notes:
--*/
#ifndef GOAL2NLSAT_H_
#define GOAL2NLSAT_H_
#include"nlsat_types.h"
#include"model_converter.h"
class goal;
class expr2var;
class goal2nlsat {
struct imp;
imp * m_imp;
struct scoped_set_imp;
public:
goal2nlsat();
~goal2nlsat();
static void collect_param_descrs(param_descrs & r);
/**
\brief "Compile" the goal into the given nlsat engine.
Store a mapping from atoms to boolean variables into a2b.
Store a mapping from terms into arithmetic variables into t2x.
\remark a2b and t2x m don't need to be empty. The definitions there are reused.
The input is expected to be in CNF
*/
void operator()(goal const & g, params_ref const & p, nlsat::solver & s, expr2var & a2b, expr2var & t2x);
};
class nlsat2goal {
struct imp;
imp * m_imp;
public:
nlsat2goal(ast_manager& m);
~nlsat2goal();
static void collect_param_descrs(param_descrs & r);
/**
\brief Translate a literal into a formula.
*/
expr_ref operator()(nlsat::solver& s, u_map<expr*> const& b2a, u_map<expr*> const& x2t, nlsat::literal l);
};
#endif
|
ahmadtech199/expo
|
ios/Exponent/Versioned/Core/UniversalModules/EXScopedBranch.h
|
// Copyright 2019-present 650 Industries. All rights reserved.
#if __has_include(<EXBranch/RNBranch.h>)
#import <EXBranch/RNBranch.h>
#import <UMCore/UMInternalModule.h>
#import <UMCore/UMModuleRegistryConsumer.h>
NS_ASSUME_NONNULL_BEGIN
@protocol EXBranchScopedModuleDelegate
- (void)branchModuleDidInit:(id _Nonnull)branchModule;
@end
@interface EXScopedBranch : RNBranch <UMModuleRegistryConsumer, UMInternalModule>
@property (nonatomic, strong) NSString *scopeKey;
- (instancetype)initWithScopeKey:(NSString *)scopeKey;
@end
NS_ASSUME_NONNULL_END
#endif
|
sauvikatinnofied/ExploringFuse
|
Day1/build/iOS/Preview/include/iOS.UIKit.IUIImagePickerControllerDelegate.h
|
<reponame>sauvikatinnofied/ExploringFuse<gh_stars>0
// This file was generated based on '/usr/local/share/uno/Packages/Experimental.iOS/0.24.0/interface/$.uno'.
// WARNING: Changes might be lost if you edit this file directly.
#pragma once
#include <Uno.Object.h>
namespace g{namespace iOS{namespace Foundation{struct NSDictionary;}}}
namespace g{namespace iOS{namespace UIKit{struct UIImage;}}}
namespace g{namespace iOS{namespace UIKit{struct UIImagePickerController;}}}
namespace g{
namespace iOS{
namespace UIKit{
// public abstract extern interface IUIImagePickerControllerDelegate :4602
// {
uInterfaceType* IUIImagePickerControllerDelegate_typeof();
struct IUIImagePickerControllerDelegate
{
void(*fp_imagePickerControllerDidCancel)(uObject*, ::g::iOS::UIKit::UIImagePickerController*);
void(*fp_imagePickerControllerDidFinishPickingImageEditingInfo)(uObject*, ::g::iOS::UIKit::UIImagePickerController*, ::g::iOS::UIKit::UIImage*, ::g::iOS::Foundation::NSDictionary*);
void(*fp_imagePickerControllerDidFinishPickingMediaWithInfo)(uObject*, ::g::iOS::UIKit::UIImagePickerController*, ::g::iOS::Foundation::NSDictionary*);
static void imagePickerControllerDidCancel(const uInterface& __this, ::g::iOS::UIKit::UIImagePickerController* picker) { __this.VTable<IUIImagePickerControllerDelegate>()->fp_imagePickerControllerDidCancel(__this, picker); }
static void imagePickerControllerDidFinishPickingImageEditingInfo(const uInterface& __this, ::g::iOS::UIKit::UIImagePickerController* picker, ::g::iOS::UIKit::UIImage* image, ::g::iOS::Foundation::NSDictionary* editingInfo) { __this.VTable<IUIImagePickerControllerDelegate>()->fp_imagePickerControllerDidFinishPickingImageEditingInfo(__this, picker, image, editingInfo); }
static void imagePickerControllerDidFinishPickingMediaWithInfo(const uInterface& __this, ::g::iOS::UIKit::UIImagePickerController* picker, ::g::iOS::Foundation::NSDictionary* info) { __this.VTable<IUIImagePickerControllerDelegate>()->fp_imagePickerControllerDidFinishPickingMediaWithInfo(__this, picker, info); }
};
// }
}}} // ::g::iOS::UIKit
|
ruby232/web-standard-functions
|
dist/lib-esm/generator/out/not_implemented.js
|
/* AUTOGENERATED CODE BELOW */
function notImplemented(fnName) {
console.log("Not yet implemented: " + fnName);
}
// Type: Core
/**
* @param message
* @return any
*/
export function ask() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("ask");
return null;
}
/**
* @param characterExpression
* @param encoding
* @return number
*/
export function byteCount() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("byteCount");
return null;
}
/**
* @param array
* @return any
*/
export function cols() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("cols");
return null;
}
/**
* @param str
* @param key
* @return any
*/
export function decrypt64() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("decrypt64");
return null;
}
/**
* @return number
*/
export function dFRClose() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("dFRClose");
return null;
}
/**
* @param value
* @param format
* @param separator
* @return number
*/
export function dFRGDate() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("dFRGDate");
return null;
}
/**
* @param value
* @return number
*/
export function dFRGNum() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("dFRGNum");
return null;
}
/**
* @param value
* @param length
* @return number
*/
export function dFRGTxt() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("dFRGTxt");
return null;
}
/**
* @return number
*/
export function dFRNext() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("dFRNext");
return null;
}
/**
* @param fileName
* @param regLength
* @param fieldDelimiter
* @param strDelimiter
* @param encoding
* @return number
*/
export function dFROpen() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("dFROpen");
return null;
}
/**
* @return number
*/
export function dFWClose() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("dFWClose");
return null;
}
/**
* @return number
*/
export function dFWNext() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("dFWNext");
return null;
}
/**
* @param fileName
* @param fieldDelimiter
* @param strDelimiter
* @param append
* @param encoding
* @return number
*/
export function dFWOpen() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("dFWOpen");
return null;
}
/**
* @param value
* @param format
* @param separator
* @return number
*/
export function dFWPDate() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("dFWPDate");
return null;
}
/**
* @param value
* @param decimals
* @return number
*/
export function dFWPNum() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("dFWPNum");
return null;
}
/**
* @param value
* @param length
* @return number
*/
export function dFWPTxt() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("dFWPTxt");
return null;
}
/**
* @param str
* @param key
* @return any
*/
export function encrypt64() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("encrypt64");
return null;
}
/**
* @param attribute
* @return number
*/
export function exists() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("exists");
return null;
}
/**
* @param fileName
* @return number
*/
export function fileExist() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("fileExist");
return null;
}
/**
* @param name
* @return any
*/
export function getDataStore() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("getDataStore");
return null;
}
/**
* @return any
*/
export function getEncryptionKey() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("getEncryptionKey");
return null;
}
/**
* @param name
* @return any
*/
export function getLocation() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("getLocation");
return null;
}
/**
* @return number
*/
export function getSOAPErr() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("getSOAPErr");
return null;
}
/**
* @return any
*/
export function getSOAPErrMsg() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("getSOAPErrMsg");
return null;
}
/**
* @return any
*/
export function getTheme() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("getTheme");
return null;
}
/**
* @param value
* @param line
* @param lineLenght
* @return any
*/
export function gXGetMLi() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("gXGetMLi");
return null;
}
/**
* @param value
* @param lineLength
* @return number
*/
export function gXMLines() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("gXMLines");
return null;
}
/**
* @param hTMLString
* @return any
*/
export function hTMLClean() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("hTMLClean");
return null;
}
/**
* @param urlString
* @return any
*/
export function urlEncode() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("urlEncode");
return null;
}
/**
* @param objectURL
* @param parameter
* @return any
*/
export function link() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("link");
return null;
}
/**
* @param fileName
* @return any
*/
export function loadBitmap() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("loadBitmap");
return null;
}
/**
* @param document
* @return number
*/
export function openDocument() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("openDocument");
return null;
}
/**
* @param blob
* @return any
*/
export function pathToUrl() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("pathToUrl");
return null;
}
/**
* @param document
* @return number
*/
export function printDocument() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("printDocument");
return null;
}
/**
* @return number
*/
export function random() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("random");
return null;
}
/**
* @param path
* @return any
*/
export function readRegKey() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("readRegKey");
return null;
}
/**
* @return any
*/
export function remoteAddr() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("remoteAddr");
return null;
}
/**
* @return any
*/
export function returnOnClick() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("returnOnClick");
return null;
}
/**
* @param red
* @param green
* @param blue
* @return any
*/
export function rGB() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("rGB");
return null;
}
/**
* @param array
* @return any
*/
export function rows() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("rows");
return null;
}
/**
* @param seed
* @return number
*/
export function rSeed() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("rSeed");
return null;
}
/**
* @return Date
*/
export function serverDate() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("serverDate");
return null;
}
/**
* @return any
*/
export function serverNow() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("serverNow");
return null;
}
/**
* @return any
*/
export function serverTime() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("serverTime");
return null;
}
/**
* @param str
* @return number
*/
export function setTheme() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("setTheme");
return null;
}
/**
* @param userId
* @return number
*/
export function setUserId() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("setUserId");
return null;
}
/**
* @param workstation
* @return number
*/
export function setWrkSt() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("setWrkSt");
return null;
}
/**
* @param fileName
* @param modal
* @return number
*/
export function shell() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("shell");
return null;
}
/**
* @param seconds
* @return number
*/
export function sleep() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("sleep");
return null;
}
/**
* @return Date
*/
export function sysDate() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("sysDate");
return null;
}
/**
* @return any
*/
export function sysTime() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("sysTime");
return null;
}
/**
* @param name
* @return any
*/
export function toFormattedString() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("toFormattedString");
return null;
}
/**
* @return any
*/
export function userCls() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("userCls");
return null;
}
/**
* @param server
* @return any
*/
export function userID() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("userID");
return null;
}
/**
* @param path
* @param value
* @return number
*/
export function writeRegKey() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("writeRegKey");
return null;
}
/**
* @return any
*/
export function wrkSt() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("wrkSt");
return null;
}
/**
* @param param1
* @param param2
* @param param3
* @return any
*/
export function xToD() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("xToD");
return null;
}
/**
* @param attribute
* @param condition
* @param defaultValue
* @return any
*/
export function set() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("set");
return null;
}
/**
* @return any
*/
export function confirmed() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("confirmed");
return null;
}
/**
* @param name
* @return any
*/
export function cursor() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("cursor");
return null;
}
/**
* @param fileName
* @return any
*/
export function deleteFile() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("deleteFile");
return null;
}
/**
* @param propertyName
* @param propertyValue
* @return any
*/
export function setEnvProperty() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("setEnvProperty");
return null;
}
/**
* @param subroutineName
* @return any
*/
export function errorhandler() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("errorhandler");
return null;
}
/**
* @param fileName
* @param type
* @return any
*/
export function outputfile() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("outputfile");
return null;
}
/**
* @param attribute
* @return any
*/
export function order() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("order");
return null;
}
/**
* @param attribute
* @return number
*/
export function level() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("level");
return null;
}
/**
* @return boolean
*/
export function modified() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("modified");
return null;
}
/**
* @param name
* @return any
*/
export function old() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("old");
return null;
}
/**
* @param name
* @return any
*/
export function previous() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("previous");
return null;
}
/**
* @param name
* @param level
* @return any
*/
export function accept() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("accept");
return null;
}
/**
* @param value
* @param attribute
* @return any
*/
export function add() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("add");
return null;
}
/**
* @param attribute
* @return any
*/
export function allowNulls() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("allowNulls");
return null;
}
/**
* @param action
* @param level
* @return any
*/
export function defaultmode() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("defaultmode");
return null;
}
/**
* @param name
* @param value
* @return any
*/
export function equal() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("equal");
return null;
}
/**
* @param message
* @param exceptionName
* @return any
*/
export function error() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("error");
return null;
}
/**
* @param message
* @param attribute
* @return any
*/
export function refMsg() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("refMsg");
return null;
}
/**
* @param userProgram
* @param submitParms
* @param parameter
* @return any
*/
export function submit() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("submit");
return null;
}
/**
* @param value
* @param attribute
* @return any
*/
export function subtract() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("subtract");
return null;
}
/**
* @param attribute
* @return any
*/
export function update() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("update");
return null;
}
/**
* @param linesCount
* @return any
*/
export function workfilelines() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("workfilelines");
return null;
}
/**
* @param expressionToEvaluate
* @param variablesList
* @param resultError
* @param errorMessage
* @return any
*/
export function calculate() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("calculate");
return null;
}
/**
* @param condition
* @return any
*/
export function search() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("search");
return null;
}
// end Type
// Type: Numeric
// end Type
// Type: Character
/**
* @return any
*/
export function cHtmlClean() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("cHtmlClean");
return null;
}
// end Type
// Type: Date
// end Type
// Type: Image
// end Type
// Type: LongVarchar
/**
* @return any
*/
export function lHtmlClean() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("lHtmlClean");
return null;
}
// end Type
// Type: DateTime
/**
* @param pYear
* @param pMonth
* @param pDay
* @param pHour
* @param pMin
* @param pSec
* @return any
*/
export function dtSet() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("dtSet");
return null;
}
// end Type
// Type: Varchar
/**
* @return any
*/
export function vHtmlClean() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("vHtmlClean");
return null;
}
// end Type
// Type: Binary
/**
* @return any
*/
export function toBase64String() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("toBase64String");
return null;
}
/**
* @param content
* @return any
*/
export function binaryFromBase64String() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("binaryFromBase64String");
return null;
}
// end Type
// Type: Boolean
// end Type
// Type: HttpClient
/**
* @param authType
* @param realm
* @param user
* @param password
* @return any
*/
export function addAuthentication() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("addAuthentication");
return null;
}
/**
* @param authType
* @param realm
* @param user
* @param password
* @return any
*/
export function addProxyAuthentication() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("addProxyAuthentication");
return null;
}
/**
* @param fileName
* @param name
* @return any
*/
export function httpClientAddFile() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("httpClientAddFile");
return null;
}
/**
* @param name
* @param value
* @return any
*/
export function httpClientAddHeader() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("httpClientAddHeader");
return null;
}
/**
* @param value
* @return any
*/
export function httpClientAddString() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("httpClientAddString");
return null;
}
/**
* @param name
* @param value
* @return any
*/
export function addVariable() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("addVariable");
return null;
}
/**
* @param method
* @param url
* @return any
*/
export function execute() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("execute");
return null;
}
/**
* @param name
* @return any
*/
export function httpClientGetHeader() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("httpClientGetHeader");
return null;
}
/**
* @param name
* @return any
*/
export function httpClientToFile() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("httpClientToFile");
return null;
}
/**
* @return any
*/
export function httpClientToString() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("httpClientToString");
return null;
}
// end Type
// Type: HttpResponse
/**
* @param name
* @param value
* @return any
*/
export function addHeader() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("addHeader");
return null;
}
/**
* @param value
* @return any
*/
export function addString() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("addString");
return null;
}
/**
* @param name
* @return any
*/
export function addFile() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("addFile");
return null;
}
/**
* @param cookie
* @return number
*/
export function httpResponseSetCookie() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("httpResponseSetCookie");
return null;
}
// end Type
// Type: HttpRequest
/**
* @return any
*/
export function httpRequestToString() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("httpRequestToString");
return null;
}
/**
* @param name
* @return any
*/
export function toFile() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("toFile");
return null;
}
/**
* @param name
* @return any
*/
export function getHeader() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("getHeader");
return null;
}
/**
* @param name
* @return any
*/
export function getVariable() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("getVariable");
return null;
}
// end Type
// Type: StringCollection
/**
* @return any
*/
export function strCollectionClear() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("strCollectionClear");
return null;
}
/**
* @param element
* @return any
*/
export function strCollectionAdd() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("strCollectionAdd");
return null;
}
/**
* @param index
* @return any
*/
export function strCollectionItem() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("strCollectionItem");
return null;
}
// end Type
// Type: WebSession
/**
* @return any
*/
export function websessionClear() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("websessionClear");
return null;
}
/**
* @return any
*/
export function destroy() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("destroy");
return null;
}
/**
* @param key
* @return any
*/
export function websessionGet() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("websessionGet");
return null;
}
/**
* @param key
* @return any
*/
export function websessionRemove() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("websessionRemove");
return null;
}
/**
* @param key
* @param value
* @return any
*/
export function websessionSet() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("websessionSet");
return null;
}
// end Type
// Type: WebWrapper
/**
* @return any
*/
export function getResponse() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("getResponse");
return null;
}
// end Type
// Type: Variant
// end Type
// Type: Location
// end Type
// Type: RegExMatch
// end Type
// Type: RegExMatchCollection
// end Type
// Type: ContentInfo
// end Type
// Type: Blob
// end Type
// Type: SearchResult
/**
* @return any
*/
export function items() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("items");
return null;
}
// end Type
// Type: SearchResultCollection
/**
* @param index
* @return any
*/
export function searchResultCollectionItem() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("searchResultCollectionItem");
return null;
}
// end Type
// Type: SearchResultItem
// end Type
// Type: Collection
/**
* @param item
* @param index
* @return any
*/
export function collectionAdd() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("collectionAdd");
return null;
}
/**
* @return any
*/
export function collectionClear() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("collectionClear");
return null;
}
/**
* @param index
* @return any
*/
export function collectionItem() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("collectionItem");
return null;
}
/**
* @param index
* @return any
*/
export function collectionRemove() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("collectionRemove");
return null;
}
/**
* @param item
* @return number
*/
export function indexOf() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("indexOf");
return null;
}
/**
* @param includeHeader
* @param includeState
* @return any
*/
export function collectionToXml() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("collectionToXml");
return null;
}
/**
* @param name
* @param outMessages
* @return boolean
*/
export function collectionFromXml() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("collectionFromXml");
return null;
}
/**
* @param name
* @param outMessages
* @return boolean
*/
export function collectionFromXmlFile() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("collectionFromXmlFile");
return null;
}
/**
* @param includeState
* @return any
*/
export function collectionToJson() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("collectionToJson");
return null;
}
/**
* @param source
* @param outMessages
* @return boolean
*/
export function collectionFromJson() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("collectionFromJson");
return null;
}
/**
* @param source
* @param outMessages
* @return boolean
*/
export function collectionFromJsonFile() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("collectionFromJsonFile");
return null;
}
/**
* @return any
*/
export function collectionClone() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("collectionClone");
return null;
}
/**
* @param columnListString
* @return any
*/
export function sort() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("sort");
return null;
}
// end Type
// Type: BusinessComponentCollection
/**
* @param primaryKeyAtt
* @return any
*/
export function bcCollectionGetByKey() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("bcCollectionGetByKey");
return null;
}
/**
* @param primaryKeyAtt
* @return boolean
*/
export function bcCollectionRemoveByKey() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("bcCollectionRemoveByKey");
return null;
}
/**
* @return boolean
*/
export function bcCollectionUpdate() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("bcCollectionUpdate");
return null;
}
/**
* @return boolean
*/
export function bcCollectionInsert() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("bcCollectionInsert");
return null;
}
/**
* @return boolean
*/
export function bcCollectionInsertOrUpdate() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("bcCollectionInsertOrUpdate");
return null;
}
/**
* @return boolean
*/
export function bcCollectionDelete() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("bcCollectionDelete");
return null;
}
// end Type
// Type: BusinessComponentLinesCollection
/**
* @param primaryKeyAtt
* @return any
*/
export function getByKey() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("getByKey");
return null;
}
/**
* @param primaryKeyAtt
* @return boolean
*/
export function removeByKey() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("removeByKey");
return null;
}
// end Type
// Type: HTMLBODY
// end Type
// Type: File
/**
* @return any
*/
export function fileDelete() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("fileDelete");
return null;
}
/**
* @return boolean
*/
export function fileExists() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("fileExists");
return null;
}
/**
* @param name
* @return any
*/
export function fileRename() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("fileRename");
return null;
}
/**
* @param name
* @return any
*/
export function copy() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("copy");
return null;
}
/**
* @return any
*/
export function fileGetName() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("fileGetName");
return null;
}
/**
* @return any
*/
export function fileGetAbsoluteName() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("fileGetAbsoluteName");
return null;
}
/**
* @return any
*/
export function getURI() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("getURI");
return null;
}
/**
* @return number
*/
export function getLength() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("getLength");
return null;
}
/**
* @return Date
*/
export function getLastModified() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("getLastModified");
return null;
}
/**
* @return any
*/
export function getPath() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("getPath");
return null;
}
/**
* @param encoding
* @return any
*/
export function fileOpen() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("fileOpen");
return null;
}
/**
* @param encoding
* @return any
*/
export function openWrite() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("openWrite");
return null;
}
/**
* @param encoding
* @return any
*/
export function openRead() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("openRead");
return null;
}
/**
* @return any
*/
export function fileClose() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("fileClose");
return null;
}
/**
* @return any
*/
export function readLine() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("readLine");
return null;
}
/**
* @param encoding
* @return any
*/
export function readAllText() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("readAllText");
return null;
}
/**
* @param encoding
* @return any
*/
export function readAllLines() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("readAllLines");
return null;
}
/**
* @param value
* @return any
*/
export function writeLine() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("writeLine");
return null;
}
/**
* @param value
* @param encoding
* @return any
*/
export function writeAllText() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("writeAllText");
return null;
}
/**
* @param value
* @param encoding
* @return any
*/
export function writeAllLines() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("writeAllLines");
return null;
}
/**
* @param value
* @param encoding
* @return any
*/
export function appendAllText() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("appendAllText");
return null;
}
/**
* @param vale
* @param encoding
* @return any
*/
export function appendAllLines() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("appendAllLines");
return null;
}
/**
* @return any
*/
export function fileCreate() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("fileCreate");
return null;
}
/**
* @param xSLTFile
* @return any
*/
export function xSLTApply() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("xSLTApply");
return null;
}
/**
* @return any
*/
export function fileHtmlClean() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("fileHtmlClean");
return null;
}
/**
* @param base64String
* @return boolean
*/
export function fromBase64String() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("fromBase64String");
return null;
}
// end Type
// Type: FileCollection
/**
* @param i
* @return any
*/
export function fileCollectionItem() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("fileCollectionItem");
return null;
}
// end Type
// Type: Directory
/**
* @return any
*/
export function create() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("create");
return null;
}
/**
* @return any
*/
export function dirDelete() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("dirDelete");
return null;
}
/**
* @return boolean
*/
export function dirExists() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("dirExists");
return null;
}
/**
* @param name
* @return any
*/
export function rename() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("rename");
return null;
}
/**
* @return any
*/
export function getName() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("getName");
return null;
}
/**
* @return any
*/
export function getAbsoluteName() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("getAbsoluteName");
return null;
}
/**
* @param filter
* @return any
*/
export function getFiles() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("getFiles");
return null;
}
/**
* @return any
*/
export function getDirectories() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("getDirectories");
return null;
}
// end Type
// Type: DirectoryCollection
/**
* @param i
* @return any
*/
export function item() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("item");
return null;
}
// end Type
// Type: Properties
/**
* @param attributeName
* @param attributeValue
* @return any
*/
export function propSet() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("propSet");
return null;
}
/**
* @param attributeName
* @return any
*/
export function propGet() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("propGet");
return null;
}
/**
* @param attributeName
* @return any
*/
export function propRemove() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("propRemove");
return null;
}
/**
* @return any
*/
export function propClear() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("propClear");
return null;
}
/**
* @return any
*/
export function propToJson() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("propToJson");
return null;
}
/**
* @param source
* @param outMessages
* @return boolean
*/
export function propFromJson() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("propFromJson");
return null;
}
// end Type
// Type: Property
// end Type
// Type: Expression
/**
* @return number
*/
export function evaluate() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("evaluate");
return null;
}
// end Type
// Type: RegEx
/**
* @return number
*/
export function getLastErrCode() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("getLastErrCode");
return null;
}
/**
* @return any
*/
export function getLastErrDescription() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("getLastErrDescription");
return null;
}
// end Type
// Type: TextSearch
/**
* @param content
* @param itemsPerPage
* @param pageNumber
* @return any
*/
export function textSearchfind() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("textSearchfind");
return null;
}
/**
* @param variableBCorText
* @param info
* @return boolean
*/
export function textSearchadd() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("textSearchadd");
return null;
}
/**
* @param variableBCorText
* @param info
* @return boolean
*/
export function textSearchupdate() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("textSearchupdate");
return null;
}
/**
* @param variable
* @return boolean
*/
export function textSearchdelete() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("textSearchdelete");
return null;
}
/**
* @return boolean
*/
export function buildDictionary() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("buildDictionary");
return null;
}
/**
* @param text
* @return any
*/
export function checkSpell() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("checkSpell");
return null;
}
/**
* @return number
*/
export function reindexAll() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("reindexAll");
return null;
}
/**
* @param variableBCorText
* @param query
* @param textType
* @param preTag
* @param postTag
* @param fragmentSize
* @param maxNumFragments
* @return any
*/
export function hTMLPreview() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("hTMLPreview");
return null;
}
// end Type
// Type: Window
/**
* @return any
*/
export function windowOpen() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("windowOpen");
return null;
}
// end Type
// Type: Video
/**
* @param videoURL
* @return any
*/
export function videoFromURL() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("videoFromURL");
return null;
}
// end Type
// Type: Audio
/**
* @param videoURL
* @return any
*/
export function fromURL() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("fromURL");
return null;
}
// end Type
// Type: BinaryFile
/**
* @param fileURL
* @return any
*/
export function binaryFileFromURL() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("binaryFileFromURL");
return null;
}
// end Type
// Type: CallOptions
// end Type
// Type: CryptoHash
/**
* @param text
* @param key
* @return any
*/
export function compute() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("compute");
return null;
}
// end Type
// Type: Geography
/**
* @return any
*/
export function geographyToString() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("geographyToString");
return null;
}
/**
* @return any
*/
export function geographyToGeoJson() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("geographyToGeoJson");
return null;
}
/**
* @return any
*/
export function geographyToWkt() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("geographyToWkt");
return null;
}
/**
* @return any
*/
export function toGeoPoint() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("toGeoPoint");
return null;
}
/**
* @return any
*/
export function toGeoLine() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("toGeoLine");
return null;
}
/**
* @return any
*/
export function toGeoPolygon() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("toGeoPolygon");
return null;
}
/**
* @return boolean
*/
export function geographyIsNull() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("geographyIsNull");
return null;
}
/**
* @return any
*/
export function geographySetNull() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("geographySetNull");
return null;
}
/**
* @return boolean
*/
export function geographyIsEmpty() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("geographyIsEmpty");
return null;
}
/**
* @return any
*/
export function geographySetEmpty() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("geographySetEmpty");
return null;
}
/**
* @return boolean
*/
export function geographyIsNullOrEmpty() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("geographyIsNullOrEmpty");
return null;
}
// end Type
// Type: GeoPoint
/**
* @return any
*/
export function geopointToGeography() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("geopointToGeography");
return null;
}
/**
* @return any
*/
export function geopointToString() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("geopointToString");
return null;
}
/**
* @return any
*/
export function geopointToGeoJson() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("geopointToGeoJson");
return null;
}
/**
* @return any
*/
export function toWKT() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("toWKT");
return null;
}
/**
* @return boolean
*/
export function geopointIsNull() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("geopointIsNull");
return null;
}
/**
* @return any
*/
export function geopointSetNull() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("geopointSetNull");
return null;
}
/**
* @return boolean
*/
export function geopointIsEmpty() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("geopointIsEmpty");
return null;
}
/**
* @return any
*/
export function geopointSetEmpty() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("geopointSetEmpty");
return null;
}
/**
* @return boolean
*/
export function geopointIsNullOrEmpty() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("geopointIsNullOrEmpty");
return null;
}
/**
* @param latitude
* @param longitude
* @return any
*/
export function newGeopoint() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("newGeopoint");
return null;
}
// end Type
// Type: GeoLine
/**
* @return any
*/
export function geolineToGeography() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("geolineToGeography");
return null;
}
/**
* @return any
*/
export function geolineToString() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("geolineToString");
return null;
}
/**
* @return any
*/
export function geolineToGeoJson() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("geolineToGeoJson");
return null;
}
/**
* @return any
*/
export function geolineToWkt() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("geolineToWkt");
return null;
}
/**
* @return boolean
*/
export function geolineIsNull() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("geolineIsNull");
return null;
}
/**
* @return any
*/
export function geolineSetNull() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("geolineSetNull");
return null;
}
/**
* @return boolean
*/
export function geolineIsEmpty() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("geolineIsEmpty");
return null;
}
/**
* @return any
*/
export function geolineSetEmpty() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("geolineSetEmpty");
return null;
}
/**
* @return boolean
*/
export function geolineIsNullOrEmpty() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("geolineIsNullOrEmpty");
return null;
}
// end Type
// Type: GeoPolygon
/**
* @return any
*/
export function geopolygonToGeography() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("geopolygonToGeography");
return null;
}
/**
* @return any
*/
export function geopolygonToString() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("geopolygonToString");
return null;
}
/**
* @return any
*/
export function geopolygonToGeoJson() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("geopolygonToGeoJson");
return null;
}
/**
* @return any
*/
export function geopolygonToWkt() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("geopolygonToWkt");
return null;
}
/**
* @return boolean
*/
export function geopolygonIsNull() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("geopolygonIsNull");
return null;
}
/**
* @return any
*/
export function geopolygonSetNull() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("geopolygonSetNull");
return null;
}
/**
* @return boolean
*/
export function geopolygonIsEmpty() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("geopolygonIsEmpty");
return null;
}
/**
* @return any
*/
export function geopolygonSetEmpty() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("geopolygonSetEmpty");
return null;
}
/**
* @return boolean
*/
export function geopolygonIsNullOrEmpty() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("geopolygonIsNullOrEmpty");
return null;
}
// end Type
// Type: WSAddressing
// end Type
// Type: WSAddressingEndPoint
// end Type
// Type: WSSecurity
// end Type
// Type: WSSignature
// end Type
// Type: WSEncryption
// end Type
// Type: WSSecurityKeyStore
// end Type
// Type: Cache
/**
* @param name
* @return any
*/
export function getCache() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("getCache");
return null;
}
/**
* @return any
*/
export function clearAllCaches() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("clearAllCaches");
return null;
}
/**
* @param key
* @param value
* @param durationMinutes
* @return any
*/
export function cacheSet() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("cacheSet");
return null;
}
/**
* @param key
* @return any
*/
export function cacheGet() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("cacheGet");
return null;
}
/**
* @param key
* @return boolean
*/
export function contains() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("contains");
return null;
}
/**
* @param key
* @return any
*/
export function remove() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("remove");
return null;
}
/**
* @return any
*/
export function clear() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("clear");
return null;
}
// end Type
// Type: StorageProvider
/**
* @param storageObjectFullName
* @param outExternalFile
* @param expirationMinutes
* @param outMessages
* @return boolean
*/
export function getPrivate() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("getPrivate");
return null;
}
/**
* @param fileFullPath
* @param storageObjectFullName
* @param outUploadedFile
* @param outMessages
* @return boolean
*/
export function uploadPrivate() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("uploadPrivate");
return null;
}
/**
* @param storageObjectFullName
* @param outExternalFile
* @param outMessages
* @return boolean
*/
export function get() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("get");
return null;
}
/**
* @param fileFullPath
* @param storageObjectFullName
* @param outUploadedFile
* @param outMessages
* @return boolean
*/
export function upload() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("upload");
return null;
}
/**
* @param storageObjectFullName
* @param outLocalFile
* @param outMessages
* @return boolean
*/
export function download() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("download");
return null;
}
/**
* @param storageObjectFullName
* @param outLocalFile
* @param outMessages
* @return boolean
*/
export function downloadPrivate() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("downloadPrivate");
return null;
}
/**
* @param storageDirectoryFullName
* @param outExternalDirectory
* @param outMessages
* @return boolean
*/
export function getDirectory() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("getDirectory");
return null;
}
// end Type
// Type: ArrayPEM
// end Type
// Type: BusinessComponentLevel
// end Type
// Type: BusinessComponent
/**
* @return any
*/
export function check() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("check");
return null;
}
/**
* @return any
*/
export function bcDelete() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("bcDelete");
return null;
}
/**
* @param primaryKeyAtt
* @return any
*/
export function load() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("load");
return null;
}
/**
* @return any
*/
export function mode() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("mode");
return null;
}
/**
* @return any
*/
export function bcSave() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("bcSave");
return null;
}
/**
* @param includeHeader
* @param includeState
* @return any
*/
export function bcToXml() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("bcToXml");
return null;
}
/**
* @param xml
* @param outMessages
* @return boolean
*/
export function bcFromXml() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("bcFromXml");
return null;
}
/**
* @param xml
* @param outMessages
* @return boolean
*/
export function bcFromXmlFile() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("bcFromXmlFile");
return null;
}
/**
* @param includeState
* @return any
*/
export function bcToJson() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("bcToJson");
return null;
}
/**
* @param source
* @param outMessages
* @return boolean
*/
export function bcFromJson() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("bcFromJson");
return null;
}
/**
* @param source
* @param outMessages
* @return boolean
*/
export function bcFromJsonFile() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("bcFromJsonFile");
return null;
}
/**
* @return boolean
*/
export function bcUpdate() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("bcUpdate");
return null;
}
/**
* @return boolean
*/
export function insert() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("insert");
return null;
}
/**
* @return boolean
*/
export function insertOrUpdate() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("insertOrUpdate");
return null;
}
/**
* @return boolean
*/
export function success() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("success");
return null;
}
/**
* @return boolean
*/
export function fail() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("fail");
return null;
}
/**
* @return any
*/
export function getMessages() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("getMessages");
return null;
}
/**
* @return any
*/
export function bcClone() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("bcClone");
return null;
}
/**
* @param name
* @return any
*/
export function createBC() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("createBC");
return null;
}
/**
* @param name
* @return any
*/
export function createCollection() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("createCollection");
return null;
}
/**
* @param name
* @return any
*/
export function bcGetValue() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("bcGetValue");
return null;
}
/**
* @param name
* @param value
* @return any
*/
export function setValue() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("setValue");
return null;
}
/**
* @return any
*/
export function getMetadata() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("getMetadata");
return null;
}
// end Type
// Type: SDT
/**
* @param includeHeader
* @param includeState
* @return any
*/
export function toXml() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("toXml");
return null;
}
/**
* @param source
* @param outMessages
* @return boolean
*/
export function fromXml() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("fromXml");
return null;
}
/**
* @param source
* @param outMessages
* @return boolean
*/
export function fromXmlFile() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("fromXmlFile");
return null;
}
/**
* @return any
*/
export function clone() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("clone");
return null;
}
/**
* @param includeState
* @return any
*/
export function toJson() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("toJson");
return null;
}
/**
* @param source
* @param outMessages
* @return boolean
*/
export function fromJson() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("fromJson");
return null;
}
/**
* @param source
* @param outMessages
* @return boolean
*/
export function fromJsonFile() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("fromJsonFile");
return null;
}
/**
* @return boolean
*/
export function sdtIsNull() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("sdtIsNull");
return null;
}
/**
* @return any
*/
export function setNull() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("setNull");
return null;
}
// end Type
// Type: SDTItem
/**
* @return any
*/
export function sdtItemToFormattedString() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("sdtItemToFormattedString");
return null;
}
// end Type
// Type: Iterator
/**
* @return any
*/
export function first() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("first");
return null;
}
/**
* @return any
*/
export function next() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("next");
return null;
}
/**
* @return boolean
*/
export function eof() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("eof");
return null;
}
// end Type
// Type:
// end Type
// Type: Void
// end Type
// Type: Timezones
// end Type
// Type: Short
// end Type
// Type: Object
// end Type
// Type: Messages
// end Type
// Type: Int
// end Type
// Type: GxControlFrame
// end Type
// Type: CallEffect
// end Type
// Type: CallType
// end Type
// Type: TargetSize
// end Type
// Type: DipOrPercentage
// end Type
// Type: GeneXusCommonUIProgress
/**
* @return any
*/
export function show() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("show");
return null;
}
/**
* @param title
* @return any
*/
export function showWithTitle() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("showWithTitle");
return null;
}
/**
* @param title
* @param description
* @return any
*/
export function showWithTitleAndDescription() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("showWithTitleAndDescription");
return null;
}
/**
* @return any
*/
export function hide() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("hide");
return null;
}
// end Type
// Type: GeneXusCommonUINavigation
// end Type
// Type: GeneXusCommonConfigurationConfigurationManager
/**
* @param propName
* @param fileName
* @return any
*/
export function getValue() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("getValue");
return null;
}
/**
* @param propName
* @param fileName
* @return boolean
*/
export function hasValue() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("hasValue");
return null;
}
// end Type
// Type: GeneXusCommonClipboard
/**
* @param data
* @return any
*/
export function setText() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("setText");
return null;
}
/**
* @return any
*/
export function getText() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("getText");
return null;
}
// end Type
// Type: GeneXusCommonAnalytics
/**
* @param viewName
* @return any
*/
export function trackView() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("trackView");
return null;
}
/**
* @param category
* @param action
* @param label
* @param value
* @return any
*/
export function trackEvent() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("trackEvent");
return null;
}
/**
* @param purchaseInfo
* @return any
*/
export function trackPurchase() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("trackPurchase");
return null;
}
/**
* @param userId
* @return any
*/
export function setAnalyticsUserId() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("setAnalyticsUserId");
return null;
}
// end Type
// Type: GeneXusCommonServer
/**
* @return any
*/
export function invalidateCache() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("invalidateCache");
return null;
}
// end Type
// Type: GeneXusCommonRuntime
// end Type
// Type: GeneXusCommonMaps
/**
* @param sourceLocation
* @param destinationLocation
* @param transportType
* @param requestAlternateRoutes
* @return any
*/
export function calculateDirections() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("calculateDirections");
return null;
}
// end Type
var GeneXusClientClientInformation = /** @class */ (function () {
function GeneXusClientClientInformation() {}
return GeneXusClientClientInformation;
})();
export { GeneXusClientClientInformation };
// Type: GeneXusClientClientStorage
/**
* @param key
* @param value
* @return any
*/
export function secureSet() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("secureSet");
return null;
}
// end Type
// Type: GeneXusSocialFacebook
/**
* @param name
* @param caption
* @param description
* @param link
* @param picture
* @return any
*/
export function postToWall() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("postToWall");
return null;
}
/**
* @param link
* @return any
*/
export function shareLink() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("shareLink");
return null;
}
/**
* @param image
* @return any
*/
export function fbShareImage() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("fbShareImage");
return null;
}
/**
* @param video
* @return any
*/
export function shareVideo() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("shareVideo");
return null;
}
// end Type
// Type: GeneXusSocialTwitter
/**
* @param text
* @param image
* @return any
*/
export function tweet() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("tweet");
return null;
}
/**
* @param userName
* @return any
*/
export function follow() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("follow");
return null;
}
// end Type
// Type: GeneXusSocialShare
/**
* @param image
* @param text
* @param url
* @param title
* @return any
*/
export function shareImage() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("shareImage");
return null;
}
// end Type
// Type: GeneXusServerSocket
/**
* @param sdtNotification
* @return number
*/
export function notify() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("notify");
return null;
}
/**
* @param clientId
* @param sdtNotification
* @return number
*/
export function notifyClient() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("notifyClient");
return null;
}
/**
* @param sdtNotification
* @return any
*/
export function broadcast() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("broadcast");
return null;
}
/**
* @param clientId
* @param message
* @return number
*/
export function notifyClientText() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("notifyClientText");
return null;
}
// end Type
// Type: GeneXusSDSynchronizationSynchronization
// end Type
// Type: GeneXusSDiOSPermissions
/**
* Requests permission to alert the user. Typically, you make this request if your app uses local or push notifications to alert the user to new information involving your app.
* @return any
*/
export function requestUserNotificationsPermission() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("requestUserNotificationsPermission");
return null;
}
/**
* Requests permission to use location services while the app is in the foreground.
* @return any
*/
export function requestLocationPermissionWhenInUse() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("requestLocationPermissionWhenInUse");
return null;
}
/**
* Requests permission to use location services whenever the app is running.
* @return any
*/
export function requestLocationPermissionAlways() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("requestLocationPermissionAlways");
return null;
}
/**
* Deprecated. Use RequestUserNotificationsPermission instead.
* @return any
*/
export function requestRemoteNotificationsPermission() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("requestRemoteNotificationsPermission");
return null;
}
// end Type
// Type: GeneXusSDStoreStoreManager
/**
* @param productIdentifiers
* @return any
*/
export function getProducts() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("getProducts");
return null;
}
/**
* @param productIdentifier
* @param quantity
* @return any
*/
export function purchaseProduct() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("purchaseProduct");
return null;
}
/**
* @return any
*/
export function getPurchases() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("getPurchases");
return null;
}
/**
* @param productIdentifier
* @return boolean
*/
export function consumeProduct() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("consumeProduct");
return null;
}
/**
* Restore transactions (iOS only)
* @return any
*/
export function restorePurchases() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("restorePurchases");
return null;
}
// end Type
// Type: GeneXusSDNotificationsNotificationsConfiguration
// end Type
// Type: GeneXusSDNotificationsRemoteNotificationResult
// end Type
// Type: GeneXusSDNotificationsNotificationParameters
/**
* @param name
* @param value
* @return any
*/
export function setParameter() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("setParameter");
return null;
}
// end Type
// Type: GeneXusSDNotificationsRemoteNotifications
/**
* @param applicationId
* @param deviceType
* @param deviceToken
* @param alertMessage
* @return number
*/
export function call() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("call");
return null;
}
/**
* @param applicationId
* @param deviceToken
* @param badgeNumber
* @param sound
* @return number
*/
export function iOSSetBadge() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("iOSSetBadge");
return null;
}
/**
* @param applicationId
* @param deviceToken
* @return number
*/
export function iOSResetBadge() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("iOSResetBadge");
return null;
}
/**
* @param applicationId
* @param deviceType
* @param deviceToken
* @param alertMessage
* @param actionName
* @param parameters
* @return any
*/
export function callAction() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("callAction");
return null;
}
/**
* @param applicationId
* @return number
*/
export function openSession() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("openSession");
return null;
}
/**
* @param remoteNotification
* @return any
*/
export function remoteNotificationAdd() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("remoteNotificationAdd");
return null;
}
/**
* @return any
*/
export function send() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("send");
return null;
}
/**
* @param applicationId
* @param configuration
* @return any
*/
export function setConfiguration() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("setConfiguration");
return null;
}
// end Type
// Type: GeneXusSDNotificationsLocalNotifications
/**
* @param alerts
* @return number
*/
export function createAlerts() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("createAlerts");
return null;
}
/**
* @return any
*/
export function listAlerts() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("listAlerts");
return null;
}
/**
* @param alerts
* @return number
*/
export function removeAlerts() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("removeAlerts");
return null;
}
/**
* @return number
*/
export function removeAllAlerts() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("removeAllAlerts");
return null;
}
// end Type
// Type: GeneXusSDMediaCamera
/**
* @param videoQuality
* @return any
*/
export function recordVideo() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("recordVideo");
return null;
}
// end Type
// Type: GeneXusSDMediaPhotoLibrary
/**
* @param image
* @return any
*/
export function savePhoto() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("savePhoto");
return null;
}
/**
* @param video
* @return any
*/
export function saveVideo() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("saveVideo");
return null;
}
/**
* @return any
*/
export function chooseImage() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("chooseImage");
return null;
}
/**
* @return any
*/
export function chooseVideo() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("chooseVideo");
return null;
}
/**
* @return any
*/
export function chooseImages() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("chooseImages");
return null;
}
// end Type
// Type: GeneXusSDMediaAudio
/**
* Plays the given audio with the specified category
* @param audio
* @param category
* @return any
*/
export function play() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("play");
return null;
}
/**
* Plays the given audio in background, keeps playing while the application is in background
* @param audio
* @param description
* @return any
*/
export function playBackground() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("playBackground");
return null;
}
/**
* Stops the audio playing in all categories
* @param category
* @return any
*/
export function audioStop() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("audioStop");
return null;
}
/**
* Returns whether there is audio playing in any category
* @param category
* @return boolean
*/
export function isPlaying() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("isPlaying");
return null;
}
/**
* Returns the current audio queue.
* @return any
*/
export function getQueue() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("getQueue");
return null;
}
/**
* Returns the state of the current audio queue (including the position in the queue and inside the current playing item, if any).
* @return any
*/
export function getQueueState() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("getQueueState");
return null;
}
/**
* Sets the current audio queue. Stops current background playback, if any.
* @param queue
* @return any
*/
export function setQueue() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("setQueue");
return null;
}
/**
* Starts or resumes playback of the current audio queue.
* @return any
*/
export function playQueue() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("playQueue");
return null;
}
/**
* Pauses playback of the current audio queue.
* @return any
*/
export function pauseQueue() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("pauseQueue");
return null;
}
/**
* Sets the current item in the media queue, given its media id.
* @param mediaId
* @return any
*/
export function setQueueCurrentItem() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("setQueueCurrentItem");
return null;
}
/**
* Sets the current item in the media queue, given its index.
* @param index
* @return any
*/
export function setQueueCurrentIndex() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("setQueueCurrentIndex");
return null;
}
/**
* Allows configuring the audio player UI settings
* @param settings
* @return any
*/
export function setPlayerSettings() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("setPlayerSettings");
return null;
}
/**
* @param show
* @return any
*/
export function iOSSetShowsMiniPlayer() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("iOSSetShowsMiniPlayer");
return null;
}
/**
* @return any
*/
export function iOSDisplayFullScreenPlayer() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("iOSDisplayFullScreenPlayer");
return null;
}
/**
* @return any
*/
export function iOSDismissFullScreenPlayer() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("iOSDismissFullScreenPlayer");
return null;
}
// end Type
// Type: GeneXusSDMediaAudioRecorder
/**
* Starts a recording session. Returns True if the operation was successful, False otherwise
* @return boolean
*/
export function start() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("start");
return null;
}
/**
* Stops the recording session and returns the URL of the recorder file.
* @return any
*/
export function stop() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("stop");
return null;
}
// end Type
// Type: GeneXusSDActions
/**
* Call this action to execute the standard batch login against the OAuth server.
* @param user
* @param password
* @param additionalParameters
* @return boolean
*/
export function login() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("login");
return null;
}
/**
* Call this action to execute the batch login against the OAuth server for a External login type.
* @param type
* @param user
* @param password
* @param additionalParameters
* @return boolean
*/
export function loginExternal() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("loginExternal");
return null;
}
/**
* Call this action to execute the standard logout against the OAuth server.
* @return any
*/
export function logout() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("logout");
return null;
}
/**
* Returns to the main object of the application, clearing the current call stack.
* @return any
*/
export function goHome() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("goHome");
return null;
}
/**
* Returns to the object specified in the parameter. If it is present more than once in the call stack, it will return to the most recent instance.
* @param objectName
* @return any
*/
export function returnTo() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("returnTo");
return null;
}
/**
* Call this action to execute the standard save in the edit form in the device.
* @return any
*/
export function save() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("save");
return null;
}
/**
* Call this action to execute the standard cancel in the edit form in the device.
* @return any
*/
export function cancel() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("cancel");
return null;
}
/**
* Call this action to execute the standard delete in the edit form in the device.
* @return any
*/
export function deleteAction() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("deleteAction");
return null;
}
/**
* Takes an application screenshot for further use like sharing, save in library, etc.
* @return any
*/
export function takeApplicationScreenshot() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("takeApplicationScreenshot");
return null;
}
// end Type
// Type: GeneXusSDContacts
/**
* Adds a contact to the device's Address Book
* @param firstName
* @param lastName
* @param eMail
* @param phone
* @param companyName
* @param photo
* @param message
* @return boolean
*/
export function addContact() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("addContact");
return null;
}
/**
* @param firstName
* @param lastName
* @param eMail
* @param phone
* @param message
* @return boolean
*/
export function removeContact() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("removeContact");
return null;
}
/**
* @param firstName
* @param lastName
* @param eMail
* @param phone
* @return any
*/
export function viewContact() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("viewContact");
return null;
}
/**
* Returns a collection of all the contacts in the device's Address Book
* @return any
*/
export function getAllContacts() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("getAllContacts");
return null;
}
// end Type
// Type: GeneXusSDCalendar
// end Type
// Type: GeneXusSDInterop
/**
* @param message
* @param to
* @return any
*/
export function sendMessage() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("sendMessage");
return null;
}
/**
* @param video
* @return any
*/
export function playVideo() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("playVideo");
return null;
}
/**
* @param audio
* @return any
*/
export function playAudio() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("playAudio");
return null;
}
/**
* @param to
* @param cc
* @param bcc
* @param subject
* @param message
* @return any
*/
export function sendEmailAdvanced() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("sendEmailAdvanced");
return null;
}
/**
* @param to
* @param message
* @return any
*/
export function sendSMS() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("sendSMS");
return null;
}
/**
* @return any
*/
export function clearCache() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("clearCache");
return null;
}
/**
* Deprecated: use Interop.SetBadgeNumber instead
* @param num
* @return any
*/
export function iOSSetBadgeNumber() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("iOSSetBadgeNumber");
return null;
}
/**
* @param num
* @return any
*/
export function setBadgeNumber() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("setBadgeNumber");
return null;
}
/**
* @param tabIndex
* @return any
*/
export function iOSSetSelectedTabIndex() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("iOSSetSelectedTabIndex");
return null;
}
// end Type
// Type: GeneXusSDScanner
/**
* @param barcodeTypes
* @return any
*/
export function scanBarcode() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("scanBarcode");
return null;
}
/**
* @param beepOnEachRead
* @param barcodeTypes
* @return any
*/
export function scanInLoop() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("scanInLoop");
return null;
}
// end Type
var GeneXusSDNetwork = /** @class */ (function () {
function GeneXusSDNetwork() {}
/**
* @param url
* @return boolean
*/
GeneXusSDNetwork.isServerAvailable = function () {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("isServerAvailable");
return null;
};
/**
* @param url
* @return any
*/
GeneXusSDNetwork.type = function () {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("type");
return null;
};
/**
* @param url
* @return boolean
*/
GeneXusSDNetwork.trafficBasedCost = function () {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("trafficBasedCost");
return null;
};
/**
* If the property Dynamic Services URL is set to True, changes the URL at runtime.
* @param url
* @return any
*/
GeneXusSDNetwork.setApplicationServerURL = function () {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("setApplicationServerURL");
return null;
};
return GeneXusSDNetwork;
})();
export { GeneXusSDNetwork };
// Type: GeneXusSDBeacons
/**
* Start monitoring the specified beacon region.
* @param proximityAlert
* @return boolean
*/
export function addBeaconProximityAlert() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("addBeaconProximityAlert");
return null;
}
/**
* Start monitoring the specified beacon regions.
* @param proximityAlerts
* @return boolean
*/
export function addBeaconProximityAlerts() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("addBeaconProximityAlerts");
return null;
}
/**
* Retrieve a collection for the beacon regions that are currently being monitored.
* @return any
*/
export function getBeaconProximityAlerts() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("getBeaconProximityAlerts");
return null;
}
/**
* Removes the beacon region being monitored.
* @param proximityAlertRegionId
* @return any
*/
export function removeBeaconProximityAlert() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("removeBeaconProximityAlert");
return null;
}
/**
* Removes all the beacon regions being monitored.
* @return any
*/
export function clearBeaconProximityAlerts() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("clearBeaconProximityAlerts");
return null;
}
/**
* Retrieve the cached state of the specified region.
* @param regionId
* @return any
*/
export function getBeaconRegionState() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("getBeaconRegionState");
return null;
}
/**
* Starts the delivery of notifications for beacons in the specified region.
* @param beaconRegion
* @return boolean
*/
export function startRangingBeaconRegion() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("startRangingBeaconRegion");
return null;
}
/**
* Retrieve a collection for the beacon regions that are currently providing ranging.
* @return any
*/
export function getRangedBeaconRegions() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("getRangedBeaconRegions");
return null;
}
/**
* Stops the delivery of notifications for the specified beacon region.
* @param regionId
* @return any
*/
export function stopRangingBeaconRegion() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("stopRangingBeaconRegion");
return null;
}
/**
* Retrieve a collection for the beacons (sorted by proximity) currently in range for the given region.
* @param regionId
* @return any
*/
export function getBeaconsInRange() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("getBeaconsInRange");
return null;
}
/**
* Advertises the current device as a beacon.
* @param beaconInfo
* @return boolean
*/
export function startAsBeacon() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("startAsBeacon");
return null;
}
/**
* Stops advertising the current device as a beacon.
* @return boolean
*/
export function stopAsBeacon() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("stopAsBeacon");
return null;
}
// end Type
// Type: GeneXusSDSearch
// end Type
// Type: GeneXusSDDeepLink
// end Type
// Type: GeneXusSDWebBrowser
/**
* Opens the give URL in the InApp Browser
* @param url
* @return any
*/
export function webBrowserOpen() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("webBrowserOpen");
return null;
}
/**
* Closes the InApp Browser
* @return any
*/
export function close() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("close");
return null;
}
// end Type
// Type: GeneXusSDDeviceAuthentication
/**
* Returns True if the API can be used in the current device, False otherwise
* @param method
* @return boolean
*/
export function isAvailable() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("isAvailable");
return null;
}
/**
* Performs the authentication step, using the method that corresponds for the current device.
* @param method
* @param title
* @param usageDescription
* @return boolean
*/
export function authenticate() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("authenticate");
return null;
}
// end Type
// Type: GeneXusSDAppLifecycle
// end Type
// Type: GeneXusSDCardScanner
/**
* @return any
*/
export function scanCard() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
notImplemented("scanCard");
return null;
}
// end Type
// Type: BlobFile
// end Type
//# sourceMappingURL=not_implemented.js.map
|
gravyhtx/vot-html-test
|
client/src/components/Header.js
|
<reponame>gravyhtx/vot-html-test
import { useState, useEffect } from "react";
import { Link, useLocation } from "react-router-dom";
import Logo from "../images/header.svg";
import NotificationBar from './NotificationBar';
import SiteData from "../config/site-data.json"
import Auth from '../utils/auth';
import { getSingleUser } from '../utils/API';
const Header = () => {
let notificationBar = document.getElementById('notification-bar')
// Get User Data
const [userData, setUserData] = useState({});
const userDataLength = Object.keys(userData).length;
useEffect(() => {
const getUserData = async () => {
try {
const token = Auth.loggedIn() ? Auth.getToken() : null;
const response = await getSingleUser(token);
// console.log(token)
if(!response.ok){
throw new Error('something went wrong!');
}
const user = await response.json();
setUserData(user);
} catch (err) {
console.error(err);
}
// notificationBar.classList.remove('hide');
};
// console.log(userData)
getUserData();
}, [userDataLength]);
// const getWallet = localStorage.getItem('-walletlink:https://www.walletlink.org:Addresses');
let siteName = SiteData.name;
let abbv = SiteData.abbreviation.toLowerCase();
let notification;
const headerLink = "/"
const notificationLink = "/register"
const location = useLocation();
const { pathname } = location;
const splitLocation = pathname.split("/");
notification=
<>
Create your account today and get a <u>FREE</u> Limited Edition VoT NFT!
<span className="info-icon" id="info-icon">
<i className="material-icons info-icon">info_outline</i>
</span>
</>;
return (
<header className="site-header" id="site-header">
<div className="navbar-container black" id="header-container">
<Link className="navbar-brand container" to={headerLink} id="header-link-container">
<div className="header-img-container" id="header-img-container">
<img
src={Logo}
className={splitLocation[1] === "" ? "header-img animate__animated animate__fadeInDown "+abbv+"-txt-header" : abbv+"-txt-header header-img"}
id="header-img"
draggable="false"
alt={siteName ? siteName+" Logo" : "Website Logo"} />
</div>
</Link>
{userData.walletAddress?<></>
:<div id="notification-bar"><NotificationBar text={notification} link={notificationLink} /></div>
}
</div>
</header>
);
}
export default Header;
|
turlodales/theos-projects
|
app_dumps/NEWVKClient.folder/PendingChatCell.h
|
<gh_stars>10-100
/**
* This header is generated by class-dump-z 0.2-0.
* class-dump-z is Copyright (C) 2009 by KennyTM~, licensed under GPLv3.
*
* Source: (null)
*/
#import "ChatCell.h"
#import "VKClient-Structs.h"
@class PendingMessage, UIButton, UIActivityIndicatorView;
__attribute__((visibility("hidden")))
@interface PendingChatCell : ChatCell {
PendingMessage* _pending;
UIActivityIndicatorView* _activity;
UIButton* _warning;
}
@property(retain, nonatomic) UIButton* warning;
@property(retain, nonatomic) UIActivityIndicatorView* activity;
@property(retain, nonatomic) PendingMessage* pending;
-(void).cxx_destruct;
-(void)attachPending:(id)pending expectedReuse:(double)reuse;
-(void)update;
-(void)actionWarning:(id)warning;
-(id)initWithDelegate:(id)delegate selfdialog:(BOOL)selfdialog reuseIdentifier:(id)identifier;
@end
|
davidlee80/amd-gpuperfstudio-dx12
|
GPUPerfStudio/Server/Common/NamedEvent.h
|
//==============================================================================
// Copyright (c) 2013-2015 Advanced Micro Devices, Inc. All rights reserved.
/// \author AMD Developer Tools Team
/// \file
/// \brief An interface to a named event class. The event is
/// global systemwide, so can be accessed across threads and processes
/// by its name. Each process will need its own copy of the event
///
/// The current implementation expected by perf studio is a manual-reset
/// event. Events have to be explicitly set to the non-signaled state.
/// This means that multiple waiting threads can respond to the signaled
/// state until it is reset
/// This system will have to change as it isn't supported by Linux, which
/// uses auto-reset, meaning that one waiting thread will be woken up
/// and the event will be set to non-signaled automatically.
//==============================================================================
#ifndef GPS_NAMEDEVENT_H
#define GPS_NAMEDEVENT_H
#include "misc.h"
// forward declaration to implementation class
class NamedEventImpl;
class NamedEvent
{
public:
NamedEvent();
~NamedEvent();
//--------------------------------------------------------------------------
/// Create a system-wide event
/// \param eventName the name this event will be known by
/// \param signaled if true, the event will be created in the signaled state
///
/// \return true if Create succeeded, false if error
//--------------------------------------------------------------------------
bool Create(const char* eventName, bool signaled = false);
//--------------------------------------------------------------------------
/// Open a previously created system-wide event
/// \param eventName the name this event is be known by (the name it was
/// given when created)
/// \param inherit if true, processes created by this process will inherit
/// the event
///
/// \return true if Open succeeded, false if event doesn't exist
//--------------------------------------------------------------------------
bool Open(const char* eventName, bool inherit = false);
//--------------------------------------------------------------------------
/// Wait for a signal/event to happen. This function won't return until it
/// receives a signal
///
/// \return true if successful, false if error
//--------------------------------------------------------------------------
bool Wait();
//--------------------------------------------------------------------------
/// Set the event to the signaled state. Any other threads/processes waiting
/// for the signal can now proceed.
///
/// \return true if successful, false if error
//--------------------------------------------------------------------------
bool Signal();
//--------------------------------------------------------------------------
/// Is the event in the Signaled state. Does not block or wait but returns
/// immediately
///
/// \return true if currently signaled, false if not
//--------------------------------------------------------------------------
bool IsSignaled();
//--------------------------------------------------------------------------
/// reset the event to non-signaled
//--------------------------------------------------------------------------
void Reset();
//--------------------------------------------------------------------------
/// close the event
//--------------------------------------------------------------------------
void Close();
private:
/// copy constructor made private; Prevent making copies of this object
NamedEvent(const NamedEvent& rhs)
{
PS_UNREFERENCED_PARAMETER(rhs);
}
/// assignment operator made private; Prevent making copies of this object
NamedEvent& operator= (const NamedEvent& rhs)
{
PS_UNREFERENCED_PARAMETER(rhs);
return *this;
}
/// pointer to implementation. Dependent on platform
NamedEventImpl* m_pImpl;
};
#endif // GPS_NAMEDEVENT_H
|
spurious/safecode-mirror
|
lib/SpeculativeChecking/Caching.cpp
|
<reponame>spurious/safecode-mirror<gh_stars>1-10
//===- Caching.cpp: -------------------------------------------------------===//
//
// The SAFECode Compiler
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
//===----------------------------------------------------------------------===//
#include <set>
#include <map>
#include "llvm/Module.h"
#include "llvm/Pass.h"
#include "llvm/Instructions.h"
using namespace llvm;
namespace {
class PoolCaching : public ModulePass {
std::map<Value*, Value*> PoolSources;
std::set<Value*> Pools;
void findPools(Module& M) {
for (Module::iterator MI = M.begin(), ME = M.end(); MI != ME; ++MI)
if (!MI->isDeclaration())
for (Function::iterator FI = MI->begin(), FE = MI->end(); FI != FE; ++FI)
for (BasicBlock::iterator BI = FI->begin(), BE = FI->end(); BI != BE; ++BI)
if (CallInst* CI = dyn_cast<CallInst>(BI))
if (Function* F = dyn_cast<Function>(CI->getOperand(0))) {
if (F->getName() == "__sc_par_poolcheck") {
Pools.insert(CI->getOperand(1));
} else if (F->getName() == "__sc_par_boundscheck") {
Pools.insert(CI->getOperand(1));
} else if (F->getName() == "__sc_par_poolinit") {
Pools.insert(CI->getOperand(1));
}
}
}
void findPoolSources() {
unsigned numPools;
do {
numPools = Pools.size();
for (std::set<Value*>::iterator ii = Pools.begin(); ii != Pools.end(); ++ii) {
(*ii)->dump();
}
} while (numPools != Pools.size());
}
public:
static char ID;
PoolCaching() : ModulePass((intptr_t)&ID) {}
bool runOnModule(Module& M) {
findPools(M);
findPoolSources();
return true;
}
};
}
char PoolCaching::ID = 0;
static RegisterPass<PoolCaching> X
("sc-par-poolcache", "Use Checking Thread caches");
|
sadewole/Auth-Oauth
|
dist/models/order.js
|
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports["default"] = void 0;
var _default = function _default(sequelize, DataTypes) {
var Order = sequelize.define('Order', {
id: {
type: DataTypes.UUID,
allowNull: false,
primaryKey: true
},
quantity: {
type: DataTypes.INTEGER,
allowNull: false
},
amount: {
type: DataTypes.INTEGER,
allowNull: false
},
email: DataTypes.STRING,
address: DataTypes.STRING,
orderedDate: DataTypes.DATE,
phone: DataTypes.STRING,
status: DataTypes.STRING,
payment: DataTypes.STRING
});
Order.associate = function (models) {
Order.belongsTo(models.User, {
foreignKey: 'user_id',
onDelete: 'CASCADE'
});
Order.belongsTo(models.Menu, {
foreignKey: 'menu_id',
onDelete: 'CASCADE'
});
};
return Order;
};
exports["default"] = _default;
|
Kuangcp/JavaBase
|
network/src/main/java/com/github/kuangcp/bio/onechatone/ServerThread.java
|
package com.github.kuangcp.bio.onechatone;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;
/**
* Created by Myth on 2017/4/3 0003
*/
public class ServerThread extends Thread{
private Socket socket;
BufferedReader br = null;
PrintStream ps = null;
public ServerThread(Socket socket){
this.socket = socket;
}
public void run(){
try{
br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
ps = new PrintStream(socket.getOutputStream());
String line = null;
while((line=br.readLine())!=null){
//如果读到的行以标识符 USER_ROUND 开始的,并以这个结束,就可以确定读到的是用户登录的登录名
if(line.startsWith(ChatProtocol.USER_ROUND) && line.endsWith(ChatProtocol.USER_ROUND)){
String userName = getRealMsg(line);
if(Server.clients.map.containsKey(userName)){
System.out.println("用户名重复");
ps.println(ChatProtocol.NAME_REP);
}else{
System.out.println("成功");
ps.println(ChatProtocol.LOGIN_SUCCESS);
Server.clients.put(userName,ps);
}
//如果标记为私聊信息,私聊信息只向特定的输出流发送
}else if(line.startsWith(ChatProtocol.PRIVATE_ROUND) && line.endsWith(ChatProtocol.PRIVATE_ROUND)){
String userAndMsg = getRealMsg(line);
//正则信息,分出用户,信息
String user = userAndMsg.split(ChatProtocol.SPLIT_SIGN)[0];
String msg = userAndMsg.split(ChatProtocol.SPLIT_SIGN)[1];
//获取私聊用户对应的输出流,发送私聊信息
Server.clients.map.get(user).println(Server.clients.getKeyByValue(ps)+"悄悄对你说 : "+msg);
//公聊就对每个Socket发送
}else{
//得到真实消息
String msg = getRealMsg(line);
//遍历所有输出流
for (PrintStream clientPs : Server.clients.valueSet()) {
clientPs.println(Server.clients.getKeyByValue(ps)+" 说 "+msg);
}
}
}
//有异常说明 Socket对应的客户端出现了问题 就要删除它
}catch (Exception e){
Server.clients.removeByValue(ps);
System.out.println(Server.clients.map.size());
try{
if(br!=null) br.close();
if(ps!=null) ps.close();
if(socket!=null) socket.close();
}catch (Exception es){
es.printStackTrace();
}
e.printStackTrace();
}
}
//去除标识符,得到真实的信息
private String getRealMsg(String line) {
return line.substring(ChatProtocol.PROTOCOL_LEN,line.length()-ChatProtocol.PROTOCOL_LEN);
}
}
|
gunishmatta/Course
|
tasks/task-9/code/frontend/src/components/WebsiteList.js
|
<reponame>gunishmatta/Course<gh_stars>10-100
import React, { Component } from 'react';
import { connect } from 'react-redux';
import axios from 'axios';
import { getWebsites } from '../actions';
import Website from './Website';
class WebsiteList extends Component {
componentDidMount(){
let token = sessionStorage.getItem('token');
axios.get('/websites/list', { headers: { 'Authorization': token } })
.then(websites => {
this.props.getWebsites(websites)
})
.catch(err => alert(err.response.data.msg));
}
render() {
return (
<div className="websites">
<h1>Websites</h1>
{
this.props.user.websites.reverse().map(website =>
<Website
key={website.id}
name={website.name}
url={website.url}
status={website.status}
/>
)
}
</div>
);
}
}
const mapStateToProps = state => {
return {
user: state.user
}
}
const mapDispatchToProps = {
getWebsites
}
export default connect(mapStateToProps, mapDispatchToProps)(WebsiteList);
|
gcodebackups/cortex-vfx
|
include/IECore/SpherePrimitive.h
|
//////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2008-2013, 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 Image Engine Design 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.
//
//////////////////////////////////////////////////////////////////////////
#ifndef IECORE_SPHEREPRIMITIVE_H
#define IECORE_SPHEREPRIMITIVE_H
#include "IECore/Primitive.h"
#include "IECore/VectorTypedData.h"
namespace IECore
{
/// SpherePrimitive represents a renderable parametric sphere
/// \ingroup geometryGroup
class SpherePrimitive : public Primitive
{
public:
IE_CORE_DECLAREOBJECT( SpherePrimitive, Primitive );
/// Construct a full sphere of radius 1.
SpherePrimitive();
/// Construct a sphere with specified parameterisation. zMin and zMax differ from the Renderman specification
/// slightly in that they're given as a proportion of that radius, so they should fall within the range [-1, 1 ]
SpherePrimitive( float radius, float zMin = -1.0f, float zMax = 1.0f, float thetaMax = 360.0f );
//! @name Sphere geometry access
/// These functions allow access to get and set the sphere's geometry after construction.
/////////////////////////////////////////////////////////////////////////////
//@{
float radius() const;
float zMin() const;
float zMax() const;
/// The returned value is specified in degrees
float thetaMax() const;
void setRadius( float r );
void setZMin( float zm );
void setZMax( float zm );
/// The value of thetaMax shoud be specified in degrees
void setThetaMax( float tm );
//@}
virtual size_t variableSize( PrimitiveVariable::Interpolation interpolation ) const;
virtual Imath::Box3f bound() const;
/// Render the sphere
virtual void render( Renderer *renderer ) const;
virtual void topologyHash( MurmurHash &h ) const;
private:
static const unsigned int m_ioVersion;
float m_radius;
float m_zMin;
float m_zMax;
float m_thetaMax;
};
IE_CORE_DECLAREPTR( SpherePrimitive );
}
#endif // IECORE_SPHEREPRIMITIVE
|
1067511899/tornado-learn
|
callbacklearn/pycallgraph/exceptions.py
|
<filename>callbacklearn/pycallgraph/exceptions.py
class PyCallGraphException(Exception):
pass
|
thautwarm/restrain-jit
|
tests/bejl/test_instructions.py
|
from restrain_jit.bejulia.julia_vm import JuVM, UnwindBlock, App, Repr, Reg, Const
from restrain_jit.jit_info import PyCodeInfo
from restrain_jit.bejulia.tools import show_instrs
jit = JuVM.func_info
@jit
def f(x, y):
pass
show_instrs(f.__func_info__.r_codeinfo.instrs)
#
# @jit
# def func1(x):
# x[:2] = 1
#
#
# show_instrs(func1.__func_info__.r_codeinfo.instrs)
|
2k13yr/telegram-1
|
app/src/main/java/org/telegram/android/base/SmileyActivity.java
|
package org.telegram.android.base;
import android.content.Context;
import android.graphics.PixelFormat;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.*;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ScrollView;
import org.telegram.android.R;
import org.telegram.android.fragments.interfaces.SmileysController;
import org.telegram.android.ui.EmojiProcessor;
import org.telegram.android.ui.Smileys;
import org.telegram.android.ui.SmileysView;
import com.viewpagerindicator.UnderlinePageIndicator;
import org.telegram.android.ui.TelegramContextWrapper;
/**
* Author: <NAME>
* Created: 03.09.13 18:13
*/
public class SmileyActivity extends TelegramActivity implements SmileysController, ViewTreeObserver.OnGlobalLayoutListener {
private View smileysView;
private WindowManager windowManager;
private DisplayMetrics metrics;
private EditText input;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
metrics = getResources().getDisplayMetrics();
windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
}
@Override
protected void onPause() {
super.onPause();
if (Build.VERSION.SDK_INT >= 16) {
getWindow().getDecorView().getViewTreeObserver().removeOnGlobalLayoutListener(this);
} else {
getWindow().getDecorView().getViewTreeObserver().removeGlobalOnLayoutListener(this);
}
hideSmileysPopup();
}
@Override
protected void onResume() {
super.onResume();
getWindow().getDecorView().getViewTreeObserver().addOnGlobalLayoutListener(this);
}
public void doAddSmiley(String text) {
int selectionEnd = input.getSelectionEnd();
if (selectionEnd < 0) {
selectionEnd = input.getText().length();
}
if (input.getText().toString().trim().length() == 0) {
if (application.isRTL()) {
text = "\u200F" + text;
} else {
text = "\u200E" + text;
}
}
CharSequence appendString = application.getEmojiProcessor().processEmojiMutable(text,
EmojiProcessor.CONFIGURATION_BUBBLES);
input.getText().insert(selectionEnd, appendString);
}
public void doDeleteText() {
input.dispatchKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DEL));
}
@Override
public boolean areSmileysVisible() {
return smileysView != null;
}
private void updateSmileysTabs(View smileysView, int page) {
if (page == 0) {
((ImageButton) smileysView.findViewById(R.id.smileyTab1))
.setImageResource(R.drawable.msg_smile_section1_active);
} else {
((ImageButton) smileysView.findViewById(R.id.smileyTab1))
.setImageResource(R.drawable.msg_smile_section1_normal);
}
if (page == 1) {
((ImageButton) smileysView.findViewById(R.id.smileyTab2))
.setImageResource(R.drawable.msg_smile_section2_active);
} else {
((ImageButton) smileysView.findViewById(R.id.smileyTab2))
.setImageResource(R.drawable.msg_smile_section2_normal);
}
if (page == 2) {
((ImageButton) smileysView.findViewById(R.id.smileyTab3))
.setImageResource(R.drawable.msg_smile_section3_active);
} else {
((ImageButton) smileysView.findViewById(R.id.smileyTab3))
.setImageResource(R.drawable.msg_smile_section3_normal);
}
if (page == 3) {
((ImageButton) smileysView.findViewById(R.id.smileyTab4))
.setImageResource(R.drawable.msg_smile_section5_active);
} else {
((ImageButton) smileysView.findViewById(R.id.smileyTab4))
.setImageResource(R.drawable.msg_smile_section5_normal);
}
if (page == 4) {
((ImageButton) smileysView.findViewById(R.id.smileyTab5))
.setImageResource(R.drawable.msg_smile_section4_active);
} else {
((ImageButton) smileysView.findViewById(R.id.smileyTab5))
.setImageResource(R.drawable.msg_smile_section4_normal);
}
}
public int getStatusBarHeight() {
int result = 0;
int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
if (resourceId > 0) {
result = getResources().getDimensionPixelSize(resourceId);
}
return result;
}
public int getActionBarHeight() {
TypedValue tv = new TypedValue();
if (getTheme().resolveAttribute(com.actionbarsherlock.R.attr.actionBarSize, tv, true)) {
return TypedValue.complexToDimensionPixelSize(tv.data, getResources().getDisplayMetrics());
}
return 0;
}
private boolean isSmilesVisible = false;
@Override
public void showSmileys(EditText dest) {
input = dest;
View root = findViewById(R.id.fragmentContainer);
int heightDiff = root.getRootView().getHeight() - root.getHeight() - getStatusBarHeight() - getActionBarHeight();
int heightDp = (int) (heightDiff / getResources().getDisplayMetrics().density);
if (heightDp > 100) {
if (smileysView == null) {
showSmileysPopup(heightDp);
} else {
hideSmileysPopup();
}
} else {
isSmilesVisible = true;
dest.requestFocus();
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(dest, InputMethodManager.SHOW_IMPLICIT);
}
}
private void toggleFullscreen(boolean fullscreen) {
WindowManager.LayoutParams attrs = getWindow().getAttributes();
if (fullscreen) {
attrs.flags |= WindowManager.LayoutParams.FLAG_FULLSCREEN;
} else {
attrs.flags &= ~WindowManager.LayoutParams.FLAG_FULLSCREEN;
}
getWindow().setAttributes(attrs);
}
@Override
public void hideSmileys() {
hideSmileysPopup();
}
@Override
public void onGlobalLayout() {
View root = findViewById(R.id.fragmentContainer);
int heightDiff = root.getRootView().getHeight() - root.getHeight() - getStatusBarHeight() - getActionBarHeight();
int heightDp = (int) (heightDiff / getResources().getDisplayMetrics().density);
if (heightDp > 100) {
if (isSmilesVisible) {
isSmilesVisible = false;
showSmileysPopup(heightDp);
}
// toggleFullscreen(true);
// getSupportActionBar().hide();
} else {
hideSmileysPopup();
// toggleFullscreen(false);
// getSupportActionBar().show();
}
}
protected int getPx(float dp) {
return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, metrics);
}
protected int getDp(float px) {
return (int) (px / getResources().getDisplayMetrics().density);
}
private void showSmileysPopup(final int keyboardHeight) {
if (smileysView != null) {
return;
}
int maxWidth = getDp(getWindow().getDecorView().getWidth());
final int countInRow = Math.min((int) (Math.floor(maxWidth / 48.0f)), 12);
smileysView = View.inflate(this, R.layout.overlay_smileys_new, null);
smileysView.findViewById(R.id.backspaceButton).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
doDeleteText();
}
});
final ViewPager pager = (ViewPager) smileysView.findViewById(R.id.smileysPages);
final Context context = new TelegramContextWrapper(this);
final LayoutInflater inflater = getLayoutInflater().cloneInContext(context);
pager.setAdapter(new PagerAdapter() {
private long[] getSmileys(int pos) {
switch (pos) {
default:
case 0:
return application.getUiKernel().getLastEmoji().getLastSmileys();
case 1:
return Smileys.STANDART;
case 2:
return Smileys.NATURE;
case 3:
return Smileys.TRANSPORT;
case 4:
return Smileys.UNSORTED;
}
}
@Override
public Object instantiateItem(ViewGroup container, int position) {
long[] smileys = getSmileys(position);
if (smileys.length > 0) {
View res = inflater.inflate(R.layout.overlay_smileys_container, container, false);
SmileysView mainSmileys = new SmileysView(SmileyActivity.this, application.getEmojiProcessor(),
smileys,
countInRow, getPx(48), getPx(8));
mainSmileys.setOnSmileClickedListener(new SmileysView.OnSmileClickedListener() {
@Override
public void onSmileClicked(long smileId) {
String smile = null;
char a = (char) (smileId & 0xFFFFFFFF);
char b = (char) ((smileId >> 16) & 0xFFFFFFFF);
char c = (char) ((smileId >> 32) & 0xFFFFFFFF);
char d = (char) ((smileId >> 48) & 0xFFFFFFFF);
if (c != 0 && d != 0) {
smile = "" + d + c + b + a;
} else if (b != 0) {
smile = b + "" + a;
} else {
smile = "" + a;
}
doAddSmiley(smile);
}
});
ScrollView.LayoutParams layoutParams = new ScrollView.LayoutParams(getPx(48) * countInRow,
ViewGroup.LayoutParams.WRAP_CONTENT);
layoutParams.gravity = Gravity.CENTER_HORIZONTAL;
mainSmileys.setLayoutParams(layoutParams);
((ScrollView) res.findViewById(R.id.scroller)).addView(mainSmileys);
container.addView(res);
return res;
} else {
View res = inflater.inflate(R.layout.msg_smileys_empty, container, false);
container.addView(res);
return res;
}
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
@Override
public int getCount() {
return 5;
}
@Override
public boolean isViewFromObject(View view, Object o) {
return view.equals(o);
}
});
((UnderlinePageIndicator) smileysView.findViewById(R.id.pageIndicator)).setViewPager(pager);
((UnderlinePageIndicator) smileysView.findViewById(R.id.pageIndicator)).setFades(false);
((UnderlinePageIndicator) smileysView.findViewById(R.id.pageIndicator)).setSelectedColor(0xffffffff);
((UnderlinePageIndicator) smileysView.findViewById(R.id.pageIndicator)).setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int i, float v, int i2) {
}
@Override
public void onPageSelected(int i) {
updateSmileysTabs(smileysView, i);
}
@Override
public void onPageScrollStateChanged(int i) {
}
});
if (application.getUiKernel().getLastEmoji().getLastSmileys().length == 0) {
pager.setCurrentItem(1);
}
smileysView.findViewById(R.id.smileyTab1).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
pager.setCurrentItem(0);
}
});
updateSmileysTabs(smileysView, pager.getCurrentItem());
smileysView.findViewById(R.id.smileyTab2).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
pager.setCurrentItem(1);
}
});
smileysView.findViewById(R.id.smileyTab3).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
pager.setCurrentItem(2);
}
});
smileysView.findViewById(R.id.smileyTab4).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
pager.setCurrentItem(3);
}
});
smileysView.findViewById(R.id.smileyTab5).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
pager.setCurrentItem(4);
}
});
WindowManager.LayoutParams params = new WindowManager.LayoutParams(
WindowManager.LayoutParams.MATCH_PARENT,
getPx(keyboardHeight),
WindowManager.LayoutParams.TYPE_PHONE,
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
PixelFormat.TRANSLUCENT);
params.gravity = Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL;
windowManager.addView(smileysView, params);
}
private void hideSmileysPopup() {
if (smileysView != null) {
windowManager.removeView(smileysView);
smileysView = null;
}
}
}
|
leandog/cocoaonep
|
Examples/WaitForIt/WaitForIt/WaitForItWorker.h
|
<filename>Examples/WaitForIt/WaitForIt/WaitForItWorker.h<gh_stars>0
//
// WaitForItWorker.h
// WaitForIt
//
// Created by <NAME> on 12/11/14.
// Copyright (c) 2014 Exosite. All rights reserved.
//
#import <Foundation/Foundation.h>
typedef void(^WaitedForThis)(NSNumber* number, NSError *error);
@interface WaitForItWorker : NSObject
@property (assign,nonatomic,readonly) BOOL isSetup;
- (void)createPortsAndScripts;
- (void)setWaitRate:(NSUInteger)seconds;
- (void)waitForIt:(WaitedForThis)complete;
@end
|
uk-gov-mirror/ministryofjustice.Claim-for-Crown-Court-Defence
|
spec/javascripts/Helpers.DataTables_spec.js
|
<gh_stars>10-100
describe('Helpers.DataTables.js', function () {
const helper = moj.Helpers.DataTables
it('should exist', function () {
expect(moj.Helpers.DataTables).toBeDefined()
})
it('should have default options set', function () {
// tooooo long to type
const defaults = moj.Helpers.DataTables._defaultOptions
expect(defaults).toBeDefined()
// deferRender: true
// Feature control deferred rendering
// for additional speed of initialisation
expect(defaults.deferRender).toEqual(true)
})
it('...should call `$.fn.DataTable`', function () {
spyOn($.fn, 'DataTable')
helper.init({
some: 'param'
}, '<div/>')
expect($.fn.DataTable).toHaveBeenCalledWith({
deferRender: true,
some: 'param'
})
})
it('...should extend and override default options', function () {
spyOn($.fn, 'DataTable')
helper.init({
deferRender: 99,
more: 'params'
}, '<div/>')
expect($.fn.DataTable).toHaveBeenCalledWith({
deferRender: 99,
more: 'params'
})
})
})
|
cvogt/cbt
|
examples/cross-build-example/build/build.scala
|
import cbt._
class Build(val context: Context) extends MultipleScalaVersions{
override def scalaVersions = Seq("2.10.5","2.11.7")
}
|
ORNL-BTRIC/OpenStudio
|
openstudiocore/src/openstudio_lib/SchedulesView.cpp
|
<filename>openstudiocore/src/openstudio_lib/SchedulesView.cpp
/**********************************************************************
* Copyright (c) 2008-2014, Alliance for Sustainable Energy.
* 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 Street, Fifth Floor, Boston, MA 02110-1301 USA
**********************************************************************/
#include <openstudio_lib/SchedulesView.hpp>
#include "../shared_gui_components/OSCheckBox.hpp"
#include <openstudio_lib/OSItemSelectorButtons.hpp>
#include "../shared_gui_components/OSLineEdit.hpp"
#include <model/Model.hpp>
#include <model/Model_Impl.hpp>
#include <model/ScheduleRule.hpp>
#include <model/ScheduleRuleset.hpp>
#include <model/ScheduleRuleset_Impl.hpp>
#include <model/ScheduleRule_Impl.hpp>
#include <model/ScheduleTypeLimits.hpp>
#include <model/ScheduleTypeLimits_Impl.hpp>
#include <utilities/time/Date.hpp>
#include <utilities/time/Time.hpp>
#include <utilities/units/QuantityConverter.hpp>
#include <utilities/units/Quantity.hpp>
#include <utilities/units/OSOptionalQuantity.hpp>
#include <utilities/units/OSQuantityVector.hpp>
#include <utilities/core/Assert.hpp>
#include <QButtonGroup>
#include <QCalendarWidget>
#include <QDateTime>
#include <QDateTimeEdit>
#include <QDoubleSpinBox>
#include <QGraphicsScene>
#include <QGraphicsView>
#include <QGridLayout>
#include <QLabel>
#include <QLineEdit>
#include <QMouseEvent>
#include <QPainter>
#include <QPushButton>
#include <QRadioButton>
#include <QResizeEvent>
#include <QScrollArea>
#include <QStackedWidget>
#include <QString>
#include <QStyleOption>
#include <QTimer>
#include <QVBoxLayout>
#include <algorithm>
#include <iterator>
#define UPPER_LIMIT 1.0
#define LOWER_LIMIT 0.0
namespace openstudio {
struct WorkspaceObjectNameLess;
static const double MARGINTOP = 10;
static const double MARGINBOTTOM = 30;
static const double MARGINLEFT = 80;
static const double MARGINRIGHT = 20;
static const double SCENEWIDTH = 86400;
static const double SCENEHEIGHT = 86400;
static const double LINEWIDTH = 3000;
static const double PENWIDTH = 500;
const std::vector<QColor> SchedulesView::colors = SchedulesView::initializeColors();
std::vector<QColor> SchedulesView::initializeColors()
{
std::vector<QColor> _colors(13);
_colors[0] = QColor(170,68,153);
_colors[1] = QColor(51,34,136);
_colors[2] = QColor(17,119,51);
_colors[3] = QColor(153,153,51);
_colors[4] = QColor(221,204,119);
_colors[5] = QColor(204,102,119);
_colors[6] = QColor(136,34,85);
_colors[7] = QColor(68,170,153);
_colors[8] = QColor(102,153,204);
_colors[9] = QColor(102,17,0);
_colors[10] = QColor(170,68,102);
_colors[11] = QColor(80,80,80);
_colors[12] = QColor(136,204,238);
return _colors;
}
SchedulesView::SchedulesView(bool isIP,
const model::Model & model)
: QWidget(),
m_model(model),
m_leftVLayout(NULL),
m_contentLayout(NULL),
m_isIP(isIP)
{
setObjectName("GrayWidgetWithLeftTopBorders");
QHBoxLayout * mainHLayout = new QHBoxLayout();
mainHLayout->setContentsMargins(1,1,0,0);
mainHLayout->setSpacing(0);
setLayout(mainHLayout);
QScrollArea * leftScrollArea = new QScrollArea();
leftScrollArea->setFrameStyle(QFrame::NoFrame);
QVBoxLayout * outerLeftVLayout = new QVBoxLayout();
outerLeftVLayout->setContentsMargins(0,0,0,0);
outerLeftVLayout->addWidget(leftScrollArea,10);
outerLeftVLayout->addStretch();
OSItemSelectorButtons * selectorButtons = new OSItemSelectorButtons();
selectorButtons->disableCopyButton();
selectorButtons->enablePurgeButton();
selectorButtons->enableRemoveButton();
bool isConnected = false;
isConnected = connect(selectorButtons,SIGNAL(itemDropped(const OSItemId &)),
this,SIGNAL(itemDropped(const OSItemId &)));
OS_ASSERT(isConnected);
isConnected = connect(selectorButtons,SIGNAL(addClicked()),
this,SIGNAL(addScheduleClicked()));
OS_ASSERT(isConnected);
isConnected = connect(selectorButtons,SIGNAL(removeClicked()),
this,SIGNAL(removeSelectedScheduleClicked()));
OS_ASSERT(isConnected);
isConnected = connect(selectorButtons,SIGNAL(purgeClicked()),
this,SIGNAL(purgeUnusedScheduleRulesetsClicked()));
OS_ASSERT(isConnected);
isConnected = connect(selectorButtons,SIGNAL(openBclDlgClicked()),
this,SIGNAL(openBclDlgClicked()));
OS_ASSERT(isConnected);
isConnected = connect(this, SIGNAL(toggleUnitsClicked(bool)),
this, SLOT(toggleUnits(bool)));
OS_ASSERT(isConnected);
outerLeftVLayout->addWidget(selectorButtons);
mainHLayout->addLayout(outerLeftVLayout);
QWidget * vLine = new QWidget();
vLine->setObjectName("VLine");
vLine->setStyleSheet("QWidget#VLine { background: #445051;}");
vLine->setFixedWidth(2);
mainHLayout->addWidget(vLine);
QWidget * leftScrollWidget = new QWidget();
leftScrollArea->setWidget(leftScrollWidget);
leftScrollArea->setWidgetResizable(true);
leftScrollWidget->setObjectName("GrayWidget");
m_leftVLayout = new QVBoxLayout();
m_leftVLayout->setContentsMargins(0,0,0,0);
m_leftVLayout->setSpacing(0);
m_leftVLayout->addStretch();
leftScrollWidget->setLayout(m_leftVLayout);
m_contentLayout = new QHBoxLayout();
m_contentLayout->setContentsMargins(0,0,0,0);
mainHLayout->addLayout(m_contentLayout,100);
connect(m_model.getImpl<openstudio::model::detail::Model_Impl>().get(),
SIGNAL(addWorkspaceObject(boost::shared_ptr<openstudio::detail::WorkspaceObject_Impl>,
const openstudio::IddObjectType&, const openstudio::UUID&)),
this,
SLOT(onModelAdd(boost::shared_ptr<openstudio::detail::WorkspaceObject_Impl>, const openstudio::IddObjectType&, const openstudio::UUID&)),
Qt::QueuedConnection);
connect(m_model.getImpl<openstudio::model::detail::Model_Impl>().get(),
SIGNAL(removeWorkspaceObject(boost::shared_ptr<openstudio::detail::WorkspaceObject_Impl>,
const openstudio::IddObjectType&, const openstudio::UUID&)),
this,
SLOT(removeSchedule(boost::shared_ptr<openstudio::detail::WorkspaceObject_Impl>, const openstudio::IddObjectType&,
const openstudio::UUID&)),
Qt::QueuedConnection);
// get all schedules
std::vector<model::ScheduleRuleset> schedules = m_model.getConcreteModelObjects<model::ScheduleRuleset>();
// sort by name
std::sort(schedules.begin(), schedules.end(), WorkspaceObjectNameGreater());
for(std::vector<model::ScheduleRuleset>::iterator it = schedules.begin();
it < schedules.end();
++it )
{
addSchedule(*it);
std::vector<model::ScheduleRule> rules = it->scheduleRules();
for( std::vector<model::ScheduleRule>::iterator ruleIt = rules.begin();
ruleIt < rules.end();
++ruleIt )
{
addScheduleRule(*ruleIt);
}
}
updateRowColors();
showEmptyPage();
}
void SchedulesView::closeAllTabs() const
{
for ( int i = 0;
i < m_leftVLayout->count() - 1;
i++ )
{
ScheduleTab * scheduleTab = qobject_cast<ScheduleTab *>(m_leftVLayout->itemAt(i)->widget());
scheduleTab->scheduleTabContent()->hide();
}
}
ScheduleTab * SchedulesView::tabForSchedule(const model::ScheduleRuleset schedule) const
{
for ( int i = 0;
i < m_leftVLayout->count() - 1;
i++ )
{
ScheduleTab * scheduleTab = qobject_cast<ScheduleTab *>(m_leftVLayout->itemAt(i)->widget());
if( scheduleTab->schedule().handle() == schedule.handle() )
{
return scheduleTab;
}
}
return NULL;
}
void SchedulesView::updateRowColors()
{
QString evenStyle;
evenStyle.append( "QWidget#ThermalZoneTab {" );
evenStyle.append( "background: #F2F2F2; ");
evenStyle.append( "border-bottom: 1px solid black; " );
evenStyle.append( "}" );
evenStyle.append( "QWidget#SideBar {background: #DEDEDE;}" );
QString oddStyle;
oddStyle.append( "QWidget#ThermalZoneTab {" );
oddStyle.append( "background: #E6E6E6; ");
oddStyle.append( "border-bottom: 1px solid black; " );
oddStyle.append( "}" );
oddStyle.append( "QWidget#SideBar {background: #CECECE;}" );
for ( int i = 0;
i < m_leftVLayout->count() - 1;
i++ )
{
ScheduleTab * scheduleTab = qobject_cast<ScheduleTab *>(m_leftVLayout->itemAt(i)->widget());
if( i % 2 == 0 )
{
scheduleTab->setStyleSheet(evenStyle);
}
else
{
scheduleTab->setStyleSheet(oddStyle);
}
}
}
void SchedulesView::addSchedule( model::ScheduleRuleset & schedule )
{
ScheduleTab * scheduleTab = new ScheduleTab(schedule,this);
connect(scheduleTab,SIGNAL(scheduleClicked(const model::ScheduleRuleset &)),this,SLOT(setCurrentSchedule(const model::ScheduleRuleset &)));
m_leftVLayout->insertWidget(0,scheduleTab);
// todo: sort?
this->setCurrentSchedule(schedule);
}
void SchedulesView::addScheduleRule( model::ScheduleRule & rule )
{
model::ScheduleRuleset scheduleRuleset = rule.scheduleRuleset();
ScheduleTab * tab = tabForSchedule(scheduleRuleset);
if( tab )
{
tab->scheduleTabContent()->scheduleRefresh();
connect(rule.getImpl<model::detail::ScheduleRule_Impl>().get(),SIGNAL(onRemoveFromWorkspace(Handle)),
tab->scheduleTabContent(),SLOT(scheduleRefresh()));
}
}
void SchedulesView::onModelAdd( boost::shared_ptr<openstudio::detail::WorkspaceObject_Impl> workspaceObjectImpl,
const openstudio::IddObjectType&,
const openstudio::UUID& )
{
boost::optional<model::ScheduleRuleset> schedule = m_model.getModelObject<model::ScheduleRuleset>(workspaceObjectImpl->handle());
if( schedule )
{
this->addSchedule(schedule.get());
}
boost::optional<model::ScheduleRule> rule = m_model.getModelObject<model::ScheduleRule>(workspaceObjectImpl->handle());
if( rule )
{
addScheduleRule(rule.get());
}
}
void SchedulesView::removeSchedule( boost::shared_ptr<openstudio::detail::WorkspaceObject_Impl> workspaceObjectImpl,
const openstudio::IddObjectType&,
const openstudio::UUID& )
{
if( workspaceObjectImpl->iddObject().type() == IddObjectType::OS_Schedule_Ruleset )
{
int removedIndex = -1;
bool wasSelected = false;
ScheduleTab * scheduleTab = 0;
for ( int i = 0;
i < m_leftVLayout->count() - 1;
i++ )
{
scheduleTab = qobject_cast<ScheduleTab *>(m_leftVLayout->itemAt(i)->widget());
if( scheduleTab->schedule().handle() == workspaceObjectImpl->handle() )
{
m_leftVLayout->removeWidget(scheduleTab);
wasSelected = scheduleTab->selected();
removedIndex = i;
delete scheduleTab;
break;
}
}
if( wasSelected )
{
int newIndex = -1;
if( removedIndex > 0 )
{
newIndex = removedIndex - 1;
}
else if( removedIndex == 0 )
{
if( m_leftVLayout->count() > 1 )
{
newIndex = 0;
}
}
if( newIndex > -1 )
{
ScheduleTab * scheduleTab = qobject_cast<ScheduleTab *>(m_leftVLayout->itemAt(newIndex)->widget());
this->setCurrentSchedule(scheduleTab->schedule());
}
else
{
this->showEmptyPage();
}
}
}
}
void SchedulesView::setCurrentSchedule(const model::ScheduleRuleset & schedule)
{
this->updateRowColors();
for ( int i = 0;
i < m_leftVLayout->count() - 1;
i++ )
{
ScheduleTab * scheduleTab;
scheduleTab = qobject_cast<ScheduleTab *>(m_leftVLayout->itemAt(i)->widget());
if( scheduleTab->schedule() == schedule )
{
if( ! scheduleTab->selected() )
{
scheduleTab->setSelected(true);
scheduleTab->expand();
}
else
{
scheduleTab->toggle();
}
}
else
{
scheduleTab->setSelected(false);
scheduleTab->collapse();
}
scheduleTab->update();
}
showScheduleRuleset(schedule);
}
void SchedulesView::showAddRulePage(const model::ScheduleRuleset & scheduleRuleset)
{
this->setUpdatesEnabled(false);
QLayoutItem *child;
while ((child = m_contentLayout->takeAt(0)) != 0)
{
delete child->widget();
delete child;
}
NewRuleView * newRuleView = new NewRuleView(scheduleRuleset, this);
m_contentLayout->addWidget(newRuleView,100);
this->setUpdatesEnabled(true);
}
void SchedulesView::showScheduleRuleset(const model::ScheduleRuleset & schedule)
{
this->setUpdatesEnabled(false);
QLayoutItem *child;
while ((child = m_contentLayout->takeAt(0)) != 0)
{
delete child->widget();
delete child;
}
ScheduleRulesetView * scheduleRulesetView = new ScheduleRulesetView(schedule);
m_contentLayout->addWidget(scheduleRulesetView,100);
this->setUpdatesEnabled(true);
}
void SchedulesView::showScheduleRule(model::ScheduleRule scheduleRule)
{
setUpdatesEnabled(false);
QLayoutItem *child;
while ((child = m_contentLayout->takeAt(0)) != 0)
{
delete child->widget();
delete child;
}
ScheduleRuleView * scheduleView = new ScheduleRuleView(m_isIP,scheduleRule,this);
bool isConnected = connect(this, SIGNAL(toggleUnitsClicked(bool)),
scheduleView, SIGNAL(toggleUnitsClicked(bool)));
OS_ASSERT(isConnected);
m_contentLayout->addWidget(scheduleView);
connect(scheduleRule.getImpl<openstudio::detail::WorkspaceObject_Impl>().get(),SIGNAL(onRemoveFromWorkspace(Handle)),
this,SLOT(onScheduleRuleRemoved(Handle)));
scheduleView->show();
setUpdatesEnabled(true);
}
void SchedulesView::onScheduleRuleRemoved(Handle handle)
{
showEmptyPage();
}
void SchedulesView::showDefaultScheduleDay(const model::ScheduleRuleset & schedule)
{
setUpdatesEnabled(false);
QLayoutItem *child;
while ((child = m_contentLayout->takeAt(0)) != 0)
{
delete child->widget();
delete child;
}
DefaultScheduleDayView * scheduleView = new DefaultScheduleDayView(m_isIP,schedule,this);
bool isConnected = connect(this, SIGNAL(toggleUnitsClicked(bool)),
scheduleView, SIGNAL(toggleUnitsClicked(bool)));
OS_ASSERT(isConnected);
m_contentLayout->addWidget(scheduleView);
scheduleView->show();
setUpdatesEnabled(true);
}
void SchedulesView::showSummerScheduleDay(model::ScheduleRuleset schedule)
{
setUpdatesEnabled(false);
QLayoutItem *child;
while ((child = m_contentLayout->takeAt(0)) != 0)
{
delete child->widget();
delete child;
}
if( ! schedule.isSummerDesignDayScheduleDefaulted() )
{
SizingScheduleDayView * scheduleView = new SizingScheduleDayView(m_isIP, schedule,this,SizingScheduleDayView::SUMMER);
bool isConnected = connect(this, SIGNAL(toggleUnitsClicked(bool)),
scheduleView, SIGNAL(toggleUnitsClicked(bool)));
OS_ASSERT(isConnected);
m_contentLayout->addWidget(scheduleView);
scheduleView->show();
}
else
{
NewRuleView * newRuleView = new NewRuleView(schedule, this, NewRuleView::SUMMER);
m_contentLayout->addWidget(newRuleView,100);
}
setUpdatesEnabled(true);
}
void SchedulesView::showWinterScheduleDay(model::ScheduleRuleset schedule)
{
setUpdatesEnabled(false);
QLayoutItem *child;
while ((child = m_contentLayout->takeAt(0)) != 0)
{
delete child->widget();
delete child;
}
if( ! schedule.isWinterDesignDayScheduleDefaulted() )
{
SizingScheduleDayView * scheduleView = new SizingScheduleDayView(m_isIP,schedule,this,SizingScheduleDayView::WINTER);
bool isConnected = connect(this, SIGNAL(toggleUnitsClicked(bool)),
scheduleView, SIGNAL(toggleUnitsClicked(bool)));
OS_ASSERT(isConnected);
m_contentLayout->addWidget(scheduleView);
scheduleView->show();
}
else
{
NewRuleView * newRuleView = new NewRuleView(schedule, this, NewRuleView::WINTER);
m_contentLayout->addWidget(newRuleView,100);
}
setUpdatesEnabled(true);
}
void SchedulesView::showEmptyPage()
{
this->setUpdatesEnabled(false);
QLayoutItem *child;
while ((child = m_contentLayout->takeAt(0)) != 0)
{
delete child->widget();
delete child;
}
QWidget * emptyWidget = new QWidget();
m_contentLayout->addWidget(emptyWidget,100);
this->setUpdatesEnabled(true);
}
boost::optional<model::ScheduleRuleset> SchedulesView::currentSchedule()
{
for ( int i = 0;
i < m_leftVLayout->count() - 1;
i++ )
{
ScheduleTab * scheduleTab;
scheduleTab = qobject_cast<ScheduleTab *>(m_leftVLayout->itemAt(i)->widget());
if( scheduleTab->selected() )
{
if( boost::optional<model::ScheduleRuleset> schedule = scheduleTab->schedule() )
{
if( ! schedule->handle().isNull() ) return schedule;
}
}
}
return boost::none;
}
void SchedulesView::paintEvent ( QPaintEvent * event )
{
QStyleOption opt;
opt.init(this);
QPainter p(this);
style()->drawPrimitive(QStyle::PE_Widget, &opt, &p, this);
}
// ***** SLOTS *****
void SchedulesView::toggleUnits(bool displayIP)
{
m_isIP = displayIP;
}
ScheduleRuleView::ScheduleRuleView(bool isIP,
const model::ScheduleRule & scheduleRule,
SchedulesView * schedulesView)
: QWidget(schedulesView),
m_schedulesView(schedulesView),
m_scheduleRule(scheduleRule),
m_dirty(false)
{
m_yearDescription = m_scheduleRule.model().getUniqueModelObject<model::YearDescription>();
// Layout
QHBoxLayout * mainHLayout = new QHBoxLayout();
mainHLayout->setContentsMargins(0,0,0,0);
mainHLayout->setSpacing(0);
setLayout(mainHLayout);
QVBoxLayout * mainVLayout = new QVBoxLayout();
mainVLayout->setContentsMargins(10,10,10,10);
mainVLayout->setSpacing(0);
mainHLayout->addLayout(mainVLayout,100);
// Rule Settings
QHBoxLayout * ruleHLayout = new QHBoxLayout();
ruleHLayout->setContentsMargins(0,0,0,0);
ruleHLayout->setSpacing(0);
mainVLayout->addLayout(ruleHLayout);
QWidget * ruleWidget = new QWidget();
ruleHLayout->addWidget(ruleWidget);
ruleHLayout->addStretch(10);
QPushButton * removeButton = new QPushButton();
removeButton->setObjectName("DeleteButton");
removeButton->setFlat(true);
removeButton->setFixedSize(24,24);
connect(removeButton,SIGNAL(clicked()),this,SLOT(onRemoveClicked()));
ruleHLayout->addWidget(removeButton,0,Qt::AlignTop);
ruleHLayout->addSpacing(MARGINRIGHT);
QVBoxLayout * ruleVLayout = new QVBoxLayout();
ruleVLayout->setContentsMargins(0,0,0,0);
ruleVLayout->setSpacing(5);
ruleWidget->setLayout(ruleVLayout);
QHBoxLayout * nameHLayout = new QHBoxLayout();
nameHLayout->setContentsMargins(0,0,0,0);
QWidget * colorWidget = new QWidget();
colorWidget->setFixedWidth(20);
QString colorStyle;
colorStyle.append("QWidget { background-color: ");
int colorIndex = m_scheduleRule.ruleIndex();
if( colorIndex > 12 )
{
colorIndex = 12;
}
QColor color = m_schedulesView->colors[colorIndex];
colorStyle.append(color.name());
colorStyle.append("; }");
colorWidget->setStyleSheet(colorStyle);
nameHLayout->addWidget(colorWidget);
m_nameEditField = new OSLineEdit();
m_nameEditField->bind(m_scheduleRule,"name");
nameHLayout->addWidget(m_nameEditField);
ruleVLayout->addLayout(nameHLayout);
QHBoxLayout * dateHLayout = new QHBoxLayout();
QLabel * dateRangeLabel = new QLabel("Date Range:");
dateHLayout->addWidget(dateRangeLabel);
m_startDateEdit = new QDateTimeEdit();
m_startDateEdit->setDisplayFormat("MM/dd");
m_startDateEdit->setCalendarPopup(true);
dateHLayout->addWidget(m_startDateEdit);
connect(m_startDateEdit,SIGNAL(dateTimeChanged(const QDateTime &)),this,SLOT(onStartDateTimeChanged(const QDateTime &)));
m_endDateEdit = new QDateTimeEdit();
m_endDateEdit->setDisplayFormat("MM/dd");
m_endDateEdit->setCalendarPopup(true);
dateHLayout->addWidget(m_endDateEdit);
connect(m_endDateEdit,SIGNAL(dateTimeChanged(const QDateTime &)),this,SLOT(onEndDateTimeChanged(const QDateTime &)));
dateHLayout->addStretch();
ruleVLayout->addLayout(dateHLayout);
QHBoxLayout * weekHLayout = new QHBoxLayout();
QLabel * applyToLabel = new QLabel("Apply to:");
weekHLayout->addWidget(applyToLabel);
weekHLayout->addStretch();
m_sundayButton = new OSCheckBox2();
m_sundayButton->setText("S");
m_sundayButton->bind(
m_scheduleRule,
boost::bind(&model::ScheduleRule::applySunday,&m_scheduleRule),
boost::optional<BoolSetter>(boost::bind(&model::ScheduleRule::setApplySunday,&m_scheduleRule,_1)));
weekHLayout->addWidget(m_sundayButton);
weekHLayout->addSpacing(10);
m_mondayButton = new OSCheckBox2();
m_mondayButton->setText("M");
m_mondayButton->bind(
m_scheduleRule,
boost::bind(&model::ScheduleRule::applyMonday,&m_scheduleRule),
boost::optional<BoolSetter>(boost::bind(&model::ScheduleRule::setApplyMonday,&m_scheduleRule,_1)));
weekHLayout->addWidget(m_mondayButton);
weekHLayout->addSpacing(10);
m_tuesdayButton = new OSCheckBox2();
m_tuesdayButton->setText("T");
m_tuesdayButton->bind(
m_scheduleRule,
boost::bind(&model::ScheduleRule::applyTuesday,&m_scheduleRule),
boost::optional<BoolSetter>(boost::bind(&model::ScheduleRule::setApplyTuesday,&m_scheduleRule,_1)));
weekHLayout->addWidget(m_tuesdayButton);
weekHLayout->addSpacing(10);
m_wednesdayButton = new OSCheckBox2();
m_wednesdayButton->setText("W");
m_wednesdayButton->bind(
m_scheduleRule,
boost::bind(&model::ScheduleRule::applyWednesday,&m_scheduleRule),
boost::optional<BoolSetter>(boost::bind(&model::ScheduleRule::setApplyWednesday,&m_scheduleRule,_1)));
weekHLayout->addWidget(m_wednesdayButton);
weekHLayout->addSpacing(10);
m_thursdayButton = new OSCheckBox2();
m_thursdayButton->setText("T");
m_thursdayButton->bind(
m_scheduleRule,
boost::bind(&model::ScheduleRule::applyThursday,&m_scheduleRule),
boost::optional<BoolSetter>(boost::bind(&model::ScheduleRule::setApplyThursday,&m_scheduleRule,_1)));
weekHLayout->addWidget(m_thursdayButton);
weekHLayout->addSpacing(10);
m_fridayButton = new OSCheckBox2();
m_fridayButton->setText("F");
m_fridayButton->bind(
m_scheduleRule,
boost::bind(&model::ScheduleRule::applyFriday,&m_scheduleRule),
boost::optional<BoolSetter>(boost::bind(&model::ScheduleRule::setApplyFriday,&m_scheduleRule,_1)));
weekHLayout->addWidget(m_fridayButton);
weekHLayout->addSpacing(10);
m_saturdayButton = new OSCheckBox2();
m_saturdayButton->setText("S");
m_saturdayButton->bind(
m_scheduleRule,
boost::bind(&model::ScheduleRule::applySaturday,&m_scheduleRule),
boost::optional<BoolSetter>(boost::bind(&model::ScheduleRule::setApplySaturday,&m_scheduleRule,_1)));
weekHLayout->addWidget(m_saturdayButton);
ruleVLayout->addLayout(weekHLayout);
// Schedule Day
m_scheduleDayView = new ScheduleDayView(isIP,m_scheduleRule.daySchedule(),m_schedulesView);
bool isConnected = false;
isConnected = connect(this, SIGNAL(toggleUnitsClicked(bool)),
m_scheduleDayView, SIGNAL(toggleUnitsClicked(bool)));
OS_ASSERT(isConnected);
isConnected = connect(this, SIGNAL(toggleUnitsClicked(bool)),
m_scheduleDayView, SLOT(onToggleUnitsClicked(bool)));
OS_ASSERT(isConnected);
mainVLayout->addWidget(m_scheduleDayView);
// Year Overview
QWidget * vLine2 = new QWidget();
vLine2->setObjectName("VLine");
vLine2->setStyleSheet("QWidget#VLine { background: #445051;}");
vLine2->setFixedWidth(2);
mainHLayout->addWidget(vLine2);
YearOverview * yearOverview = new YearOverview(m_scheduleRule.scheduleRuleset());
mainHLayout->addWidget(yearOverview);
// Connect
connect( m_scheduleRule.getImpl<openstudio::model::detail::ScheduleRule_Impl>().get(),
SIGNAL(onChange()),
this,
SLOT(scheduleRefresh()) );
connect( m_yearDescription->getImpl<openstudio::model::detail::YearDescription_Impl>().get(),
SIGNAL(onChange()),
this,
SLOT(scheduleRefresh()) );
connect( this,SIGNAL(startDateTimeChanged(model::ScheduleRule &, const QDateTime &)),
m_schedulesView,SIGNAL(startDateTimeChanged(model::ScheduleRule &, const QDateTime &)) );
connect( this,SIGNAL(endDateTimeChanged(model::ScheduleRule &, const QDateTime &)),
m_schedulesView,SIGNAL(endDateTimeChanged(model::ScheduleRule &, const QDateTime &)) );
connect( this,SIGNAL(removeScheduleRuleClicked(model::ScheduleRule &)),
m_schedulesView,SIGNAL(removeScheduleRuleClicked(model::ScheduleRule &)) );
// Refresh
scheduleRefresh();
}
void ScheduleRuleView::onRemoveClicked()
{
//m_scheduleRule.remove();
m_scheduleRule.getImpl<openstudio::model::detail::ScheduleRule_Impl>();
emit removeScheduleRuleClicked(m_scheduleRule);
}
model::ScheduleRule ScheduleRuleView::scheduleRule() const
{
return m_scheduleRule;
}
void ScheduleRuleView::refresh()
{
if( m_dirty )
{
m_startDateEdit->blockSignals(true);
m_endDateEdit->blockSignals(true);
QDate minDate(QDate(m_yearDescription->assumedYear(),1,1));
QDate maxDate(QDate(m_yearDescription->assumedYear(),12,31));
m_startDateEdit->setDateRange(minDate,maxDate);
m_endDateEdit->setDateRange(minDate,maxDate);
boost::optional<Date> startDate = m_scheduleRule.startDate();
if( startDate )
{
QDate qstartDate(startDate->year(),startDate->monthOfYear().value(),startDate->dayOfMonth());
m_startDateEdit->setDate(qstartDate);
m_startDateEdit->calendarWidget()->setSelectedDate(qstartDate);
}
boost::optional<Date> endDate = m_scheduleRule.endDate();
if( endDate )
{
QDate qendDate(endDate->year(),endDate->monthOfYear().value(),endDate->dayOfMonth());
m_endDateEdit->setDate(qendDate);
m_endDateEdit->calendarWidget()->setSelectedDate(qendDate);
}
m_startDateEdit->blockSignals(false);
m_endDateEdit->blockSignals(false);
m_dirty = false;
}
}
void ScheduleRuleView::scheduleRefresh()
{
m_dirty = true;
QTimer::singleShot(0,this,SLOT(refresh()));
}
void ScheduleRuleView::onStartDateTimeChanged(const QDateTime & newDate)
{
emit startDateTimeChanged(m_scheduleRule,newDate);
}
void ScheduleRuleView::onEndDateTimeChanged(const QDateTime & newDate)
{
emit endDateTimeChanged(m_scheduleRule,newDate);
}
DefaultScheduleDayView::DefaultScheduleDayView( bool isIP,
const model::ScheduleRuleset & scheduleRuleset,
SchedulesView * schedulesView )
: QWidget(schedulesView)
{
// Layout
QHBoxLayout * mainHLayout = new QHBoxLayout();
mainHLayout->setContentsMargins(0,0,0,0);
mainHLayout->setSpacing(0);
setLayout(mainHLayout);
QVBoxLayout * mainVLayout = new QVBoxLayout();
mainVLayout->setContentsMargins(10,10,10,10);
mainVLayout->setSpacing(0);
mainHLayout->addLayout(mainVLayout,100);
// Schedule Day
ScheduleDayView * scheduleDayView = new ScheduleDayView(isIP,scheduleRuleset.defaultDaySchedule(),schedulesView);
bool isConnected = connect(this, SIGNAL(toggleUnitsClicked(bool)),
scheduleDayView, SIGNAL(toggleUnitsClicked(bool)));
OS_ASSERT(isConnected);
mainVLayout->addWidget(scheduleDayView);
// Year Overview
QWidget * vLine2 = new QWidget();
vLine2->setObjectName("VLine");
vLine2->setStyleSheet("QWidget#VLine { background: #445051;}");
vLine2->setFixedWidth(2);
mainHLayout->addWidget(vLine2);
YearOverview * yearOverview = new YearOverview(scheduleRuleset);
mainHLayout->addWidget(yearOverview);
}
SizingScheduleDayView::SizingScheduleDayView( bool isIP,
const model::ScheduleRuleset & scheduleRuleset,
SchedulesView * schedulesView,
ViewType type )
: QWidget(schedulesView),
m_type(type)
{
// Layout
QHBoxLayout * mainHLayout = new QHBoxLayout();
mainHLayout->setContentsMargins(0,0,0,0);
mainHLayout->setSpacing(0);
setLayout(mainHLayout);
QVBoxLayout * mainVLayout = new QVBoxLayout();
mainVLayout->setContentsMargins(10,10,10,10);
mainVLayout->setSpacing(0);
mainHLayout->addLayout(mainVLayout,100);
// Schedule Day
if( m_type == SUMMER )
{
if( ! scheduleRuleset.isSummerDesignDayScheduleDefaulted() )
{
QLabel * label = new QLabel("Summer design day profile.");
mainVLayout->addWidget(label);
model::ScheduleDay scheduleDay = scheduleRuleset.summerDesignDaySchedule();
ScheduleDayView * scheduleDayView = new ScheduleDayView(isIP,scheduleDay,schedulesView);
bool isConnected = connect(this, SIGNAL(toggleUnitsClicked(bool)),
scheduleDayView, SIGNAL(toggleUnitsClicked(bool)));
OS_ASSERT(isConnected);
mainVLayout->addWidget(scheduleDayView);
}
}
else
{
if( ! scheduleRuleset.isWinterDesignDayScheduleDefaulted() )
{
QLabel * label = new QLabel("Winter design day profile.");
mainVLayout->addWidget(label);
model::ScheduleDay scheduleDay = scheduleRuleset.winterDesignDaySchedule();
ScheduleDayView * scheduleDayView = new ScheduleDayView(isIP,scheduleDay,schedulesView);
bool isConnected = connect(this, SIGNAL(toggleUnitsClicked(bool)),
scheduleDayView, SIGNAL(toggleUnitsClicked(bool)));
OS_ASSERT(isConnected);
mainVLayout->addWidget(scheduleDayView);
}
}
}
ScheduleDayView::ScheduleDayView(bool isIP,
const model::ScheduleDay & scheduleDay,
SchedulesView * schedulesView)
: QWidget(schedulesView),
m_zoom(1.0),
m_snap(3600.0),
m_scheduleDay(scheduleDay),
m_schedulesView(schedulesView),
m_dayScheduleScene(NULL),
m_scheduleDayEditor(NULL),
m_scheduleOverview(NULL),
m_upperLimitSpinBox(NULL),
m_lowerLimitSpinBox(NULL),
m_dirty(false),
m_isIP(isIP)
{
bool isConnected = false;
// Note: QDoubleSpinBox are used, rather than OSQuantityEdit
// because limits are not connected via Q_PROPERTY.
m_lowerLimitSpinBox = new QDoubleSpinBox();
double lowerLimitSpinBoxValue = LOWER_LIMIT;
model::OptionalScheduleTypeLimits typeLimits = scheduleDay.scheduleTypeLimits();
if (typeLimits) {
OSOptionalQuantity lowerLimitQ = typeLimits->getLowerLimitValue(m_isIP);
if (lowerLimitQ.isSet()) {
lowerLimitSpinBoxValue = lowerLimitQ.get().value();
}
else {
if (OptionalDouble temp = typeLimits->lowerLimitValue()) {
lowerLimitSpinBoxValue = *temp;
}
}
}
m_lowerLimitSpinBox->setValue(lowerLimitSpinBoxValue);
m_lowerLimitSpinBox->setMinimum(-1E10);
isConnected = connect(m_lowerLimitSpinBox,SIGNAL(valueChanged(double)),
this,SLOT(onLowerValueChanged(double)));
OS_ASSERT(isConnected);
m_upperLimitSpinBox = new QDoubleSpinBox();
double upperLimitSpinBoxValue = UPPER_LIMIT;
if (typeLimits) {
OSOptionalQuantity upperLimitQ = typeLimits->getUpperLimitValue(m_isIP);
if (upperLimitQ.isSet()) {
upperLimitSpinBoxValue = upperLimitQ.get().value();
}
else {
if (OptionalDouble temp = typeLimits->upperLimitValue()) {
upperLimitSpinBoxValue = *temp;
}
}
}
m_upperLimitSpinBox->setValue(upperLimitSpinBoxValue);
m_upperLimitSpinBox->setMaximum(1E10);
isConnected = connect(m_upperLimitSpinBox,SIGNAL(valueChanged(double)),
this,SLOT(onUpperValueChanged(double)));
OS_ASSERT(isConnected);
isConnected = connect(this,SIGNAL(toggleUnitsClicked(bool)),
this,SLOT(onToggleUnitsClicked(bool)));
OS_ASSERT(isConnected);
// Scene
m_dayScheduleScene = new DayScheduleScene(this,m_scheduleDay);
m_dayScheduleScene->setSceneRect(0,0,SCENEWIDTH,SCENEHEIGHT);
// Layout
QVBoxLayout * mainVLayout = new QVBoxLayout();
mainVLayout->setContentsMargins(0,0,0,0);
mainVLayout->setSpacing(10);
setLayout(mainVLayout);
// Name
QHBoxLayout * hLayout = NULL;
QLabel * label = NULL;
label = new QLabel("Name:");
label->setObjectName("H2");
mainVLayout->addWidget(label);
QString name;
boost::optional<model::ScheduleRuleset> currentSchedule = schedulesView->currentSchedule();
if(currentSchedule){
boost::optional<std::string> optionalString = currentSchedule->name();
if(optionalString){
name = optionalString->c_str();
}
}
QLineEdit * lineEdit = new QLineEdit(name);
lineEdit->setReadOnly(true);
mainVLayout->addWidget(lineEdit);
// Lower Limit
hLayout = new QHBoxLayout();
mainVLayout->addLayout(hLayout);
label = new QLabel("Lower Limit");
hLayout->addWidget(label);
hLayout->addWidget(m_lowerLimitSpinBox);
hLayout->addSpacing(20);
// Upper Limit
label = new QLabel("Upper Limit");
hLayout->addWidget(label);
hLayout->addWidget(m_upperLimitSpinBox);
hLayout->addStretch();
// Day Schedule
m_scheduleDayEditor = new ScheduleDayEditor(isIP, this, m_scheduleDay );
isConnected = connect(this, SIGNAL(toggleUnitsClicked(bool)),
m_scheduleDayEditor, SLOT(toggleUnits(bool)));
OS_ASSERT(isConnected);
mainVLayout->addWidget(m_scheduleDayEditor);
// Zoom button group
QHBoxLayout * zoomButtonLayout = new QHBoxLayout();
QButtonGroup * zoomButtonGroup = new QButtonGroup(this);
zoomButtonLayout->addStretch();
QPushButton * hourlyZoomButton = new QPushButton();
hourlyZoomButton->setObjectName("StandardGrayButton");
hourlyZoomButton->setCheckable(true);
hourlyZoomButton->setChecked(true);
zoomButtonGroup->addButton(hourlyZoomButton);
hourlyZoomButton->setText("Hourly");
connect(hourlyZoomButton,SIGNAL(clicked()),this,SLOT(setHourlyZoom()));
zoomButtonLayout->addWidget(hourlyZoomButton);
zoomButtonLayout->addSpacing(10);
QPushButton * quarterHourlyZoomButton = new QPushButton();
quarterHourlyZoomButton->setObjectName("StandardGrayButton");
quarterHourlyZoomButton->setCheckable(true);
zoomButtonGroup->addButton(quarterHourlyZoomButton);
quarterHourlyZoomButton->setText("15 Minutes");
connect(quarterHourlyZoomButton,SIGNAL(clicked()),this,SLOT(setQuarterHourlyZoom()));
zoomButtonLayout->addWidget(quarterHourlyZoomButton);
zoomButtonLayout->addSpacing(10);
QPushButton * oneMinuteZommButton = new QPushButton();
oneMinuteZommButton->setObjectName("StandardGrayButton");
oneMinuteZommButton->setCheckable(true);
zoomButtonGroup->addButton(oneMinuteZommButton);
oneMinuteZommButton->setText("1 Minute");
connect(oneMinuteZommButton,SIGNAL(clicked()),this,SLOT(setOneMinuteZoom()));
zoomButtonLayout->addWidget(oneMinuteZommButton);
zoomButtonLayout->addStretch();
mainVLayout->addLayout(zoomButtonLayout);
// Day Overview
QHBoxLayout * overviewLayout = new QHBoxLayout();
m_scheduleOverview = new DayScheduleOverview( this );
overviewLayout->addSpacing(MARGINLEFT);
overviewLayout->addWidget(m_scheduleOverview);
overviewLayout->addSpacing(MARGINRIGHT);
mainVLayout->addLayout(overviewLayout);
}
double ScheduleDayView::upperLimit() const
{
if(m_upperLimitSpinBox){
return m_upperLimitSpinBox->value();
}
else{
return UPPER_LIMIT;
}
}
void ScheduleDayView::setUpperLimit(double value)
{
if(m_upperLimitSpinBox){
m_upperLimitSpinBox->setValue(value);
m_upperLimitSpinBox->setMinimum(value);
}
}
double ScheduleDayView::lowerLimit() const
{
if(m_lowerLimitSpinBox){
return m_lowerLimitSpinBox->value();
}
else{
return LOWER_LIMIT;
}
}
void ScheduleDayView::setLowerLimit(double value)
{
if(m_lowerLimitSpinBox){
m_lowerLimitSpinBox->setValue(value);
m_lowerLimitSpinBox->setMaximum(value);
}
}
void ScheduleDayView::onLowerValueChanged(double d)
{
m_upperLimitSpinBox->setMinimum(d);
if(scene()){
scene()->scheduleRefresh();
}
}
void ScheduleDayView::onUpperValueChanged(double d)
{
m_lowerLimitSpinBox->setMaximum(d);
if(scene()){
scene()->scheduleRefresh();
}
}
bool ScheduleDayView::isIP() const {
return m_isIP;
}
void ScheduleDayView::onToggleUnitsClicked(bool displayIP) {
model::OptionalScheduleTypeLimits typeLimits = m_scheduleDay.scheduleTypeLimits();
if (typeLimits) {
Unit oldUnits = typeLimits->getLowerLimitValue(m_isIP).units();
Unit newUnits = typeLimits->getLowerLimitValue(displayIP).units();
if (oldUnits != newUnits) {
Quantity oldLowerLimit(lowerLimit(),oldUnits);
OptionalQuantity newLowerLimit = convert(oldLowerLimit,newUnits);
if (newLowerLimit) {
setLowerLimit(newLowerLimit->value());
}
Quantity oldUpperLimit(upperLimit(),oldUnits);
OptionalQuantity newUpperLimit = convert(oldUpperLimit,newUnits);
if (newUpperLimit) {
setUpperLimit(newUpperLimit->value());
}
}
}
m_isIP = displayIP;
if (scene()) {
scene()->scheduleRefresh();
}
}
SchedulesView * ScheduleDayView::schedulesView() const
{
return m_schedulesView;
}
model::ScheduleDay ScheduleDayView::scheduleDay() const
{
return m_scheduleDay;
}
double ScheduleDayView::focusStartTime() const
{
return m_focusStartTime;
}
double ScheduleDayView::focusEndTime() const
{
return focusStartTime() + duration();
}
double ScheduleDayView::duration() const
{
return SCENEWIDTH / zoom();
}
DayScheduleScene * ScheduleDayView::scene() const
{
return m_dayScheduleScene;
}
double ScheduleDayView::zoom() const
{
return m_zoom;
}
double ScheduleDayView::snap() const
{
return m_snap;
}
void ScheduleDayView::setHourlyZoom()
{
m_zoom = 1.0;
m_snap = 3600.0;
emit zoomChanged(m_zoom);
m_scheduleDayEditor->fitInView();
if( focusStartTime() > SCENEWIDTH - duration() )
{
m_focusStartTime = SCENEWIDTH - duration();
}
m_scheduleOverview->updateFocusRectangleGeometry();
m_scheduleDayEditor->update();
}
void ScheduleDayView::setQuarterHourlyZoom()
{
m_zoom = 4.0;
m_snap = 900.0;
emit zoomChanged(m_zoom);
m_scheduleDayEditor->fitInView();
if( focusStartTime() > SCENEWIDTH - duration() )
{
m_focusStartTime = SCENEWIDTH - duration();
}
m_scheduleOverview->updateFocusRectangleGeometry();
m_scheduleDayEditor->update();
}
void ScheduleDayView::setOneMinuteZoom()
{
m_zoom = 60.0;
m_snap = 60.0;
emit zoomChanged(m_zoom);
m_scheduleDayEditor->fitInView();
if( focusStartTime() > SCENEWIDTH - duration() )
{
m_focusStartTime = SCENEWIDTH - duration();
}
m_scheduleOverview->updateFocusRectangleGeometry();
m_scheduleDayEditor->update();
}
bool ScheduleDayView::setFocusStartTime(double proposedStartTime)
{
double startTime = proposedStartTime;
if( proposedStartTime < 0.0 )
{
startTime = 0.0;
}
else if( proposedStartTime > SCENEWIDTH - duration() )
{
startTime = SCENEWIDTH - duration();
}
m_focusStartTime = startTime;
m_scheduleOverview->updateFocusRectangleGeometry();
m_scheduleDayEditor->fitInView();
m_scheduleDayEditor->update();
return true;
}
ScheduleDayEditor::ScheduleDayEditor(bool isIP, ScheduleDayView * scheduleDayView, const model::ScheduleDay & scheduleDay) :
QWidget(scheduleDayView),
m_scheduleDayView(scheduleDayView),
m_scheduleDay(scheduleDay),
m_dirty(true),
m_isIP(isIP)
{
m_graphicsView = new DaySchedulePlotArea(this);
m_graphicsView->setCacheMode(QGraphicsView::CacheNone);
m_graphicsView->resize(SCENEWIDTH, SCENEHEIGHT);
m_graphicsView->move(MARGINLEFT,MARGINTOP);
m_graphicsView->setFrameShape(QFrame::NoFrame);
m_graphicsView->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
m_graphicsView->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
m_graphicsView->setScene(scheduleDayView->scene());
m_yLabel = new QLabel(this);
setLabelText();
setSizePolicy(QSizePolicy::MinimumExpanding,QSizePolicy::MinimumExpanding);
//connect( m_scheduleDay.scheduleTypeLimits().getImpl<model::detail::ScheduleTypeLimits_Impl>().get(),
// SIGNAL(onChange()),
// this,
// SLOT(scheduleRefresh()) );
connect( this, SIGNAL(changeVerticalAxisClicked(model::ScheduleDay)),
m_scheduleDayView->schedulesView(),SIGNAL(changeVerticalAxisClicked(model::ScheduleDay)));
QTimer::singleShot(0,this,SLOT(fitInView()));
}
void ScheduleDayEditor::setLabelText()
{
boost::optional<model::ScheduleTypeLimits> scheduleTypeLimits = m_scheduleDay.scheduleTypeLimits();
if (scheduleTypeLimits) {
OSOptionalQuantity optionalQuantity = scheduleTypeLimits->getLowerLimitValue(m_isIP);
std::stringstream ss;
ss << optionalQuantity.units();
QString text = QString::fromStdString(ss.str());
m_yLabel->setText(text);
}
}
ScheduleDayView * ScheduleDayEditor::scheduleDayView() const
{
return m_scheduleDayView;
}
void ScheduleDayEditor::fitInView()
{
m_graphicsView->fitInView( QRectF(SCENEWIDTH / SCENEWIDTH * m_scheduleDayView->focusStartTime(),0.0,
SCENEWIDTH / m_scheduleDayView->zoom() - 2.0,SCENEHEIGHT - 2.0));
}
void ScheduleDayEditor::resizeEvent ( QResizeEvent * event )
{
m_graphicsView->resize(event->size().width() - MARGINLEFT - MARGINRIGHT, event->size().height() - MARGINTOP - MARGINBOTTOM);
int buttonHeight = 140; // Can't ask for button height until it is first rendered
m_yLabel->move(0, MARGINTOP + m_graphicsView->size().height() / 2 - buttonHeight / 2.0);
fitInView();
QWidget::resizeEvent( event );
}
void ScheduleDayEditor::mouseDoubleClickEvent(QMouseEvent * event)
{
}
void ScheduleDayEditor::paintEvent ( QPaintEvent * event )
{
QStyleOption opt;
opt.init(this);
QPainter p(this);
QTransform transform;
p.setTransform(transform);
style()->drawPrimitive(QStyle::PE_Widget, &opt, &p, this);
// Draw border
p.drawLine( MARGINLEFT - 1.0, height() - MARGINBOTTOM, width() - MARGINRIGHT, height() - MARGINBOTTOM );
p.drawLine( MARGINLEFT - 1.0, MARGINTOP, MARGINLEFT - 1.0, height() - MARGINBOTTOM );
p.drawLine( MARGINLEFT - 1.0, MARGINTOP - 1.0, width() - MARGINRIGHT, MARGINTOP - 1.0 );
p.drawLine( width() - MARGINRIGHT, MARGINTOP, width() - MARGINRIGHT, height() - MARGINBOTTOM );
// Draw horizontal tick marks
double startTimeSeconds = scheduleDayView()->focusStartTime();
double endTimeSeconds = scheduleDayView()->focusEndTime();
double xstart = MARGINLEFT;
double xend = width() - MARGINRIGHT;
double timeSnapLength = scheduleDayView()->snap() * 4.0;
double prevSnapTime = (int)(startTimeSeconds / timeSnapLength) * timeSnapLength;
double time = prevSnapTime + timeSnapLength;
if( abs(startTimeSeconds - prevSnapTime) < 0.00001 )
{
time = startTimeSeconds;
}
double x = xstart + (time - startTimeSeconds) * (xend - xstart) / (endTimeSeconds - startTimeSeconds);
double xSnapLength = timeSnapLength * (xend - xstart) / (endTimeSeconds - startTimeSeconds);
while( x <= xend + 1.0 && x >= xstart - 1.0 )
{
p.drawLine(x,height() - MARGINBOTTOM,x,height() - MARGINBOTTOM + 7.0);
Time osTime(0,0,0,time);
QString timeString;
if( osTime.days() == 1 )
{
timeString.append("24");
timeString.append(":");
timeString.append("00");
}
else
{
timeString.append(QString::number(osTime.hours()));
timeString.append(":");
int minutes = osTime.minutes();
if( minutes < 10 )
{
timeString.append("0");
}
timeString.append(QString::number(minutes));
}
p.drawText( QRect(x - xSnapLength / 2.0,
height() - MARGINBOTTOM + 7.0,
xSnapLength,MARGINBOTTOM - 7.0 ),
Qt::AlignHCenter | Qt::AlignTop,timeString);
x = x + xSnapLength;
time = time + timeSnapLength;
}
// Draw vertical tick marks
double ystart = MARGINTOP;
double yend = height() - MARGINBOTTOM;
double yStartValue = m_scheduleDayView->upperLimit();
double yEndValue = m_scheduleDayView->lowerLimit();
double ySnap = 7.0;
double yStride = (yend - ystart) / ySnap;
double yValueStride = (yStartValue - yEndValue) / ySnap;
double y = ystart;
double yValue = yStartValue;
while( y >= ystart - 1.0 && y <= yend + 1.0 )
{
p.drawLine(MARGINLEFT - 7.0,y,MARGINLEFT,y);
double roundedValue = static_cast<double>(static_cast<int>(yValue*100+0.5))/100.0;
QString valueString = QString::number(roundedValue,'g',3);
p.drawText(QRect(7.0,y - 5.0,MARGINLEFT - 15.0,10.0),Qt::AlignRight | Qt::AlignCenter,valueString);
y = y + yStride;
yValue = yValue - yValueStride;
}
}
// ***** SLOTS *****
void ScheduleDayEditor::toggleUnits(bool displayIP)
{
m_isIP = displayIP;
setLabelText();
}
CalendarSegmentItem::CalendarSegmentItem( QGraphicsItem * parent )
: QGraphicsItem(parent),
m_previousVCalendarItem(NULL),
m_nextVCalendarItem(NULL),
m_isHovering(false),
m_mouseDown(false),
m_endTime(SCENEWIDTH)
{
setAcceptHoverEvents(true);
setToolTip("Double click to cut segment");
setZValue(100);
}
double CalendarSegmentItem::vCenterPos() const
{
return pos().y() + boundingRect().height() / 2.0;
}
CalendarSegmentItem * CalendarSegmentItem::nextCalendarItem() const
{
if( VCalendarSegmentItem * item = nextVCalendarItem() )
{
return item->nextCalendarItem();
}
else
{
return NULL;
}
}
CalendarSegmentItem * CalendarSegmentItem::previousCalendarItem() const
{
if( VCalendarSegmentItem * item = previousVCalendarItem() )
{
return item->previousCalendarItem();
}
else
{
return NULL;
}
}
bool CalendarSegmentItem::isMouseDown() const
{
return m_mouseDown;
}
void CalendarSegmentItem::setMouseDown(bool mouseDown)
{
m_mouseDown = mouseDown;
}
void CalendarSegmentItem::setHovering(bool hovering)
{
m_isHovering = hovering;
}
QRectF CalendarSegmentItem::boundingRect () const
{
return QRectF(0.0,0.0,(endTime() - startTime()) * SCENEWIDTH / SCENEWIDTH,LINEWIDTH);
}
void CalendarSegmentItem::paint( QPainter *painter,
const QStyleOptionGraphicsItem *option,
QWidget *widget )
{
if( m_isHovering )
{
painter->setPen(Qt::NoPen);
painter->setBrush(QBrush(Qt::blue));
painter->drawRect(boundingRect());
}
QPen pen;
//SCENEHEIGHT
double penwidth = PENWIDTH;
if( QWidget * view = qobject_cast<QWidget *>(widget->parent()) )
{
double height = view->height();
penwidth = (PENWIDTH / height) * 400.0;
}
pen.setWidth(penwidth);
pen.setCapStyle(Qt::FlatCap);
painter->setPen(pen);
painter->drawLine(QPointF(0.0,LINEWIDTH / 2.0),QPointF(boundingRect().width(),LINEWIDTH / 2.0));
}
void CalendarSegmentItem::splitSegment(double splitTime)
{
double oldEndTime = endTime();
VCalendarSegmentItem * oldNextVCalendarItem;
oldNextVCalendarItem = this->nextVCalendarItem();
CalendarSegmentItem * item = new CalendarSegmentItem;
scene()->addItem(item);
VCalendarSegmentItem * vitem = new VCalendarSegmentItem;
scene()->addItem(vitem);
vitem->setPreviousCalendarItem(this);
vitem->setNextCalendarItem(item);
this->setNextVCalendarItem(vitem);
item->setPreviousVCalendarItem(vitem);
item->setNextVCalendarItem(oldNextVCalendarItem);
setEndTime(splitTime);
item->setStartTime(splitTime);
item->setEndTime(oldEndTime);
item->setValue(value());
vitem->setTime(splitTime);
if( oldNextVCalendarItem )
{
oldNextVCalendarItem->setPreviousCalendarItem(item);
}
vitem->updateLength();
}
DayScheduleScene * CalendarSegmentItem::scene() const
{
if( QGraphicsScene * scene = QGraphicsItem::scene() )
{
return qobject_cast<DayScheduleScene *>(scene);
}
else
{
return NULL;
}
}
VCalendarSegmentItem * CalendarSegmentItem::nextVCalendarItem() const
{
return m_nextVCalendarItem;
}
void CalendarSegmentItem::setNextVCalendarItem(VCalendarSegmentItem * item)
{
m_nextVCalendarItem = item;
}
VCalendarSegmentItem * CalendarSegmentItem::previousVCalendarItem() const
{
return m_previousVCalendarItem;
}
void CalendarSegmentItem::setPreviousVCalendarItem(VCalendarSegmentItem * item)
{
m_previousVCalendarItem = item;
}
double CalendarSegmentItem::startTime() const
{
return scenePos().x() / SCENEWIDTH * SCENEWIDTH;
}
double CalendarSegmentItem::endTime() const
{
return m_endTime;
}
void CalendarSegmentItem::setStartTime(double time)
{
prepareGeometryChange();
setX( time * SCENEWIDTH / SCENEWIDTH );
}
void CalendarSegmentItem::setEndTime(double time)
{
prepareGeometryChange();
m_endTime = time;
}
double CalendarSegmentItem::value() const
{
return (SCENEHEIGHT - (scenePos().y() + boundingRect().height() / 2.0) ) / SCENEHEIGHT;
}
void CalendarSegmentItem::setValue(double value)
{
setY(SCENEHEIGHT - (value * SCENEHEIGHT) - (boundingRect().height() / 2.0));
double upperLimitValue = scene()->scheduleDayView()->upperLimit();
double lowerLimitValue = scene()->scheduleDayView()->lowerLimit();
float fullscalevalue = lowerLimitValue + value * (upperLimitValue - lowerLimitValue);
QString tooltip = QString::number(fullscalevalue,'g',3);
tooltip.append(" - Double click to cut segment");
setToolTip(tooltip);
}
VCalendarSegmentItem::VCalendarSegmentItem( QGraphicsItem * parent )
: QGraphicsItem(parent),
m_isHovering(false)
{
setAcceptHoverEvents(true);
setLength(LINEWIDTH * 3.0);
}
DayScheduleScene * VCalendarSegmentItem::scene() const
{
if( QGraphicsScene * scene = QGraphicsItem::scene() )
{
return qobject_cast<DayScheduleScene *>(scene);
}
else
{
return NULL;
}
}
double VCalendarSegmentItem::vCenterPos() const
{
return pos().y() + boundingRect().height() / 2.0;
}
double VCalendarSegmentItem::hCenterPos() const
{
return pos().x() + boundingRect().width() / 2.0;
}
void VCalendarSegmentItem::setMouseDown(bool mouseDown)
{
m_mouseDown = mouseDown;
}
void VCalendarSegmentItem::setHovering(bool hovering)
{
m_isHovering = hovering;
}
QRectF VCalendarSegmentItem::boundingRect() const
{
return QRectF(0.0,0.0,LINEWIDTH,m_length);
}
void VCalendarSegmentItem::paint( QPainter *painter,
const QStyleOptionGraphicsItem *option,
QWidget *widget )
{
if( ScheduleDayEditor * mainScheduleView = qobject_cast<ScheduleDayEditor *>(widget->parent()->parent()) )
{
QTransform transform = painter->transform();
double zoom = mainScheduleView->scheduleDayView()->zoom();
double dx = 0.5 * LINEWIDTH * ( 1.0 - 1.0 / zoom );
transform.translate(dx,0.0);
transform.scale(1.0 / zoom,1.0);
painter->setTransform(transform);
}
if( m_isHovering )
{
painter->setPen(Qt::NoPen);
painter->setBrush(QBrush(Qt::blue));
painter->drawRect(boundingRect());
}
QPen pen;
pen.setWidth(PENWIDTH);
pen.setCapStyle(Qt::SquareCap);
painter->setPen(pen);
painter->drawLine(LINEWIDTH / 2.0,0.0,LINEWIDTH / 2.0,boundingRect().height() - 1.0);
}
bool VCalendarSegmentItem::isMouseDown() const
{
return m_mouseDown;
}
CalendarSegmentItem * VCalendarSegmentItem::nextCalendarItem() const
{
return m_nextCalendarItem;
}
void VCalendarSegmentItem::setNextCalendarItem(CalendarSegmentItem * item)
{
m_nextCalendarItem = item;
}
CalendarSegmentItem * VCalendarSegmentItem::previousCalendarItem() const
{
return m_previousCalendarItem;
}
void VCalendarSegmentItem::setPreviousCalendarItem(CalendarSegmentItem * item)
{
m_previousCalendarItem = item;
}
void VCalendarSegmentItem::setLength(double length)
{
prepareGeometryChange();
m_length = length;
}
double VCalendarSegmentItem::length() const
{
return m_length;
}
void VCalendarSegmentItem::updateLength()
{
CalendarSegmentItem * previousCalendarItem = this->previousCalendarItem();
CalendarSegmentItem * nextCalendarItem = this->nextCalendarItem();
double nextY = nextCalendarItem->pos().y() + nextCalendarItem->boundingRect().height() / 2.0;
double prevY = previousCalendarItem->pos().y() + previousCalendarItem->boundingRect().height() / 2.0;
double length = abs(nextY - prevY);
if( prevY < nextY )
{
if( length < LINEWIDTH * 3.0 )
{
this->setLength(LINEWIDTH * 3.0);
this->setPos(this->pos().x(),0.5 * prevY + 0.5 * (nextY - LINEWIDTH * 3.0));
}
else
{
this->setPos(this->pos().x(),prevY);
this->setLength(length);
}
}
else
{
if( length < LINEWIDTH * 3.0 )
{
this->setLength(LINEWIDTH * 3.0);
this->setPos(this->pos().x(),0.5 * nextY + 0.5 * (prevY - LINEWIDTH * 3.0));
}
else
{
this->setPos(this->pos().x(),nextY);
this->setLength(length + 1.0);
}
}
update();
}
void VCalendarSegmentItem::remove()
{
CalendarSegmentItem * oldNextItem = nextCalendarItem();
VCalendarSegmentItem * newNextVItem = oldNextItem->nextVCalendarItem();
CalendarSegmentItem * item = previousCalendarItem();
if( newNextVItem )
{
item->setNextVCalendarItem(newNextVItem);
newNextVItem->setPreviousCalendarItem(item);
newNextVItem->updateLength();
}
else
{
item->setNextVCalendarItem(NULL);
}
item->setEndTime(oldNextItem->endTime());
delete oldNextItem;
delete this;
}
double VCalendarSegmentItem::time() const
{
return scene()->timeAt(scenePos().x() + boundingRect().width() / 2.0);
}
void VCalendarSegmentItem::setTime(double time)
{
double newX = scene()->xAt(time) - boundingRect().width() / 2.0;
setX(newX);
previousCalendarItem()->setEndTime(time);
nextCalendarItem()->setStartTime(time);
}
DayScheduleOverview::DayScheduleOverview(ScheduleDayView * scheduleRuleView)
: QWidget(scheduleRuleView),
m_lastMousePos(0)
{
m_graphicsView = new QGraphicsView(this);
m_graphicsView->move(0.0,0.0);
m_scheduleRuleView = scheduleRuleView;
setFixedHeight(100);
m_graphicsView->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
m_graphicsView->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
m_graphicsView->setScene(m_scheduleRuleView->scene());
// Focus Rectangle
m_focusRectangle = new QWidget(this);
m_focusRectangle->setStyleSheet("QWidget { border: 1px solid black; }");
QTimer::singleShot(0,this,SLOT(fitInView()));
updateFocusRectangleGeometry();
connect(m_scheduleRuleView,SIGNAL(zoomChanged(double)),this,SLOT(onZoomChange(double)));
}
void DayScheduleOverview::onZoomChange(double newZoom)
{
updateFocusRectangleGeometry();
}
void DayScheduleOverview::updateFocusRectangleGeometry()
{
QPoint currentPos = m_focusRectangle->pos();
int x = xAt(m_scheduleRuleView->focusStartTime());
m_focusRectangle->move(x,currentPos.y());
m_focusRectangle->resize(width() / m_scheduleRuleView->zoom() - 1.0,100 - 1.0);
}
double DayScheduleOverview::timeAt(int x) const
{
return SCENEWIDTH / width() * x;
}
int DayScheduleOverview::xAt(double time) const
{
return time / SCENEWIDTH * width();
}
void DayScheduleOverview::fitInView()
{
m_graphicsView->fitInView(QRectF(0,0,SCENEWIDTH,SCENEHEIGHT));
}
void DayScheduleOverview::resizeEvent(QResizeEvent * event)
{
m_graphicsView->resize(event->size());
fitInView();
updateFocusRectangleGeometry();
}
void DayScheduleOverview::mouseMoveEvent(QMouseEvent * event)
{
if( m_isMouseDown )
{
double dt = timeAt(event->pos().x()) - m_lastMousePos;
double currentT = m_scheduleRuleView->focusStartTime();
double proposedStartTime = currentT + dt;
if( m_scheduleRuleView->setFocusStartTime(proposedStartTime) )
{
event->accept();
}
}
m_lastMousePos = timeAt(event->pos().x());
}
void DayScheduleOverview::mousePressEvent(QMouseEvent * event)
{
if( (timeAt(event->pos().x()) <= m_scheduleRuleView->focusEndTime()) && (timeAt(event->pos().x()) >= m_scheduleRuleView->focusStartTime()) )
{
m_isMouseDown = true;
m_lastMousePos = timeAt(event->pos().x());
event->accept();
}
}
void DayScheduleOverview::mouseReleaseEvent(QMouseEvent * event)
{
m_isMouseDown = false;
m_lastMousePos = 0;
event->accept();
}
DaySchedulePlotArea::DaySchedulePlotArea(ScheduleDayEditor * scheduleDayEditor)
: QGraphicsView(scheduleDayEditor),
m_scheduleDayEditor(scheduleDayEditor),
m_currentItem(NULL),
m_currentHoverItem(NULL)
{
connect(this,SIGNAL(dayScheduleSceneChanged( DayScheduleScene *, double, double )),
m_scheduleDayEditor->scheduleDayView()->schedulesView(),SIGNAL(dayScheduleSceneChanged( DayScheduleScene *, double, double )));
setFocusPolicy(Qt::StrongFocus);
}
QGraphicsItem * DaySchedulePlotArea::segmentAt(QPoint point) const
{
double zoom = m_scheduleDayEditor->scheduleDayView()->zoom();
QPointF scenepoint = mapToScene(point);
return scene()->segmentAt(scenepoint.x(),scenepoint.y(),zoom);
}
int DaySchedulePlotArea::timeAt(double x) const
{
QPointF scenepoint = mapToScene(QPoint(x,0));
return scene()->timeAt(scenepoint.x());
}
boost::optional<double> DaySchedulePlotArea::valueAt(double x) const
{
int time = timeAt(x);
return scene()->valueAt(time);
}
DayScheduleScene * DaySchedulePlotArea::scene() const
{
return qobject_cast<DayScheduleScene *>(QGraphicsView::scene());
}
void DaySchedulePlotArea::mouseDoubleClickEvent(QMouseEvent * event)
{
QGraphicsItem * item = segmentAt(event->pos());
if( item )
{
if( dynamic_cast<CalendarSegmentItem *>(item) )
{
double time = scene()->timeAt(mapToScene(event->pos()).x());
double newTime = time;
if( newTime < 0.0 )
{
newTime = 0.0;
}
else if( newTime > SCENEWIDTH )
{
newTime = SCENEWIDTH;
}
double timeSnapLength = scene()->scheduleDayView()->snap();
double prevSnapTime = (int)(newTime / timeSnapLength) * timeSnapLength;
double nextSnapTime = prevSnapTime + timeSnapLength;
if( (newTime - prevSnapTime) < (timeSnapLength / 2.0) )
{
newTime = prevSnapTime;
}
else if( (nextSnapTime - newTime) < (timeSnapLength / 2.0) )
{
newTime = nextSnapTime;
}
scene()->addSegment(newTime);
event->accept();
emit dayScheduleSceneChanged(scene(),scene()->scheduleDayView()->lowerLimit(),scene()->scheduleDayView()->upperLimit());
}
else if( VCalendarSegmentItem * calendarItem = dynamic_cast<VCalendarSegmentItem *>(item) )
{
calendarItem->remove();
event->accept();
emit dayScheduleSceneChanged(scene(),scene()->scheduleDayView()->lowerLimit(),scene()->scheduleDayView()->upperLimit());
}
}
}
void DaySchedulePlotArea::mouseMoveEvent(QMouseEvent * event)
{
QPointF scenePos = mapToScene(event->pos());
m_currentHoverItem = NULL;
m_keyboardInputValue.clear();
if( m_currentItem )
{
if( CalendarSegmentItem * calendarItem = dynamic_cast<CalendarSegmentItem *>(m_currentItem) )
{
calendarItem->setHovering(true);
m_currentHoverItem = calendarItem;
setFocus();
calendarItem->update();
double value = 1.0 - (mapToScene(event->pos()).y() / SCENEHEIGHT);
if( value > 1.0 ) { value = 1.0; }
if( value < 0.0 ) { value = 0.0; }
calendarItem->setValue(value);
// Fixup next V item
VCalendarSegmentItem * _nextVCalendarItem = calendarItem->nextVCalendarItem();
if( _nextVCalendarItem )
{
_nextVCalendarItem->updateLength();
}
// Fixup prev V item
VCalendarSegmentItem * _previousVCalendarItem = calendarItem->previousVCalendarItem();
if( _previousVCalendarItem )
{
_previousVCalendarItem->updateLength();
}
scene()->update();
}
else if( VCalendarSegmentItem * calendarItem = dynamic_cast<VCalendarSegmentItem *>(m_currentItem) )
{
calendarItem->setHovering(true);
calendarItem->update();
if( calendarItem->isMouseDown() )
{
double time = scene()->timeAt(mapToScene(event->pos()).x());
double newTime = time;
if( newTime < 0.0 )
{
newTime = 0.0;
}
else if( newTime > SCENEWIDTH )
{
newTime = SCENEWIDTH;
}
double timeSnapLength = scene()->scheduleDayView()->snap();
if( CalendarSegmentItem * nextCalendarItem = calendarItem->nextCalendarItem() )
{
if( nextCalendarItem->endTime() - timeSnapLength - time < 1E-10 )
{
newTime = nextCalendarItem->endTime() - timeSnapLength;
}
}
if( CalendarSegmentItem * prevCalendarItem = calendarItem->previousCalendarItem() )
{
if( time - timeSnapLength - prevCalendarItem->startTime() < 1E-10 )
{
newTime = prevCalendarItem->startTime() + timeSnapLength;
}
}
double prevSnapTime = (int)(newTime / timeSnapLength) * timeSnapLength;
double nextSnapTime = prevSnapTime + timeSnapLength;
if( (newTime - prevSnapTime) < (timeSnapLength / 2.0) )
{
newTime = prevSnapTime;
}
else if( (nextSnapTime - newTime) < (timeSnapLength / 2.0) )
{
newTime = nextSnapTime;
}
calendarItem->setTime(newTime);
scene()->update();
}
}
}
else
{
QList<QGraphicsItem *> items = this->items();
for( QList<QGraphicsItem *>::iterator it = items.begin();
it < items.end();
++it )
{
if( CalendarSegmentItem * calendarItem = dynamic_cast<CalendarSegmentItem *>(*it) )
{
calendarItem->setHovering(false);
calendarItem->update();
}
else if( VCalendarSegmentItem * calendarItem = dynamic_cast<VCalendarSegmentItem *>(*it) )
{
calendarItem->setHovering(false);
calendarItem->update();
}
}
QGraphicsItem * item = segmentAt(mapFromScene(m_lastScenePos));
if( CalendarSegmentItem * calendarItem = dynamic_cast<CalendarSegmentItem *>(item) )
{
calendarItem->setHovering(true);
m_currentHoverItem = calendarItem;
setFocus();
calendarItem->update();
}
else if( VCalendarSegmentItem * calendarItem = dynamic_cast<VCalendarSegmentItem *>(item) )
{
calendarItem->setHovering(true);
calendarItem->update();
}
}
m_lastScenePos = scenePos;
QGraphicsView::mouseMoveEvent(event);
}
void DaySchedulePlotArea::mousePressEvent(QMouseEvent * event)
{
m_lastScenePos = mapToScene(event->pos());
m_currentItem = NULL;
m_currentHoverItem = NULL;
QGraphicsItem * item = segmentAt(event->pos());
if( item )
{
if( CalendarSegmentItem * calendarItem = dynamic_cast<CalendarSegmentItem *>(item) )
{
calendarItem->setMouseDown(true);
m_currentItem = calendarItem;
}
else if( VCalendarSegmentItem * calendarItem = dynamic_cast<VCalendarSegmentItem *>(item) )
{
calendarItem->setMouseDown(true);
m_currentItem = calendarItem;
}
}
QGraphicsView::mousePressEvent(event);
}
void DaySchedulePlotArea::mouseReleaseEvent(QMouseEvent * event)
{
QList<QGraphicsItem *> items = this->items();
for( QList<QGraphicsItem *>::iterator it = items.begin();
it < items.end();
++it )
{
if( CalendarSegmentItem * calendarItem = dynamic_cast<CalendarSegmentItem *>(*it) )
{
calendarItem->setMouseDown(false);
}
else if( VCalendarSegmentItem * calendarItem = dynamic_cast<VCalendarSegmentItem *>(*it) )
{
calendarItem->setMouseDown(false);
}
}
emit dayScheduleSceneChanged(scene(),scene()->scheduleDayView()->lowerLimit(),scene()->scheduleDayView()->upperLimit());
m_currentItem = NULL;
QGraphicsView::mouseReleaseEvent(event);
}
void DaySchedulePlotArea::keyPressEvent(QKeyEvent * event)
{
if( m_currentHoverItem )
{
if( event->key() == Qt::Key_Enter || event->key() == Qt::Key_Return )
{
ScheduleDayView * scheduleDayView = scene()->scheduleDayView();
double upperLimit = scheduleDayView->upperLimit();
double lowerLimit = scheduleDayView->lowerLimit();
double value = m_keyboardInputValue.toDouble();
double scaledValue = (value - lowerLimit) / (upperLimit - lowerLimit);
m_currentHoverItem->setValue(scaledValue);
m_keyboardInputValue.clear();
m_currentHoverItem->setHovering(false);
m_currentHoverItem = NULL;
emit dayScheduleSceneChanged(scene(),scene()->scheduleDayView()->lowerLimit(),scene()->scheduleDayView()->upperLimit());
}
else if( event->key() == Qt::Key_Minus )
{
m_keyboardInputValue.clear();
m_keyboardInputValue.append(event->text());
}
else if( event->key() == Qt::Key_0 ||
event->key() == Qt::Key_1 ||
event->key() == Qt::Key_2 ||
event->key() == Qt::Key_3 ||
event->key() == Qt::Key_4 ||
event->key() == Qt::Key_5 ||
event->key() == Qt::Key_6 ||
event->key() == Qt::Key_7 ||
event->key() == Qt::Key_8 ||
event->key() == Qt::Key_9 ||
event->key() == Qt::Key_Period
)
{
m_keyboardInputValue.append(event->text());
}
}
}
DayScheduleScene::DayScheduleScene(ScheduleDayView * scheduleDayView, const model::ScheduleDay & scheduleDay)
: QGraphicsScene(scheduleDayView),
m_firstSegment(NULL),
m_scheduleDayView(scheduleDayView),
m_scheduleDay(scheduleDay),
m_dirty(true)
{
setSceneRect(0,0,SCENEWIDTH,SCENEHEIGHT);
connect( m_scheduleDay.getImpl<openstudio::model::detail::ScheduleDay_Impl>().get(),
SIGNAL(onChange()),
this,
SLOT(scheduleRefresh()) );
refresh();
}
model::ScheduleDay DayScheduleScene::scheduleDay() const
{
return m_scheduleDay;
}
void DayScheduleScene::scheduleRefresh()
{
m_dirty = true;
QTimer::singleShot(0,this,SLOT(refresh()));
}
void DayScheduleScene::refresh()
{
if( m_dirty )
{
clearSegments();
std::vector<openstudio::Time> times = m_scheduleDay.times();
std::vector<double> realvalues;
if (m_scheduleDay.scheduleTypeLimits()) {
OSQuantityVector quantities = m_scheduleDay.getValues(m_scheduleDayView->isIP());
realvalues = quantities.values();
}
else {
realvalues = m_scheduleDay.values();
}
// The min and max values of the schedule as it appears on the screen
double minvalue = * std::min_element(realvalues.begin(),realvalues.end());
double maxvalue = * std::max_element(realvalues.begin(),realvalues.end());
// The upper and lower limt are the limits input from the user input fields.
double upperLimit = m_scheduleDayView->upperLimit();
double lowerLimit = m_scheduleDayView->lowerLimit();
if( maxvalue > upperLimit )
{
upperLimit = maxvalue; // + 0.05 * (maxvalue - minvalue);
m_scheduleDayView->setUpperLimit(upperLimit);
}
if( minvalue < lowerLimit )
{
lowerLimit = minvalue; // - 0.05 * (maxvalue - minvalue);
m_scheduleDayView->setLowerLimit(lowerLimit);
}
int i = 0;
double lastTime = 0.0;
CalendarSegmentItem * previousSegment = NULL;
for( std::vector<openstudio::Time>::iterator it = times.begin();
it < times.end();
++it )
{
double scaledValue = (realvalues[i] - lowerLimit) / (upperLimit - lowerLimit);
CalendarSegmentItem * segment = new CalendarSegmentItem();
addItem(segment);
segment->setValue(scaledValue);
segment->setStartTime(lastTime);
double time = it->totalSeconds();
segment->setEndTime(time);
if( previousSegment )
{
VCalendarSegmentItem * vSegment = new VCalendarSegmentItem();
addItem(vSegment);
segment->setPreviousVCalendarItem(vSegment);
vSegment->setNextCalendarItem(segment);
vSegment->setPreviousCalendarItem(previousSegment);
previousSegment->setNextVCalendarItem(vSegment);
vSegment->setTime(lastTime);
vSegment->updateLength();
}
else
{
m_firstSegment = segment;
}
previousSegment = segment;
lastTime = time;
i++;
}
m_scheduleDayView->update();
m_dirty = false;
}
}
ScheduleDayView * DayScheduleScene::scheduleDayView() const
{
return m_scheduleDayView;
}
CalendarSegmentItem * DayScheduleScene::segmentAt(double time) const
{
CalendarSegmentItem * segment = m_firstSegment;
while( segment )
{
if( segment->endTime() >= time )
{
return segment;
}
else
{
segment = segment->nextCalendarItem();
}
}
return NULL;
}
boost::optional<double> DayScheduleScene::valueAt(double time) const
{
if( CalendarSegmentItem * item = segmentAt(time) )
{
return item->value();
}
return boost::none;
}
void DayScheduleScene::addSegment(double untilTime,double value)
{
CalendarSegmentItem * segment = addSegment(untilTime);
segment->setValue(value);
}
CalendarSegmentItem * DayScheduleScene::addSegment(double untilTime)
{
CalendarSegmentItem * segment = segmentAt(untilTime);
double startTime = segment->startTime();
VCalendarSegmentItem * prevVCalendarItem = segment->previousVCalendarItem();
CalendarSegmentItem * item = new CalendarSegmentItem;
addItem(item);
VCalendarSegmentItem * vitem = new VCalendarSegmentItem;
addItem(vitem);
vitem->setPreviousCalendarItem(item);
vitem->setNextCalendarItem(segment);
segment->setPreviousVCalendarItem(vitem);
item->setPreviousVCalendarItem(prevVCalendarItem);
item->setNextVCalendarItem(vitem);
segment->setStartTime(untilTime);
item->setStartTime(startTime);
item->setEndTime(untilTime);
item->setValue(segment->value());
vitem->setTime(untilTime);
if( prevVCalendarItem )
{
prevVCalendarItem->setNextCalendarItem(item);
}
else
{
m_firstSegment = item;
}
vitem->updateLength();
return item;
}
void DayScheduleScene::clearSegments()
{
std::vector<CalendarSegmentItem *> _segments = segments();
for( std::vector<CalendarSegmentItem *>::iterator it = _segments.begin();
it < _segments.end();
++it )
{
if( VCalendarSegmentItem * vItem = (*it)->nextVCalendarItem() )
{
delete vItem;
}
delete *it;
}
m_firstSegment = NULL;
}
std::vector<CalendarSegmentItem *> DayScheduleScene::segments() const
{
std::vector<CalendarSegmentItem *> result;
CalendarSegmentItem * segment = m_firstSegment;
while( segment )
{
result.push_back(segment);
segment = segment->nextCalendarItem();
}
return result;
}
QGraphicsItem * DayScheduleScene::segmentAt(double x,double y, double zoom) const
{
int time = timeAt(x);
CalendarSegmentItem * segment = segmentAt(time);
QGraphicsItem * result = NULL;
double vtol = LINEWIDTH / 2.0;
double htol = LINEWIDTH / 2.0 / zoom;
if( segment )
{
if( (segment->vCenterPos() < y + vtol) && (segment->vCenterPos() > y - vtol) )
{
result = segment;
}
if( ! result )
{
if( VCalendarSegmentItem * item = segment->nextVCalendarItem() )
{
if( (item->hCenterPos() < x + htol) && (item->hCenterPos() > x - htol) )
{
if( (item->vCenterPos() < y + item->boundingRect().height() / 2.0) )
{
result = item;
}
}
}
}
if( ! result )
{
if( VCalendarSegmentItem * item = segment->previousVCalendarItem() )
{
if( (item->hCenterPos() < x + htol) && (item->hCenterPos() > x - htol) )
{
if( (item->vCenterPos() < y + item->boundingRect().height() / 2.0) )
{
result = item;
}
}
}
}
}
return result;
}
double DayScheduleScene::timeAt(double x) const
{
return x * SCENEWIDTH / SCENEWIDTH;
}
double DayScheduleScene::xAt(double time) const
{
return time * SCENEWIDTH / SCENEWIDTH;
}
ScheduleCalendarWidget::ScheduleCalendarWidget(MonthView * monthView)
: QCalendarWidget(monthView),
m_monthView(monthView)
{
}
void ScheduleCalendarWidget::paintCell(QPainter * painter, const QRect & rect, const QDate & date) const
{
painter->setBrush(QBrush(QColor(230,230,230)));
if( date.month() == m_monthView->month() )
{
int dayOfYear = date.dayOfYear();
int ruleIndex = m_monthView->yearOverview()->activeRuleIndices()[dayOfYear - 1];
QColor ruleColor = SchedulesView::colors[12];
if( ruleIndex > 12 )
{
ruleIndex = 12;
}
if( ruleIndex > -1 )
{
ruleColor = SchedulesView::colors[ruleIndex];
}
QString dateString = QString::number(date.day());
painter->setBrush(QBrush(ruleColor));
painter->drawRect(rect);
painter->drawText(rect,Qt::AlignHCenter | Qt::AlignVCenter,dateString);
}
else
{
painter->drawRect(rect);
}
}
MonthView::MonthView( YearOverview * yearOverview )
: QWidget(yearOverview),
m_yearOverview(yearOverview),
m_month(0)
{
QVBoxLayout * mainVLayout = new QVBoxLayout();
setLayout(mainVLayout);
mainVLayout->setContentsMargins(0,0,0,0);
mainVLayout->setSpacing(0);
m_monthLabel = new QLabel("January");
mainVLayout->addWidget(m_monthLabel,0,Qt::AlignCenter);
mainVLayout->addSpacing(5);
m_calendarWidget = new ScheduleCalendarWidget(this);
m_calendarWidget->setVerticalHeaderFormat(QCalendarWidget::NoVerticalHeader);
m_calendarWidget->setHorizontalHeaderFormat(QCalendarWidget::SingleLetterDayNames);
m_calendarWidget->setNavigationBarVisible(false);
m_calendarWidget->setSelectionMode(QCalendarWidget::NoSelection);
mainVLayout->addWidget(m_calendarWidget);
QFrame * line1 = new QFrame();
line1->setFrameShape(QFrame::HLine);
line1->setFixedHeight(1);
mainVLayout->addWidget(line1);
}
int MonthView::month() const
{
return m_month;
}
YearOverview * MonthView::yearOverview() const
{
return m_yearOverview;
}
void MonthView::setMonth(int month)
{
m_month = month;
std::string monthName = monthOfYear(month).valueName();
m_monthLabel->setText(QString::fromStdString(monthName));
update();
}
void MonthView::update()
{
int year = m_yearOverview->scheduleRuleset().model().getUniqueModelObject<model::YearDescription>().assumedYear();
QDate startDate(year,m_month,1);
QDate endDate(year,m_month,startDate.daysInMonth());
m_calendarWidget->setMinimumDate(startDate);
m_calendarWidget->setMaximumDate(endDate);
m_calendarWidget->update();
QWidget::update();
}
YearOverview::YearOverview( const model::ScheduleRuleset & scheduleRuleset, QWidget * parent )
: QWidget(parent),
m_scheduleRuleset(scheduleRuleset),
m_dirty(false)
{
refreshActiveRuleIndices();
QVBoxLayout * mainScrollLayout = new QVBoxLayout();
mainScrollLayout->setContentsMargins(0,0,0,0);
setLayout(mainScrollLayout);
QScrollArea * scrollArea = new QScrollArea();
scrollArea->setFrameStyle(QFrame::NoFrame);
scrollArea->setWidgetResizable(true);
scrollArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
scrollArea->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
mainScrollLayout->addWidget(scrollArea);
QWidget * scrollWidget = new QWidget();
scrollArea->setWidget(scrollWidget);
QVBoxLayout * mainLayout = new QVBoxLayout();
mainLayout->setContentsMargins(0,0,0,0);
scrollWidget->setLayout(mainLayout);
QGridLayout * gridLayout = new QGridLayout();
gridLayout->setContentsMargins(0,0,0,0);
m_januaryView = new MonthView(this);
m_januaryView->setMonth(1);
gridLayout->addWidget(m_januaryView,0,0);
m_februaryView = new MonthView(this);
m_februaryView->setMonth(2);
gridLayout->addWidget(m_februaryView,1,0);
m_marchView = new MonthView(this);
m_marchView->setMonth(3);
gridLayout->addWidget(m_marchView,2,0);
m_aprilView = new MonthView(this);
m_aprilView->setMonth(4);
gridLayout->addWidget(m_aprilView,3,0);
m_mayView = new MonthView(this);
m_mayView->setMonth(5);
gridLayout->addWidget(m_mayView,4,0);
m_juneView = new MonthView(this);
m_juneView->setMonth(6);
gridLayout->addWidget(m_juneView,5,0);
m_julyView = new MonthView(this);
m_julyView->setMonth(7);
gridLayout->addWidget(m_julyView,6,0);
m_augustView = new MonthView(this);
m_augustView->setMonth(8);
gridLayout->addWidget(m_augustView,7,0);
m_septemberView = new MonthView(this);
m_septemberView->setMonth(9);
gridLayout->addWidget(m_septemberView,8,0);
m_octoberView = new MonthView(this);
m_octoberView->setMonth(10);
gridLayout->addWidget(m_octoberView,9,0);
m_novemberView = new MonthView(this);
m_novemberView->setMonth(11);
gridLayout->addWidget(m_novemberView,10,0);
m_decemberView = new MonthView(this);
m_decemberView->setMonth(12);
gridLayout->addWidget(m_decemberView,11,0);
mainLayout->addLayout(gridLayout);
mainLayout->addStretch(10);
connect(m_scheduleRuleset.model().getImpl<openstudio::model::detail::Model_Impl>().get(),
SIGNAL(addWorkspaceObject(boost::shared_ptr<openstudio::detail::WorkspaceObject_Impl>,
const openstudio::IddObjectType&, const openstudio::UUID&)),
this,
SLOT(onModelAdd(boost::shared_ptr<openstudio::detail::WorkspaceObject_Impl>, const openstudio::IddObjectType&, const openstudio::UUID&)),
Qt::QueuedConnection);
std::vector<model::ScheduleRule> scheduleRules = m_scheduleRuleset.scheduleRules();
for( std::vector<model::ScheduleRule>::iterator it = scheduleRules.begin();
it < scheduleRules.end();
++it )
{
connect( it->getImpl<openstudio::model::detail::ScheduleRule_Impl>().get(),
SIGNAL(onChange()),
this,
SLOT(scheduleRefresh()) );
}
model::YearDescription yearDescription = m_scheduleRuleset.model().getUniqueModelObject<model::YearDescription>();
connect( yearDescription.getImpl<openstudio::model::detail::YearDescription_Impl>().get(),
SIGNAL(onChange()),
this,
SLOT(scheduleRefresh()) );
refresh();
}
void YearOverview::refreshActiveRuleIndices()
{
int year = m_scheduleRuleset.model().getUniqueModelObject<model::YearDescription>().assumedYear();
Date startDate(1,1,year);
Date endDate(12,31,year);
m_activeRuleIndices = m_scheduleRuleset.getActiveRuleIndices(startDate,endDate);
m_dirty = false;
}
void YearOverview::onModelAdd( boost::shared_ptr<openstudio::detail::WorkspaceObject_Impl> wo,
const openstudio::IddObjectType& iddType,
const openstudio::UUID& uuid )
{
boost::optional<model::ScheduleRule> scheduleRule = m_scheduleRuleset.model().getModelObject<model::ScheduleRule>(wo->handle());
if( scheduleRule )
{
if( scheduleRule->scheduleRuleset().handle() == m_scheduleRuleset.handle() )
{
connect( scheduleRule->getImpl<openstudio::model::detail::ScheduleRule_Impl>().get(),
SIGNAL(onChange()),
this,
SLOT(scheduleRefresh()) );
}
}
}
std::vector<int> YearOverview::activeRuleIndices() const
{
return m_activeRuleIndices;
}
void YearOverview::scheduleRefresh()
{
m_dirty = true;
QTimer::singleShot(0,this,SLOT(refresh()));
}
void YearOverview::refresh()
{
if( m_dirty )
{
refreshActiveRuleIndices();
m_januaryView->update();
m_februaryView->update();
m_marchView->update();
m_aprilView->update();
m_mayView->update();
m_juneView->update();
m_julyView->update();
m_augustView->update();
m_septemberView->update();
m_octoberView->update();
m_novemberView->update();
m_decemberView->update();
}
update();
}
model::ScheduleRuleset YearOverview::scheduleRuleset() const
{
return m_scheduleRuleset;
}
ScheduleTabHeader::ScheduleTabHeader( ScheduleTab * scheduleTab, QWidget * parent )
: QWidget(parent),
m_scheduleTab(scheduleTab),
m_mouseDown(false),
m_dirty(true)
{
setObjectName("ScheduleTabHeader");
QHBoxLayout * mainHLayout = new QHBoxLayout();
mainHLayout->setContentsMargins(5,5,5,5);
mainHLayout->setSpacing(5);
setLayout(mainHLayout);
QString style;
style.append("QWidget#ScheduleTabHeader { ");
style.append("background-color: #CECECE;");
style.append("}");
setStyleSheet(style);
m_mainLabel = new QLabel(this);
mainHLayout->addWidget(m_mainLabel,10);
m_mainLabel->setWordWrap(true);
//m_mainLabel->setFixedWidth(120);
mainHLayout->addStretch();
m_toggleButton = new QPushButton();
m_toggleButton->setFlat(true);
m_toggleButton->setCheckable(true);
m_toggleButton->setChecked(false);
m_toggleButton->setEnabled(false);
connect(m_toggleButton,SIGNAL(toggled(bool)),this,SIGNAL(toggleHeaderClicked(bool)));
mainHLayout->addWidget(m_toggleButton);
style.clear();
style.append("QPushButton { ");
style.append("border: none; ");
style.append("background-image: url(\":/images/toggle_arrow.png\"); ");
style.append("} ");
style.append("QPushButton:checked { ");
style.append("background-image: url(\":/images/toggle_arrow_closed.png\"); ");
style.append("} ");
m_toggleButton->setFixedSize(11,11);
m_toggleButton->setStyleSheet(style);
setFixedHeight(50);
m_selectionWidget = new QWidget(this);
m_selectionWidget->setFixedHeight(50);
style.clear();
style.append("QWidget { ");
style.append("background-color: qlineargradient(x1:0,y1:0,x2:0,y2:1,");
style.append(" stop: 0.0 #636161,");
style.append(" stop: 0.10 #636161,");
style.append(" stop: 0.15 #A3A3A3,");
style.append(" stop: 1.0 #A3A3A3);");
style.append("}");
m_selectionWidget->setStyleSheet(style);
m_selectionWidget->hide();
refresh();
connect(this,SIGNAL(scheduleClicked(const model::ScheduleRuleset &)),m_scheduleTab,SIGNAL(scheduleClicked(const model::ScheduleRuleset &)));
connect( m_scheduleTab->schedule().getImpl<openstudio::model::detail::ScheduleRuleset_Impl>().get(),
SIGNAL(onChange()),
this,
SLOT(refresh()) );
}
void ScheduleTabHeader::expand()
{
m_toggleButton->setChecked(false);
}
void ScheduleTabHeader::collapse()
{
m_toggleButton->setChecked(true);
}
void ScheduleTabHeader::toggle()
{
m_toggleButton->toggle();
}
void ScheduleTabHeader::refresh()
{
m_dirty = true;
QTimer::singleShot(0,this,SLOT(refreshNow()));
}
void ScheduleTabHeader::refreshNow()
{
if( m_dirty )
{
setText(QString::fromStdString(m_scheduleTab->schedule().name().get()));
m_dirty = false;
}
}
void ScheduleTabHeader::mouseReleaseEvent( QMouseEvent * event )
{
if( m_mouseDown )
{
emit scheduleClicked(scheduleTab()->schedule());
}
m_mouseDown = false;
event->accept();
}
void ScheduleTabHeader::mousePressEvent( QMouseEvent * event )
{
m_mouseDown = true;
event->accept();
}
ScheduleTab * ScheduleTabHeader::scheduleTab() const
{
return m_scheduleTab;
}
void ScheduleTabHeader::setSelected(bool selected)
{
m_mainLabel->raise();
m_toggleButton->raise();
if( selected )
{
m_selectionWidget->show();
}
else
{
m_selectionWidget->hide();
}
}
void ScheduleTabHeader::setText(const QString & text)
{
m_mainLabel->setText(text);
}
void ScheduleTabHeader::resizeEvent ( QResizeEvent * event )
{
m_selectionWidget->resize(event->size().width(),67);
QWidget::resizeEvent(event);
}
void ScheduleTabHeader::paintEvent ( QPaintEvent * event )
{
QStyleOption opt;
opt.init(this);
QPainter p(this);
style()->drawPrimitive(QStyle::PE_Widget, &opt, &p, this);
}
ScheduleTabContent::ScheduleTabContent( ScheduleTab * scheduleTab, QWidget * parent )
: QWidget(parent),
m_scheduleTab(scheduleTab)
{
QVBoxLayout * mainVLayout = new QVBoxLayout();
mainVLayout->setContentsMargins(5,5,5,5);
mainVLayout->setSpacing(5);
setLayout(mainVLayout);
QLabel * designDayLabel = new QLabel("Design Day Profiles");
mainVLayout->addWidget(designDayLabel);
QHBoxLayout * summerDesignDayLayout = new QHBoxLayout();
summerDesignDayLayout->setContentsMargins(0,0,0,0);
mainVLayout->addLayout(summerDesignDayLayout);
DefaultTab * summerTab = new DefaultTab(m_scheduleTab,DefaultTab::SUMMER);
summerDesignDayLayout->addWidget(summerTab);
QHBoxLayout * winterDesignDayLayout = new QHBoxLayout();
winterDesignDayLayout->setContentsMargins(0,0,0,0);
mainVLayout->addLayout(winterDesignDayLayout);
DefaultTab * winterTab = new DefaultTab(m_scheduleTab,DefaultTab::WINTER);
winterDesignDayLayout->addWidget(winterTab);
QHBoxLayout * runPeriodLayout = new QHBoxLayout();
runPeriodLayout->setContentsMargins(0,0,0,0);
mainVLayout->addLayout(runPeriodLayout);
QPushButton * runPeriodButton = new QPushButton();
runPeriodButton->setText("Run Period Profiles");
runPeriodButton->setObjectName("Button");
QString style;
style.append("QWidget#Button { ");
style.append("background: none; border: none; ");
style.append("} ");
style.append("QWidget#Button:hover { ");
style.append("color: #2C3233;");
style.append("}");
runPeriodButton->setStyleSheet(style);
runPeriodButton->setToolTip("Click to add new run period profile");
runPeriodLayout->addWidget(runPeriodButton);
runPeriodLayout->addStretch();
connect(runPeriodButton,SIGNAL(clicked()),this,SLOT(onRunPeriodRulesClicked()));
connect( this,SIGNAL(runPeriodRulesClicked(const model::ScheduleRuleset)),
m_scheduleTab->schedulesView(),SLOT(showAddRulePage(const model::ScheduleRuleset)));
QPushButton * addButton = new QPushButton();
addButton->setStyleSheet("QPushButton { border: none; background-image: url(\":/images/add-small.png\"); }");
addButton->setFixedSize(20,20);
connect(addButton,SIGNAL(clicked()),this,SLOT(onRunPeriodRulesClicked()));
runPeriodLayout->addWidget(addButton);
m_ruleLayout = new QVBoxLayout();
m_ruleLayout->setContentsMargins(0,0,0,0);
m_ruleLayout->setSpacing(0);
mainVLayout->addLayout(m_ruleLayout);
QHBoxLayout * defaultLayout = new QHBoxLayout();
defaultLayout->setContentsMargins(0,0,0,0);
mainVLayout->addLayout(defaultLayout);
DefaultTab * defaultTab = new DefaultTab(m_scheduleTab);
defaultLayout->addWidget(defaultTab);
}
void ScheduleTabContent::refresh()
{
if( m_dirty )
{
model::ScheduleRuleset scheduleRuleset = m_scheduleTab->schedule();
QLayoutItem *child;
while ((child = m_ruleLayout->takeAt(0)) != 0)
{
delete child->widget();
delete child;
}
std::vector<model::ScheduleRule> scheduleRules = scheduleRuleset.scheduleRules();
for( std::vector<model::ScheduleRule>::iterator it = scheduleRules.begin();
it < scheduleRules.end();
++it )
{
ScheduleTabRule * scheduleTabRule = new ScheduleTabRule(m_scheduleTab,*it);
m_ruleLayout->addWidget(scheduleTabRule);
}
m_dirty = false;
}
}
void ScheduleTabContent::scheduleRefresh()
{
m_dirty = true;
QTimer::singleShot(0,this,SLOT(refresh()));
}
void ScheduleTabContent::onRunPeriodRulesClicked()
{
emit runPeriodRulesClicked(scheduleTab()->schedule());
}
void ScheduleTabContent::onDefaultClicked()
{
emit defaultClicked(scheduleTab()->schedule());
}
void ScheduleTabContent::addScheduleRule( const model::ScheduleRule & scheduleRule )
{
ScheduleTabRule * scheduleTabRule = new ScheduleTabRule(m_scheduleTab,scheduleRule);
m_ruleLayout->insertWidget(0,scheduleTabRule);
}
ScheduleTab * ScheduleTabContent::scheduleTab() const
{
return m_scheduleTab;
}
DefaultTab::DefaultTab( ScheduleTab * scheduleTab, TabType type )
: QWidget( scheduleTab ),
m_mouseDown(false),
m_scheduleTab(scheduleTab),
m_type(type),
m_hovering(false)
{
setFixedHeight(25);
bool isConnected = false;
isConnected = connect( this,SIGNAL(defaultClicked(model::ScheduleRuleset)),
m_scheduleTab->schedulesView(),SLOT(showDefaultScheduleDay(const model::ScheduleRuleset)) );
OS_ASSERT(isConnected);
isConnected = connect( this,SIGNAL(winterClicked(model::ScheduleRuleset)),
m_scheduleTab->schedulesView(),SLOT(showWinterScheduleDay(model::ScheduleRuleset)) );
OS_ASSERT(isConnected);
isConnected = connect( this,SIGNAL(summerClicked(model::ScheduleRuleset)),
m_scheduleTab->schedulesView(),SLOT(showSummerScheduleDay(model::ScheduleRuleset)) );
OS_ASSERT(isConnected);
QHBoxLayout * mainHLayout = new QHBoxLayout();
mainHLayout->setContentsMargins(10,0,0,0);
setLayout(mainHLayout);
//m_label = new QLabel("Default");
switch( m_type )
{
case SUMMER :
m_label = new QLabel("Summer");
setToolTip("Click to edit summer design day profile");
break;
case WINTER :
m_label = new QLabel("Winter");
setToolTip("Click to edit winter design day profile");
break;
default :
m_label = new QLabel("Default");
setToolTip("Click to edit default profile");
}
m_label->setMouseTracking(true);
mainHLayout->addWidget(m_label);
setMouseTracking(true);
}
void DefaultTab::paintEvent ( QPaintEvent * event )
{
QStyleOption opt;
opt.init(this);
QPainter p(this);
style()->drawPrimitive(QStyle::PE_Widget, &opt, &p, this);
if( m_hovering )
{
p.setBrush(QBrush(QColor(207,207,207)));
p.setPen(Qt::NoPen);
p.drawRect(0,0,size().width() - 1,size().height() - 1);
}
p.setPen(Qt::SolidLine);
p.setBrush(QBrush(m_scheduleTab->schedulesView()->colors[12]));
p.drawRect(0,0,5,size().height() - 1);
p.setBrush(QBrush(QColor(Qt::black)));
p.drawLine(0,0,size().width(),0);
p.drawLine(0,size().height() - 1,size().width(),size().height() - 1);
}
void DefaultTab::mouseReleaseEvent( QMouseEvent * event )
{
if( m_mouseDown )
{
model::ScheduleRuleset schedule = m_scheduleTab->schedule();
switch( m_type )
{
case DEFAULT :
emit defaultClicked(schedule);
break;
case SUMMER :
emit summerClicked(schedule);
break;
case WINTER :
emit winterClicked(schedule);
break;
}
}
m_mouseDown = false;
event->accept();
}
void DefaultTab::mouseMoveEvent( QMouseEvent * event )
{
m_hovering = true;
update();
event->accept();
}
void DefaultTab::mousePressEvent( QMouseEvent * event )
{
m_mouseDown = true;
event->accept();
}
void DefaultTab::leaveEvent ( QEvent * event )
{
m_mouseDown = false;
m_hovering = false;
update();
event->accept();
}
ScheduleTabRule::ScheduleTabRule( ScheduleTab * scheduleTab,
const model::ScheduleRule & scheduleRule,
QWidget * parent )
: QWidget( parent ),
m_scheduleTab(scheduleTab),
m_scheduleRule(scheduleRule),
m_mouseDown(false),
m_dirty(true),
m_hovering(false)
{
setFixedHeight(25);
connect(this,SIGNAL(clicked(model::ScheduleRule)),
m_scheduleTab->schedulesView(),SLOT(showScheduleRule(model::ScheduleRule)));
QHBoxLayout * mainHLayout = new QHBoxLayout();
mainHLayout->setContentsMargins(10,0,0,0);
setLayout(mainHLayout);
m_label = new QLabel();
m_label->setMouseTracking(true);
mainHLayout->addWidget(m_label);
scheduleRefresh();
connect( m_scheduleRule.getImpl<openstudio::model::detail::ScheduleRule_Impl>().get(),
SIGNAL(onChange()),
this,
SLOT(scheduleRefresh()) );
setMouseTracking(true);
}
void ScheduleTabRule::refresh()
{
if( m_dirty )
{
QString stringLabel("Priority ");
stringLabel.append(QString::number(m_scheduleRule.ruleIndex() + 1));
m_label->setText(stringLabel);
QString tooltip("Click to edit ");
tooltip.append(QString::fromStdString(m_scheduleRule.name().get()));
setToolTip(tooltip);
m_dirty = false;
}
}
void ScheduleTabRule::scheduleRefresh()
{
m_dirty = true;
QTimer::singleShot(0,this,SLOT(refresh()));
}
void ScheduleTabRule::paintEvent ( QPaintEvent * event )
{
QStyleOption opt;
opt.init(this);
QPainter p(this);
style()->drawPrimitive(QStyle::PE_Widget, &opt, &p, this);
int i = m_scheduleRule.ruleIndex();
if( i > 12 )
{
i = 12;
}
if( m_hovering )
{
p.setBrush(QBrush(QColor(207,207,207)));
p.setPen(Qt::NoPen);
p.drawRect(0,0,size().width() - 1,size().height() - 1);
}
p.setBrush(QBrush(m_scheduleTab->schedulesView()->colors[i]));
p.setPen(Qt::SolidLine);
p.drawRect(0,0,5,size().height() - 1);
p.setBrush(QBrush(QColor(Qt::black)));
if( m_scheduleRule.ruleIndex() == 0 )
{
p.drawLine(0,0,size().width(),0);
}
p.drawLine(0,size().height() - 1,size().width(),size().height() - 1);
}
void ScheduleTabRule::mouseMoveEvent( QMouseEvent * event )
{
m_hovering = true;
update();
event->accept();
}
void ScheduleTabRule::mouseReleaseEvent( QMouseEvent * event )
{
if( m_mouseDown )
{
emit clicked(m_scheduleRule);
}
m_mouseDown = false;
event->accept();
}
void ScheduleTabRule::mousePressEvent( QMouseEvent * event )
{
m_mouseDown = true;
event->accept();
}
void ScheduleTabRule::leaveEvent ( QEvent * event )
{
m_mouseDown = false;
m_hovering = false;
update();
event->accept();
}
ScheduleTab::ScheduleTab(const model::ScheduleRuleset & schedule, SchedulesView * schedulesView, QWidget * parent)
: QWidget(parent),
m_mouseDown(false),
m_selected(false),
m_schedule(schedule),
m_schedulesView(schedulesView)
{
QVBoxLayout * mainVLayout = new QVBoxLayout();
mainVLayout->setContentsMargins(0,0,0,0);
mainVLayout->setSpacing(0);
setLayout(mainVLayout);
m_header = new ScheduleTabHeader(this);
m_header->setText(QString::fromStdString(m_schedule.name().get()));
mainVLayout->addWidget(m_header);
QFrame * line1 = new QFrame();
line1->setFrameShape(QFrame::HLine);
line1->setFixedHeight(1);
mainVLayout->addWidget(line1);
m_content = new ScheduleTabContent(this);
mainVLayout->addWidget(m_content);
m_content->setVisible(false);
QFrame * line2 = new QFrame();
line2->setFrameShape(QFrame::HLine);
line2->setFixedHeight(1);
mainVLayout->addWidget(line2);
connect(m_header,SIGNAL(toggleHeaderClicked( bool)),this,SLOT(onToggleHeaderClicked(bool)));
}
void ScheduleTab::expand()
{
m_content->show();
m_header->expand();
}
void ScheduleTab::collapse()
{
m_content->hide();
m_header->collapse();
}
void ScheduleTab::toggle()
{
m_header->toggle();
m_content->setVisible(! m_content->isVisible() );
}
void ScheduleTab::onToggleHeaderClicked(bool close)
{
//if( close )
//{
// m_content->hide();
//}
//else
//{
// m_content->show();
//}
}
ScheduleTabHeader * ScheduleTab::scheduleTabHeader() const
{
return m_header;
}
ScheduleTabContent * ScheduleTab::scheduleTabContent() const
{
return m_content;
}
SchedulesView * ScheduleTab::schedulesView() const
{
return m_schedulesView;
}
model::ScheduleRuleset ScheduleTab::schedule()
{
return m_schedule;
}
void ScheduleTab::setSelected(bool selected)
{
m_header->setSelected(selected);
m_selected = selected;
}
bool ScheduleTab::selected()
{
return m_selected;
}
void ScheduleTab::paintEvent ( QPaintEvent * event )
{
QStyleOption opt;
opt.init(this);
QPainter p(this);
style()->drawPrimitive(QStyle::PE_Widget, &opt, &p, this);
}
void ScheduleTab::leaveEvent ( QEvent * event )
{
m_mouseDown = false;
event->accept();
}
void ScheduleTab::resizeEvent ( QResizeEvent * event )
{
}
void ScheduleTab::onRemoveClicked()
{
}
void ScheduleTab::onObjectChanged()
{
}
void ScheduleTab::refresh()
{
}
NewRuleView::NewRuleView( const model::ScheduleRuleset & scheduleRuleset, SchedulesView * schedulesView, Type type )
: QWidget(schedulesView),
m_schedulesView(schedulesView),
m_scheduleRuleset(scheduleRuleset),
m_type(type)
{
QVBoxLayout * mainVLayout = new QVBoxLayout();
mainVLayout->setContentsMargins(20,20,20,20);
switch( m_type )
{
case SUMMER :
{
QLabel * label = new QLabel();
QString text;
text.append("The summer design day profile is not set, therefore the default run period profile will be used.");
text.append(" To override the default run period profile select one of the following:");
label->setText(text);
label->setWordWrap(true);
mainVLayout->addWidget(label);
mainVLayout->addSpacing(10);
break;
}
case WINTER :
{
QLabel * label = new QLabel();
QString text;
text.append("The winter design day profile is not set, therefore the default run period profile will be used.");
text.append(" To override the default run period profile select one of the following:");
label->setText(text);
label->setWordWrap(true);
mainVLayout->addWidget(label);
mainVLayout->addSpacing(10);
break;
}
default :
break;
}
QHBoxLayout * mainHLayout = new QHBoxLayout();
mainHLayout->setContentsMargins(0,0,0,0);
setLayout(mainVLayout);
QWidget * box = new QWidget();
QVBoxLayout * innerVLayout = new QVBoxLayout();
innerVLayout->setContentsMargins(0,0,0,0);
box->setLayout(innerVLayout);
mainHLayout->addWidget(box);
mainVLayout->addLayout(mainHLayout);
if( m_type == DEFAULT )
{
QLabel * selectLabel = new QLabel();
selectLabel->setText("Select One of the Following:");
innerVLayout->addWidget(selectLabel);
}
QHBoxLayout * newEmptyLayout = new QHBoxLayout();
newEmptyLayout->setContentsMargins(0,0,0,0);
QRadioButton * newEmptyButton = new QRadioButton();
newEmptyButton->setText("Make a New Profile");
newEmptyButton->setChecked(true);
newEmptyLayout->addWidget(newEmptyButton);
innerVLayout->addLayout(newEmptyLayout);
//QHBoxLayout * newLayout = new QHBoxLayout();
//newLayout->setContentsMargins(0,0,0,0);
//QRadioButton * newButton = new QRadioButton();
//newLayout->addWidget(newButton);
//newButton->setText("Make a New Profile Based on:");
//QComboBox * newComboBox = new QComboBox();
//newLayout->addWidget(newComboBox);
//innerVLayout->addLayout(newLayout);
QHBoxLayout * addLayout = new QHBoxLayout();
addLayout->addStretch();
addLayout->setContentsMargins(0,0,0,0);
QPushButton * addButton = new QPushButton();
addButton->setText("Add");
addButton->setObjectName("StandardBlueButton");
addLayout->addWidget(addButton);
innerVLayout->addLayout(addLayout);
connect(addButton,SIGNAL(clicked()),SLOT(onAddClicked()));
connect(this,SIGNAL(addRuleClicked(model::ScheduleRuleset &)),schedulesView,SIGNAL(addRuleClicked(model::ScheduleRuleset &)));
connect(this,SIGNAL(addSummerProfileClicked(model::ScheduleRuleset &)),schedulesView,SIGNAL(addSummerProfileClicked(model::ScheduleRuleset &)));
connect(this,SIGNAL(addWinterProfileClicked(model::ScheduleRuleset &)),schedulesView,SIGNAL(addWinterProfileClicked(model::ScheduleRuleset &)));
innerVLayout->addStretch();
mainHLayout->addStretch();
}
void NewRuleView::onAddClicked()
{
switch( m_type )
{
case SUMMER :
emit addSummerProfileClicked(m_scheduleRuleset);
break;
case WINTER :
emit addWinterProfileClicked(m_scheduleRuleset);
break;
default :
emit addRuleClicked(m_scheduleRuleset);
}
}
ScheduleRulesetView::ScheduleRulesetView(const model::ScheduleRuleset & scheduleRuleset)
: QWidget(),
m_scheduleRuleset(scheduleRuleset)
{
QVBoxLayout * mainVLayout = new QVBoxLayout();
mainVLayout->setContentsMargins(10,10,10,10);
mainVLayout->setSpacing(10);
setLayout(mainVLayout);
QLabel * nameLabel = new QLabel("Name:");
nameLabel->setObjectName("H2");
mainVLayout->addWidget(nameLabel);
OSLineEdit * lineEdit = new OSLineEdit();
lineEdit->bind(m_scheduleRuleset,"name");
mainVLayout->addWidget(lineEdit);
mainVLayout->addStretch();
}
} // openstudio
|
ibcom/mydigitalstructure-learn-xero
|
node_modules/xero-node/dist/gen/model/payroll-uk/earningsTemplate.js
|
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
class EarningsTemplate {
static getAttributeTypeMap() {
return EarningsTemplate.attributeTypeMap;
}
}
exports.EarningsTemplate = EarningsTemplate;
EarningsTemplate.discriminator = undefined;
EarningsTemplate.attributeTypeMap = [
{
"name": "payTemplateEarningID",
"baseName": "payTemplateEarningID",
"type": "string"
},
{
"name": "ratePerUnit",
"baseName": "ratePerUnit",
"type": "number"
},
{
"name": "numberOfUnits",
"baseName": "numberOfUnits",
"type": "number"
},
{
"name": "fixedAmount",
"baseName": "fixedAmount",
"type": "number"
},
{
"name": "earningsRateID",
"baseName": "earningsRateID",
"type": "string"
},
{
"name": "name",
"baseName": "name",
"type": "string"
}
];
//# sourceMappingURL=earningsTemplate.js.map
|
scossin/abbreviations
|
java/common/src/main/java/fr/erias/edsabb/writer/WriteOutput.java
|
package fr.erias.edsabb.writer;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
public class WriteOutput implements IWriteOutput {
private FileOutputStream fos;
public WriteOutput(File outputFile) throws IOException {
outputFile.delete();
outputFile.createNewFile();
boolean append = true;
fos = new FileOutputStream(outputFile, append);
}
public FileOutputStream getFileOutputStream() {
return(fos);
}
@Override
public void write (String line) throws IOException {
fos.write(line.getBytes());
}
public void close() throws IOException {
this.fos.close();
}
}
|
viacheslavpleshkov/unit-factory-ucode-uchat
|
client/src/json/auth/mx_json_log_out.c
|
#include "uchat_client.h"
char *mx_json_log_out_request(t_json_data *data) {
char *s;
*(int *)s = asprintf(&s, mx_get_json_format_template(JS_LOG_OUT),
JS_LOG_OUT, data->user_id, data->token) - 4;
return s;
}
|
M-Yankov/CPlusPlus
|
03.Inheritance/School/Teacher.h
|
#ifndef Teacher_h
#define Teacher_h
#include "Person.h"
class Teacher : public Person
{
private:
unsigned short _daysInSoftUni;
float _salary;
public:
Teacher(unsigned short id, std::string name, int currentCourse, float salary, unsigned short daysInSoftUni);
float getSalary();
void setSalary(float salary);
unsigned short getDaysInSoftUni();
void setDaysInSoftUni(unsigned short days);
std::string toString() override;
};
#endif // !Teacher_h
|
rwietter/codebase
|
javascript/ECMAScript-Course/8-ForEach/trste.js
|
let Frequency = new Array(
"a",
"b",
"c",
"a",
"e",
"f",
"g",
"h",
"i",
"j",
"k",
"l",
"m",
"n",
"o",
"p",
"q",
"r",
"s",
"t",
"u",
"v",
"x",
"w",
"y",
"z"
);
function hashFunc(c) {
return c - "a";
}
function countFre(S) {
for (let i = 0; i < S.length; ++i) {
let index = hashFunc(S[i]);
Frequency[index]++;
}
for (let i = 0; i < 26; ++i) {
console.log(i + "a", Frequency[i]);
}
}
countFre(Frequency);
function countFree(S) {
for (let c = "a"; c <= "z"; ++c) {
let frequency = 0;
for (let i = 0; i < S.length; ++i) {
if (S[i] == c) {
frequency++;
}
console.log(i + "a", Frequency[i], frequency);
}
}
}
countFree(Frequency);
|
bingchunjin/1806_SDK
|
uboot/board/freescale/common/pq-mds-pib.h
|
/*
* Copyright (C) 2007 Freescale Semiconductor, Inc.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation;
*/
extern int pib_init(void);
|
emthrm/library
|
test/graph/topological_sort.test.cpp
|
<gh_stars>1-10
/*
* @brief グラフ/トポロジカルソート
*/
#define IGNORE
#define PROBLEM "http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=GRL_4_B"
#include <iostream>
#include <vector>
#include "../../graph/edge.hpp"
#include "../../graph/topological_sort.hpp"
int main() {
int v, e;
std::cin >> v >> e;
std::vector<std::vector<Edge<bool>>> graph(v);
while (e--) {
int s, t;
std::cin >> s >> t;
graph[s].emplace_back(s, t);
}
for (const int ver : topological_sort(graph)) std::cout << ver << '\n';
return 0;
}
|
BoleynSu/CP-CompetitiveProgramming
|
archives/problemset/poj.org/3261.cpp
|
<reponame>BoleynSu/CP-CompetitiveProgramming
#include <stdio.h>
#include <string.h>
const int LOG2_MAXLENGTH=16;
const int MAXLENGTH=1<<LOG2_MAXLENGTH;
const int MAXALPHABET=1000002;
typedef int string[MAXLENGTH];
int sort[MAXLENGTH];
int _SA[MAXLENGTH],_rank[MAXLENGTH],_TSA[MAXLENGTH],_Trank[MAXLENGTH];
int* SA=_SA;
int* rank=_rank;
int* TSA=_TSA;
int* Trank=_Trank;
void quick_sort(string s,int L,int R)
{
int i=L,j=R,mid=s[SA[(L+R)>>1]],swap;
while (i<=j)
{
while (s[SA[i]]<mid) i++;
while (s[SA[j]]>mid) j--;
if (i<=j)
{
swap=SA[i],SA[i]=SA[j],SA[j]=swap;
i++,j--;
}
}
if (L<j) quick_sort(s,L,j);
if (i<R) quick_sort(s,i,R);
}
void get_SA(string s,int length)
{
for (int i=1;i<=length;i++) SA[i]=i;
quick_sort(s,1,length);
rank[SA[1]]=1;
for (int i=2;i<=length;i++)
if (s[SA[i]]==s[SA[i-1]]) rank[SA[i]]=rank[SA[i-1]];
else rank[SA[i]]=rank[SA[i-1]]+1;
for (int block=1;block<length;block<<=1)
{
for (int i=1;i<=length;i++) sort[rank[SA[i]]]=i;
for (int i=length;i>=1;i--)
if (SA[i]-block>=1) TSA[sort[rank[SA[i]-block]]--]=SA[i]-block;
for (int i=length-block+1;i<=length;i++)
TSA[sort[rank[i]]--]=i;
int* swap;
swap=SA,SA=TSA,TSA=swap;
swap=rank,rank=Trank,Trank=swap;
rank[SA[1]]=1;
for (int i=2;i<=length;i++)
if (Trank[SA[i]]==Trank[SA[i-1]]
&&Trank[SA[i]+block]==Trank[SA[i-1]+block])
rank[SA[i]]=rank[SA[i-1]];
else rank[SA[i]]=rank[SA[i-1]]+1;
}
}
int height[MAXLENGTH];
void get_height(string s,int length)
{
for (int h=0,i=1;i<=length;i++)
{
if (h) h--;
if (rank[i]!=1)
{
int j=SA[rank[i]-1];
while (s[i+h]==s[j+h]) h++;
}
height[rank[i]]=h;
}
}
int N,K;
string a;
bool check(int value)
{
int i=1;
while (i<=N)
{
while (i<=N&&height[i]<value) i++;
int repeat=1;
while (i<=N&&height[i]>=value)
{
repeat++;
i++;
}
if (repeat>=K) return true;
}
return false;
}
int main()
{
scanf("%d%d",&N,&K);
for (int i=1;i<=N;i++) scanf("%d",a+i);
get_SA(a,N);
get_height(a,N);
int L=0,R=N;
while (L+1!=R)
{
int mid=(L+R)>>1;
if (check(mid)) L=mid;
else R=mid;
}
printf("%d\n",L);
}
|
danielirias/towpod
|
app/src/main/java/net/towpod/actTestLocationOriginal.java
|
<reponame>danielirias/towpod
package net.towpod;
import android.Manifest;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.TextView;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
public class actTestLocationOriginal extends AppCompatActivity {
LocationManager locationManager;
double longitudeBest, latitudeBest;
double longitudeGPS, latitudeGPS;
double longitudeNetwork, latitudeNetwork;
TextView longitudeValueBest, latitudeValueBest;
TextView longitudeValueGPS, latitudeValueGPS;
TextView longitudeValueNetwork, latitudeValueNetwork;
public String Proveedor;
public String strLatGPS, strLonGPS;
public String strLatNET, strLonNET;
public String strLatBest, strLonBest;
String Latitud, Longitud;
String Direccion, Ciudad, CodigoPostal, ZonaDestacada, SubArea, Estado, CodigoEstado, Pais, CodigoPais;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.act_test_location);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
longitudeValueBest = (TextView) findViewById(R.id.longitudeValueBest);
latitudeValueBest = (TextView) findViewById(R.id.latitudeValueBest);
longitudeValueGPS = (TextView) findViewById(R.id.longitudeValueGPS);
latitudeValueGPS = (TextView) findViewById(R.id.latitudeValueGPS);
longitudeValueNetwork = (TextView) findViewById(R.id.longitudeValueNetwork);
latitudeValueNetwork = (TextView) findViewById(R.id.latitudeValueNetwork);
}
@Override
protected void onStart()
{
super.onStart();
GetGPSUpdates();
GetNetworkUpdates();
GetBestUpdates();
}
//==============================================================================================
//INICIO DE LOCALIZACION========================================================================
//==============================================================================================
private boolean checkLocation()
{
if (!isLocationEnabled())
showAlert();
return isLocationEnabled();
}
private void showAlert()
{
final AlertDialog.Builder dialog = new AlertDialog.Builder(this);
dialog.setTitle("Servicios de ubicación")
.setMessage("Su ubicación está desactivada.\nPor favor active su ubicación.")
.setPositiveButton("Configurar de ubicación", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
Intent myIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(myIntent);
}
})
.setNegativeButton("Cancelar", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
}
});
dialog.show();
}
private boolean isLocationEnabled()
{
return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) ||
locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
}
public void GetGPSUpdates()
{
if (!checkLocation())
return;
locationManager.removeUpdates(locationListenerGPS);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)
{
}
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 3000, 1, locationListenerGPS);
}
public void GetNetworkUpdates()
{
if (!checkLocation())
return;
locationManager.removeUpdates(locationListenerNetwork);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)
{
}
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 3000, 1, locationListenerNetwork);
}
public void GetBestUpdates()
{
if (!checkLocation())
return;
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)
{
}
locationManager.removeUpdates(locationListenerBest);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(true);
criteria.setPowerRequirement(Criteria.POWER_LOW);
Proveedor = locationManager.getBestProvider(criteria, true);
if (Proveedor != null)
{
locationManager.requestLocationUpdates(Proveedor, 3000, 1, locationListenerBest);
//Toast.makeText(this, "USANDO: " + Proveedor, Toast.LENGTH_LONG).show();
}
}
private final LocationListener locationListenerNetwork = new LocationListener()
{
public void onLocationChanged(Location location)
{
longitudeNetwork = location.getLongitude();
latitudeNetwork = location.getLatitude();
Latitud = String.valueOf(location.getLatitude());
Longitud = String.valueOf(location.getLongitude());
runOnUiThread(new Runnable()
{
@Override
public void run()
{
longitudeValueNetwork.setText(longitudeNetwork + "");
latitudeValueNetwork.setText(latitudeNetwork + "");
strLatNET = String.valueOf(latitudeNetwork);
strLonNET = String.valueOf(longitudeNetwork);
SetMyBestLocation();
//Toast.makeText(actTestLocation.this, "NETWORK updated", Toast.LENGTH_SHORT).show();
}
});
}
@Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
@Override
public void onProviderEnabled(String s) {
}
@Override
public void onProviderDisabled(String s) {
}
};
private final LocationListener locationListenerGPS = new LocationListener()
{
public void onLocationChanged(Location location)
{
longitudeGPS = location.getLongitude();
latitudeGPS = location.getLatitude();
Latitud = String.valueOf(location.getLatitude());
Longitud = String.valueOf(location.getLongitude());
runOnUiThread(new Runnable()
{
@Override
public void run()
{
longitudeValueGPS.setText(longitudeGPS + "");
latitudeValueGPS.setText(latitudeGPS + "");
strLatGPS = String.valueOf(latitudeBest);
strLonGPS = String.valueOf(longitudeBest);
SetMyBestLocation();
//Toast.makeText(actTestLocation.this, "GPS updated", Toast.LENGTH_SHORT).show();
}
});
}
@Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
@Override
public void onProviderEnabled(String s) {
}
@Override
public void onProviderDisabled(String s) {
}
};
private final LocationListener locationListenerBest = new LocationListener()
{
public void onLocationChanged(Location location)
{
latitudeBest = location.getLatitude();
longitudeBest = location.getLongitude();
Latitud = String.valueOf(location.getLatitude());
Longitud = String.valueOf(location.getLongitude());
runOnUiThread(new Runnable()
{
@Override
public void run()
{
longitudeValueBest.setText(longitudeBest + "");
latitudeValueBest.setText(latitudeBest + "");
strLatBest = String.valueOf(latitudeBest);
strLonBest = String.valueOf(longitudeBest);
SetMyBestLocation();
//Toast.makeText(actTestLocation.this, Proveedor +" actualizado", Toast.LENGTH_SHORT).show();
}
});
}
@Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
@Override
public void onProviderEnabled(String s) {
}
@Override
public void onProviderDisabled(String s) {
}
};
public void SetMyBestLocation()
{
if (Latitud.toString().substring(0,1).equals("0"))
{
Latitud = strLatNET;
Longitud = strLonNET;
}
Geocoder geocoder = new Geocoder(this, Locale.getDefault());
List<Address> addresses = null;
try
{
addresses = geocoder.getFromLocation(Double.parseDouble(Latitud), Double.parseDouble(Longitud), 1);
}
catch (IOException e1)
{
Log.e("LocationSampleActivity", "IO Exception in getFromLocation()");
e1.printStackTrace();
}
// If the reverse geocode returned an address
if (addresses != null && addresses.size() > 0)
{
// Get the first address
Address address = addresses.get(0);
Direccion = address.getAddressLine(0);
Ciudad = address.getLocality();
Estado = address.getAdminArea();
CodigoPais = address.getCountryCode();
Pais = address.getCountryName();
}
TextView addressText = (TextView) findViewById(R.id.addressText);
addressText.setText(Latitud + "\n" + Longitud + "\n" + Ciudad + "\n" + Pais);
//Toast.makeText(this, Latitud + "\n" + Longitud + "\n" + Pais, Toast.LENGTH_SHORT).show();
}
//==============================================================================================
//FIN DE LOCALIZACION===========================================================================
//==============================================================================================
}
|
weso/umlShaclex
|
src/main/scala/es/weso/uml/Schema2UML.scala
|
<reponame>weso/umlShaclex
package es.weso.uml
import com.typesafe.scalalogging.LazyLogging
import es.weso.schema.{Schema, ShExSchema, ShaclexSchema}
object Schema2UML extends LazyLogging {
def schema2UML(schema: Schema): Either[String,(UML,List[String])] = {
schema match {
case shexSchema: ShExSchema => ShEx2UML.schema2Uml(shexSchema.schema)
case shaclSchema: ShaclexSchema => SHACL2UML.schema2Uml(shaclSchema.schema)
case _ => Left(s"Unsupported conversion of ${schema.name} to UML")
}
}
}
|
alexey-suknatov-exactpro/sailfish-core
|
BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/ReportEntity.java
|
<filename>BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/ReportEntity.java
/******************************************************************************
* Copyright 2009-2018 Exactpro (Exactpro Systems Limited)
*
* 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.exactpro.sf.scriptrunner;
import com.exactpro.sf.common.messages.IMessage;
import org.apache.commons.lang3.StringUtils;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
public class ReportEntity implements Iterable<ReportEntity> {
private final String name;
private final Object value;
private final List<ReportEntity> fields;
public ReportEntity(String name, Object value) {
Objects.requireNonNull(name, "name cannot be null");
this.value = value;
List<ReportEntity> fields = new ArrayList<>();
if(value instanceof Iterable<?>) {
int index = 0;
Iterable<?> iterable = (Iterable<?>)value;
for(Object element : iterable) {
fields.add(new ReportEntity(Integer.toString(index++), element));
}
} else if(value instanceof Map<?, ?>) {
Map<?, ?> map = (Map<?, ?>)value;
map.forEach((k,v) -> {
fields.add(new ReportEntity(Objects.toString(k), v));
});
} else if(value instanceof IMessage) {
IMessage message = (IMessage)value;
if(!StringUtils.isNumeric(name)) {
name = message.getName();
}
for(String fieldName : message.getFieldNames()) {
fields.add(new ReportEntity(fieldName, message.getField(fieldName)));
}
}
this.name = name;
this.fields = Collections.unmodifiableList(fields);
}
public String getName() {
return name;
}
@SuppressWarnings("unchecked")
public <T> T getValue() {
return (T)value;
}
public List<ReportEntity> getFields() {
return fields;
}
public boolean hasFields() {
return !fields.isEmpty();
}
@Override
public Iterator<ReportEntity> iterator() {
return fields.iterator();
}
}
|
d8corp/innet
|
lib/scope/index.es6.js
|
export { default, default as scope } from './scope.es6.js';
|
mcx/tvm
|
src/robot/FrictionCone.cpp
|
<reponame>mcx/tvm
/** Copyright 2017-2020 CNRS-AIST JRL and CNRS-UM LIRMM */
#include <tvm/defs.h>
#include <tvm/robot/internal/FrictionCone.h>
#include <Eigen/Geometry>
namespace tvm
{
namespace robot
{
namespace internal
{
FrictionCone::FrictionCone(const Eigen::Matrix3d & frame, unsigned int nrGen, double mu, double dir) : generators(nrGen)
{
Eigen::Vector3d normal = frame.row(2);
Eigen::Vector3d tan = dir * frame.row(0);
double angle = std::atan(mu);
Eigen::Vector3d gen = Eigen::AngleAxisd(angle, tan) * normal;
double step = tvm::constant::pi * 2. / nrGen;
for(unsigned int i = 0; i < nrGen; ++i)
{
generators[i] = Eigen::AngleAxisd(dir * step * i, normal) * gen;
}
}
} // namespace internal
} // namespace robot
} // namespace tvm
|
rkyankya/coursemology2
|
spec/models/course/enrol_request_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe Course::EnrolRequest, type: :model do
it 'belongs to a course' do
expect(subject).to belong_to(:course).
inverse_of(:enrol_requests).
without_validating_presence
end
it 'belongs to a user' do
expect(subject).to belong_to(:user).
inverse_of(:course_enrol_requests).
without_validating_presence
end
let!(:instance) { create :instance }
with_tenant(:instance) do
let(:user) { create(:user) }
let(:course) { create(:course) }
describe 'validations' do
context 'when enrolled user is an existing course_user' do
let!(:student) { create(:course_student, course: course) }
subject { build(:course_enrol_request, course: course, user: student.user) }
it 'is not valid' do
expect(subject.valid?).to be_falsey
expect(subject.errors[:base]).to include(
I18n.t('activerecord.errors.models.course/enrol_request.user_in_course')
)
end
end
end
end
end
|
haizhenhan/Kepler
|
kernel/2.6.32/drivers/net/igb/igb_ethtool.c
|
<reponame>haizhenhan/Kepler<gh_stars>10-100
/*******************************************************************************
Intel(R) Gigabit Ethernet Linux driver
Copyright(c) 2007-2009 Intel Corporation.
This program is free software; you can redistribute it and/or modify it
under the terms and conditions of the GNU General Public License,
version 2, as published by the Free Software Foundation.
This program is distributed in the hope it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
more details.
You should have received a copy of the GNU General Public License along with
this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA.
The full GNU General Public License is included in this distribution in
the file called "COPYING".
Contact Information:
e1000-devel Mailing List <<EMAIL>>
Intel Corporation, 5200 N.E. <NAME> Parkway, Hillsboro, OR 97124-6497
*******************************************************************************/
/* ethtool support for igb */
#include <linux/vmalloc.h>
#include <linux/netdevice.h>
#include <linux/pci.h>
#include <linux/delay.h>
#include <linux/interrupt.h>
#include <linux/if_ether.h>
#include <linux/ethtool.h>
#include <linux/sched.h>
#include "igb.h"
struct igb_stats {
char stat_string[ETH_GSTRING_LEN];
int sizeof_stat;
int stat_offset;
};
#define IGB_STAT(m) FIELD_SIZEOF(struct igb_adapter, m), \
offsetof(struct igb_adapter, m)
static const struct igb_stats igb_gstrings_stats[] = {
{ "rx_packets", IGB_STAT(stats.gprc) },
{ "tx_packets", IGB_STAT(stats.gptc) },
{ "rx_bytes", IGB_STAT(stats.gorc) },
{ "tx_bytes", IGB_STAT(stats.gotc) },
{ "rx_broadcast", IGB_STAT(stats.bprc) },
{ "tx_broadcast", IGB_STAT(stats.bptc) },
{ "rx_multicast", IGB_STAT(stats.mprc) },
{ "tx_multicast", IGB_STAT(stats.mptc) },
{ "rx_errors", IGB_STAT(net_stats.rx_errors) },
{ "tx_errors", IGB_STAT(net_stats.tx_errors) },
{ "tx_dropped", IGB_STAT(net_stats.tx_dropped) },
{ "multicast", IGB_STAT(stats.mprc) },
{ "collisions", IGB_STAT(stats.colc) },
{ "rx_length_errors", IGB_STAT(net_stats.rx_length_errors) },
{ "rx_over_errors", IGB_STAT(net_stats.rx_over_errors) },
{ "rx_crc_errors", IGB_STAT(stats.crcerrs) },
{ "rx_frame_errors", IGB_STAT(net_stats.rx_frame_errors) },
{ "rx_no_buffer_count", IGB_STAT(stats.rnbc) },
{ "rx_queue_drop_packet_count", IGB_STAT(net_stats.rx_fifo_errors) },
{ "rx_missed_errors", IGB_STAT(stats.mpc) },
{ "tx_aborted_errors", IGB_STAT(stats.ecol) },
{ "tx_carrier_errors", IGB_STAT(stats.tncrs) },
{ "tx_fifo_errors", IGB_STAT(net_stats.tx_fifo_errors) },
{ "tx_heartbeat_errors", IGB_STAT(net_stats.tx_heartbeat_errors) },
{ "tx_window_errors", IGB_STAT(stats.latecol) },
{ "tx_abort_late_coll", IGB_STAT(stats.latecol) },
{ "tx_deferred_ok", IGB_STAT(stats.dc) },
{ "tx_single_coll_ok", IGB_STAT(stats.scc) },
{ "tx_multi_coll_ok", IGB_STAT(stats.mcc) },
{ "tx_timeout_count", IGB_STAT(tx_timeout_count) },
{ "tx_restart_queue", IGB_STAT(restart_queue) },
{ "rx_long_length_errors", IGB_STAT(stats.roc) },
{ "rx_short_length_errors", IGB_STAT(stats.ruc) },
{ "rx_align_errors", IGB_STAT(stats.algnerrc) },
{ "tx_tcp_seg_good", IGB_STAT(stats.tsctc) },
{ "tx_tcp_seg_failed", IGB_STAT(stats.tsctfc) },
{ "rx_flow_control_xon", IGB_STAT(stats.xonrxc) },
{ "rx_flow_control_xoff", IGB_STAT(stats.xoffrxc) },
{ "tx_flow_control_xon", IGB_STAT(stats.xontxc) },
{ "tx_flow_control_xoff", IGB_STAT(stats.xofftxc) },
{ "rx_long_byte_count", IGB_STAT(stats.gorc) },
{ "rx_csum_offload_good", IGB_STAT(hw_csum_good) },
{ "rx_csum_offload_errors", IGB_STAT(hw_csum_err) },
{ "tx_dma_out_of_sync", IGB_STAT(stats.doosync) },
{ "alloc_rx_buff_failed", IGB_STAT(alloc_rx_buff_failed) },
{ "tx_smbus", IGB_STAT(stats.mgptc) },
{ "rx_smbus", IGB_STAT(stats.mgprc) },
{ "dropped_smbus", IGB_STAT(stats.mgpdc) },
};
#define IGB_QUEUE_STATS_LEN \
(((((struct igb_adapter *)netdev_priv(netdev))->num_rx_queues)* \
(sizeof(struct igb_rx_queue_stats) / sizeof(u64))) + \
((((struct igb_adapter *)netdev_priv(netdev))->num_tx_queues) * \
(sizeof(struct igb_tx_queue_stats) / sizeof(u64))))
#define IGB_GLOBAL_STATS_LEN \
sizeof(igb_gstrings_stats) / sizeof(struct igb_stats)
#define IGB_STATS_LEN (IGB_GLOBAL_STATS_LEN + IGB_QUEUE_STATS_LEN)
static const char igb_gstrings_test[][ETH_GSTRING_LEN] = {
"Register test (offline)", "Eeprom test (offline)",
"Interrupt test (offline)", "Loopback test (offline)",
"Link test (on/offline)"
};
#define IGB_TEST_LEN sizeof(igb_gstrings_test) / ETH_GSTRING_LEN
static int igb_get_settings(struct net_device *netdev, struct ethtool_cmd *ecmd)
{
struct igb_adapter *adapter = netdev_priv(netdev);
struct e1000_hw *hw = &adapter->hw;
if (hw->phy.media_type == e1000_media_type_copper) {
ecmd->supported = (SUPPORTED_10baseT_Half |
SUPPORTED_10baseT_Full |
SUPPORTED_100baseT_Half |
SUPPORTED_100baseT_Full |
SUPPORTED_1000baseT_Full|
SUPPORTED_Autoneg |
SUPPORTED_TP);
ecmd->advertising = ADVERTISED_TP;
if (hw->mac.autoneg == 1) {
ecmd->advertising |= ADVERTISED_Autoneg;
/* the e1000 autoneg seems to match ethtool nicely */
ecmd->advertising |= hw->phy.autoneg_advertised;
}
ecmd->port = PORT_TP;
ecmd->phy_address = hw->phy.addr;
} else {
ecmd->supported = (SUPPORTED_1000baseT_Full |
SUPPORTED_FIBRE |
SUPPORTED_Autoneg);
ecmd->advertising = (ADVERTISED_1000baseT_Full |
ADVERTISED_FIBRE |
ADVERTISED_Autoneg);
ecmd->port = PORT_FIBRE;
}
ecmd->transceiver = XCVR_INTERNAL;
if (rd32(E1000_STATUS) & E1000_STATUS_LU) {
adapter->hw.mac.ops.get_speed_and_duplex(hw,
&adapter->link_speed,
&adapter->link_duplex);
ecmd->speed = adapter->link_speed;
/* unfortunately FULL_DUPLEX != DUPLEX_FULL
* and HALF_DUPLEX != DUPLEX_HALF */
if (adapter->link_duplex == FULL_DUPLEX)
ecmd->duplex = DUPLEX_FULL;
else
ecmd->duplex = DUPLEX_HALF;
} else {
ecmd->speed = -1;
ecmd->duplex = -1;
}
ecmd->autoneg = hw->mac.autoneg ? AUTONEG_ENABLE : AUTONEG_DISABLE;
return 0;
}
static int igb_set_settings(struct net_device *netdev, struct ethtool_cmd *ecmd)
{
struct igb_adapter *adapter = netdev_priv(netdev);
struct e1000_hw *hw = &adapter->hw;
/* When SoL/IDER sessions are active, autoneg/speed/duplex
* cannot be changed */
if (igb_check_reset_block(hw)) {
dev_err(&adapter->pdev->dev, "Cannot change link "
"characteristics when SoL/IDER is active.\n");
return -EINVAL;
}
while (test_and_set_bit(__IGB_RESETTING, &adapter->state))
msleep(1);
if (ecmd->autoneg == AUTONEG_ENABLE) {
hw->mac.autoneg = 1;
hw->phy.autoneg_advertised = ecmd->advertising |
ADVERTISED_TP |
ADVERTISED_Autoneg;
ecmd->advertising = hw->phy.autoneg_advertised;
if (adapter->fc_autoneg)
hw->fc.requested_mode = e1000_fc_default;
} else {
if (igb_set_spd_dplx(adapter, ecmd->speed + ecmd->duplex)) {
clear_bit(__IGB_RESETTING, &adapter->state);
return -EINVAL;
}
}
/* reset the link */
if (netif_running(adapter->netdev)) {
igb_down(adapter);
igb_up(adapter);
} else
igb_reset(adapter);
clear_bit(__IGB_RESETTING, &adapter->state);
return 0;
}
static void igb_get_pauseparam(struct net_device *netdev,
struct ethtool_pauseparam *pause)
{
struct igb_adapter *adapter = netdev_priv(netdev);
struct e1000_hw *hw = &adapter->hw;
pause->autoneg =
(adapter->fc_autoneg ? AUTONEG_ENABLE : AUTONEG_DISABLE);
if (hw->fc.current_mode == e1000_fc_rx_pause)
pause->rx_pause = 1;
else if (hw->fc.current_mode == e1000_fc_tx_pause)
pause->tx_pause = 1;
else if (hw->fc.current_mode == e1000_fc_full) {
pause->rx_pause = 1;
pause->tx_pause = 1;
}
}
static int igb_set_pauseparam(struct net_device *netdev,
struct ethtool_pauseparam *pause)
{
struct igb_adapter *adapter = netdev_priv(netdev);
struct e1000_hw *hw = &adapter->hw;
int retval = 0;
adapter->fc_autoneg = pause->autoneg;
while (test_and_set_bit(__IGB_RESETTING, &adapter->state))
msleep(1);
if (adapter->fc_autoneg == AUTONEG_ENABLE) {
hw->fc.requested_mode = e1000_fc_default;
if (netif_running(adapter->netdev)) {
igb_down(adapter);
igb_up(adapter);
} else
igb_reset(adapter);
} else {
if (pause->rx_pause && pause->tx_pause)
hw->fc.requested_mode = e1000_fc_full;
else if (pause->rx_pause && !pause->tx_pause)
hw->fc.requested_mode = e1000_fc_rx_pause;
else if (!pause->rx_pause && pause->tx_pause)
hw->fc.requested_mode = e1000_fc_tx_pause;
else if (!pause->rx_pause && !pause->tx_pause)
hw->fc.requested_mode = e1000_fc_none;
hw->fc.current_mode = hw->fc.requested_mode;
retval = ((hw->phy.media_type == e1000_media_type_copper) ?
igb_force_mac_fc(hw) : igb_setup_link(hw));
}
clear_bit(__IGB_RESETTING, &adapter->state);
return retval;
}
static u32 igb_get_rx_csum(struct net_device *netdev)
{
struct igb_adapter *adapter = netdev_priv(netdev);
return !(adapter->flags & IGB_FLAG_RX_CSUM_DISABLED);
}
static int igb_set_rx_csum(struct net_device *netdev, u32 data)
{
struct igb_adapter *adapter = netdev_priv(netdev);
if (data)
adapter->flags &= ~IGB_FLAG_RX_CSUM_DISABLED;
else
adapter->flags |= IGB_FLAG_RX_CSUM_DISABLED;
return 0;
}
static u32 igb_get_tx_csum(struct net_device *netdev)
{
return (netdev->features & NETIF_F_IP_CSUM) != 0;
}
static int igb_set_tx_csum(struct net_device *netdev, u32 data)
{
struct igb_adapter *adapter = netdev_priv(netdev);
if (data) {
netdev->features |= (NETIF_F_IP_CSUM | NETIF_F_IPV6_CSUM);
if (adapter->hw.mac.type == e1000_82576)
netdev->features |= NETIF_F_SCTP_CSUM;
} else {
netdev->features &= ~(NETIF_F_IP_CSUM | NETIF_F_IPV6_CSUM |
NETIF_F_SCTP_CSUM);
}
return 0;
}
static int igb_set_tso(struct net_device *netdev, u32 data)
{
struct igb_adapter *adapter = netdev_priv(netdev);
if (data) {
netdev->features |= NETIF_F_TSO;
netdev->features |= NETIF_F_TSO6;
} else {
netdev->features &= ~NETIF_F_TSO;
netdev->features &= ~NETIF_F_TSO6;
}
dev_info(&adapter->pdev->dev, "TSO is %s\n",
data ? "Enabled" : "Disabled");
return 0;
}
static u32 igb_get_msglevel(struct net_device *netdev)
{
struct igb_adapter *adapter = netdev_priv(netdev);
return adapter->msg_enable;
}
static void igb_set_msglevel(struct net_device *netdev, u32 data)
{
struct igb_adapter *adapter = netdev_priv(netdev);
adapter->msg_enable = data;
}
static int igb_get_regs_len(struct net_device *netdev)
{
#define IGB_REGS_LEN 551
return IGB_REGS_LEN * sizeof(u32);
}
static void igb_get_regs(struct net_device *netdev,
struct ethtool_regs *regs, void *p)
{
struct igb_adapter *adapter = netdev_priv(netdev);
struct e1000_hw *hw = &adapter->hw;
u32 *regs_buff = p;
u8 i;
memset(p, 0, IGB_REGS_LEN * sizeof(u32));
regs->version = (1 << 24) | (hw->revision_id << 16) | hw->device_id;
/* General Registers */
regs_buff[0] = rd32(E1000_CTRL);
regs_buff[1] = rd32(E1000_STATUS);
regs_buff[2] = rd32(E1000_CTRL_EXT);
regs_buff[3] = rd32(E1000_MDIC);
regs_buff[4] = rd32(E1000_SCTL);
regs_buff[5] = rd32(E1000_CONNSW);
regs_buff[6] = rd32(E1000_VET);
regs_buff[7] = rd32(E1000_LEDCTL);
regs_buff[8] = rd32(E1000_PBA);
regs_buff[9] = rd32(E1000_PBS);
regs_buff[10] = rd32(E1000_FRTIMER);
regs_buff[11] = rd32(E1000_TCPTIMER);
/* NVM Register */
regs_buff[12] = rd32(E1000_EECD);
/* Interrupt */
/* Reading EICS for EICR because they read the
* same but EICS does not clear on read */
regs_buff[13] = rd32(E1000_EICS);
regs_buff[14] = rd32(E1000_EICS);
regs_buff[15] = rd32(E1000_EIMS);
regs_buff[16] = rd32(E1000_EIMC);
regs_buff[17] = rd32(E1000_EIAC);
regs_buff[18] = rd32(E1000_EIAM);
/* Reading ICS for ICR because they read the
* same but ICS does not clear on read */
regs_buff[19] = rd32(E1000_ICS);
regs_buff[20] = rd32(E1000_ICS);
regs_buff[21] = rd32(E1000_IMS);
regs_buff[22] = rd32(E1000_IMC);
regs_buff[23] = rd32(E1000_IAC);
regs_buff[24] = rd32(E1000_IAM);
regs_buff[25] = rd32(E1000_IMIRVP);
/* Flow Control */
regs_buff[26] = rd32(E1000_FCAL);
regs_buff[27] = rd32(E1000_FCAH);
regs_buff[28] = rd32(E1000_FCTTV);
regs_buff[29] = rd32(E1000_FCRTL);
regs_buff[30] = rd32(E1000_FCRTH);
regs_buff[31] = rd32(E1000_FCRTV);
/* Receive */
regs_buff[32] = rd32(E1000_RCTL);
regs_buff[33] = rd32(E1000_RXCSUM);
regs_buff[34] = rd32(E1000_RLPML);
regs_buff[35] = rd32(E1000_RFCTL);
regs_buff[36] = rd32(E1000_MRQC);
regs_buff[37] = rd32(E1000_VT_CTL);
/* Transmit */
regs_buff[38] = rd32(E1000_TCTL);
regs_buff[39] = rd32(E1000_TCTL_EXT);
regs_buff[40] = rd32(E1000_TIPG);
regs_buff[41] = rd32(E1000_DTXCTL);
/* Wake Up */
regs_buff[42] = rd32(E1000_WUC);
regs_buff[43] = rd32(E1000_WUFC);
regs_buff[44] = rd32(E1000_WUS);
regs_buff[45] = rd32(E1000_IPAV);
regs_buff[46] = rd32(E1000_WUPL);
/* MAC */
regs_buff[47] = rd32(E1000_PCS_CFG0);
regs_buff[48] = rd32(E1000_PCS_LCTL);
regs_buff[49] = rd32(E1000_PCS_LSTAT);
regs_buff[50] = rd32(E1000_PCS_ANADV);
regs_buff[51] = rd32(E1000_PCS_LPAB);
regs_buff[52] = rd32(E1000_PCS_NPTX);
regs_buff[53] = rd32(E1000_PCS_LPABNP);
/* Statistics */
regs_buff[54] = adapter->stats.crcerrs;
regs_buff[55] = adapter->stats.algnerrc;
regs_buff[56] = adapter->stats.symerrs;
regs_buff[57] = adapter->stats.rxerrc;
regs_buff[58] = adapter->stats.mpc;
regs_buff[59] = adapter->stats.scc;
regs_buff[60] = adapter->stats.ecol;
regs_buff[61] = adapter->stats.mcc;
regs_buff[62] = adapter->stats.latecol;
regs_buff[63] = adapter->stats.colc;
regs_buff[64] = adapter->stats.dc;
regs_buff[65] = adapter->stats.tncrs;
regs_buff[66] = adapter->stats.sec;
regs_buff[67] = adapter->stats.htdpmc;
regs_buff[68] = adapter->stats.rlec;
regs_buff[69] = adapter->stats.xonrxc;
regs_buff[70] = adapter->stats.xontxc;
regs_buff[71] = adapter->stats.xoffrxc;
regs_buff[72] = adapter->stats.xofftxc;
regs_buff[73] = adapter->stats.fcruc;
regs_buff[74] = adapter->stats.prc64;
regs_buff[75] = adapter->stats.prc127;
regs_buff[76] = adapter->stats.prc255;
regs_buff[77] = adapter->stats.prc511;
regs_buff[78] = adapter->stats.prc1023;
regs_buff[79] = adapter->stats.prc1522;
regs_buff[80] = adapter->stats.gprc;
regs_buff[81] = adapter->stats.bprc;
regs_buff[82] = adapter->stats.mprc;
regs_buff[83] = adapter->stats.gptc;
regs_buff[84] = adapter->stats.gorc;
regs_buff[86] = adapter->stats.gotc;
regs_buff[88] = adapter->stats.rnbc;
regs_buff[89] = adapter->stats.ruc;
regs_buff[90] = adapter->stats.rfc;
regs_buff[91] = adapter->stats.roc;
regs_buff[92] = adapter->stats.rjc;
regs_buff[93] = adapter->stats.mgprc;
regs_buff[94] = adapter->stats.mgpdc;
regs_buff[95] = adapter->stats.mgptc;
regs_buff[96] = adapter->stats.tor;
regs_buff[98] = adapter->stats.tot;
regs_buff[100] = adapter->stats.tpr;
regs_buff[101] = adapter->stats.tpt;
regs_buff[102] = adapter->stats.ptc64;
regs_buff[103] = adapter->stats.ptc127;
regs_buff[104] = adapter->stats.ptc255;
regs_buff[105] = adapter->stats.ptc511;
regs_buff[106] = adapter->stats.ptc1023;
regs_buff[107] = adapter->stats.ptc1522;
regs_buff[108] = adapter->stats.mptc;
regs_buff[109] = adapter->stats.bptc;
regs_buff[110] = adapter->stats.tsctc;
regs_buff[111] = adapter->stats.iac;
regs_buff[112] = adapter->stats.rpthc;
regs_buff[113] = adapter->stats.hgptc;
regs_buff[114] = adapter->stats.hgorc;
regs_buff[116] = adapter->stats.hgotc;
regs_buff[118] = adapter->stats.lenerrs;
regs_buff[119] = adapter->stats.scvpc;
regs_buff[120] = adapter->stats.hrmpc;
/* These should probably be added to e1000_regs.h instead */
#define E1000_PSRTYPE_REG(_i) (0x05480 + ((_i) * 4))
#define E1000_IP4AT_REG(_i) (0x05840 + ((_i) * 8))
#define E1000_IP6AT_REG(_i) (0x05880 + ((_i) * 4))
#define E1000_WUPM_REG(_i) (0x05A00 + ((_i) * 4))
#define E1000_FFMT_REG(_i) (0x09000 + ((_i) * 8))
#define E1000_FFVT_REG(_i) (0x09800 + ((_i) * 8))
#define E1000_FFLT_REG(_i) (0x05F00 + ((_i) * 8))
for (i = 0; i < 4; i++)
regs_buff[121 + i] = rd32(E1000_SRRCTL(i));
for (i = 0; i < 4; i++)
regs_buff[125 + i] = rd32(E1000_PSRTYPE_REG(i));
for (i = 0; i < 4; i++)
regs_buff[129 + i] = rd32(E1000_RDBAL(i));
for (i = 0; i < 4; i++)
regs_buff[133 + i] = rd32(E1000_RDBAH(i));
for (i = 0; i < 4; i++)
regs_buff[137 + i] = rd32(E1000_RDLEN(i));
for (i = 0; i < 4; i++)
regs_buff[141 + i] = rd32(E1000_RDH(i));
for (i = 0; i < 4; i++)
regs_buff[145 + i] = rd32(E1000_RDT(i));
for (i = 0; i < 4; i++)
regs_buff[149 + i] = rd32(E1000_RXDCTL(i));
for (i = 0; i < 10; i++)
regs_buff[153 + i] = rd32(E1000_EITR(i));
for (i = 0; i < 8; i++)
regs_buff[163 + i] = rd32(E1000_IMIR(i));
for (i = 0; i < 8; i++)
regs_buff[171 + i] = rd32(E1000_IMIREXT(i));
for (i = 0; i < 16; i++)
regs_buff[179 + i] = rd32(E1000_RAL(i));
for (i = 0; i < 16; i++)
regs_buff[195 + i] = rd32(E1000_RAH(i));
for (i = 0; i < 4; i++)
regs_buff[211 + i] = rd32(E1000_TDBAL(i));
for (i = 0; i < 4; i++)
regs_buff[215 + i] = rd32(E1000_TDBAH(i));
for (i = 0; i < 4; i++)
regs_buff[219 + i] = rd32(E1000_TDLEN(i));
for (i = 0; i < 4; i++)
regs_buff[223 + i] = rd32(E1000_TDH(i));
for (i = 0; i < 4; i++)
regs_buff[227 + i] = rd32(E1000_TDT(i));
for (i = 0; i < 4; i++)
regs_buff[231 + i] = rd32(E1000_TXDCTL(i));
for (i = 0; i < 4; i++)
regs_buff[235 + i] = rd32(E1000_TDWBAL(i));
for (i = 0; i < 4; i++)
regs_buff[239 + i] = rd32(E1000_TDWBAH(i));
for (i = 0; i < 4; i++)
regs_buff[243 + i] = rd32(E1000_DCA_TXCTRL(i));
for (i = 0; i < 4; i++)
regs_buff[247 + i] = rd32(E1000_IP4AT_REG(i));
for (i = 0; i < 4; i++)
regs_buff[251 + i] = rd32(E1000_IP6AT_REG(i));
for (i = 0; i < 32; i++)
regs_buff[255 + i] = rd32(E1000_WUPM_REG(i));
for (i = 0; i < 128; i++)
regs_buff[287 + i] = rd32(E1000_FFMT_REG(i));
for (i = 0; i < 128; i++)
regs_buff[415 + i] = rd32(E1000_FFVT_REG(i));
for (i = 0; i < 4; i++)
regs_buff[543 + i] = rd32(E1000_FFLT_REG(i));
regs_buff[547] = rd32(E1000_TDFH);
regs_buff[548] = rd32(E1000_TDFT);
regs_buff[549] = rd32(E1000_TDFHS);
regs_buff[550] = rd32(E1000_TDFPC);
}
static int igb_get_eeprom_len(struct net_device *netdev)
{
struct igb_adapter *adapter = netdev_priv(netdev);
return adapter->hw.nvm.word_size * 2;
}
static int igb_get_eeprom(struct net_device *netdev,
struct ethtool_eeprom *eeprom, u8 *bytes)
{
struct igb_adapter *adapter = netdev_priv(netdev);
struct e1000_hw *hw = &adapter->hw;
u16 *eeprom_buff;
int first_word, last_word;
int ret_val = 0;
u16 i;
if (eeprom->len == 0)
return -EINVAL;
eeprom->magic = hw->vendor_id | (hw->device_id << 16);
first_word = eeprom->offset >> 1;
last_word = (eeprom->offset + eeprom->len - 1) >> 1;
eeprom_buff = kmalloc(sizeof(u16) *
(last_word - first_word + 1), GFP_KERNEL);
if (!eeprom_buff)
return -ENOMEM;
if (hw->nvm.type == e1000_nvm_eeprom_spi)
ret_val = hw->nvm.ops.read(hw, first_word,
last_word - first_word + 1,
eeprom_buff);
else {
for (i = 0; i < last_word - first_word + 1; i++) {
ret_val = hw->nvm.ops.read(hw, first_word + i, 1,
&eeprom_buff[i]);
if (ret_val)
break;
}
}
/* Device's eeprom is always little-endian, word addressable */
for (i = 0; i < last_word - first_word + 1; i++)
le16_to_cpus(&eeprom_buff[i]);
memcpy(bytes, (u8 *)eeprom_buff + (eeprom->offset & 1),
eeprom->len);
kfree(eeprom_buff);
return ret_val;
}
static int igb_set_eeprom(struct net_device *netdev,
struct ethtool_eeprom *eeprom, u8 *bytes)
{
struct igb_adapter *adapter = netdev_priv(netdev);
struct e1000_hw *hw = &adapter->hw;
u16 *eeprom_buff;
void *ptr;
int max_len, first_word, last_word, ret_val = 0;
u16 i;
if (eeprom->len == 0)
return -EOPNOTSUPP;
if (eeprom->magic != (hw->vendor_id | (hw->device_id << 16)))
return -EFAULT;
max_len = hw->nvm.word_size * 2;
first_word = eeprom->offset >> 1;
last_word = (eeprom->offset + eeprom->len - 1) >> 1;
eeprom_buff = kmalloc(max_len, GFP_KERNEL);
if (!eeprom_buff)
return -ENOMEM;
ptr = (void *)eeprom_buff;
if (eeprom->offset & 1) {
/* need read/modify/write of first changed EEPROM word */
/* only the second byte of the word is being modified */
ret_val = hw->nvm.ops.read(hw, first_word, 1,
&eeprom_buff[0]);
ptr++;
}
if (((eeprom->offset + eeprom->len) & 1) && (ret_val == 0)) {
/* need read/modify/write of last changed EEPROM word */
/* only the first byte of the word is being modified */
ret_val = hw->nvm.ops.read(hw, last_word, 1,
&eeprom_buff[last_word - first_word]);
}
/* Device's eeprom is always little-endian, word addressable */
for (i = 0; i < last_word - first_word + 1; i++)
le16_to_cpus(&eeprom_buff[i]);
memcpy(ptr, bytes, eeprom->len);
for (i = 0; i < last_word - first_word + 1; i++)
eeprom_buff[i] = cpu_to_le16(eeprom_buff[i]);
ret_val = hw->nvm.ops.write(hw, first_word,
last_word - first_word + 1, eeprom_buff);
/* Update the checksum over the first part of the EEPROM if needed
* and flush shadow RAM for 82573 controllers */
if ((ret_val == 0) && ((first_word <= NVM_CHECKSUM_REG)))
igb_update_nvm_checksum(hw);
kfree(eeprom_buff);
return ret_val;
}
static void igb_get_drvinfo(struct net_device *netdev,
struct ethtool_drvinfo *drvinfo)
{
struct igb_adapter *adapter = netdev_priv(netdev);
char firmware_version[32];
u16 eeprom_data;
strncpy(drvinfo->driver, igb_driver_name, 32);
strncpy(drvinfo->version, igb_driver_version, 32);
/* EEPROM image version # is reported as firmware version # for
* 82575 controllers */
adapter->hw.nvm.ops.read(&adapter->hw, 5, 1, &eeprom_data);
sprintf(firmware_version, "%d.%d-%d",
(eeprom_data & 0xF000) >> 12,
(eeprom_data & 0x0FF0) >> 4,
eeprom_data & 0x000F);
strncpy(drvinfo->fw_version, firmware_version, 32);
strncpy(drvinfo->bus_info, pci_name(adapter->pdev), 32);
drvinfo->n_stats = IGB_STATS_LEN;
drvinfo->testinfo_len = IGB_TEST_LEN;
drvinfo->regdump_len = igb_get_regs_len(netdev);
drvinfo->eedump_len = igb_get_eeprom_len(netdev);
}
static void igb_get_ringparam(struct net_device *netdev,
struct ethtool_ringparam *ring)
{
struct igb_adapter *adapter = netdev_priv(netdev);
ring->rx_max_pending = IGB_MAX_RXD;
ring->tx_max_pending = IGB_MAX_TXD;
ring->rx_mini_max_pending = 0;
ring->rx_jumbo_max_pending = 0;
ring->rx_pending = adapter->rx_ring_count;
ring->tx_pending = adapter->tx_ring_count;
ring->rx_mini_pending = 0;
ring->rx_jumbo_pending = 0;
}
static int igb_set_ringparam(struct net_device *netdev,
struct ethtool_ringparam *ring)
{
struct igb_adapter *adapter = netdev_priv(netdev);
struct igb_ring *temp_ring;
int i, err = 0;
u32 new_rx_count, new_tx_count;
if ((ring->rx_mini_pending) || (ring->rx_jumbo_pending))
return -EINVAL;
new_rx_count = max(ring->rx_pending, (u32)IGB_MIN_RXD);
new_rx_count = min(new_rx_count, (u32)IGB_MAX_RXD);
new_rx_count = ALIGN(new_rx_count, REQ_RX_DESCRIPTOR_MULTIPLE);
new_tx_count = max(ring->tx_pending, (u32)IGB_MIN_TXD);
new_tx_count = min(new_tx_count, (u32)IGB_MAX_TXD);
new_tx_count = ALIGN(new_tx_count, REQ_TX_DESCRIPTOR_MULTIPLE);
if ((new_tx_count == adapter->tx_ring_count) &&
(new_rx_count == adapter->rx_ring_count)) {
/* nothing to do */
return 0;
}
while (test_and_set_bit(__IGB_RESETTING, &adapter->state))
msleep(1);
if (!netif_running(adapter->netdev)) {
for (i = 0; i < adapter->num_tx_queues; i++)
adapter->tx_ring[i].count = new_tx_count;
for (i = 0; i < adapter->num_rx_queues; i++)
adapter->rx_ring[i].count = new_rx_count;
adapter->tx_ring_count = new_tx_count;
adapter->rx_ring_count = new_rx_count;
goto clear_reset;
}
if (adapter->num_tx_queues > adapter->num_rx_queues)
temp_ring = vmalloc(adapter->num_tx_queues * sizeof(struct igb_ring));
else
temp_ring = vmalloc(adapter->num_rx_queues * sizeof(struct igb_ring));
if (!temp_ring) {
err = -ENOMEM;
goto clear_reset;
}
igb_down(adapter);
/*
* We can't just free everything and then setup again,
* because the ISRs in MSI-X mode get passed pointers
* to the tx and rx ring structs.
*/
if (new_tx_count != adapter->tx_ring_count) {
memcpy(temp_ring, adapter->tx_ring,
adapter->num_tx_queues * sizeof(struct igb_ring));
for (i = 0; i < adapter->num_tx_queues; i++) {
temp_ring[i].count = new_tx_count;
err = igb_setup_tx_resources(adapter, &temp_ring[i]);
if (err) {
while (i) {
i--;
igb_free_tx_resources(&temp_ring[i]);
}
goto err_setup;
}
}
for (i = 0; i < adapter->num_tx_queues; i++)
igb_free_tx_resources(&adapter->tx_ring[i]);
memcpy(adapter->tx_ring, temp_ring,
adapter->num_tx_queues * sizeof(struct igb_ring));
adapter->tx_ring_count = new_tx_count;
}
if (new_rx_count != adapter->rx_ring->count) {
memcpy(temp_ring, adapter->rx_ring,
adapter->num_rx_queues * sizeof(struct igb_ring));
for (i = 0; i < adapter->num_rx_queues; i++) {
temp_ring[i].count = new_rx_count;
err = igb_setup_rx_resources(adapter, &temp_ring[i]);
if (err) {
while (i) {
i--;
igb_free_rx_resources(&temp_ring[i]);
}
goto err_setup;
}
}
for (i = 0; i < adapter->num_rx_queues; i++)
igb_free_rx_resources(&adapter->rx_ring[i]);
memcpy(adapter->rx_ring, temp_ring,
adapter->num_rx_queues * sizeof(struct igb_ring));
adapter->rx_ring_count = new_rx_count;
}
err_setup:
igb_up(adapter);
vfree(temp_ring);
clear_reset:
clear_bit(__IGB_RESETTING, &adapter->state);
return err;
}
/* ethtool register test data */
struct igb_reg_test {
u16 reg;
u16 reg_offset;
u16 array_len;
u16 test_type;
u32 mask;
u32 write;
};
/* In the hardware, registers are laid out either singly, in arrays
* spaced 0x100 bytes apart, or in contiguous tables. We assume
* most tests take place on arrays or single registers (handled
* as a single-element array) and special-case the tables.
* Table tests are always pattern tests.
*
* We also make provision for some required setup steps by specifying
* registers to be written without any read-back testing.
*/
#define PATTERN_TEST 1
#define SET_READ_TEST 2
#define WRITE_NO_TEST 3
#define TABLE32_TEST 4
#define TABLE64_TEST_LO 5
#define TABLE64_TEST_HI 6
/* 82576 reg test */
static struct igb_reg_test reg_test_82576[] = {
{ E1000_FCAL, 0x100, 1, PATTERN_TEST, 0xFFFFFFFF, 0xFFFFFFFF },
{ E1000_FCAH, 0x100, 1, PATTERN_TEST, 0x0000FFFF, 0xFFFFFFFF },
{ E1000_FCT, 0x100, 1, PATTERN_TEST, 0x0000FFFF, 0xFFFFFFFF },
{ E1000_VET, 0x100, 1, PATTERN_TEST, 0xFFFFFFFF, 0xFFFFFFFF },
{ E1000_RDBAL(0), 0x100, 4, PATTERN_TEST, 0xFFFFFF80, 0xFFFFFFFF },
{ E1000_RDBAH(0), 0x100, 4, PATTERN_TEST, 0xFFFFFFFF, 0xFFFFFFFF },
{ E1000_RDLEN(0), 0x100, 4, PATTERN_TEST, 0x000FFFF0, 0x000FFFFF },
{ E1000_RDBAL(4), 0x40, 12, PATTERN_TEST, 0xFFFFFF80, 0xFFFFFFFF },
{ E1000_RDBAH(4), 0x40, 12, PATTERN_TEST, 0xFFFFFFFF, 0xFFFFFFFF },
{ E1000_RDLEN(4), 0x40, 12, PATTERN_TEST, 0x000FFFF0, 0x000FFFFF },
/* Enable all RX queues before testing. */
{ E1000_RXDCTL(0), 0x100, 4, WRITE_NO_TEST, 0, E1000_RXDCTL_QUEUE_ENABLE },
{ E1000_RXDCTL(4), 0x40, 12, WRITE_NO_TEST, 0, E1000_RXDCTL_QUEUE_ENABLE },
/* RDH is read-only for 82576, only test RDT. */
{ E1000_RDT(0), 0x100, 4, PATTERN_TEST, 0x0000FFFF, 0x0000FFFF },
{ E1000_RDT(4), 0x40, 12, PATTERN_TEST, 0x0000FFFF, 0x0000FFFF },
{ E1000_RXDCTL(0), 0x100, 4, WRITE_NO_TEST, 0, 0 },
{ E1000_RXDCTL(4), 0x40, 12, WRITE_NO_TEST, 0, 0 },
{ E1000_FCRTH, 0x100, 1, PATTERN_TEST, 0x0000FFF0, 0x0000FFF0 },
{ E1000_FCTTV, 0x100, 1, PATTERN_TEST, 0x0000FFFF, 0x0000FFFF },
{ E1000_TIPG, 0x100, 1, PATTERN_TEST, 0x3FFFFFFF, 0x3FFFFFFF },
{ E1000_TDBAL(0), 0x100, 4, PATTERN_TEST, 0xFFFFFF80, 0xFFFFFFFF },
{ E1000_TDBAH(0), 0x100, 4, PATTERN_TEST, 0xFFFFFFFF, 0xFFFFFFFF },
{ E1000_TDLEN(0), 0x100, 4, PATTERN_TEST, 0x000FFFF0, 0x000FFFFF },
{ E1000_TDBAL(4), 0x40, 12, PATTERN_TEST, 0xFFFFFF80, 0xFFFFFFFF },
{ E1000_TDBAH(4), 0x40, 12, PATTERN_TEST, 0xFFFFFFFF, 0xFFFFFFFF },
{ E1000_TDLEN(4), 0x40, 12, PATTERN_TEST, 0x000FFFF0, 0x000FFFFF },
{ E1000_RCTL, 0x100, 1, SET_READ_TEST, 0xFFFFFFFF, 0x00000000 },
{ E1000_RCTL, 0x100, 1, SET_READ_TEST, 0x04CFB0FE, 0x003FFFFB },
{ E1000_RCTL, 0x100, 1, SET_READ_TEST, 0x04CFB0FE, 0xFFFFFFFF },
{ E1000_TCTL, 0x100, 1, SET_READ_TEST, 0xFFFFFFFF, 0x00000000 },
{ E1000_RA, 0, 16, TABLE64_TEST_LO, 0xFFFFFFFF, 0xFFFFFFFF },
{ E1000_RA, 0, 16, TABLE64_TEST_HI, 0x83FFFFFF, 0xFFFFFFFF },
{ E1000_RA2, 0, 8, TABLE64_TEST_LO, 0xFFFFFFFF, 0xFFFFFFFF },
{ E1000_RA2, 0, 8, TABLE64_TEST_HI, 0x83FFFFFF, 0xFFFFFFFF },
{ E1000_MTA, 0, 128,TABLE32_TEST, 0xFFFFFFFF, 0xFFFFFFFF },
{ 0, 0, 0, 0 }
};
/* 82575 register test */
static struct igb_reg_test reg_test_82575[] = {
{ E1000_FCAL, 0x100, 1, PATTERN_TEST, 0xFFFFFFFF, 0xFFFFFFFF },
{ E1000_FCAH, 0x100, 1, PATTERN_TEST, 0x0000FFFF, 0xFFFFFFFF },
{ E1000_FCT, 0x100, 1, PATTERN_TEST, 0x0000FFFF, 0xFFFFFFFF },
{ E1000_VET, 0x100, 1, PATTERN_TEST, 0xFFFFFFFF, 0xFFFFFFFF },
{ E1000_RDBAL(0), 0x100, 4, PATTERN_TEST, 0xFFFFFF80, 0xFFFFFFFF },
{ E1000_RDBAH(0), 0x100, 4, PATTERN_TEST, 0xFFFFFFFF, 0xFFFFFFFF },
{ E1000_RDLEN(0), 0x100, 4, PATTERN_TEST, 0x000FFF80, 0x000FFFFF },
/* Enable all four RX queues before testing. */
{ E1000_RXDCTL(0), 0x100, 4, WRITE_NO_TEST, 0, E1000_RXDCTL_QUEUE_ENABLE },
/* RDH is read-only for 82575, only test RDT. */
{ E1000_RDT(0), 0x100, 4, PATTERN_TEST, 0x0000FFFF, 0x0000FFFF },
{ E1000_RXDCTL(0), 0x100, 4, WRITE_NO_TEST, 0, 0 },
{ E1000_FCRTH, 0x100, 1, PATTERN_TEST, 0x0000FFF0, 0x0000FFF0 },
{ E1000_FCTTV, 0x100, 1, PATTERN_TEST, 0x0000FFFF, 0x0000FFFF },
{ E1000_TIPG, 0x100, 1, PATTERN_TEST, 0x3FFFFFFF, 0x3FFFFFFF },
{ E1000_TDBAL(0), 0x100, 4, PATTERN_TEST, 0xFFFFFF80, 0xFFFFFFFF },
{ E1000_TDBAH(0), 0x100, 4, PATTERN_TEST, 0xFFFFFFFF, 0xFFFFFFFF },
{ E1000_TDLEN(0), 0x100, 4, PATTERN_TEST, 0x000FFF80, 0x000FFFFF },
{ E1000_RCTL, 0x100, 1, SET_READ_TEST, 0xFFFFFFFF, 0x00000000 },
{ E1000_RCTL, 0x100, 1, SET_READ_TEST, 0x04CFB3FE, 0x003FFFFB },
{ E1000_RCTL, 0x100, 1, SET_READ_TEST, 0x04CFB3FE, 0xFFFFFFFF },
{ E1000_TCTL, 0x100, 1, SET_READ_TEST, 0xFFFFFFFF, 0x00000000 },
{ E1000_TXCW, 0x100, 1, PATTERN_TEST, 0xC000FFFF, 0x0000FFFF },
{ E1000_RA, 0, 16, TABLE64_TEST_LO, 0xFFFFFFFF, 0xFFFFFFFF },
{ E1000_RA, 0, 16, TABLE64_TEST_HI, 0x800FFFFF, 0xFFFFFFFF },
{ E1000_MTA, 0, 128, TABLE32_TEST, 0xFFFFFFFF, 0xFFFFFFFF },
{ 0, 0, 0, 0 }
};
static bool reg_pattern_test(struct igb_adapter *adapter, u64 *data,
int reg, u32 mask, u32 write)
{
struct e1000_hw *hw = &adapter->hw;
u32 pat, val;
u32 _test[] =
{0x5A5A5A5A, 0xA5A5A5A5, 0x00000000, 0xFFFFFFFF};
for (pat = 0; pat < ARRAY_SIZE(_test); pat++) {
wr32(reg, (_test[pat] & write));
val = rd32(reg);
if (val != (_test[pat] & write & mask)) {
dev_err(&adapter->pdev->dev, "pattern test reg %04X "
"failed: got 0x%08X expected 0x%08X\n",
reg, val, (_test[pat] & write & mask));
*data = reg;
return 1;
}
}
return 0;
}
static bool reg_set_and_check(struct igb_adapter *adapter, u64 *data,
int reg, u32 mask, u32 write)
{
struct e1000_hw *hw = &adapter->hw;
u32 val;
wr32(reg, write & mask);
val = rd32(reg);
if ((write & mask) != (val & mask)) {
dev_err(&adapter->pdev->dev, "set/check reg %04X test failed:"
" got 0x%08X expected 0x%08X\n", reg,
(val & mask), (write & mask));
*data = reg;
return 1;
}
return 0;
}
#define REG_PATTERN_TEST(reg, mask, write) \
do { \
if (reg_pattern_test(adapter, data, reg, mask, write)) \
return 1; \
} while (0)
#define REG_SET_AND_CHECK(reg, mask, write) \
do { \
if (reg_set_and_check(adapter, data, reg, mask, write)) \
return 1; \
} while (0)
static int igb_reg_test(struct igb_adapter *adapter, u64 *data)
{
struct e1000_hw *hw = &adapter->hw;
struct igb_reg_test *test;
u32 value, before, after;
u32 i, toggle;
toggle = 0x7FFFF3FF;
switch (adapter->hw.mac.type) {
case e1000_82576:
test = reg_test_82576;
break;
default:
test = reg_test_82575;
break;
}
/* Because the status register is such a special case,
* we handle it separately from the rest of the register
* tests. Some bits are read-only, some toggle, and some
* are writable on newer MACs.
*/
before = rd32(E1000_STATUS);
value = (rd32(E1000_STATUS) & toggle);
wr32(E1000_STATUS, toggle);
after = rd32(E1000_STATUS) & toggle;
if (value != after) {
dev_err(&adapter->pdev->dev, "failed STATUS register test "
"got: 0x%08X expected: 0x%08X\n", after, value);
*data = 1;
return 1;
}
/* restore previous status */
wr32(E1000_STATUS, before);
/* Perform the remainder of the register test, looping through
* the test table until we either fail or reach the null entry.
*/
while (test->reg) {
for (i = 0; i < test->array_len; i++) {
switch (test->test_type) {
case PATTERN_TEST:
REG_PATTERN_TEST(test->reg +
(i * test->reg_offset),
test->mask,
test->write);
break;
case SET_READ_TEST:
REG_SET_AND_CHECK(test->reg +
(i * test->reg_offset),
test->mask,
test->write);
break;
case WRITE_NO_TEST:
writel(test->write,
(adapter->hw.hw_addr + test->reg)
+ (i * test->reg_offset));
break;
case TABLE32_TEST:
REG_PATTERN_TEST(test->reg + (i * 4),
test->mask,
test->write);
break;
case TABLE64_TEST_LO:
REG_PATTERN_TEST(test->reg + (i * 8),
test->mask,
test->write);
break;
case TABLE64_TEST_HI:
REG_PATTERN_TEST((test->reg + 4) + (i * 8),
test->mask,
test->write);
break;
}
}
test++;
}
*data = 0;
return 0;
}
static int igb_eeprom_test(struct igb_adapter *adapter, u64 *data)
{
u16 temp;
u16 checksum = 0;
u16 i;
*data = 0;
/* Read and add up the contents of the EEPROM */
for (i = 0; i < (NVM_CHECKSUM_REG + 1); i++) {
if ((adapter->hw.nvm.ops.read(&adapter->hw, i, 1, &temp))
< 0) {
*data = 1;
break;
}
checksum += temp;
}
/* If Checksum is not Correct return error else test passed */
if ((checksum != (u16) NVM_SUM) && !(*data))
*data = 2;
return *data;
}
static irqreturn_t igb_test_intr(int irq, void *data)
{
struct net_device *netdev = (struct net_device *) data;
struct igb_adapter *adapter = netdev_priv(netdev);
struct e1000_hw *hw = &adapter->hw;
adapter->test_icr |= rd32(E1000_ICR);
return IRQ_HANDLED;
}
static int igb_intr_test(struct igb_adapter *adapter, u64 *data)
{
struct e1000_hw *hw = &adapter->hw;
struct net_device *netdev = adapter->netdev;
u32 mask, ics_mask, i = 0, shared_int = true;
u32 irq = adapter->pdev->irq;
*data = 0;
/* Hook up test interrupt handler just for this test */
if (adapter->msix_entries)
/* NOTE: we don't test MSI-X interrupts here, yet */
return 0;
if (adapter->flags & IGB_FLAG_HAS_MSI) {
shared_int = false;
if (request_irq(irq, &igb_test_intr, 0, netdev->name, netdev)) {
*data = 1;
return -1;
}
} else if (!request_irq(irq, &igb_test_intr, IRQF_PROBE_SHARED,
netdev->name, netdev)) {
shared_int = false;
} else if (request_irq(irq, &igb_test_intr, IRQF_SHARED,
netdev->name, netdev)) {
*data = 1;
return -1;
}
dev_info(&adapter->pdev->dev, "testing %s interrupt\n",
(shared_int ? "shared" : "unshared"));
/* Disable all the interrupts */
wr32(E1000_IMC, 0xFFFFFFFF);
msleep(10);
/* Define all writable bits for ICS */
switch(hw->mac.type) {
case e1000_82575:
ics_mask = 0x37F47EDD;
break;
case e1000_82576:
ics_mask = 0x77D4FBFD;
break;
default:
ics_mask = 0x7FFFFFFF;
break;
}
/* Test each interrupt */
for (; i < 31; i++) {
/* Interrupt to test */
mask = 1 << i;
if (!(mask & ics_mask))
continue;
if (!shared_int) {
/* Disable the interrupt to be reported in
* the cause register and then force the same
* interrupt and see if one gets posted. If
* an interrupt was posted to the bus, the
* test failed.
*/
adapter->test_icr = 0;
/* Flush any pending interrupts */
wr32(E1000_ICR, ~0);
wr32(E1000_IMC, mask);
wr32(E1000_ICS, mask);
msleep(10);
if (adapter->test_icr & mask) {
*data = 3;
break;
}
}
/* Enable the interrupt to be reported in
* the cause register and then force the same
* interrupt and see if one gets posted. If
* an interrupt was not posted to the bus, the
* test failed.
*/
adapter->test_icr = 0;
/* Flush any pending interrupts */
wr32(E1000_ICR, ~0);
wr32(E1000_IMS, mask);
wr32(E1000_ICS, mask);
msleep(10);
if (!(adapter->test_icr & mask)) {
*data = 4;
break;
}
if (!shared_int) {
/* Disable the other interrupts to be reported in
* the cause register and then force the other
* interrupts and see if any get posted. If
* an interrupt was posted to the bus, the
* test failed.
*/
adapter->test_icr = 0;
/* Flush any pending interrupts */
wr32(E1000_ICR, ~0);
wr32(E1000_IMC, ~mask);
wr32(E1000_ICS, ~mask);
msleep(10);
if (adapter->test_icr & mask) {
*data = 5;
break;
}
}
}
/* Disable all the interrupts */
wr32(E1000_IMC, ~0);
msleep(10);
/* Unhook test interrupt handler */
free_irq(irq, netdev);
return *data;
}
static void igb_free_desc_rings(struct igb_adapter *adapter)
{
struct igb_ring *tx_ring = &adapter->test_tx_ring;
struct igb_ring *rx_ring = &adapter->test_rx_ring;
struct pci_dev *pdev = adapter->pdev;
int i;
if (tx_ring->desc && tx_ring->buffer_info) {
for (i = 0; i < tx_ring->count; i++) {
struct igb_buffer *buf = &(tx_ring->buffer_info[i]);
if (buf->dma)
pci_unmap_single(pdev, buf->dma, buf->length,
PCI_DMA_TODEVICE);
if (buf->skb)
dev_kfree_skb(buf->skb);
}
}
if (rx_ring->desc && rx_ring->buffer_info) {
for (i = 0; i < rx_ring->count; i++) {
struct igb_buffer *buf = &(rx_ring->buffer_info[i]);
if (buf->dma)
pci_unmap_single(pdev, buf->dma,
IGB_RXBUFFER_2048,
PCI_DMA_FROMDEVICE);
if (buf->skb)
dev_kfree_skb(buf->skb);
}
}
if (tx_ring->desc) {
pci_free_consistent(pdev, tx_ring->size, tx_ring->desc,
tx_ring->dma);
tx_ring->desc = NULL;
}
if (rx_ring->desc) {
pci_free_consistent(pdev, rx_ring->size, rx_ring->desc,
rx_ring->dma);
rx_ring->desc = NULL;
}
kfree(tx_ring->buffer_info);
tx_ring->buffer_info = NULL;
kfree(rx_ring->buffer_info);
rx_ring->buffer_info = NULL;
return;
}
static int igb_setup_desc_rings(struct igb_adapter *adapter)
{
struct e1000_hw *hw = &adapter->hw;
struct igb_ring *tx_ring = &adapter->test_tx_ring;
struct igb_ring *rx_ring = &adapter->test_rx_ring;
struct pci_dev *pdev = adapter->pdev;
struct igb_buffer *buffer_info;
u32 rctl;
int i, ret_val;
/* Setup Tx descriptor ring and Tx buffers */
if (!tx_ring->count)
tx_ring->count = IGB_DEFAULT_TXD;
tx_ring->buffer_info = kcalloc(tx_ring->count,
sizeof(struct igb_buffer),
GFP_KERNEL);
if (!tx_ring->buffer_info) {
ret_val = 1;
goto err_nomem;
}
tx_ring->size = tx_ring->count * sizeof(union e1000_adv_tx_desc);
tx_ring->size = ALIGN(tx_ring->size, 4096);
tx_ring->desc = pci_alloc_consistent(pdev, tx_ring->size,
&tx_ring->dma);
if (!tx_ring->desc) {
ret_val = 2;
goto err_nomem;
}
tx_ring->next_to_use = tx_ring->next_to_clean = 0;
wr32(E1000_TDBAL(0),
((u64) tx_ring->dma & 0x00000000FFFFFFFF));
wr32(E1000_TDBAH(0), ((u64) tx_ring->dma >> 32));
wr32(E1000_TDLEN(0),
tx_ring->count * sizeof(union e1000_adv_tx_desc));
wr32(E1000_TDH(0), 0);
wr32(E1000_TDT(0), 0);
wr32(E1000_TCTL,
E1000_TCTL_PSP | E1000_TCTL_EN |
E1000_COLLISION_THRESHOLD << E1000_CT_SHIFT |
E1000_COLLISION_DISTANCE << E1000_COLD_SHIFT);
for (i = 0; i < tx_ring->count; i++) {
union e1000_adv_tx_desc *tx_desc;
struct sk_buff *skb;
unsigned int size = 1024;
tx_desc = E1000_TX_DESC_ADV(*tx_ring, i);
skb = alloc_skb(size, GFP_KERNEL);
if (!skb) {
ret_val = 3;
goto err_nomem;
}
skb_put(skb, size);
buffer_info = &tx_ring->buffer_info[i];
buffer_info->skb = skb;
buffer_info->length = skb->len;
buffer_info->dma = pci_map_single(pdev, skb->data, skb->len,
PCI_DMA_TODEVICE);
tx_desc->read.buffer_addr = cpu_to_le64(buffer_info->dma);
tx_desc->read.olinfo_status = cpu_to_le32(skb->len) <<
E1000_ADVTXD_PAYLEN_SHIFT;
tx_desc->read.cmd_type_len = cpu_to_le32(skb->len);
tx_desc->read.cmd_type_len |= cpu_to_le32(E1000_TXD_CMD_EOP |
E1000_TXD_CMD_IFCS |
E1000_TXD_CMD_RS |
E1000_ADVTXD_DTYP_DATA |
E1000_ADVTXD_DCMD_DEXT);
}
/* Setup Rx descriptor ring and Rx buffers */
if (!rx_ring->count)
rx_ring->count = IGB_DEFAULT_RXD;
rx_ring->buffer_info = kcalloc(rx_ring->count,
sizeof(struct igb_buffer),
GFP_KERNEL);
if (!rx_ring->buffer_info) {
ret_val = 4;
goto err_nomem;
}
rx_ring->size = rx_ring->count * sizeof(union e1000_adv_rx_desc);
rx_ring->desc = pci_alloc_consistent(pdev, rx_ring->size,
&rx_ring->dma);
if (!rx_ring->desc) {
ret_val = 5;
goto err_nomem;
}
rx_ring->next_to_use = rx_ring->next_to_clean = 0;
rctl = rd32(E1000_RCTL);
wr32(E1000_RCTL, rctl & ~E1000_RCTL_EN);
wr32(E1000_RDBAL(0),
((u64) rx_ring->dma & 0xFFFFFFFF));
wr32(E1000_RDBAH(0),
((u64) rx_ring->dma >> 32));
wr32(E1000_RDLEN(0), rx_ring->size);
wr32(E1000_RDH(0), 0);
wr32(E1000_RDT(0), 0);
rctl &= ~(E1000_RCTL_LBM_TCVR | E1000_RCTL_LBM_MAC);
rctl = E1000_RCTL_EN | E1000_RCTL_BAM | E1000_RCTL_RDMTS_HALF |
(adapter->hw.mac.mc_filter_type << E1000_RCTL_MO_SHIFT);
wr32(E1000_RCTL, rctl);
wr32(E1000_SRRCTL(0), E1000_SRRCTL_DESCTYPE_ADV_ONEBUF);
for (i = 0; i < rx_ring->count; i++) {
union e1000_adv_rx_desc *rx_desc;
struct sk_buff *skb;
buffer_info = &rx_ring->buffer_info[i];
rx_desc = E1000_RX_DESC_ADV(*rx_ring, i);
skb = alloc_skb(IGB_RXBUFFER_2048 + NET_IP_ALIGN,
GFP_KERNEL);
if (!skb) {
ret_val = 6;
goto err_nomem;
}
skb_reserve(skb, NET_IP_ALIGN);
buffer_info->skb = skb;
buffer_info->dma = pci_map_single(pdev, skb->data,
IGB_RXBUFFER_2048,
PCI_DMA_FROMDEVICE);
rx_desc->read.pkt_addr = cpu_to_le64(buffer_info->dma);
memset(skb->data, 0x00, skb->len);
}
return 0;
err_nomem:
igb_free_desc_rings(adapter);
return ret_val;
}
static void igb_phy_disable_receiver(struct igb_adapter *adapter)
{
struct e1000_hw *hw = &adapter->hw;
/* Write out to PHY registers 29 and 30 to disable the Receiver. */
igb_write_phy_reg(hw, 29, 0x001F);
igb_write_phy_reg(hw, 30, 0x8FFC);
igb_write_phy_reg(hw, 29, 0x001A);
igb_write_phy_reg(hw, 30, 0x8FF0);
}
static int igb_integrated_phy_loopback(struct igb_adapter *adapter)
{
struct e1000_hw *hw = &adapter->hw;
u32 ctrl_reg = 0;
hw->mac.autoneg = false;
if (hw->phy.type == e1000_phy_m88) {
/* Auto-MDI/MDIX Off */
igb_write_phy_reg(hw, M88E1000_PHY_SPEC_CTRL, 0x0808);
/* reset to update Auto-MDI/MDIX */
igb_write_phy_reg(hw, PHY_CONTROL, 0x9140);
/* autoneg off */
igb_write_phy_reg(hw, PHY_CONTROL, 0x8140);
}
ctrl_reg = rd32(E1000_CTRL);
/* force 1000, set loopback */
igb_write_phy_reg(hw, PHY_CONTROL, 0x4140);
/* Now set up the MAC to the same speed/duplex as the PHY. */
ctrl_reg = rd32(E1000_CTRL);
ctrl_reg &= ~E1000_CTRL_SPD_SEL; /* Clear the speed sel bits */
ctrl_reg |= (E1000_CTRL_FRCSPD | /* Set the Force Speed Bit */
E1000_CTRL_FRCDPX | /* Set the Force Duplex Bit */
E1000_CTRL_SPD_1000 |/* Force Speed to 1000 */
E1000_CTRL_FD | /* Force Duplex to FULL */
E1000_CTRL_SLU); /* Set link up enable bit */
if (hw->phy.type == e1000_phy_m88)
ctrl_reg |= E1000_CTRL_ILOS; /* Invert Loss of Signal */
wr32(E1000_CTRL, ctrl_reg);
/* Disable the receiver on the PHY so when a cable is plugged in, the
* PHY does not begin to autoneg when a cable is reconnected to the NIC.
*/
if (hw->phy.type == e1000_phy_m88)
igb_phy_disable_receiver(adapter);
udelay(500);
return 0;
}
static int igb_set_phy_loopback(struct igb_adapter *adapter)
{
return igb_integrated_phy_loopback(adapter);
}
static int igb_setup_loopback_test(struct igb_adapter *adapter)
{
struct e1000_hw *hw = &adapter->hw;
u32 reg;
if (hw->phy.media_type == e1000_media_type_internal_serdes) {
reg = rd32(E1000_RCTL);
reg |= E1000_RCTL_LBM_TCVR;
wr32(E1000_RCTL, reg);
wr32(E1000_SCTL, E1000_ENABLE_SERDES_LOOPBACK);
reg = rd32(E1000_CTRL);
reg &= ~(E1000_CTRL_RFCE |
E1000_CTRL_TFCE |
E1000_CTRL_LRST);
reg |= E1000_CTRL_SLU |
E1000_CTRL_FD;
wr32(E1000_CTRL, reg);
/* Unset switch control to serdes energy detect */
reg = rd32(E1000_CONNSW);
reg &= ~E1000_CONNSW_ENRGSRC;
wr32(E1000_CONNSW, reg);
/* Set PCS register for forced speed */
reg = rd32(E1000_PCS_LCTL);
reg &= ~E1000_PCS_LCTL_AN_ENABLE; /* Disable Autoneg*/
reg |= E1000_PCS_LCTL_FLV_LINK_UP | /* Force link up */
E1000_PCS_LCTL_FSV_1000 | /* Force 1000 */
E1000_PCS_LCTL_FDV_FULL | /* SerDes Full duplex */
E1000_PCS_LCTL_FSD | /* Force Speed */
E1000_PCS_LCTL_FORCE_LINK; /* Force Link */
wr32(E1000_PCS_LCTL, reg);
return 0;
} else if (hw->phy.media_type == e1000_media_type_copper) {
return igb_set_phy_loopback(adapter);
}
return 7;
}
static void igb_loopback_cleanup(struct igb_adapter *adapter)
{
struct e1000_hw *hw = &adapter->hw;
u32 rctl;
u16 phy_reg;
rctl = rd32(E1000_RCTL);
rctl &= ~(E1000_RCTL_LBM_TCVR | E1000_RCTL_LBM_MAC);
wr32(E1000_RCTL, rctl);
hw->mac.autoneg = true;
igb_read_phy_reg(hw, PHY_CONTROL, &phy_reg);
if (phy_reg & MII_CR_LOOPBACK) {
phy_reg &= ~MII_CR_LOOPBACK;
igb_write_phy_reg(hw, PHY_CONTROL, phy_reg);
igb_phy_sw_reset(hw);
}
}
static void igb_create_lbtest_frame(struct sk_buff *skb,
unsigned int frame_size)
{
memset(skb->data, 0xFF, frame_size);
frame_size &= ~1;
memset(&skb->data[frame_size / 2], 0xAA, frame_size / 2 - 1);
memset(&skb->data[frame_size / 2 + 10], 0xBE, 1);
memset(&skb->data[frame_size / 2 + 12], 0xAF, 1);
}
static int igb_check_lbtest_frame(struct sk_buff *skb, unsigned int frame_size)
{
frame_size &= ~1;
if (*(skb->data + 3) == 0xFF)
if ((*(skb->data + frame_size / 2 + 10) == 0xBE) &&
(*(skb->data + frame_size / 2 + 12) == 0xAF))
return 0;
return 13;
}
static int igb_run_loopback_test(struct igb_adapter *adapter)
{
struct e1000_hw *hw = &adapter->hw;
struct igb_ring *tx_ring = &adapter->test_tx_ring;
struct igb_ring *rx_ring = &adapter->test_rx_ring;
struct pci_dev *pdev = adapter->pdev;
int i, j, k, l, lc, good_cnt;
int ret_val = 0;
unsigned long time;
wr32(E1000_RDT(0), rx_ring->count - 1);
/* Calculate the loop count based on the largest descriptor ring
* The idea is to wrap the largest ring a number of times using 64
* send/receive pairs during each loop
*/
if (rx_ring->count <= tx_ring->count)
lc = ((tx_ring->count / 64) * 2) + 1;
else
lc = ((rx_ring->count / 64) * 2) + 1;
k = l = 0;
for (j = 0; j <= lc; j++) { /* loop count loop */
for (i = 0; i < 64; i++) { /* send the packets */
igb_create_lbtest_frame(tx_ring->buffer_info[k].skb,
1024);
pci_dma_sync_single_for_device(pdev,
tx_ring->buffer_info[k].dma,
tx_ring->buffer_info[k].length,
PCI_DMA_TODEVICE);
k++;
if (k == tx_ring->count)
k = 0;
}
wr32(E1000_TDT(0), k);
msleep(200);
time = jiffies; /* set the start time for the receive */
good_cnt = 0;
do { /* receive the sent packets */
pci_dma_sync_single_for_cpu(pdev,
rx_ring->buffer_info[l].dma,
IGB_RXBUFFER_2048,
PCI_DMA_FROMDEVICE);
ret_val = igb_check_lbtest_frame(
rx_ring->buffer_info[l].skb, 1024);
if (!ret_val)
good_cnt++;
l++;
if (l == rx_ring->count)
l = 0;
/* time + 20 msecs (200 msecs on 2.4) is more than
* enough time to complete the receives, if it's
* exceeded, break and error off
*/
} while (good_cnt < 64 && jiffies < (time + 20));
if (good_cnt != 64) {
ret_val = 13; /* ret_val is the same as mis-compare */
break;
}
if (jiffies >= (time + 20)) {
ret_val = 14; /* error code for time out error */
break;
}
} /* end loop count loop */
return ret_val;
}
static int igb_loopback_test(struct igb_adapter *adapter, u64 *data)
{
/* PHY loopback cannot be performed if SoL/IDER
* sessions are active */
if (igb_check_reset_block(&adapter->hw)) {
dev_err(&adapter->pdev->dev,
"Cannot do PHY loopback test "
"when SoL/IDER is active.\n");
*data = 0;
goto out;
}
*data = igb_setup_desc_rings(adapter);
if (*data)
goto out;
*data = igb_setup_loopback_test(adapter);
if (*data)
goto err_loopback;
*data = igb_run_loopback_test(adapter);
igb_loopback_cleanup(adapter);
err_loopback:
igb_free_desc_rings(adapter);
out:
return *data;
}
static int igb_link_test(struct igb_adapter *adapter, u64 *data)
{
struct e1000_hw *hw = &adapter->hw;
*data = 0;
if (hw->phy.media_type == e1000_media_type_internal_serdes) {
int i = 0;
hw->mac.serdes_has_link = false;
/* On some blade server designs, link establishment
* could take as long as 2-3 minutes */
do {
hw->mac.ops.check_for_link(&adapter->hw);
if (hw->mac.serdes_has_link)
return *data;
msleep(20);
} while (i++ < 3750);
*data = 1;
} else {
hw->mac.ops.check_for_link(&adapter->hw);
if (hw->mac.autoneg)
msleep(4000);
if (!(rd32(E1000_STATUS) &
E1000_STATUS_LU))
*data = 1;
}
return *data;
}
static void igb_diag_test(struct net_device *netdev,
struct ethtool_test *eth_test, u64 *data)
{
struct igb_adapter *adapter = netdev_priv(netdev);
u16 autoneg_advertised;
u8 forced_speed_duplex, autoneg;
bool if_running = netif_running(netdev);
set_bit(__IGB_TESTING, &adapter->state);
if (eth_test->flags == ETH_TEST_FL_OFFLINE) {
/* Offline tests */
/* save speed, duplex, autoneg settings */
autoneg_advertised = adapter->hw.phy.autoneg_advertised;
forced_speed_duplex = adapter->hw.mac.forced_speed_duplex;
autoneg = adapter->hw.mac.autoneg;
dev_info(&adapter->pdev->dev, "offline testing starting\n");
/* Link test performed before hardware reset so autoneg doesn't
* interfere with test result */
if (igb_link_test(adapter, &data[4]))
eth_test->flags |= ETH_TEST_FL_FAILED;
if (if_running)
/* indicate we're in test mode */
dev_close(netdev);
else
igb_reset(adapter);
if (igb_reg_test(adapter, &data[0]))
eth_test->flags |= ETH_TEST_FL_FAILED;
igb_reset(adapter);
if (igb_eeprom_test(adapter, &data[1]))
eth_test->flags |= ETH_TEST_FL_FAILED;
igb_reset(adapter);
if (igb_intr_test(adapter, &data[2]))
eth_test->flags |= ETH_TEST_FL_FAILED;
igb_reset(adapter);
if (igb_loopback_test(adapter, &data[3]))
eth_test->flags |= ETH_TEST_FL_FAILED;
/* restore speed, duplex, autoneg settings */
adapter->hw.phy.autoneg_advertised = autoneg_advertised;
adapter->hw.mac.forced_speed_duplex = forced_speed_duplex;
adapter->hw.mac.autoneg = autoneg;
/* force this routine to wait until autoneg complete/timeout */
adapter->hw.phy.autoneg_wait_to_complete = true;
igb_reset(adapter);
adapter->hw.phy.autoneg_wait_to_complete = false;
clear_bit(__IGB_TESTING, &adapter->state);
if (if_running)
dev_open(netdev);
} else {
dev_info(&adapter->pdev->dev, "online testing starting\n");
/* Online tests */
if (igb_link_test(adapter, &data[4]))
eth_test->flags |= ETH_TEST_FL_FAILED;
/* Online tests aren't run; pass by default */
data[0] = 0;
data[1] = 0;
data[2] = 0;
data[3] = 0;
clear_bit(__IGB_TESTING, &adapter->state);
}
msleep_interruptible(4 * 1000);
}
static int igb_wol_exclusion(struct igb_adapter *adapter,
struct ethtool_wolinfo *wol)
{
struct e1000_hw *hw = &adapter->hw;
int retval = 1; /* fail by default */
switch (hw->device_id) {
case E1000_DEV_ID_82575GB_QUAD_COPPER:
/* WoL not supported */
wol->supported = 0;
break;
case E1000_DEV_ID_82575EB_FIBER_SERDES:
case E1000_DEV_ID_82576_FIBER:
case E1000_DEV_ID_82576_SERDES:
/* Wake events not supported on port B */
if (rd32(E1000_STATUS) & E1000_STATUS_FUNC_1) {
wol->supported = 0;
break;
}
/* return success for non excluded adapter ports */
retval = 0;
break;
case E1000_DEV_ID_82576_QUAD_COPPER:
/* quad port adapters only support WoL on port A */
if (!(adapter->flags & IGB_FLAG_QUAD_PORT_A)) {
wol->supported = 0;
break;
}
/* return success for non excluded adapter ports */
retval = 0;
break;
default:
/* dual port cards only support WoL on port A from now on
* unless it was enabled in the eeprom for port B
* so exclude FUNC_1 ports from having WoL enabled */
if (rd32(E1000_STATUS) & E1000_STATUS_FUNC_1 &&
!adapter->eeprom_wol) {
wol->supported = 0;
break;
}
retval = 0;
}
return retval;
}
static void igb_get_wol(struct net_device *netdev, struct ethtool_wolinfo *wol)
{
struct igb_adapter *adapter = netdev_priv(netdev);
wol->supported = WAKE_UCAST | WAKE_MCAST |
WAKE_BCAST | WAKE_MAGIC;
wol->wolopts = 0;
/* this function will set ->supported = 0 and return 1 if wol is not
* supported by this hardware */
if (igb_wol_exclusion(adapter, wol) ||
!device_can_wakeup(&adapter->pdev->dev))
return;
/* apply any specific unsupported masks here */
switch (adapter->hw.device_id) {
default:
break;
}
if (adapter->wol & E1000_WUFC_EX)
wol->wolopts |= WAKE_UCAST;
if (adapter->wol & E1000_WUFC_MC)
wol->wolopts |= WAKE_MCAST;
if (adapter->wol & E1000_WUFC_BC)
wol->wolopts |= WAKE_BCAST;
if (adapter->wol & E1000_WUFC_MAG)
wol->wolopts |= WAKE_MAGIC;
return;
}
static int igb_set_wol(struct net_device *netdev, struct ethtool_wolinfo *wol)
{
struct igb_adapter *adapter = netdev_priv(netdev);
if (wol->wolopts & (WAKE_PHY | WAKE_ARP | WAKE_MAGICSECURE))
return -EOPNOTSUPP;
if (igb_wol_exclusion(adapter, wol) ||
!device_can_wakeup(&adapter->pdev->dev))
return wol->wolopts ? -EOPNOTSUPP : 0;
/* these settings will always override what we currently have */
adapter->wol = 0;
if (wol->wolopts & WAKE_UCAST)
adapter->wol |= E1000_WUFC_EX;
if (wol->wolopts & WAKE_MCAST)
adapter->wol |= E1000_WUFC_MC;
if (wol->wolopts & WAKE_BCAST)
adapter->wol |= E1000_WUFC_BC;
if (wol->wolopts & WAKE_MAGIC)
adapter->wol |= E1000_WUFC_MAG;
device_set_wakeup_enable(&adapter->pdev->dev, adapter->wol);
return 0;
}
/* bit defines for adapter->led_status */
#define IGB_LED_ON 0
static int igb_phys_id(struct net_device *netdev, u32 data)
{
struct igb_adapter *adapter = netdev_priv(netdev);
struct e1000_hw *hw = &adapter->hw;
if (!data || data > (u32)(MAX_SCHEDULE_TIMEOUT / HZ))
data = (u32)(MAX_SCHEDULE_TIMEOUT / HZ);
igb_blink_led(hw);
msleep_interruptible(data * 1000);
igb_led_off(hw);
clear_bit(IGB_LED_ON, &adapter->led_status);
igb_cleanup_led(hw);
return 0;
}
static int igb_set_coalesce(struct net_device *netdev,
struct ethtool_coalesce *ec)
{
struct igb_adapter *adapter = netdev_priv(netdev);
struct e1000_hw *hw = &adapter->hw;
int i;
if ((ec->rx_coalesce_usecs > IGB_MAX_ITR_USECS) ||
((ec->rx_coalesce_usecs > 3) &&
(ec->rx_coalesce_usecs < IGB_MIN_ITR_USECS)) ||
(ec->rx_coalesce_usecs == 2))
return -EINVAL;
/* convert to rate of irq's per second */
if (ec->rx_coalesce_usecs && ec->rx_coalesce_usecs <= 3) {
adapter->itr_setting = ec->rx_coalesce_usecs;
adapter->itr = IGB_START_ITR;
} else {
adapter->itr_setting = ec->rx_coalesce_usecs << 2;
adapter->itr = adapter->itr_setting;
}
for (i = 0; i < adapter->num_rx_queues; i++)
wr32(adapter->rx_ring[i].itr_register, adapter->itr);
return 0;
}
static int igb_get_coalesce(struct net_device *netdev,
struct ethtool_coalesce *ec)
{
struct igb_adapter *adapter = netdev_priv(netdev);
if (adapter->itr_setting <= 3)
ec->rx_coalesce_usecs = adapter->itr_setting;
else
ec->rx_coalesce_usecs = adapter->itr_setting >> 2;
return 0;
}
static int igb_nway_reset(struct net_device *netdev)
{
struct igb_adapter *adapter = netdev_priv(netdev);
if (netif_running(netdev))
igb_reinit_locked(adapter);
return 0;
}
static int igb_get_sset_count(struct net_device *netdev, int sset)
{
switch (sset) {
case ETH_SS_STATS:
return IGB_STATS_LEN;
case ETH_SS_TEST:
return IGB_TEST_LEN;
default:
return -ENOTSUPP;
}
}
static void igb_get_ethtool_stats(struct net_device *netdev,
struct ethtool_stats *stats, u64 *data)
{
struct igb_adapter *adapter = netdev_priv(netdev);
u64 *queue_stat;
int stat_count_tx = sizeof(struct igb_tx_queue_stats) / sizeof(u64);
int stat_count_rx = sizeof(struct igb_rx_queue_stats) / sizeof(u64);
int j;
int i;
igb_update_stats(adapter);
for (i = 0; i < IGB_GLOBAL_STATS_LEN; i++) {
char *p = (char *)adapter+igb_gstrings_stats[i].stat_offset;
data[i] = (igb_gstrings_stats[i].sizeof_stat ==
sizeof(u64)) ? *(u64 *)p : *(u32 *)p;
}
for (j = 0; j < adapter->num_tx_queues; j++) {
int k;
queue_stat = (u64 *)&adapter->tx_ring[j].tx_stats;
for (k = 0; k < stat_count_tx; k++)
data[i + k] = queue_stat[k];
i += k;
}
for (j = 0; j < adapter->num_rx_queues; j++) {
int k;
queue_stat = (u64 *)&adapter->rx_ring[j].rx_stats;
for (k = 0; k < stat_count_rx; k++)
data[i + k] = queue_stat[k];
i += k;
}
}
static void igb_get_strings(struct net_device *netdev, u32 stringset, u8 *data)
{
struct igb_adapter *adapter = netdev_priv(netdev);
u8 *p = data;
int i;
switch (stringset) {
case ETH_SS_TEST:
memcpy(data, *igb_gstrings_test,
IGB_TEST_LEN*ETH_GSTRING_LEN);
break;
case ETH_SS_STATS:
for (i = 0; i < IGB_GLOBAL_STATS_LEN; i++) {
memcpy(p, igb_gstrings_stats[i].stat_string,
ETH_GSTRING_LEN);
p += ETH_GSTRING_LEN;
}
for (i = 0; i < adapter->num_tx_queues; i++) {
sprintf(p, "tx_queue_%u_packets", i);
p += ETH_GSTRING_LEN;
sprintf(p, "tx_queue_%u_bytes", i);
p += ETH_GSTRING_LEN;
}
for (i = 0; i < adapter->num_rx_queues; i++) {
sprintf(p, "rx_queue_%u_packets", i);
p += ETH_GSTRING_LEN;
sprintf(p, "rx_queue_%u_bytes", i);
p += ETH_GSTRING_LEN;
sprintf(p, "rx_queue_%u_drops", i);
p += ETH_GSTRING_LEN;
}
/* BUG_ON(p - data != IGB_STATS_LEN * ETH_GSTRING_LEN); */
break;
}
}
static const struct ethtool_ops igb_ethtool_ops = {
.get_settings = igb_get_settings,
.set_settings = igb_set_settings,
.get_drvinfo = igb_get_drvinfo,
.get_regs_len = igb_get_regs_len,
.get_regs = igb_get_regs,
.get_wol = igb_get_wol,
.set_wol = igb_set_wol,
.get_msglevel = igb_get_msglevel,
.set_msglevel = igb_set_msglevel,
.nway_reset = igb_nway_reset,
.get_link = ethtool_op_get_link,
.get_eeprom_len = igb_get_eeprom_len,
.get_eeprom = igb_get_eeprom,
.set_eeprom = igb_set_eeprom,
.get_ringparam = igb_get_ringparam,
.set_ringparam = igb_set_ringparam,
.get_pauseparam = igb_get_pauseparam,
.set_pauseparam = igb_set_pauseparam,
.get_rx_csum = igb_get_rx_csum,
.set_rx_csum = igb_set_rx_csum,
.get_tx_csum = igb_get_tx_csum,
.set_tx_csum = igb_set_tx_csum,
.get_sg = ethtool_op_get_sg,
.set_sg = ethtool_op_set_sg,
.get_tso = ethtool_op_get_tso,
.set_tso = igb_set_tso,
.self_test = igb_diag_test,
.get_strings = igb_get_strings,
.phys_id = igb_phys_id,
.get_sset_count = igb_get_sset_count,
.get_ethtool_stats = igb_get_ethtool_stats,
.get_coalesce = igb_get_coalesce,
.set_coalesce = igb_set_coalesce,
};
void igb_set_ethtool_ops(struct net_device *netdev)
{
SET_ETHTOOL_OPS(netdev, &igb_ethtool_ops);
}
|
5nefarious/icarous
|
Modules/ACCoRD/inc/PolycarpAcceptablePolygon.h
|
/*
* PolycarpAcceptablePolygon - determining if a 2D polygon is well-formed
*
* Contact: <NAME> (<EMAIL>), <NAME> (<EMAIL>)
*
* Copyright (c) 2015-2017 United States Government as represented by
* the National Aeronautics and Space Administration. No copyright
* is claimed in the United States under Title 17, U.S.Code. All Other
* Rights Reserved.
*/
#ifndef POLYCARPACCEPTABLEPOLYGON_H_
#define POLYCARPACCEPTABLEPOLYGON_H_
#include <vector>
#include "Vect2.h"
namespace larcfm {
class PolycarpAcceptablePolygon {
public:
class EdgeCross {
public:
bool ans;
bool invalid;
EdgeCross(bool b1, bool b2) {
ans = b1;
invalid = b2;
}
};
class CrossAns {
public:
int index;
double num;
double denom;
CrossAns(int a, double b, double c) {
index = a;
num = b;
denom = c;
}
};
static bool near_poly_edge(const std::vector<Vect2>& p,const Vect2& s,double BUFF,int i);
static EdgeCross upshot_crosses_edge(const std::vector<Vect2>& p,const Vect2& s,int i);
static CrossAns compute_intercept(const std::vector<Vect2>& p,const Vect2& s,int i);
static CrossAns min_cross_dist_index(const std::vector<Vect2>& p,const Vect2& s);
static bool corner_lt_3deg(const Vect2& v,const Vect2& w);
static bool acceptable_polygon_2D(const std::vector<Vect2>& p,double BUFF);
static int counterclockwise_corner_index(const std::vector<Vect2>& p,int eps);
static double min_y_val(const std::vector<Vect2>& p);
static Vect2 test_point_below(const std::vector<Vect2>& p,double BUFF);
static bool counterclockwise_edges(const std::vector<Vect2>& p);
static bool segment_near_any_edge(const std::vector<Vect2>& p,double BUFF,const Vect2& segstart, const Vect2& segend);
};
}
#endif
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.