content
stringlengths
0
181M
language
stringclasses
54 values
require 'spec_helper' RSpec.describe('Keep scanning') do include_examples 'scan', /ab\Kcd/, 1 => [:keep, :mark, '\K', 2, 4] include_examples 'scan', /(a\Kb)|(c\\\Kd)ef/, 2 => [:keep, :mark, '\K', 2, 4], 9 => [:keep, :mark, '\K', 11, 13] end
Ruby
# GBQE78 - Rocket Power: Beach Bandits [Core] # Values set here will override the main dolphin settings. [EmuState] # The Emulation State. 1 is worst, 5 is best, 0 is not set. EmulationStateId = 4 EmulationIssues = Slow. [OnLoad] # Add memory patches to be loaded once on boot here. [OnFrame] # Add memory patches to be applied every frame here. [ActionReplay] # Add action replay cheats here.
INI
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Enlight")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyProduct("Enlight")] [assembly: AssemblyCopyright("Copyright © Microsoft 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("360ebc08-80a0-4752-9383-f221a7ca51da")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
C#
`weighted.median` <- function(y, w) { ox <- order(y) y <- y[ox] w <-w[ox] k <- 1 low <- cumsum(c(0,w)) up <- sum(w)-low df <- low-up repeat { if (df[k] < 0) k<-k+1 else if (df[k] == 0) return((w[k]*y[k]+w[k-1]*y[k-1])/(w[k]+w[k-1])) else return(y[k-1]) } }
R
/* Part of JPL -- SWI-Prolog/Java interface Author: Paul Singleton, Fred Dushin and Jan Wielemaker E-mail: paul@jbgb.com WWW: http://www.swi-prolog.org Copyright (c) 2004-2017, Paul Singleton All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. */ :- module(jpl, [ jpl_get_default_jvm_opts/1, jpl_set_default_jvm_opts/1, jpl_get_actual_jvm_opts/1, jpl_pl_lib_version/1, jpl_c_lib_version/1, jpl_pl_syntax/1, jpl_new/3, jpl_call/4, jpl_get/3, jpl_set/3, jpl_servlet_byref/3, jpl_servlet_byval/3, jpl_class_to_classname/2, jpl_class_to_type/2, jpl_classname_to_class/2, jpl_classname_to_type/2, jpl_datum_to_type/2, jpl_false/1, jpl_is_class/1, jpl_is_false/1, jpl_is_null/1, jpl_is_object/1, jpl_is_object_type/1, jpl_is_ref/1, jpl_is_true/1, jpl_is_type/1, jpl_is_void/1, jpl_null/1, jpl_object_to_class/2, jpl_object_to_type/2, jpl_primitive_type/1, jpl_ref_to_type/2, jpl_true/1, jpl_type_to_class/2, jpl_type_to_classname/2, jpl_void/1, jpl_array_to_length/2, jpl_array_to_list/2, jpl_datums_to_array/2, jpl_enumeration_element/2, jpl_enumeration_to_list/2, jpl_hashtable_pair/2, jpl_iterator_element/2, jpl_list_to_array/2, jpl_terms_to_array/2, jpl_array_to_terms/2, jpl_map_element/2, jpl_set_element/2 ]). :- use_module(library(lists)). :- use_module(library(apply)). /** <module> A Java interface for SWI Prolog 7.x The library(jpl) provides a bidirectional interface to a Java Virtual Machine. @see http://jpl7.org/ */ % suppress debugging this library :- set_prolog_flag(generate_debug_info, false). %! jpl_new(+X, +Params, -V) is det. % % X can be: % * an atomic classname, e.g. =|'java.lang.String'|= % * or an atomic descriptor, e.g. =|'[I'|= or =|'Ljava.lang.String;'|= % * or a suitable type, i.e. any class(_,_) or array(_), e.g. class([java,util],['Date']) % % If X is an object (non-array) type or descriptor and Params is a % list of values or references, then V is the result of an invocation % of that type's most specifically-typed constructor to whose % respective formal parameters the actual Params are assignable (and % assigned). % % If X is an array type or descriptor and Params is a list of values % or references, each of which is (independently) assignable to the % array element type, then V is a new array of as many elements as % Params has members, initialised with the respective members of % Params. % % If X is an array type or descriptor and Params is a non-negative % integer N, then V is a new array of that type, with N elements, each % initialised to Java's appropriate default value for the type. % % If V is {Term} then we attempt to convert a new org.jpl7.Term instance to % a corresponding term; this is of little obvious use here, but is % consistent with jpl_call/4 and jpl_get/3. jpl_new(X, Params, V) :- ( var(X) -> throw(error(instantiation_error,context(jpl_new/3,'1st arg must be bound to a classname, descriptor or object type'))) ; jpl_is_type(X) % NB only class(_,_) or array(_) -> Type = X ; atom(X) % e.g. 'java.lang.String', '[L', 'boolean' -> ( jpl_classname_to_type(X, Type) -> true ; throw(error(domain_error(classname,X),context(jpl_new/3,'if 1st arg is an atom, it must be a classname or descriptor'))) ) ; throw(error(type_error(instantiable,X),context(jpl_new/3,'1st arg must be a classname, descriptor or object type'))) ), jpl_new_1(Type, Params, Vx), ( nonvar(V), V = {Term} % yucky way of requesting Term->term conversion -> ( jni_jref_to_term(Vx, TermX) % fails if Rx is not a JRef to a org.jpl7.Term -> Term = TermX ; throw(error(type_error,context(jpl_call/4, 'result is not a org.jpl7.Term instance as required'))) ) ; V = Vx ). %! jpl_new_1(+Tx, +Params, -Vx) % % (serves only jpl_new/3) % % Tx can be a class(_,_) or array(_) type. % % Params must be a proper list of constructor parameters. % % At exit, Vx is bound to a JPL reference to a new, initialised instance of Tx jpl_new_1(class(Ps,Cs), Params, Vx) :- !, % green (see below) Tx = class(Ps,Cs), ( var(Params) -> throw(error(instantiation_error,context(jpl_new/3,'2nd arg must be a proper list of valid parameters for a constructor'))) ; \+ is_list(Params) -> throw(error(type_error(list,Params),context(jpl_new/3,'2nd arg must be a proper list of valid parameters for a constructor'))) ; true ), length(Params, A), % the "arity" of the required constructor jpl_type_to_class(Tx, Cx), % throws Java exception if class is not found N = '<init>', % JNI's constructor naming convention for GetMethodID() Tr = void, % all constructors have this return "type" findall( z3(I,MID,Tfps), jpl_method_spec(Tx, I, N, A, _Mods, MID, Tr, Tfps), % cached Z3s ), ( Z3s == [] % no constructors which require the given qty of parameters? -> jpl_type_to_classname(Tx, Cn), ( jpl_call(Cx, isInterface, [], @(true)) -> throw(error(type_error(concrete_class,Cn),context(jpl_new/3,'cannot create instance of an interface'))) ; throw(error(existence_error(constructor,Cn/A),context(jpl_new/3,'no constructor found with the corresponding quantity of parameters'))) ) ; ( catch( jpl_datums_to_types(Params, Taps), % infer actual parameter types error(type_error(acyclic,Te),context(jpl_datum_to_type/2,Msg)), throw(error(type_error(acyclic,Te),context(jpl_new/3,Msg))) ) -> true ; throw(error(domain_error(list(jpl_datum),Params),context(jpl_new/3,'one or more of the actual parameters is not a valid representation of any Java value or object'))) ), findall( z3(I,MID,Tfps), % select constructors to which actual parameters are assignable ( member(z3(I,MID,Tfps), Z3s), jpl_types_fit_types(Taps, Tfps) % assignability test: actual parameter types "fit" formal parameter types? ), Z3sA ), ( Z3sA == [] % no type-assignable constructors? -> ( Z3s = [_] -> throw(error(existence_error(constructor,Tx/A),context(jpl_new/3,'the actual parameters are not assignable to the formal parameter types of the only constructor which takes this qty of parameters'))) ; throw(error(type_error(constructor_args,Params),context(jpl_new/3,'the actual parameters are not assignable to the formal parameter types of any of the constructors which take this qty of parameters'))) ) ; Z3sA = [z3(I,MID,Tfps)] -> true ; jpl_z3s_to_most_specific_z3(Z3sA, z3(I,MID,Tfps)) -> true ; throw(error(type_error(constructor_params,Params),context(jpl_new/3,'more than one most-specific matching constructor (shouldn''t happen)'))) ) ), catch( jNewObject(Cx, MID, Tfps, Params, Vx), error(java_exception(_), 'java.lang.InstantiationException'), ( jpl_type_to_classname(Tx, Cn), throw(error(type_error(concrete_class,Cn),context(jpl_new/3,'cannot create instance of an abstract class'))) ) ), jpl_cache_type_of_ref(Tx, Vx). % since we know it jpl_new_1(array(T), Params, Vx) :- !, ( var(Params) -> throw(error(instantiation_error,context(jpl_new/3,'when constructing a new array, 2nd arg must either be a non-negative integer (denoting the required array length) or a proper list of valid element values'))) ; integer(Params) % integer I -> array[0..I-1] of default values -> ( Params >= 0 -> Len is Params ; throw(error(domain_error(array_length,Params),context(jpl_new/3,'when constructing a new array, if the 2nd arg is an integer (denoting the required array length) then it must be non-negative'))) ) ; is_list(Params) % [V1,..VN] -> array[0..N-1] of respective values -> length(Params, Len) ), jpl_new_array(T, Len, Vx), % NB may throw out-of-memory exception ( nth0(I, Params, Param), % nmember fails silently when Params is integer jpl_set(Vx, I, Param), fail ; true ), jpl_cache_type_of_ref(array(T), Vx). % since we know it jpl_new_1(T, _Params, _Vx) :- % doomed attempt to create new primitive type instance (formerly a dubious completist feature :-) jpl_primitive_type(T), !, throw(error(domain_error(object_type,T),context(jpl_new/3,'cannot construct an instance of a primitive type'))). % ( var(Params) % -> throw(error(instantiation_error, % context(jpl_new/3, % 'when constructing a new instance of a primitive type, 2nd arg must be bound (to a representation of a suitable value)'))) % ; Params == [] % -> jpl_primitive_type_default_value(T, Vx) % ; Params = [Param] % -> jpl_primitive_type_term_to_value(T, Param, Vx) % ; throw(error(domain_error(constructor_args,Params), % context(jpl_new/3, % 'when constructing a new instance of a primitive type, 2nd arg must either be an empty list (indicating that the default value of that type is required) or a list containing exactly one representation of a suitable value)'))) % ). jpl_new_1(T, _, _) :- throw(error(domain_error(jpl_type,T),context(jpl_new/3,'1st arg must denote a known or plausible type'))). %! jpl_new_array(+ElementType, +Length, -NewArray) is det % % binds NewArray to a jref to a newly created Java array of ElementType and Length jpl_new_array(boolean, Len, A) :- jNewBooleanArray(Len, A). jpl_new_array(byte, Len, A) :- jNewByteArray(Len, A). jpl_new_array(char, Len, A) :- jNewCharArray(Len, A). jpl_new_array(short, Len, A) :- jNewShortArray(Len, A). jpl_new_array(int, Len, A) :- jNewIntArray(Len, A). jpl_new_array(long, Len, A) :- jNewLongArray(Len, A). jpl_new_array(float, Len, A) :- jNewFloatArray(Len, A). jpl_new_array(double, Len, A) :- jNewDoubleArray(Len, A). jpl_new_array(array(T), Len, A) :- jpl_type_to_class(array(T), C), jNewObjectArray(Len, C, @(null), A). % initialise each element to null jpl_new_array(class(Ps,Cs), Len, A) :- jpl_type_to_class(class(Ps,Cs), C), jNewObjectArray(Len, C, @(null), A). %! jpl_call(+X, +MethodName:atom, +Params:list(datum), -Result:datum) is det % % X should be either % * an object reference, e.g. =|<jref>(1552320)|= (for static or instance methods) % * or a classname, e.g. =|'java.util.Date'|= (for static methods only) % * or a descriptor, e.g. =|'Ljava.util.Date;'|= (for static methods only) % * or type, e.g. =|class([java,util],['Date'])|= (for static methods only) % % MethodName should be a method name (as an atom) (may involve dynamic overload resolution based on inferred types of params) % % Params should be a proper list (perhaps empty) of suitable actual parameters for the named method. % % The class or object may have several methods with the given name; % JPL will resolve (per call) to the most appropriate method based on the quantity and inferred types of Params. % This resolution mimics the corresponding static resolution performed by Java compilers. % % Finally, an attempt will be made to unify Result with the method's returned value, % or with =|@(void)|= if it has none. jpl_call(X, Mspec, Params, R) :- ( jpl_object_to_type(X, Type) % the usual case (goal fails safely if X is var or rubbish) -> Obj = X, Kind = instance ; var(X) -> throw(error(instantiation_error,context(jpl_call/4,'1st arg must be bound to an object, classname, descriptor or type'))) ; atom(X) -> ( jpl_classname_to_type(X, Type) % does this attempt to load the class? -> ( jpl_type_to_class(Type, ClassObj) -> Kind = static ; throw(error(existence_error(class,X),context(jpl_call/4,'the named class cannot be found'))) ) ; throw(error(type_error(class_name_or_descriptor,X),context(jpl_call/4,'1st arg must be an object, classname, descriptor or type'))) ) ; X = class(_,_) -> Type = X, jpl_type_to_class(Type, ClassObj), Kind = static ; X = array(_) -> throw(error(type_error(object_or_class,X),context(jpl_call/4,'cannot call a static method of an array type, as none exists'))) ; throw(error(domain_error(object_or_class,X),context(jpl_call/4,'1st arg must be an object, classname, descriptor or type'))) ), ( atom(Mspec) % the usual case, i.e. a method name -> true ; var(Mspec) -> throw(error(instantiation_error,context(jpl_call/4,'2nd arg must be an atom naming a public method of the class or object'))) ; throw(error(type_error(method_name,Mspec),context(jpl_call/4,'2nd arg must be an atom naming a public method of the class or object'))) ), ( is_list(Params) -> ( catch( jpl_datums_to_types(Params, Taps), error(type_error(acyclic,Te),context(jpl_datum_to_type/2,Msg)), throw(error(type_error(acyclic,Te),context(jpl_call/4,Msg))) ) -> true ; throw(error(type_error(method_params,Params),context(jpl_call/4,'not all actual parameters are convertible to Java values or references'))) ), length(Params, A) ; var(Params) -> throw(error(instantiation_error,context(jpl_call/4,'3rd arg must be a proper list of actual parameters for the named method'))) ; throw(error(type_error(method_params,Params),context(jpl_call/4,'3rd arg must be a proper list of actual parameters for the named method'))) ), ( Kind == instance -> jpl_call_instance(Type, Obj, Mspec, Params, Taps, A, Rx) ; jpl_call_static(Type, ClassObj, Mspec, Params, Taps, A, Rx) ), ( nonvar(R), R = {Term} % yucky way of requesting Term->term conversion -> ( jni_jref_to_term(Rx, TermX) % fails if Rx isn't a JRef to a org.jpl7.Term -> Term = TermX ; throw(error(type_error,context(jpl_call/4,'result is not a org.jpl7.Term instance as required'))) ) ; R = Rx ). %! jpl_call_instance(+ObjectType, +Object, +MethodName, +Params, +ActualParamTypes, +Arity, -Result) % % calls the MethodName-d method (instance or static) of Object (which is of ObjectType), % which most specifically applies to Params, % which we have found to be (respectively) of ActualParamTypes, % and of which there are Arity, yielding Result. jpl_call_instance(Type, Obj, Mname, Params, Taps, A, Rx) :- findall( % get remaining details of all accessible methods of Obj's class (as denoted by Type) z5(I,Mods,MID,Tr,Tfps), jpl_method_spec(Type, I, Mname, A, Mods, MID, Tr, Tfps), Z5s ), ( Z5s = [] -> throw(error(existence_error(method,Mname/A),context(jpl_call/4,'the class or object has no public methods with the given name and quantity of parameters'))) ; findall( z5(I,Mods,MID,Tr,Tfps), % those to which Params is assignable ( member(z5(I,Mods,MID,Tr,Tfps), Z5s), jpl_types_fit_types(Taps, Tfps) % assignability test: actual param types "fit" formal param types ), Z5sA % Params-assignable methods ), ( Z5sA == [] -> throw(error(type_error(method_params,Params),context(jpl_call/4,'the actual parameters are not assignable to the formal parameters of any of the named methods'))) ; Z5sA = [z5(I,Mods,MID,Tr,Tfps)] -> true % exactly one applicable method ; jpl_z5s_to_most_specific_z5(Z5sA, z5(I,Mods,MID,Tr,Tfps)) -> true % exactly one most-specific applicable method ; throw(error(existence_error(most_specific_method,Mname/Params),context(jpl_call/4,'more than one most-specific method is found for the actual parameters (this should not happen)'))) ) ), ( member(static, Mods) % if the chosen method is static -> jpl_object_to_class(Obj, ClassObj), % get a java.lang.Class instance which personifies Obj's class jpl_call_static_method(Tr, ClassObj, MID, Tfps, Params, Rx) % call static method w.r.t. associated Class object ; jpl_call_instance_method(Tr, Obj, MID, Tfps, Params, Rx) % else call (non-static) method w.r.t. object itself ). %! jpl_call_static(+ClassType, +ClassObject, +MethodName, +Params, +ActualParamTypes, +Arity, -Result) % % calls the MethodName-d static method of the class (which is of ClassType, % and which is represented by the java.lang.Class instance ClassObject) % which most specifically applies to Params, % which we have found to be (respectively) of ActualParamTypes, % and of which there are Arity, yielding Result. jpl_call_static(Type, ClassObj, Mname, Params, Taps, A, Rx) :- findall( % get all accessible static methods of the class denoted by Type and ClassObj z5(I,Mods,MID,Tr,Tfps), ( jpl_method_spec(Type, I, Mname, A, Mods, MID, Tr, Tfps), member(static, Mods) ), Z5s ), ( Z5s = [] -> throw(error(existence_error(method,Mname/A),context(jpl_call/4,'the class has no public static methods with the given name and quantity of parameters'))) ; findall( z5(I,Mods,MID,Tr,Tfps), ( member(z5(I,Mods,MID,Tr,Tfps), Z5s), jpl_types_fit_types(Taps, Tfps) % assignability test: actual param types "fit" formal param types ), Z5sA % Params-assignable methods ), ( Z5sA == [] -> throw(error(type_error(method_params,Params),context(jpl_call/4,'the actual parameters are not assignable to the formal parameters of any of the named methods'))) ; Z5sA = [z5(I,Mods,MID,Tr,Tfps)] -> true % exactly one applicable method ; jpl_z5s_to_most_specific_z5(Z5sA, z5(I,Mods,MID,Tr,Tfps)) -> true % exactly one most-specific applicable method ; throw(error(existence_error(most_specific_method,Mname/Params),context(jpl_call/4,'more than one most-specific method is found for the actual parameters (this should not happen)'))) ) ), jpl_call_static_method(Tr, ClassObj, MID, Tfps, Params, Rx). %! jpl_call_instance_method(+Type, +ClassObject, +MethodID, +FormalParamTypes, +Params, -Result) jpl_call_instance_method(void, Class, MID, Tfps, Ps, R) :- jCallVoidMethod(Class, MID, Tfps, Ps), jpl_void(R). jpl_call_instance_method(boolean, Class, MID, Tfps, Ps, R) :- jCallBooleanMethod(Class, MID, Tfps, Ps, R). jpl_call_instance_method(byte, Class, MID, Tfps, Ps, R) :- jCallByteMethod(Class, MID, Tfps, Ps, R). jpl_call_instance_method(char, Class, MID, Tfps, Ps, R) :- jCallCharMethod(Class, MID, Tfps, Ps, R). jpl_call_instance_method(short, Class, MID, Tfps, Ps, R) :- jCallShortMethod(Class, MID, Tfps, Ps, R). jpl_call_instance_method(int, Class, MID, Tfps, Ps, R) :- jCallIntMethod(Class, MID, Tfps, Ps, R). jpl_call_instance_method(long, Class, MID, Tfps, Ps, R) :- jCallLongMethod(Class, MID, Tfps, Ps, R). jpl_call_instance_method(float, Class, MID, Tfps, Ps, R) :- jCallFloatMethod(Class, MID, Tfps, Ps, R). jpl_call_instance_method(double, Class, MID, Tfps, Ps, R) :- jCallDoubleMethod(Class, MID, Tfps, Ps, R). jpl_call_instance_method(array(_), Class, MID, Tfps, Ps, R) :- jCallObjectMethod(Class, MID, Tfps, Ps, R). jpl_call_instance_method(class(_,_), Class, MID, Tfps, Ps, R) :- jCallObjectMethod(Class, MID, Tfps, Ps, R). %! jpl_call_static_method(+Type, +ClassObject, +MethodID, +FormalParamTypes, +Params, -Result) jpl_call_static_method(void, Class, MID, Tfps, Ps, R) :- jCallStaticVoidMethod(Class, MID, Tfps, Ps), jpl_void(R). jpl_call_static_method(boolean, Class, MID, Tfps, Ps, R) :- jCallStaticBooleanMethod(Class, MID, Tfps, Ps, R). jpl_call_static_method(byte, Class, MID, Tfps, Ps, R) :- jCallStaticByteMethod(Class, MID, Tfps, Ps, R). jpl_call_static_method(char, Class, MID, Tfps, Ps, R) :- jCallStaticCharMethod(Class, MID, Tfps, Ps, R). jpl_call_static_method(short, Class, MID, Tfps, Ps, R) :- jCallStaticShortMethod(Class, MID, Tfps, Ps, R). jpl_call_static_method(int, Class, MID, Tfps, Ps, R) :- jCallStaticIntMethod(Class, MID, Tfps, Ps, R). jpl_call_static_method(long, Class, MID, Tfps, Ps, R) :- jCallStaticLongMethod(Class, MID, Tfps, Ps, R). jpl_call_static_method(float, Class, MID, Tfps, Ps, R) :- jCallStaticFloatMethod(Class, MID, Tfps, Ps, R). jpl_call_static_method(double, Class, MID, Tfps, Ps, R) :- jCallStaticDoubleMethod(Class, MID, Tfps, Ps, R). jpl_call_static_method(array(_), Class, MID, Tfps, Ps, R) :- jCallStaticObjectMethod(Class, MID, Tfps, Ps, R). jpl_call_static_method(class(_,_), Class, MID, Tfps, Ps, R) :- jCallStaticObjectMethod(Class, MID, Tfps, Ps, R). %! jpl_get(+X, +Fspec, -V:datum) is det % % X can be % % * a classname % * or a descriptor % * or an (object or array) type (for static fields) % * or a non-array object (for static and non-static fields) % * or an array (for 'length' pseudo field, or indexed element retrieval) % % Fspec can be % % * an atomic field name % * or an integral array index (to get an element from an array) % * or a pair I-J of integers (to get a subrange of an array). % % Finally, an attempt will be made to unify V with the retrieved value or object reference. % % Examples % % == % jpl_get('java.awt.Cursor', 'NE_RESIZE_CURSOR', Q). % Q = 7. % % jpl_new(array(class([java,lang],['String'])), [for,while,do,if,then,else,try,catch,finally], A), % jpl_get(A, 3-5, B). % B = [if, then, else]. % == jpl_get(X, Fspec, V) :- ( jpl_object_to_type(X, Type) -> Obj = X, jpl_get_instance(Type, Type, Obj, Fspec, Vx) % pass Type twice for FAI ; var(X) -> throw(error(instantiation_error,context(jpl_get/3,'1st arg must be bound to an object, classname, descriptor or type'))) ; jpl_is_type(X) % e.g. class([java,lang],['String']), array(int) -> Type = X, ( jpl_type_to_class(Type, ClassObj) -> jpl_get_static(Type, ClassObj, Fspec, Vx) ; jpl_type_to_classname(Type, Classname), throw(error(existence_error(class,Classname),context(jpl_get/3,'the named class cannot be found'))) ) ; atom(X) -> ( jpl_classname_to_type(X, Type) % does this attempt to load the class? -> ( jpl_type_to_class(Type, ClassObj) -> jpl_get_static(Type, ClassObj, Fspec, Vx) ; throw(error(existence_error(class,X),context(jpl_get/3,'the named class cannot be found'))) ) ; throw(error(type_error(class_name_or_descriptor,X),context(jpl_get/3, '1st arg must be an object, classname, descriptor or type'))) ) ; throw(error(domain_error(object_or_class,X),context(jpl_get/3,'1st arg must be bound to an object, classname, descriptor or type'))) ), ( nonvar(V), V = {Term} % yucky way of requesting Term->term conversion -> ( jni_jref_to_term(Vx, TermX) % fails if Rx is not a JRef to a org.jpl7.Term -> Term = TermX ; throw(error(type_error,context(jpl_call/4,'result is not a org.jpl7.Term instance as required'))) ) ; V = Vx ). %! jpl_get_static(+Type:type, +ClassObject:jref, +FieldName:atom, -Value:datum) is det % % ClassObject is an instance of java.lang.Class which represents % the same class as Type; Value (Vx below) is guaranteed unbound % on entry, and will, before exit, be unified with the retrieved % value jpl_get_static(Type, ClassObj, Fname, Vx) :- ( atom(Fname) % assume it's a field name -> true ; var(Fname) -> throw(error(instantiation_error,context(jpl_get/3,'2nd arg must be bound to an atom naming a public field of the class'))) ; throw(error(type_error(field_name,Fname),context(jpl_get/3,'2nd arg must be an atom naming a public field of the class'))) ), % get static fields of the denoted class findall( z4(I,Mods,FID,Tf), ( jpl_field_spec(Type, I, Fname, Mods, FID, Tf), member(static, Mods) ), Z4s ), ( Z4s = [] -> throw(error(existence_error(field,Fname),context(jpl_get/3,'the class or object has no public static field with the given name'))) ; Z4s = [z4(I,_Mods,FID,Tf)] -> jpl_get_static_field(Tf, ClassObj, FID, Vx) ; throw(error(existence_error(unique_field,Fname),context(jpl_get/3,'more than one field is found with the given name'))) ). %! jpl_get_instance(+Type, +Type, +Object, +FieldSpecifier, -Value) is det jpl_get_instance(class(_,_), Type, Obj, Fname, Vx) :- ( atom(Fname) % the usual case -> true ; var(Fname) -> throw(error(instantiation_error,context(jpl_get/3,'2nd arg must be bound to an atom naming a public field of the class or object'))) ; throw(error(type_error(field_name,Fname),context(jpl_get/3,'2nd arg must be an atom naming a public field of the class or object'))) ), findall( z4(I,Mods,FID,Tf), jpl_field_spec(Type, I, Fname, Mods, FID, Tf), Z4s ), ( Z4s = [] -> throw(error(existence_error(field,Fname),context(jpl_get/3,'the class or object has no public field with the given name'))) ; Z4s = [z4(I,Mods,FID,Tf)] -> ( member(static, Mods) -> jpl_object_to_class(Obj, ClassObj), jpl_get_static_field(Tf, ClassObj, FID, Vx) ; jpl_get_instance_field(Tf, Obj, FID, Vx) ) ; throw(error(existence_error(unique_field,Fname),context(jpl_get/3,'more than one field is found with the given name'))) ). jpl_get_instance(array(ElementType), _, Array, Fspec, Vx) :- ( var(Fspec) -> throw(error(instantiation_error,context(jpl_get/3,'when 1st arg is an array, 2nd arg must be bound to an index, an index range, or ''length'''))) ; integer(Fspec) -> ( Fspec < 0 % lo bound check -> throw(error(domain_error(array_index,Fspec),context(jpl_get/3,'when 1st arg is an array, integral 2nd arg must be non-negative'))) ; jGetArrayLength(Array, Len), Fspec >= Len % hi bound check -> throw(error(domain_error(array_index,Fspec),context(jpl_get/3,'when 1st arg is an array, integral 2nd arg must not exceed upper bound of array'))) ; jpl_get_array_element(ElementType, Array, Fspec, Vx) ) ; Fspec = N-M % NB should we support e.g. 3-2 -> [] ? -> ( integer(N), integer(M) -> ( N >= 0, M >= N -> jGetArrayLength(Array, Len), ( N >= Len -> throw(error(domain_error(array_index_range,N-M),context(jpl_get/3,'lower bound of array index range must not exceed upper bound of array'))) ; M >= Len -> throw(error(domain_error(array_index_range,N-M),context(jpl_get/3,'upper bound of array index range must not exceed upper bound of array'))) ; jpl_get_array_elements(ElementType, Array, N, M, Vx) ) ; throw(error(domain_error(array_index_range,N-M),context(jpl_get/3,'array index range must be a non-decreasing pair of non-negative integers'))) ) ; throw(error(type_error(array_index_range,N-M),context(jpl_get/3,'array index range must be a non-decreasing pair of non-negative integers'))) ) ; atom(Fspec) -> ( Fspec == length % special-case for this solitary array "method" -> jGetArrayLength(Array, Vx) ; throw(error(domain_error(array_field_name,Fspec),context(jpl_get/3,'the array has no public field with the given name'))) ) ; throw(error(type_error(array_lookup_spec,Fspec),context(jpl_get/3,'when 1st arg is an array, 2nd arg must be an index, an index range, or ''length'''))) ). %! jpl_get_array_element(+ElementType:type, +Array:jref, +Index, -Vc) is det % % Array is a JPL reference to a Java array of ElementType; Vc is % (unified with a JPL repn of) its Index-th (numbered from 0) % element Java values are now converted to Prolog terms within % foreign code % % @tbd more of this could be done within foreign code jpl_get_array_element(Type, Array, Index, Vc) :- ( ( Type = class(_,_) ; Type = array(_) ) -> jGetObjectArrayElement(Array, Index, Vr) ; jpl_primitive_type(Type) -> jni_type_to_xput_code(Type, Xc), jni_alloc_buffer(Xc, 1, Bp), % one-element buf for a Type jpl_get_primitive_array_region(Type, Array, Index, 1, Bp), jni_fetch_buffer_value(Bp, 0, Vr, Xc), % zero-th element jni_free_buffer(Bp) ), Vr = Vc. % redundant since Vc is always (?) unbound at call %! jpl_get_array_elements(+ElementType, +Array, +N, +M, -Vs) % % serves only jpl_get_instance/5 % % Vs will always be unbound on entry jpl_get_array_elements(ElementType, Array, N, M, Vs) :- ( ( ElementType = class(_,_) ; ElementType = array(_) ) -> jpl_get_object_array_elements(Array, N, M, Vs) ; jpl_get_primitive_array_elements(ElementType, Array, N, M, Vs) ). jpl_get_instance_field(boolean, Obj, FieldID, V) :- jGetBooleanField(Obj, FieldID, V). jpl_get_instance_field(byte, Obj, FieldID, V) :- jGetByteField(Obj, FieldID, V). jpl_get_instance_field(char, Obj, FieldID, V) :- jGetCharField(Obj, FieldID, V). jpl_get_instance_field(short, Obj, FieldID, V) :- jGetShortField(Obj, FieldID, V). jpl_get_instance_field(int, Obj, FieldID, V) :- jGetIntField(Obj, FieldID, V). jpl_get_instance_field(long, Obj, FieldID, V) :- jGetLongField(Obj, FieldID, V). jpl_get_instance_field(float, Obj, FieldID, V) :- jGetFloatField(Obj, FieldID, V). jpl_get_instance_field(double, Obj, FieldID, V) :- jGetDoubleField(Obj, FieldID, V). jpl_get_instance_field(class(_,_), Obj, FieldID, V) :- jGetObjectField(Obj, FieldID, V). jpl_get_instance_field(array(_), Obj, FieldID, V) :- jGetObjectField(Obj, FieldID, V). %! jpl_get_object_array_elements(+Array, +LoIndex, +HiIndex, -Vcs) is det % % Array should be a (zero-based) array of some object (array or non-array) type; LoIndex is an integer, 0 =< LoIndex < % length(Array); HiIndex is an integer, LoIndex-1 =< HiIndex < % length(Array); at call, Vcs will be unbound; at exit, Vcs will % be a list of (references to) the array's elements % [LoIndex..HiIndex] inclusive jpl_get_object_array_elements(Array, Lo, Hi, Vcs) :- ( Lo =< Hi -> Vcs = [Vc|Vcs2], jGetObjectArrayElement(Array, Lo, Vc), Next is Lo+1, jpl_get_object_array_elements(Array, Next, Hi, Vcs2) ; Vcs = [] ). %! jpl_get_primitive_array_elements(+ElementType, +Array, +LoIndex, +HiIndex, -Vcs) is det. % % Array should be a (zero-based) Java array of (primitive) % ElementType; Vcs should be unbound on entry, and on exit will be % a list of (JPL representations of the values of) the elements % [LoIndex..HiIndex] inclusive jpl_get_primitive_array_elements(ElementType, Array, Lo, Hi, Vcs) :- Size is Hi-Lo+1, ( Size == 0 -> Vcs = [] ; jni_type_to_xput_code(ElementType, Xc), jni_alloc_buffer(Xc, Size, Bp), jpl_get_primitive_array_region(ElementType, Array, Lo, Size, Bp), jpl_primitive_buffer_to_array(ElementType, Xc, Bp, 0, Size, Vcs), jni_free_buffer(Bp) ). jpl_get_primitive_array_region(boolean, Array, Lo, S, I) :- jGetBooleanArrayRegion(Array, Lo, S, jbuf(I,boolean)). jpl_get_primitive_array_region(byte, Array, Lo, S, I) :- jGetByteArrayRegion(Array, Lo, S, jbuf(I,byte)). jpl_get_primitive_array_region(char, Array, Lo, S, I) :- jGetCharArrayRegion(Array, Lo, S, jbuf(I,char)). jpl_get_primitive_array_region(short, Array, Lo, S, I) :- jGetShortArrayRegion(Array, Lo, S, jbuf(I,short)). jpl_get_primitive_array_region(int, Array, Lo, S, I) :- jGetIntArrayRegion(Array, Lo, S, jbuf(I,int)). jpl_get_primitive_array_region(long, Array, Lo, S, I) :- jGetLongArrayRegion(Array, Lo, S, jbuf(I,long)). jpl_get_primitive_array_region(float, Array, Lo, S, I) :- jGetFloatArrayRegion(Array, Lo, S, jbuf(I,float)). jpl_get_primitive_array_region(double, Array, Lo, S, I) :- jGetDoubleArrayRegion(Array, Lo, S, jbuf(I,double)). jpl_get_static_field(boolean, Array, FieldID, V) :- jGetStaticBooleanField(Array, FieldID, V). jpl_get_static_field(byte, Array, FieldID, V) :- jGetStaticByteField(Array, FieldID, V). jpl_get_static_field(char, Array, FieldID, V) :- jGetStaticCharField(Array, FieldID, V). jpl_get_static_field(short, Array, FieldID, V) :- jGetStaticShortField(Array, FieldID, V). jpl_get_static_field(int, Array, FieldID, V) :- jGetStaticIntField(Array, FieldID, V). jpl_get_static_field(long, Array, FieldID, V) :- jGetStaticLongField(Array, FieldID, V). jpl_get_static_field(float, Array, FieldID, V) :- jGetStaticFloatField(Array, FieldID, V). jpl_get_static_field(double, Array, FieldID, V) :- jGetStaticDoubleField(Array, FieldID, V). jpl_get_static_field(class(_,_), Array, FieldID, V) :- jGetStaticObjectField(Array, FieldID, V). jpl_get_static_field(array(_), Array, FieldID, V) :- jGetStaticObjectField(Array, FieldID, V). %! jpl_set(+X, +Fspec, +V) is det. % % sets the Fspec-th field of (class or object) X to value V iff it is assignable % % X can be % * a class instance (for static or non-static fields) % * or an array (for indexed element or subrange assignment) % * or a classname, or a class(_,_) or array(_) type (for static fields) % * but not a String (no fields to retrieve) % % Fspec can be % * an atomic field name (overloading through shadowing has yet to be handled properly) % * or an array index I (X must be an array object: V is assigned to X[I]) % * or a pair I-J of integers (X must be an array object, V must be a list of values: successive members of V are assigned to X[I..J]) % % V must be a suitable value or object. jpl_set(X, Fspec, V) :- ( jpl_object_to_type(X, Type) % the usual case (test is safe if X is var or rubbish) -> Obj = X, catch( jpl_set_instance(Type, Type, Obj, Fspec, V), % first 'Type' is for FAI error(type_error(acyclic,Te),context(jpl_datum_to_type/2,Msg)), throw(error(type_error(acyclic,Te),context(jpl_set/3,Msg))) ) ; var(X) -> throw(error(instantiation_error,context(jpl_set/3,'1st arg must be an object, classname, descriptor or type'))) ; ( atom(X) -> ( jpl_classname_to_type(X, Type) % it's a classname or descriptor... -> true ; throw(error(existence_error(class,X),context(jpl_set/3,'the named class cannot be found'))) ) ; ( X = class(_,_) % it's a class type... ; X = array(_) % ...or an array type ) -> Type = X ), ( jpl_type_to_class(Type, ClassObj) % ...whose Class object is available -> true ; jpl_type_to_classname(Type, Classname), throw(error(existence_error(class,Classname),context(jpl_set/3,'the class cannot be found'))) ) -> catch( jpl_set_static(Type, ClassObj, Fspec, V), error(type_error(acyclic,Te),context(jpl_datum_to_type/2,Msg)), throw(error(type_error(acyclic,Te),context(jpl_set/3,Msg))) ) ; throw(error(domain_error(object_or_class,X),context(jpl_set/3,'1st arg must be an object, classname, descriptor or type'))) ). %! jpl_set_instance(+Type, +Type, +ObjectReference, +FieldName, +Value) is det. % % ObjectReference is a JPL reference to a Java object % of the class denoted by Type (which is passed twice for first agument indexing); % % FieldName should name a public, non-final (static or non-static) field of this object, % but could be anything, and is validated here; % % Value should be assignable to the named field, but could be anything, and is validated here jpl_set_instance(class(_,_), Type, Obj, Fname, V) :- % a non-array object ( atom(Fname) % the usual case -> true ; var(Fname) -> throw(error(instantiation_error,context(jpl_set/3,'2nd arg must be bound to the name of a public, non-final field'))) ; throw(error(type_error(field_name,Fname),context(jpl_set/3,'2nd arg must be the name of a public, non-final field'))) ), findall( z4(I,Mods,FID,Tf), jpl_field_spec(Type, I, Fname, Mods, FID, Tf), % public fields of class denoted by Type Z4s ), ( Z4s = [] -> throw(error(existence_error(field,Fname),context(jpl_set/3,'no public fields of the object have this name'))) ; Z4s = [z4(I,Mods,FID,Tf)] -> ( member(final, Mods) -> throw(error(permission_error(modify,final_field,Fname),context(jpl_set/3,'cannot assign a value to a final field (actually you could but I''ve decided not to let you)'))) ; jpl_datum_to_type(V, Tv) -> ( jpl_type_fits_type(Tv, Tf) -> ( member(static, Mods) -> jpl_object_to_class(Obj, ClassObj), jpl_set_static_field(Tf, ClassObj, FID, V) ; jpl_set_instance_field(Tf, Obj, FID, V) % oughta be jpl_set_instance_field? ) ; jpl_type_to_nicename(Tf, NNf), throw(error(type_error(NNf,V),context(jpl_set/3,'the value is not assignable to the named field of the class'))) ) ; throw(error(type_error(field_value,V),context(jpl_set/3,'3rd arg does not represent any Java value or object'))) ) ; throw(error(existence_error(field,Fname),context(jpl_set/3,'more than one public field of the object has this name (this should not happen)'))) % 'existence'? or some other sort of error maybe? ). jpl_set_instance(array(Type), _, Obj, Fspec, V) :- ( is_list(V) % a list of array element values -> Vs = V ; var(V) -> throw(error(instantiation_error,context(jpl_set/3, 'when 1st arg is an array, 3rd arg must be bound to a suitable element value or list of values'))) ; Vs = [V] % a single array element value ), length(Vs, Iv), ( var(Fspec) -> throw(error(instantiation_error,context(jpl_set/3,'when 1st arg is an array, 2nd arg must be bound to an index or index range'))) ; integer(Fspec) % single-element assignment -> ( Fspec < 0 -> throw(error(domain_error(array_index,Fspec),context(jpl_set/3,'when 1st arg is an array, an integral 2nd arg must be a non-negative index'))) ; Iv is 1 -> N is Fspec ; Iv is 0 -> throw(error(domain_error(array_element(Fspec),Vs),context(jpl_set/3,'no values for array element assignment: needs one'))) ; throw(error(domain_error(array_element(Fspec),Vs),context(jpl_set/3,'too many values for array element assignment: needs one'))) ) ; Fspec = N-M % element-sequence assignment -> ( integer(N), integer(M) -> ( N >= 0, Size is (M-N)+1, Size >= 0 -> ( Size == Iv -> true ; Size < Iv -> throw(error(domain_error(array_elements(N-M),Vs),context(jpl_set/3,'too few values for array range assignment'))) ; throw(error(domain_error(array_elements(N-M),Vs),context(jpl_set/3,'too many values for array range assignment'))) ) ; throw(error(domain_error(array_index_range,N-M),context(jpl_set/3,'array index range must be a non-decreasing pair of non-negative integers'))) ) ; throw(error(type_error(array_index_range,N-M),context(jpl_set/3,'array index range must be a non-decreasing pair of non-negative integers'))) ) ; atom(Fspec) -> ( Fspec == length -> throw(error(permission_error(modify,final_field,length),context(jpl_set/3,'cannot assign a value to a final field'))) ; throw(error(existence_error(field,Fspec),context(jpl_set/3,'array has no field with that name'))) ) ; throw(error(domain_error(array_index,Fspec),context(jpl_set/3,'when 1st arg is an array object, 2nd arg must be a non-negative index or index range'))) ), jpl_set_array(Type, Obj, N, Iv, Vs). %! jpl_set_static(+Type, +ClassObj, +FieldName, +Value) is det. % % We can rely on: % * Type being a class/2 type representing some accessible class % * ClassObj being an instance of java.lang.Class which represents the same class as Type % % but FieldName could be anything, so we validate it here, % look for a suitable (static) field of the target class, % then call jpl_set_static_field/4 to attempt to assign Value (which could be anything) to it % % NB this does not yet handle shadowed fields correctly. jpl_set_static(Type, ClassObj, Fname, V) :- ( atom(Fname) % the usual case -> true ; var(Fname) -> throw(error(instantiation_error,context(jpl_set/3,'when 1st arg denotes a class, 2nd arg must be bound to the name of a public, static, non-final field'))) ; throw(error(type_error(field_name,Fname),context(jpl_set/3,'when 1st arg denotes a class, 2nd arg must be the name of a public, static, non-final field'))) ), findall( % get all static fields of the denoted class z4(I,Mods,FID,Tf), ( jpl_field_spec(Type, I, Fname, Mods, FID, Tf), member(static, Mods) ), Z4s ), ( Z4s = [] -> throw(error(existence_error(field,Fname),context(jpl_set/3,'class has no public static fields of this name'))) ; Z4s = [z4(I,Mods,FID,Tf)] % exactly one synonymous field? -> ( member(final, Mods) -> throw(error(permission_error(modify,final_field,Fname),context(jpl_set/3,'cannot assign a value to a final field'))) ; jpl_datum_to_type(V, Tv) -> ( jpl_type_fits_type(Tv, Tf) -> jpl_set_static_field(Tf, ClassObj, FID, V) ; jpl_type_to_nicename(Tf, NNf), throw(error(type_error(NNf,V),context(jpl_set/3,'the value is not assignable to the named field of the class'))) ) ; throw(error(type_error(field_value,V),context(jpl_set/3,'3rd arg does not represent any Java value or object'))) ) ; throw(error(existence_error(field,Fname),context(jpl_set/3,'more than one public static field of the class has this name (this should not happen)(?)'))) ). %! jpl_set_array(+ElementType, +Array, +Offset, +DatumQty, +Datums) is det. % % Datums, of which there are DatumQty, are stashed in successive % elements of Array which is an array of ElementType starting at % the Offset-th (numbered from 0) % throws error(type_error(acyclic,_),context(jpl_datum_to_type/2,_)) jpl_set_array(T, A, N, I, Ds) :- ( jpl_datums_to_types(Ds, Tds) % most specialised types of given values -> ( jpl_types_fit_type(Tds, T) % all assignable to element type? -> true ; throw(error(type_error(array(T),Ds),context(jpl_set/3,'not all values are assignable to the array element type'))) ) ; throw(error(type_error(array(T),Ds),context(jpl_set/3,'not all values are convertible to Java values or references'))) ), ( ( T = class(_,_) ; T = array(_) % array elements are objects ) -> ( nth0(J, Ds, D), % for each datum Nd is N+J, % compute array index ( D = {Tq} % quoted term? -> jni_term_to_jref(Tq, D2) % convert to a JPL reference to a corresponding org.jpl7.Term object ; D = D2 ), jSetObjectArrayElement(A, Nd, D2), fail % iterate ; true ) ; jpl_primitive_type(T) % array elements are primitive values -> jni_type_to_xput_code(T, Xc), jni_alloc_buffer(Xc, I, Bp), % I-element buf of required primitive type jpl_set_array_1(Ds, T, 0, Bp), jpl_set_elements(T, A, N, I, Bp), jni_free_buffer(Bp) ; throw(error(system_error(array_element_type,T),context(jpl_set/3,'array element type is unknown (this should not happen)'))) ). %! jpl_set_array_1(+Values, +Type, +BufferIndex, +BufferPointer) is det. % % successive members of Values are stashed as (primitive) Type % from the BufferIndex-th element (numbered from 0) onwards of the % buffer indicated by BufferPointer % % NB this could be done more efficiently (?) within foreign code... jpl_set_array_1([], _, _, _). jpl_set_array_1([V|Vs], Tprim, Ib, Bp) :- jni_type_to_xput_code(Tprim, Xc), jni_stash_buffer_value(Bp, Ib, V, Xc), Ibnext is Ib+1, jpl_set_array_1(Vs, Tprim, Ibnext, Bp). jpl_set_elements(boolean, Obj, N, I, Bp) :- jSetBooleanArrayRegion(Obj, N, I, jbuf(Bp,boolean)). jpl_set_elements(char, Obj, N, I, Bp) :- jSetCharArrayRegion(Obj, N, I, jbuf(Bp,char)). jpl_set_elements(byte, Obj, N, I, Bp) :- jSetByteArrayRegion(Obj, N, I, jbuf(Bp,byte)). jpl_set_elements(short, Obj, N, I, Bp) :- jSetShortArrayRegion(Obj, N, I, jbuf(Bp,short)). jpl_set_elements(int, Obj, N, I, Bp) :- jSetIntArrayRegion(Obj, N, I, jbuf(Bp,int)). jpl_set_elements(long, Obj, N, I, Bp) :- jSetLongArrayRegion(Obj, N, I, jbuf(Bp,long)). jpl_set_elements(float, Obj, N, I, Bp) :- jSetFloatArrayRegion(Obj, N, I, jbuf(Bp,float)). jpl_set_elements(double, Obj, N, I, Bp) :- jSetDoubleArrayRegion(Obj, N, I, jbuf(Bp,double)). %! jpl_set_instance_field(+Type, +Obj, +FieldID, +V) is det. % % We can rely on Type, Obj and FieldID being valid, and on V being % assignable (if V is a quoted term then it is converted here) jpl_set_instance_field(boolean, Obj, FieldID, V) :- jSetBooleanField(Obj, FieldID, V). jpl_set_instance_field(byte, Obj, FieldID, V) :- jSetByteField(Obj, FieldID, V). jpl_set_instance_field(char, Obj, FieldID, V) :- jSetCharField(Obj, FieldID, V). jpl_set_instance_field(short, Obj, FieldID, V) :- jSetShortField(Obj, FieldID, V). jpl_set_instance_field(int, Obj, FieldID, V) :- jSetIntField(Obj, FieldID, V). jpl_set_instance_field(long, Obj, FieldID, V) :- jSetLongField(Obj, FieldID, V). jpl_set_instance_field(float, Obj, FieldID, V) :- jSetFloatField(Obj, FieldID, V). jpl_set_instance_field(double, Obj, FieldID, V) :- jSetDoubleField(Obj, FieldID, V). jpl_set_instance_field(class(_,_), Obj, FieldID, V) :- % also handles byval term assignments ( V = {T} % quoted term? -> jni_term_to_jref(T, V2) % convert to a JPL reference to a corresponding org.jpl7.Term object ; V = V2 ), jSetObjectField(Obj, FieldID, V2). jpl_set_instance_field(array(_), Obj, FieldID, V) :- jSetObjectField(Obj, FieldID, V). %! jpl_set_static_field(+Type, +ClassObj, +FieldID, +V) % % We can rely on Type, ClassObj and FieldID being valid, % and on V being assignable (if V is a quoted term then it is converted here). jpl_set_static_field(boolean, Obj, FieldID, V) :- jSetStaticBooleanField(Obj, FieldID, V). jpl_set_static_field(byte, Obj, FieldID, V) :- jSetStaticByteField(Obj, FieldID, V). jpl_set_static_field(char, Obj, FieldID, V) :- jSetStaticCharField(Obj, FieldID, V). jpl_set_static_field(short, Obj, FieldID, V) :- jSetStaticShortField(Obj, FieldID, V). jpl_set_static_field(int, Obj, FieldID, V) :- jSetStaticIntField(Obj, FieldID, V). jpl_set_static_field(long, Obj, FieldID, V) :- jSetStaticLongField(Obj, FieldID, V). jpl_set_static_field(float, Obj, FieldID, V) :- jSetStaticFloatField(Obj, FieldID, V). jpl_set_static_field(double, Obj, FieldID, V) :- jSetStaticDoubleField(Obj, FieldID, V). jpl_set_static_field(class(_,_), Obj, FieldID, V) :- % also handles byval term assignments ( V = {T} % quoted term? -> jni_term_to_jref(T, V2) % convert to a JPL reference to a corresponding org.jpl7.Term object ; V = V2 ), jSetStaticObjectField(Obj, FieldID, V2). jpl_set_static_field(array(_), Obj, FieldID, V) :- jSetStaticObjectField(Obj, FieldID, V). %! jpl_get_default_jvm_opts(-Opts:list(atom)) is det % % Returns (as a list of atoms) the options which will be passed to the JVM when it is initialised, % e.g. =|['-Xrs']|= jpl_get_default_jvm_opts(Opts) :- jni_get_default_jvm_opts(Opts). %! jpl_set_default_jvm_opts(+Opts:list(atom)) is det % % Replaces the default JVM initialisation options with those supplied. jpl_set_default_jvm_opts(Opts) :- is_list(Opts), length(Opts, N), jni_set_default_jvm_opts(N, Opts). %! jpl_get_actual_jvm_opts(-Opts:list(atom)) is semidet % % Returns (as a list of atoms) the options with which the JVM was initialised. % % Fails silently if a JVM has not yet been started, and can thus be used to test for this. jpl_get_actual_jvm_opts(Opts) :- jni_get_actual_jvm_opts(Opts). jpl_assert(Fact) :- ( jpl_assert_policy(Fact, yes) -> assert(Fact) ; true ). jpl_assert_policy(jpl_field_spec_cache(_,_,_,_,_,_), yes). jpl_assert_policy(jpl_method_spec_cache(_,_,_,_,_,_,_,_), yes). jpl_assert_policy(jpl_class_tag_type_cache(_,_), yes). jpl_assert_policy(jpl_classname_type_cache(_,_), yes). jpl_assert_policy(jpl_iref_type_cache(_,_), no). % must correspond to JPL_CACHE_TYPE_OF_REF in jpl.c jpl_assert_policy(jpl_field_spec_is_cached(_), YN) :- jpl_assert_policy(jpl_field_spec_cache(_,_,_,_,_,_), YN). jpl_assert_policy(jpl_method_spec_is_cached(_), YN) :- jpl_assert_policy(jpl_method_spec_cache(_,_,_,_,_,_,_,_), YN). %! jpl_tidy_iref_type_cache(+Iref) is det. % % Delete the cached type info, if any, under Iref. % % Called from jpl.c's jni_free_iref() via jni_tidy_iref_type_cache() jpl_tidy_iref_type_cache(Iref) :- % write('[decaching types for iref='), write(Iref), write(']'), nl, retractall(jpl_iref_type_cache(Iref,_)), true. jpl_fergus_find_candidate([], Candidate, Candidate, []). jpl_fergus_find_candidate([X|Xs], Candidate0, Candidate, Rest) :- ( jpl_fergus_greater(X, Candidate0) -> Candidate1 = X, Rest = [Candidate0|Rest1] ; Candidate1 = Candidate0, Rest = [X|Rest1] ), jpl_fergus_find_candidate(Xs, Candidate1, Candidate, Rest1). jpl_fergus_greater(z5(_,_,_,_,Tps1), z5(_,_,_,_,Tps2)) :- jpl_types_fit_types(Tps1, Tps2). jpl_fergus_greater(z3(_,_,Tps1), z3(_,_,Tps2)) :- jpl_types_fit_types(Tps1, Tps2). %! jpl_fergus_is_the_greatest(+Xs:list(T), -GreatestX:T) % % Xs is a list of things for which jpl_fergus_greater/2 defines a % partial ordering; GreatestX is one of those, than which none is % greater; fails if there is more than one such; this algorithm % was contributed to c.l.p by Fergus Henderson in response to my % "there must be a better way" challenge: there was, this is it jpl_fergus_is_the_greatest([X|Xs], Greatest) :- jpl_fergus_find_candidate(Xs, X, Greatest, Rest), forall( member(R, Rest), jpl_fergus_greater(Greatest, R) ). %! jpl_z3s_to_most_specific_z3(+Zs, -Z) % % Zs is a list of arity-matching, type-suitable z3(I,MID,Tfps). % % Z is the single most specific element of Zs, % i.e. that than which no other z3/3 has a more specialised signature (fails if there is more than one such). jpl_z3s_to_most_specific_z3(Zs, Z) :- jpl_fergus_is_the_greatest(Zs, Z). %! jpl_z5s_to_most_specific_z5(+Zs, -Z) % % Zs is a list of arity-matching, type-suitable z5(I,Mods,MID,Tr,Tfps) % % Z is the single most specific element of Zs, % i.e. that than which no other z5/5 has a more specialised signature (fails if there is more than one such) jpl_z5s_to_most_specific_z5(Zs, Z) :- jpl_fergus_is_the_greatest(Zs, Z). %! jpl_pl_lib_version(-Version) % % Version is the fully qualified version identifier of the in-use Prolog component (jpl.pl) of JPL. % % It should exactly match the version identifiers of JPL's C (jpl.c) and Java (jpl.jar) components. % % Example % % == % ?- jpl_pl_lib_version(V). % V = '7.4.0-alpha'. % == jpl_pl_lib_version(VersionString) :- jpl_pl_lib_version(Major, Minor, Patch, Status), atomic_list_concat([Major,'.',Minor,'.',Patch,'-',Status], VersionString). %! jpl_pl_lib_version(-Major, -Minor, -Patch, -Status) % % Major, Minor, Patch and Status are the respective components of the version identifier of the in-use C component (jpl.c) of JPL. % % Example % % == % ?- jpl:jpl_pl_lib_version(Major, Minor, Patch, Status). % Major = 7, % Minor = 4, % Patch = 0, % Status = alpha. % == jpl_pl_lib_version(7, 4, 0, alpha). % jref as blob %! jpl_c_lib_version(-Version) % % Version is the fully qualified version identifier of the in-use C component (jpl.c) of JPL. % % It should exactly match the version identifiers of JPL's Prolog (jpl.pl) and Java (jpl.jar) components. % % Example % % == % ?- jpl_c_lib_version(V). % V = '7.4.0-alpha'. % == %! jpl_java_lib_version(-Version) % % Version is the fully qualified version identifier of the in-use Java component (jpl.jar) of JPL. % % Example % % == % ?- jpl:jpl_java_lib_version(V). % V = '7.4.0-alpha'. % == %! jpl_java_lib_version(V) jpl_java_lib_version(V) :- jpl_call('org.jpl7.JPL', version_string, [], V). %! jpl_pl_lib_path(-Path:atom) jpl_pl_lib_path(Path) :- module_property(jpl, file(Path)). %! jpl_c_lib_path(-Path:atom) jpl_c_lib_path(Path) :- shlib:current_library(_, _, Path, jpl, _), !. %! jpl_java_lib_path(-Path:atom) jpl_java_lib_path(Path) :- jpl_call('org.jpl7.JPL', jarPath, [], Path). % jpl_type_alfa(0'$) --> % presumably not allowed % "$". % given the "inner class" syntax? jpl_type_alfa(0'_) --> "_", !. jpl_type_alfa(C) --> [C], { C>=0'a, C=<0'z }, !. jpl_type_alfa(C) --> [C], { C>=0'A, C=<0'Z }. jpl_type_alfa_num(C) --> jpl_type_alfa(C), !. jpl_type_alfa_num(C) --> [C], { C>=0'0, C=<0'9 }. jpl_type_array_classname(array(T)) --> "[", jpl_type_classname_2(T). jpl_type_array_descriptor(array(T)) --> "[", jpl_type_descriptor_1(T). jpl_type_bare_class_descriptor(class(Ps,Cs)) --> jpl_type_slashed_package_parts(Ps), jpl_type_class_parts(Cs). jpl_type_bare_classname(class(Ps,Cs)) --> jpl_type_dotted_package_parts(Ps), jpl_type_class_parts(Cs). jpl_type_class_descriptor(class(Ps,Cs)) --> "L", jpl_type_bare_class_descriptor(class(Ps,Cs)), ";". jpl_type_class_part(N) --> jpl_type_id(N). jpl_type_class_parts([C|Cs]) --> jpl_type_class_part(C), jpl_type_inner_class_parts(Cs). jpl_type_classname_1(T) --> jpl_type_bare_classname(T), !. jpl_type_classname_1(T) --> jpl_type_array_classname(T), !. jpl_type_classname_1(T) --> jpl_type_primitive(T). jpl_type_classname_2(T) --> jpl_type_delimited_classname(T). jpl_type_classname_2(T) --> jpl_type_array_classname(T). jpl_type_classname_2(T) --> jpl_type_primitive(T). jpl_type_delimited_classname(Class) --> "L", jpl_type_bare_classname(Class), ";". jpl_type_descriptor_1(T) --> jpl_type_primitive(T), !. jpl_type_descriptor_1(T) --> jpl_type_class_descriptor(T), !. jpl_type_descriptor_1(T) --> jpl_type_array_descriptor(T), !. jpl_type_descriptor_1(T) --> jpl_type_method_descriptor(T). jpl_type_dotted_package_parts([P|Ps]) --> jpl_type_package_part(P), ".", !, jpl_type_dotted_package_parts(Ps). jpl_type_dotted_package_parts([]) --> []. jpl_type_findclassname(T) --> jpl_type_bare_class_descriptor(T). jpl_type_findclassname(T) --> jpl_type_array_descriptor(T). jpl_type_id(A) --> { nonvar(A) -> atom_codes(A,[C|Cs]) ; true }, jpl_type_alfa(C), jpl_type_id_rest(Cs), { atom_codes(A, [C|Cs]) }. jpl_type_id_rest([C|Cs]) --> jpl_type_alfa_num(C), !, jpl_type_id_rest(Cs). jpl_type_id_rest([]) --> []. jpl_type_id_v2(A) --> % inner class name parts (empirically) { nonvar(A) -> atom_codes(A,Cs) ; true }, jpl_type_id_rest(Cs), { atom_codes(A, Cs) }. jpl_type_inner_class_part(N) --> jpl_type_id_v2(N). jpl_type_inner_class_parts([C|Cs]) --> "$", jpl_type_inner_class_part(C), !, jpl_type_inner_class_parts(Cs). jpl_type_inner_class_parts([]) --> []. jpl_type_method_descriptor(method(Ts,T)) --> "(", jpl_type_method_descriptor_args(Ts), ")", jpl_type_method_descriptor_return(T). jpl_type_method_descriptor_args([T|Ts]) --> jpl_type_descriptor_1(T), !, jpl_type_method_descriptor_args(Ts). jpl_type_method_descriptor_args([]) --> []. jpl_type_method_descriptor_return(T) --> jpl_type_void(T). jpl_type_method_descriptor_return(T) --> jpl_type_descriptor_1(T). jpl_type_package_part(N) --> jpl_type_id(N). jpl_type_primitive(boolean) --> "Z", !. jpl_type_primitive(byte) --> "B", !. jpl_type_primitive(char) --> "C", !. jpl_type_primitive(short) --> "S", !. jpl_type_primitive(int) --> "I", !. jpl_type_primitive(long) --> "J", !. jpl_type_primitive(float) --> "F", !. jpl_type_primitive(double) --> "D". jpl_type_slashed_package_parts([P|Ps]) --> jpl_type_package_part(P), "/", !, jpl_type_slashed_package_parts(Ps). jpl_type_slashed_package_parts([]) --> []. jpl_type_void(void) --> "V". %! jCallBooleanMethod(+Obj:jref, +MethodID:methodId, +Types:list(type), +Params:list(datum), -Rbool:boolean) jCallBooleanMethod(Obj, MethodID, Types, Params, Rbool) :- jni_params_put(Params, Types, ParamBuf), jni_func(39, Obj, MethodID, ParamBuf, Rbool). %! jCallByteMethod(+Obj:jref, +MethodID:methodId, +Types, +Params:list(datum), -Rbyte:byte) jCallByteMethod(Obj, MethodID, Types, Params, Rbyte) :- jni_params_put(Params, Types, ParamBuf), jni_func(42, Obj, MethodID, ParamBuf, Rbyte). %! jCallCharMethod(+Obj:jref, +MethodID:methodId, +Types:list(type), +Params:list(datum), -Rchar:char) jCallCharMethod(Obj, MethodID, Types, Params, Rchar) :- jni_params_put(Params, Types, ParamBuf), jni_func(45, Obj, MethodID, ParamBuf, Rchar). %! jCallDoubleMethod(+Obj:jref, +MethodID:methodId, +Types:list(type), +Params:list(datum), -Rdouble:double) jCallDoubleMethod(Obj, MethodID, Types, Params, Rdouble) :- jni_params_put(Params, Types, ParamBuf), jni_func(60, Obj, MethodID, ParamBuf, Rdouble). %! jCallFloatMethod(+Obj:jref, +MethodID:methodId, +Types:list(type), +Params:list(datum), -Rfloat:float) jCallFloatMethod(Obj, MethodID, Types, Params, Rfloat) :- jni_params_put(Params, Types, ParamBuf), jni_func(57, Obj, MethodID, ParamBuf, Rfloat). %! jCallIntMethod(+Obj:jref, +MethodID:methodId, +Types:list(type), +Params:list(datum), -Rint:int) jCallIntMethod(Obj, MethodID, Types, Params, Rint) :- jni_params_put(Params, Types, ParamBuf), jni_func(51, Obj, MethodID, ParamBuf, Rint). %! jCallLongMethod(+Obj:jref, +MethodID:methodId, +Types:list(type), +Params:list(datum), -Rlong:long) jCallLongMethod(Obj, MethodID, Types, Params, Rlong) :- jni_params_put(Params, Types, ParamBuf), jni_func(54, Obj, MethodID, ParamBuf, Rlong). %! jCallObjectMethod(+Obj:jref, +MethodID:methodId, +Types:list(type), +Params:list(datum), -Robj:jref) jCallObjectMethod(Obj, MethodID, Types, Params, Robj) :- jni_params_put(Params, Types, ParamBuf), jni_func(36, Obj, MethodID, ParamBuf, Robj). %! jCallShortMethod(+Obj:jref, +MethodID:methodId, +Types:list(type), +Params:list(datum), -Rshort:short) jCallShortMethod(Obj, MethodID, Types, Params, Rshort) :- jni_params_put(Params, Types, ParamBuf), jni_func(48, Obj, MethodID, ParamBuf, Rshort). %! jCallStaticBooleanMethod(+Class:jref, +MethodID:methodId, +Types:list(type), +Params:list(datum), -Rbool:boolean) jCallStaticBooleanMethod(Class, MethodID, Types, Params, Rbool) :- jni_params_put(Params, Types, ParamBuf), jni_func(119, Class, MethodID, ParamBuf, Rbool). %! jCallStaticByteMethod(+Class:jref, +MethodID:methodId, +Types:list(type), +Params:list(datum), -Rbyte:byte) jCallStaticByteMethod(Class, MethodID, Types, Params, Rbyte) :- jni_params_put(Params, Types, ParamBuf), jni_func(122, Class, MethodID, ParamBuf, Rbyte). %! jCallStaticCharMethod(+Class:jref, +MethodID:methodId, +Types:list(type), +Params:list(datum), -Rchar:char) jCallStaticCharMethod(Class, MethodID, Types, Params, Rchar) :- jni_params_put(Params, Types, ParamBuf), jni_func(125, Class, MethodID, ParamBuf, Rchar). %! jCallStaticDoubleMethod(+Class:jref, +MethodID:methodId, +Types:list(type), +Params:list(datum), -Rdouble:double) jCallStaticDoubleMethod(Class, MethodID, Types, Params, Rdouble) :- jni_params_put(Params, Types, ParamBuf), jni_func(140, Class, MethodID, ParamBuf, Rdouble). %! jCallStaticFloatMethod(+Class:jref, +MethodID:methodId, +Types:list(type), +Params:list(datum), -Rfloat:float) jCallStaticFloatMethod(Class, MethodID, Types, Params, Rfloat) :- jni_params_put(Params, Types, ParamBuf), jni_func(137, Class, MethodID, ParamBuf, Rfloat). %! jCallStaticIntMethod(+Class:jref, +MethodID:methodId, +Types:list(type), +Params:list(datum), -Rint:int) jCallStaticIntMethod(Class, MethodID, Types, Params, Rint) :- jni_params_put(Params, Types, ParamBuf), jni_func(131, Class, MethodID, ParamBuf, Rint). %! jCallStaticLongMethod(+Class:jref, +MethodID:methodId, +Types:list(type), +Params:list(datum), -Rlong:long) jCallStaticLongMethod(Class, MethodID, Types, Params, Rlong) :- jni_params_put(Params, Types, ParamBuf), jni_func(134, Class, MethodID, ParamBuf, Rlong). %! jCallStaticObjectMethod(+Class:jref, +MethodID:methodId, +Types:list(type), +Params:list(datum), -Robj:jref) jCallStaticObjectMethod(Class, MethodID, Types, Params, Robj) :- jni_params_put(Params, Types, ParamBuf), jni_func(116, Class, MethodID, ParamBuf, Robj). %! jCallStaticShortMethod(+Class:jref, +MethodID:methodId, +Types:list(type), +Params:list(datum), -Rshort:short) jCallStaticShortMethod(Class, MethodID, Types, Params, Rshort) :- jni_params_put(Params, Types, ParamBuf), jni_func(128, Class, MethodID, ParamBuf, Rshort). %! jCallStaticVoidMethod(+Class:jref, +MethodID:methodId, +Types:list(type), +Params:list(datum)) jCallStaticVoidMethod(Class, MethodID, Types, Params) :- jni_params_put(Params, Types, ParamBuf), jni_void(143, Class, MethodID, ParamBuf). %! jCallVoidMethod(+Obj:jref, +MethodID:methodId, +Types:list(type), +Params:list(datum)) jCallVoidMethod(Obj, MethodID, Types, Params) :- jni_params_put(Params, Types, ParamBuf), jni_void(63, Obj, MethodID, ParamBuf). %! jFindClass(+ClassName:findclassname, -Class:jref) jFindClass(ClassName, Class) :- jni_func(6, ClassName, Class). %! jGetArrayLength(+Array:jref, -Size:int) jGetArrayLength(Array, Size) :- jni_func(171, Array, Size). %! jGetBooleanArrayRegion(+Array:jref, +Start:int, +Len:int, +Buf:boolean_buf) jGetBooleanArrayRegion(Array, Start, Len, Buf) :- jni_void(199, Array, Start, Len, Buf). %! jGetBooleanField(+Obj:jref, +FieldID:fieldId, -Rbool:boolean) jGetBooleanField(Obj, FieldID, Rbool) :- jni_func(96, Obj, FieldID, Rbool). %! jGetByteArrayRegion(+Array:jref, +Start:int, +Len:int, +Buf:byte_buf) jGetByteArrayRegion(Array, Start, Len, Buf) :- jni_void(200, Array, Start, Len, Buf). %! jGetByteField(+Obj:jref, +FieldID:fieldId, -Rbyte:byte) jGetByteField(Obj, FieldID, Rbyte) :- jni_func(97, Obj, FieldID, Rbyte). %! jGetCharArrayRegion(+Array:jref, +Start:int, +Len:int, +Buf:char_buf) jGetCharArrayRegion(Array, Start, Len, Buf) :- jni_void(201, Array, Start, Len, Buf). %! jGetCharField(+Obj:jref, +FieldID:fieldId, -Rchar:char) jGetCharField(Obj, FieldID, Rchar) :- jni_func(98, Obj, FieldID, Rchar). %! jGetDoubleArrayRegion(+Array:jref, +Start:int, +Len:int, +Buf:double_buf) jGetDoubleArrayRegion(Array, Start, Len, Buf) :- jni_void(206, Array, Start, Len, Buf). %! jGetDoubleField(+Obj:jref, +FieldID:fieldId, -Rdouble:double) jGetDoubleField(Obj, FieldID, Rdouble) :- jni_func(103, Obj, FieldID, Rdouble). %! jGetFieldID(+Class:jref, +Name:fieldName, +Type:type, -FieldID:fieldId) jGetFieldID(Class, Name, Type, FieldID) :- jpl_type_to_descriptor(Type, TD), jni_func(94, Class, Name, TD, FieldID). %! jGetFloatArrayRegion(+Array:jref, +Start:int, +Len:int, +Buf:float_buf) jGetFloatArrayRegion(Array, Start, Len, Buf) :- jni_void(205, Array, Start, Len, Buf). %! jGetFloatField(+Obj:jref, +FieldID:fieldId, -Rfloat:float) jGetFloatField(Obj, FieldID, Rfloat) :- jni_func(102, Obj, FieldID, Rfloat). %! jGetIntArrayRegion(+Array:jref, +Start:int, +Len:int, +Buf:int_buf) jGetIntArrayRegion(Array, Start, Len, Buf) :- jni_void(203, Array, Start, Len, Buf). %! jGetIntField(+Obj:jref, +FieldID:fieldId, -Rint:int) jGetIntField(Obj, FieldID, Rint) :- jni_func(100, Obj, FieldID, Rint). %! jGetLongArrayRegion(+Array:jref, +Start:int, +Len:int, +Buf:long_buf) jGetLongArrayRegion(Array, Start, Len, Buf) :- jni_void(204, Array, Start, Len, Buf). %! jGetLongField(+Obj:jref, +FieldID:fieldId, -Rlong:long) jGetLongField(Obj, FieldID, Rlong) :- jni_func(101, Obj, FieldID, Rlong). %! jGetMethodID(+Class:jref, +Name:atom, +Type:type, -MethodID:methodId) jGetMethodID(Class, Name, Type, MethodID) :- jpl_type_to_descriptor(Type, TD), jni_func(33, Class, Name, TD, MethodID). %! jGetObjectArrayElement(+Array:jref, +Index:int, -Obj:jref) jGetObjectArrayElement(Array, Index, Obj) :- jni_func(173, Array, Index, Obj). %! jGetObjectClass(+Object:jref, -Class:jref) jGetObjectClass(Object, Class) :- jni_func(31, Object, Class). %! jGetObjectField(+Obj:jref, +FieldID:fieldId, -RObj:jref) jGetObjectField(Obj, FieldID, Robj) :- jni_func(95, Obj, FieldID, Robj). %! jGetShortArrayRegion(+Array:jref, +Start:int, +Len:int, +Buf:short_buf) jGetShortArrayRegion(Array, Start, Len, Buf) :- jni_void(202, Array, Start, Len, Buf). %! jGetShortField(+Obj:jref, +FieldID:fieldId, -Rshort:short) jGetShortField(Obj, FieldID, Rshort) :- jni_func(99, Obj, FieldID, Rshort). %! jGetStaticBooleanField(+Class:jref, +FieldID:fieldId, -Rbool:boolean) jGetStaticBooleanField(Class, FieldID, Rbool) :- jni_func(146, Class, FieldID, Rbool). %! jGetStaticByteField(+Class:jref, +FieldID:fieldId, -Rbyte:byte) jGetStaticByteField(Class, FieldID, Rbyte) :- jni_func(147, Class, FieldID, Rbyte). %! jGetStaticCharField(+Class:jref, +FieldID:fieldId, -Rchar:char) jGetStaticCharField(Class, FieldID, Rchar) :- jni_func(148, Class, FieldID, Rchar). %! jGetStaticDoubleField(+Class:jref, +FieldID:fieldId, -Rdouble:double) jGetStaticDoubleField(Class, FieldID, Rdouble) :- jni_func(153, Class, FieldID, Rdouble). %! jGetStaticFieldID(+Class:jref, +Name:fieldName, +Type:type, -FieldID:fieldId) jGetStaticFieldID(Class, Name, Type, FieldID) :- jpl_type_to_descriptor(Type, TD), % cache this? jni_func(144, Class, Name, TD, FieldID). %! jGetStaticFloatField(+Class:jref, +FieldID:fieldId, -Rfloat:float) jGetStaticFloatField(Class, FieldID, Rfloat) :- jni_func(152, Class, FieldID, Rfloat). %! jGetStaticIntField(+Class:jref, +FieldID:fieldId, -Rint:int) jGetStaticIntField(Class, FieldID, Rint) :- jni_func(150, Class, FieldID, Rint). %! jGetStaticLongField(+Class:jref, +FieldID:fieldId, -Rlong:long) jGetStaticLongField(Class, FieldID, Rlong) :- jni_func(151, Class, FieldID, Rlong). %! jGetStaticMethodID(+Class:jref, +Name:methodName, +Type:type, -MethodID:methodId) jGetStaticMethodID(Class, Name, Type, MethodID) :- jpl_type_to_descriptor(Type, TD), jni_func(113, Class, Name, TD, MethodID). %! jGetStaticObjectField(+Class:jref, +FieldID:fieldId, -RObj:jref) jGetStaticObjectField(Class, FieldID, Robj) :- jni_func(145, Class, FieldID, Robj). %! jGetStaticShortField(+Class:jref, +FieldID:fieldId, -Rshort:short) jGetStaticShortField(Class, FieldID, Rshort) :- jni_func(149, Class, FieldID, Rshort). %! jGetSuperclass(+Class1:jref, -Class2:jref) jGetSuperclass(Class1, Class2) :- jni_func(10, Class1, Class2). %! jIsAssignableFrom(+Class1:jref, +Class2:jref) jIsAssignableFrom(Class1, Class2) :- jni_func(11, Class1, Class2, @(true)). %! jNewBooleanArray(+Length:int, -Array:jref) jNewBooleanArray(Length, Array) :- jni_func(175, Length, Array). %! jNewByteArray(+Length:int, -Array:jref) jNewByteArray(Length, Array) :- jni_func(176, Length, Array). %! jNewCharArray(+Length:int, -Array:jref) jNewCharArray(Length, Array) :- jni_func(177, Length, Array). %! jNewDoubleArray(+Length:int, -Array:jref) jNewDoubleArray(Length, Array) :- jni_func(182, Length, Array). %! jNewFloatArray(+Length:int, -Array:jref) jNewFloatArray(Length, Array) :- jni_func(181, Length, Array). %! jNewIntArray(+Length:int, -Array:jref) jNewIntArray(Length, Array) :- jni_func(179, Length, Array). %! jNewLongArray(+Length:int, -Array:jref) jNewLongArray(Length, Array) :- jni_func(180, Length, Array). %! jNewObject(+Class:jref, +MethodID:methodId, +Types:list(type), +Params:list(datum), -Obj:jref) jNewObject(Class, MethodID, Types, Params, Obj) :- jni_params_put(Params, Types, ParamBuf), jni_func(30, Class, MethodID, ParamBuf, Obj). %! jNewObjectArray(+Len:int, +Class:jref, +InitVal:jref, -Array:jref) jNewObjectArray(Len, Class, InitVal, Array) :- jni_func(172, Len, Class, InitVal, Array). %! jNewShortArray(+Length:int, -Array:jref) jNewShortArray(Length, Array) :- jni_func(178, Length, Array). %! jSetBooleanArrayRegion(+Array:jref, +Start:int, +Len:int, +Buf:boolean_buf) jSetBooleanArrayRegion(Array, Start, Len, Buf) :- jni_void(207, Array, Start, Len, Buf). %! jSetBooleanField(+Obj:jref, +FieldID:fieldId, +Rbool:boolean) jSetBooleanField(Obj, FieldID, Rbool) :- jni_void(105, Obj, FieldID, Rbool). %! jSetByteArrayRegion(+Array:jref, +Start:int, +Len:int, +Buf:byte_buf) jSetByteArrayRegion(Array, Start, Len, Buf) :- jni_void(208, Array, Start, Len, Buf). %! jSetByteField(+Obj:jref, +FieldID:fieldId, +Rbyte:byte) jSetByteField(Obj, FieldID, Rbyte) :- jni_void(106, Obj, FieldID, Rbyte). %! jSetCharArrayRegion(+Array:jref, +Start:int, +Len:int, +Buf:char_buf) jSetCharArrayRegion(Array, Start, Len, Buf) :- jni_void(209, Array, Start, Len, Buf). %! jSetCharField(+Obj:jref, +FieldID:fieldId, +Rchar:char) jSetCharField(Obj, FieldID, Rchar) :- jni_void(107, Obj, FieldID, Rchar). %! jSetDoubleArrayRegion(+Array:jref, +Start:int, +Len:int, +Buf:double_buf) jSetDoubleArrayRegion(Array, Start, Len, Buf) :- jni_void(214, Array, Start, Len, Buf). %! jSetDoubleField(+Obj:jref, +FieldID:fieldId, +Rdouble:double) jSetDoubleField(Obj, FieldID, Rdouble) :- jni_void(112, Obj, FieldID, Rdouble). %! jSetFloatArrayRegion(+Array:jref, +Start:int, +Len:int, +Buf:float_buf) jSetFloatArrayRegion(Array, Start, Len, Buf) :- jni_void(213, Array, Start, Len, Buf). %! jSetFloatField(+Obj:jref, +FieldID:fieldId, +Rfloat:float) jSetFloatField(Obj, FieldID, Rfloat) :- jni_void(111, Obj, FieldID, Rfloat). %! jSetIntArrayRegion(+Array:jref, +Start:int, +Len:int, +Buf:int_buf) jSetIntArrayRegion(Array, Start, Len, Buf) :- jni_void(211, Array, Start, Len, Buf). %! jSetIntField(+Obj:jref, +FieldID:fieldId, +Rint:int) jSetIntField(Obj, FieldID, Rint) :- jni_void(109, Obj, FieldID, Rint). %! jSetLongArrayRegion(+Array:jref, +Start:int, +Len:int, +Buf:long_buf) jSetLongArrayRegion(Array, Start, Len, Buf) :- jni_void(212, Array, Start, Len, Buf). %! jSetLongField(+Obj:jref, +FieldID:fieldId, +Rlong:long) jSetLongField(Obj, FieldID, Rlong) :- jni_void(110, Obj, FieldID, Rlong). %! jSetObjectArrayElement(+Array:jref, +Index:int, +Obj:jref) jSetObjectArrayElement(Array, Index, Obj) :- jni_void(174, Array, Index, Obj). %! jSetObjectField(+Obj:jref, +FieldID:fieldId, +RObj:jref) jSetObjectField(Obj, FieldID, Robj) :- jni_void(104, Obj, FieldID, Robj). %! jSetShortArrayRegion(+Array:jref, +Start:int, +Len:int, +Buf:short_buf) jSetShortArrayRegion(Array, Start, Len, Buf) :- jni_void(210, Array, Start, Len, Buf). %! jSetShortField(+Obj:jref, +FieldID:fieldId, +Rshort:short) jSetShortField(Obj, FieldID, Rshort) :- jni_void(108, Obj, FieldID, Rshort). %! jSetStaticBooleanField(+Class:jref, +FieldID:fieldId, +Rbool:boolean) jSetStaticBooleanField(Class, FieldID, Rbool) :- jni_void(155, Class, FieldID, Rbool). %! jSetStaticByteField(+Class:jref, +FieldID:fieldId, +Rbyte:byte) jSetStaticByteField(Class, FieldID, Rbyte) :- jni_void(156, Class, FieldID, Rbyte). %! jSetStaticCharField(+Class:jref, +FieldID:fieldId, +Rchar:char) jSetStaticCharField(Class, FieldID, Rchar) :- jni_void(157, Class, FieldID, Rchar). %! jSetStaticDoubleField(+Class:jref, +FieldID:fieldId, +Rdouble:double) jSetStaticDoubleField(Class, FieldID, Rdouble) :- jni_void(162, Class, FieldID, Rdouble). %! jSetStaticFloatField(+Class:jref, +FieldID:fieldId, +Rfloat:float) jSetStaticFloatField(Class, FieldID, Rfloat) :- jni_void(161, Class, FieldID, Rfloat). %! jSetStaticIntField(+Class:jref, +FieldID:fieldId, +Rint:int) jSetStaticIntField(Class, FieldID, Rint) :- jni_void(159, Class, FieldID, Rint). %! jSetStaticLongField(+Class:jref, +FieldID:fieldId, +Rlong) jSetStaticLongField(Class, FieldID, Rlong) :- jni_void(160, Class, FieldID, Rlong). %! jSetStaticObjectField(+Class:jref, +FieldID:fieldId, +Robj:jref) jSetStaticObjectField(Class, FieldID, Robj) :- jni_void(154, Class, FieldID, Robj). %! jSetStaticShortField(+Class:jref, +FieldID:fieldId, +Rshort:short) jSetStaticShortField(Class, FieldID, Rshort) :- jni_void(158, Class, FieldID, Rshort). %! jni_params_put(+Params:list(datum), +Types:list(type), -ParamBuf:paramBuf) % % The old form used a static buffer, hence was not re-entrant; % the new form allocates a buffer of one jvalue per arg, % puts the (converted) args into respective elements, then returns it % (the caller is responsible for freeing it). jni_params_put(As, Ts, ParamBuf) :- jni_ensure_jvm, % in case e.g. NewStringUTF() is called length(As, N), jni_type_to_xput_code(jvalue, Xc), % Xc will be 15 jni_alloc_buffer(Xc, N, ParamBuf), jni_params_put_1(As, 0, Ts, ParamBuf). %! jni_params_put_1(+Params:list(datum), +N:integer, +JPLTypes:list(type), +ParamBuf:paramBuf) % % Params is a (full or partial) list of args-not-yet-stashed. % % Types are their (JPL) types (e.g. 'boolean'). % % N is the arg and buffer index (0+) at which the head of Params is to be stashed. % % The old form used a static buffer and hence was non-reentrant; % the new form uses a dynamically allocated buffer (which oughta be freed after use). % % NB if the (user-provided) actual params were to be unsuitable for conversion % to the method-required types, this would fail silently (without freeing the buffer); % it's not clear whether the overloaded-method-resolution ensures that all args % are convertible jni_params_put_1([], _, [], _). jni_params_put_1([A|As], N, [Tjni|Ts], ParamBuf) :- % type checking? ( jni_type_to_xput_code(Tjni, Xc) -> ( A = {Term} % a quoted general term? -> jni_term_to_jref(Term, Ax) % convert it to a @(Tag) ref to a new Term instance ; A = Ax ), jni_param_put(N, Xc, Ax, ParamBuf) % foreign ; fail % oughta raise an exception? ), N2 is N+1, jni_params_put_1(As, N2, Ts, ParamBuf). % stash remaining params (if any) %! jni_type_to_xput_code(+JspType, -JniXputCode) % % NB JniXputCode determines widening and casting in foreign code % % NB the codes could be compiled into jni_method_spec_cache etc. % instead of, or as well as, types (for - small - efficiency gain) jni_type_to_xput_code(boolean, 1). % JNI_XPUT_BOOLEAN jni_type_to_xput_code(byte, 2). % JNI_XPUT_BYTE jni_type_to_xput_code(char, 3). % JNI_XPUT_CHAR jni_type_to_xput_code(short, 4). % JNI_XPUT_SHORT jni_type_to_xput_code(int, 5). % JNI_XPUT_INT jni_type_to_xput_code(long, 6). % JNI_XPUT_LONG jni_type_to_xput_code(float, 7). % JNI_XPUT_FLOAT jni_type_to_xput_code(double, 8). % JNI_XPUT_DOUBLE jni_type_to_xput_code(class(_,_), 12). % JNI_XPUT_REF jni_type_to_xput_code(array(_), 12). % JNI_XPUT_REF jni_type_to_xput_code(jvalue, 15). % JNI_XPUT_JVALUE %! jpl_class_to_constructor_array(+Class:jref, -MethodArray:jref) % % NB might this be done more efficiently in foreign code? or in Java? jpl_class_to_constructor_array(Cx, Ma) :- jpl_classname_to_class('java.lang.Class', CC), % cacheable? jGetMethodID( CC, getConstructors, method([],array(class([java,lang,reflect],['Constructor']))), MID), % cacheable? jCallObjectMethod(Cx, MID, [], [], Ma). %! jpl_class_to_constructors(+Class:jref, -Methods:list(jref)) jpl_class_to_constructors(Cx, Ms) :- jpl_class_to_constructor_array(Cx, Ma), jpl_object_array_to_list(Ma, Ms). %! jpl_class_to_field_array(+Class:jref, -FieldArray:jref) jpl_class_to_field_array(Cx, Fa) :- jpl_classname_to_class('java.lang.Class', CC), % cacheable? jGetMethodID(CC, getFields, method([],array(class([java,lang,reflect],['Field']))), MID), % cacheable? jCallObjectMethod(Cx, MID, [], [], Fa). %! jpl_class_to_fields(+Class:jref, -Fields:list(jref)) % % NB do this in Java (ditto for methods)? jpl_class_to_fields(C, Fs) :- jpl_class_to_field_array(C, Fa), jpl_object_array_to_list(Fa, Fs). %! jpl_class_to_method_array(+Class:jref, -MethodArray:jref) % % NB migrate into foreign code for efficiency? jpl_class_to_method_array(Cx, Ma) :- jpl_classname_to_class('java.lang.Class', CC), % cacheable? jGetMethodID(CC, getMethods, method([],array(class([java,lang,reflect],['Method']))), MID), % cacheable? jCallObjectMethod(Cx, MID, [], [], Ma). %! jpl_class_to_methods(+Class:jref, -Methods:list(jref)) % % NB also used for constructors. % % NB do this in Java (ditto for fields)? jpl_class_to_methods(Cx, Ms) :- jpl_class_to_method_array(Cx, Ma), jpl_object_array_to_list(Ma, Ms). %! jpl_constructor_to_modifiers(+Method, -Modifiers) % % NB migrate into foreign code for efficiency? jpl_constructor_to_modifiers(X, Ms) :- jpl_classname_to_class('java.lang.reflect.Constructor', Cx), % cached? jpl_method_to_modifiers_1(X, Cx, Ms). %! jpl_constructor_to_name(+Method:jref, -Name:atom) % % It is a JNI convention that each constructor behaves (at least, % for reflection), as a method whose name is '<init>'. jpl_constructor_to_name(_X, '<init>'). %! jpl_constructor_to_parameter_types(+Method:jref, -ParameterTypes:list(type)) % % NB migrate to foreign code for efficiency? jpl_constructor_to_parameter_types(X, Tfps) :- jpl_classname_to_class('java.lang.reflect.Constructor', Cx), % cached? jpl_method_to_parameter_types_1(X, Cx, Tfps). %! jpl_constructor_to_return_type(+Method:jref, -Type:type) % % It is a JNI convention that, for the purposes of retrieving a MethodID, % a constructor has a return type of 'void'. jpl_constructor_to_return_type(_X, void). %! jpl_field_spec(+Type:type, -Index:integer, -Name:atom, -Modifiers, -MID:mId, -FieldType:type) % % I'm unsure whether arrays have fields, but if they do, this will handle them correctly. jpl_field_spec(T, I, N, Mods, MID, Tf) :- ( jpl_field_spec_is_cached(T) -> jpl_field_spec_cache(T, I, N, Mods, MID, Tf) ; jpl_type_to_class(T, C), jpl_class_to_fields(C, Fs), ( T = array(_BaseType) % regardless of base type... -> Tci = array(_) % ...the "cache index" type is this ; Tci = T ), jpl_field_spec_1(C, Tci, Fs), jpl_assert(jpl_field_spec_is_cached(Tci)), jpl_field_spec_cache(Tci, I, N, Mods, MID, Tf) ). jpl_field_spec_1(C, Tci, Fs) :- ( nth1(I, Fs, F), jpl_field_to_name(F, N), jpl_field_to_modifiers(F, Mods), jpl_field_to_type(F, Tf), ( member(static, Mods) -> jGetStaticFieldID(C, N, Tf, MID) ; jGetFieldID(C, N, Tf, MID) ), jpl_assert(jpl_field_spec_cache(Tci,I,N,Mods,MID,Tf)), fail ; true ). :- dynamic jpl_field_spec_cache/6. % document this... :- dynamic jpl_field_spec_is_cached/1. % document this... %! jpl_field_to_modifiers(+Field:jref, -Modifiers:ordset(modifier)) jpl_field_to_modifiers(F, Ms) :- jpl_classname_to_class('java.lang.reflect.Field', Cf), jpl_method_to_modifiers_1(F, Cf, Ms). %! jpl_field_to_name(+Field:jref, -Name:atom) jpl_field_to_name(F, N) :- jpl_classname_to_class('java.lang.reflect.Field', Cf), jpl_member_to_name_1(F, Cf, N). %! jpl_field_to_type(+Field:jref, -Type:type) jpl_field_to_type(F, Tf) :- jpl_classname_to_class('java.lang.reflect.Field', Cf), jGetMethodID(Cf, getType, method([],class([java,lang],['Class'])), MID), jCallObjectMethod(F, MID, [], [], Cr), jpl_class_to_type(Cr, Tf). %! jpl_method_spec(+Type:type, -Index:integer, -Name:atom, -Arity:integer, -Modifiers:ordset(modifier), -MID:methodId, -ReturnType:type, -ParameterTypes:list(type)) % % Generates pertinent details of all accessible methods of Type (class/2 or array/1), % populating or using the cache as appropriate. jpl_method_spec(T, I, N, A, Mods, MID, Tr, Tfps) :- ( jpl_method_spec_is_cached(T) -> jpl_method_spec_cache(T, I, N, A, Mods, MID, Tr, Tfps) ; jpl_type_to_class(T, C), jpl_class_to_constructors(C, Xs), jpl_class_to_methods(C, Ms), ( T = array(_BaseType) % regardless of base type... -> Tci = array(_) % ...the "cache index" type is this ; Tci = T ), jpl_method_spec_1(C, Tci, Xs, Ms), jpl_assert(jpl_method_spec_is_cached(Tci)), jpl_method_spec_cache(Tci, I, N, A, Mods, MID, Tr, Tfps) ). %! jpl_method_spec_1(+Class:jref, +CacheIndexType:partialType, +Constructors:list(method), +Methods:list(method)) % % If the original type is e.g. array(byte) then CacheIndexType is array(_) else it is that type. jpl_method_spec_1(C, Tci, Xs, Ms) :- ( ( nth1(I, Xs, X), % generate constructors, numbered from 1 jpl_constructor_to_name(X, N), jpl_constructor_to_modifiers(X, Mods), jpl_constructor_to_return_type(X, Tr), jpl_constructor_to_parameter_types(X, Tfps) ; length(Xs, J0), nth1(J, Ms, M), % generate members, continuing numbering I is J0+J, jpl_method_to_name(M, N), jpl_method_to_modifiers(M, Mods), jpl_method_to_return_type(M, Tr), jpl_method_to_parameter_types(M, Tfps) ), length(Tfps, A), % arity ( member(static, Mods) -> jGetStaticMethodID(C, N, method(Tfps,Tr), MID) ; jGetMethodID(C, N, method(Tfps,Tr), MID) ), jpl_assert(jpl_method_spec_cache(Tci,I,N,A,Mods,MID,Tr,Tfps)), fail ; true ). :- dynamic jpl_method_spec_cache/8. :- dynamic jpl_method_spec_is_cached/1. %! jpl_method_to_modifiers(+Method:jref, -ModifierSet:ordset(modifier)) jpl_method_to_modifiers(M, Ms) :- jpl_classname_to_class('java.lang.reflect.Method', Cm), jpl_method_to_modifiers_1(M, Cm, Ms). %! jpl_method_to_modifiers_1(+Method:jref, +ConstructorClass:jref, -ModifierSet:ordset(modifier)) jpl_method_to_modifiers_1(XM, Cxm, Ms) :- jGetMethodID(Cxm, getModifiers, method([],int), MID), jCallIntMethod(XM, MID, [], [], I), jpl_modifier_int_to_modifiers(I, Ms). %! jpl_method_to_name(+Method:jref, -Name:atom) jpl_method_to_name(M, N) :- jpl_classname_to_class('java.lang.reflect.Method', CM), jpl_member_to_name_1(M, CM, N). %! jpl_member_to_name_1(+Member:jref, +CM:jref, -Name:atom) jpl_member_to_name_1(M, CM, N) :- jGetMethodID(CM, getName, method([],class([java,lang],['String'])), MID), jCallObjectMethod(M, MID, [], [], N). %! jpl_method_to_parameter_types(+Method:jref, -Types:list(type)) jpl_method_to_parameter_types(M, Tfps) :- jpl_classname_to_class('java.lang.reflect.Method', Cm), jpl_method_to_parameter_types_1(M, Cm, Tfps). %! jpl_method_to_parameter_types_1(+XM:jref, +Cxm:jref, -Tfps:list(type)) % % XM is (a JPL ref to) an instance of java.lang.reflect.[Constructor|Method] jpl_method_to_parameter_types_1(XM, Cxm, Tfps) :- jGetMethodID(Cxm, getParameterTypes, method([],array(class([java,lang],['Class']))), MID), jCallObjectMethod(XM, MID, [], [], Atp), jpl_object_array_to_list(Atp, Ctps), jpl_classes_to_types(Ctps, Tfps). %! jpl_method_to_return_type(+Method:jref, -Type:type) jpl_method_to_return_type(M, Tr) :- jpl_classname_to_class('java.lang.reflect.Method', Cm), jGetMethodID(Cm, getReturnType, method([],class([java,lang],['Class'])), MID), jCallObjectMethod(M, MID, [], [], Cr), jpl_class_to_type(Cr, Tr). jpl_modifier_bit(public, 0x001). jpl_modifier_bit(private, 0x002). jpl_modifier_bit(protected, 0x004). jpl_modifier_bit(static, 0x008). jpl_modifier_bit(final, 0x010). jpl_modifier_bit(synchronized, 0x020). jpl_modifier_bit(volatile, 0x040). jpl_modifier_bit(transient, 0x080). jpl_modifier_bit(native, 0x100). jpl_modifier_bit(interface, 0x200). jpl_modifier_bit(abstract, 0x400). %! jpl_modifier_int_to_modifiers(+Int:integer, -ModifierSet:ordset(modifier)) % % ModifierSet is an ordered (hence canonical) list, % possibly empty (although I suspect never in practice?), % of modifier atoms, e.g. [public,static] jpl_modifier_int_to_modifiers(I, Ms) :- setof( M, % should use e.g. set_of_all/3 B^( jpl_modifier_bit(M, B), (B /\ I) =\= 0 ), Ms ). %! jpl_cache_type_of_ref(+Type:type, +Ref:jref) % % Type must be a proper (concrete) JPL type % % Ref must be a proper JPL reference (not void) % % Type is memoed (if policy so dictates) as the type of the referenced object (unless it's null) % by iref (so as not to disable atom-based GC) % % NB obsolete lemmas must be watched-out-for and removed jpl_cache_type_of_ref(T, Ref) :- ( jpl_assert_policy(jpl_iref_type_cache(_,_), no) -> true ; \+ ground(T) % shouldn't happen (implementation error) -> write('[jpl_cache_type_of_ref/2: arg 1 is not ground]'), nl, % oughta throw an exception fail ; Ref == @(null) % a null ref? (this is valid) -> true % silently ignore it ; ( jpl_iref_type_cache(Ref, TC) % we expect TC == T -> ( T == TC -> true ; % write('[JPL: found obsolete tag-type lemma...]'), nl, % or keep statistics? (why?) retractall(jpl_iref_type_cache(Ref,_)), jpl_assert(jpl_iref_type_cache(Ref,T)) ) ; jpl_assert(jpl_iref_type_cache(Ref,T)) ) ). %! jpl_class_tag_type_cache(-Ref:jref, -ClassType:type) % % Ref is a reference to a JVM instance of java.lang.Class which denotes ClassType. % % We index on Ref so as to keep these objects around % even after an atom garbage collection % (if needed once, they are likely to be needed again) :- dynamic jpl_class_tag_type_cache/2. %! jpl_class_to_ancestor_classes(+Class:jref, -AncestorClasses:list(jref)) % % AncestorClasses will be a list of (JPL references to) instances of java.lang.Class % denoting the "implements" lineage (?), nearest first % (the first member denotes the class which Class directly implements, % the next (if any) denotes the class which *that* class implements, % and so on to java.lang.Object) jpl_class_to_ancestor_classes(C, Cas) :- ( jpl_class_to_super_class(C, Ca) -> Cas = [Ca|Cas2], jpl_class_to_ancestor_classes(Ca, Cas2) ; Cas = [] ). %! jpl_class_to_classname(+Class:jref, -ClassName:dottedName) % % Class is a reference to a class object. % % ClassName is its canonical (?) source-syntax (dotted) name, % e.g. =|'java.util.Date'|= % % NB not used outside jni_junk and jpl_test (is this (still) true?) % % NB oughta use the available caches (but their indexing doesn't suit) jpl_class_to_classname(C, CN) :- jpl_call(C, getName, [], CN). %! jpl_class_to_raw_classname(+Class:jref, -ClassName:rawName) % % Hhmm, I forget exactly what a "raw" classname is. jpl_class_to_raw_classname(Cobj, CN) :- jpl_classname_to_class('java.lang.Class', CC), % cached? jGetMethodID(CC, getName, method([],class([java,lang],['String'])), MIDgetName), jCallObjectMethod(Cobj, MIDgetName, [], [], S), S = CN. %! jpl_class_to_raw_classname_chars(+Class:jref, -ClassnameChars:codes) % % Class is a reference to a class object % % ClassnameChars is a codes representation of its dotted name jpl_class_to_raw_classname_chars(Cobj, CsCN) :- jpl_class_to_raw_classname(Cobj, CN), atom_codes(CN, CsCN). jpl_class_to_super_class(C, Cx) :- jGetSuperclass(C, Cx), Cx \== @(null), % as returned when C is java.lang.Object, i.e. no superclass jpl_cache_type_of_ref(class([java,lang],['Class']), Cx). %! jpl_class_to_type(+ClassObject:jref, -Type:type) % % ClassObject is a reference to a class object of Type. % % NB should ensure that, if not found in cache, then cache is updated. % % Intriguingly, getParameterTypes returns class objects (undocumented AFAIK) with names % 'boolean', 'byte' etc. and even 'void' (?!) jpl_class_to_type(Ref, Type) :- ( jpl_class_tag_type_cache(Ref, Tx) -> true ; jpl_class_to_raw_classname_chars(Ref, Cs), % uncached jpl_classname_chars_to_type(Cs, Tr), jpl_type_to_canonical_type(Tr, Tx), % map e.g. class([],[byte]) -> byte jpl_assert(jpl_class_tag_type_cache(Ref,Tx)) -> true % the elseif goal should be determinate, but just in case... ), Type = Tx. jpl_classes_to_types([], []). jpl_classes_to_types([C|Cs], [T|Ts]) :- jpl_class_to_type(C, T), jpl_classes_to_types(Cs, Ts). jpl_classname_chars_to_type(Cs, Type) :- ( phrase(jpl_type_classname_1(Type), Cs) -> true ). %! jpl_classname_to_class(+ClassName:className, -Class:jref) % % ClassName unambiguously represents a class, e.g. =|'java.lang.String'|= % % Class is a (canonical) reference to the corresponding class object. % % NB uses caches where the class is already encountered. jpl_classname_to_class(N, C) :- jpl_classname_to_type(N, T), % cached jpl_type_to_class(T, C). % cached %! jpl_classname_to_type(+Classname:className, -Type:type) % % Classname is any of: a source-syntax (dotted) class name, e.g. 'java.util.Date', '[java.util.Date' or '[L' % % Type is its corresponding JPL type structure, e.g. =|class([java,util],['Date'])|=, =|array(class([java,util],['Date']))|=, =|array(long)|= % % NB by "classname" do I mean "typename"? % % NB should this throw an exception for unbound CN? is this public API? jpl_classname_to_type(CN, T) :- ( jpl_classname_type_cache(CN, Tx) -> Tx = T ; atom_codes(CN, CsCN), phrase(jpl_type_classname_1(T), CsCN) -> jpl_assert(jpl_classname_type_cache(CN,T)), true ). %! jpl_classname_type_cache( -Classname:className, -Type:type) % % Classname is the atomic name of Type. % % NB may denote a class which cannot be found. :- dynamic jpl_classname_type_cache/2. %! jpl_datum_to_type(+Datum:datum, -Type:type) % % Datum must be a JPL representation of an instance of one (or more) Java types; % % Type is the unique most specialised type of which Datum denotes an instance; % % NB 3 is an instance of byte, char, short, int and long, % of which byte and char are the joint, overlapping most specialised types, % so this relates 3 to the pseudo subtype 'char_byte'; % % @see jpl_type_to_preferred_concrete_type/2 for converting inferred types to instantiable types jpl_datum_to_type(D, T) :- ( jpl_value_to_type(D, T) -> true ; jpl_ref_to_type(D, T) -> true ; nonvar(D), D = {Term} -> ( cyclic_term(Term) -> throw(error(type_error(acyclic,Term),context(jpl_datum_to_type/2,'must be acyclic'))) ; atom(Term) -> T = class([org,jpl7],['Atom']) ; integer(Term) -> T = class([org,jpl7],['Integer']) ; float(Term) -> T = class([org,jpl7],['Float']) ; var(Term) -> T = class([org,jpl7],['Variable']) ; T = class([org,jpl7],['Compound']) ) ). jpl_datums_to_most_specific_common_ancestor_type([D], T) :- jpl_datum_to_type(D, T). jpl_datums_to_most_specific_common_ancestor_type([D1,D2|Ds], T0) :- jpl_datum_to_type(D1, T1), jpl_type_to_ancestor_types(T1, Ts1), jpl_datums_to_most_specific_common_ancestor_type_1([D2|Ds], [T1|Ts1], [T0|_]). jpl_datums_to_most_specific_common_ancestor_type_1([], Ts, Ts). jpl_datums_to_most_specific_common_ancestor_type_1([D|Ds], Ts1, Ts0) :- jpl_datum_to_type(D, Tx), jpl_lineage_types_type_to_common_lineage_types(Ts1, Tx, Ts2), jpl_datums_to_most_specific_common_ancestor_type_1(Ds, Ts2, Ts0). %! jpl_datums_to_types(+Datums:list(datum), -Types:list(type)) % % Each member of Datums is a JPL value or reference, % denoting an instance of some Java type, % and the corresponding member of Types denotes the most specialised type % of which it is an instance (including some I invented for the overlaps % between e.g. char and short). jpl_datums_to_types([], []). jpl_datums_to_types([D|Ds], [T|Ts]) :- jpl_datum_to_type(D, T), jpl_datums_to_types(Ds, Ts). %! jpl_ground_is_type(+X:term) % % X, known to be ground, is (or at least superficially resembles :-) a JPL type. jpl_ground_is_type(X) :- jpl_primitive_type(X), !. jpl_ground_is_type(array(X)) :- jpl_ground_is_type(X). jpl_ground_is_type(class(_,_)). jpl_ground_is_type(method(_,_)). :- dynamic jpl_iref_type_cache/2. jpl_lineage_types_type_to_common_lineage_types(Ts, Tx, Ts0) :- ( append(_, [Tx|Ts2], Ts) -> [Tx|Ts2] = Ts0 ; jpl_type_to_super_type(Tx, Tx2) -> jpl_lineage_types_type_to_common_lineage_types(Ts, Tx2, Ts0) ). jpl_non_var_is_object_type(class(_,_)). jpl_non_var_is_object_type(array(_)). %! jpl_object_array_to_list(+Array:jref, -Values:list(datum)) % % Values is a list of JPL values (primitive values or object references) % representing the respective elements of Array. jpl_object_array_to_list(A, Vs) :- jpl_array_to_length(A, N), jpl_object_array_to_list_1(A, 0, N, Vs). %! jpl_object_array_to_list_1(+A, +I, +N, -Xs) jpl_object_array_to_list_1(A, I, N, Xs) :- ( I == N -> Xs = [] ; jGetObjectArrayElement(A, I, X), Xs = [X|Xs2], J is I+1, jpl_object_array_to_list_1(A, J, N, Xs2) ). %! jpl_object_to_class(+Object:jref, -Class:jref) % % fails silently if Object is not a valid reference to a Java object % % Class is a (canonical) reference to the (canonical) class object % which represents the class of Object % % NB what's the point of caching the type if we don't look there first? jpl_object_to_class(Obj, C) :- jpl_is_object(Obj), jGetObjectClass(Obj, C), jpl_cache_type_of_ref(class([java,lang],['Class']), C). %! jpl_object_to_type(+Object:jref, -Type:type) % % Object must be a proper JPL reference to a Java object % (i.e. a class or array instance, but not null, void or String). % % Type is the JPL type of that object. jpl_object_to_type(Ref, Type) :- jpl_is_object(Ref), ( jpl_iref_type_cache(Ref, T) -> true % T is Tag's type ; jpl_object_to_class(Ref, Cobj), % else get ref to class obj jpl_class_to_type(Cobj, T), % get type of class it denotes jpl_assert(jpl_iref_type_cache(Ref,T)) ), Type = T. jpl_object_type_to_super_type(T, Tx) :- ( ( T = class(_,_) ; T = array(_) ) -> jpl_type_to_class(T, C), jpl_class_to_super_class(C, Cx), Cx \== @(null), jpl_class_to_type(Cx, Tx) ). %! jpl_primitive_buffer_to_array(+Type, +Xc, +Bp, +I, +Size, -Vcs) % % Bp points to a buffer of (sufficient) Type values. % % Vcs will be unbound on entry, % and on exit will be a list of Size of them, starting at index I % (the buffer is indexed from zero) jpl_primitive_buffer_to_array(T, Xc, Bp, I, Size, [Vc|Vcs]) :- jni_fetch_buffer_value(Bp, I, Vc, Xc), Ix is I+1, ( Ix < Size -> jpl_primitive_buffer_to_array(T, Xc, Bp, Ix, Size, Vcs) ; Vcs = [] ). %! jpl_primitive_type(-Type:atom) is nondet % % Type is an atomic JPL representation of one of Java's primitive types. % % == % ?- setof(Type, jpl_primitive_type(Type), Types). % Types = [boolean, byte, char, double, float, int, long, short]. % == jpl_primitive_type(boolean). jpl_primitive_type(char). jpl_primitive_type(byte). jpl_primitive_type(short). jpl_primitive_type(int). jpl_primitive_type(long). jpl_primitive_type(float). jpl_primitive_type(double). %! jpl_primitive_type_default_value(-Type:type, -Value:datum) % % Each element of any array of (primitive) Type created by jpl_new/3, % or any instance of (primitive) Type created by jpl_new/3, % will be initialised to Value (to mimic Java semantics). jpl_primitive_type_default_value(boolean, @(false)). jpl_primitive_type_default_value(char, 0). jpl_primitive_type_default_value(byte, 0). jpl_primitive_type_default_value(short, 0). jpl_primitive_type_default_value(int, 0). jpl_primitive_type_default_value(long, 0). jpl_primitive_type_default_value(float, 0.0). jpl_primitive_type_default_value(double, 0.0). jpl_primitive_type_super_type(T, Tx) :- ( jpl_type_fits_type_direct_prim(T, Tx) ; jpl_type_fits_type_direct_xtra(T, Tx) ). %! jpl_primitive_type_term_to_value(+Type, +Term, -Val) % % Term, after widening iff appropriate, represents an instance of Type. % % Val is the instance of Type which it represents (often the same thing). % % NB currently used only by jpl_new_1 when creating an "instance" % of a primitive type (which may be misguided completism - you can't % do that in Java) jpl_primitive_type_term_to_value(Type, Term, Val) :- ( jpl_primitive_type_term_to_value_1(Type, Term, Val) -> true ). %! jpl_primitive_type_term_to_value_1(+Type, +RawValue, -WidenedValue) % % I'm not worried about structure duplication here. % % NB this oughta be done in foreign code. jpl_primitive_type_term_to_value_1(boolean, @(false), @(false)). jpl_primitive_type_term_to_value_1(boolean, @(true), @(true)). jpl_primitive_type_term_to_value_1(char, I, I) :- integer(I), I >= 0, I =< 65535. % (2**16)-1. jpl_primitive_type_term_to_value_1(byte, I, I) :- integer(I), I >= 128, % -(2**7) I =< 127. % (2**7)-1 jpl_primitive_type_term_to_value_1(short, I, I) :- integer(I), I >= -32768, % -(2**15) I =< 32767. % (2**15)-1 jpl_primitive_type_term_to_value_1(int, I, I) :- integer(I), I >= -2147483648, % -(2**31) I =< 2147483647. % (2**31)-1 jpl_primitive_type_term_to_value_1(long, I, I) :- integer(I), I >= -9223372036854775808, % -(2**63) I =< 9223372036854775807. % (2**63)-1 jpl_primitive_type_term_to_value_1(float, V, F) :- ( integer(V) -> F is float(V) ; float(V) -> F = V ). jpl_primitive_type_term_to_value_1(double, V, F) :- ( integer(V) -> F is float(V) ; float(V) -> F = V ). jpl_primitive_type_to_ancestor_types(T, Ts) :- ( jpl_primitive_type_super_type(T, Ta) -> Ts = [Ta|Tas], jpl_primitive_type_to_ancestor_types(Ta, Tas) ; Ts = [] ). jpl_primitive_type_to_super_type(T, Tx) :- jpl_primitive_type_super_type(T, Tx). %! jpl_ref_to_type(+Ref:jref, -Type:type) % % Ref must be a proper JPL reference (to an object, null or void). % % Type is its type. jpl_ref_to_type(Ref, T) :- ( Ref == @(null) -> T = null ; Ref == @(void) -> T = void ; jpl_object_to_type(Ref, T) ). %! jpl_tag_to_type(+Tag:tag, -Type:type) % % Tag must be an (atomic) object tag. % % Type is its type (either from the cache or by reflection). % OBSOLETE jpl_tag_to_type(Tag, Type) :- jni_tag_to_iref(Tag, Iref), ( jpl_iref_type_cache(Iref, T) -> true % T is Tag's type ; jpl_object_to_class(@(Tag), Cobj), % else get ref to class obj jpl_class_to_type(Cobj, T), % get type of class it denotes jpl_assert(jpl_iref_type_cache(Iref,T)) ), Type = T. %! jpl_type_fits_type(+TypeX:type, +TypeY:type) is semidet % % TypeX and TypeY must each be proper JPL types. % % This succeeds iff TypeX is assignable to TypeY. jpl_type_fits_type(Tx, Ty) :- ( jpl_type_fits_type_1(Tx, Ty) -> true ). %! jpl_type_fits_type_1(+T1:type, +T2:type) % % NB it doesn't matter that this leaves choicepoints; it serves only jpl_type_fits_type/2 jpl_type_fits_type_1(T, T). jpl_type_fits_type_1(class(Ps1,Cs1), class(Ps2,Cs2)) :- jpl_type_to_class(class(Ps1,Cs1), C1), jpl_type_to_class(class(Ps2,Cs2), C2), jIsAssignableFrom(C1, C2). jpl_type_fits_type_1(array(T1), class(Ps2,Cs2)) :- jpl_type_to_class(array(T1), C1), jpl_type_to_class(class(Ps2,Cs2), C2), jIsAssignableFrom(C1, C2). jpl_type_fits_type_1(array(T1), array(T2)) :- jpl_type_to_class(array(T1), C1), jpl_type_to_class(array(T2), C2), jIsAssignableFrom(C1, C2). jpl_type_fits_type_1(null, class(_,_)). jpl_type_fits_type_1(null, array(_)). jpl_type_fits_type_1(T1, T2) :- jpl_type_fits_type_xprim(T1, T2). jpl_type_fits_type_direct_prim(float, double). jpl_type_fits_type_direct_prim(long, float). jpl_type_fits_type_direct_prim(int, long). jpl_type_fits_type_direct_prim(char, int). jpl_type_fits_type_direct_prim(short, int). jpl_type_fits_type_direct_prim(byte, short). jpl_type_fits_type_direct_xprim(Tp, Tq) :- jpl_type_fits_type_direct_prim(Tp, Tq). jpl_type_fits_type_direct_xprim(Tp, Tq) :- jpl_type_fits_type_direct_xtra(Tp, Tq). %! jpl_type_fits_type_direct_xtra(-PseudoType:type, -ConcreteType:type) % % This defines the direct subtype-supertype relationships % which involve the intersection pseudo types =|char_int|=, =|char_short|= and =|char_byte|= jpl_type_fits_type_direct_xtra(char_int, int). % char_int is a direct subtype of int jpl_type_fits_type_direct_xtra(char_int, char). % etc. jpl_type_fits_type_direct_xtra(char_short, short). jpl_type_fits_type_direct_xtra(char_short, char). jpl_type_fits_type_direct_xtra(char_byte, byte). jpl_type_fits_type_direct_xtra(char_byte, char). jpl_type_fits_type_direct_xtra(overlong, float). % 6/Oct/2006 experiment %! jpl_type_fits_type_xprim(-Tp, -T) is nondet % % NB serves only jpl_type_fits_type_1/2 jpl_type_fits_type_xprim(Tp, T) :- jpl_type_fits_type_direct_xprim(Tp, Tq), ( Tq = T ; jpl_type_fits_type_xprim(Tq, T) ). %! jpl_type_to_ancestor_types(+T:type, -Tas:list(type)) % % This does not accommodate the assignability of null, % but that's OK (?) since "type assignability" and "type ancestry" are not equivalent. jpl_type_to_ancestor_types(T, Tas) :- ( ( T = class(_,_) ; T = array(_) ) -> jpl_type_to_class(T, C), jpl_class_to_ancestor_classes(C, Cas), jpl_classes_to_types(Cas, Tas) ; jpl_primitive_type_to_ancestor_types(T, Tas) -> true ). %! jpl_type_to_canonical_type(+Type:type, -CanonicalType:type) % % Type must be a type, not necessarily canonical. % % CanonicalType will be equivalent and canonical. % % Example % == % ?- jpl:jpl_type_to_canonical_type(class([],[byte]), T). % T = byte. % == jpl_type_to_canonical_type(array(T), array(Tc)) :- !, jpl_type_to_canonical_type(T, Tc). jpl_type_to_canonical_type(class([],[void]), void) :- !. jpl_type_to_canonical_type(class([],[N]), N) :- jpl_primitive_type(N), !. jpl_type_to_canonical_type(class(Ps,Cs), class(Ps,Cs)) :- !. jpl_type_to_canonical_type(void, void) :- !. jpl_type_to_canonical_type(P, P) :- jpl_primitive_type(P). %! jpl_type_to_class(+Type:type, -Class:jref) % % Incomplete types are now never cached (or otherwise passed around). % % jFindClass throws an exception if FCN can't be found. jpl_type_to_class(T, RefA) :- ( ground(T) -> ( jpl_class_tag_type_cache(RefB, T) -> true ; ( jpl_type_to_findclassname(T, FCN) % peculiar syntax for FindClass() -> jFindClass(FCN, RefB), % which caches type of RefB jpl_cache_type_of_ref(class([java,lang],['Class']), RefB) % 9/Nov/2004 bugfix (?) ), jpl_assert(jpl_class_tag_type_cache(RefB,T)) ), RefA = RefB ; throw(error(instantiation_error,context(jpl_type_to_class/2,'1st arg must be bound to a JPL type'))) ). %! jpl_type_to_nicename(+Type:type, -NiceName:dottedName) % % Type, which is a class or array type (not sure about the others...), % is denoted by ClassName in dotted syntax. % % NB is this used? is "nicename" well defined and necessary? % % NB this could use caching if indexing were amenable. % % Examples % == % ?- jpl:jpl_type_to_nicename(class([java,util],['Date']), Name). % Name = 'java.util.Date'. % % ?- jpl:jpl_type_to_nicename(boolean, Name). % Name = boolean. % == % % @see jpl_type_to_classname/2 jpl_type_to_nicename(T, NN) :- ( jpl_primitive_type(T) -> NN = T ; ( phrase(jpl_type_classname_1(T), Cs) -> atom_codes(CNx, Cs), % green commit to first solution NN = CNx ) ). %! jpl_type_to_classname(+Type:type, -ClassName:dottedName) % % Type, which is a class or array type (not sure about the others...), % is denoted by ClassName in dotted syntax. % % e.g. jpl_type_to_classname(class([java,util],['Date']), 'java.util.Date') % % @see jpl_type_to_nicename/2 jpl_type_to_classname(T, CN) :- ( phrase(jpl_type_classname_1(T), Cs) -> atom_codes(CNx, Cs), % green commit to first solution CN = CNx ). %! jpl_type_to_descriptor(+Type:type, -Descriptor:descriptor) % % Type (denoting any Java type) % (can also be a JPL method/2 structure (?!)) % is represented by Descriptor (JVM internal syntax) % % Example % == % ?- jpl:jpl_type_to_descriptor(class([java,util],['Date']), Descriptor). % Descriptor = 'Ljava/util/Date;'. % == % % I'd cache this, but I'd prefer more efficient indexing on types (hashed?) jpl_type_to_descriptor(T, D) :- ( phrase(jpl_type_descriptor_1(T), Cs) -> atom_codes(Dx, Cs), D = Dx ). %! jpl_type_to_findclassname(+Type:type, -FindClassName:findClassName) % % FindClassName denotes Type (class or array only) % in the syntax required peculiarly by JNI's FindClass(). % % Example % == % ?- jpl:jpl_type_to_findclassname(class([java,util],['Date']), FindClassName). % FindClassName = 'java/util/Date'. % == jpl_type_to_findclassname(T, FCN) :- ( phrase(jpl_type_findclassname(T), Cs) -> atom_codes(FCNx, Cs), FCN = FCNx ). %! jpl_type_to_super_type(+Type:type, -SuperType:type) % % Type should be a proper JPL type. % % SuperType is the (at most one) type which it directly implements (if it's a class). % % If Type denotes a class, this works only if that class can be found. jpl_type_to_super_type(T, Tx) :- ( jpl_object_type_to_super_type(T, Tx) -> true ; jpl_primitive_type_to_super_type(T, Tx) -> true ). %! jpl_type_to_preferred_concrete_type(+Type:type, -ConcreteType:type) % % Type must be a canonical JPL type, % possibly an inferred pseudo type such as =|char_int|= or =|array(char_byte)|= % % ConcreteType is the preferred concrete (Java-instantiable) type. % % Example % == % ?- jpl_type_to_preferred_concrete_type(array(char_byte), T). % T = array(byte). % == % % NB introduced 16/Apr/2005 to fix bug whereby jpl_list_to_array([1,2,3],A) failed % because the lists's inferred type of array(char_byte) is not Java-instantiable jpl_type_to_preferred_concrete_type(T, Tc) :- ( jpl_type_to_preferred_concrete_type_1(T, TcX) -> Tc = TcX ). jpl_type_to_preferred_concrete_type_1(char_int, int). jpl_type_to_preferred_concrete_type_1(char_short, short). jpl_type_to_preferred_concrete_type_1(char_byte, byte). jpl_type_to_preferred_concrete_type_1(array(T), array(Tc)) :- jpl_type_to_preferred_concrete_type_1(T, Tc). jpl_type_to_preferred_concrete_type_1(T, T). %! jpl_types_fit_type(+Types:list(type), +Type:type) % % Each member of Types is (independently) (if that means anything) assignable to Type. % % Used in dynamic type check when attempting to e.g. assign list of values to array. jpl_types_fit_type([], _). jpl_types_fit_type([T1|T1s], T2) :- jpl_type_fits_type(T1, T2), jpl_types_fit_type(T1s, T2). %! jpl_types_fit_types(+Types1:list(type), +Types2:list(type)) % % Each member type of Types1 "fits" the respective member type of Types2. jpl_types_fit_types([], []). jpl_types_fit_types([T1|T1s], [T2|T2s]) :- jpl_type_fits_type(T1, T2), jpl_types_fit_types(T1s, T2s). %! jpl_value_to_type(+Value:datum, -Type:type) % % Value must be a proper JPL datum other than a ref % i.e. primitive, String or void % % Type is its unique most specific type, % which may be one of the pseudo types =|char_byte|=, =|char_short|= or =|char_int|=. jpl_value_to_type(V, T) :- ground(V), % critically assumed by jpl_value_to_type_1/2 ( jpl_value_to_type_1(V, Tv) % 2nd arg must be unbound -> T = Tv ). %! jpl_value_to_type_1(+Value:datum, -Type:type) is semidet % % Type is the unique most specific JPL type of which Value represents an instance. % % Called solely by jpl_value_to_type/2, which commits to first solution. % % NB some integer values are of JPL-peculiar uniquely most % specific subtypes, i.e. char_byte, char_short, char_int but all % are understood by JPL's internal utilities which call this proc. % % NB we regard float as subtype of double. % % NB objects and refs always have straightforward types. jpl_value_to_type_1(@(false), boolean) :- !. jpl_value_to_type_1(@(true), boolean) :- !. jpl_value_to_type_1(A, class([java,lang],['String'])) :- % yes it's a "value" atom(A), !. jpl_value_to_type_1(I, T) :- integer(I), !, ( I >= 0 -> ( I < 128 -> T = char_byte ; I < 32768 -> T = char_short ; I < 65536 -> T = char_int ; I < 2147483648 -> T = int ; I =< 9223372036854775807 -> T = long ; T = overlong ) ; I >= -128 -> T = byte ; I >= -32768 -> T = short ; I >= -2147483648 -> T = int ; I >= -9223372036854775808 -> T = long ; T = overlong ). jpl_value_to_type_1(F, float) :- float(F). %! jpl_is_class(@Term) % % True if Term is a JPL reference to an instance of =|java.lang.Class|=. jpl_is_class(X) :- jpl_is_object(X), jpl_object_to_type(X, class([java,lang],['Class'])). %! jpl_is_false(@Term) % % True if Term is =|@(false)|=, the JPL representation of the Java boolean value 'false'. jpl_is_false(X) :- X == @(false). %! jpl_is_fieldID(-X) % % X is a JPL field ID structure (jfieldID/1).. % % NB JPL internal use only. % % NB applications should not be messing with these. % % NB a var arg may get bound. jpl_is_fieldID(jfieldID(X)) :- integer(X). %! jpl_is_methodID(-X) % % X is a JPL method ID structure (jmethodID/1). % % NB JPL internal use only. % % NB applications should not be messing with these. % % NB a var arg may get bound. jpl_is_methodID(jmethodID(X)) :- % NB a var arg may get bound... integer(X). %! jpl_is_null(@Term) % % True if Term is =|@(null)|=, the JPL representation of Java's 'null' reference. jpl_is_null(X) :- X == @(null). %! jpl_is_object(@Term) % % True if Term is a well-formed JPL object reference. % % NB this checks only syntax, not whether the object exists. jpl_is_object(X) :- blob(X, jref). %! jpl_is_object_type(@Term) % % True if Term is an object (class or array) type, not e.g. a primitive, null or void. jpl_is_object_type(T) :- \+ var(T), jpl_non_var_is_object_type(T). %! jpl_is_ref(@Term) % % True if Term is a well-formed JPL reference, % either to a Java object % or to Java's notional but important 'null' non-object. jpl_is_ref(Term) :- ( jpl_is_object(Term) -> true ; jpl_is_null(Term) -> true ). %! jpl_is_true(@Term) % % True if Term is =|@(true)|=, the JPL representation of the Java boolean value 'true'. jpl_is_true(X) :- X == @(true). %! jpl_is_type(@Term) % % True if Term is a well-formed JPL type structure. jpl_is_type(X) :- ground(X), jpl_ground_is_type(X). %! jpl_is_void(@Term) % % True if Term is =|@(void)|=, the JPL representation of the pseudo Java value 'void' % (which is returned by jpl_call/4 when invoked on void methods). % % NB you can try passing 'void' back to Java, but it won't ever be interested. jpl_is_void(X) :- X == @(void). %! jpl_false(-X:datum) is semidet % % X is =|@(false)|=, the JPL representation of the Java boolean value 'false'. % % @see jpl_is_false/1 jpl_false(@(false)). %! jpl_null(-X:datum) is semidet % % X is =|@(null)|=, the JPL representation of Java's 'null' reference % % @see jpl_is_null/1 jpl_null(@(null)). %! jpl_true(-X:datum) is semidet % % X is =|@(true)|=, the JPL representation of the Java boolean value 'true'. % % @see jpl_is_true/1 jpl_true(@(true)). %! jpl_void(-X:datum) is semidet % % X is =|@(void)|=, the JPL representation of the pseudo Java value 'void' % % @see jpl_is_void/1 jpl_void(@(void)). %! jpl_array_to_length(+Array:jref, -Length:integer) % % Array should be a JPL reference to a Java array of any type. % % Length is the length of that array. % % This is a utility predicate, defined thus: % % == % jpl_array_to_length(A, N) :- % ( jpl_ref_to_type(A, array(_)) % -> jGetArrayLength(A, N) % ). % == jpl_array_to_length(A, N) :- ( jpl_ref_to_type(A, array(_)) % can this be done cheaper e.g. in foreign code? -> jGetArrayLength(A, N) % *must* be array, else undefined (crash?) ). %! jpl_array_to_list(+Array:jref, -Elements:list(datum)) % % Array should be a JPL reference to a Java array of any type. % % Elements is a Prolog list of JPL representations of the array's elements % (values or references, as appropriate). % % This is a utility predicate, defined thus: % % == % jpl_array_to_list(A, Es) :- % jpl_array_to_length(A, Len), % ( Len > 0 % -> LoBound is 0, % HiBound is Len-1, % jpl_get(A, LoBound-HiBound, Es) % ; Es = [] % ). % == jpl_array_to_list(A, Es) :- jpl_array_to_length(A, Len), ( Len > 0 -> LoBound is 0, HiBound is Len-1, jpl_get(A, LoBound-HiBound, Es) ; Es = [] ). %! jpl_datums_to_array(+Datums:list(datum), -A:jref) % % A will be a JPL reference to a new Java array, % whose base type is the most specific Java type % of which each member of Datums is (directly or indirectly) an instance. % % NB this fails silently if % * Datums is an empty list (no base type can be inferred) % * Datums contains both a primitive value and an object (including array) reference (no common supertype) jpl_datums_to_array(Ds, A) :- ground(Ds), jpl_datums_to_most_specific_common_ancestor_type(Ds, T), % T may be pseudo e.g. char_byte jpl_type_to_preferred_concrete_type(T, Tc), % bugfix added 16/Apr/2005 jpl_new(array(Tc), Ds, A). %! jpl_enumeration_element(+Enumeration:jref, -Element:datum) % % generates each Element from the Enumeration % * if the element is a java.lang.String then Element will be an atom % * if the element is null then Element will (oughta) be null % * otherwise I reckon it has to be an object ref jpl_enumeration_element(En, E) :- ( jpl_call(En, hasMoreElements, [], @(true)) -> jpl_call(En, nextElement, [], Ex), ( E = Ex ; jpl_enumeration_element(En, E) ) ). %! jpl_enumeration_to_list(+Enumeration:jref, -Elements:list(datum)) % % Enumeration should be a JPL reference to an object which implements the =|Enumeration|= interface. % % Elements is a Prolog list of JPL references to the enumerated objects. % % This is a utility predicate, defined thus: % == % jpl_enumeration_to_list(Enumeration, Es) :- % ( jpl_call(Enumeration, hasMoreElements, [], @(true)) % -> jpl_call(Enumeration, nextElement, [], E), % Es = [E|Es1], % jpl_enumeration_to_list(Enumeration, Es1) % ; Es = [] % ). % == jpl_enumeration_to_list(Enumeration, Es) :- ( jpl_call(Enumeration, hasMoreElements, [], @(true)) -> jpl_call(Enumeration, nextElement, [], E), Es = [E|Es1], jpl_enumeration_to_list(Enumeration, Es1) ; Es = [] ). %! jpl_hashtable_pair(+HashTable:jref, -KeyValuePair:pair(datum,datum)) is nondet % % Generates Key-Value pairs from the given HashTable. % % NB String is converted to atom but Integer is presumably returned as an object ref % (i.e. as elsewhere, no auto unboxing); % % NB this is anachronistic: the Map interface is preferred. jpl_hashtable_pair(HT, K-V) :- jpl_call(HT, keys, [], Ek), jpl_enumeration_to_list(Ek, Ks), member(K, Ks), jpl_call(HT, get, [K], V). %! jpl_iterator_element(+Iterator:jref, -Element:datum) % % Iterator should be a JPL reference to an object which implements the =|java.util.Iterator|= interface. % % Element is the JPL representation of the next element in the iteration. % % This is a utility predicate, defined thus: % == % jpl_iterator_element(I, E) :- % ( jpl_call(I, hasNext, [], @(true)) % -> ( jpl_call(I, next, [], E) % ; jpl_iterator_element(I, E) % ) % ). % == jpl_iterator_element(I, E) :- ( jpl_call(I, hasNext, [], @(true)) -> ( jpl_call(I, next, [], E) ; jpl_iterator_element(I, E) ) ). %! jpl_list_to_array(+Datums:list(datum), -Array:jref) % % Datums should be a proper Prolog list of JPL datums (values or references). % % If Datums have a most specific common supertype, % then Array is a JPL reference to a new Java array, whose base type is that common supertype, % and whose respective elements are the Java values or objects represented by Datums. jpl_list_to_array(Ds, A) :- jpl_datums_to_array(Ds, A). %! jpl_terms_to_array(+Terms:list(term), -Array:jref) is semidet % % Terms should be a proper Prolog list of arbitrary terms. % % Array is a JPL reference to a new Java array of org.jpl7.Term, % whose elements represent the respective members of the list. jpl_terms_to_array(Ts, A) :- jpl_terms_to_array_1(Ts, Ts2), jpl_new(array(class([org,jpl7],['Term'])), Ts2, A). jpl_terms_to_array_1([], []). jpl_terms_to_array_1([T|Ts], [{T}|Ts2]) :- jpl_terms_to_array_1(Ts, Ts2). %! jpl_array_to_terms(+JRef:jref, -Terms:list(term)) % % JRef should be a JPL reference to a Java array of org.jpl7.Term instances (or ots subtypes); % Terms will be a list of the terms which the respective array elements represent. jpl_array_to_terms(JRef, Terms) :- jpl_call('org.jpl7.Util', termArrayToList, [JRef], {Terms}). %! jpl_map_element(+Map:jref, -KeyValue:pair(datum,datum)) is nondet % % Map must be a JPL Reference to an object which implements the =|java.util.Map|= interface % % This generates each Key-Value pair from the Map, e.g. % % == % ?- jpl_call('java.lang.System', getProperties, [], Map), jpl_map_element(Map, E). % Map = @<jref>(0x20b5c38), % E = 'java.runtime.name'-'Java(TM) SE Runtime Environment' ; % Map = @<jref>(0x20b5c38), % E = 'sun.boot.library.path'-'C:\\Program Files\\Java\\jre7\\bin' % etc. % == % % This is a utility predicate, defined thus: % % == % jpl_map_element(Map, K-V) :- % jpl_call(Map, entrySet, [], ES), % jpl_set_element(ES, E), % jpl_call(E, getKey, [], K), % jpl_call(E, getValue, [], V). % == jpl_map_element(Map, K-V) :- jpl_call(Map, entrySet, [], ES), jpl_set_element(ES, E), jpl_call(E, getKey, [], K), jpl_call(E, getValue, [], V). %! jpl_set_element(+Set:jref, -Element:datum) is nondet % % Set must be a JPL reference to an object which implements the =|java.util.Set|= interface. % % On backtracking, Element is bound to a JPL representation of each element of Set. % % This is a utility predicate, defined thus: % % == % jpl_set_element(S, E) :- % jpl_call(S, iterator, [], I), % jpl_iterator_element(I, E). % == jpl_set_element(S, E) :- jpl_call(S, iterator, [], I), jpl_iterator_element(I, E). %! jpl_servlet_byref(+Config, +Request, +Response) % % This serves the "byref" servlet demo, % exemplifying one tactic for implementing a servlet in Prolog % by accepting the Request and Response objects as JPL references % and accessing their members via JPL as required; % % @see jpl_servlet_byval/3 jpl_servlet_byref(Config, Request, Response) :- jpl_call(Config, getServletContext, [], Context), jpl_call(Response, setStatus, [200], _), jpl_call(Response, setContentType, ['text/html'], _), jpl_call(Response, getWriter, [], W), jpl_call(W, println, ['<html><head></head><body><h2>jpl_servlet_byref/3 says:</h2><pre>'], _), jpl_call(W, println, ['\nservlet context stuff:'], _), jpl_call(Context, getInitParameterNames, [], ContextInitParameterNameEnum), jpl_enumeration_to_list(ContextInitParameterNameEnum, ContextInitParameterNames), length(ContextInitParameterNames, NContextInitParameterNames), atomic_list_concat(['\tContext.InitParameters = ',NContextInitParameterNames], NContextInitParameterNamesMsg), jpl_call(W, println, [NContextInitParameterNamesMsg], _), ( member(ContextInitParameterName, ContextInitParameterNames), jpl_call(Context, getInitParameter, [ContextInitParameterName], ContextInitParameter), atomic_list_concat(['\t\tContext.InitParameter[',ContextInitParameterName,'] = ',ContextInitParameter], ContextInitParameterMsg), jpl_call(W, println, [ContextInitParameterMsg], _), fail ; true ), jpl_call(Context, getMajorVersion, [], MajorVersion), atomic_list_concat(['\tContext.MajorVersion = ',MajorVersion], MajorVersionMsg), jpl_call(W, println, [MajorVersionMsg], _), jpl_call(Context, getMinorVersion, [], MinorVersion), atomic_list_concat(['\tContext.MinorVersion = ',MinorVersion], MinorVersionMsg), jpl_call(W, println, [MinorVersionMsg], _), jpl_call(Context, getServerInfo, [], ServerInfo), atomic_list_concat(['\tContext.ServerInfo = ',ServerInfo], ServerInfoMsg), jpl_call(W, println, [ServerInfoMsg], _), jpl_call(W, println, ['\nservlet config stuff:'], _), jpl_call(Config, getServletName, [], ServletName), ( ServletName == @(null) -> ServletNameAtom = null ; ServletNameAtom = ServletName ), atomic_list_concat(['\tConfig.ServletName = ',ServletNameAtom], ServletNameMsg), jpl_call(W, println, [ServletNameMsg], _), jpl_call(Config, getInitParameterNames, [], ConfigInitParameterNameEnum), jpl_enumeration_to_list(ConfigInitParameterNameEnum, ConfigInitParameterNames), length(ConfigInitParameterNames, NConfigInitParameterNames), atomic_list_concat(['\tConfig.InitParameters = ',NConfigInitParameterNames], NConfigInitParameterNamesMsg), jpl_call(W, println, [NConfigInitParameterNamesMsg], _), ( member(ConfigInitParameterName, ConfigInitParameterNames), jpl_call(Config, getInitParameter, [ConfigInitParameterName], ConfigInitParameter), atomic_list_concat(['\t\tConfig.InitParameter[',ConfigInitParameterName,'] = ',ConfigInitParameter], ConfigInitParameterMsg), jpl_call(W, println, [ConfigInitParameterMsg], _), fail ; true ), jpl_call(W, println, ['\nrequest stuff:'], _), jpl_call(Request, getAttributeNames, [], AttributeNameEnum), jpl_enumeration_to_list(AttributeNameEnum, AttributeNames), length(AttributeNames, NAttributeNames), atomic_list_concat(['\tRequest.Attributes = ',NAttributeNames], NAttributeNamesMsg), jpl_call(W, println, [NAttributeNamesMsg], _), ( member(AttributeName, AttributeNames), jpl_call(Request, getAttribute, [AttributeName], Attribute), jpl_call(Attribute, toString, [], AttributeString), atomic_list_concat(['\t\tRequest.Attribute[',AttributeName,'] = ',AttributeString], AttributeMsg), jpl_call(W, println, [AttributeMsg], _), fail ; true ), jpl_call(Request, getCharacterEncoding, [], CharacterEncoding), ( CharacterEncoding == @(null) -> CharacterEncodingAtom = '' ; CharacterEncodingAtom = CharacterEncoding ), atomic_list_concat(['\tRequest.CharacterEncoding',' = ',CharacterEncodingAtom], CharacterEncodingMsg), jpl_call(W, println, [CharacterEncodingMsg], _), jpl_call(Request, getContentLength, [], ContentLength), atomic_list_concat(['\tRequest.ContentLength',' = ',ContentLength], ContentLengthMsg), jpl_call(W, println, [ContentLengthMsg], _), jpl_call(Request, getContentType, [], ContentType), ( ContentType == @(null) -> ContentTypeAtom = '' ; ContentTypeAtom = ContentType ), atomic_list_concat(['\tRequest.ContentType',' = ',ContentTypeAtom], ContentTypeMsg), jpl_call(W, println, [ContentTypeMsg], _), jpl_call(Request, getParameterNames, [], ParameterNameEnum), jpl_enumeration_to_list(ParameterNameEnum, ParameterNames), length(ParameterNames, NParameterNames), atomic_list_concat(['\tRequest.Parameters = ',NParameterNames], NParameterNamesMsg), jpl_call(W, println, [NParameterNamesMsg], _), ( member(ParameterName, ParameterNames), jpl_call(Request, getParameter, [ParameterName], Parameter), atomic_list_concat(['\t\tRequest.Parameter[',ParameterName,'] = ',Parameter], ParameterMsg), jpl_call(W, println, [ParameterMsg], _), fail ; true ), jpl_call(Request, getProtocol, [], Protocol), atomic_list_concat(['\tRequest.Protocol',' = ',Protocol], ProtocolMsg), jpl_call(W, println, [ProtocolMsg], _), jpl_call(Request, getRemoteAddr, [], RemoteAddr), atomic_list_concat(['\tRequest.RemoteAddr',' = ',RemoteAddr], RemoteAddrMsg), jpl_call(W, println, [RemoteAddrMsg], _), jpl_call(Request, getRemoteHost, [], RemoteHost), atomic_list_concat(['\tRequest.RemoteHost',' = ',RemoteHost], RemoteHostMsg), jpl_call(W, println, [RemoteHostMsg], _), jpl_call(Request, getScheme, [], Scheme), atomic_list_concat(['\tRequest.Scheme',' = ',Scheme], SchemeMsg), jpl_call(W, println, [SchemeMsg], _), jpl_call(Request, getServerName, [], ServerName), atomic_list_concat(['\tRequest.ServerName',' = ',ServerName], ServerNameMsg), jpl_call(W, println, [ServerNameMsg], _), jpl_call(Request, getServerPort, [], ServerPort), atomic_list_concat(['\tRequest.ServerPort',' = ',ServerPort], ServerPortMsg), jpl_call(W, println, [ServerPortMsg], _), jpl_call(Request, isSecure, [], @(Secure)), atomic_list_concat(['\tRequest.Secure',' = ',Secure], SecureMsg), jpl_call(W, println, [SecureMsg], _), jpl_call(W, println, ['\nHTTP request stuff:'], _), jpl_call(Request, getAuthType, [], AuthType), ( AuthType == @(null) -> AuthTypeAtom = '' ; AuthTypeAtom = AuthType ), atomic_list_concat(['\tRequest.AuthType',' = ',AuthTypeAtom], AuthTypeMsg), jpl_call(W, println, [AuthTypeMsg], _), jpl_call(Request, getContextPath, [], ContextPath), ( ContextPath == @(null) -> ContextPathAtom = '' ; ContextPathAtom = ContextPath ), atomic_list_concat(['\tRequest.ContextPath',' = ',ContextPathAtom], ContextPathMsg), jpl_call(W, println, [ContextPathMsg], _), jpl_call(Request, getCookies, [], CookieArray), ( CookieArray == @(null) -> Cookies = [] ; jpl_array_to_list(CookieArray, Cookies) ), length(Cookies, NCookies), atomic_list_concat(['\tRequest.Cookies',' = ',NCookies], NCookiesMsg), jpl_call(W, println, [NCookiesMsg], _), ( nth0(NCookie, Cookies, Cookie), atomic_list_concat(['\t\tRequest.Cookie[',NCookie,']'], CookieMsg), jpl_call(W, println, [CookieMsg], _), jpl_call(Cookie, getName, [], CookieName), atomic_list_concat(['\t\t\tRequest.Cookie.Name = ',CookieName], CookieNameMsg), jpl_call(W, println, [CookieNameMsg], _), jpl_call(Cookie, getValue, [], CookieValue), atomic_list_concat(['\t\t\tRequest.Cookie.Value = ',CookieValue], CookieValueMsg), jpl_call(W, println, [CookieValueMsg], _), jpl_call(Cookie, getPath, [], CookiePath), ( CookiePath == @(null) -> CookiePathAtom = '' ; CookiePathAtom = CookiePath ), atomic_list_concat(['\t\t\tRequest.Cookie.Path = ',CookiePathAtom], CookiePathMsg), jpl_call(W, println, [CookiePathMsg], _), jpl_call(Cookie, getComment, [], CookieComment), ( CookieComment == @(null) -> CookieCommentAtom = '' ; CookieCommentAtom = CookieComment ), atomic_list_concat(['\t\t\tRequest.Cookie.Comment = ',CookieCommentAtom], CookieCommentMsg), jpl_call(W, println, [CookieCommentMsg], _), jpl_call(Cookie, getDomain, [], CookieDomain), ( CookieDomain == @(null) -> CookieDomainAtom = '' ; CookieDomainAtom = CookieDomain ), atomic_list_concat(['\t\t\tRequest.Cookie.Domain = ',CookieDomainAtom], CookieDomainMsg), jpl_call(W, println, [CookieDomainMsg], _), jpl_call(Cookie, getMaxAge, [], CookieMaxAge), atomic_list_concat(['\t\t\tRequest.Cookie.MaxAge = ',CookieMaxAge], CookieMaxAgeMsg), jpl_call(W, println, [CookieMaxAgeMsg], _), jpl_call(Cookie, getVersion, [], CookieVersion), atomic_list_concat(['\t\t\tRequest.Cookie.Version = ',CookieVersion], CookieVersionMsg), jpl_call(W, println, [CookieVersionMsg], _), jpl_call(Cookie, getSecure, [], @(CookieSecure)), atomic_list_concat(['\t\t\tRequest.Cookie.Secure',' = ',CookieSecure], CookieSecureMsg), jpl_call(W, println, [CookieSecureMsg], _), fail ; true ), jpl_call(W, println, ['</pre></body></html>'], _), true. %! jpl_servlet_byval(+MultiMap, -ContentType:atom, -Body:atom) % % This exemplifies an alternative (to jpl_servlet_byref) tactic % for implementing a servlet in Prolog; % most Request fields are extracted in Java before this is called, % and passed in as a multimap (a map, some of whose values are maps). jpl_servlet_byval(MM, CT, Ba) :- CT = 'text/html', multimap_to_atom(MM, MMa), atomic_list_concat(['<html><head></head><body>','<h2>jpl_servlet_byval/3 says:</h2><pre>', MMa,'</pre></body></html>'], Ba). %! is_pair(?T:term) % % I define a half-decent "pair" as having a ground key (any val) is_pair(Key-_Val) :- ground(Key). is_pairs(List) :- is_list(List), maplist(is_pair, List). multimap_to_atom(KVs, A) :- multimap_to_atom_1(KVs, '', Cz, []), flatten(Cz, Cs), atomic_list_concat(Cs, A). multimap_to_atom_1([], _, Cs, Cs). multimap_to_atom_1([K-V|KVs], T, Cs1, Cs0) :- Cs1 = [T,K,' = '|Cs2], ( is_list(V) -> ( is_pairs(V) -> V = V2 ; findall(N-Ve, nth1(N, V, Ve), V2) ), T2 = [' ',T], Cs2 = ['\n'|Cs2a], multimap_to_atom_1(V2, T2, Cs2a, Cs3) ; to_atom(V, AV), Cs2 = [AV,'\n'|Cs3] ), multimap_to_atom_1(KVs, T, Cs3, Cs0). %! to_atom(+Term, -Atom) % % unifies Atom with a printed representation of Term. % % @tbd Sort of quoting requirements and use format(codes(Codes),...) to_atom(Term, Atom) :- ( atom(Term) -> Atom = Term % avoid superfluous quotes ; term_to_atom(Term, Atom) ). %! jpl_pl_syntax(-Syntax:atom) % % unifies Syntax with 'traditional' or 'modern' according to the mode in which SWI Prolog 7.x was started jpl_pl_syntax(Syntax) :- ( [] == '[]' -> Syntax = traditional ; Syntax = modern ). /******************************* * MESSAGES * *******************************/ :- multifile prolog:error_message/3. prolog:error_message(java_exception(Ex)) --> ( { jpl_call(Ex, toString, [], Msg) } -> [ 'Java exception: ~w'-[Msg] ] ; [ 'Java exception: ~w'-[Ex] ] ). /******************************* * PATHS * *******************************/ :- multifile user:file_search_path/2. :- dynamic user:file_search_path/2. user:file_search_path(jar, swi(lib)). %! add_search_path(+Var, +Value) is det. % % Add value to the end of search-path Var. Value is normally a % directory. Does not change the environment if Dir is already in % Var. % % @param Value Path to add in OS notation. add_search_path(Path, Dir) :- ( getenv(Path, Old) -> ( current_prolog_flag(windows, true) -> Sep = (;) ; Sep = (:) ), ( atomic_list_concat(Current, Sep, Old), memberchk(Dir, Current) -> true % already present ; atomic_list_concat([Old, Sep, Dir], New), setenv(Path, New) ) ; setenv(Path, Dir) ). %! search_path_separator(-Sep:atom) % % Separator used the the OS in =PATH=, =LD_LIBRARY_PATH=, % =CLASSPATH=, etc. search_path_separator((;)) :- current_prolog_flag(windows, true), !. search_path_separator(:). /******************************* * LOAD THE JVM * *******************************/ %! check_java_environment % % Verify the Java environment. Preferably we would create, but % most Unix systems do not allow putenv("LD_LIBRARY_PATH=..." in % the current process. A suggesting found on the net is to modify % LD_LIBRARY_PATH right at startup and next execv() yourself, but % this doesn't work if we want to load Java on demand or if Prolog % itself is embedded in another application. % % So, after reading lots of pages on the web, I decided checking % the environment and producing a sensible error message is the % best we can do. % % Please not that Java2 doesn't require $CLASSPATH to be set, so % we do not check for that. check_java_environment :- current_prolog_flag(apple, true), !, print_message(error, jpl(run(jpl_config_dylib))). check_java_environment :- check_lib(java), check_lib(jvm). check_lib(Name) :- check_shared_object(Name, File, EnvVar, Absolute), ( Absolute == (-) -> ( current_prolog_flag(windows, true) -> A = '%', Z = '%' ; A = '$', Z = '' ), format(string(Msg), 'Please add directory holding ~w to ~w~w~w', [ File, A, EnvVar, Z ]), throw(error(existence_error(library, Name), context(_, Msg))) ; true ). %! check_shared_object(+Lib, -File, -EnvVar, -AbsFile) is semidet. % % True if AbsFile is existing .so/.dll file for Lib. % % @param File Full name of Lib (i.e. libjpl.so or jpl.dll) % @param EnvVar Search-path for shared objects. check_shared_object(Name, File, EnvVar, Absolute) :- libfile(Name, File), library_search_path(Path, EnvVar), ( member(Dir, Path), atomic_list_concat([Dir, File], /, Absolute), exists_file(Absolute) -> true ; Absolute = (-) ). libfile(Base, File) :- current_prolog_flag(unix, true), !, atom_concat(lib, Base, F0), current_prolog_flag(shared_object_extension, Ext), file_name_extension(F0, Ext, File). libfile(Base, File) :- current_prolog_flag(windows, true), !, current_prolog_flag(shared_object_extension, Ext), file_name_extension(Base, Ext, File). %! library_search_path(-Dirs:list, -EnvVar) is det. % % Dirs is the list of directories searched for shared % objects/DLLs. EnvVar is the variable in which the search path os % stored. library_search_path(Path, EnvVar) :- current_prolog_flag(shared_object_search_path, EnvVar), search_path_separator(Sep), ( getenv(EnvVar, Env), atomic_list_concat(Path, Sep, Env) -> true ; Path = [] ). %! add_jpl_to_classpath % % Add jpl.jar to =CLASSPATH= to facilitate callbacks add_jpl_to_classpath :- absolute_file_name(jar('jpl.jar'), [ access(read) ], JplJAR), !, ( getenv('CLASSPATH', Old) -> true ; Old = '.' ), ( current_prolog_flag(windows, true) -> Separator = ';' ; Separator = ':' ), atomic_list_concat([JplJAR, Old], Separator, New), setenv('CLASSPATH', New). %! libjpl(-Spec) is det. % % Return the spec for loading the JPL shared object. This shared % object must be called libjpl.so as the Java System.loadLibrary() % call used by jpl.jar adds the lib* prefix. libjpl(File) :- ( current_prolog_flag(unix, true) -> File = foreign(libjpl) ; File = foreign(jpl) ). %! add_jpl_to_ldpath(+JPL) is det. % % Add the directory holding jpl.so to search path for dynamic % libraries. This is needed for callback from Java. Java appears % to use its own search and the new value of the variable is % picked up correctly. add_jpl_to_ldpath(JPL) :- absolute_file_name(JPL, File, [ file_type(executable), file_errors(fail) ]), !, file_directory_name(File, Dir), prolog_to_os_filename(Dir, OsDir), current_prolog_flag(shared_object_search_path, PathVar), add_search_path(PathVar, OsDir). add_jpl_to_ldpath(_). %! add_java_to_ldpath is det. % % Adds the directories holding jvm.dll and java.dll to the %PATH%. % This appears to work on Windows. Unfortunately most Unix systems % appear to inspect the content of LD_LIBRARY_PATH only once. add_java_to_ldpath :- current_prolog_flag(windows, true), !, phrase(java_dirs, Extra), ( Extra \== [] -> print_message(informational, extend_ld_path(Extra)), maplist(win_add_dll_directory, Extra) ; true ). add_java_to_ldpath. %! java_dirs// is det. % % DCG that produces existing candidate directories holding % Java related DLLs java_dirs --> % JDK directories java_dir(jvm, '/jre/bin/client'), java_dir(jvm, '/jre/bin/server'), java_dir(java, '/jre/bin'), % JRE directories java_dir(jvm, '/bin/client'), java_dir(jvm, '/bin/server'), java_dir(java, '/bin'). java_dir(DLL, _SubPath) --> { check_shared_object(DLL, _, _Var, Abs), Abs \== (-) }, !. java_dir(_DLL, SubPath) --> { java_home(JavaHome), atom_concat(JavaHome, SubPath, SubDir), exists_directory(SubDir) }, !, [SubDir]. java_dir(_, _) --> []. %! java_home(-Home) is semidet % % Find the home location of Java. % % @param Home JAVA home in OS notation java_home_win_key( jre, 'HKEY_LOCAL_MACHINE/Software/JavaSoft/Java Runtime Environment'). java_home_win_key( jdk, 'HKEY_LOCAL_MACHINE/Software/JavaSoft/Java Development Kit'). java_home(Home) :- getenv('JAVA_HOME', Home), exists_directory(Home), !. :- if(current_prolog_flag(windows, true)). java_home(Home) :- java_home_win_key(_, Key0), % TBD: user can't choose jre or jdk catch(win_registry_get_value(Key0, 'CurrentVersion', Version), _, fail), atomic_list_concat([Key0, Version], /, Key), win_registry_get_value(Key, 'JavaHome', WinHome), prolog_to_os_filename(Home, WinHome), exists_directory(Home), !. :- else. java_home(Home) :- member(Home, [ '/usr/lib/java', '/usr/local/lib/java' ]), exists_directory(Home), !. :- endif. :- dynamic jvm_ready/0. :- volatile jvm_ready/0. setup_jvm :- jvm_ready, !. setup_jvm :- add_jpl_to_classpath, add_java_to_ldpath, libjpl(JPL), add_jpl_to_ldpath(JPL), catch(load_foreign_library(JPL), E, report_java_setup_problem(E)), assert(jvm_ready). report_java_setup_problem(E) :- print_message(error, E), check_java_environment. /******************************* * MESSAGES * *******************************/ :- multifile prolog:message//1. prolog:message(extend_ld_path(Dirs)) --> [ 'Extended DLL search path with'-[] ], dir_per_line(Dirs). prolog:message(jpl(run(Command))) --> [ 'Could not find libjpl.dylib dependencies.'-[], 'Please run `?- ~p.` to correct this'-[Command] ]. dir_per_line([]) --> []. dir_per_line([H|T]) --> [ nl, ' ~q'-[H] ], dir_per_line(T). % Initialize JVM :- initialization(setup_jvm, now). % must be ready before export
Prolog
(************************************************************************) (* * The Coq Proof Assistant / The Coq Development Team *) (* v * Copyright INRIA, CNRS and contributors *) (* <O___,, * (see version control and CREDITS file for authors & dates) *) (* \VV/ **************************************************************) (* // * This file is distributed under the terms of the *) (* * GNU Lesser General Public License Version 2.1 *) (* * (see LICENSE file for the text of the license) *) (************************************************************************) (** Compilation modes: - BuildVo : process statements and proofs (standard compilation), and also output an empty .vos file and .vok file - BuildVio : process statements, delay proofs in futures - Vio2Vo : load delayed proofs and process them - BuildVos : process statements, and discard proofs, and load .vos files for required libraries - BuildVok : like BuildVo, but load .vos files for required libraries When loading the .vos version of a required library, if the file exists but is empty, then we attempt to load the .vo version of that library. This trick is useful to avoid the need for the user to compile .vos version when an up to date .vo version is already available. *) type compilation_mode = BuildVo | BuildVio | Vio2Vo | BuildVos | BuildVok type t = { compilation_mode : compilation_mode ; compile_file: (string * bool) option (* bool is verbosity *) ; compilation_output_name : string option ; vio_checking : bool ; vio_tasks : (int list * string) list ; vio_files : string list ; vio_files_j : int ; echo : bool ; glob_out : Dumpglob.glob_output ; output_context : bool } val default : t val parse : string list -> t
OCaml
/* 编辑器边框颜色 */ /* 菜单颜色、上边框颜色 */ /* 菜单选中状态的颜色 */ /* input focus 时的颜色 */ /* 按钮颜色 */ /* tab selected 状态下的颜色 */ .wangEditor-container { position: relative; background-color: #fff; border: 1px solid #ccc; z-index: 1; width: 100%; } .wangEditor-container a:focus, .wangEditor-container button:focus { outline: none; } .wangEditor-container, .wangEditor-container * { margin: 0; padding: 0; box-sizing: border-box; line-height: 1; } .wangEditor-container img { border: none; } .wangEditor-container .clearfix:after { content: ''; display: table; clear: both; } .wangEditor-container .clearfix { *zoom: 1; } .wangEditor-container textarea { border: none; } .wangEditor-container textarea:focus { outline: none; } .wangEditor-container .height-tip { position: absolute; width: 3px; background-color: #ccc; left: 0; transition: top .2s; } .wangEditor-container .txt-toolbar { position: absolute; background-color: #fff; padding: 3px 5px; border-top: 2px solid #666; box-shadow: 1px 3px 3px #999; border-left: 1px\9 solid\9 #ccc\9; border-bottom: 1px\9 solid\9 #999\9; border-right: 1px\9 solid\9 #999\9; } .wangEditor-container .txt-toolbar .tip-triangle { display: block; position: absolute; width: 0; height: 0; border: 5px solid; border-color: transparent transparent #666 transparent; top: -12px; left: 50%; margin-left: -5px; } .wangEditor-container .txt-toolbar a { color: #666; display: inline-block; margin: 0 3px; padding: 5px; text-decoration: none; border-radius: 3px; } .wangEditor-container .txt-toolbar a:hover { background-color: #f1f1f1; } .wangEditor-container .img-drag-point { display: block; position: absolute; width: 12px; height: 12px; border-radius: 50%; cursor: se-resize; background-color: #666; margin-left: -6px; margin-top: -6px; box-shadow: 1px 1px 5px #999; } .wangEditor-container .wangEditor-upload-progress { position: absolute; height: 1px; background: #1e88e5; width: 0; display: none; -webkit-transition: width .5s; -o-transition: width .5s; transition: width .5s; } .wangEditor-fullscreen { position: fixed; top: 0; bottom: 0; left: 0; right: 0; } .wangEditor-container .code-textarea { resize: none; width: 100%; font-size: 14px; line-height: 1.5; font-family: 'Verdana'; color: #333; padding: 0 15px 0 15px; } .wangEditor-menu-container { width: 100%; border-bottom: 1px solid #f1f1f1; background-color: #fff; } .wangEditor-menu-container a { text-decoration: none; } .wangEditor-menu-container .menu-group { float: left; padding: 0 8px; border-right: 1px solid #f1f1f1; } .wangEditor-menu-container .menu-item { float: left; position: relative; text-align: center; height: 31px; width: 35px; } .wangEditor-menu-container .menu-item:hover { background-color: #f1f1f1; } .wangEditor-menu-container .menu-item a { display: block; text-align: center; color: #666; width: 100%; padding: 8px 0; font-size: 0.9em; } .wangEditor-menu-container .menu-item .selected { color: #1e88e5; } .wangEditor-menu-container .menu-item .active { background-color: #f1f1f1; } .wangEditor-menu-container .menu-item .disable { opacity: 0.5; filter: alpha(opacity=50); } .wangEditor-menu-container .menu-tip { display: block; position: absolute; z-index: 20; width: 60px; text-align: center; background-color: #666; color: #fff; padding: 7px 0; font-size: 12px; top: 100%; left: 50%; margin-left: -30px; border-radius: 2px; box-shadow: 1px 1px 5px #999; display: none; /*// 小三角 .tip-triangle { display: block; position: absolute; width: 0; height: 0; border:5px solid; border-color: transparent transparent @fore-color transparent; top: -10px; left: 50%; margin-left: -5px; }*/ } .wangEditor-menu-container .menu-tip-40 { width: 40px; margin-left: -20px; } .wangEditor-menu-container .menu-tip-50 { width: 50px; margin-left: -25px; } .wangEditor-menu-shadow { /*border-bottom-width: 0;*/ border-bottom: 1px\9 solid\9 #f1f1f1\9; box-shadow: 0 1px 3px #999; } .wangEditor-container .wangEditor-txt { width: 100%; text-align: left; padding: 15px; padding-top: 0; margin-top: 5px; overflow-y: auto; } .wangEditor-container .wangEditor-txt p, .wangEditor-container .wangEditor-txt h1, .wangEditor-container .wangEditor-txt h2, .wangEditor-container .wangEditor-txt h3, .wangEditor-container .wangEditor-txt h4, .wangEditor-container .wangEditor-txt h5 { margin: 10px 0; line-height: 1.8; } .wangEditor-container .wangEditor-txt p *, .wangEditor-container .wangEditor-txt h1 *, .wangEditor-container .wangEditor-txt h2 *, .wangEditor-container .wangEditor-txt h3 *, .wangEditor-container .wangEditor-txt h4 *, .wangEditor-container .wangEditor-txt h5 * { line-height: 1.8; } .wangEditor-container .wangEditor-txt ul, .wangEditor-container .wangEditor-txt ol { padding-left: 20px; } .wangEditor-container .wangEditor-txt img { cursor: pointer; } .wangEditor-container .wangEditor-txt img.clicked { box-shadow: 1px 1px 10px #999; } .wangEditor-container .wangEditor-txt table.clicked { box-shadow: 1px 1px 10px #999; } .wangEditor-container .wangEditor-txt pre code { line-height: 1.5; } .wangEditor-container .wangEditor-txt:focus { outline: none; } .wangEditor-container .wangEditor-txt blockquote { display: block; border-left: 8px solid #d0e5f2; padding: 5px 10px; margin: 10px 0; line-height: 1.4; font-size: 100%; background-color: #f1f1f1; } .wangEditor-container .wangEditor-txt table { border: none; border-collapse: collapse; } .wangEditor-container .wangEditor-txt table td, .wangEditor-container .wangEditor-txt table th { border: 1px solid #999; padding: 3px 5px; min-width: 50px; height: 20px; } .wangEditor-container .wangEditor-txt pre { border: 1px solid #ccc; background-color: #f8f8f8; padding: 10px; margin: 5px 0px; font-size: 0.8em; border-radius: 3px; } .wangEditor-drop-list { display: none; position: absolute; background-color: #fff; overflow: hidden; z-index: 10; transition: height .7s; border-top: 1px solid #f1f1f1; box-shadow: 1px 3px 3px #999; border-left: 1px\9 solid\9 #ccc\9; border-bottom: 1px\9 solid\9 #999\9; border-right: 1px\9 solid\9 #999\9; } .wangEditor-drop-list a { text-decoration: none; display: block; color: #666; padding: 3px 5px; } .wangEditor-drop-list a:hover { background-color: #f1f1f1; } .wangEditor-drop-panel, .txt-toolbar { display: none; position: absolute; padding: 10px; font-size: 14px; /*border: 1px\9 solid\9 #cccccc\9;*/ background-color: #fff; z-index: 10; border-top: 2px solid #666; box-shadow: 1px 3px 3px #999; border-left: 1px\9 solid\9 #ccc\9; border-bottom: 1px\9 solid\9 #999\9; border-right: 1px\9 solid\9 #999\9; } .wangEditor-drop-panel .tip-triangle, .txt-toolbar .tip-triangle { display: block; position: absolute; width: 0; height: 0; border: 5px solid; border-color: transparent transparent #666 transparent; top: -12px; left: 50%; margin-left: -5px; } .wangEditor-drop-panel a, .txt-toolbar a { text-decoration: none; } .wangEditor-drop-panel input[type=text], .txt-toolbar input[type=text] { border: none; border-bottom: 1px solid #ccc; font-size: 14px; height: 20px; color: #333; padding: 3px 0; } .wangEditor-drop-panel input[type=text]:focus, .txt-toolbar input[type=text]:focus { outline: none; border-bottom: 2px solid #1e88e5; } .wangEditor-drop-panel input[type=text].block, .txt-toolbar input[type=text].block { display: block; width: 100%; } .wangEditor-drop-panel textarea, .txt-toolbar textarea { border: 1px solid #ccc; } .wangEditor-drop-panel textarea:focus, .txt-toolbar textarea:focus { outline: none; border-color: #1e88e5; } .wangEditor-drop-panel button, .txt-toolbar button { font-size: 14px; color: #1e88e5; border: none; padding: 10px; background-color: #fff; cursor: pointer; border-radius: 3px; } .wangEditor-drop-panel button:hover, .txt-toolbar button:hover { background-color: #f1f1f1; } .wangEditor-drop-panel button:focus, .txt-toolbar button:focus { outline: none; } .wangEditor-drop-panel button.right, .txt-toolbar button.right { float: right; margin-left: 10px; } .wangEditor-drop-panel button.gray, .txt-toolbar button.gray { color: #999; } .wangEditor-drop-panel button.link, .txt-toolbar button.link { padding: 5px 10px; } .wangEditor-drop-panel button.link:hover, .txt-toolbar button.link:hover { background-color: #fff; text-decoration: underline; } .wangEditor-drop-panel .color-item, .txt-toolbar .color-item { display: block; float: left; width: 25px; height: 25px; text-align: center; padding: 2px; border-radius: 2px; text-decoration: underline; } .wangEditor-drop-panel .color-item:hover, .txt-toolbar .color-item:hover { background-color: #f1f1f1; } .wangEditor-drop-panel .list-menu-item, .txt-toolbar .list-menu-item { display: block; float: left; color: #333; padding: 5px 5px; border-radius: 2px; } .wangEditor-drop-panel .list-menu-item:hover, .txt-toolbar .list-menu-item:hover { background-color: #f1f1f1; } .wangEditor-drop-panel table.choose-table, .txt-toolbar table.choose-table { border: none; border-collapse: collapse; } .wangEditor-drop-panel table.choose-table td, .txt-toolbar table.choose-table td { border: 1px solid #ccc; width: 16px; height: 12px; } .wangEditor-drop-panel table.choose-table td.active, .txt-toolbar table.choose-table td.active { background-color: #ccc; opacity: .5; filter: alpha(opacity=50); } .wangEditor-drop-panel .panel-tab .tab-container, .txt-toolbar .panel-tab .tab-container { margin-bottom: 5px; } .wangEditor-drop-panel .panel-tab .tab-container a, .txt-toolbar .panel-tab .tab-container a { display: inline-block; color: #999; text-align: center; margin: 0 5px; padding: 5px 5px; } .wangEditor-drop-panel .panel-tab .tab-container a.selected, .txt-toolbar .panel-tab .tab-container a.selected { color: #1e88e5; border-bottom: 2px solid #1e88e5; } .wangEditor-drop-panel .panel-tab .content-container .content, .txt-toolbar .panel-tab .content-container .content { display: none; } .wangEditor-drop-panel .panel-tab .content-container .content a, .txt-toolbar .panel-tab .content-container .content a { display: inline-block; margin: 2px; padding: 2px; border-radius: 2px; } .wangEditor-drop-panel .panel-tab .content-container .content a:hover, .txt-toolbar .panel-tab .content-container .content a:hover { background-color: #f1f1f1; } .wangEditor-drop-panel .panel-tab .content-container .selected, .txt-toolbar .panel-tab .content-container .selected { display: block; } .wangEditor-drop-panel .panel-tab .emotion-content-container, .txt-toolbar .panel-tab .emotion-content-container { height: 200px; overflow-y: auto; } .wangEditor-drop-panel .upload-icon-container, .txt-toolbar .upload-icon-container { color: #ccc; text-align: center; margin: 20px 20px 15px 20px !important; padding: 5px !important; font-size: 65px; cursor: pointer; border: 2px dotted #f1f1f1; display: block !important; } .wangEditor-drop-panel .upload-icon-container:hover, .txt-toolbar .upload-icon-container:hover { color: #666; border-color: #ccc; } .wangEditor-modal { position: absolute; top: 50%; left: 50%; background-color: #fff; border-top: 1px solid #f1f1f1; box-shadow: 1px 3px 3px #999; border-top: 1px\9 solid\9 #ccc\9; border-left: 1px\9 solid\9 #ccc\9; border-bottom: 1px\9 solid\9 #999\9; border-right: 1px\9 solid\9 #999\9; } .wangEditor-modal .wangEditor-modal-close { position: absolute; top: 0; right: 0; margin-top: -25px; margin-right: -25px; font-size: 1.5em; color: #666; cursor: pointer; } @font-face { font-family: 'icomoon'; src: url('../fonts/icomoon.eot?-qdfu1s'); src: url('../fonts/icomoon.eot?#iefix-qdfu1s') format('embedded-opentype'), url('../fonts/icomoon.ttf?-qdfu1s') format('truetype'), url('../fonts/icomoon.woff?-qdfu1s') format('woff'), url('../fonts/icomoon.svg?-qdfu1s#icomoon') format('svg'); font-weight: normal; font-style: normal; } [class^="wangeditor-menu-img-"], [class*=" wangeditor-menu-img-"] { font-family: 'icomoon'; speak: none; font-style: normal; font-weight: normal; font-variant: normal; text-transform: none; line-height: 1; /* Better Font Rendering =========== */ -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; } .wangeditor-menu-img-link:before { content: "\e800"; } .wangeditor-menu-img-unlink:before { content: "\e801"; } .wangeditor-menu-img-code:before { content: "\e802"; } .wangeditor-menu-img-cancel:before { content: "\e803"; } .wangeditor-menu-img-terminal:before { content: "\e804"; } .wangeditor-menu-img-angle-down:before { content: "\e805"; } .wangeditor-menu-img-font:before { content: "\e806"; } .wangeditor-menu-img-bold:before { content: "\e807"; } .wangeditor-menu-img-italic:before { content: "\e808"; } .wangeditor-menu-img-header:before { content: "\e809"; } .wangeditor-menu-img-align-left:before { content: "\e80a"; } .wangeditor-menu-img-align-center:before { content: "\e80b"; } .wangeditor-menu-img-align-right:before { content: "\e80c"; } .wangeditor-menu-img-list-bullet:before { content: "\e80d"; } .wangeditor-menu-img-indent-left:before { content: "\e80e"; } .wangeditor-menu-img-indent-right:before { content: "\e80f"; } .wangeditor-menu-img-list-numbered:before { content: "\e810"; } .wangeditor-menu-img-underline:before { content: "\e811"; } .wangeditor-menu-img-table:before { content: "\e812"; } .wangeditor-menu-img-eraser:before { content: "\e813"; } .wangeditor-menu-img-text-height:before { content: "\e814"; } .wangeditor-menu-img-brush:before { content: "\e815"; } .wangeditor-menu-img-pencil:before { content: "\e816"; } .wangeditor-menu-img-minus:before { content: "\e817"; } .wangeditor-menu-img-picture:before { content: "\e818"; } .wangeditor-menu-img-file-image:before { content: "\e819"; } .wangeditor-menu-img-cw:before { content: "\e81a"; } .wangeditor-menu-img-ccw:before { content: "\e81b"; } .wangeditor-menu-img-music:before { content: "\e911"; } .wangeditor-menu-img-play:before { content: "\e912"; } .wangeditor-menu-img-location:before { content: "\e947"; } .wangeditor-menu-img-happy:before { content: "\e9df"; } .wangeditor-menu-img-sigma:before { content: "\ea67"; } .wangeditor-menu-img-enlarge2:before { content: "\e98b"; } .wangeditor-menu-img-shrink2:before { content: "\e98c"; } .wangeditor-menu-img-newspaper:before { content: "\e904"; } .wangeditor-menu-img-camera:before { content: "\e90f"; } .wangeditor-menu-img-video-camera:before { content: "\e914"; } .wangeditor-menu-img-file-zip:before { content: "\e92b"; } .wangeditor-menu-img-stack:before { content: "\e92e"; } .wangeditor-menu-img-credit-card:before { content: "\e93f"; } .wangeditor-menu-img-address-book:before { content: "\e944"; } .wangeditor-menu-img-envelop:before { content: "\e945"; } .wangeditor-menu-img-drawer:before { content: "\e95c"; } .wangeditor-menu-img-download:before { content: "\e960"; } .wangeditor-menu-img-upload:before { content: "\e961"; } .wangeditor-menu-img-lock:before { content: "\e98f"; } .wangeditor-menu-img-unlocked:before { content: "\e990"; } .wangeditor-menu-img-wrench:before { content: "\e991"; } .wangeditor-menu-img-eye:before { content: "\e9ce"; } .wangeditor-menu-img-eye-blocked:before { content: "\e9d1"; } .wangeditor-menu-img-command:before { content: "\ea4e"; } .wangeditor-menu-img-font2:before { content: "\ea5c"; } .wangeditor-menu-img-libreoffice:before { content: "\eade"; } .wangeditor-menu-img-quotes-left:before { content: "\e977"; } .wangeditor-menu-img-strikethrough:before { content: "\ea65"; } .wangeditor-menu-img-desktop:before { content: "\f108"; } .wangeditor-menu-img-tablet:before { content: "\f10a"; } .wangeditor-menu-img-search-plus:before { content: "\f00e"; } .wangeditor-menu-img-search-minus:before { content: "\f010"; } .wangeditor-menu-img-trash-o:before { content: "\f014"; } .wangeditor-menu-img-align-justify:before { content: "\f039"; } .wangeditor-menu-img-arrows-v:before { content: "\f07d"; } .wangeditor-menu-img-sigma2:before { content: "\ea68"; } .wangeditor-menu-img-omega:before { content: "\e900"; } .wangeditor-menu-img-cancel-circle:before { content: "\e901"; } .hljs { display: block; overflow-x: auto; padding: 0.5em; color: #333; background: #f8f8f8; -webkit-text-size-adjust: none; } .hljs-comment, .diff .hljs-header { color: #998; font-style: italic; } .hljs-keyword, .css .rule .hljs-keyword, .hljs-winutils, .nginx .hljs-title, .hljs-subst, .hljs-request, .hljs-status { color: #333; font-weight: bold; } .hljs-number, .hljs-hexcolor, .ruby .hljs-constant { color: #008080; } .hljs-string, .hljs-tag .hljs-value, .hljs-doctag, .tex .hljs-formula { color: #d14; } .hljs-title, .hljs-id, .scss .hljs-preprocessor { color: #900; font-weight: bold; } .hljs-list .hljs-keyword, .hljs-subst { font-weight: normal; } .hljs-class .hljs-title, .hljs-type, .vhdl .hljs-literal, .tex .hljs-command { color: #458; font-weight: bold; } .hljs-tag, .hljs-tag .hljs-title, .hljs-rule .hljs-property, .django .hljs-tag .hljs-keyword { color: #000080; font-weight: normal; } .hljs-attribute, .hljs-variable, .lisp .hljs-body, .hljs-name { color: #008080; } .hljs-regexp { color: #009926; } .hljs-symbol, .ruby .hljs-symbol .hljs-string, .lisp .hljs-keyword, .clojure .hljs-keyword, .scheme .hljs-keyword, .tex .hljs-special, .hljs-prompt { color: #990073; } .hljs-built_in { color: #0086b3; } .hljs-preprocessor, .hljs-pragma, .hljs-pi, .hljs-doctype, .hljs-shebang, .hljs-cdata { color: #999; font-weight: bold; } .hljs-deletion { background: #fdd; } .hljs-addition { background: #dfd; } .diff .hljs-change { background: #0086b3; } .hljs-chunk { color: #aaa; }
CSS
// file: clk_wiz_v3_6_tb.v // // (c) Copyright 2008 - 2011 Xilinx, Inc. All rights reserved. // // This file contains confidential and proprietary information // of Xilinx, Inc. and is protected under U.S. and // international copyright and other intellectual property // laws. // // DISCLAIMER // This disclaimer is not a license and does not grant any // rights to the materials distributed herewith. Except as // otherwise provided in a valid license issued to you by // Xilinx, and to the maximum extent permitted by applicable // law: (1) THESE MATERIALS ARE MADE AVAILABLE "AS IS" AND // WITH ALL FAULTS, AND XILINX HEREBY DISCLAIMS ALL WARRANTIES // AND CONDITIONS, EXPRESS, IMPLIED, OR STATUTORY, INCLUDING // BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY, NON- // INFRINGEMENT, OR FITNESS FOR ANY PARTICULAR PURPOSE; and // (2) Xilinx shall not be liable (whether in contract or tort, // including negligence, or under any other theory of // liability) for any loss or damage of any kind or nature // related to, arising under or in connection with these // materials, including for any direct, or any indirect, // special, incidental, or consequential loss or damage // (including loss of data, profits, goodwill, or any type of // loss or damage suffered as a result of any action brought // by a third party) even if such damage or loss was // reasonably foreseeable or Xilinx had been advised of the // possibility of the same. // // CRITICAL APPLICATIONS // Xilinx products are not designed or intended to be fail- // safe, or for use in any application requiring fail-safe // performance, such as life-support or safety devices or // systems, Class III medical devices, nuclear facilities, // applications related to the deployment of airbags, or any // other applications that could lead to death, personal // injury, or severe property or environmental damage // (individually and collectively, "Critical // Applications"). Customer assumes the sole risk and // liability of any use of Xilinx products in Critical // Applications, subject only to applicable laws and // regulations governing limitations on product liability. // // THIS COPYRIGHT NOTICE AND DISCLAIMER MUST BE RETAINED AS // PART OF THIS FILE AT ALL TIMES. // //---------------------------------------------------------------------------- // Clocking wizard demonstration testbench //---------------------------------------------------------------------------- // This demonstration testbench instantiates the example design for the // clocking wizard. Input clocks are toggled, which cause the clocking // network to lock and the counters to increment. //---------------------------------------------------------------------------- `timescale 1ps/1ps `define wait_lock @(posedge LOCKED) module clk_wiz_v3_6_tb (); // Clock to Q delay of 100ps localparam TCQ = 100; // timescale is 1ps/1ps localparam ONE_NS = 1000; localparam PHASE_ERR_MARGIN = 100; // 100ps // how many cycles to run localparam COUNT_PHASE = 1024; // we'll be using the period in many locations localparam time PER1 = 10.000*ONE_NS; localparam time PER1_1 = PER1/2; localparam time PER1_2 = PER1 - PER1/2; // Declare the input clock signals reg CLK_IN1 = 1; // The high bits of the sampling counters wire [3:1] COUNT; // Status and control signals reg RESET = 0; wire LOCKED; reg COUNTER_RESET = 0; wire [3:1] CLK_OUT; //Freq Check using the M & D values setting and actual Frequency generated // Input clock generation //------------------------------------ always begin CLK_IN1 = #PER1_1 ~CLK_IN1; CLK_IN1 = #PER1_2 ~CLK_IN1; end // Test sequence reg [15*8-1:0] test_phase = ""; initial begin // Set up any display statements using time to be readable $timeformat(-12, 2, "ps", 10); COUNTER_RESET = 0; test_phase = "reset"; RESET = 1; #(PER1*6); RESET = 0; test_phase = "wait lock"; `wait_lock; #(PER1*6); COUNTER_RESET = 1; #(PER1*20) COUNTER_RESET = 0; test_phase = "counting"; #(PER1*COUNT_PHASE); $display("SIMULATION PASSED"); $display("SYSTEM_CLOCK_COUNTER : %0d\n",$time/PER1); $finish; end // Instantiation of the example design containing the clock // network and sampling counters //--------------------------------------------------------- clk_wiz_v3_6_exdes #( .TCQ (TCQ) ) dut (// Clock in ports .CLK_IN1 (CLK_IN1), // Reset for logic in example design .COUNTER_RESET (COUNTER_RESET), .CLK_OUT (CLK_OUT), // High bits of the counters .COUNT (COUNT), // Status and control signals .RESET (RESET), .LOCKED (LOCKED)); // Freq Check endmodule
Coq
class CreateAssessmentScores < ActiveRecord::Migration def self.up create_table :assessment_scores do |t| t.integer :student_id t.integer :assessment_tool_id # t.integer :exam_id t.integer :grade_points t.timestamps end end def self.down drop_table :assessment_scores end end
Ruby
//---Example Use--- // charizard image1 ( // .pixel(), // .color(), // .width(), // .height() //); module charizard ( input wire [16:0] pixel, output wire [8:0] width, height, output reg [15:0] color ); reg [15:0] image [3248:0] = '{ 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'h1882, 16'h1882, 16'h1882, 16'h1882, 16'h1882, 16'h1882, 16'h1882, 16'h1882, 16'h1882, 16'h1882, 16'h1882, 16'h1882, 16'h1882, 16'h1882, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'h1882, 16'h1882, 16'h1882, 16'h1882, 16'h1882, 16'h1882, 16'h1882, 16'h1882, 16'h1882, 16'hd286, 16'hd286, 16'hd286, 16'hd286, 16'hd286, 16'hd286, 16'hd286, 16'hd286, 16'hd286, 16'hd286, 16'hd286, 16'hd286, 16'hd286, 16'hd286, 16'h1882, 16'h1882, 16'h1882, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'h1882, 16'h1882, 16'h1882, 16'h1882, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hd286, 16'hd286, 16'hd286, 16'hd286, 16'hd286, 16'h1882, 16'h1882, 16'h1882, 16'h1882, 16'h1882, 16'h1882, 16'h1882, 16'h1882, 16'h1882, 16'h1882, 16'h1882, 16'h1882, 16'h1882, 16'h1882, 16'h1882, 16'h1882, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'h1882, 16'h1882, 16'h1882, 16'hf5a, 16'hf5a, 16'hf5a, 16'h1882, 16'h1882, 16'hf5a, 16'hf5a, 16'hf5a, 16'hd286, 16'hd286, 16'h1882, 16'h1882, 16'h1882, 16'h1882, 16'h1882, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hf5a, 16'hf5a, 16'hf5a, 16'h1882, 16'h1882, 16'h1882, 16'h1882, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'h1882, 16'h1882, 16'hffff, 16'hd286, 16'hf5a, 16'hf5a, 16'hf5a, 16'h1882, 16'hd286, 16'hffff, 16'h1882, 16'h1882, 16'h1882, 16'h1882, 16'h1882, 16'hd286, 16'hd286, 16'hd286, 16'hd286, 16'hf5a, 16'hf5a, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hf5a, 16'hf5a, 16'hf5a, 16'h1882, 16'h1882, 16'h1882, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'h1882, 16'hffff, 16'hffff, 16'hf5a, 16'hd286, 16'hd286, 16'hd286, 16'hd286, 16'hd286, 16'h1882, 16'hf5a, 16'hffff, 16'h1882, 16'h1882, 16'hd286, 16'hd286, 16'hd286, 16'hd286, 16'hd286, 16'hd286, 16'hd286, 16'hd286, 16'hd286, 16'hd286, 16'hd286, 16'hd286, 16'hd286, 16'hf5a, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hf5a, 16'h1882, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'h1882, 16'h1882, 16'h1882, 16'h1882, 16'hd286, 16'hd286, 16'hd286, 16'hd286, 16'hd286, 16'h1882, 16'hf5a, 16'hffff, 16'h1882, 16'h1882, 16'h1882, 16'h1882, 16'h1882, 16'h1882, 16'h1882, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hd286, 16'hd286, 16'hd286, 16'hd286, 16'hffff, 16'hffff, 16'hffff, 16'h1882, 16'hd286, 16'h1882, 16'h1882, 16'h1882, 16'h1882, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'h1882, 16'h1882, 16'hd286, 16'hd286, 16'hd286, 16'hd286, 16'h1882, 16'hf5a, 16'hffff, 16'h1882, 16'h1882, 16'hd286, 16'hf5a, 16'hf5a, 16'hd286, 16'h1882, 16'h1882, 16'h1882, 16'hf5a, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hd286, 16'hd286, 16'hffff, 16'h1882, 16'h1882, 16'hd286, 16'hd286, 16'hf5a, 16'h1882, 16'hd286, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hd286, 16'h1882, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'h1882, 16'h1882, 16'h1882, 16'hd286, 16'hd286, 16'h1882, 16'hf5a, 16'hf5a, 16'h1882, 16'h1882, 16'hf5a, 16'hffff, 16'hffff, 16'hffff, 16'h1882, 16'hf5a, 16'h1882, 16'hf5a, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hd286, 16'hd286, 16'hf5a, 16'h1882, 16'h1882, 16'h1882, 16'h1882, 16'h1882, 16'h1882, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hd286, 16'hffff, 16'hffff, 16'hd286, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'h1882, 16'h1882, 16'h1882, 16'h1882, 16'hd286, 16'hf5a, 16'hf5a, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'h1882, 16'hf5a, 16'hffff, 16'h1882, 16'hf5a, 16'hf5a, 16'hf5a, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'h1882, 16'hf5a, 16'hf5a, 16'hf5a, 16'h1882, 16'hd286, 16'hf5a, 16'hf5a, 16'h1882, 16'h1882, 16'hd286, 16'hffff, 16'hffff, 16'hffff, 16'hd286, 16'h1882, 16'hf5a, 16'h1882, 16'h1882, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'h1882, 16'h1882, 16'h1882, 16'h1882, 16'h1882, 16'hd286, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'h1882, 16'h1882, 16'hffff, 16'h1882, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'h1882, 16'h1882, 16'hf5a, 16'hf5a, 16'hf5a, 16'hd286, 16'hd286, 16'h1882, 16'hd286, 16'h1882, 16'hffff, 16'hffff, 16'hffff, 16'h1882, 16'hffff, 16'hffff, 16'h1882, 16'h1882, 16'h1882, 16'hffff, 16'h1882, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'h1882, 16'h1882, 16'h1882, 16'h1882, 16'hd286, 16'hf5a, 16'hf5a, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'h1882, 16'hd286, 16'h1882, 16'hf5a, 16'h1882, 16'hf5a, 16'hf5a, 16'h1882, 16'h1882, 16'hd286, 16'hd286, 16'hd286, 16'hd286, 16'hd286, 16'hd286, 16'hd286, 16'h1882, 16'h1882, 16'hd286, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'h1882, 16'hffff, 16'h1882, 16'hffff, 16'h1882, 16'hf5a, 16'h1882, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'h1882, 16'hd286, 16'h1882, 16'hd286, 16'hf5a, 16'hf5a, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'h1882, 16'hf5a, 16'hf5a, 16'hf5a, 16'hd286, 16'h1882, 16'h1882, 16'h1882, 16'h1882, 16'hd286, 16'hd286, 16'hd286, 16'hd286, 16'hd286, 16'h1882, 16'h1882, 16'hd286, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hffff, 16'hffff, 16'h1882, 16'h1882, 16'hffff, 16'h1882, 16'hf5a, 16'h1882, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'h1882, 16'hd286, 16'hd286, 16'h1882, 16'hd286, 16'hf5a, 16'hf5a, 16'hf5a, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hf5a, 16'hf5a, 16'hf5a, 16'hffff, 16'hf5a, 16'hf5a, 16'hffff, 16'hffff, 16'hffff, 16'hd286, 16'h1882, 16'h1882, 16'h1882, 16'h1882, 16'hd286, 16'hd286, 16'h1882, 16'h1882, 16'h1882, 16'hd286, 16'hd286, 16'hd286, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hffff, 16'h1882, 16'hffff, 16'h1882, 16'hf5a, 16'h1882, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'h1882, 16'hd286, 16'hd286, 16'h1882, 16'hd286, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hffff, 16'hffff, 16'hf5a, 16'hd286, 16'hd286, 16'hd286, 16'hf5a, 16'hffff, 16'hf5a, 16'hf5a, 16'hffff, 16'hffff, 16'hffff, 16'hf5a, 16'h1882, 16'h1882, 16'h1882, 16'h1882, 16'h1882, 16'h1882, 16'h1882, 16'h1882, 16'h1882, 16'hd286, 16'hd286, 16'hd286, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hd286, 16'hf5a, 16'hffff, 16'h1882, 16'h1882, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'h1882, 16'h1882, 16'h1882, 16'h1882, 16'h1882, 16'h1882, 16'h1882, 16'h1882, 16'hd286, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hd286, 16'hd286, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hd286, 16'hffff, 16'hffff, 16'h1882, 16'h1882, 16'h1882, 16'hd286, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'h1882, 16'h1882, 16'hd286, 16'hd286, 16'hd286, 16'hf5a, 16'hf5a, 16'hf5a, 16'hd286, 16'hf5a, 16'hf5a, 16'hf5a, 16'h1882, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'h1882, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hd286, 16'hd286, 16'hd286, 16'hd286, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hd286, 16'hffff, 16'h1882, 16'hd286, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'h1882, 16'hd286, 16'hd286, 16'hd286, 16'hf5a, 16'hf5a, 16'hf5a, 16'hd286, 16'hd286, 16'hd286, 16'h1882, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'h1882, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'h1882, 16'h1882, 16'h1882, 16'h1882, 16'h1882, 16'h1882, 16'h1882, 16'h1882, 16'hd286, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hd286, 16'h1882, 16'h1882, 16'hd286, 16'hd286, 16'hd286, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hffff, 16'h1882, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'h1882, 16'hd286, 16'hd286, 16'hd286, 16'hf5a, 16'hd286, 16'hd286, 16'hd286, 16'hd286, 16'h1882, 16'hffff, 16'hffff, 16'hffff, 16'h1882, 16'hffff, 16'h1882, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'h1882, 16'hd286, 16'hd286, 16'hd286, 16'h1882, 16'hd286, 16'hd286, 16'hd286, 16'hf5a, 16'hd286, 16'h1882, 16'h1882, 16'hd286, 16'h1882, 16'hd286, 16'hd286, 16'hd286, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hd286, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'h1882, 16'hd286, 16'hd286, 16'hd286, 16'hd286, 16'hd286, 16'hd286, 16'hd286, 16'h1882, 16'hffff, 16'hffff, 16'hffff, 16'h1882, 16'hf5a, 16'hffff, 16'h1882, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'h1882, 16'hd286, 16'hd286, 16'hd286, 16'hd286, 16'h1882, 16'hd286, 16'hd286, 16'hd286, 16'h1882, 16'hf5a, 16'h1882, 16'h1882, 16'h1882, 16'hd286, 16'hd286, 16'hd286, 16'hf5a, 16'hf5a, 16'hd286, 16'h1882, 16'hf5a, 16'h1882, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hf5a, 16'h1882, 16'hd286, 16'hd286, 16'hd286, 16'hd286, 16'h1882, 16'h1882, 16'h1882, 16'hffff, 16'hffff, 16'hffff, 16'h1882, 16'hf5a, 16'hffff, 16'hffff, 16'h1882, 16'h1882, 16'h1882, 16'h1882, 16'h1882, 16'h1882, 16'hd286, 16'h1882, 16'hd286, 16'hd286, 16'hd286, 16'hd286, 16'h1882, 16'hd286, 16'h1882, 16'hf5a, 16'hffff, 16'hffff, 16'hffff, 16'h1882, 16'hd286, 16'hd286, 16'hd286, 16'hd286, 16'hd286, 16'hd286, 16'hd286, 16'hd286, 16'h1882, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hf5a, 16'h1882, 16'h1882, 16'hd286, 16'hd286, 16'h1882, 16'h1882, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'h1882, 16'hf5a, 16'hffff, 16'hd286, 16'hd286, 16'hd286, 16'hd286, 16'hd286, 16'hd286, 16'hd286, 16'hd286, 16'h1882, 16'hd286, 16'hd286, 16'hf5a, 16'hf5a, 16'hd286, 16'hd286, 16'h1882, 16'h1882, 16'h1882, 16'h1882, 16'hd286, 16'h1882, 16'h1882, 16'h1882, 16'h1882, 16'hd286, 16'hd286, 16'hd286, 16'h1882, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hf5a, 16'h1882, 16'h1882, 16'h1882, 16'hd286, 16'h1882, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'h1882, 16'hf5a, 16'hd286, 16'hd286, 16'hd286, 16'hd286, 16'hd286, 16'hd286, 16'hd286, 16'hd286, 16'hd286, 16'h1882, 16'h1882, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'h1882, 16'h1882, 16'h1882, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hf5a, 16'hf5a, 16'h1882, 16'h1882, 16'h1882, 16'hd286, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'h1882, 16'hd286, 16'hd286, 16'hd286, 16'hd286, 16'hd286, 16'hd286, 16'hd286, 16'hd286, 16'h1882, 16'h1882, 16'hf5a, 16'hf5a, 16'h1882, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hd286, 16'h1882, 16'hd286, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hf5a, 16'hf5a, 16'h1882, 16'h1882, 16'h1882, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'h1882, 16'hd286, 16'hd286, 16'hd286, 16'hd286, 16'hd286, 16'h1882, 16'h1882, 16'h1882, 16'hd286, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'h1882, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'h1882, 16'hf5a, 16'hffff, 16'hffff, 16'hd286, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hf5a, 16'hf5a, 16'hf5a, 16'h1882, 16'h1882, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'h1882, 16'hd286, 16'h1882, 16'h1882, 16'h1882, 16'hd286, 16'hd286, 16'hd286, 16'hd286, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'h1882, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'h1882, 16'hf5a, 16'hf5a, 16'h1882, 16'h1882, 16'hd286, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hf5a, 16'hf5a, 16'hf5a, 16'h1882, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'h1882, 16'hd286, 16'h1882, 16'hd286, 16'hd286, 16'hd286, 16'hd286, 16'hd286, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hffff, 16'hf5a, 16'h1882, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hd286, 16'hf5a, 16'hd286, 16'h1882, 16'hf5a, 16'hffff, 16'hffff, 16'hd286, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hf5a, 16'hf5a, 16'hf5a, 16'h1882, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'h1882, 16'hd286, 16'hd286, 16'h1882, 16'hd286, 16'hd286, 16'hd286, 16'hd286, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hffff, 16'hffff, 16'hf5a, 16'h1882, 16'hf5a, 16'hf5a, 16'hf5a, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'h1882, 16'hf5a, 16'hf5a, 16'hd286, 16'hf5a, 16'hf5a, 16'hf5a, 16'h1882, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hf5a, 16'hf5a, 16'hf5a, 16'hd286, 16'h1882, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'h1882, 16'hd286, 16'hd286, 16'h1882, 16'hd286, 16'hd286, 16'hd286, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hffff, 16'hffff, 16'hf5a, 16'h1882, 16'hf5a, 16'hf5a, 16'hd286, 16'h1882, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'h1882, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hd286, 16'h1882, 16'hd286, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hd286, 16'h1882, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'h1882, 16'hd286, 16'hd286, 16'h1882, 16'hd286, 16'hd286, 16'hd286, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hffff, 16'hffff, 16'hf5a, 16'h1882, 16'hf5a, 16'hffff, 16'hffff, 16'hd286, 16'h1882, 16'hffff, 16'hffff, 16'hffff, 16'h1882, 16'hd286, 16'hf5a, 16'hffff, 16'hf5a, 16'hf5a, 16'hf5a, 16'h1882, 16'hf5a, 16'hffff, 16'h1882, 16'hffff, 16'hd286, 16'h1882, 16'h1882, 16'hd286, 16'hf5a, 16'hf5a, 16'hd286, 16'hd286, 16'h1882, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'h1882, 16'hd286, 16'hd286, 16'h1882, 16'hd286, 16'hd286, 16'hd286, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hffff, 16'hffff, 16'hffff, 16'h1882, 16'hf5a, 16'hf5a, 16'hffff, 16'hffff, 16'hffff, 16'hd286, 16'h1882, 16'hd286, 16'hf5a, 16'hffff, 16'hffff, 16'hffff, 16'hd286, 16'hf5a, 16'hf5a, 16'h1882, 16'hf5a, 16'hf5a, 16'h1882, 16'h1882, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'h1882, 16'hd286, 16'hd286, 16'h1882, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'h1882, 16'hd286, 16'hd286, 16'hd286, 16'h1882, 16'hd286, 16'hd286, 16'hd286, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hffff, 16'hffff, 16'hffff, 16'hf5a, 16'h1882, 16'hf5a, 16'hf5a, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hf5a, 16'hd286, 16'hd286, 16'hf5a, 16'hd286, 16'h1882, 16'hd286, 16'hf5a, 16'hf5a, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hd286, 16'h1882, 16'h1882, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'h1882, 16'hd286, 16'hd286, 16'hd286, 16'h1882, 16'hd286, 16'hd286, 16'hd286, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'h1882, 16'hf5a, 16'hf5a, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hf5a, 16'hd286, 16'hd286, 16'h1882, 16'hd286, 16'hd286, 16'hf5a, 16'hf5a, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'h1882, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'h1882, 16'hd286, 16'hd286, 16'hd286, 16'h1882, 16'hd286, 16'hd286, 16'hd286, 16'hf5a, 16'hf5a, 16'hf5a, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hf5a, 16'h1882, 16'hf5a, 16'hf5a, 16'hf5a, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hf5a, 16'hf5a, 16'hd286, 16'hd286, 16'h1882, 16'hd286, 16'hf5a, 16'hf5a, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hd286, 16'h1882, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'h1882, 16'hd286, 16'hd286, 16'hd286, 16'hd286, 16'h1882, 16'h1882, 16'hf5a, 16'hd286, 16'hd286, 16'hf5a, 16'hf5a, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'h1882, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hd286, 16'hd286, 16'h1882, 16'hd286, 16'hf5a, 16'hf5a, 16'hf5a, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'h1882, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'h1882, 16'hd286, 16'hd286, 16'hd286, 16'hd286, 16'hd286, 16'h1882, 16'hf5a, 16'hf5a, 16'hd286, 16'hd286, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hf5a, 16'h1882, 16'hd286, 16'hd286, 16'hf5a, 16'hf5a, 16'hf5a, 16'hd286, 16'hd286, 16'hd286, 16'h1882, 16'hd286, 16'hf5a, 16'hf5a, 16'hf5a, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hd286, 16'h1882, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'h1882, 16'hd286, 16'hd286, 16'hd286, 16'hd286, 16'hd286, 16'h1882, 16'hf5a, 16'hf5a, 16'hf5a, 16'hd286, 16'hd286, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hf5a, 16'h1882, 16'h1882, 16'h1882, 16'hd286, 16'hd286, 16'hd286, 16'hd286, 16'h1882, 16'hd286, 16'hd286, 16'hd286, 16'hf5a, 16'hf5a, 16'hf5a, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'h1882, 16'h1882, 16'hd286, 16'hffff, 16'h1882, 16'h1882, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'h1882, 16'hd286, 16'hd286, 16'hd286, 16'hd286, 16'hd286, 16'h1882, 16'h1882, 16'hf5a, 16'hf5a, 16'hf5a, 16'hd286, 16'hd286, 16'hd286, 16'hffff, 16'hffff, 16'hf5a, 16'hf5a, 16'hd286, 16'h1882, 16'h1882, 16'h1882, 16'h1882, 16'h1882, 16'hd286, 16'hd286, 16'hd286, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'h1882, 16'h1882, 16'hffff, 16'hffff, 16'h1882, 16'hffff, 16'hffff, 16'hd286, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'h1882, 16'hd286, 16'hd286, 16'hd286, 16'hd286, 16'hd286, 16'hd286, 16'h1882, 16'h1882, 16'h1882, 16'hf5a, 16'hf5a, 16'hf5a, 16'hd286, 16'hd286, 16'hd286, 16'hd286, 16'hf5a, 16'hd286, 16'h1882, 16'h1882, 16'h1882, 16'h1882, 16'h1882, 16'hd286, 16'hd286, 16'hd286, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hffff, 16'hffff, 16'hffff, 16'hf5a, 16'hffff, 16'hffff, 16'hffff, 16'h1882, 16'hf5a, 16'hffff, 16'h1882, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'h1882, 16'hd286, 16'hd286, 16'hd286, 16'hd286, 16'hd286, 16'hd286, 16'hd286, 16'hd286, 16'h1882, 16'h1882, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hd286, 16'hd286, 16'h1882, 16'h1882, 16'h1882, 16'h1882, 16'h1882, 16'hd286, 16'hd286, 16'hd286, 16'hd286, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hffff, 16'hf5a, 16'hf5a, 16'hf5a, 16'hffff, 16'hd286, 16'hf5a, 16'hf5a, 16'h1882, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'h1882, 16'hd286, 16'hd286, 16'hd286, 16'hd286, 16'hd286, 16'hd286, 16'hd286, 16'hd286, 16'hd286, 16'h1882, 16'h1882, 16'hf5a, 16'hf5a, 16'hd286, 16'hd286, 16'h1882, 16'h1882, 16'h1882, 16'h1882, 16'hd286, 16'hd286, 16'h1882, 16'hd286, 16'hd286, 16'hd286, 16'hd286, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hd286, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'h1882, 16'hf5a, 16'hd286, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'h1882, 16'hd286, 16'hd286, 16'hd286, 16'hd286, 16'hd286, 16'hd286, 16'hd286, 16'hd286, 16'hd286, 16'hd286, 16'h1882, 16'h1882, 16'h1882, 16'h1882, 16'h1882, 16'h1882, 16'h1882, 16'hf5a, 16'hd286, 16'hd286, 16'h1882, 16'h1882, 16'hd286, 16'hd286, 16'hd286, 16'hd286, 16'hd286, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hd286, 16'hd286, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hd286, 16'h1882, 16'hffff, 16'hffff, 16'hffff, 16'hf5a, 16'hf5a, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hf5a, 16'hf5a, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'h1882, 16'h1882, 16'hd286, 16'hd286, 16'hd286, 16'hd286, 16'hd286, 16'hd286, 16'hd286, 16'hd286, 16'hd286, 16'hd286, 16'hd286, 16'h1882, 16'h1882, 16'h1882, 16'h1882, 16'hf5a, 16'hd286, 16'hd286, 16'hd286, 16'h1882, 16'h1882, 16'h1882, 16'hd286, 16'hd286, 16'hd286, 16'hd286, 16'hd286, 16'hd286, 16'hf5a, 16'hd286, 16'h1882, 16'hd286, 16'hf5a, 16'hf5a, 16'hd286, 16'hffff, 16'hffff, 16'hd286, 16'hffff, 16'hffff, 16'hf5a, 16'hf5a, 16'hf5a, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hf5a, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'h1882, 16'h1882, 16'hd286, 16'hd286, 16'hd286, 16'hd286, 16'hd286, 16'hd286, 16'hd286, 16'hd286, 16'hd286, 16'hd286, 16'hd286, 16'h1882, 16'hf5a, 16'hf5a, 16'hd286, 16'hd286, 16'hd286, 16'h1882, 16'h1882, 16'h1882, 16'h1882, 16'h1882, 16'h1882, 16'hd286, 16'hd286, 16'hd286, 16'hd286, 16'h1882, 16'h1882, 16'hd286, 16'hd286, 16'hd286, 16'h1882, 16'hf5a, 16'hffff, 16'h1882, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'h1882, 16'h1882, 16'hd286, 16'hd286, 16'hd286, 16'hd286, 16'hd286, 16'hd286, 16'hd286, 16'hd286, 16'h1882, 16'hf5a, 16'hf5a, 16'hf5a, 16'hd286, 16'hd286, 16'hd286, 16'h1882, 16'h1882, 16'h1882, 16'h1882, 16'h1882, 16'h1882, 16'h1882, 16'h1882, 16'h1882, 16'h1882, 16'h1882, 16'h1882, 16'hd286, 16'hd286, 16'hd286, 16'h1882, 16'hd286, 16'hf5a, 16'h1882, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hffff, 16'h1882, 16'h1882, 16'h1882, 16'hd286, 16'hd286, 16'hd286, 16'hd286, 16'h1882, 16'hd286, 16'hf5a, 16'hf5a, 16'hd286, 16'hd286, 16'hd286, 16'h1882, 16'h1882, 16'h1882, 16'h1882, 16'h1882, 16'h1882, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'h1882, 16'hd286, 16'hd286, 16'h1882, 16'h1882, 16'hd286, 16'hd286, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hf5a, 16'hf5a, 16'hf5a, 16'hffff, 16'hffff, 16'hffff, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hffff, 16'hffff, 16'h1882, 16'h1882, 16'h1882, 16'h1882, 16'hd286, 16'hf5a, 16'hf5a, 16'hf5a, 16'hd286, 16'hd286, 16'hd286, 16'h1882, 16'h1882, 16'h1882, 16'h1882, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'h1882, 16'h1882, 16'hffff, 16'hffff, 16'h1882, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hd286, 16'hd286, 16'hd286, 16'hd286, 16'hf5a, 16'hf5a, 16'hd286, 16'hd286, 16'hd286, 16'hd286, 16'h1882, 16'h1882, 16'h1882, 16'h1882, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'h1882, 16'hf5a, 16'hffff, 16'hffff, 16'hd286, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hd286, 16'hd286, 16'hd286, 16'hd286, 16'hd286, 16'hd286, 16'hf5a, 16'hf5a, 16'hd286, 16'hd286, 16'hd286, 16'h1882, 16'h1882, 16'h1882, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hd286, 16'hd286, 16'hf5a, 16'hffff, 16'h1882, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hd286, 16'hd286, 16'hd286, 16'hd286, 16'hd286, 16'hd286, 16'hd286, 16'hd286, 16'hd286, 16'hd286, 16'h1882, 16'h1882, 16'h1882, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'h1882, 16'hd286, 16'hf5a, 16'hd286, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hd286, 16'hd286, 16'hd286, 16'hd286, 16'hd286, 16'hd286, 16'hd286, 16'hd286, 16'hd286, 16'h1882, 16'h1882, 16'h1882, 16'h1882, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'h1882, 16'hd286, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hf5a, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff, 16'hffff }; // assign width = 57; // assign height = 57; assign width = 56; //for 0 indexed width assign height = 56; //for 0 indexed Height assign color = image[pixel]; endmodule
Coq
package engine import ( "fmt" "reflect" "strings" "sync" "time" "github.com/accurateproject/accurate/cache2go" "github.com/accurateproject/accurate/config" "github.com/accurateproject/accurate/utils" "github.com/accurateproject/rpcclient" ) type ResourceUsage struct { ID string // Unique identifier of this resourceUsage, Eg: FreeSWITCH UUID UsageTime time.Time // So we can expire it later UsageUnits float64 // Number of units used } // ResourceLimit represents a limit imposed for accessing a resource (eg: new calls) type ResourceLimit struct { ID string // Identifier of this limit Filters []*RequestFilter // Filters for the request ActivationTime time.Time // Time when this limit becomes active ExpiryTime time.Time Weight float64 // Weight to sort the ResourceLimits Limit float64 // Limit value ActionTriggers ActionTriggers // Thresholds to check after changing Limit UsageTTL time.Duration // Expire usage after this duration Usage map[string]*ResourceUsage // Keep a record of usage, bounded with timestamps so we can expire too long records usageCounter float64 // internal counter aggregating real usage of ResourceLimit } func (rl *ResourceLimit) removeExpiredUnits() { for ruID, rv := range rl.Usage { if time.Now().Sub(rv.UsageTime) <= rl.UsageTTL { continue // not expired } delete(rl.Usage, ruID) rl.usageCounter -= rv.UsageUnits } } func (rl *ResourceLimit) UsedUnits() float64 { if rl.UsageTTL != 0 { rl.removeExpiredUnits() } return rl.usageCounter } func (rl *ResourceLimit) RecordUsage(ru *ResourceUsage) error { if _, hasID := rl.Usage[ru.ID]; hasID { return fmt.Errorf("Duplicate resource usage with id: %s", ru.ID) } rl.Usage[ru.ID] = ru rl.usageCounter += ru.UsageUnits return nil } func (rl *ResourceLimit) RemoveUsage(ruID string) error { ru, hasIt := rl.Usage[ruID] if !hasIt { return fmt.Errorf("Cannot find usage record with id: %s", ruID) } delete(rl.Usage, ru.ID) rl.usageCounter -= ru.UsageUnits return nil } // Pas the config as a whole so we can ask access concurrently func NewResourceLimiterService(cfg *config.Config, dataDB AccountingStorage, cdrStatS rpcclient.RpcClientConnection) (*ResourceLimiterService, error) { if cdrStatS != nil && reflect.ValueOf(cdrStatS).IsNil() { cdrStatS = nil } rls := &ResourceLimiterService{stringIndexes: make(map[string]map[string]utils.StringMap), dataDB: dataDB, cdrStatS: cdrStatS} return rls, nil } // ResourcesLimiter is the service handling channel limits type ResourceLimiterService struct { sync.RWMutex stringIndexes map[string]map[string]utils.StringMap // map[fieldName]map[fieldValue]utils.StringMap[resourceID] dataDB AccountingStorage // So we can load the data in cache and index it cdrStatS rpcclient.RpcClientConnection } // Index cached ResourceLimits with MetaString filter types func (rls *ResourceLimiterService) indexStringFilters(rlIDs []string) error { utils.Logger.Info("<RLs> Start indexing string filters") newStringIndexes := make(map[string]map[string]utils.StringMap) // Index it transactional var cacheIDsToIndex []string // Cache keys of RLs to be indexed if rlIDs == nil { //FIXME: cacheIDsToIndex = cache2go.GetEntriesKeys(utils.ResourceLimitsPrefix) } else { for _, rlID := range rlIDs { cacheIDsToIndex = append(cacheIDsToIndex, utils.ResourceLimitsPrefix+rlID) } } for _, cacheKey := range cacheIDsToIndex { x, ok := cache2go.Get("FIXME", cacheKey) if !ok { return utils.ErrNotFound } rl := x.(*ResourceLimit) var hasMetaString bool for _, fltr := range rl.Filters { if fltr.Type != MetaString { continue } hasMetaString = true // Mark that we found at least one metatring so we don't need to index globally if _, hastIt := newStringIndexes[fltr.FieldName]; !hastIt { newStringIndexes[fltr.FieldName] = make(map[string]utils.StringMap) } for _, fldVal := range fltr.Values { if _, hasIt := newStringIndexes[fltr.FieldName][fldVal]; !hasIt { newStringIndexes[fltr.FieldName][fldVal] = make(utils.StringMap) } newStringIndexes[fltr.FieldName][fldVal][rl.ID] = true } } if !hasMetaString { if _, hasIt := newStringIndexes[utils.NOT_AVAILABLE]; !hasIt { newStringIndexes[utils.NOT_AVAILABLE] = make(map[string]utils.StringMap) } if _, hasIt := newStringIndexes[utils.NOT_AVAILABLE][utils.NOT_AVAILABLE]; !hasIt { newStringIndexes[utils.NOT_AVAILABLE][utils.NOT_AVAILABLE] = make(utils.StringMap) } newStringIndexes[utils.NOT_AVAILABLE][utils.NOT_AVAILABLE][rl.ID] = true // Fields without real field index will be located in map[NOT_AVAILABLE][NOT_AVAILABLE][rl.ID] } } rls.Lock() defer rls.Unlock() if rlIDs == nil { // We have rebuilt complete index rls.stringIndexes = newStringIndexes return nil } // Merge the indexes since we have only performed limited indexing for fldNameKey, mpFldName := range newStringIndexes { if _, hasIt := rls.stringIndexes[fldNameKey]; !hasIt { rls.stringIndexes[fldNameKey] = mpFldName } else { for fldValKey, strMap := range newStringIndexes[fldNameKey] { if _, hasIt := rls.stringIndexes[fldNameKey][fldValKey]; !hasIt { rls.stringIndexes[fldNameKey][fldValKey] = strMap } else { for resIDKey := range newStringIndexes[fldNameKey][fldValKey] { rls.stringIndexes[fldNameKey][fldValKey][resIDKey] = true } } } } } utils.Logger.Info("<RLs> Done indexing string filters") return nil } // Called when cache/re-caching is necessary func (rls *ResourceLimiterService) cacheResourceLimits(loadID string, rlIDs []string) error { if rlIDs == nil { utils.Logger.Info("<RLs> Start caching all resource limits") } else if len(rlIDs) == 0 { return nil } else { utils.Logger.Info(fmt.Sprintf("<RLs> Start caching resource limits with ids: %+v", rlIDs)) } if err := rls.dataDB.PreloadCacheForPrefix(utils.ResourceLimitsPrefix); err != nil { return err } utils.Logger.Info("<RLs> Done caching resource limits") return rls.indexStringFilters(rlIDs) } func (rls *ResourceLimiterService) matchingResourceLimitsForEvent(ev map[string]interface{}) (map[string]*ResourceLimit, error) { matchingResources := make(map[string]*ResourceLimit) for fldName, fieldValIf := range ev { if _, hasIt := rls.stringIndexes[fldName]; !hasIt { continue } strVal, canCast := utils.CastFieldIfToString(fieldValIf) if !canCast { return nil, fmt.Errorf("Cannot cast field: %s into string", fldName) } if _, hasIt := rls.stringIndexes[fldName][strVal]; !hasIt { continue } for resName := range rls.stringIndexes[fldName][strVal] { if _, hasIt := matchingResources[resName]; hasIt { // Already checked this RL continue } x, ok := cache2go.Get("FIXME", utils.ResourceLimitsPrefix+resName) if !ok { return nil, utils.ErrNotFound } rl := x.(*ResourceLimit) now := time.Now() if rl.ActivationTime.After(now) || (!rl.ExpiryTime.IsZero() && rl.ExpiryTime.Before(now)) { // not active continue } passAllFilters := true for _, fltr := range rl.Filters { if pass, err := fltr.Pass(ev, "", rls.cdrStatS); err != nil { return nil, utils.NewErrServerError(err) } else if !pass { passAllFilters = false continue } } if passAllFilters { matchingResources[rl.ID] = rl // Cannot save it here since we could have errors after and resource will remain unused } } } // Check un-indexed resources for resName := range rls.stringIndexes[utils.NOT_AVAILABLE][utils.NOT_AVAILABLE] { if _, hasIt := matchingResources[resName]; hasIt { // Already checked this RL continue } x, ok := cache2go.Get("FIXME: ", utils.ResourceLimitsPrefix+resName) if !ok { return nil, utils.ErrNotFound } rl := x.(*ResourceLimit) now := time.Now() if rl.ActivationTime.After(now) || (!rl.ExpiryTime.IsZero() && rl.ExpiryTime.Before(now)) { // not active continue } for _, fltr := range rl.Filters { if pass, err := fltr.Pass(ev, "", rls.cdrStatS); err != nil { return nil, utils.NewErrServerError(err) } else if !pass { continue } matchingResources[rl.ID] = rl // Cannot save it here since we could have errors after and resource will remain unused } } return matchingResources, nil } // Called to start the service func (rls *ResourceLimiterService) ListenAndServe() error { if err := rls.cacheResourceLimits("ResourceLimiterServiceStart", nil); err != nil { return err } return nil } // Called to shutdown the service func (rls *ResourceLimiterService) ServiceShutdown() error { return nil } // RPC Methods // Cache/Re-cache func (rls *ResourceLimiterService) V1CacheResourceLimits(attrs *utils.AttrRLsCache, reply *string) error { if err := rls.cacheResourceLimits(attrs.LoadID, attrs.ResourceLimitIDs); err != nil { return err } *reply = utils.OK return nil } // Alias API for external usage func (rls *ResourceLimiterService) CacheResourceLimits(attrs *utils.AttrRLsCache, reply *string) error { return rls.V1CacheResourceLimits(attrs, reply) } func (rls *ResourceLimiterService) V1ResourceLimitsForEvent(ev map[string]interface{}, reply *[]*ResourceLimit) error { rls.Lock() // Unknown number of RLs updated defer rls.Unlock() matchingRLForEv, err := rls.matchingResourceLimitsForEvent(ev) if err != nil { return utils.NewErrServerError(err) } retRLs := make([]*ResourceLimit, len(matchingRLForEv)) i := 0 for _, rl := range matchingRLForEv { retRLs[i] = rl i++ } *reply = retRLs return nil } // Alias API for external use func (rls *ResourceLimiterService) ResourceLimitsForEvent(ev map[string]interface{}, reply *[]*ResourceLimit) error { return rls.V1ResourceLimitsForEvent(ev, reply) } // Called when a session or another event needs to func (rls *ResourceLimiterService) V1InitiateResourceUsage(attrs utils.AttrRLsResourceUsage, reply *string) error { rls.Lock() // Unknown number of RLs updated defer rls.Unlock() matchingRLForEv, err := rls.matchingResourceLimitsForEvent(attrs.Event) if err != nil { return utils.NewErrServerError(err) } for rlID, rl := range matchingRLForEv { if rl.Limit < rl.UsedUnits()+attrs.RequestedUnits { delete(matchingRLForEv, rlID) } if err := rl.RecordUsage(&ResourceUsage{ID: attrs.ResourceUsageID, UsageTime: time.Now(), UsageUnits: attrs.RequestedUnits}); err != nil { return err // Should not happen } } if len(matchingRLForEv) == 0 { return utils.ErrResourceUnavailable } for _, rl := range matchingRLForEv { cache2go.Set("FIXME:", utils.ResourceLimitsPrefix+rl.ID, rl, "") } *reply = utils.OK return nil } // Alias for externam methods func (rls *ResourceLimiterService) InitiateResourceUsage(attrs utils.AttrRLsResourceUsage, reply *string) error { return rls.V1InitiateResourceUsage(attrs, reply) } func (rls *ResourceLimiterService) V1TerminateResourceUsage(attrs utils.AttrRLsResourceUsage, reply *string) error { rls.Lock() // Unknown number of RLs updated defer rls.Unlock() matchingRLForEv, err := rls.matchingResourceLimitsForEvent(attrs.Event) if err != nil { return utils.NewErrServerError(err) } for _, rl := range matchingRLForEv { rl.RemoveUsage(attrs.ResourceUsageID) } *reply = utils.OK return nil } // Alias for external methods func (rls *ResourceLimiterService) TerminateResourceUsage(attrs utils.AttrRLsResourceUsage, reply *string) error { return rls.V1TerminateResourceUsage(attrs, reply) } // Make the service available as RPC internally func (rls *ResourceLimiterService) Call(serviceMethod string, args interface{}, reply interface{}) error { parts := strings.Split(serviceMethod, ".") if len(parts) != 2 { return utils.ErrNotImplemented } // get method method := reflect.ValueOf(rls).MethodByName(parts[0][len(parts[0])-2:] + parts[1]) // Inherit the version in the method if !method.IsValid() { return utils.ErrNotImplemented } // construct the params params := []reflect.Value{reflect.ValueOf(args), reflect.ValueOf(reply)} ret := method.Call(params) if len(ret) != 1 { return utils.ErrServerError } if ret[0].Interface() == nil { return nil } err, ok := ret[0].Interface().(error) if !ok { return utils.ErrServerError } return err }
Go
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html><head><title></title> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <link rel="stylesheet" type="text/css" href="search.css"/> <script type="text/javascript" src="search.js"></script> </head> <body class="SRPage"> <div id="SRIndex"> <div class="SRStatus" id="Loading">Loading...</div> <div class="SRResult" id="SR_calctemp"> <div class="SREntry"> <a id="Item0" onkeydown="return searchResults.Nav(event,0)" onkeypress="return searchResults.Nav(event,0)" onkeyup="return searchResults.Nav(event,0)" class="SRSymbol" href="../prims_8f90.html#a5f96c7fc4ae0db597131c0862462bdf0" target="_parent">calcTemp</a> <span class="SRScope">prims.f90</span> </div> </div> <div class="SRResult" id="SR_cellpos"> <div class="SREntry"> <a id="Item1" onkeydown="return searchResults.Nav(event,1)" onkeypress="return searchResults.Nav(event,1)" onkeyup="return searchResults.Nav(event,1)" class="SRSymbol" href="../admesh_8f90.html#a05707d1dd21fefa65fa00167bf69a7f4" target="_parent">cellPos</a> <span class="SRScope">admesh.f90</span> </div> </div> <div class="SRResult" id="SR_checkproximity"> <div class="SREntry"> <a id="Item2" onkeydown="return searchResults.Nav(event,2)" onkeypress="return searchResults.Nav(event,2)" onkeyup="return searchResults.Nav(event,2)" class="SRSymbol" href="../admesh_8f90.html#a5160d5783dcaa66aa71416b785554366" target="_parent">checkProximity</a> <span class="SRScope">admesh.f90</span> </div> </div> <div class="SRResult" id="SR_children"> <div class="SREntry"> <a id="Item3" onkeydown="return searchResults.Nav(event,3)" onkeypress="return searchResults.Nav(event,3)" onkeyup="return searchResults.Nav(event,3)" class="SRSymbol" href="../admesh_8f90.html#adc3672c44efbd2b631e63360684689c7" target="_parent">children</a> <span class="SRScope">admesh.f90</span> </div> </div> <div class="SRResult" id="SR_coarseblocks"> <div class="SREntry"> <a id="Item4" onkeydown="return searchResults.Nav(event,4)" onkeypress="return searchResults.Nav(event,4)" onkeyup="return searchResults.Nav(event,4)" class="SRSymbol" href="../admesh_8f90.html#a0b9479efda016cfde6b0926b4cbb77c2" target="_parent">coarseBlocks</a> <span class="SRScope">admesh.f90</span> </div> </div> <div class="SRResult" id="SR_constants"> <div class="SREntry"> <a id="Item5" onkeydown="return searchResults.Nav(event,5)" onkeypress="return searchResults.Nav(event,5)" onkeyup="return searchResults.Nav(event,5)" class="SRSymbol" href="../namespaceconstants.html" target="_parent">constants</a> </div> </div> <div class="SRResult" id="SR_constants_2ef90"> <div class="SREntry"> <a id="Item6" onkeydown="return searchResults.Nav(event,6)" onkeypress="return searchResults.Nav(event,6)" onkeyup="return searchResults.Nav(event,6)" class="SRSymbol" href="../constants_8f90.html" target="_parent">constants.f90</a> </div> </div> <div class="SRResult" id="SR_cool_5fdmc"> <div class="SREntry"> <a id="Item7" onkeydown="return searchResults.Nav(event,7)" onkeypress="return searchResults.Nav(event,7)" onkeyup="return searchResults.Nav(event,7)" class="SRSymbol" href="../namespaceconstants.html#a42f51a68a959daecb888b8f198f80db3" target="_parent">COOL_DMC</a> <span class="SRScope">constants</span> </div> </div> <div class="SRResult" id="SR_cool_5fnone"> <div class="SREntry"> <a id="Item8" onkeydown="return searchResults.Nav(event,8)" onkeypress="return searchResults.Nav(event,8)" onkeyup="return searchResults.Nav(event,8)" class="SRSymbol" href="../namespaceconstants.html#a259868190bfea20cb5f119388fd42b1e" target="_parent">COOL_NONE</a> <span class="SRScope">constants</span> </div> </div> <div class="SRResult" id="SR_cooldata"> <div class="SREntry"> <a id="Item9" onkeydown="return searchResults.Nav(event,9)" onkeypress="return searchResults.Nav(event,9)" onkeyup="return searchResults.Nav(event,9)" class="SRSymbol" href="../namespaceglobals.html#ab86361204ca89a1bfb0977eb797bbb9a" target="_parent">cooldata</a> <span class="SRScope">globals</span> </div> </div> <div class="SRResult" id="SR_cooling"> <div class="SREntry"> <a id="Item10" onkeydown="return searchResults.Nav(event,10)" onkeypress="return searchResults.Nav(event,10)" onkeyup="return searchResults.Nav(event,10)" class="SRSymbol" href="../cooling_8f90.html#a15086e2460b3086eb1e6677f807e13a7" target="_parent">cooling</a> <span class="SRScope">cooling.f90</span> </div> </div> <div class="SRResult" id="SR_cooling_2ef90"> <div class="SREntry"> <a id="Item11" onkeydown="return searchResults.Nav(event,11)" onkeypress="return searchResults.Nav(event,11)" onkeyup="return searchResults.Nav(event,11)" class="SRSymbol" href="../cooling_8f90.html" target="_parent">cooling.f90</a> </div> </div> <div class="SRResult" id="SR_coolingdmc"> <div class="SREntry"> <a id="Item12" onkeydown="return searchResults.Nav(event,12)" onkeypress="return searchResults.Nav(event,12)" onkeyup="return searchResults.Nav(event,12)" class="SRSymbol" href="../cooling_8f90.html#a312199b37157b7f23af3cee53ddd9582" target="_parent">coolingdmc</a> <span class="SRScope">cooling.f90</span> </div> </div> <div class="SRStatus" id="Searching">Searching...</div> <div class="SRStatus" id="NoMatches">No Matches</div> <script type="text/javascript"><!-- document.getElementById("Loading").style.display="none"; document.getElementById("NoMatches").style.display="none"; var searchResults = new SearchResults("searchResults"); searchResults.Search(); --></script> </div> </body> </html>
HTML
[root] name = "git-tags-rs" version = "0.1.0" dependencies = [ "clap 0.10.5 (registry+https://github.com/rust-lang/crates.io-index)", "git2 0.2.12 (registry+https://github.com/rust-lang/crates.io-index)", "glob 0.2.10 (registry+https://github.com/rust-lang/crates.io-index)", "tempfile 0.5.1 (registry+https://github.com/rust-lang/crates.io-index)", "yaml-rust 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] name = "ansi_term" version = "0.6.1" source = "registry+https://github.com/rust-lang/crates.io-index" [[package]] name = "bitflags" version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" [[package]] name = "clap" version = "0.10.5" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "ansi_term 0.6.1 (registry+https://github.com/rust-lang/crates.io-index)", "strsim 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] name = "gcc" version = "0.3.8" source = "registry+https://github.com/rust-lang/crates.io-index" [[package]] name = "git2" version = "0.2.12" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "bitflags 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", "libc 0.1.8 (registry+https://github.com/rust-lang/crates.io-index)", "libgit2-sys 0.2.15 (registry+https://github.com/rust-lang/crates.io-index)", "url 0.2.35 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] name = "glob" version = "0.2.10" source = "registry+https://github.com/rust-lang/crates.io-index" [[package]] name = "kernel32-sys" version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "winapi 0.1.21 (registry+https://github.com/rust-lang/crates.io-index)", "winapi-build 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] name = "libc" version = "0.1.8" source = "registry+https://github.com/rust-lang/crates.io-index" [[package]] name = "libgit2-sys" version = "0.2.15" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "libc 0.1.8 (registry+https://github.com/rust-lang/crates.io-index)", "libssh2-sys 0.1.25 (registry+https://github.com/rust-lang/crates.io-index)", "libz-sys 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)", "openssl-sys 0.6.2 (registry+https://github.com/rust-lang/crates.io-index)", "pkg-config 0.3.4 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] name = "libressl-pnacl-sys" version = "2.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "pnacl-build-helper 1.4.0 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] name = "libssh2-sys" version = "0.1.25" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "libc 0.1.8 (registry+https://github.com/rust-lang/crates.io-index)", "libz-sys 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)", "openssl-sys 0.6.2 (registry+https://github.com/rust-lang/crates.io-index)", "pkg-config 0.3.4 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] name = "libz-sys" version = "0.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "libc 0.1.8 (registry+https://github.com/rust-lang/crates.io-index)", "pkg-config 0.3.4 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] name = "matches" version = "0.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" [[package]] name = "openssl-sys" version = "0.6.2" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "gcc 0.3.8 (registry+https://github.com/rust-lang/crates.io-index)", "libc 0.1.8 (registry+https://github.com/rust-lang/crates.io-index)", "libressl-pnacl-sys 2.1.5 (registry+https://github.com/rust-lang/crates.io-index)", "pkg-config 0.3.4 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] name = "pkg-config" version = "0.3.4" source = "registry+https://github.com/rust-lang/crates.io-index" [[package]] name = "pnacl-build-helper" version = "1.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "tempdir 0.3.4 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] name = "rand" version = "0.3.8" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "libc 0.1.8 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] name = "rustc-serialize" version = "0.3.15" source = "registry+https://github.com/rust-lang/crates.io-index" [[package]] name = "strsim" version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" [[package]] name = "tempdir" version = "0.3.4" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "rand 0.3.8 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] name = "tempfile" version = "0.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "kernel32-sys 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", "libc 0.1.8 (registry+https://github.com/rust-lang/crates.io-index)", "rand 0.3.8 (registry+https://github.com/rust-lang/crates.io-index)", "winapi 0.1.21 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] name = "url" version = "0.2.35" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "matches 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)", "rustc-serialize 0.3.15 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] name = "winapi" version = "0.1.21" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "libc 0.1.8 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] name = "winapi-build" version = "0.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" [[package]] name = "yaml-rust" version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index"
TOML
name = "Deconvolution" uuid = "41ba435c-a500-5816-a783-a9707c6f5f3a" authors = ["Mosè Giordano <mose@gnu.org>"] version = "1.1.1" [deps] FFTW = "7a1cc6ca-52ef-59f5-83cd-3a7055c09341" [compat] FFTW = "0.0, 0.1, 0.2, 0.3, 1" julia = "1" [extras] StableRNGs = "860ef19b-820b-49d6-a774-d7a799459cd3" Test = "8dfed614-e22c-5e08-85e1-65c5234f0b40" [targets] test = ["Test", "StableRNGs"]
TOML
<?xml version="1.0" encoding="UTF-8"?> <feature-model xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://www.tdg-seville.info/benavides/featuremodelling/feature-model.xsd"> <feature name="R"> <binaryRelation name="26469"> <cardinality max="1" min="0"/> <solitaryFeature name="o_1"> <binaryRelation name="26470"> <cardinality max="1" min="1"/> <solitaryFeature name="m_1_1"> </solitaryFeature> </binaryRelation> </solitaryFeature> </binaryRelation> <binaryRelation name="26471"> <cardinality max="1" min="1"/> <solitaryFeature name="m_2"> <binaryRelation name="26472"> <cardinality max="1" min="0"/> <solitaryFeature name="o_2_1"> </solitaryFeature> </binaryRelation> </solitaryFeature> </binaryRelation> <binaryRelation name="26473"> <cardinality max="1" min="0"/> <solitaryFeature name="o_3"> </solitaryFeature> </binaryRelation> <binaryRelation name="26474"> <cardinality max="1" min="0"/> <solitaryFeature name="o_4"> </solitaryFeature> </binaryRelation> <setRelation name="26475"> <cardinality max="2" min="1"/> <groupedFeature name="g_5_1"> </groupedFeature> <groupedFeature name="g_5_2"> </groupedFeature> </setRelation> <binaryRelation name="26476"> <cardinality max="1" min="1"/> <solitaryFeature name="m_6"> </solitaryFeature> </binaryRelation> </feature> </feature-model>
XML
@ECHO OFF TheWord Comforter_-_20040605IThankTheLORDForLovingEachAndEveryChildAndWeLoveOffspring.xml Comforter_-_20040605TheLORDIThankTheLORDForLovingEachAndEveryChildAndWeLoveOffspring.xml
Batchfile
#!/bin/bash # # Copyright (c) 2012 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. set -e set -o pipefail if [ "$VERBOSE" ]; then set -x fi set -u # Create the Debian changelog file needed by dpkg-gencontrol. This just adds a # placeholder change, indicating it is the result of an automatic build. # TODO(mmoss) Release packages should create something meaningful for a # changelog, but simply grabbing the actual 'svn log' is way too verbose. Do we # have any type of "significant/visible changes" log that we could use for this? gen_changelog() { rm -f "${DEB_CHANGELOG}" process_template "${SCRIPTDIR}/changelog.template" "${DEB_CHANGELOG}" debchange -a --nomultimaint -m --changelog "${DEB_CHANGELOG}" \ "Release Notes: ${RELEASENOTES}" GZLOG="${STAGEDIR}/usr/share/doc/${PACKAGE}-${CHANNEL}/changelog.gz" mkdir -p "$(dirname "${GZLOG}")" gzip -9 -c "${DEB_CHANGELOG}" > "${GZLOG}" chmod 644 "${GZLOG}" } # Create the Debian control file needed by dpkg-deb. gen_control() { dpkg-gencontrol -v"${VERSIONFULL}" -c"${DEB_CONTROL}" -l"${DEB_CHANGELOG}" \ -f"${DEB_FILES}" -p"${PACKAGE}-${CHANNEL}" -P"${STAGEDIR}" \ -O > "${STAGEDIR}/DEBIAN/control" rm -f "${DEB_CONTROL}" } # Setup the installation directory hierachy in the package staging area. prep_staging_debian() { prep_staging_common install -m 755 -d "${STAGEDIR}/DEBIAN" \ "${STAGEDIR}/etc/cron.daily" \ "${STAGEDIR}/usr/share/menu" \ "${STAGEDIR}/usr/share/doc/${USR_BIN_SYMLINK_NAME}" } # Put the package contents in the staging area. stage_install_debian() { # Always use a different name for /usr/bin symlink depending on channel. # First, to avoid file collisions. Second, to make it possible to # use update-alternatives for /usr/bin/google-chrome. local USR_BIN_SYMLINK_NAME="${PACKAGE}-${CHANNEL}" local PACKAGE_ORIG="${PACKAGE}" if [ "$CHANNEL" != "stable" ]; then # Avoid file collisions between channels. local INSTALLDIR="${INSTALLDIR}-${CHANNEL}" local PACKAGE="${PACKAGE}-${CHANNEL}" # Make it possible to distinguish between menu entries # for different channels. local MENUNAME="${MENUNAME} (${CHANNEL})" fi prep_staging_debian SHLIB_PERMS=644 stage_install_common log_cmd echo "Staging Debian install files in '${STAGEDIR}'..." install -m 755 -d "${STAGEDIR}/${INSTALLDIR}/cron" process_template "${BUILDDIR}/installer/common/repo.cron" \ "${STAGEDIR}/${INSTALLDIR}/cron/${PACKAGE}" chmod 755 "${STAGEDIR}/${INSTALLDIR}/cron/${PACKAGE}" pushd "${STAGEDIR}/etc/cron.daily/" > /dev/null ln -snf "${INSTALLDIR}/cron/${PACKAGE}" "${PACKAGE}" popd > /dev/null process_template "${BUILDDIR}/installer/debian/debian.menu" \ "${STAGEDIR}/usr/share/menu/${PACKAGE}.menu" chmod 644 "${STAGEDIR}/usr/share/menu/${PACKAGE}.menu" process_template "${BUILDDIR}/installer/debian/postinst" \ "${STAGEDIR}/DEBIAN/postinst" chmod 755 "${STAGEDIR}/DEBIAN/postinst" process_template "${BUILDDIR}/installer/debian/prerm" \ "${STAGEDIR}/DEBIAN/prerm" chmod 755 "${STAGEDIR}/DEBIAN/prerm" process_template "${BUILDDIR}/installer/debian/postrm" \ "${STAGEDIR}/DEBIAN/postrm" chmod 755 "${STAGEDIR}/DEBIAN/postrm" } verify_package() { local DEPENDS="$1" local EXPECTED_DEPENDS="${TMPFILEDIR}/expected_deb_depends" local ACTUAL_DEPENDS="${TMPFILEDIR}/actual_deb_depends" echo ${DEPENDS} | sed 's/, /\n/g' | LANG=C sort > "${EXPECTED_DEPENDS}" dpkg -I "${PACKAGE}-${CHANNEL}_${VERSIONFULL}_${ARCHITECTURE}.deb" | \ grep '^ Depends: ' | sed 's/^ Depends: //' | sed 's/, /\n/g' | \ LANG=C sort > "${ACTUAL_DEPENDS}" BAD_DIFF=0 diff -u "${EXPECTED_DEPENDS}" "${ACTUAL_DEPENDS}" || BAD_DIFF=1 if [ $BAD_DIFF -ne 0 ]; then echo echo "ERROR: bad dpkg dependencies!" echo exit $BAD_DIFF fi } # Actually generate the package file. do_package() { log_cmd echo "Packaging ${ARCHITECTURE}..." PREDEPENDS="$COMMON_PREDEPS" DEPENDS="${COMMON_DEPS}" RECOMMENDS="${COMMON_RECOMMENDS}" PROVIDES="www-browser" gen_changelog process_template "${SCRIPTDIR}/control.template" "${DEB_CONTROL}" export DEB_HOST_ARCH="${ARCHITECTURE}" if [ -f "${DEB_CONTROL}" ]; then gen_control fi if [ ${IS_OFFICIAL_BUILD} -ne 0 ]; then local COMPRESSION_OPTS="-Zxz -z9" else local COMPRESSION_OPTS="-Znone" fi log_cmd fakeroot dpkg-deb ${COMPRESSION_OPTS} -b "${STAGEDIR}" . verify_package "$DEPENDS" } # Remove temporary files and unwanted packaging output. cleanup() { log_cmd echo "Cleaning..." rm -rf "${STAGEDIR}" rm -rf "${TMPFILEDIR}" } usage() { echo "usage: $(basename $0) [-a target_arch] [-b 'dir'] -c channel" echo " -d branding [-f] [-o 'dir'] -s 'dir' -t target_os" echo "-a arch package architecture (ia32 or x64)" echo "-b dir build input directory [${BUILDDIR}]" echo "-c channel the package channel (unstable, beta, stable)" echo "-d brand either chromium or google_chrome" echo "-f indicates that this is an official build" echo "-h this help message" echo "-o dir package output directory [${OUTPUTDIR}]" echo "-s dir /path/to/sysroot" echo "-t platform target platform" } # Check that the channel name is one of the allowable ones. verify_channel() { case $CHANNEL in stable ) CHANNEL=stable RELEASENOTES="http://googlechromereleases.blogspot.com/search/label/Stable%20updates" ;; unstable|dev|alpha ) CHANNEL=unstable RELEASENOTES="http://googlechromereleases.blogspot.com/search/label/Dev%20updates" ;; testing|beta ) CHANNEL=beta RELEASENOTES="http://googlechromereleases.blogspot.com/search/label/Beta%20updates" ;; * ) echo echo "ERROR: '$CHANNEL' is not a valid channel type." echo exit 1 ;; esac } process_opts() { while getopts ":a:b:c:d:fho:s:t:" OPTNAME do case $OPTNAME in a ) TARGETARCH="$OPTARG" ;; b ) BUILDDIR=$(readlink -f "${OPTARG}") ;; c ) CHANNEL="$OPTARG" ;; d ) BRANDING="$OPTARG" ;; f ) IS_OFFICIAL_BUILD=1 ;; h ) usage exit 0 ;; o ) OUTPUTDIR=$(readlink -f "${OPTARG}") mkdir -p "${OUTPUTDIR}" ;; s ) SYSROOT="$OPTARG" ;; t ) TARGET_OS="$OPTARG" ;; \: ) echo "'-$OPTARG' needs an argument." usage exit 1 ;; * ) echo "invalid command-line option: $OPTARG" usage exit 1 ;; esac done } #========= # MAIN #========= SCRIPTDIR=$(readlink -f "$(dirname "$0")") OUTPUTDIR="${PWD}" # Default target architecture to same as build host. if [ "$(uname -m)" = "x86_64" ]; then TARGETARCH="x64" else TARGETARCH="ia32" fi # call cleanup() on exit trap cleanup 0 process_opts "$@" BUILDDIR=${BUILDDIR:=$(readlink -f "${SCRIPTDIR}/../../../../out/Release")} IS_OFFICIAL_BUILD=${IS_OFFICIAL_BUILD:=0} STAGEDIR="${BUILDDIR}/deb-staging-${CHANNEL}" mkdir -p "${STAGEDIR}" TMPFILEDIR="${BUILDDIR}/deb-tmp-${CHANNEL}" mkdir -p "${TMPFILEDIR}" DEB_CHANGELOG="${TMPFILEDIR}/changelog" DEB_FILES="${TMPFILEDIR}/files" DEB_CONTROL="${TMPFILEDIR}/control" source ${BUILDDIR}/installer/common/installer.include get_version_info VERSIONFULL="${VERSION}-${PACKAGE_RELEASE}" if [ "$BRANDING" = "google_chrome" ]; then source "${BUILDDIR}/installer/common/google-chrome.info" else source "${BUILDDIR}/installer/common/chromium-browser.info" fi eval $(sed -e "s/^\([^=]\+\)=\(.*\)$/export \1='\2'/" \ "${BUILDDIR}/installer/theme/BRANDING") verify_channel # Some Debian packaging tools want these set. export DEBFULLNAME="${MAINTNAME}" export DEBEMAIL="${MAINTMAIL}" DEB_COMMON_DEPS="${BUILDDIR}/deb_common.deps" COMMON_DEPS=$(sed ':a;N;$!ba;s/\n/, /g' "${DEB_COMMON_DEPS}") COMMON_PREDEPS="dpkg (>= 1.14.0)" COMMON_RECOMMENDS="libu2f-udev" # Make everything happen in the OUTPUTDIR. cd "${OUTPUTDIR}" case "$TARGETARCH" in arm ) export ARCHITECTURE="armhf" ;; arm64 ) export ARCHITECTURE="arm64" ;; ia32 ) export ARCHITECTURE="i386" ;; x64 ) export ARCHITECTURE="amd64" ;; mipsel ) export ARCHITECTURE="mipsel" ;; mips64el ) export ARCHITECTURE="mips64el" ;; * ) echo echo "ERROR: Don't know how to build DEBs for '$TARGETARCH'." echo exit 1 ;; esac BASEREPOCONFIG="dl.google.com/linux/chrome/deb/ stable main" # Only use the default REPOCONFIG if it's unset (e.g. verify_channel might have # set it to an empty string) REPOCONFIG="${REPOCONFIG-deb [arch=${ARCHITECTURE}] http://${BASEREPOCONFIG}}" # Allowed configs include optional HTTPS support and explicit multiarch # platforms. REPOCONFIGREGEX="deb (\\\\[arch=[^]]*\\\\b${ARCHITECTURE}\\\\b[^]]*\\\\]" REPOCONFIGREGEX+="[[:space:]]*) https?://${BASEREPOCONFIG}" stage_install_debian do_package
Shell
test_that('input_trees returns correctly', { trees_list_test <- input_trees(x_tree = fungal_tree, y_tree = plant_tree, x_key = mycor_ei$fungal_name, y_key = mycor_ei$plant_name, response = mycor_ei$ei, response_type = mycor_ei$mycorrhizae_type) expect_equal(length(trees_list_test$x_tree$tip.label), 53) expect_equal(length(trees_list_test$y_tree$tip.label), 290) expect_equal(length(trees_list_test$x_tree$tip.label), ncol(trees_list_test$mat)) expect_equal(length(trees_list_test$y_tree$tip.label), nrow(trees_list_test$mat)) mycor_AM <- mycor_ei %>% filter(mycorrhizae_type == 'AM') trees_list_test_AM <- input_trees(x_tree = fungal_tree, y_tree = plant_tree, x_key = mycor_AM$fungal_name, y_key = mycor_AM$plant_name, response = mycor_AM$ei) expect_equal(length(trees_list_test_AM$x_tree$tip.label), 15) expect_equal(length(trees_list_test_AM$y_tree$tip.label), 234) expect_equal(length(trees_list_test_AM$x_tree$tip.label), ncol(trees_list_test_AM$mat)) expect_equal(length(trees_list_test_AM$y_tree$tip.label), nrow(trees_list_test_AM$mat)) })
R
- name: Install Docker Dependencies yum: name: "{{ item }}" state: present loop: "{{ yum_pkgs }}" - name: Install Docker-CE Repo shell: "yum-config-manager --add-repo {{ docker_yum_repo }}" - name: Install Docker-CE yum: name: "{{ item }}" state: present loop: "{{ docker_yum_pkgs }}" - name: Create Docker group group: name: docker state: present - name: Add users to Docker group user: name: "{{ item }}" groups: docker append: yes loop: "{{ docker_users }}" notify: reboot host - name: Enable and Start Docker Service service: name: docker state: started enabled: yes - name: Install Docker PIP libraries pip: name: "{{ item }}" state: latest executable: pip3 loop: "{{ docker_pip }}" - name: run handlers immediately meta: flush_handlers
YAML
W:\Model_Programs\GISTranslator\TableDrivenTranslator\bin\TableDrivenTranslator.exe TranslationTables.mdb Taxlots_Divides_translation W:\AGMaster21\AGMaster21_taxlots.mdb
Batchfile
use std::sync::mpsc; use std::thread; use std::time::Duration; fn main() { //创建了一个新通道 let (tx, rx) = mpsc::channel(); thread::spawn(move || { let vals = vec![ String::from("hi"), String::from("from"), String::from("the"), String::from("thread"), ]; //线程通过管道发送多条消息 for val in vals{ tx.send(val).unwrap(); thread::sleep(Duration::from_secs(1)); } }); // 主线程通过管道接受消息并打印 for received in rx { println!("Got: {}",received); } }
RenderScript
import 'package:angular_router/angular_router.dart'; const idParam = 'id'; class RoutePaths { static final dashboard = RoutePath(path: 'dashboard'); static final heroes = RoutePath(path: 'heroes'); static final hero = RoutePath(path: '${heroes.path}/:$idParam'); } int getId(Map<String, String> parameters) { final id = parameters[idParam]; return id == null ? null : int.tryParse(id); }
Dart
#! /usr/bin/env python # Copyright 2011 Tom SF Haines # 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. from utils.prog_bar import ProgBar from swood import SWood import test_model as mod # Tests the stocahstic woodland class on the model contained within test_model.py # Parameters... tree_count = 256 option_count = 4 # Get trainning data... int_dm, real_dm, cats, weight = mod.generate_train() # Train... p = ProgBar() sw = SWood(int_dm, real_dm, cats, tree_count = tree_count, option_count = option_count, weight = weight, callback=p.callback) del p print 'Out-of-bag success rate = %.2f%%'%(100.0*sw. oob_success()) print # Test... mod.test(sw.classify)
Python
FROM hashicorp/vault:1.18 COPY --chmod=755 ./.github/docker/vault/entrypoint /tmp/entrypoint RUN sh -e <<EOF apk update apk add jq EOF EXPOSE 8200 ENTRYPOINT ["/tmp/entrypoint/container.sh"]
Dockerfile
function [J, grad] = costFunctionReg(theta, X, y, lambda) %COSTFUNCTIONREG Compute cost and gradient for logistic regression with regularization % J = COSTFUNCTIONREG(theta, X, y, lambda) computes the cost of using % theta as the parameter for regularized logistic regression and the % gradient of the cost w.r.t. to the parameters. % Initialize some useful values m = length(y); % number of training examples % You need to return the following variables correctly J = 0; grad = zeros(size(theta),1); % ====================== YOUR CODE HERE ====================== % Instructions: Compute the cost of a particular choice of theta. % You should set J to the cost. % Compute the partial derivatives and set grad to the partial % derivatives of the cost w.r.t. each parameter in theta h = sigmoid(X* theta); J = -1/ m * (y'* log(h) + (1-y)' * log(1-h)) + lambda / 2/ m * (theta(2:end)'* theta(2:end)); grad(1) = sum(h - y)/m ; grad(2:end) = 1/m * (X(:, 2:end)' * (h- y))... + lambda/m*theta(2:end); % ============================================================= end
MATLAB
-- Runeforged Sentry UPDATE `creature_template` SET `spell1` = 64852, `spell2` = 64870, `spell3` = 64847, `AIName` = 'EventAI' WHERE `entry` = 34234; UPDATE `creature_template` SET `spell1` = 64852, `spell2` = 64870, `spell3` = 64847 WHERE `entry` = 34235; DELETE FROM `creature_ai_scripts` WHERE (`creature_id`=34234); INSERT INTO `creature_ai_scripts` VALUES (3423401, 34234, 0, 0, 100, 1, 2000, 2000, 10000, 10000, 11, 64852, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 'Runeforged Sentry - Cast Flaming Rune'), (3423402, 34234, 0, 0, 100, 1, 3000, 5000, 5000, 7000, 11, 64870, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 'Runeforged Sentry - Cast Lava Burst'), (3423403, 34234, 0, 0, 100, 1, 2500, 3000, 12000, 15000, 11, 64847, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 'Runeforged Sentry - Cast Runed Flame Jets'); -- Steelforged Defender UPDATE `creature_template` SET `spell1` = 62845, `spell2` = 57780, `spell3` = 50370, `AIName` = 'EventAI' WHERE `entry` = 33236; UPDATE `creature_template` SET `spell1` = 62845, `spell2` = 57780, `spell3` = 50370 WHERE `entry` = 34113; UPDATE `creature` SET `spawntimesecs` = 604800 WHERE `id` IN (33236, 33838); DELETE FROM `creature_ai_scripts` WHERE (`creature_id`=33236); INSERT INTO `creature_ai_scripts` VALUES (3323601, 33236, 0, 0, 100, 1, 4000, 6000, 15000, 20000, 11, 62845, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 'Steelforged Defender - Cast Hamstring'), (3323602, 33236, 0, 0, 100, 1, 0, 4000, 6000, 8000, 11, 57780, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 'Steelforged Defender - Cast Lightning Bolt'), (3323603, 33236, 0, 0, 100, 1, 5000, 6000, 4000, 6000, 11, 50370, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 'Steelforged Defender - Cast Sunder Armor'); -- Mechagnome Battletank UPDATE `creature_template` SET `spell1` = 64693, `spell2` = 64953, `AIName` = 'EventAI' WHERE `entry` = 34164; UPDATE `creature_template` SET `spell1` = 64693, `spell2` = 64953 WHERE `entry` = 34165; DELETE FROM `creature_ai_scripts` WHERE (`creature_id`=34164); INSERT INTO `creature_ai_scripts` VALUES (3416401, 34164, 0, 0, 100, 1, 3000, 4000, 6000, 8000, 11, 64693, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 'Mechagnome Battletank - Cast Flame Cannon'), (3416402, 34164, 0, 0, 100, 1, 10000, 10000, 15000, 20000, 11, 64953, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 'Mechagnome Battletank - Cast Jump Attack'); -- Ulduar Colossus UPDATE `creature_template` SET `spell1` = 62625, `AIName` = 'EventAI' WHERE `entry` = 33237; UPDATE `creature_template` SET `spell1` = 62625 WHERE `entry` = 34105; DELETE FROM `creature_ai_scripts` WHERE (`creature_id`=33237); INSERT INTO `creature_ai_scripts` VALUES (3323701, 33237, 0, 0, 100, 1, 8000, 10000, 20000, 25000, 11, 62625, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 'Ulduar Colossus - Cast Ground Slam'); -- invisible triggers UPDATE `creature_template` SET `flags_extra` = 2 WHERE `entry` IN (33377, 33742, 34286, 33500, 33406, 33575); -- Molten Colossus UPDATE `creature_template` SET `spell1` = 64697, `spell2` = 64698, `mingold` = 7100, `maxgold` = 7600, `AIName` = 'EventAI' WHERE `entry` = 34069; UPDATE `creature_template` SET `spell1` = 64697, `spell2` = 64698, `mingold` = 14200, `maxgold` = 15600 WHERE `entry` = 34185; DELETE FROM `creature_ai_scripts` WHERE (`creature_id`=34069); INSERT INTO `creature_ai_scripts` VALUES (3406901, 34069, 0, 0, 100, 1, 6000, 10000, 10000, 12000, 11, 64697, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 'Molten Colossus - Cast Earthquake'), (3406902, 34069, 0, 0, 100, 1, 2000, 4000, 6000, 9000, 11, 64698, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 'Molten Colossus - Cast Pyroblast'); -- Magma Rager UPDATE `creature_template` SET `spell1` = 64773, `spell2` = 64746, `mingold` = 7100, `maxgold` = 7600, `AIName` = 'EventAI' WHERE `entry` = 34086; UPDATE `creature_template` SET `spell1` = 64773, `spell2` = 64746, `mingold` = 14200, `maxgold` = 15600 WHERE `entry` = 34201; DELETE FROM `creature_ai_scripts` WHERE (`creature_id`=34086); INSERT INTO `creature_ai_scripts` VALUES (3408601, 34086, 0, 0, 100, 1, 2000, 40000, 6000, 8000, 11, 64773, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 'Magma Rager - Cast Fire Blast'), (3408602, 34086, 0, 0, 100, 1, 8000, 16000, 15000, 25000, 11, 64746, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 'Magma Rager - Cast Superheated winds'); UPDATE `creature_template` SET `unit_flags` = 33718790, modelid1 = 11686, modelid2 = 0, `spell1` = 64724, `AIName` = 'EventAI' WHERE `entry` = 34194; DELETE FROM `creature_ai_scripts` WHERE (`creature_id`=34194); INSERT INTO `creature_ai_scripts` VALUES (3419401, 34194, 0, 0, 100, 1, 0, 0, 10000, 10000, 11, 64724, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 'Superheated Winds'); -- Forge Construct UPDATE `creature_template` SET `spell1` = 64719, `spell2` = 64720, `mingold` = 7100, `maxgold` = 7600, `AIName` = 'EventAI' WHERE `entry` = 34085; UPDATE `creature_template` SET `spell1` = 64719, `spell2` = 64721, `mingold` = 14200, `maxgold` = 15600 WHERE `entry` = 34186; DELETE FROM `creature_ai_scripts` WHERE (`creature_id`=34085); INSERT INTO `creature_ai_scripts` VALUES (3408501, 34085, 0, 0, 100, 1, 8000, 12000, 10000, 15000, 11, 64719, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 'Forge Construct - Cast Charge'), (3408502, 34085, 0, 0, 100, 3, 2000, 6000, 6000, 9000, 11, 64720, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 'Forge Construct - Cast Flame Emission 10'), (3408503, 34085, 0, 0, 100, 5, 2000, 6000, 6000, 9000, 11, 64721, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 'Forge Construct - Cast Flame Emission 25'); -- XB-488 Disposalbot UPDATE `creature_template` SET `spell1` = 65080, `spell2` = 65084, `mingold` = 7100, `maxgold` = 7600, `AIName` = 'EventAI' WHERE `entry` = 34273; UPDATE `creature_template` SET `spell1` = 65104, `spell2` = 65084, `mingold` = 14200, `maxgold` = 15600 WHERE `entry` = 34274; DELETE FROM `creature_ai_scripts` WHERE (`creature_id`=34273); INSERT INTO `creature_ai_scripts` VALUES (3427301, 34273, 2, 0, 100, 1, 30, 20, 0, 0, 11, 65084, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 'XB-488 Disposalbot - Cast Self Destruct'), (3427302, 34273, 0, 0, 100, 3, 2000, 6000, 10000, 15000, 11, 65080, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 'XB-488 Disposalbot - Cast Cut Scrap Metal 10'), (3427303, 34273, 0, 0, 100, 5, 2000, 6000, 10000, 15000, 11, 65104, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 'XB-488 Disposalbot - Cast Cut Scrap Metal 25'); -- Parts Recovery Technician UPDATE `creature_template` SET `spell1` = 65071, `spell2` = 65070, `mingold` = 7100, `maxgold` = 7600, `mechanic_immune_mask` = 33554432, `AIName` = 'EventAI' WHERE `entry` = 34267; UPDATE `creature_template` SET `spell1` = 65071, `spell2` = 65070, `mingold` = 14200, `maxgold` = 15600, `mechanic_immune_mask` = 33554432 WHERE `entry` = 34268; DELETE FROM `creature_ai_scripts` WHERE (`creature_id`=34267); INSERT INTO `creature_ai_scripts` VALUES (3426701, 34267, 0, 0, 100, 1, 8000, 12000, 10000, 15000, 11, 65071, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 'Parts Recovery Technician - Cast Mechano Kick'), (3426702, 34267, 0, 0, 100, 1, 6000, 8000, 25000, 30000, 11, 65070, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 'Parts Recovery Technician - Cast Defense Matrix'); -- XD-175 Compactobot UPDATE `creature_template` SET `spell1` = 65073, `mingold` = 7100, `maxgold` = 7600, `AIName` = 'EventAI' WHERE `entry` = 34271; UPDATE `creature_template` SET `spell1` = 65106, `mingold` = 14200, `maxgold` = 15600 WHERE `entry` = 34272; UPDATE `creature_template` SET `mingold` = 7100, `maxgold` = 7600 WHERE `entry` = 34269; DELETE FROM `creature_ai_scripts` WHERE (`creature_id`=34271); INSERT INTO `creature_ai_scripts` VALUES (3427101, 34271, 0, 0, 100, 3, 8000, 12000, 15000, 20000, 11, 65073, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 'XD-175 Compactobot - Cast Trash Compactor 10'), (3427102, 34271, 0, 0, 100, 5, 8000, 12000, 15000, 20000, 11, 65106, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 'XD-175 Compactobot - Cast Trash Compactor 25'); -- Lightning Charged Iron Dwarf UPDATE `creature_template` SET `spell1` = 64889, `mingold` = 7100, `maxgold` = 7600, `AIName` = 'EventAI' WHERE `entry` = 34199; UPDATE `creature_template` SET `spell1` = 64975, `mingold` = 14200, `maxgold` = 15600 WHERE `entry` = 34237; DELETE FROM `creature_ai_scripts` WHERE (`creature_id`=34199); INSERT INTO `creature_ai_scripts` VALUES (3419901, 34199, 0, 0, 100, 3, 0, 0, 10000, 15000, 11, 64889, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 'Lightning Charged Iron Dwarf - Cast Lightning Charged 10'), (3419902, 34199, 0, 0, 100, 5, 0, 0, 10000, 15000, 11, 64975, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 'Lightning Charged Iron Dwarf - Cast Lightning Charged 25'); -- Hardened Iron Golem UPDATE `creature_template` SET `spell1` = 64877, `spell2` = 64874, `mingold` = 7100, `maxgold` = 7600, `mechanic_immune_mask` = 33554496, `AIName` = 'EventAI' WHERE `entry` = 34190; UPDATE `creature_template` SET `spell1` = 64877, `spell2` = 64967, `mingold` = 14200, `maxgold` = 15600, `mechanic_immune_mask` = 33554496 WHERE `entry` = 34229; DELETE FROM `creature_ai_scripts` WHERE (`creature_id`=34190); INSERT INTO `creature_ai_scripts` VALUES (3419001, 34190, 0, 0, 100, 1, 4000, 8000, 25000, 30000, 11, 64877, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 'Hardened Iron Golem - Cast Harden Fists'), (3419002, 34190, 0, 0, 100, 3, 5000, 7000, 20000, 30000, 11, 64874, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 'Hardened Iron Golem - Cast Rune Punch 10'), (3419003, 34190, 0, 0, 100, 5, 5000, 7000, 20000, 30000, 11, 64967, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 'Hardened Iron Golem - Cast Rune Punch 25'); -- Iron Mender UPDATE `creature_template` SET `spell1` = 64918, `spell2` = 64903, `spell3` = 64897, `mechanic_immune_mask` = 33554496, `mingold` = 7100, `maxgold` = 7600, `AIName` = 'EventAI' WHERE `entry` = 34198; UPDATE `creature_template` SET `spell1` = 64971, `spell2` = 64970, `spell3` = 64968, `mechanic_immune_mask` = 33554496, `mingold` = 14200, `maxgold` = 15600 WHERE `entry` = 34236; DELETE FROM `creature_ai_scripts` WHERE (`creature_id`=34198); INSERT INTO `creature_ai_scripts` VALUES (3419801, 34198, 0, 0, 100, 3, 2000, 4000, 4000, 6000, 11, 64918, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 'Iron Mender - Cast Electro Shock 10'), (3419802, 34198, 0, 0, 100, 5, 2000, 4000, 4000, 6000, 11, 64971, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 'Iron Mender - Cast Electro Shock 25'), (3419803, 34198, 0, 0, 100, 3, 3000, 6000, 10000, 15000, 11, 64903, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 'Iron Mender - Cast Fuse Lightning 10'), (3419804, 34198, 0, 0, 100, 5, 3000, 6000, 10000, 15000, 11, 64970, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 'Iron Mender - Cast Fuse Lightning 25'), (3419805, 34198, 0, 0, 100, 3, 10000, 25000, 30000, 45000, 11, 64897, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 'Iron Mender - Cast Fuse Metal 10'), (3419806, 34198, 0, 0, 100, 5, 10000, 25000, 30000, 45000, 11, 64968, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 'Iron Mender - Cast Fuse Metal 25'); -- Rune Etched Sentry UPDATE `creature_template` SET `spell1` = 64852, `spell2` = 64870, `spell3` = 64847, `mechanic_immune_mask` = 33554496, `mingold` = 7100, `maxgold` = 7600, `AIName` = 'EventAI' WHERE `entry` = 34196; UPDATE `creature_template` SET `spell1` = 64852, `spell2` = 64870, `spell3` = 64847, `mechanic_immune_mask` = 33554496, `mingold` = 14200, `maxgold` = 15600 WHERE `entry` = 34245; DELETE FROM `creature_ai_scripts` WHERE (`creature_id`=34196); INSERT INTO `creature_ai_scripts` VALUES (3419601, 34196, 0, 0, 100, 1, 2000, 2000, 10000, 10000, 11, 64852, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 'Rune Etched Sentry - Cast Flaming Rune'), (3419602, 34196, 0, 0, 100, 1, 3000, 5000, 5000, 7000, 11, 64870, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 'Rune Etched Sentry - Cast Lava Burst'), (3419603, 34196, 0, 0, 100, 1, 2500, 3000, 12000, 15000, 11, 64847, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 'Rune Etched Sentry - Cast Runed Flame Jets'); -- Chamber Overseer UPDATE `creature_template` SET `spell1` = 64820, `spell2` = 64825, `mingold` = 7100, `maxgold` = 7600, `mechanic_immune_mask` = 33554496, `AIName` = 'EventAI' WHERE `entry` = 34197; UPDATE `creature_template` SET `spell1` = 64943, `spell2` = 64944, `mingold` = 14200, `maxgold` = 15600, `mechanic_immune_mask` = 33554496 WHERE `entry` = 34226; DELETE FROM `creature_ai_scripts` WHERE (`creature_id`=34197); INSERT INTO `creature_ai_scripts` VALUES (3419701, 34197, 0, 0, 100, 3, 4000, 8000, 6000, 9000, 11, 64820, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 'Chamber Overseer - Cast Devastating Leap 10'), (3419702, 34197, 0, 0, 100, 5, 4000, 8000, 6000, 9000, 11, 64943, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 'Chamber Overseer - Cast Devastating Leap 25'), (3419703, 34197, 0, 0, 100, 3, 10000, 12000, 8000, 12000, 11, 64825, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 'Chamber Overseer - Cast Staggering Roar 10'), (3419704, 34197, 0, 0, 100, 5, 10000, 12000, 8000, 12000, 11, 64944, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 'Chamber Overseer - Cast Staggering Roar 25'); -- Storm Tempered Keeper UPDATE `creature_template` SET `spell1` = 63541, `spell2` = 63630, `mingold` = 7100, `maxgold` = 7600, `mechanic_immune_mask` = 33554496, `AIName` = 'EventAI' WHERE `entry` = 33722; UPDATE `creature_template` SET `spell1` = 63541, `spell2` = 63630, `mingold` = 14200, `maxgold` = 15600, `mechanic_immune_mask` = 33554496 WHERE `entry` = 33723; DELETE FROM `creature_ai_scripts` WHERE (`creature_id`=33722); INSERT INTO `creature_ai_scripts` VALUES (3372201, 33722, 0, 0, 100, 1, 120000, 120000, 120000, 150000, 11, 63630, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 'Storm Tempered Keeper - Cast Vengeful Surge'), (3372202, 33722, 0, 0, 100, 1, 3000, 6000, 10000, 15000, 11, 63541, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 'Storm Tempered Keeper - Cast Forked Lightning'); -- Storm Tempered Keeper UPDATE `creature_template` SET `spell1` = 63541, `spell2` = 63630, `mingold` = 7100, `maxgold` = 7600, `mechanic_immune_mask` = 33554496, `AIName` = 'EventAI' WHERE `entry` = 33699; UPDATE `creature_template` SET `spell1` = 63541, `spell2` = 63630, `mingold` = 14200, `maxgold` = 15600, `mechanic_immune_mask` = 33554496 WHERE `entry` = 33700; DELETE FROM `creature_ai_scripts` WHERE (`creature_id`=33699); INSERT INTO `creature_ai_scripts` VALUES (3369901, 33699, 0, 0, 100, 1, 120000, 120000, 120000, 150000, 11, 63630, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 'Storm Tempered Keeper - Cast Vengeful Surge'), (3369902, 33699, 0, 0, 100, 1, 3000, 6000, 10000, 15000, 11, 63541, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 'Storm Tempered Keeper - Cast Forked Lightning'); -- Champion of Hodir UPDATE `creature_template` SET `spell1` = 64639, `mingold` = 7100, `maxgold` = 7600, `AIName` = 'EventAI' WHERE `entry` = 34133; UPDATE `creature_template` SET `spell1` = 64652, `mingold` = 14200, `maxgold` = 15600 WHERE `entry` = 34139; DELETE FROM `creature_ai_scripts` WHERE (`creature_id`=34133); INSERT INTO `creature_ai_scripts` VALUES (3413301, 34133, 0, 0, 100, 3, 3000, 6000, 12000, 16000, 11, 64639, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 'Champion of Hodir - Cast Stomp 10'), (3413302, 34133, 0, 0, 100, 5, 3000, 6000, 12000, 16000, 11, 64652, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 'Champion of Hodir - Cast Stomp 25'); -- Winter Jormungar UPDATE `creature_template` SET `spell1` = 64638, `AIName` = 'EventAI' WHERE `entry` = 34137; UPDATE `creature_template` SET `spell1` = 64638 WHERE `entry` = 34140; DELETE FROM `creature_ai_scripts` WHERE (`creature_id`=34137); INSERT INTO `creature_ai_scripts` VALUES (3413701, 34137, 0, 0, 100, 1, 3000, 6000, 6000, 9000, 11, 64638, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 'Winter Jormungar - Cast Acidic Bite'); UPDATE `creature` SET `spawndist` = 0 WHERE `id` = 34137; -- Winter Revenant UPDATE `creature_template` SET `spell1` = 64642, `spell2` = 64643, `spell3` = 64644, `mechanic_immune_mask` = 33554496, `mingold` = 7100, `maxgold` = 7600, `AIName` = 'EventAI' WHERE `entry` = 34134; UPDATE `creature_template` SET `spell1` = 64653, `spell2` = 64643, `spell3` = 64644, `mechanic_immune_mask` = 33554496, `mingold` = 14200, `maxgold` = 15600 WHERE `entry` = 34141; DELETE FROM `creature_ai_scripts` WHERE (`creature_id`=34134); INSERT INTO `creature_ai_scripts` VALUES (3413401, 34134, 0, 0, 100, 3, 8000, 12000, 15000, 20000, 11, 64642, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 'Winter Revenant - Cast Blizzard 10'), (3413402, 34134, 0, 0, 100, 5, 8000, 12000, 15000, 20000, 11, 64653, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 'Winter Revenant - Cast Blizzard 25'), (3413403, 34134, 0, 0, 100, 1, 3000, 5000, 10000, 12000, 11, 64643, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 'Winter Revenant - Cast Whirling Strike'), (3413404, 34134, 0, 0, 100, 1, 15000, 20000, 60000, 75000, 11, 64644, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 'Winter Revenant - Cast Shield of the Winter Revenant'); -- Winter Rumbler UPDATE `creature_template` SET `spell1` = 64645, `spell2` = 64647, `mingold` = 7100, `maxgold` = 7600, `mechanic_immune_mask` = 33554496, `AIName` = 'EventAI' WHERE `entry` = 34135; UPDATE `creature_template` SET `spell1` = 64645, `spell2` = 64654, `mingold` = 14200, `maxgold` = 15600, `mechanic_immune_mask` = 33554496 WHERE `entry` = 34142; DELETE FROM `creature_ai_scripts` WHERE (`creature_id`=34135); INSERT INTO `creature_ai_scripts` VALUES (3413501, 34135, 0, 0, 100, 1, 6000, 12000, 10000, 16000, 11, 64645, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 'Winter Rumbler - Cast Cone of Cold'), (3413502, 34135, 0, 0, 100, 3, 3000, 6000, 8000, 12000, 11, 64647, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 'Winter Rumbler - Cast Snow Blindness 10'), (3413503, 34135, 0, 0, 100, 5, 3000, 6000, 8000, 12000, 11, 64654, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 'Winter Rumbler - Cast Snow Blindness 25'); -- Guardian Lasher UPDATE `creature_template` SET `spell1` = 63007, `spell2` = 63047, `mingold` = 7100, `maxgold` = 7600, `mechanic_immune_mask` = 33554496, `AIName` = 'EventAI' WHERE `entry` = 33430; UPDATE `creature_template` SET `spell1` = 63007, `spell2` = 63550, `mingold` = 14200, `maxgold` = 15600, `mechanic_immune_mask` = 33554496 WHERE `entry` = 33732; DELETE FROM `creature_ai_scripts` WHERE (`creature_id`=33430); INSERT INTO `creature_ai_scripts` VALUES (3343001, 33430, 4, 0, 100, 1, 0, 0, 0, 0, 11, 63007, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 'Guardian Lasher - Cast Guardian Pheromones'), (3343002, 33430, 0, 0, 100, 3, 3000, 6000, 10000, 14000, 11, 63047, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 'Guardian Lasher - Cast Guardian''s Lash 10'), (3343003, 33430, 0, 0, 100, 5, 3000, 6000, 10000, 14000, 11, 63550, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 'Guardian Lasher - Cast Guardian''s Lash 25'); -- Forest Swarmer UPDATE `creature_template` SET `spell1` = 63059, `mingold` = 7100, `maxgold` = 7600, `AIName` = 'EventAI' WHERE `entry` = 33431; UPDATE `creature_template` SET `spell1` = 63059, `mingold` = 14200, `maxgold` = 15600 WHERE `entry` = 33731; DELETE FROM `creature_ai_scripts` WHERE (`creature_id`=33431); INSERT INTO `creature_ai_scripts` VALUES (3343101, 33431, 0, 0, 100, 1, 3000, 9000, 10000, 20000, 11, 63059, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 'Forest Swarmer - Cast Pollinate'); DELETE FROM conditions WHERE SourceEntry = 63059; INSERT INTO `conditions` VALUES ('13','0','63059','0','18','1','33430','0','0','',NULL); -- Guardian of Life UPDATE `creature_template` SET `spell1` = 63226, `mingold` = 7100, `maxgold` = 7600, `AIName` = 'EventAI' WHERE `entry` = 33528; UPDATE `creature_template` SET `spell1` = 63551, `mingold` = 14200, `maxgold` = 15600 WHERE `entry` = 33733; DELETE FROM `creature_ai_scripts` WHERE (`creature_id`=33528); INSERT INTO `creature_ai_scripts` VALUES (3352801, 33528, 0, 0, 100, 3, 3000, 9000, 15000, 20000, 11, 63226, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 'Guardian of Life - Cast Poison Breath 10'), (3352802, 33528, 0, 0, 100, 5, 3000, 9000, 15000, 20000, 11, 63551, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 'Guardian of Life - Cast Poison Breath 25'); -- Nature's Blade UPDATE `creature_template` SET `spell1` = 63247, `mingold` = 7100, `maxgold` = 7600, `AIName` = 'EventAI' WHERE `entry` = 33527; UPDATE `creature_template` SET `spell1` = 63568, `mingold` = 14200, `maxgold` = 15600 WHERE `entry` = 33741; DELETE FROM `creature_ai_scripts` WHERE (`creature_id`=33527); INSERT INTO `creature_ai_scripts` VALUES (3352701, 33527, 0, 0, 100, 3, 3000, 9000, 18000, 24000, 11, 63247, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 'Nature Blade - Cast Living Tsunami 10'), (3352702, 33527, 0, 0, 100, 5, 3000, 9000, 18000, 24000, 11, 63568, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 'Nature Blade - Cast Living Tsunami 25'); -- Ironroot Lasher UPDATE `creature_template` SET `spell1` = 63240, `mingold` = 7100, `maxgold` = 7600, `AIName` = 'EventAI' WHERE `entry` = 33526; UPDATE `creature_template` SET `spell1` = 63553, `mingold` = 14200, `maxgold` = 15600 WHERE `entry` = 33734; DELETE FROM `creature_ai_scripts` WHERE (`creature_id`=33526); INSERT INTO `creature_ai_scripts` VALUES (3352601, 33526, 0, 0, 100, 3, 3000, 8000, 12000, 16000, 11, 63240, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 'Ironroot Lasher - Cast Ironroot Thorns 10'), (3352602, 33526, 0, 0, 100, 5, 3000, 8000, 12000, 16000, 11, 63553, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 'Ironroot Lasher - Cast Ironroot Thorns 25'); -- Mangrove Ent UPDATE `creature_template` SET `spell1` = 63272, `spell2` = 63242, `spell3` = 63241, `mingold` = 7100, `maxgold` = 7600, `AIName` = 'EventAI' WHERE `entry` = 33525; UPDATE `creature_template` SET `spell1` = 63272, `spell2` = 63556, `spell3` = 63554, `mingold` = 14200, `maxgold` = 15600 WHERE `entry` = 33735; DELETE FROM `creature_ai_scripts` WHERE (`creature_id`=33525); INSERT INTO `creature_ai_scripts` VALUES (3352501, 33525, 0, 0, 100, 1, 8000, 12000, 25000, 30000, 11, 63272, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 'Mangrove Ent - Cast Hurricane'), (3352502, 33525, 0, 0, 100, 3, 12000, 16000, 12000, 16000, 11, 63242, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 'Mangrove Ent - Cast Nourish 10'), (3352503, 33525, 0, 0, 100, 5, 12000, 16000, 12000, 16000, 11, 63556, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 'Mangrove Ent - Cast Nourish 25'), (3352504, 33525, 0, 0, 100, 3, 25000, 30000, 25000, 30000, 11, 63241, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 'Mangrove Ent - Cast Tranquility 10'), (3352505, 33525, 0, 0, 100, 5, 25000, 30000, 25000, 30000, 11, 63554, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 'Mangrove Ent - Cast Tranquility 25'); -- Misguided Nymph UPDATE `creature_template` SET `spell1` = 63082, `spell2` = 63111, `spell3` = 63136, `mingold` = 7100, `maxgold` = 7600, `AIName` = 'EventAI' WHERE `entry` = 33355; UPDATE `creature_template` SET `spell1` = 63559, `spell2` = 63562, `spell3` = 63564, `mingold` = 14200, `maxgold` = 15600 WHERE `entry` = 33737; DELETE FROM `creature_ai_scripts` WHERE (`creature_id`=33355); INSERT INTO `creature_ai_scripts` VALUES (3335501, 33355, 0, 0, 100, 3, 8000, 12000, 25000, 30000, 11, 63082, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 'Misguided Nymph - Cast Bind Life 10'), (3335502, 33355, 0, 0, 100, 5, 8000, 12000, 25000, 30000, 11, 63559, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 'Misguided Nymph - Cast Bind Life 25'), (3335503, 33355, 0, 0, 100, 3, 4000, 6000, 12000, 16000, 11, 63111, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 'Misguided Nymph - Cast Frost Spear 10'), (3335504, 33355, 0, 0, 100, 5, 4000, 6000, 12000, 16000, 11, 63562, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 'Misguided Nymph - Cast Frost Spear 25'), (3335505, 33355, 0, 0, 100, 3, 15000, 20000, 15000, 20000, 11, 63136, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 'Misguided Nymph - Cast Winter''s Embrace 10'), (3335506, 33355, 0, 0, 100, 5, 15000, 20000, 15000, 20000, 11, 63564, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 'Misguided Nymph - Cast Winter''s Embrace 25'); -- Corrupted Servitor UPDATE `creature_template` SET `spell1` = 63169, `spell2` = 63149, `mingold` = 7100, `maxgold` = 7600, `mechanic_immune_mask` = 33554496, `AIName` = 'EventAI' WHERE `entry` = 33354; UPDATE `creature_template` SET `spell1` = 63549, `spell2` = 63149, `mingold` = 14200, `maxgold` = 15600, `mechanic_immune_mask` = 33554496 WHERE `entry` = 33729; DELETE FROM `creature_ai_scripts` WHERE (`creature_id`=33354); INSERT INTO `creature_ai_scripts` VALUES (3335401, 33354, 0, 0, 100, 3, 2000, 4000, 20000, 25000, 11, 63169, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 'Corrupted Servitor - Cast Petrify Joints 10'), (3335402, 33354, 0, 0, 100, 5, 2000, 4000, 20000, 25000, 11, 63549, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 'Corrupted Servitor - Cast Petrify Joints 25'), (3335403, 33354, 0, 0, 100, 1, 6000, 8000, 12000, 16000, 11, 63149, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 'Corrupted Servitor - Cast Violent Earth'); -- Arachnopod Destroyer UPDATE `creature_template` SET `spell1` = 64717, `spell2` = 64776, `mingold` = 7100, `maxgold` = 7600, `mechanic_immune_mask` = 33554496, `AIName` = 'EventAI' WHERE `entry` = 34183; UPDATE `creature_template` SET `spell1` = 64717, `spell2` = 64776, `mingold` = 14200, `maxgold` = 15600, `mechanic_immune_mask` = 33554496 WHERE `entry` = 34214; DELETE FROM `creature_ai_scripts` WHERE (`creature_id`=34183); INSERT INTO `creature_ai_scripts` VALUES (3418301, 34183, 0, 0, 100, 1, 2000, 4000, 12000, 16000, 11, 64717, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 'Arachnopod Destroyer - Cast Flame Spray'), (3418302, 34183, 0, 0, 100, 1, 8000, 10000, 12000, 16000, 11, 64776, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 'Arachnopod Destroyer - Cast Machine Gun'); -- Boomer XP-500 UPDATE `creature_template` SET `spell1` = 55714, `AIName` = 'EventAI' WHERE `entry` = 34192; UPDATE `creature_template` SET `spell1` = 55714 WHERE `entry` = 34216; DELETE FROM `creature_ai_scripts` WHERE (`creature_id`=34192); INSERT INTO `creature_ai_scripts` VALUES (3419201, 34192, 9, 0, 100, 1, 0, 3, 0, 0, 11, 55714, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 'Boomer XP-500 - Explode'); -- Clockwork Sapper UPDATE `creature_template` SET `spell1` = 64740, `mingold` = 7100, `maxgold` = 7600, `mechanic_immune_mask` = 33554496, `AIName` = 'EventAI' WHERE `entry` = 34193; UPDATE `creature_template` SET `spell1` = 64740, `mingold` = 14200, `maxgold` = 15600, `mechanic_immune_mask` = 33554496 WHERE `entry` = 34220; DELETE FROM `creature_ai_scripts` WHERE (`creature_id`=34193); INSERT INTO `creature_ai_scripts` VALUES (3419301, 34193, 0, 0, 100, 1, 2000, 6000, 12000, 16000, 11, 64740, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 'Clockwork Sapper - Cast Energy Sap'); -- Twilight Adherent UPDATE `creature_template` SET `spell1` = 64663, `spell2` = 63760, `spell3` = 13704, `equipment_id` = 1848, `mechanic_immune_mask` = 33554513, `unit_class` = 2, `mingold` = 7100, `maxgold` = 7600, `AIName` = 'EventAI' WHERE `entry` = 33818; UPDATE `creature_template` SET `spell1` = 64663, `spell2` = 63760, `spell3` = 13704, `equipment_id` = 1848, `mechanic_immune_mask` = 33554513, `unit_class` = 2, `mingold` = 14200, `maxgold` = 15600 WHERE `entry` = 33827; DELETE FROM `creature_ai_scripts` WHERE (`creature_id`=33818); INSERT INTO `creature_ai_scripts` VALUES (3381801, 33818, 0, 0, 100, 1, 10000, 16000, 20000, 25000, 11, 64663, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 'Twilight Adherent - Cast Arcane Burst'), (3381802, 33818, 0, 0, 100, 1, 18000, 24000, 20000, 24000, 11, 63760, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 'Twilight Adherent - Cast Greater Heal'), (3381803, 33818, 0, 0, 100, 1, 2000, 4000, 10000, 16000, 11, 13704, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 'Twilight Adherent - Cast Psychic Scream'); -- Twilight Guardian UPDATE `creature_template` SET `spell1` = 52719, `spell2` = 62317, `spell3` = 63757, `mechanic_immune_mask` = 33554513, `equipment_id` = 1852, `mingold` = 7100, `maxgold` = 7600, `AIName` = 'EventAI' WHERE `entry` = 33822; UPDATE `creature_template` SET `spell1` = 52719, `spell2` = 62317, `spell3` = 63757, `mechanic_immune_mask` = 33554513, `equipment_id` = 1852, `mingold` = 14200, `maxgold` = 15600 WHERE `entry` = 33828; DELETE FROM `creature_ai_scripts` WHERE (`creature_id`=33822); INSERT INTO `creature_ai_scripts` VALUES (3382201, 33822, 0, 0, 100, 1, 6000, 10000, 8000, 10000, 11, 52719, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 'Twilight Guardian - Cast Concussion Blow'), (3382202, 33822, 0, 0, 100, 1, 2000, 3000, 3000, 6000, 11, 62317, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 'Twilight Guardian - Cast Devastate'), (3382203, 33822, 0, 0, 100, 1, 16000, 18000, 14000, 16000, 11, 63757, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 'Twilight Guardian - Cast Thunderclap'); -- Twilight Shadowblade UPDATE `creature_template` SET `spell1` = 63753, `mechanic_immune_mask` = 33554513, `equipment_id` = 1862, `baseattacktime` = 1000, `mingold` = 7100, `maxgold` = 7600, `AIName` = 'EventAI' WHERE `entry` = 33824; UPDATE `creature_template` SET `spell1` = 63753, `mechanic_immune_mask` = 33554513, `equipment_id` = 1862, `baseattacktime` = 1000, `mingold` = 7100, `maxgold` = 7600 WHERE `entry` = 33831; DELETE FROM `creature_ai_scripts` WHERE (`creature_id`=33824); INSERT INTO `creature_ai_scripts` VALUES (3382401, 33824, 0, 0, 100, 5, 6000, 8000, 14000, 16000, 11, 63753, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 'Twilight Shadowblade - Cast Fan of Knives'); -- Twilight Slayer UPDATE `creature_template` SET `spell1` = 63784, `spell2` = 35054, `mechanic_immune_mask` = 33554513, `equipment_id` = 1847, `mingold` = 7100, `maxgold` = 7600, `AIName` = 'EventAI' WHERE `entry` = 33823; UPDATE `creature_template` SET `spell1` = 63784, `spell2` = 35054, `mechanic_immune_mask` = 33554513, `equipment_id` = 1847, `mingold` = 14200, `maxgold` = 15600 WHERE `entry` = 33832; DELETE FROM `creature_ai_scripts` WHERE (`creature_id`=33823); INSERT INTO `creature_ai_scripts` VALUES (3382301, 33823, 0, 0, 100, 1, 3000, 5000, 16000, 20000, 11, 35054, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 'Twilight Slayer - Cast Mortal Strike'), (3382302, 33823, 0, 0, 100, 1, 9000, 12000, 28000, 34000, 11, 63784, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 'Twilight Slayer - Cast Bladestorm'); UPDATE `creature_template` SET `equipment_id` = 1849 WHERE `entry` = 32885; UPDATE `creature_template` SET `equipment_id` = 1850 WHERE `entry` = 32908; -- Faceless Horror UPDATE `creature_template` SET `spell1` = 64429, `spell2` = 63722, `spell3` = 63710, `spell4` = 63703, `mechanic_immune_mask` = 33554513, `mingold` = 7100, `maxgold` = 7600, `AIName` = 'EventAI' WHERE `entry` = 33772; UPDATE `creature_template` SET `spell1` = 64429, `spell2` = 63722, `spell3` = 63710, `spell4` = 63703, `mechanic_immune_mask` = 33554513, `mingold` = 14200, `maxgold` = 15600 WHERE `entry` = 33773; DELETE FROM `creature_ai_scripts` WHERE (`creature_id`=33772); INSERT INTO `creature_ai_scripts` VALUES (3377201, 33772, 0, 0, 100, 1, 18000, 22000, 15000, 20000, 11, 64429, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 'Faceless Horror - Cast Death Grip'), (3377202, 33772, 0, 0, 100, 1, 2000, 4000, 10000, 12000, 11, 63722, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 'Faceless Horror - Cast Shadow Crash'), (3377203, 33772, 4, 0, 100, 1, 0, 0, 0, 0, 11, 63703, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 'Faceless Horror - Cast Void Wave'); -- Twilight Frost Mage UPDATE `creature_template` SET `spell1` = 64663, `spell2` = 63758, `spell3` = 63912, `spell4` = 63913, `equipment_id` = 1849, `mechanic_immune_mask` = 33554513, `unit_class` = 2, `mingold` = 7100, `maxgold` = 7600, `AIName` = 'EventAI' WHERE `entry` = 33819; UPDATE `creature_template` SET `spell1` = 64663, `spell2` = 63758, `spell3` = 63912, `spell4` = 63913, `equipment_id` = 1849, `mechanic_immune_mask` = 33554513, `unit_class` = 2, `mingold` = 14200, `maxgold` = 15600 WHERE `entry` = 33829; DELETE FROM `creature_ai_scripts` WHERE (`creature_id`=33819); INSERT INTO `creature_ai_scripts` VALUES (3381901, 33819, 0, 0, 100, 1, 10000, 16000, 20000, 25000, 11, 64663, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 'Twilight Frost Mage - Cast Arcane Burst'), (3381902, 33819, 0, 0, 100, 1, 1000, 2000, 6000, 8000, 11, 63913, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 'Twilight Frost Mage - Cast Frostbolt'), (3381903, 33819, 0, 0, 100, 1, 2000, 4000, 10000, 16000, 11, 63758, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 'Twilight Frost Mage - Cast Frost Bolt Volley'), (3381904, 33819, 0, 0, 100, 1, 8000, 10000, 12000, 16000, 11, 63912, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 'Twilight Frost Mage - Cast Frost Nova'); -- Twilight Pyromancer UPDATE `creature_template` SET `spell1` = 64663, `spell2` = 63789, `spell3` = 63775, `equipment_id` = 1848, `mechanic_immune_mask` = 33554513, `unit_class` = 2, `mingold` = 7100, `maxgold` = 7600, `AIName` = 'EventAI' WHERE `entry` = 33820; UPDATE `creature_template` SET `spell1` = 64663, `spell2` = 63789, `spell3` = 63775, `equipment_id` = 1848, `mechanic_immune_mask` = 33554513, `unit_class` = 2, `mingold` = 14200, `maxgold` = 15600 WHERE `entry` = 33830; DELETE FROM `creature_ai_scripts` WHERE (`creature_id`=33820); INSERT INTO `creature_ai_scripts` VALUES (3382001, 33820, 0, 0, 100, 1, 10000, 16000, 20000, 25000, 11, 64663, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 'Twilight Pyromancer - Cast Arcane Burst'), (3382002, 33820, 0, 0, 100, 1, 1000, 2000, 6000, 8000, 11, 63789, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 'Twilight Pyromancer - Cast Fireball'), (3382003, 33820, 0, 0, 100, 1, 2000, 4000, 10000, 16000, 11, 63775, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 'Twilight Pyromancer - Cast Flamestrike'); -- Enslaved Fire Elemental UPDATE `creature_template` SET `spell1` = 38064, `spell2` = 63778, `mechanic_immune_mask` = 33554513, `AIName` = 'EventAI' WHERE `entry` = 33838; DELETE FROM `creature_ai_scripts` WHERE (`creature_id`=33838); INSERT INTO `creature_ai_scripts` VALUES (3383801, 33838, 0, 0, 100, 1, 4000, 8000, 12000, 14000, 11, 38064, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 'Enslaved Fire Elemental - Cast Blast Wave'), (3383802, 33838, 4, 0, 100, 1, 0, 0, 0, 0, 11, 63778, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 'Enslaved Fire Elemental - Cast Fire Shield');
PLSQL
#Requires -Version 3.0 Param( [string] [Parameter(Mandatory=$true)] $ResourceGroupLocation, [string] $ResourceGroupName = 'ARMApplication', [switch] $UploadArtifacts, [string] $StorageAccountName, [string] $StorageContainerName = $ResourceGroupName.ToLowerInvariant() + '-stageartifacts', [string] $TemplateFile = 'LogicApp.json', [string] $TemplateParametersFile = 'LogicApp.parameters.json', [string] $ArtifactStagingDirectory = '.', [string] $DSCSourceFolder = 'DSC', [switch] $ValidateOnly ) try { [Microsoft.Azure.Common.Authentication.AzureSession]::ClientFactory.AddUserAgent("VSAzureTools-$UI$($host.name)".replace(' ','_'), '3.0.0') } catch { } $ErrorActionPreference = 'Stop' Set-StrictMode -Version 3 function Format-ValidationOutput { param ($ValidationOutput, [int] $Depth = 0) Set-StrictMode -Off return @($ValidationOutput | Where-Object { $_ -ne $null } | ForEach-Object { @(' ' * $Depth + ': ' + $_.Message) + @(Format-ValidationOutput @($_.Details) ($Depth + 1)) }) } $OptionalParameters = New-Object -TypeName Hashtable $TemplateFile = [System.IO.Path]::GetFullPath([System.IO.Path]::Combine($PSScriptRoot, $TemplateFile)) $TemplateParametersFile = [System.IO.Path]::GetFullPath([System.IO.Path]::Combine($PSScriptRoot, $TemplateParametersFile)) if ($UploadArtifacts) { # Convert relative paths to absolute paths if needed $ArtifactStagingDirectory = [System.IO.Path]::GetFullPath([System.IO.Path]::Combine($PSScriptRoot, $ArtifactStagingDirectory)) $DSCSourceFolder = [System.IO.Path]::GetFullPath([System.IO.Path]::Combine($PSScriptRoot, $DSCSourceFolder)) # Parse the parameter file and update the values of artifacts location and artifacts location SAS token if they are present $JsonParameters = Get-Content $TemplateParametersFile -Raw | ConvertFrom-Json if (($JsonParameters | Get-Member -Type NoteProperty 'parameters') -ne $null) { $JsonParameters = $JsonParameters.parameters } $ArtifactsLocationName = '_artifactsLocation' $ArtifactsLocationSasTokenName = '_artifactsLocationSasToken' $OptionalParameters[$ArtifactsLocationName] = $JsonParameters | Select -Expand $ArtifactsLocationName -ErrorAction Ignore | Select -Expand 'value' -ErrorAction Ignore $OptionalParameters[$ArtifactsLocationSasTokenName] = $JsonParameters | Select -Expand $ArtifactsLocationSasTokenName -ErrorAction Ignore | Select -Expand 'value' -ErrorAction Ignore # Create DSC configuration archive if (Test-Path $DSCSourceFolder) { $DSCSourceFilePaths = @(Get-ChildItem $DSCSourceFolder -File -Filter '*.ps1' | ForEach-Object -Process {$_.FullName}) foreach ($DSCSourceFilePath in $DSCSourceFilePaths) { $DSCArchiveFilePath = $DSCSourceFilePath.Substring(0, $DSCSourceFilePath.Length - 4) + '.zip' Publish-AzureRmVMDscConfiguration $DSCSourceFilePath -OutputArchivePath $DSCArchiveFilePath -Force -Verbose } } # Create a storage account name if none was provided if ($StorageAccountName -eq '') { $StorageAccountName = 'stage' + ((Get-AzureRmContext).Subscription.SubscriptionId).Replace('-', '').substring(0, 19) } $StorageAccount = (Get-AzureRmStorageAccount | Where-Object{$_.StorageAccountName -eq $StorageAccountName}) # Create the storage account if it doesn't already exist if ($StorageAccount -eq $null) { $StorageResourceGroupName = 'ARM_Deploy_Staging' New-AzureRmResourceGroup -Location "$ResourceGroupLocation" -Name $StorageResourceGroupName -Force $StorageAccount = New-AzureRmStorageAccount -StorageAccountName $StorageAccountName -Type 'Standard_LRS' -ResourceGroupName $StorageResourceGroupName -Location "$ResourceGroupLocation" } # Generate the value for artifacts location if it is not provided in the parameter file if ($OptionalParameters[$ArtifactsLocationName] -eq $null) { $OptionalParameters[$ArtifactsLocationName] = $StorageAccount.Context.BlobEndPoint + $StorageContainerName } # Copy files from the local storage staging location to the storage account container New-AzureStorageContainer -Name $StorageContainerName -Context $StorageAccount.Context -ErrorAction SilentlyContinue *>&1 $ArtifactFilePaths = Get-ChildItem $ArtifactStagingDirectory -Recurse -File | ForEach-Object -Process {$_.FullName} foreach ($SourcePath in $ArtifactFilePaths) { Set-AzureStorageBlobContent -File $SourcePath -Blob $SourcePath.Substring($ArtifactStagingDirectory.length + 1) ` -Container $StorageContainerName -Context $StorageAccount.Context -Force } # Generate a 4 hour SAS token for the artifacts location if one was not provided in the parameters file if ($OptionalParameters[$ArtifactsLocationSasTokenName] -eq $null) { $OptionalParameters[$ArtifactsLocationSasTokenName] = ConvertTo-SecureString -AsPlainText -Force ` (New-AzureStorageContainerSASToken -Container $StorageContainerName -Context $StorageAccount.Context -Permission r -ExpiryTime (Get-Date).AddHours(4)) } } # Create or update the resource group using the specified template file and template parameters file New-AzureRmResourceGroup -Name $ResourceGroupName -Location $ResourceGroupLocation -Verbose -Force if ($ValidateOnly) { $ErrorMessages = Format-ValidationOutput (Test-AzureRmResourceGroupDeployment -ResourceGroupName $ResourceGroupName ` -TemplateFile $TemplateFile ` -TemplateParameterFile $TemplateParametersFile ` @OptionalParameters) if ($ErrorMessages) { Write-Output '', 'Validation returned the following errors:', @($ErrorMessages), '', 'Template is invalid.' } else { Write-Output '', 'Template is valid.' } } else { New-AzureRmResourceGroupDeployment -Name ((Get-ChildItem $TemplateFile).BaseName + '-' + ((Get-Date).ToUniversalTime()).ToString('MMdd-HHmm')) ` -ResourceGroupName $ResourceGroupName ` -TemplateFile $TemplateFile ` -TemplateParameterFile $TemplateParametersFile ` @OptionalParameters ` -Force -Verbose ` -ErrorVariable ErrorMessages if ($ErrorMessages) { Write-Output '', 'Template deployment returned the following errors:', @(@($ErrorMessages) | ForEach-Object { $_.Exception.Message.TrimEnd("`r`n") }) } }
PowerShell
use bevy::prelude::*; #[derive(Debug)] pub struct TargetGraphics { entity: Entity, } impl TargetGraphics { pub fn new(entity: Entity) -> Self { Self { entity } } pub fn entity(&self) -> Entity { self.entity } }
RenderScript
--[[ Copyright (C) 2014-2017 - Eloi Carbo This program is free software: you can redistribute it and/or modify it under the terms of the GNU 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 General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ]]-- local fs = require "nixio.fs" local filters_dir = "/etc/bird6/filters/" local lock_file = "/etc/bird6/filter_lock" m = SimpleForm("bird6", "Bird6 Filters", "<b>INFO:</b> New files are created using Timestamps.<br />In order to make it easier to handle, use SSH to connect to your terminal and rename those files.<br />If your file is not correctly shown in the list, please, refresh your browser.") s = m:section(SimpleSection) files = s:option(ListValue, "Files", "Filter Files:") local new_filter = filters_dir .. os.date("filter-%Y%m%d-%H%M") -- New File Entry files:value(new_filter, "New File (".. new_filter .. ")") files.default = new_filter local i, file_list = 0, { } for filename in io.popen("find " .. filters_dir .. " -type f"):lines() do i = i + 1 files:value(filename, filename) end ld = s:option(Button, "_load", "Load File") ld.inputstyle = "reload" st_file = s:option(DummyValue, "_stfile", "Editing file:") function st_file.cfgvalue(self, section) if ld:formvalue(section) then fs.writefile(lock_file, files:formvalue(section)) return files:formvalue(section) else fs.writefile(lock_file, "") return "" end end area = s:option(Value, "_filters") area.template = "bird6/tvalue" area.rows = 30 function area.cfgvalue(self,section) if ld:formvalue(section) then local contents = fs.readfile(files:formvalue(section)) if contents then return contents else return "" end else return "" end end function area.write(self, section) local locked_file = fs.readfile(lock_file) if locked_file and not ld:formvalue(section) then local text = self:formvalue(section):gsub("\r\n?", "\n") fs.writefile(locked_file, text) fs.writefile(lock_file, "") end end return m
Lua
<?php namespace App\Http\Controllers\Admin; use App\Calendario; use App\Http\Controllers\Controller; use App\Http\Requests\MassDestroyCalendarioRequest; use App\Http\Requests\StoreCalendarioRequest; use App\Http\Requests\UpdateCalendarioRequest; use Gate; use Illuminate\Http\Request; use Symfony\Component\HttpFoundation\Response; class CalendarioController extends Controller { public function index() { abort_if(Gate::denies('calendario_access'), Response::HTTP_FORBIDDEN, '403 Forbidden'); $calendarios = Calendario::all(); return view('admin.calendarios.index', compact('calendarios')); } public function create() { abort_if(Gate::denies('calendario_create'), Response::HTTP_FORBIDDEN, '403 Forbidden'); return view('admin.calendarios.create'); } public function store(StoreCalendarioRequest $request) { $calendario = Calendario::create($request->all()); return redirect()->route('admin.calendarios.index'); } public function edit(Calendario $calendario) { abort_if(Gate::denies('calendario_edit'), Response::HTTP_FORBIDDEN, '403 Forbidden'); return view('admin.calendarios.edit', compact('calendario')); } public function update(UpdateCalendarioRequest $request, Calendario $calendario) { $calendario->update($request->all()); return redirect()->route('admin.calendarios.index'); } public function show(Calendario $calendario) { abort_if(Gate::denies('calendario_show'), Response::HTTP_FORBIDDEN, '403 Forbidden'); return view('admin.calendarios.show', compact('calendario')); } public function destroy(Calendario $calendario) { abort_if(Gate::denies('calendario_delete'), Response::HTTP_FORBIDDEN, '403 Forbidden'); $calendario->delete(); return back(); } public function massDestroy(MassDestroyCalendarioRequest $request) { Calendario::whereIn('id', request('ids'))->delete(); return response(null, Response::HTTP_NO_CONTENT); } }
Hack
module Main where import Neuron import Trainingdata import Backpropagation import Utils import TopologyParser import TraindataParser import GraphicInterface import Text.Printf import Data.Char import System.Environment import Control.Monad {-- use main and call there some examples for GHC compiler GHCi can call examples directly --} main = do args <- getArgs let usecase = (args !! 0) let steps | (length args >= 2) = readI (args !! 1) | otherwise = 100 let saveAction | (length args == 3) = (args !! 2) | otherwise = "" case (args !! 0) of "pgm1" -> universalUseCase (staticPPMexample steps) saveAction "xor" -> universalUseCase (xorExample steps) saveAction "num" -> universalUseCase (numberPPMexample steps) saveAction "demo" -> demo steps "demoXor" -> demoXor steps test :: [Double] -> Double test xs = sum xs universalUseCase net action = do pureNet <- net putStrLn (show pureNet) showError pureNet ------------------------------------------------------------------------ -- trained networks ------------------------------------------------------------------------ xorExample steps = do net <- initNetworkFromFile (dataPath ++ "traindata/xor/topology") tdata <- initTraindata (dataPath ++ "traindata/xor/trainingdata") let trainedNet = trainNet net tdata steps 0.35 0.15 return trainedNet staticPPMexample 0 = staticPPMexample 100 staticPPMexample steps = do let path = dataPath ++ "traindata/img/17_22_lucida/" in0 <- readPPMFile (path ++ "0.pgm") in1 <- readPPMFile (path ++ "1.pgm") in2 <- readPPMFile (path ++ "2.pgm") in3 <- readPPMFile (path ++ "3.pgm") in4 <- readPPMFile (path ++ "4.pgm") in5 <- readPPMFile (path ++ "5.pgm") in6 <- readPPMFile (path ++ "6.pgm") in7 <- readPPMFile (path ++ "7.pgm") in8 <- readPPMFile (path ++ "8.pgm") in9 <- readPPMFile (path ++ "9.pgm") let inputValues = [in0,in1,in2,in3,in4,in5,in6,in7,in8,in9] let outputValues = getOutputMatrix (length inputValues) let tdata = Trainingdata (length inputValues) inputValues outputValues -- input neurons 10 x 12 = 120 net <- initNetwork "374b\n10b\n10" let trainedNet = trainNet net tdata steps 0.35 0.15 return trainedNet numberPPMexample :: Int -> IO Network numberPPMexample steps = do let path = dataPath ++ "traindata/img/10_12_arial/" tdata <- dirToTrainData path net <- initNetworkFromTdata tdata return (trainNet net tdata steps 0.35 0.15) ------------------------------------------------------------------------ -- DEMOS ------------------------------------------------------------------------ demo steps = do let path = "traindata/img/10_12_arial/" tdata <- dirToTrainData (dataPath ++ path) nt <- initNetworkFromTdata tdata let net = trainNet nt tdata steps 0.35 0.15 putStrLn ("training folder: " ++ path) showNumsOutput net path putStrLn "----------------------------------" putStrLn "pattern folder: traindata/img/10_12_great_times/" showNumsOutput net "traindata/img/10_12_great_times/" demoXor steps = do trainedNet <- xorExample steps putStr "0.0 XOR 0.0 = " showOutput trainedNet [0.0, 0.0] putStr "1.0 XOR 0.0 = " showOutput trainedNet [1.0, 0.0] putStr "0.0 XOR 1.0 = " showOutput trainedNet [0.0, 1.0] putStr "1.0 XOR 1.0 = " showOutput trainedNet [1.0, 1.0]
Haskell
(import * from layout) (import * from gui) (defun ttt () (let** ((w (window 0 0 400 400 title: "T-T-T")) (color 0) (#'cell() (let ((div (set-style (create-element "div") position "absolute" textAlign "center" backgroundColor "#EEEEEE"))) (setf div."data-resize" (lambda (x0 y0 x1 y1) (declare (ignorable x0 x1)) (setf div.style.fontSize (+ (* (- y1 y0) 0.9) "px")))) (set-handler div onclick (when (= div.textContent "") (setf div.textContent (aref "OX" color)) (setf color (- 1 color)))) (add-widget w div)))) (set-layout w (V border: 16 spacing: 8 (H (dom (cell)) (dom (cell)) (dom (cell))) (H (dom (cell)) (dom (cell)) (dom (cell))) (H (dom (cell)) (dom (cell)) (dom (cell))))) (show-window w center: true))) (defun main () (ttt)) (main)
Common Lisp
module P20StateTaxSpec (main,spec) where import Test.Hspec import Test.Hspec.QuickCheck import Test.QuickCheck((==>)) import P20StateTax hiding (main) main :: IO () main = hspec spec spec :: Spec spec = do describe "getTaxAmt" $ do prop "has the property of returning 0.005 times amount for wisconsin, eau clair" $ \amt -> getTaxAmt "wisconsin" "eau clair" amt `shouldBe` amt * 0.005 prop "has the property of returning 0.005 times amount for wn, eau clair" $ \amt -> getTaxAmt "wn" "eau clair" amt `shouldBe` amt * 0.005 prop "has the property of returning 0.004 times amount for wisconsin, dunn" $ \amt -> getTaxAmt "wisconsin" "dunn" amt `shouldBe` amt * 0.004 prop "has the property of returning 0.004 times amount for wn, dunn" $ \amt -> getTaxAmt "wn" "dunn" amt `shouldBe` amt * 0.004 prop "has the property of returning 0.08 times amount for illinois, (anything)" $ \amt county-> getTaxAmt "illinois" county amt `shouldBe` amt * 0.08 prop "has the property of returning 0.08 times amount for il, (anything)" $ \amt county -> getTaxAmt "il" county amt `shouldBe` amt * 0.08 prop "has the property of returning 0.2 times amount for oxfordshire, (anything)" $ \amt area -> getTaxAmt "oxfordshire" area amt `shouldBe` amt * 0.2 prop "has the property of returning 0.2 times amount for oxon, (anything)" $ \amt area -> getTaxAmt "oxon" area amt `shouldBe` amt * 0.2 prop "has the property of returning 0 for all other places" $ \amt state county -> state `notElem` [ "wisconsin" , "wn" , "illinois" , "il" , "oxfordshire" , "oxon" ] ==> getTaxAmt state county amt `shouldBe` 0 describe "getTaxAmt'" $ do prop "has the property of returning 0.005 times amount for wisconsin, eau clair" $ \amt -> getTaxAmt' "wisconsin" "eau clair" amt `shouldBe` amt * 0.005 prop "has the property of returning 0.005 times amount for wn, eau clair" $ \amt -> getTaxAmt' "wn" "eau clair" amt `shouldBe` amt * 0.005 prop "has the property of returning 0.004 times amount for wisconsin, dunn" $ \amt -> getTaxAmt' "wisconsin" "dunn" amt `shouldBe` amt * 0.004 prop "has the property of returning 0.004 times amount for wn, dunn" $ \amt -> getTaxAmt' "wn" "dunn" amt `shouldBe` amt * 0.004 prop "has the property of returning 0.08 times amount for illinois, (anything)" $ \amt county-> getTaxAmt' "illinois" county amt `shouldBe` amt * 0.08 prop "has the property of returning 0.08 times amount for il, (anything)" $ \amt county -> getTaxAmt' "il" county amt `shouldBe` amt * 0.08 prop "has the property of returning 0.2 times amount for oxfordshire, (anything)" $ \amt area -> getTaxAmt' "oxfordshire" area amt `shouldBe` amt * 0.2 prop "has the property of returning 0.2 times amount for oxon, (anything)" $ \amt area -> getTaxAmt' "oxon" area amt `shouldBe` amt * 0.2 prop "has the property of returning 0 for all other places" $ \amt state county -> state `notElem` [ "wisconsin" , "wn" , "illinois" , "il" , "oxfordshire" , "oxon" ] ==> getTaxAmt' state county amt `shouldBe` 0 prop "has property of giving identical results to getTaxAmt for all inputs" $ \a s c -> getTaxAmt a s c `shouldBe` getTaxAmt' a s c describe "getTaxRateFor" $ do it "gives zero rate for unknown state" $ do getTaxRateFor "blarb" taxLookup `shouldBe` (Rate 0) it "gives correct rate for illinois" $ do getTaxRateFor "illinois" taxLookup `shouldBe` (Rate 0.08) it "gives correct rate for illinois" $ do getTaxRateFor "illinois" taxLookup `shouldBe` (Rate 0.08) it "gives correct rate for dunn, wisconsin" $ do let counties = getTaxRateFor "wn" taxLookup getTaxRateFor "dunn" counties `shouldBe` (Rate 0.004) it "gives correct rate for bumblefuck, wisconsin" $ do let counties = getTaxRateFor "wisconsin" taxLookup getTaxRateFor "eau clair" counties `shouldBe` (Rate 0.005) it "gives correct rate for bumblefuck, wisconsin" $ do let counties = getTaxRateFor "wn" taxLookup getTaxRateFor "bumblefuck" counties `shouldBe` (Rate 0)
Haskell
define("ace/mode/haskell_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/text_highlight_rules"],function(e,t,n){"use strict";var r=e("../lib/oop"),i=e("./text_highlight_rules").TextHighlightRules,s=function(){this.$rules={start:[{token:["punctuation.definition.entity.haskell","keyword.operator.function.infix.haskell","punctuation.definition.entity.haskell"],regex:"(`)([a-zA-Z_']*?)(`)",comment:"In case this regex seems unusual for an infix operator, note that Haskell allows any ordinary function application (elem 4 [1..10]) to be rewritten as an infix expression (4 `elem` [1..10])."},{token:"constant.language.unit.haskell",regex:"\\(\\)"},{token:"constant.language.empty-list.haskell",regex:"\\[\\]"},{token:"keyword.other.haskell",regex:"\\bmodule\\b",push:[{token:"keyword.other.haskell",regex:"\\bwhere\\b",next:"pop"},{include:"#module_name"},{include:"#module_exports"},{token:"invalid",regex:"[a-z]+"},{defaultToken:"meta.declaration.module.haskell"}]},{token:"keyword.other.haskell",regex:"\\bclass\\b",push:[{token:"keyword.other.haskell",regex:"\\bwhere\\b",next:"pop"},{token:"support.class.prelude.haskell",regex:"\\b(?:Monad|Functor|Eq|Ord|Read|Show|Num|(?:Frac|Ra)tional|Enum|Bounded|Real(?:Frac|Float)?|Integral|Floating)\\b"},{token:"entity.other.inherited-class.haskell",regex:"[A-Z][A-Za-z_']*"},{token:"variable.other.generic-type.haskell",regex:"\\b[a-z][a-zA-Z0-9_']*\\b"},{defaultToken:"meta.declaration.class.haskell"}]},{token:"keyword.other.haskell",regex:"\\binstance\\b",push:[{token:"keyword.other.haskell",regex:"\\bwhere\\b|$",next:"pop"},{include:"#type_signature"},{defaultToken:"meta.declaration.instance.haskell"}]},{token:"keyword.other.haskell",regex:"import",push:[{token:"meta.import.haskell",regex:"$|;|^",next:"pop"},{token:"keyword.other.haskell",regex:"qualified|as|hiding"},{include:"#module_name"},{include:"#module_exports"},{defaultToken:"meta.import.haskell"}]},{token:["keyword.other.haskell","meta.deriving.haskell"],regex:"(deriving)(\\s*\\()",push:[{token:"meta.deriving.haskell",regex:"\\)",next:"pop"},{token:"entity.other.inherited-class.haskell",regex:"\\b[A-Z][a-zA-Z_']*"},{defaultToken:"meta.deriving.haskell"}]},{token:"keyword.other.haskell",regex:"\\b(?:deriving|where|data|type|case|of|let|in|newtype|default)\\b"},{token:"keyword.operator.haskell",regex:"\\binfix[lr]?\\b"},{token:"keyword.control.haskell",regex:"\\b(?:do|if|then|else)\\b"},{token:"constant.numeric.float.haskell",regex:"\\b(?:[0-9]+\\.[0-9]+(?:[eE][+-]?[0-9]+)?|[0-9]+[eE][+-]?[0-9]+)\\b",comment:"Floats are always decimal"},{token:"constant.numeric.haskell",regex:"\\b(?:[0-9]+|0(?:[xX][0-9a-fA-F]+|[oO][0-7]+))\\b"},{token:["meta.preprocessor.c","punctuation.definition.preprocessor.c","meta.preprocessor.c"],regex:"^(\\s*)(#)(\\s*\\w+)",comment:'In addition to Haskell\'s "native" syntax, GHC permits the C preprocessor to be run on a source file.'},{include:"#pragma"},{token:"punctuation.definition.string.begin.haskell",regex:'"',push:[{token:"punctuation.definition.string.end.haskell",regex:'"',next:"pop"},{token:"constant.character.escape.haskell",regex:"\\\\(?:NUL|SOH|STX|ETX|EOT|ENQ|ACK|BEL|BS|HT|LF|VT|FF|CR|SO|SI|DLE|DC1|DC2|DC3|DC4|NAK|SYN|ETB|CAN|EM|SUB|ESC|FS|GS|RS|US|SP|DEL|[abfnrtv\\\\\\\"'\\&])"},{token:"constant.character.escape.octal.haskell",regex:"\\\\o[0-7]+|\\\\x[0-9A-Fa-f]+|\\\\[0-9]+"},{token:"constant.character.escape.control.haskell",regex:"\\^[A-Z@\\[\\]\\\\\\^_]"},{defaultToken:"string.quoted.double.haskell"}]},{token:["punctuation.definition.string.begin.haskell","string.quoted.single.haskell","constant.character.escape.haskell","constant.character.escape.octal.haskell","constant.character.escape.hexadecimal.haskell","constant.character.escape.control.haskell","punctuation.definition.string.end.haskell"],regex:"(')(?:([\\ -\\[\\]-~])|(\\\\(?:NUL|SOH|STX|ETX|EOT|ENQ|ACK|BEL|BS|HT|LF|VT|FF|CR|SO|SI|DLE|DC1|DC2|DC3|DC4|NAK|SYN|ETB|CAN|EM|SUB|ESC|FS|GS|RS|US|SP|DEL|[abfnrtv\\\\\\\"'\\&]))|(\\\\o[0-7]+)|(\\\\x[0-9A-Fa-f]+)|(\\^[A-Z@\\[\\]\\\\\\^_]))(')"},{token:["meta.function.type-declaration.haskell","entity.name.function.haskell","meta.function.type-declaration.haskell","keyword.other.double-colon.haskell"],regex:"^(\\s*)([a-z_][a-zA-Z0-9_']*|\\([|!%$+\\-.,=</>]+\\))(\\s*)(::)",push:[{token:"meta.function.type-declaration.haskell",regex:"$",next:"pop"},{include:"#type_signature"},{defaultToken:"meta.function.type-declaration.haskell"}]},{token:"support.constant.haskell",regex:"\\b(?:Just|Nothing|Left|Right|True|False|LT|EQ|GT|\\(\\)|\\[\\])\\b"},{token:"constant.other.haskell",regex:"\\b[A-Z]\\w*\\b"},{include:"#comments"},{token:"support.function.prelude.haskell",regex:"\\b(?:abs|acos|acosh|all|and|any|appendFile|applyM|asTypeOf|asin|asinh|atan|atan2|atanh|break|catch|ceiling|compare|concat|concatMap|const|cos|cosh|curry|cycle|decodeFloat|div|divMod|drop|dropWhile|elem|encodeFloat|enumFrom|enumFromThen|enumFromThenTo|enumFromTo|error|even|exp|exponent|fail|filter|flip|floatDigits|floatRadix|floatRange|floor|fmap|foldl|foldl1|foldr|foldr1|fromEnum|fromInteger|fromIntegral|fromRational|fst|gcd|getChar|getContents|getLine|head|id|init|interact|ioError|isDenormalized|isIEEE|isInfinite|isNaN|isNegativeZero|iterate|last|lcm|length|lex|lines|log|logBase|lookup|map|mapM|mapM_|max|maxBound|maximum|maybe|min|minBound|minimum|mod|negate|not|notElem|null|odd|or|otherwise|pi|pred|print|product|properFraction|putChar|putStr|putStrLn|quot|quotRem|read|readFile|readIO|readList|readLn|readParen|reads|readsPrec|realToFrac|recip|rem|repeat|replicate|return|reverse|round|scaleFloat|scanl|scanl1|scanr|scanr1|seq|sequence|sequence_|show|showChar|showList|showParen|showString|shows|showsPrec|significand|signum|sin|sinh|snd|span|splitAt|sqrt|subtract|succ|sum|tail|take|takeWhile|tan|tanh|toEnum|toInteger|toRational|truncate|uncurry|undefined|unlines|until|unwords|unzip|unzip3|userError|words|writeFile|zip|zip3|zipWith|zipWith3)\\b"},{include:"#infix_op"},{token:"keyword.operator.haskell",regex:"[|!%$?~+:\\-.=</>\\\\]+",comment:"In case this regex seems overly general, note that Haskell permits the definition of new operators which can be nearly any string of punctuation characters, such as $%^&*."},{token:"punctuation.separator.comma.haskell",regex:","}],"#block_comment":[{token:"punctuation.definition.comment.haskell",regex:"\\{-(?!#)",push:[{include:"#block_comment"},{token:"punctuation.definition.comment.haskell",regex:"-\\}",next:"pop"},{defaultToken:"comment.block.haskell"}]}],"#comments":[{token:"punctuation.definition.comment.haskell",regex:"--.*",push_:[{token:"comment.line.double-dash.haskell",regex:"$",next:"pop"},{defaultToken:"comment.line.double-dash.haskell"}]},{include:"#block_comment"}],"#infix_op":[{token:"entity.name.function.infix.haskell",regex:"\\([|!%$+:\\-.=</>]+\\)|\\(,+\\)"}],"#module_exports":[{token:"meta.declaration.exports.haskell",regex:"\\(",push:[{token:"meta.declaration.exports.haskell.end",regex:"\\)",next:"pop"},{token:"entity.name.function.haskell",regex:"\\b[a-z][a-zA-Z_']*"},{token:"storage.type.haskell",regex:"\\b[A-Z][A-Za-z_']*"},{token:"punctuation.separator.comma.haskell",regex:","},{include:"#infix_op"},{token:"meta.other.unknown.haskell",regex:"\\(.*?\\)",comment:"So named because I don't know what to call this."},{defaultToken:"meta.declaration.exports.haskell.end"}]}],"#module_name":[{token:"support.other.module.haskell",regex:"[A-Z][A-Za-z._']*"}],"#pragma":[{token:"meta.preprocessor.haskell",regex:"\\{-#",push:[{token:"meta.preprocessor.haskell",regex:"#-\\}",next:"pop"},{token:"keyword.other.preprocessor.haskell",regex:"\\b(?:LANGUAGE|UNPACK|INLINE)\\b"},{defaultToken:"meta.preprocessor.haskell"}]}],"#type_signature":[{token:["meta.class-constraint.haskell","entity.other.inherited-class.haskell","meta.class-constraint.haskell","variable.other.generic-type.haskell","meta.class-constraint.haskell","keyword.other.big-arrow.haskell"],regex:"(\\(\\s*)([A-Z][A-Za-z]*)(\\s+)([a-z][A-Za-z_']*)(\\)\\s*)(=>)"},{include:"#pragma"},{token:"keyword.other.arrow.haskell",regex:"->"},{token:"keyword.other.big-arrow.haskell",regex:"=>"},{token:"support.type.prelude.haskell",regex:"\\b(?:Int(?:eger)?|Maybe|Either|Bool|Float|Double|Char|String|Ordering|ShowS|ReadS|FilePath|IO(?:Error)?)\\b"},{token:"variable.other.generic-type.haskell",regex:"\\b[a-z][a-zA-Z0-9_']*\\b"},{token:"storage.type.haskell",regex:"\\b[A-Z][a-zA-Z0-9_']*\\b"},{token:"support.constant.unit.haskell",regex:"\\(\\)"},{include:"#comments"}]},this.normalizeRules()};s.metaData={fileTypes:["hs"],keyEquivalent:"^~H",name:"Haskell",scopeName:"source.haskell"},r.inherits(s,i),t.HaskellHighlightRules=s}),define("ace/mode/folding/cstyle",["require","exports","module","ace/lib/oop","ace/range","ace/mode/folding/fold_mode"],function(e,t,n){"use strict";var r=e("../../lib/oop"),i=e("../../range").Range,s=e("./fold_mode").FoldMode,o=t.FoldMode=function(e){e&&(this.foldingStartMarker=new RegExp(this.foldingStartMarker.source.replace(/\|[^|]*?$/,"|"+e.start)),this.foldingStopMarker=new RegExp(this.foldingStopMarker.source.replace(/\|[^|]*?$/,"|"+e.end)))};r.inherits(o,s),function(){this.foldingStartMarker=/(\{|\[)[^\}\]]*$|^\s*(\/\*)/,this.foldingStopMarker=/^[^\[\{]*(\}|\])|^[\s\*]*(\*\/)/,this.singleLineBlockCommentRe=/^\s*(\/\*).*\*\/\s*$/,this.tripleStarBlockCommentRe=/^\s*(\/\*\*\*).*\*\/\s*$/,this.startRegionRe=/^\s*(\/\*|\/\/)#?region\b/,this._getFoldWidgetBase=this.getFoldWidget,this.getFoldWidget=function(e,t,n){var r=e.getLine(n);if(this.singleLineBlockCommentRe.test(r)&&!this.startRegionRe.test(r)&&!this.tripleStarBlockCommentRe.test(r))return"";var i=this._getFoldWidgetBase(e,t,n);return!i&&this.startRegionRe.test(r)?"start":i},this.getFoldWidgetRange=function(e,t,n,r){var i=e.getLine(n);if(this.startRegionRe.test(i))return this.getCommentRegionBlock(e,i,n);var s=i.match(this.foldingStartMarker);if(s){var o=s.index;if(s[1])return this.openingBracketBlock(e,s[1],n,o);var u=e.getCommentFoldRange(n,o+s[0].length,1);return u&&!u.isMultiLine()&&(r?u=this.getSectionRange(e,n):t!="all"&&(u=null)),u}if(t==="markbegin")return;var s=i.match(this.foldingStopMarker);if(s){var o=s.index+s[0].length;return s[1]?this.closingBracketBlock(e,s[1],n,o):e.getCommentFoldRange(n,o,-1)}},this.getSectionRange=function(e,t){var n=e.getLine(t),r=n.search(/\S/),s=t,o=n.length;t+=1;var u=t,a=e.getLength();while(++t<a){n=e.getLine(t);var f=n.search(/\S/);if(f===-1)continue;if(r>f)break;var l=this.getFoldWidgetRange(e,"all",t);if(l){if(l.start.row<=s)break;if(l.isMultiLine())t=l.end.row;else if(r==f)break}u=t}return new i(s,o,u,e.getLine(u).length)},this.getCommentRegionBlock=function(e,t,n){var r=t.search(/\s*$/),s=e.getLength(),o=n,u=/^\s*(?:\/\*|\/\/|--)#?(end)?region\b/,a=1;while(++n<s){t=e.getLine(n);var f=u.exec(t);if(!f)continue;f[1]?a--:a++;if(!a)break}var l=n;if(l>o)return new i(o,r,l,t.length)}}.call(o.prototype)}),define("ace/mode/haskell",["require","exports","module","ace/lib/oop","ace/mode/text","ace/mode/haskell_highlight_rules","ace/mode/folding/cstyle"],function(e,t,n){"use strict";var r=e("../lib/oop"),i=e("./text").Mode,s=e("./haskell_highlight_rules").HaskellHighlightRules,o=e("./folding/cstyle").FoldMode,u=function(){this.HighlightRules=s,this.foldingRules=new o,this.$behaviour=this.$defaultBehaviour};r.inherits(u,i),function(){this.lineCommentStart="--",this.blockComment=null,this.$id="ace/mode/haskell"}.call(u.prototype),t.Mode=u})
JavaScript
// Copyright (c) 2016, the Dartino project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE.md file. /// API for LSM6DS0 "iNEMO inertial module: 3D accelerometer and 3D gyroscope" /// chip using the I2C bus. /// /// The following sample code shows how to access the LSM6DS0 on a /// STM32F746G Discovery board with "MEMS and environmental sensor /// expansion board for STM32 Nucleo" (X-NUCLEO-IKS01A1) attached. /// /// ``` /// import 'package:i2c/i2c.dart'; /// import 'package:i2c/devices/lsm6ds0.dart'; /// import 'package:stm32/stm32f746g_disco.dart'; /// /// main() { /// STM32F746GDiscovery board = new STM32F746GDiscovery(); /// var i2c1 = board.i2c1; /// /// // The LSM6DS0 sensor has address 0x6b in the X-NUCLEO-IKS01A1. /// var lsm6ds0 = new LSM6DS0(new I2CDevice(0x6b, i2c1)); /// lsm6ds0.powerOn(); /// while (true) { /// print('${lsm6ds0.readAccel()}'); /// sleep(10); /// } /// } /// ``` /// /// For the datasheet for the LSM6DS0 see: /// http://www.st.com/web/en/resource/technical/document/datasheet/DM00101533.pdf library lsm6ds0; import 'dart:math' as Math; import 'package:i2c/i2c.dart'; /// Rates of output from the gyroscope. enum GyroOutputRate { // Order is important as enum index is used as bit pattern. powerDown, at_14_9Hz, at_59_5Hz, at_119Hz, at_238Hz, at_476Hz, at_952Hz } /// Scales for the gyroscope. enum GyroScale { // Order is important as enum index is used as bit pattern. at_245DPS, at_500DPS, _NoOp, // This bit-pattern is not used. at_2000DPS } /// Bandwidth for the gyroscope. enum GyroBandwidth { // Order is important as enum index is used as bit pattern. low, medium, high, highest } /// Rate of output from the accelerometer. enum AccelOutputRate { // Order is important as enum index is used as bit pattern. at_PowerDown, at_10Hz, at_50Hz, at_119Hz, at_238Hz, at_476Hz, at_952Hz, } /// Scale for the accelerometer. enum AccelScale { // Order is important as enum index is used as bit pattern. at_2G, at_16G, at_4G, at_8G, } /// Bandwidth for the accelerometer. enum AccelBandwidth { // Order is important as enum index is used as bit pattern. at_408Hz, at_211Hz, at_105Hz, at_50Hz, } class Measurement { final double x; final double y; final double z; Measurement(this.x, this.y, this.z); toString() => 'Measurement x: $x, y: $y, z: $z'; } /// Accelerometer measurement. /// /// Values are in g (earth gravitational force, g = 9.80665 m/s2). class AccelMeasurement extends Measurement { AccelMeasurement(double x, double y, double z) : super(x, y, z); // See http://cache.freescale.com/files/sensors/doc/app_note/AN3461.pdf for // calculating pitch and roll. Here we are using the equations 28 and 29. /// The current pitch in degrees. double get pitch => _toDegrees(Math.atan(y / Math.sqrt(x * x + z * z))); /// The current roll in degrees. double get roll => _toDegrees(Math.atan(-x / z)); _toDegrees(double value) => (value * 180) / Math.PI; toString() => 'Acceleration x: $x g, y: $y g, z: $z g'; } /// Gyroscope measurement. /// /// Values are in degrees/s (degrees per second). class GyroMeasurement extends Measurement { GyroMeasurement(double x, double y, double z) : super(x, y, z); toString() => 'Gyro x: $x g, y: $y g, z: $z g'; } /// Accelerometer and gyroscope. class LSM6DS0 { // Accelerometer and gyroscope registers. static const _actThs = 0x04; // ACT_THS static const _actDur = 0x05; // ACT_DUR static const _intGenCfgXL = 0x06; // INT_GEN_CFG_XL; static const _intGEN_THS_X_XL = 0x07; // INT_GEN_THS_X_XL static const _intGEN_THS_Y_XL = 0x08; // INT_GEN_THS_Y_XL static const _intGEN_THS_Z_XL = 0x09; // INT_GEN_THS_Z_XL static const _intGEN_DUR_XL = 0x0A; // INT_GEN_DUR_XL static const _referenceG = 0x0B; // REFERENCE_G static const _int1Ctrl = 0x0C; // INT1_CTRL static const _int2Ctrl = 0x0D; // INT2_CTRL static const _whoAmI = 0x0F; // WHO_AM_I static const _ctrlReg1G = 0x10; // CTRL_REG1_G static const _ctrlReg2G = 0x11; // CTRL_REG2_G static const _ctrlReg3G = 0x12; // CTRL_REG3_G static const _orientCfgG = 0x13; // ORIENT_CFG_G static const _intGenSrcG = 0x14; // INT_GEN_SRC_G static const _outTempL = 0x15; // OUT_TEMP_L static const _outTempH = 0x16; // OUT_TEMP_H static const _statusReg = 0x17; // STATUS_REG static const _outXLG = 0x18; // OUT_X_L_G static const _outXHG = 0x19; // OUT_X_H_G static const _outYLG = 0x1A; // OUT_Y_L_G static const _outYHG = 0x1B; // OUT_Y_H_G static const _outZLG = 0x1C; // OUT_Z_L_G static const _outZHG = 0x1D; // OUT_Z_H_G static const _ctrlReg4 = 0x1E; // CTRL_REG4 static const _ctrlReg5XL = 0x1F; // CTRL_REG5_XL static const _ctrlReg6XL = 0x20; // CTRL_REG6_XL static const _ctrlReg7XL = 0x21; // CTRL_REG7_XL static const _ctrlReg8 = 0x22; // CTRL_REG8 static const _ctrlReg9 = 0x23; // CTRL_REG9 static const _ctrlReg10 = 0x24; // CTRL_REG10 static const _intGenSrcXL = 0x26; // INT_GEN_SRC_XL static const _statusReg2 = 0x27; // STATUS_REG static const _outXLXL = 0x28; // OUT_X_L_XL static const _outXHXL = 0x29; // OUT_X_H_XL static const _outYLXL = 0x2A; // OUT_Y_L_XL static const _outYHXL = 0x2B; // OUT_Y_H_XL static const _outZLXL = 0x2C; // OUT_Z_L_XL static const _outZHXL = 0x2D; // OUT_Z_H_XL static const _fifoCtrl = 0x2E; // FIFO_CTRL static const _fifoSrc = 0x2F; // FIFO_SRC static const _intGenCfgG = 0x30; // INT_GEN_CFG_G static const _intGenThsXHG = 0x31; // INT_GEN_THS_XH_G static const _intGenThsXLG = 0x32; // INT_GEN_THS_XL_G static const _intGenThsYHG = 0x33; // INT_GEN_THS_YH_G static const _intGenThsYLG = 0x34; // INT_GEN_THS_YL_G static const _intGenThsZHG = 0x35; // INT_GEN_THS_ZH_G static const _intGenThsZLG = 0x36; // INT_GEN_THS_ZL_G static const _intGenDurG = 0x37; // INT_GEN_DUR_G final I2CDevice _device; // I2C device for Accelerometer and gyroscope. var _gyroRate = GyroOutputRate.at_238Hz; var _gyroScale = GyroScale.at_245DPS; var _gyroBandwidth = GyroBandwidth.medium; var _accelRate = AccelOutputRate.at_238Hz; var _accelScale = AccelScale.at_2G; var _accelBandwidth = AccelBandwidth.at_50Hz; static const _gyroRes = const { GyroScale.at_245DPS: 245.0/32768.0, GyroScale.at_500DPS: 500.0/32768.0, GyroScale.at_2000DPS: 2000.0/32768.0, }; static const _accelRes = const { AccelScale.at_2G: 2.0/32768.0, AccelScale.at_16G: 16.0/32768.0, AccelScale.at_4G: 4.0/32768.0, AccelScale.at_8G: 8.0/32768.0, }; /// The argument is the I2C device for the accelerometer and /// gyroscope. LSM6DS0(this._device); void _configureGyro() { // Enable all three axis of the gyroscope. _device.writeByte(_ctrlReg4, 0x07 << 3); // Rate, scale and bandwidth. _device.writeByte( _ctrlReg1G, _gyroRate.index << 5 | _gyroScale.index << 3 | _gyroBandwidth.index); // High pass filter _device.writeByte(_ctrlReg3G, 0x00); // Disable HPF. } void _configureAccel() { // Enable all three axis of the accelerometer. _device.writeByte(_ctrlReg5XL, 0x07 << 3); // Rate, scale and bandwidth. var bwScalOrd = 1; // 1 means use _accelBandwidth. _device.writeByte( _ctrlReg6XL, _accelRate.index << 5 | _accelScale.index << 3 | bwScalOrd << 2 | _accelBandwidth.index); // No high-resolution mode, no filter. _device.writeByte(_ctrlReg7XL, 0); } void powerOn() { if (_device != null) { _configureGyro(); _configureAccel(); // Enable block data update. _device.writeByte(_ctrlReg8, 0x44); } } /// Returns `true` if new a gyroscope measurement is ready. /// /// This will query the status register in the chip. bool hasGyroMeasurement() { var status = _device.readByte(_statusReg); return (status & 0x02) != 0; } /// Returns `true` if new a accelerometer measurement is ready. /// /// This will query the status register in the chip. bool hasAccelMeasurement() { var status = _device.readByte(_statusReg); return (status & 0x01) != 0; } /// Read the current gyroscope measurement. GyroMeasurement readGyro() { var x = _readSigned16(_outXHG, _outXLG); var y = _readSigned16(_outYHG, _outYLG); var z = _readSigned16(_outZHG, _outZLG); var res = _gyroRes[_gyroScale]; return new GyroMeasurement(x * res, y * res, z * res); } /// Read the current accelerometer measurement. AccelMeasurement readAccel() { var x = _readSigned16(_outXHXL, _outXLXL); var y = _readSigned16(_outYHXL, _outYLXL); var z = _readSigned16(_outZHXL, _outZLXL); var res = _accelRes[_accelScale]; return new AccelMeasurement(x * res, y * res, z * res); } int _readSigned16(int msbRegister, int lsbRegister) { // Always read LSB before MSB. var lsb = _device.readByte(lsbRegister); var msb = _device.readByte(msbRegister); var x = msb << 8 | lsb; return x < 0x7fff ? x : x - 0x10000; } }
Dart
package org.herac.tuxguitar.android.view.dialog.browser.filesystem; import android.content.Context; import android.content.res.TypedArray; import android.graphics.drawable.Drawable; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView; import org.herac.tuxguitar.android.R; import java.io.File; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; public class TGBrowserSettingsFolderAdapter extends BaseAdapter { private Context context; private File path; private TGBrowserSettingsMountPoint mountPoint; private List<TGBrowserSettingsFolderAdapterItem> items; private TGBrowserSettingsFolderAdapterListener listener; public TGBrowserSettingsFolderAdapter(Context context, TGBrowserSettingsMountPoint mountPoint) { this.context = context; this.mountPoint = mountPoint; this.items = new ArrayList<TGBrowserSettingsFolderAdapterItem>(); this.updatePath(this.mountPoint.getPath()); } public File getPath() { return this.path; } public void setListener(TGBrowserSettingsFolderAdapterListener listener) { this.listener = listener; } @Override public int getCount() { return this.items.size(); } @Override public Object getItem(int position) { return this.items.get(position); } @Override public long getItemId(int position) { return position; } public LayoutInflater getLayoutInflater() { return (LayoutInflater) this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); } @Override public View getView(int position, View convertView, ViewGroup parent) { TGBrowserSettingsFolderAdapterItem item = this.items.get(position); View view = (convertView != null ? convertView : getLayoutInflater().inflate(R.layout.view_browser_element, parent, false)); view.setTag(item); TextView textView = (TextView) view.findViewById(R.id.tg_browser_element_name); textView.setText(item.getLabel()); Drawable styledIcon = this.findStyledFolderIcon(); if( styledIcon != null ) { ImageView imageView = (ImageView) view.findViewById(R.id.tg_browser_element_icon); imageView.setImageDrawable(styledIcon); } view.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { updatePath(((TGBrowserSettingsFolderAdapterItem) v.getTag()).getFile()); } }); return view; } public Drawable findStyledFolderIcon() { TypedArray typedArray = this.context.obtainStyledAttributes(R.style.browserElementIconFolderStyle, new int[] {android.R.attr.src}); if( typedArray != null ) { return typedArray.getDrawable(0); } return null; } public void updatePath(File path) { this.path = path; this.items.clear(); if( this.path != null && this.path.exists() && this.path.isDirectory() ) { if( this.path.getParentFile() != null && !this.path.equals(this.mountPoint.getPath())) { this.items.add(new TGBrowserSettingsFolderAdapterItem("../", this.path.getParentFile())); } List<File> directoryFiles = this.getDirectoryFiles(this.path); this.sortFiles(directoryFiles); for(File file : directoryFiles) { this.items.add(new TGBrowserSettingsFolderAdapterItem(file.getName(), file)); } } this.notifyDataSetChanged(); if( this.listener != null ) { this.listener.onPathChanged(this.path); } } public List<File> getDirectoryFiles(File parent) { List<File> directoryFiles = new ArrayList<File>(); File[] files = parent.listFiles(); if( files != null ) { for(File file : files) { if( file.isDirectory() ) { directoryFiles.add(file); } } } return directoryFiles; } public void sortFiles(List<File> files) { Collections.sort(files, new Comparator<File>() { public int compare(File f1, File f2) { if( f1 == f2 ) { return 0; } if( f1 == null ) { return -1; } if( f2 == null ) { return 1; } return f1.getName().compareTo(f2.getName()); } }); } }
Java
void piksr2(n,arr,brr) int n; float arr[],brr[]; { int i,j; float a,b; for (j=2;j<=n;j++) { a=arr[j]; b=brr[j]; i=j-1; while (i > 0 && arr[i] > a) { arr[i+1]=arr[i]; brr[i+1]=brr[i]; i--; } arr[i+1]=a; brr[i+1]=b; } }
C
using Documenter, FeatherLib makedocs( modules = [FeatherLib], sitename = "FeatherLib.jl", analytics="UA-132838790-1", pages = [ "Introduction" => "index.md" ] ) deploydocs( repo = "github.com/queryverse/FeatherLib.jl.git" )
Julia
;; ;;Excerpted from "Programming Clojure, Second Edition", ;;published by The Pragmatic Bookshelf. ;;Copyrights apply to this code. It may not be used to create training material, ;;courses, books, articles, and the like. Contact us if you are in doubt. ;;We make no guarantees that this code is fit for any purpose. ;;Visit http://www.pragmaticprogrammer.com/titles/shcloj2 for more book information. ;; (ns examples.wallingford (:require [examples.replace-symbol :only (deeply-nested)])) ; based on http://www.cs.uni.edu/~wallingf/patterns/recursion.html#3 ; overly-literal port, do not use (declare replace-symbol replace-symbol-expression) (defn replace-symbol [coll oldsym newsym] (if (empty? coll) () (cons (replace-symbol-expression (first coll) oldsym newsym) (replace-symbol (rest coll) oldsym newsym)))) (defn replace-symbol-expression [symbol-expr oldsym newsym] (if (symbol? symbol-expr) (if (= symbol-expr oldsym) newsym symbol-expr) (replace-symbol symbol-expr oldsym newsym)))
Clojure
Register-PSFConfigValidation -Name "bool" -ScriptBlock { Param ( $Value ) $Result = [PSCustomObject]@{ Success = $True Value = $null Message = "" } try { if ($Value.GetType().FullName -notin "System.Boolean", 'System.Management.Automation.SwitchParameter') { $Result.Message = "Not a boolean: $Value" $Result.Success = $False return $Result } } catch { $Result.Message = "Not a boolean: $Value" $Result.Success = $False return $Result } $Result.Value = $Value -as [bool] return $Result }
PowerShell
package com.natevaughan.koach.demo import com.natevaughan.koach.workout.SimpleActivity import com.natevaughan.koach.workout.interval.* /** * Created by nate on 7/20/17 */ fun main(args: Array<String>) { val interval1 = SimpleActivity(Activity.SWIM, Distance(100.0, DistanceUnit.METERS), Time(1, 30)) val interval2 = SimpleActivity(Activity.SWIM, Distance(100.0, DistanceUnit.METERS), Time(1, 29)) val interval3 = SimpleActivity(Activity.SWIM, Distance(100.0, DistanceUnit.METERS), Time(1, 28)) // val swimSet = IntervalSet(arrayOf(interval1, interval2, interval3)) // // val workout = Workout(arrayListOf(swimSet)) // println(distanceReport(workout)) } fun oldMain(args: Array<String>) { println(Color.ORANGE) println(mnemonic(Color.BLUE)) println(mix(Color.BLUE,Color.YELLOW)) println(mix(Color.BLUE,Color.ORANGE)) } fun mnemonic(color: Color) : String { when (color) { Color.BLUE -> return "foo" Color.ORANGE -> return "bar" else -> { return "baz" } } } fun mix(color1: Color, color2: Color) : Color { when (setOf(color1, color2)) { setOf(Color.BLUE, Color.RED) -> return Color.PURPLE setOf(Color.RED, Color.YELLOW) -> return Color.ORANGE setOf(Color.BLUE, Color.YELLOW) -> return Color.GREEN } throw Exception("could not mix colors") }
Kotlin
using Surrogates using LinearAlgebra using Test using QuadGK using Cubature #1D obj = x -> 3 * x + log(x) a = 1.0 b = 4.0 x = sample(2000, a, b, SobolSample()) y = obj.(x) alpha = 2.0 n = 6 my_loba = LobachevskySurrogate(x, y, a, b, alpha = 2.0, n = 6) val = my_loba(3.83) # Test that input dimension is properly checked for 1D Lobachevsky surrogates @test_throws ArgumentError my_loba(Float64[]) @test_throws ArgumentError my_loba((2.0, 3.0, 4.0)) #1D integral int_1D = lobachevsky_integral(my_loba, a, b) int = quadgk(obj, a, b) int_val_true = int[1] - int[2] @test abs(int_1D - int_val_true) < 2 * 10^-5 update!(my_loba, 3.7, 12.1) update!(my_loba, [1.23, 3.45], [5.20, 109.67]) #ND obj = x -> x[1] + log(x[2]) lb = [0.0, 0.0] ub = [8.0, 8.0] alpha = [2.4, 2.4] n = 8 x = sample(3200, lb, ub, SobolSample()) y = obj.(x) my_loba_ND = LobachevskySurrogate(x, y, lb, ub, alpha = [2.4, 2.4], n = 8) my_loba_kwargs = LobachevskySurrogate(x, y, lb, ub) pred = my_loba_ND((1.0, 2.0)) # Test that input dimension is properly checked for ND Lobachevsky surrogates @test_throws ArgumentError my_loba_ND(Float64[]) @test_throws ArgumentError my_loba_ND(1.0) @test_throws ArgumentError my_loba_ND((2.0, 3.0, 4.0)) #ND int_ND = lobachevsky_integral(my_loba_ND, lb, ub) int = hcubature(obj, lb, ub) int_val_true = int[1] - int[2] @test abs(int_ND - int_val_true) < 10^-1 update!(my_loba_ND, (10.0, 11.0), 4.0) update!(my_loba_ND, [(12.0, 15.0), (13.0, 14.0)], [4.0, 5.0]) lobachevsky_integrate_dimension(my_loba_ND, lb, ub, 2) obj = x -> x[1] + log(x[2]) + exp(x[3]) lb = [0.0, 0.0, 0.0] ub = [8.0, 8.0, 8.0] alpha = [2.4, 2.4, 2.4] x = sample(50, lb, ub, SobolSample()) y = obj.(x) n = 4 my_loba_ND = LobachevskySurrogate(x, y, lb, ub) lobachevsky_integrate_dimension(my_loba_ND, lb, ub, 2) #Sparse #1D obj = x -> 3 * x + log(x) a = 1.0 b = 4.0 x = sample(100, a, b, SobolSample()) y = obj.(x) alpha = 2.0 n = 6 my_loba = LobachevskySurrogate(x, y, a, b, alpha = 2.0, n = 6, sparse = true) #ND obj = x -> x[1] + log(x[2]) lb = [0.0, 0.0] ub = [8.0, 8.0] alpha = [2.4, 2.4] n = 8 x = sample(100, lb, ub, SobolSample()) y = obj.(x) my_loba_ND = LobachevskySurrogate(x, y, lb, ub, alpha = [2.4, 2.4], n = 8, sparse = true)
Julia
;; ;; ANSI COMMON LISP: 21. Streams ;; (deftest pipe-stream.1 (typep (lisp-system:sysctl 'stream 'pipe 'make 0) 'stream) t) (deftest pipe-stream.2 (typep (lisp-system:sysctl 'stream 'pipe 'make 0) 'lisp-system::pipe-stream) t) (deftest pipe-stream.3 (subtypep 'lisp-system::pipe-stream 'stream) t t) (deftest pipe-stream.4 (subtypep 'stream 'lisp-system::pipe-stream) nil t) (deftest pipe-stream.5 (subtypep 'string 'lisp-system::pipe-stream) nil t) (deftest pipe-stream.6 (let ((x (lisp-system:sysctl 'stream 'pipe 'make 1))) (type-of x)) lisp-system::pipe-stream) (deftest pipe-stream.7 (lisp-system:sysctl 'stream 'pipe 'make 100000000) nil nil) (deftest pipe-stream-type.1 (let ((x (lisp-system:sysctl 'stream 'pipe 'make 0))) (lisp-system:sysctl 'stream 'pipe 'type x)) 0 t) (deftest pipe-stream-type.2 (let ((x (lisp-system:sysctl 'stream 'pipe 'make 1))) (lisp-system:sysctl 'stream 'pipe 'type x)) 1 t) (deftest pipe-stream-type.3 (let ((x (lisp-system:sysctl 'stream 'pipe 'make 0))) (lisp-system:sysctl 'stream 'pipe 'type x 2)) 2 t) (deftest pipe-stream-type.4 (let ((x (lisp-system:sysctl 'stream 'pipe 'make 0))) (lisp-system:sysctl 'stream 'pipe 'type x 2) (lisp-system:sysctl 'stream 'pipe 'type x)) 2 t)
Common Lisp
FROM debian:sid-slim RUN apt-get update \ && apt-get install -y --no-install-recommends \ ca-certificates curl firefox \ && rm -fr /var/lib/apt/lists/* \ && curl -L https://github.com/mozilla/geckodriver/releases/download/v0.28.0/geckodriver-v0.28.0-linux64.tar.gz | tar xz -C /usr/local/bin \ && apt-get purge -y ca-certificates curl CMD ["geckodriver", "--host", "0.0.0.0"]
Dockerfile
// // ___FILENAME___ // ___PROJECTNAME___ // // Created by ___FULLUSERNAME___ on ___DATE___. //___COPYRIGHT___ // import UIKit class ___FILEBASENAMEASIDENTIFIER___: ___VARIABLE_cocoaTouchSubclass___ { override func awakeFromNib() { super.awakeFromNib() // Initialization code } }
Swift
defmodule Peepchat.RegistrationControllerTest do use Peepchat.ConnCase alias Peepchat.User @valid_attrs %{ "email" => "mike@example.com", "password" => "fqhi12hrrfasf", "password-confirmation" => "fqhi12hrrfasf" } @invalid_attrs %{} setup %{conn: conn} do {:ok, conn: put_req_header(conn, "accept", "application/json")} end test "creates and renders resource when data is valid", %{conn: conn} do conn = post conn, registration_path(conn, :create), %{data: %{type: "users", attributes: @valid_attrs }} assert json_response(conn, 201)["data"]["id"] assert Repo.get_by(User, %{email: @valid_attrs["email"]}) end test "does not create resource and renders errors when data is invalid", %{conn: conn} do assert_error_sent 400, fn -> conn = post conn, registration_path(conn, :create), %{data: %{type: "user", attributes: @invalid_attrs }} end end end
Elixir
# The set of languages for which implicit dependencies are needed: SET(CMAKE_DEPENDS_LANGUAGES "CXX" ) # The set of files for implicit dependencies of each language: SET(CMAKE_DEPENDS_CHECK_CXX "/home/hangxinliu/golf_cart/src/scan_tools/polar_scan_matcher/src/psm_node.cpp" "/home/hangxinliu/golf_cart/build/scan_tools/polar_scan_matcher/CMakeFiles/psm_node.dir/src/psm_node.cpp.o" ) SET(CMAKE_CXX_COMPILER_ID "GNU") # Preprocessor definitions for this target. SET(CMAKE_TARGET_DEFINITIONS "ROSCONSOLE_BACKEND_LOG4CXX" "ROS_BUILD_SHARED_LIBS=1" "ROS_PACKAGE_NAME=\"polar_scan_matcher\"" ) # Targets to which this target links. SET(CMAKE_TARGET_LINKED_INFO_FILES "/home/hangxinliu/golf_cart/build/scan_tools/polar_scan_matcher/CMakeFiles/polar_scan_matcher.dir/DependInfo.cmake" ) # The include file search paths: SET(CMAKE_C_TARGET_INCLUDE_PATH "/home/hangxinliu/golf_cart/src/scan_tools/polar_scan_matcher/include" "/opt/ros/indigo/include" ) SET(CMAKE_CXX_TARGET_INCLUDE_PATH ${CMAKE_C_TARGET_INCLUDE_PATH}) SET(CMAKE_Fortran_TARGET_INCLUDE_PATH ${CMAKE_C_TARGET_INCLUDE_PATH}) SET(CMAKE_ASM_TARGET_INCLUDE_PATH ${CMAKE_C_TARGET_INCLUDE_PATH})
CMake
<?xml version="1.0"?> <testpioconfig> <erebus PNETCDF_PATH="${PNETCDF}" NETCDF_PATH="${NETCDF}" ENV_MP_LABELIO="yes" CXX="mpCC" CC="mpcc" FC="mpfort" MPIFC="mpfort" MPICC="mpcc" MPICXX="mpCC" FFLAGS = "-O3 -ip -no-prec-div -free -g -traceback" CFLAGS = " -O -g -traceback" CPPDEFS= "-DFORTRANUNDERSCORE " workdir="/ampstmp/${USER}/testpio" submit="bsub &lt; " run = "mpirun.lsf" corespernode="12" conopts="--enable-filesystem-hints=gpfs " netcdf4="true" preamble = " #BSUB -q ampsrt #BSUB -N #BSUB -x #BSUB -a poe #BSUB -o testpio.%J.stdout #BSUB -e testpio.%J.stderr #BSUB -J testpio_suite #BSUB -W 3:00 " /> <!-- PNETCDF_PATH="/glade/u/home/jedwards/pnetcdf/svn1163/intel/" --> <yellowstone PNETCDF_PATH="${PNETCDF}" NETCDF_PATH="${NETCDF}" ENV_MP_LABELIO="yes" ENV_MP_MPILIB="mpich2" CXX="mpiicpc" CC="mpcc" FC="mpif90" MPIFC="mpif90" MPICC="mpicc" MPICXX="mpiicpc" FFLAGS = " -ip -no-prec-div -free -g -traceback" CFLAGS = " -g -traceback" CPPDEFS= "-DFORTRANUNDERSCORE " workdir="/glade/scratch/${USER}/testpio" submit="bsub &lt; " run = "mpirun.lsf" corespernode="32" conopts="--disable-timing --enable-filesystem-hints=gpfs " netcdf4="true" preamble = ' #BSUB -q small #BSUB -N ##BSUB -x #BSUB -a poe #BSUB -o testpio.%J.stdout #BSUB -e testpio.%J.stderr #BSUB -J testpio_suite #BSUB -W 1:00 ' /> <yellowstone_pgi PNETCDF_PATH="${PNETCDF}" NETCDF_PATH="${NETCDF}" ENV_MP_LABELIO="yes" ENV_MP_MPILIB="mpich2" CXX="pgCC" CC="pgcc" FC="pgf95" MPIFC="mpif90" MPICC="mpicc" MPICXX="mpiCC" FFLAGS = " " CFLAGS = " " CPPDEFS= "-DFORTRANUNDERSCORE -DNO_MPIMOD" workdir="/glade/scratch/${USER}/testpio_pgi" submit="bsub &lt; " run = "mpirun.lsf" corespernode="16" conopts="--enable-filesystem-hints=gpfs " preamble = ' #BSUB -q small #BSUB -N #BSUB -x #BSUB -a poe #BSUB -o testpio.%J.stdout #BSUB -e testpio.%J.stderr #BSUB -J testpio_suite #BSUB -W 1:00 ' /> <yellowstone_gnu PNETCDF_PATH="${PNETCDF}" NETCDF_PATH="${NETCDF}" ENV_MP_LABELIO="yes" ENV_MP_MPILIB="mpich2" CXX="g++" CC="gcc" FC="gfortran" MPIFC="mpif90" MPICC="mpicc" MPICXX="mpiCC" FFLAGS = " " CFLAGS = " " CPPDEFS= "-DFORTRANUNDERSCORE " workdir="/glade/scratch/${USER}/testpio_gnu" submit="bsub &lt; " run = "mpirun.lsf" corespernode="16" conopts="--enable-filesystem-hints=gpfs " preamble = ' #BSUB -q small #BSUB -N #BSUB -x #BSUB -a poe #BSUB -o testpio.%J.stdout #BSUB -e testpio.%J.stderr #BSUB -J testpio_suite #BSUB -W 1:00 ' /> <janus PNETCDF_PATH="/home/jimedwards/parallel-netcdf/1.3.0/intel/12.1.4" NETCDF_PATH="${NETCDF}" CXX="icpc" CC="icc" FC="mpif90" MPIFC="mpif90" MPICC="mpicc" MPICXX="mpic++" FFLAGS = "-O3 -ip -no-prec-div -free -g -traceback" CFLAGS = " -O -g -traceback" CPPDEFS= "-DFORTRANUNDERSCORE " LDLIBS="`$NETCDF/bin/nc-config --flibs`" workdir="/lustre/janus_scratch/${USER}/testpio" submit="qsub" run = "mpirun" netcdf4 = "true" corespernode="12" conopts="--enable-filesystem-hints=lustre --with-piovdc=/home/jimedwards/libpiovdc/1.0/intel_12.1.4" preamble = " #PBS -l walltime=01:00:00 #PBS -N testpiob #PBS -j oe #PBS -q janus-short #PBS -V " /> <carver PNETCDF_PATH="/global/homes/j/jedwards/pnetcdf/carver/intel/" NETCDF_PATH="${NETCDF_DIR}" CXX="icpc" CC="icc" FC="mpif90" MPIFC="mpif90" MPICC="mpicc" MPICXX="mpic++" FFLAGS = "-O3 -ip -no-prec-div -free -g -traceback" CFLAGS = " -O -g -traceback" CPPDEFS= "-DFORTRANUNDERSCORE " LDLIBS="`$NETCDF/bin/nc-config --flibs`" workdir="${SCRATCH}/testpio" submit="qsub" run = "mpirun" corespernode="8" conopts="--enable-filesystem-hints=gpfs --with-piovdc=/global/homes/j/jedwards/libpiovdc/carver/intel" preamble = " #PBS -l walltime=00:30:00 #PBS -N testpiob #PBS -j oe #PBS -q debug #PBS -V " /> <intrepid ENV_IBMCMP_INCLUDE="/soft/apps/ibmcmp-jan2013/vac/bg/9.0/include:/soft/apps/ibmcmp-jan2010/vacpp/bg/9.0/include:/soft/apps/ibmcmp-jan2010/xlf/bg/11.1/include:/soft/apps/ibmcmp-jan2010/xlmass/bg/4.4/include:/soft/apps/ibmcmp-jan2010/xlsmp/bg/1.7/include" ADDENV_PATH="/soft/apps/darshan/bin/:/soft/apps/ibmcmp-jan2013/xlf/bg/11.1/bin/:/soft/apps/ibmcmp-jan2010/vac/bg/9.0/bin/" NETCDF_PATH="/soft/apps/current/netcdf-4.1.3-disable_netcdf_4" PNETCDF_PATH="/home/robl/soft/pnetcdf-1.3.0pre1-xl" MPIFC = "/software/common/apps/misc-scripts/tmpixlf90" MPICC = "/software/common/apps/misc-scripts/tmpixlc" FC = "/software/common/apps/misc-scripts/tmpixlf90" CC = "/software/common/apps/misc-scripts/tmpixlc" CPPDEFS = " -DBGP " FFLAGS = "-qarch=450 -qextname=flush -g -qfullpath" CFLAGS = " -g -qfullpath -I/bgsys/drivers/ppcfloor/comm/include -I/bgsys/drivers/ppcfloor/arch/include" conopts = " --enable-mpiio --enable-timing --build=powerpc-bgp-linux --host=powerpc64-suse-linux --disable-netcdf4" workdir = "/intrepid-fs0/users/${USER}/scratch/testpio" run = "cobalt-mpirun -mode vn -nofree --stdout " submit ="qsub -AClimEndStation --mode script -t 01:00:00 -q prod-devel -n 128 " corespernode="4" pecount="128" /> <aum ADDENV_PATH = "" ADDENV_LD_LIBRARY_PATH = "" ENV_P4_GLOBMEMSIZE="518400000" MPIFC = "mpif90" MPICC = "mpicc" FC = "gfortran" CC = "gcc" NETCDF_PATH="" FFLAGS = "-g --free-line-length-none " submit="qsub" run="mpirun" conopts = " --disable-netcdf --disable-pnetcdf" workdir = "/scratch/${USER}/testpio" corespernode="8" preamble = " #PBS -l walltime=01:00:00 #PBS -N testpiob #PBS -j oe #PBS -V " testsuites = "mpiio" /> <cyberstar ADDENV_PATH = "" ADDENV_LD_LIBRARY_PATH = "" ENV_P4_GLOBMEMSIZE="518400000" MPIFC = "mpif90" MPICC = "mpicc" FC = "pgf90" CC = "gcc" NETCDF_PATH="" FFLAGS = "-g" submit="qsub" run="mpirun" conopts = " --disable-pnetcdf" workdir = "/gpfs/scratch/${USER}/testpio" corespernode="8" preamble = " #PBS -l walltime=01:00:00 #PBS -N testpiob #PBS -j oe #PBS -V " testsuites = "mpiio" /> <mirage1 MCT_PATH="/glade/home/jedwards/src/MCT2_7_0_100228-mpiserial101109_tag02/" MPIFC = "ifort" MPICC = "icc" FC = "ifort" CC = "icc" NETCDF_PATH="/fs/local/apps/netcdf-3.6.2/" FFLAGS = "-g " submit="" run="" conopts = " --enable-mpiserial --disable-mpi2 " workdir = "/ptmp/${USER}/testpio" corespernode="1" preamble = "" testsuites = "snet " /> <titan MPIFC = "ftn " MPICC = "cc " FC = "pgf90" CC = "pgcc" CPPDEFS = " -DFORTRANUNDERSCORE" ENV_NETCDF_PATH="$NETCDF_DIR" ENV_PNETCDF_PATH="$PARALLEL_NETCDF_DIR" workdir = "/tmp/work/${USER}/testpio" run = "aprun" submit = "qsub" netcdf4 = "true" conopts = " --enable-filesystem-hints=lustre" corespernode="16" preamble=" #PBS -N testpio_suite #PBS -q batch #PBS -l walltime=02:00:00 #PBS -j oe #PBS -V #PBS -l gres=widow3" /> <athena MPIFC = "ftn" MPICC = "cc" FC = "pgf90" CC = "pgcc" FFLAGS = "-D_USE_FLOW_CONTROL" NETCDF_PATH = "$NETCDF_DIR" PNETCDF_PATH = "$PNETCDF_DIR" workdir = "/lustre/scratch/${USER}/testpio" run = "aprun" submit = "qsub" conopts = " --enable-filesystem-hints=lustre" corespernode="8" preamble=" #PBS -N testpio_suite #PBS -q batch #PBS -l walltime=00:50:00 #PBS -j oe #PBS -V" /> <kraken MPIFC = "ftn -L$LIBSCI_BASE_DIR/pgi/lib" MPICC = "cc -L$LIBSCI_BASE_DIR/pgi/lib" FC = "pgf90" CC = "pgcc" FFLAGS = "-D_USE_FLOW_CONTROL" NETCDF_PATH = "$NETCDF_PATH" PNETCDF_PATH = "$PNETCDF_DIR" workdir = "/lustre/scratch/${USER}/testpio2" run = "aprun" submit = "qsub" conopts = " --enable-filesystem-hints=lustre" corespernode = "12" preamble=" #PBS -A TG-ATM090041 #PBS -N testpio_suite #PBS -l walltime=00:50:00 #PBS -j oe #PBS -V" /> <columbia MPIFC = "mpif90" MPICC = "mpicc" FC = "ifort" CC = "icc" FFLAGS = "-D_USE_FLOW_CONTROL" NETCDF_PATH = "$NETCDF_DIR" PNETCDF_PATH = "$PNETCDF_DIR" workdir = "/nobackup1/${USER}/testpio" run = "mpirun" submit = "qsub" conopts = " --disable-pnetcdf" corespernode = "512" preamble=" #PBS -N testpio_suite #PBS -q normal #PBS -l walltime=00:50:00 #PBS -l mem=100GB #PBS -j oe" testsuites = "snet mpiio" /> <pleiades MPIFC = "ifort" MPICC = "icc" FC = "ifort" CC = "icc" FFLAGS = "-D_USE_FLOW_CONTROL" LDLIBS = "-lmpi" NETCDF_PATH = "$NETCDF_DIR" PNETCDF_PATH = "$PNETCDF_DIR" workdir = "/nobackup/${USER}/TESTPIO/testpio" run = "mpiexec" submit = "qsub" conopts = " --disable-pnetcdf" corespernode = "8" preamble=" #PBS -N testpio_suite #PBS -q normal #PBS -l walltime=00:50:00 #PBS -j oe" testsuites = "snet mpiio" /> <lynx MPIFC = "ftn " MPICC = "cc " FC = "ftn" CC = "cc" LDLIBS = " -L/contrib/hdf5/1.8.7_seq/hdf5-pgi//lib -lhdf5_hl -lhdf5 -lm -lcurl -L/contrib/libidn/1.19/pgi/lib -lidn -lssl -lcrypto -ldl -lz" CPPDEFS = "-D_USE_FLOW_CONTROL -DFORTRANUNDERSCORE" NETCDF_PATH = "${NETCDF}" workdir = "/ptmp/${USER}/testpio.pgi" run = "aprun" corespernode = "12" submit = "qsub " conopts = " --enable-filesystem-hints=lustre " preamble=" #PBS -N testpio_suite #PBS -l walltime=01:50:00 #PBS -j oe #PBS -V" /> <lynx_intel MPIFC = "ftn " MPICC = "cc " FC = "ftn" CC = "cc" CPPDEFS = " -DFORTRANUNDERSCORE" NETCDF_PATH = "${NETCDF}" LDLIBS="`$NETCDF/bin/nc-config --flibs` -lssl -lcrypto -ldl -lz -L/contrib/libidn/1.19/gnu/lib -lidn -L/opt/cray/pmi/1.0-1.0000.8160.39.1.ss/lib64 -lpmi" workdir = "/ptmp/${USER}/testpio.intel" run = "aprun" corespernode = "12" submit = "qsub " conopts = " --enable-filesystem-hints=lustre --with-piovdc=/glade/home/jedwards/libpiovdc-cinterop/lynx/intel" preamble=" #PBS -N testpio_suite #PBS -l walltime=01:50:00 #PBS -j oe #PBS -V" /> <lynx_gnu MPIFC = "ftn " MPICC = "cc " FC = "ftn" CC = "cc" FFLAGS = "-D_USE_FLOW_CONTROL -Wl,-zmuldefs -ffree-line-length-none" NETCDF_PATH = "/contrib/netcdf/3.6.3/gnu" PNETCDF_PATH = "/contrib/pnetcdf/1.2.0/gnu-4.5.1" workdir = "/ptmp/${USER}/testpio" run = "aprun" corespernode = "12" submit = "qsub " conopts = " --enable-filesystem-hints=lustre " preamble=" #PBS -N testpio_suite #PBS -l walltime=01:50:00 #PBS -j oe #PBS -V" /> <hopper MPIFC = "ftn " MPICC = "cc " FC = "ftn" CC = "cc" CPPDEFS = " -DFORTRANUNDERSCORE -D_NO_MPI_RSEND" NETCDF_PATH = "${NETCDF_DIR}" PNETCDF_PATH = "${PARALLEL_NETCDF_DIR}" LDLIBS="`nf-config --flibs`" workdir = "/scratch/scratchdirs/${USER}/testpio.norsend" run = "aprun" corespernode = "24" submit = "qsub " conopts = " --enable-netcdf4 --enable-pnetcdf --enable-timing --enable-filesystem-hints=lustre " preamble=" #PBS -N testpio_suite #PBS -l walltime=01:00:00 #PBS -q regular #PBS -j oe #PBS -V" /> <hopper_gnu MPIFC = "ftn " MPICC = "cc " FC = "ftn" CC = "cc" CPPDEFS = " -DFORTRANUNDERSCORE -D_NO_MPI_RSEND" NETCDF_PATH = "${NETCDF_DIR}" LDLIBS="`nf-config --flibs`" workdir = "/scratch/scratchdirs/${USER}/testpio.gnu" run = "aprun" corespernode = "24" submit = "qsub " conopts = " --enable-netcdf4 --enable-pnetcdf --enable-timing --enable-filesystem-hints=lustre " preamble=" #PBS -N testpio_suite #PBS -l walltime=01:00:00 #PBS -q regular #PBS -j oe #PBS -V" /> </testpioconfig>
XML
import { Component } from '@angular/core'; import { OnlineTomatoService } from '@services/data.service'; @Component({ selector: 'page-historyTomato', templateUrl: 'historyTomato.html', styleUrls: ['historyTomato.scss'], providers: [OnlineTomatoService], }) export class HistoryTomatoPage { // 番茄钟长度 searchReturnItems = []; constructor( public tomatoservice: OnlineTomatoService, ) { } ionViewDidLoad() { } /** * 番茄钟搜索 */ seachTomatoes(evt) { const keywords = evt.target.value; // 前端需对关键词做少许过滤 console.log('keyword', keywords); this.tomatoservice.searchTomatos({ keywords }).subscribe(data => { // console.log(data); const arr = data; this.searchReturnItems = arr; }); } }
TypeScript
# Copyright (C) 2013 - 2023 Metrum Research Group # # This file is part of mrgsolve. # # mrgsolve is free software: you can redistribute it and/or modify it # under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 2 of the License, or # (at your option) any later version. # # mrgsolve 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 General Public License for more details. # # You should have received a copy of the GNU General Public License # along with mrgsolve. If not, see <http://www.gnu.org/licenses/>. Sys.setenv("R_TESTS" = "") library(magrittr) library(mrgsolve) library(testthat) test_check("mrgsolve", reporter="summary")
R
Test set-up for seaice pkg with Open-Boundary Conditions ======================================================== This verification experiment is used to test `pkg/seaice` with `pkg/obcs` and the set-up itself is carved out from `../lab_sea/input.salt_plume/`. The **primary** test uses input files from `input/` dir which have been generated using the matlab script [`input/mk_input.m`](input/mk_input.m) together with the set of output files from running test experiment `../lab_sea/input.salt_plume`. The **secondary** test `input.seaiceSponge/` uses OBCS sponge-layer for seaice fields (`useSeaiceSponge=.TRUE.`) in addition to prescribed OBCS from the primary test. The **secondary** test `input.tides/` adds 4 tidal components to the barotropic velocity at the open-boundaries (`useOBCStides=.TRUE.`) in addition to prescribed OBCS from the primary test. The additional tidal component binary input files have been generated using the matlab script `mk_tides.m` (see comments inside). Note: naming of tidal input files ("OB\*File") has been changed and augmented to include Open-Boundary tangential flows in PR [#752](https://github.com/MITgcm/MITgcm/pull/752) (see [`input.tides/update_TideFileName.sed`](input.tides/update_TideFileName.sed) on how to update `data.obcs`)
GCC Machine Description
[ { "kind": "Kubernetes", "clusterName": "primary", "podSubnet": "10.10.0.0/16", "svcSubnet": "10.224.0.0/12", "network": "network-1" } ]
JSON
/* Start.s * Assembly language assist for user programs running on top of Nachos. * * Since we don't want to pull in the entire C library, we define * what we need for a user program here, namely Start and the system * calls. */ #define IN_ASM #include "syscall.h" .text .align 2 /* ------------------------------------------------------------- * __start * Initialize running a C program, by calling "main". * * NOTE: This has to be first, so that it gets loaded at location 0. * The Nachos kernel always starts a program by jumping to location 0. * ------------------------------------------------------------- */ .globl __start .ent __start __start: jal main move $4,$0 addiu $4,$2,0 jal Exit /* if we return from main, exit(0) */ .end __start /* ------------------------------------------------------------- * System call stubs: * Assembly language assist to make system calls to the Nachos kernel. * There is one stub per system call, that places the code for the * system call into register r2, and leaves the arguments to the * system call alone (in other words, arg1 is in r4, arg2 is * in r5, arg3 is in r6, arg4 is in r7) * * The return value is in r2. This follows the standard C calling * convention on the MIPS. * ------------------------------------------------------------- */ .globl Halt .ent Halt Halt: addiu $2,$0,SC_Halt syscall j $31 .end Halt .globl Exit .ent Exit Exit: addiu $2,$0,SC_Exit syscall j $31 .end Exit .globl Exec .ent Exec Exec: addiu $2,$0,SC_Exec syscall j $31 .end Exec .globl Join .ent Join Join: addiu $2,$0,SC_Join syscall j $31 .end Join .globl Create .ent Create Create: addiu $2,$0,SC_Create syscall j $31 .end Create .globl Open .ent Open Open: addiu $2,$0,SC_Open syscall j $31 .end Open .globl Read .ent Read Read: addiu $2,$0,SC_Read syscall j $31 .end Read .globl Write .ent Write Write: addiu $2,$0,SC_Write syscall j $31 .end Write .globl Close .ent Close Close: addiu $2,$0,SC_Close syscall j $31 .end Close .globl Fork .ent Fork Fork: addiu $2,$0,SC_Fork syscall j $31 .end Fork .globl Yield .ent Yield Yield: addiu $2,$0,SC_Yield syscall j $31 .end Yield .globl Dump .ent Dump Dump: addiu $2,$0,SC_Dump syscall j $31 .end SC_Dump /* dummy function to keep gcc happy */ .globl __main .ent __main __main: j $31 .end __main
Assembly
// amm_master_qsys_with_pcie_pcie_ip.v // This file was auto-generated from altera_pcie_hard_ip_hw.tcl. If you edit it your changes // will probably be lost. // // Generated using ACDS version 13.0sp1 232 at 2014.11.18.17:01:08 `timescale 1 ps / 1 ps module amm_master_qsys_with_pcie_pcie_ip #( parameter p_pcie_hip_type = "2", parameter[7:0] lane_mask = 8'b11111110, parameter max_link_width = 1, parameter millisecond_cycle_count = "125000", parameter enable_gen2_core = "false", parameter gen2_lane_rate_mode = "false", parameter no_soft_reset = "false", parameter core_clk_divider = 2, parameter enable_ch0_pclk_out = "true", parameter core_clk_source = "pclk", parameter CB_P2A_AVALON_ADDR_B0 = 0, parameter bar0_size_mask = 9, parameter bar0_io_space = "false", parameter bar0_64bit_mem_space = "true", parameter bar0_prefetchable = "true", parameter CB_P2A_AVALON_ADDR_B1 = 0, parameter bar1_size_mask = 0, parameter bar1_io_space = "false", parameter bar1_64bit_mem_space = "true", parameter bar1_prefetchable = "false", parameter CB_P2A_AVALON_ADDR_B2 = 0, parameter bar2_size_mask = 15, parameter bar2_io_space = "false", parameter bar2_64bit_mem_space = "false", parameter bar2_prefetchable = "false", parameter CB_P2A_AVALON_ADDR_B3 = 0, parameter bar3_size_mask = 0, parameter bar3_io_space = "false", parameter bar3_64bit_mem_space = "false", parameter bar3_prefetchable = "false", parameter CB_P2A_AVALON_ADDR_B4 = 0, parameter bar4_size_mask = 0, parameter bar4_io_space = "false", parameter bar4_64bit_mem_space = "false", parameter bar4_prefetchable = "false", parameter CB_P2A_AVALON_ADDR_B5 = 0, parameter bar5_size_mask = 0, parameter bar5_io_space = "false", parameter bar5_64bit_mem_space = "false", parameter bar5_prefetchable = "false", parameter vendor_id = 4466, parameter device_id = 57345, parameter revision_id = 1, parameter class_code = 0, parameter subsystem_vendor_id = 4466, parameter subsystem_device_id = 4, parameter port_link_number = 1, parameter msi_function_count = 0, parameter enable_msi_64bit_addressing = "true", parameter enable_function_msix_support = "false", parameter eie_before_nfts_count = 4, parameter enable_completion_timeout_disable = "false", parameter completion_timeout = "NONE", parameter enable_adapter_half_rate_mode = "false", parameter msix_pba_bir = 0, parameter msix_pba_offset = 0, parameter msix_table_bir = 0, parameter msix_table_offset = 0, parameter msix_table_size = 0, parameter use_crc_forwarding = "false", parameter surprise_down_error_support = "false", parameter dll_active_report_support = "false", parameter bar_io_window_size = "32BIT", parameter bar_prefetchable = 32, parameter[6:0] hot_plug_support = 7'b0000000, parameter no_command_completed = "true", parameter slot_power_limit = 0, parameter slot_power_scale = 0, parameter slot_number = 0, parameter enable_slot_register = "false", parameter advanced_errors = "false", parameter enable_ecrc_check = "false", parameter enable_ecrc_gen = "false", parameter max_payload_size = 0, parameter retry_buffer_last_active_address = 255, parameter credit_buffer_allocation_aux = "ABSOLUTE", parameter vc0_rx_flow_ctrl_posted_header = 28, parameter vc0_rx_flow_ctrl_posted_data = 198, parameter vc0_rx_flow_ctrl_nonposted_header = 30, parameter vc0_rx_flow_ctrl_nonposted_data = 0, parameter vc0_rx_flow_ctrl_compl_header = 48, parameter vc0_rx_flow_ctrl_compl_data = 256, parameter RX_BUF = 9, parameter RH_NUM = 7, parameter G_TAG_NUM0 = 32, parameter endpoint_l0_latency = 0, parameter endpoint_l1_latency = 0, parameter enable_l1_aspm = "false", parameter l01_entry_latency = 31, parameter diffclock_nfts_count = 255, parameter sameclock_nfts_count = 255, parameter l1_exit_latency_sameclock = 7, parameter l1_exit_latency_diffclock = 7, parameter l0_exit_latency_sameclock = 7, parameter l0_exit_latency_diffclock = 7, parameter gen2_diffclock_nfts_count = 255, parameter gen2_sameclock_nfts_count = 255, parameter CG_COMMON_CLOCK_MODE = 1, parameter CB_PCIE_MODE = 0, parameter AST_LITE = 0, parameter CB_PCIE_RX_LITE = 0, parameter CG_RXM_IRQ_NUM = 16, parameter CG_AVALON_S_ADDR_WIDTH = 20, parameter bypass_tl = "false", parameter CG_IMPL_CRA_AV_SLAVE_PORT = 1, parameter CG_NO_CPL_REORDERING = 0, parameter CG_ENABLE_A2P_INTERRUPT = 0, parameter CG_IRQ_BIT_ENA = 65535, parameter CB_A2P_ADDR_MAP_IS_FIXED = 1, parameter CB_A2P_ADDR_MAP_NUM_ENTRIES = 1, parameter CB_A2P_ADDR_MAP_PASS_THRU_BITS = 31, parameter[31:0] CB_A2P_ADDR_MAP_FIXED_TABLE_0_HIGH = 32'b00000000000000000000000000000000, parameter[31:0] CB_A2P_ADDR_MAP_FIXED_TABLE_0_LOW = 32'b00000000000000000000000000000000, parameter[31:0] CB_A2P_ADDR_MAP_FIXED_TABLE_1_HIGH = 32'b00000000000000000000000000000000, parameter[31:0] CB_A2P_ADDR_MAP_FIXED_TABLE_1_LOW = 32'b00000000000000000000000000000000, parameter[31:0] CB_A2P_ADDR_MAP_FIXED_TABLE_2_HIGH = 32'b00000000000000000000000000000000, parameter[31:0] CB_A2P_ADDR_MAP_FIXED_TABLE_2_LOW = 32'b00000000000000000000000000000000, parameter[31:0] CB_A2P_ADDR_MAP_FIXED_TABLE_3_HIGH = 32'b00000000000000000000000000000000, parameter[31:0] CB_A2P_ADDR_MAP_FIXED_TABLE_3_LOW = 32'b00000000000000000000000000000000, parameter[31:0] CB_A2P_ADDR_MAP_FIXED_TABLE_4_HIGH = 32'b00000000000000000000000000000000, parameter[31:0] CB_A2P_ADDR_MAP_FIXED_TABLE_4_LOW = 32'b00000000000000000000000000000000, parameter[31:0] CB_A2P_ADDR_MAP_FIXED_TABLE_5_HIGH = 32'b00000000000000000000000000000000, parameter[31:0] CB_A2P_ADDR_MAP_FIXED_TABLE_5_LOW = 32'b00000000000000000000000000000000, parameter[31:0] CB_A2P_ADDR_MAP_FIXED_TABLE_6_HIGH = 32'b00000000000000000000000000000000, parameter[31:0] CB_A2P_ADDR_MAP_FIXED_TABLE_6_LOW = 32'b00000000000000000000000000000000, parameter[31:0] CB_A2P_ADDR_MAP_FIXED_TABLE_7_HIGH = 32'b00000000000000000000000000000000, parameter[31:0] CB_A2P_ADDR_MAP_FIXED_TABLE_7_LOW = 32'b00000000000000000000000000000000, parameter[31:0] CB_A2P_ADDR_MAP_FIXED_TABLE_8_HIGH = 32'b00000000000000000000000000000000, parameter[31:0] CB_A2P_ADDR_MAP_FIXED_TABLE_8_LOW = 32'b00000000000000000000000000000000, parameter[31:0] CB_A2P_ADDR_MAP_FIXED_TABLE_9_HIGH = 32'b00000000000000000000000000000000, parameter[31:0] CB_A2P_ADDR_MAP_FIXED_TABLE_9_LOW = 32'b00000000000000000000000000000000, parameter[31:0] CB_A2P_ADDR_MAP_FIXED_TABLE_10_HIGH = 32'b00000000000000000000000000000000, parameter[31:0] CB_A2P_ADDR_MAP_FIXED_TABLE_10_LOW = 32'b00000000000000000000000000000000, parameter[31:0] CB_A2P_ADDR_MAP_FIXED_TABLE_11_HIGH = 32'b00000000000000000000000000000000, parameter[31:0] CB_A2P_ADDR_MAP_FIXED_TABLE_11_LOW = 32'b00000000000000000000000000000000, parameter[31:0] CB_A2P_ADDR_MAP_FIXED_TABLE_12_HIGH = 32'b00000000000000000000000000000000, parameter[31:0] CB_A2P_ADDR_MAP_FIXED_TABLE_12_LOW = 32'b00000000000000000000000000000000, parameter[31:0] CB_A2P_ADDR_MAP_FIXED_TABLE_13_HIGH = 32'b00000000000000000000000000000000, parameter[31:0] CB_A2P_ADDR_MAP_FIXED_TABLE_13_LOW = 32'b00000000000000000000000000000000, parameter[31:0] CB_A2P_ADDR_MAP_FIXED_TABLE_14_HIGH = 32'b00000000000000000000000000000000, parameter[31:0] CB_A2P_ADDR_MAP_FIXED_TABLE_14_LOW = 32'b00000000000000000000000000000000, parameter[31:0] CB_A2P_ADDR_MAP_FIXED_TABLE_15_HIGH = 32'b00000000000000000000000000000000, parameter[31:0] CB_A2P_ADDR_MAP_FIXED_TABLE_15_LOW = 32'b00000000000000000000000000000000, parameter RXM_DATA_WIDTH = 64, parameter RXM_BEN_WIDTH = 8, parameter TL_SELECTION = 1, parameter pcie_mode = "SHARED_MODE", parameter single_rx_detect = 1, parameter enable_coreclk_out_half_rate = "false", parameter low_priority_vc = 0, parameter link_width = 1, parameter cyclone4 = 1 ) ( output wire pcie_core_clk_clk, // pcie_core_clk.clk output wire pcie_core_reset_reset_n, // pcie_core_reset.reset_n input wire cal_blk_clk_clk, // cal_blk_clk.clk input wire [30:0] txs_address, // txs.address input wire txs_chipselect, // .chipselect input wire [7:0] txs_byteenable, // .byteenable output wire [63:0] txs_readdata, // .readdata input wire [63:0] txs_writedata, // .writedata input wire txs_read, // .read input wire txs_write, // .write input wire [6:0] txs_burstcount, // .burstcount output wire txs_readdatavalid, // .readdatavalid output wire txs_waitrequest, // .waitrequest input wire refclk_export, // refclk.export input wire [39:0] test_in_test_in, // test_in.test_in input wire pcie_rstn_export, // pcie_rstn.export output wire clocks_sim_clk250_export, // clocks_sim.clk250_export output wire clocks_sim_clk500_export, // .clk500_export output wire clocks_sim_clk125_export, // .clk125_export input wire reconfig_busy_busy_altgxb_reconfig, // reconfig_busy.busy_altgxb_reconfig input wire pipe_ext_pipe_mode, // pipe_ext.pipe_mode input wire pipe_ext_phystatus_ext, // .phystatus_ext output wire pipe_ext_rate_ext, // .rate_ext output wire [1:0] pipe_ext_powerdown_ext, // .powerdown_ext output wire pipe_ext_txdetectrx_ext, // .txdetectrx_ext input wire pipe_ext_rxelecidle0_ext, // .rxelecidle0_ext input wire [7:0] pipe_ext_rxdata0_ext, // .rxdata0_ext input wire [2:0] pipe_ext_rxstatus0_ext, // .rxstatus0_ext input wire pipe_ext_rxvalid0_ext, // .rxvalid0_ext input wire pipe_ext_rxdatak0_ext, // .rxdatak0_ext output wire [7:0] pipe_ext_txdata0_ext, // .txdata0_ext output wire pipe_ext_txdatak0_ext, // .txdatak0_ext output wire pipe_ext_rxpolarity0_ext, // .rxpolarity0_ext output wire pipe_ext_txcompl0_ext, // .txcompl0_ext output wire pipe_ext_txelecidle0_ext, // .txelecidle0_ext input wire powerdown_pll_powerdown, // powerdown.pll_powerdown input wire powerdown_gxb_powerdown, // .gxb_powerdown output wire [31:0] bar1_0_address, // bar1_0.address output wire bar1_0_read, // .read input wire bar1_0_waitrequest, // .waitrequest output wire bar1_0_write, // .write input wire bar1_0_readdatavalid, // .readdatavalid input wire [63:0] bar1_0_readdata, // .readdata output wire [63:0] bar1_0_writedata, // .writedata output wire [6:0] bar1_0_burstcount, // .burstcount output wire [7:0] bar1_0_byteenable, // .byteenable output wire [31:0] bar2_address, // bar2.address output wire bar2_read, // .read input wire bar2_waitrequest, // .waitrequest output wire bar2_write, // .write input wire bar2_readdatavalid, // .readdatavalid input wire [63:0] bar2_readdata, // .readdata output wire [63:0] bar2_writedata, // .writedata output wire [6:0] bar2_burstcount, // .burstcount output wire [7:0] bar2_byteenable, // .byteenable input wire cra_chipselect, // cra.chipselect input wire [11:0] cra_address, // .address input wire [3:0] cra_byteenable, // .byteenable input wire cra_read, // .read output wire [31:0] cra_readdata, // .readdata input wire cra_write, // .write input wire [31:0] cra_writedata, // .writedata output wire cra_waitrequest, // .waitrequest output wire cra_irq_irq, // cra_irq.irq input wire [15:0] rxm_irq_irq, // rxm_irq.irq input wire rx_in_rx_datain_0, // rx_in.rx_datain_0 output wire tx_out_tx_dataout_0, // tx_out.tx_dataout_0 input wire [3:0] reconfig_togxb_data, // reconfig_togxb.data input wire reconfig_gxbclk_clk, // reconfig_gxbclk.clk output wire [4:0] reconfig_fromgxb_0_data, // reconfig_fromgxb_0.data input wire fixedclk_clk // fixedclk.clk ); wire reset_controller_internal_rx_digitalreset_serdes_interconect; // reset_controller_internal:rx_digitalreset_serdes -> altgx_internal:rx_digitalreset wire pipe_interface_internal_txdatak_pcs_interconect; // pipe_interface_internal:txdatak_pcs -> altgx_internal:tx_ctrlenable wire [7:0] pipe_interface_internal_txdata_pcs_interconect; // pipe_interface_internal:txdata_pcs -> altgx_internal:tx_datain wire pipe_interface_internal_pclk_central_hip_interconect; // pipe_interface_internal:pclk_central_hip -> pcie_internal_hip:pclk_central wire pipe_interface_internal_pclk_ch0_hip_interconect; // pipe_interface_internal:pclk_ch0_hip -> pcie_internal_hip:pclk_ch0 wire pipe_interface_internal_pll_fixed_clk_hip_interconect; // pipe_interface_internal:pll_fixed_clk_hip -> pcie_internal_hip:pll_fixed_clk wire pcie_internal_hip_l2_exit_interconect; // pcie_internal_hip:l2_exit -> reset_controller_internal:l2_exit wire pcie_internal_hip_hotrst_exit_interconect; // pcie_internal_hip:hotrst_exit -> reset_controller_internal:hotrst_exit wire pcie_internal_hip_dlup_exit_interconect; // pcie_internal_hip:dlup_exit -> reset_controller_internal:dlup_exit wire [4:0] pcie_internal_hip_dl_ltssm_int_interconect; // pcie_internal_hip:dl_ltssm_int -> reset_controller_internal:ltssm wire reset_controller_internal_srst_interconect; // reset_controller_internal:srst -> pcie_internal_hip:srst wire reset_controller_internal_crst_interconect; // reset_controller_internal:crst -> pcie_internal_hip:crst wire pipe_interface_internal_rc_pll_locked_interconect; // pipe_interface_internal:rc_pll_locked -> reset_controller_internal:pll_locked wire altgx_internal_rx_freqlocked_interconect; // altgx_internal:rx_freqlocked -> reset_controller_internal:rx_freqlocked wire reset_controller_internal_txdigitalreset_interconect; // reset_controller_internal:txdigitalreset -> altgx_internal:tx_digitalreset wire reset_controller_internal_rxanalogreset_interconect; // reset_controller_internal:rxanalogreset -> altgx_internal:rx_analogreset wire pipe_interface_internal_rc_areset_interconect; // pipe_interface_internal:rc_areset -> pcie_internal_hip:rc_areset wire [7:0] altgx_internal_rx_dataout_interconect; // altgx_internal:rx_dataout -> pipe_interface_internal:rxdata_pcs wire altgx_internal_pipephydonestatus_interconect; // altgx_internal:pipephydonestatus -> pipe_interface_internal:phystatus_pcs wire altgx_internal_pipeelecidle_interconect; // altgx_internal:pipeelecidle -> pipe_interface_internal:rxelecidle_pcs wire altgx_internal_pipedatavalid_interconect; // altgx_internal:pipedatavalid -> pipe_interface_internal:rxvalid_pcs wire [2:0] altgx_internal_pipestatus_interconect; // altgx_internal:pipestatus -> pipe_interface_internal:rxstatus_pcs wire altgx_internal_rx_ctrldetect_interconect; // altgx_internal:rx_ctrldetect -> pipe_interface_internal:rxdatak_pcs wire pipe_interface_internal_gxb_powerdown_pcs_interconect; // pipe_interface_internal:gxb_powerdown_pcs -> altgx_internal:gxb_powerdown wire altgx_internal_hip_tx_clkout_0_interconect; // altgx_internal:hip_tx_clkout_0 -> pipe_interface_internal:hip_tx_clkout_pcs wire reset_controller_internal_clk250_out_interconect; // reset_controller_internal:clk250_out -> pipe_interface_internal:clk250_out wire reset_controller_internal_clk500_out_interconect; // reset_controller_internal:clk500_out -> pipe_interface_internal:clk500_out wire pcie_internal_hip_rate_ext_interconect; // pcie_internal_hip:rate_ext -> pipe_interface_internal:rate_hip wire altgx_internal_pll_locked_interconect; // altgx_internal:pll_locked -> pipe_interface_internal:pll_locked_pcs wire [1:0] pipe_interface_internal_powerdown_pcs_interconect; // pipe_interface_internal:powerdown_pcs -> altgx_internal:powerdn wire pipe_interface_internal_rxpolarity_pcs_interconect; // pipe_interface_internal:rxpolarity_pcs -> altgx_internal:pipe8b10binvpolarity wire pipe_interface_internal_txcompl_pcs_interconect; // pipe_interface_internal:txcompl_pcs -> altgx_internal:tx_forcedispcompliance wire pipe_interface_internal_txdetectrx_pcs_interconect; // pipe_interface_internal:txdetectrx_pcs -> altgx_internal:tx_detectrxloop wire pipe_interface_internal_txelecidle_pcs_interconect; // pipe_interface_internal:txelecidle_pcs -> altgx_internal:tx_forceelecidle wire pipe_interface_internal_rxdatak_hip_0_interconect; // pipe_interface_internal:rxdatak_hip_0 -> pcie_internal_hip:rxdatak0_ext wire [2:0] pcie_internal_hip_eidle_infer_sel_0_interconect; // pcie_internal_hip:eidle_infer_sel_0 -> altgx_internal:rx_elecidleinfersel_0 wire [7:0] pipe_interface_internal_rxdata_hip_0_interconect; // pipe_interface_internal:rxdata_hip_0 -> pcie_internal_hip:rxdata0_ext wire pipe_interface_internal_rxvalid_hip_0_interconect; // pipe_interface_internal:rxvalid_hip_0 -> pcie_internal_hip:rxvalid0_ext wire pipe_interface_internal_rxelecidle_hip_0_interconect; // pipe_interface_internal:rxelecidle_hip_0 -> pcie_internal_hip:rxelecidle0_ext wire pipe_interface_internal_phystatus_hip_0_interconect; // pipe_interface_internal:phystatus_hip_0 -> pcie_internal_hip:phystatus0_ext wire [2:0] pipe_interface_internal_rxstatus_hip_0_interconect; // pipe_interface_internal:rxstatus_hip_0 -> pcie_internal_hip:rxstatus0_ext wire [7:0] pcie_internal_hip_txdata0_ext_interconect; // pcie_internal_hip:txdata0_ext -> pipe_interface_internal:txdata0_hip wire pcie_internal_hip_txdatak0_ext_interconect; // pcie_internal_hip:txdatak0_ext -> pipe_interface_internal:txdatak0_hip wire [1:0] pcie_internal_hip_powerdown0_ext_interconect; // pcie_internal_hip:powerdown0_ext -> pipe_interface_internal:powerdown0_hip wire pcie_internal_hip_rxpolarity0_ext_interconect; // pcie_internal_hip:rxpolarity0_ext -> pipe_interface_internal:rxpolarity0_hip wire pcie_internal_hip_txcompl0_ext_interconect; // pcie_internal_hip:txcompl0_ext -> pipe_interface_internal:txcompl0_hip wire pcie_internal_hip_txdetectrx0_ext_interconect; // pcie_internal_hip:txdetectrx0_ext -> pipe_interface_internal:txdetectrx0_hip wire pcie_internal_hip_txelecidle0_ext_interconect; // pcie_internal_hip:txelecidle0_ext -> pipe_interface_internal:txelecidle0_hip wire rst_controller_reset_out_reset; // rst_controller:reset_out -> pcie_internal_hip:Rstn_i wire [2:0] pcie_internal_hip_eidle_infer_sel; // port fragment wire [4:0] pcie_internal_hip_dl_ltssm; // port fragment wire [0:0] altgx_internal_tx_dataout; // port fragment wire [0:0] altgx_internal_hip_tx_clkout; // port fragment wire [0:0] pipe_interface_internal_rxvalid_hip; // port fragment wire [0:0] pipe_interface_internal_rxelecidle_hip; // port fragment wire [7:0] pipe_interface_internal_rxdata_hip; // port fragment wire [2:0] pipe_interface_internal_rxstatus_hip; // port fragment wire [0:0] pipe_interface_internal_rxdatak_hip; // port fragment wire [0:0] pipe_interface_internal_phystatus_hip; // port fragment generate // If any of the display statements (or deliberately broken // instantiations) within this generate block triggers then this module // has been instantiated this module with a set of parameters different // from those it was generated for. This will usually result in a // non-functioning system. if (p_pcie_hip_type != "2") begin initial begin $display("Generated module instantiated with wrong parameters"); $stop; end instantiated_with_wrong_parameters_error_see_comment_above p_pcie_hip_type_check ( .error(1'b1) ); end if (lane_mask != 8'b11111110) begin initial begin $display("Generated module instantiated with wrong parameters"); $stop; end instantiated_with_wrong_parameters_error_see_comment_above lane_mask_check ( .error(1'b1) ); end if (max_link_width != 1) begin initial begin $display("Generated module instantiated with wrong parameters"); $stop; end instantiated_with_wrong_parameters_error_see_comment_above max_link_width_check ( .error(1'b1) ); end if (millisecond_cycle_count != "125000") begin initial begin $display("Generated module instantiated with wrong parameters"); $stop; end instantiated_with_wrong_parameters_error_see_comment_above millisecond_cycle_count_check ( .error(1'b1) ); end if (enable_gen2_core != "false") begin initial begin $display("Generated module instantiated with wrong parameters"); $stop; end instantiated_with_wrong_parameters_error_see_comment_above enable_gen2_core_check ( .error(1'b1) ); end if (gen2_lane_rate_mode != "false") begin initial begin $display("Generated module instantiated with wrong parameters"); $stop; end instantiated_with_wrong_parameters_error_see_comment_above gen2_lane_rate_mode_check ( .error(1'b1) ); end if (no_soft_reset != "false") begin initial begin $display("Generated module instantiated with wrong parameters"); $stop; end instantiated_with_wrong_parameters_error_see_comment_above no_soft_reset_check ( .error(1'b1) ); end if (core_clk_divider != 2) begin initial begin $display("Generated module instantiated with wrong parameters"); $stop; end instantiated_with_wrong_parameters_error_see_comment_above core_clk_divider_check ( .error(1'b1) ); end if (enable_ch0_pclk_out != "true") begin initial begin $display("Generated module instantiated with wrong parameters"); $stop; end instantiated_with_wrong_parameters_error_see_comment_above enable_ch0_pclk_out_check ( .error(1'b1) ); end if (core_clk_source != "pclk") begin initial begin $display("Generated module instantiated with wrong parameters"); $stop; end instantiated_with_wrong_parameters_error_see_comment_above core_clk_source_check ( .error(1'b1) ); end if (CB_P2A_AVALON_ADDR_B0 != 0) begin initial begin $display("Generated module instantiated with wrong parameters"); $stop; end instantiated_with_wrong_parameters_error_see_comment_above cb_p2a_avalon_addr_b0_check ( .error(1'b1) ); end if (bar0_size_mask != 9) begin initial begin $display("Generated module instantiated with wrong parameters"); $stop; end instantiated_with_wrong_parameters_error_see_comment_above bar0_size_mask_check ( .error(1'b1) ); end if (bar0_io_space != "false") begin initial begin $display("Generated module instantiated with wrong parameters"); $stop; end instantiated_with_wrong_parameters_error_see_comment_above bar0_io_space_check ( .error(1'b1) ); end if (bar0_64bit_mem_space != "true") begin initial begin $display("Generated module instantiated with wrong parameters"); $stop; end instantiated_with_wrong_parameters_error_see_comment_above bar0_64bit_mem_space_check ( .error(1'b1) ); end if (bar0_prefetchable != "true") begin initial begin $display("Generated module instantiated with wrong parameters"); $stop; end instantiated_with_wrong_parameters_error_see_comment_above bar0_prefetchable_check ( .error(1'b1) ); end if (CB_P2A_AVALON_ADDR_B1 != 0) begin initial begin $display("Generated module instantiated with wrong parameters"); $stop; end instantiated_with_wrong_parameters_error_see_comment_above cb_p2a_avalon_addr_b1_check ( .error(1'b1) ); end if (bar1_size_mask != 0) begin initial begin $display("Generated module instantiated with wrong parameters"); $stop; end instantiated_with_wrong_parameters_error_see_comment_above bar1_size_mask_check ( .error(1'b1) ); end if (bar1_io_space != "false") begin initial begin $display("Generated module instantiated with wrong parameters"); $stop; end instantiated_with_wrong_parameters_error_see_comment_above bar1_io_space_check ( .error(1'b1) ); end if (bar1_64bit_mem_space != "true") begin initial begin $display("Generated module instantiated with wrong parameters"); $stop; end instantiated_with_wrong_parameters_error_see_comment_above bar1_64bit_mem_space_check ( .error(1'b1) ); end if (bar1_prefetchable != "false") begin initial begin $display("Generated module instantiated with wrong parameters"); $stop; end instantiated_with_wrong_parameters_error_see_comment_above bar1_prefetchable_check ( .error(1'b1) ); end if (CB_P2A_AVALON_ADDR_B2 != 0) begin initial begin $display("Generated module instantiated with wrong parameters"); $stop; end instantiated_with_wrong_parameters_error_see_comment_above cb_p2a_avalon_addr_b2_check ( .error(1'b1) ); end if (bar2_size_mask != 15) begin initial begin $display("Generated module instantiated with wrong parameters"); $stop; end instantiated_with_wrong_parameters_error_see_comment_above bar2_size_mask_check ( .error(1'b1) ); end if (bar2_io_space != "false") begin initial begin $display("Generated module instantiated with wrong parameters"); $stop; end instantiated_with_wrong_parameters_error_see_comment_above bar2_io_space_check ( .error(1'b1) ); end if (bar2_64bit_mem_space != "false") begin initial begin $display("Generated module instantiated with wrong parameters"); $stop; end instantiated_with_wrong_parameters_error_see_comment_above bar2_64bit_mem_space_check ( .error(1'b1) ); end if (bar2_prefetchable != "false") begin initial begin $display("Generated module instantiated with wrong parameters"); $stop; end instantiated_with_wrong_parameters_error_see_comment_above bar2_prefetchable_check ( .error(1'b1) ); end if (CB_P2A_AVALON_ADDR_B3 != 0) begin initial begin $display("Generated module instantiated with wrong parameters"); $stop; end instantiated_with_wrong_parameters_error_see_comment_above cb_p2a_avalon_addr_b3_check ( .error(1'b1) ); end if (bar3_size_mask != 0) begin initial begin $display("Generated module instantiated with wrong parameters"); $stop; end instantiated_with_wrong_parameters_error_see_comment_above bar3_size_mask_check ( .error(1'b1) ); end if (bar3_io_space != "false") begin initial begin $display("Generated module instantiated with wrong parameters"); $stop; end instantiated_with_wrong_parameters_error_see_comment_above bar3_io_space_check ( .error(1'b1) ); end if (bar3_64bit_mem_space != "false") begin initial begin $display("Generated module instantiated with wrong parameters"); $stop; end instantiated_with_wrong_parameters_error_see_comment_above bar3_64bit_mem_space_check ( .error(1'b1) ); end if (bar3_prefetchable != "false") begin initial begin $display("Generated module instantiated with wrong parameters"); $stop; end instantiated_with_wrong_parameters_error_see_comment_above bar3_prefetchable_check ( .error(1'b1) ); end if (CB_P2A_AVALON_ADDR_B4 != 0) begin initial begin $display("Generated module instantiated with wrong parameters"); $stop; end instantiated_with_wrong_parameters_error_see_comment_above cb_p2a_avalon_addr_b4_check ( .error(1'b1) ); end if (bar4_size_mask != 0) begin initial begin $display("Generated module instantiated with wrong parameters"); $stop; end instantiated_with_wrong_parameters_error_see_comment_above bar4_size_mask_check ( .error(1'b1) ); end if (bar4_io_space != "false") begin initial begin $display("Generated module instantiated with wrong parameters"); $stop; end instantiated_with_wrong_parameters_error_see_comment_above bar4_io_space_check ( .error(1'b1) ); end if (bar4_64bit_mem_space != "false") begin initial begin $display("Generated module instantiated with wrong parameters"); $stop; end instantiated_with_wrong_parameters_error_see_comment_above bar4_64bit_mem_space_check ( .error(1'b1) ); end if (bar4_prefetchable != "false") begin initial begin $display("Generated module instantiated with wrong parameters"); $stop; end instantiated_with_wrong_parameters_error_see_comment_above bar4_prefetchable_check ( .error(1'b1) ); end if (CB_P2A_AVALON_ADDR_B5 != 0) begin initial begin $display("Generated module instantiated with wrong parameters"); $stop; end instantiated_with_wrong_parameters_error_see_comment_above cb_p2a_avalon_addr_b5_check ( .error(1'b1) ); end if (bar5_size_mask != 0) begin initial begin $display("Generated module instantiated with wrong parameters"); $stop; end instantiated_with_wrong_parameters_error_see_comment_above bar5_size_mask_check ( .error(1'b1) ); end if (bar5_io_space != "false") begin initial begin $display("Generated module instantiated with wrong parameters"); $stop; end instantiated_with_wrong_parameters_error_see_comment_above bar5_io_space_check ( .error(1'b1) ); end if (bar5_64bit_mem_space != "false") begin initial begin $display("Generated module instantiated with wrong parameters"); $stop; end instantiated_with_wrong_parameters_error_see_comment_above bar5_64bit_mem_space_check ( .error(1'b1) ); end if (bar5_prefetchable != "false") begin initial begin $display("Generated module instantiated with wrong parameters"); $stop; end instantiated_with_wrong_parameters_error_see_comment_above bar5_prefetchable_check ( .error(1'b1) ); end if (vendor_id != 4466) begin initial begin $display("Generated module instantiated with wrong parameters"); $stop; end instantiated_with_wrong_parameters_error_see_comment_above vendor_id_check ( .error(1'b1) ); end if (device_id != 57345) begin initial begin $display("Generated module instantiated with wrong parameters"); $stop; end instantiated_with_wrong_parameters_error_see_comment_above device_id_check ( .error(1'b1) ); end if (revision_id != 1) begin initial begin $display("Generated module instantiated with wrong parameters"); $stop; end instantiated_with_wrong_parameters_error_see_comment_above revision_id_check ( .error(1'b1) ); end if (class_code != 0) begin initial begin $display("Generated module instantiated with wrong parameters"); $stop; end instantiated_with_wrong_parameters_error_see_comment_above class_code_check ( .error(1'b1) ); end if (subsystem_vendor_id != 4466) begin initial begin $display("Generated module instantiated with wrong parameters"); $stop; end instantiated_with_wrong_parameters_error_see_comment_above subsystem_vendor_id_check ( .error(1'b1) ); end if (subsystem_device_id != 4) begin initial begin $display("Generated module instantiated with wrong parameters"); $stop; end instantiated_with_wrong_parameters_error_see_comment_above subsystem_device_id_check ( .error(1'b1) ); end if (port_link_number != 1) begin initial begin $display("Generated module instantiated with wrong parameters"); $stop; end instantiated_with_wrong_parameters_error_see_comment_above port_link_number_check ( .error(1'b1) ); end if (msi_function_count != 0) begin initial begin $display("Generated module instantiated with wrong parameters"); $stop; end instantiated_with_wrong_parameters_error_see_comment_above msi_function_count_check ( .error(1'b1) ); end if (enable_msi_64bit_addressing != "true") begin initial begin $display("Generated module instantiated with wrong parameters"); $stop; end instantiated_with_wrong_parameters_error_see_comment_above enable_msi_64bit_addressing_check ( .error(1'b1) ); end if (enable_function_msix_support != "false") begin initial begin $display("Generated module instantiated with wrong parameters"); $stop; end instantiated_with_wrong_parameters_error_see_comment_above enable_function_msix_support_check ( .error(1'b1) ); end if (eie_before_nfts_count != 4) begin initial begin $display("Generated module instantiated with wrong parameters"); $stop; end instantiated_with_wrong_parameters_error_see_comment_above eie_before_nfts_count_check ( .error(1'b1) ); end if (enable_completion_timeout_disable != "false") begin initial begin $display("Generated module instantiated with wrong parameters"); $stop; end instantiated_with_wrong_parameters_error_see_comment_above enable_completion_timeout_disable_check ( .error(1'b1) ); end if (completion_timeout != "NONE") begin initial begin $display("Generated module instantiated with wrong parameters"); $stop; end instantiated_with_wrong_parameters_error_see_comment_above completion_timeout_check ( .error(1'b1) ); end if (enable_adapter_half_rate_mode != "false") begin initial begin $display("Generated module instantiated with wrong parameters"); $stop; end instantiated_with_wrong_parameters_error_see_comment_above enable_adapter_half_rate_mode_check ( .error(1'b1) ); end if (msix_pba_bir != 0) begin initial begin $display("Generated module instantiated with wrong parameters"); $stop; end instantiated_with_wrong_parameters_error_see_comment_above msix_pba_bir_check ( .error(1'b1) ); end if (msix_pba_offset != 0) begin initial begin $display("Generated module instantiated with wrong parameters"); $stop; end instantiated_with_wrong_parameters_error_see_comment_above msix_pba_offset_check ( .error(1'b1) ); end if (msix_table_bir != 0) begin initial begin $display("Generated module instantiated with wrong parameters"); $stop; end instantiated_with_wrong_parameters_error_see_comment_above msix_table_bir_check ( .error(1'b1) ); end if (msix_table_offset != 0) begin initial begin $display("Generated module instantiated with wrong parameters"); $stop; end instantiated_with_wrong_parameters_error_see_comment_above msix_table_offset_check ( .error(1'b1) ); end if (msix_table_size != 0) begin initial begin $display("Generated module instantiated with wrong parameters"); $stop; end instantiated_with_wrong_parameters_error_see_comment_above msix_table_size_check ( .error(1'b1) ); end if (use_crc_forwarding != "false") begin initial begin $display("Generated module instantiated with wrong parameters"); $stop; end instantiated_with_wrong_parameters_error_see_comment_above use_crc_forwarding_check ( .error(1'b1) ); end if (surprise_down_error_support != "false") begin initial begin $display("Generated module instantiated with wrong parameters"); $stop; end instantiated_with_wrong_parameters_error_see_comment_above surprise_down_error_support_check ( .error(1'b1) ); end if (dll_active_report_support != "false") begin initial begin $display("Generated module instantiated with wrong parameters"); $stop; end instantiated_with_wrong_parameters_error_see_comment_above dll_active_report_support_check ( .error(1'b1) ); end if (bar_io_window_size != "32BIT") begin initial begin $display("Generated module instantiated with wrong parameters"); $stop; end instantiated_with_wrong_parameters_error_see_comment_above bar_io_window_size_check ( .error(1'b1) ); end if (bar_prefetchable != 32) begin initial begin $display("Generated module instantiated with wrong parameters"); $stop; end instantiated_with_wrong_parameters_error_see_comment_above bar_prefetchable_check ( .error(1'b1) ); end if (hot_plug_support != 7'b0000000) begin initial begin $display("Generated module instantiated with wrong parameters"); $stop; end instantiated_with_wrong_parameters_error_see_comment_above hot_plug_support_check ( .error(1'b1) ); end if (no_command_completed != "true") begin initial begin $display("Generated module instantiated with wrong parameters"); $stop; end instantiated_with_wrong_parameters_error_see_comment_above no_command_completed_check ( .error(1'b1) ); end if (slot_power_limit != 0) begin initial begin $display("Generated module instantiated with wrong parameters"); $stop; end instantiated_with_wrong_parameters_error_see_comment_above slot_power_limit_check ( .error(1'b1) ); end if (slot_power_scale != 0) begin initial begin $display("Generated module instantiated with wrong parameters"); $stop; end instantiated_with_wrong_parameters_error_see_comment_above slot_power_scale_check ( .error(1'b1) ); end if (slot_number != 0) begin initial begin $display("Generated module instantiated with wrong parameters"); $stop; end instantiated_with_wrong_parameters_error_see_comment_above slot_number_check ( .error(1'b1) ); end if (enable_slot_register != "false") begin initial begin $display("Generated module instantiated with wrong parameters"); $stop; end instantiated_with_wrong_parameters_error_see_comment_above enable_slot_register_check ( .error(1'b1) ); end if (advanced_errors != "false") begin initial begin $display("Generated module instantiated with wrong parameters"); $stop; end instantiated_with_wrong_parameters_error_see_comment_above advanced_errors_check ( .error(1'b1) ); end if (enable_ecrc_check != "false") begin initial begin $display("Generated module instantiated with wrong parameters"); $stop; end instantiated_with_wrong_parameters_error_see_comment_above enable_ecrc_check_check ( .error(1'b1) ); end if (enable_ecrc_gen != "false") begin initial begin $display("Generated module instantiated with wrong parameters"); $stop; end instantiated_with_wrong_parameters_error_see_comment_above enable_ecrc_gen_check ( .error(1'b1) ); end if (max_payload_size != 0) begin initial begin $display("Generated module instantiated with wrong parameters"); $stop; end instantiated_with_wrong_parameters_error_see_comment_above max_payload_size_check ( .error(1'b1) ); end if (retry_buffer_last_active_address != 255) begin initial begin $display("Generated module instantiated with wrong parameters"); $stop; end instantiated_with_wrong_parameters_error_see_comment_above retry_buffer_last_active_address_check ( .error(1'b1) ); end if (credit_buffer_allocation_aux != "ABSOLUTE") begin initial begin $display("Generated module instantiated with wrong parameters"); $stop; end instantiated_with_wrong_parameters_error_see_comment_above credit_buffer_allocation_aux_check ( .error(1'b1) ); end if (vc0_rx_flow_ctrl_posted_header != 28) begin initial begin $display("Generated module instantiated with wrong parameters"); $stop; end instantiated_with_wrong_parameters_error_see_comment_above vc0_rx_flow_ctrl_posted_header_check ( .error(1'b1) ); end if (vc0_rx_flow_ctrl_posted_data != 198) begin initial begin $display("Generated module instantiated with wrong parameters"); $stop; end instantiated_with_wrong_parameters_error_see_comment_above vc0_rx_flow_ctrl_posted_data_check ( .error(1'b1) ); end if (vc0_rx_flow_ctrl_nonposted_header != 30) begin initial begin $display("Generated module instantiated with wrong parameters"); $stop; end instantiated_with_wrong_parameters_error_see_comment_above vc0_rx_flow_ctrl_nonposted_header_check ( .error(1'b1) ); end if (vc0_rx_flow_ctrl_nonposted_data != 0) begin initial begin $display("Generated module instantiated with wrong parameters"); $stop; end instantiated_with_wrong_parameters_error_see_comment_above vc0_rx_flow_ctrl_nonposted_data_check ( .error(1'b1) ); end if (vc0_rx_flow_ctrl_compl_header != 48) begin initial begin $display("Generated module instantiated with wrong parameters"); $stop; end instantiated_with_wrong_parameters_error_see_comment_above vc0_rx_flow_ctrl_compl_header_check ( .error(1'b1) ); end if (vc0_rx_flow_ctrl_compl_data != 256) begin initial begin $display("Generated module instantiated with wrong parameters"); $stop; end instantiated_with_wrong_parameters_error_see_comment_above vc0_rx_flow_ctrl_compl_data_check ( .error(1'b1) ); end if (RX_BUF != 9) begin initial begin $display("Generated module instantiated with wrong parameters"); $stop; end instantiated_with_wrong_parameters_error_see_comment_above rx_buf_check ( .error(1'b1) ); end if (RH_NUM != 7) begin initial begin $display("Generated module instantiated with wrong parameters"); $stop; end instantiated_with_wrong_parameters_error_see_comment_above rh_num_check ( .error(1'b1) ); end if (G_TAG_NUM0 != 32) begin initial begin $display("Generated module instantiated with wrong parameters"); $stop; end instantiated_with_wrong_parameters_error_see_comment_above g_tag_num0_check ( .error(1'b1) ); end if (endpoint_l0_latency != 0) begin initial begin $display("Generated module instantiated with wrong parameters"); $stop; end instantiated_with_wrong_parameters_error_see_comment_above endpoint_l0_latency_check ( .error(1'b1) ); end if (endpoint_l1_latency != 0) begin initial begin $display("Generated module instantiated with wrong parameters"); $stop; end instantiated_with_wrong_parameters_error_see_comment_above endpoint_l1_latency_check ( .error(1'b1) ); end if (enable_l1_aspm != "false") begin initial begin $display("Generated module instantiated with wrong parameters"); $stop; end instantiated_with_wrong_parameters_error_see_comment_above enable_l1_aspm_check ( .error(1'b1) ); end if (l01_entry_latency != 31) begin initial begin $display("Generated module instantiated with wrong parameters"); $stop; end instantiated_with_wrong_parameters_error_see_comment_above l01_entry_latency_check ( .error(1'b1) ); end if (diffclock_nfts_count != 255) begin initial begin $display("Generated module instantiated with wrong parameters"); $stop; end instantiated_with_wrong_parameters_error_see_comment_above diffclock_nfts_count_check ( .error(1'b1) ); end if (sameclock_nfts_count != 255) begin initial begin $display("Generated module instantiated with wrong parameters"); $stop; end instantiated_with_wrong_parameters_error_see_comment_above sameclock_nfts_count_check ( .error(1'b1) ); end if (l1_exit_latency_sameclock != 7) begin initial begin $display("Generated module instantiated with wrong parameters"); $stop; end instantiated_with_wrong_parameters_error_see_comment_above l1_exit_latency_sameclock_check ( .error(1'b1) ); end if (l1_exit_latency_diffclock != 7) begin initial begin $display("Generated module instantiated with wrong parameters"); $stop; end instantiated_with_wrong_parameters_error_see_comment_above l1_exit_latency_diffclock_check ( .error(1'b1) ); end if (l0_exit_latency_sameclock != 7) begin initial begin $display("Generated module instantiated with wrong parameters"); $stop; end instantiated_with_wrong_parameters_error_see_comment_above l0_exit_latency_sameclock_check ( .error(1'b1) ); end if (l0_exit_latency_diffclock != 7) begin initial begin $display("Generated module instantiated with wrong parameters"); $stop; end instantiated_with_wrong_parameters_error_see_comment_above l0_exit_latency_diffclock_check ( .error(1'b1) ); end if (gen2_diffclock_nfts_count != 255) begin initial begin $display("Generated module instantiated with wrong parameters"); $stop; end instantiated_with_wrong_parameters_error_see_comment_above gen2_diffclock_nfts_count_check ( .error(1'b1) ); end if (gen2_sameclock_nfts_count != 255) begin initial begin $display("Generated module instantiated with wrong parameters"); $stop; end instantiated_with_wrong_parameters_error_see_comment_above gen2_sameclock_nfts_count_check ( .error(1'b1) ); end if (CG_COMMON_CLOCK_MODE != 1) begin initial begin $display("Generated module instantiated with wrong parameters"); $stop; end instantiated_with_wrong_parameters_error_see_comment_above cg_common_clock_mode_check ( .error(1'b1) ); end if (CB_PCIE_MODE != 0) begin initial begin $display("Generated module instantiated with wrong parameters"); $stop; end instantiated_with_wrong_parameters_error_see_comment_above cb_pcie_mode_check ( .error(1'b1) ); end if (AST_LITE != 0) begin initial begin $display("Generated module instantiated with wrong parameters"); $stop; end instantiated_with_wrong_parameters_error_see_comment_above ast_lite_check ( .error(1'b1) ); end if (CB_PCIE_RX_LITE != 0) begin initial begin $display("Generated module instantiated with wrong parameters"); $stop; end instantiated_with_wrong_parameters_error_see_comment_above cb_pcie_rx_lite_check ( .error(1'b1) ); end if (CG_RXM_IRQ_NUM != 16) begin initial begin $display("Generated module instantiated with wrong parameters"); $stop; end instantiated_with_wrong_parameters_error_see_comment_above cg_rxm_irq_num_check ( .error(1'b1) ); end if (CG_AVALON_S_ADDR_WIDTH != 20) begin initial begin $display("Generated module instantiated with wrong parameters"); $stop; end instantiated_with_wrong_parameters_error_see_comment_above cg_avalon_s_addr_width_check ( .error(1'b1) ); end if (bypass_tl != "false") begin initial begin $display("Generated module instantiated with wrong parameters"); $stop; end instantiated_with_wrong_parameters_error_see_comment_above bypass_tl_check ( .error(1'b1) ); end if (CG_IMPL_CRA_AV_SLAVE_PORT != 1) begin initial begin $display("Generated module instantiated with wrong parameters"); $stop; end instantiated_with_wrong_parameters_error_see_comment_above cg_impl_cra_av_slave_port_check ( .error(1'b1) ); end if (CG_NO_CPL_REORDERING != 0) begin initial begin $display("Generated module instantiated with wrong parameters"); $stop; end instantiated_with_wrong_parameters_error_see_comment_above cg_no_cpl_reordering_check ( .error(1'b1) ); end if (CG_ENABLE_A2P_INTERRUPT != 0) begin initial begin $display("Generated module instantiated with wrong parameters"); $stop; end instantiated_with_wrong_parameters_error_see_comment_above cg_enable_a2p_interrupt_check ( .error(1'b1) ); end if (CG_IRQ_BIT_ENA != 65535) begin initial begin $display("Generated module instantiated with wrong parameters"); $stop; end instantiated_with_wrong_parameters_error_see_comment_above cg_irq_bit_ena_check ( .error(1'b1) ); end if (CB_A2P_ADDR_MAP_IS_FIXED != 1) begin initial begin $display("Generated module instantiated with wrong parameters"); $stop; end instantiated_with_wrong_parameters_error_see_comment_above cb_a2p_addr_map_is_fixed_check ( .error(1'b1) ); end if (CB_A2P_ADDR_MAP_NUM_ENTRIES != 1) begin initial begin $display("Generated module instantiated with wrong parameters"); $stop; end instantiated_with_wrong_parameters_error_see_comment_above cb_a2p_addr_map_num_entries_check ( .error(1'b1) ); end if (CB_A2P_ADDR_MAP_PASS_THRU_BITS != 31) begin initial begin $display("Generated module instantiated with wrong parameters"); $stop; end instantiated_with_wrong_parameters_error_see_comment_above cb_a2p_addr_map_pass_thru_bits_check ( .error(1'b1) ); end if (CB_A2P_ADDR_MAP_FIXED_TABLE_0_HIGH != 32'b00000000000000000000000000000000) begin initial begin $display("Generated module instantiated with wrong parameters"); $stop; end instantiated_with_wrong_parameters_error_see_comment_above cb_a2p_addr_map_fixed_table_0_high_check ( .error(1'b1) ); end if (CB_A2P_ADDR_MAP_FIXED_TABLE_0_LOW != 32'b00000000000000000000000000000000) begin initial begin $display("Generated module instantiated with wrong parameters"); $stop; end instantiated_with_wrong_parameters_error_see_comment_above cb_a2p_addr_map_fixed_table_0_low_check ( .error(1'b1) ); end if (CB_A2P_ADDR_MAP_FIXED_TABLE_1_HIGH != 32'b00000000000000000000000000000000) begin initial begin $display("Generated module instantiated with wrong parameters"); $stop; end instantiated_with_wrong_parameters_error_see_comment_above cb_a2p_addr_map_fixed_table_1_high_check ( .error(1'b1) ); end if (CB_A2P_ADDR_MAP_FIXED_TABLE_1_LOW != 32'b00000000000000000000000000000000) begin initial begin $display("Generated module instantiated with wrong parameters"); $stop; end instantiated_with_wrong_parameters_error_see_comment_above cb_a2p_addr_map_fixed_table_1_low_check ( .error(1'b1) ); end if (CB_A2P_ADDR_MAP_FIXED_TABLE_2_HIGH != 32'b00000000000000000000000000000000) begin initial begin $display("Generated module instantiated with wrong parameters"); $stop; end instantiated_with_wrong_parameters_error_see_comment_above cb_a2p_addr_map_fixed_table_2_high_check ( .error(1'b1) ); end if (CB_A2P_ADDR_MAP_FIXED_TABLE_2_LOW != 32'b00000000000000000000000000000000) begin initial begin $display("Generated module instantiated with wrong parameters"); $stop; end instantiated_with_wrong_parameters_error_see_comment_above cb_a2p_addr_map_fixed_table_2_low_check ( .error(1'b1) ); end if (CB_A2P_ADDR_MAP_FIXED_TABLE_3_HIGH != 32'b00000000000000000000000000000000) begin initial begin $display("Generated module instantiated with wrong parameters"); $stop; end instantiated_with_wrong_parameters_error_see_comment_above cb_a2p_addr_map_fixed_table_3_high_check ( .error(1'b1) ); end if (CB_A2P_ADDR_MAP_FIXED_TABLE_3_LOW != 32'b00000000000000000000000000000000) begin initial begin $display("Generated module instantiated with wrong parameters"); $stop; end instantiated_with_wrong_parameters_error_see_comment_above cb_a2p_addr_map_fixed_table_3_low_check ( .error(1'b1) ); end if (CB_A2P_ADDR_MAP_FIXED_TABLE_4_HIGH != 32'b00000000000000000000000000000000) begin initial begin $display("Generated module instantiated with wrong parameters"); $stop; end instantiated_with_wrong_parameters_error_see_comment_above cb_a2p_addr_map_fixed_table_4_high_check ( .error(1'b1) ); end if (CB_A2P_ADDR_MAP_FIXED_TABLE_4_LOW != 32'b00000000000000000000000000000000) begin initial begin $display("Generated module instantiated with wrong parameters"); $stop; end instantiated_with_wrong_parameters_error_see_comment_above cb_a2p_addr_map_fixed_table_4_low_check ( .error(1'b1) ); end if (CB_A2P_ADDR_MAP_FIXED_TABLE_5_HIGH != 32'b00000000000000000000000000000000) begin initial begin $display("Generated module instantiated with wrong parameters"); $stop; end instantiated_with_wrong_parameters_error_see_comment_above cb_a2p_addr_map_fixed_table_5_high_check ( .error(1'b1) ); end if (CB_A2P_ADDR_MAP_FIXED_TABLE_5_LOW != 32'b00000000000000000000000000000000) begin initial begin $display("Generated module instantiated with wrong parameters"); $stop; end instantiated_with_wrong_parameters_error_see_comment_above cb_a2p_addr_map_fixed_table_5_low_check ( .error(1'b1) ); end if (CB_A2P_ADDR_MAP_FIXED_TABLE_6_HIGH != 32'b00000000000000000000000000000000) begin initial begin $display("Generated module instantiated with wrong parameters"); $stop; end instantiated_with_wrong_parameters_error_see_comment_above cb_a2p_addr_map_fixed_table_6_high_check ( .error(1'b1) ); end if (CB_A2P_ADDR_MAP_FIXED_TABLE_6_LOW != 32'b00000000000000000000000000000000) begin initial begin $display("Generated module instantiated with wrong parameters"); $stop; end instantiated_with_wrong_parameters_error_see_comment_above cb_a2p_addr_map_fixed_table_6_low_check ( .error(1'b1) ); end if (CB_A2P_ADDR_MAP_FIXED_TABLE_7_HIGH != 32'b00000000000000000000000000000000) begin initial begin $display("Generated module instantiated with wrong parameters"); $stop; end instantiated_with_wrong_parameters_error_see_comment_above cb_a2p_addr_map_fixed_table_7_high_check ( .error(1'b1) ); end if (CB_A2P_ADDR_MAP_FIXED_TABLE_7_LOW != 32'b00000000000000000000000000000000) begin initial begin $display("Generated module instantiated with wrong parameters"); $stop; end instantiated_with_wrong_parameters_error_see_comment_above cb_a2p_addr_map_fixed_table_7_low_check ( .error(1'b1) ); end if (CB_A2P_ADDR_MAP_FIXED_TABLE_8_HIGH != 32'b00000000000000000000000000000000) begin initial begin $display("Generated module instantiated with wrong parameters"); $stop; end instantiated_with_wrong_parameters_error_see_comment_above cb_a2p_addr_map_fixed_table_8_high_check ( .error(1'b1) ); end if (CB_A2P_ADDR_MAP_FIXED_TABLE_8_LOW != 32'b00000000000000000000000000000000) begin initial begin $display("Generated module instantiated with wrong parameters"); $stop; end instantiated_with_wrong_parameters_error_see_comment_above cb_a2p_addr_map_fixed_table_8_low_check ( .error(1'b1) ); end if (CB_A2P_ADDR_MAP_FIXED_TABLE_9_HIGH != 32'b00000000000000000000000000000000) begin initial begin $display("Generated module instantiated with wrong parameters"); $stop; end instantiated_with_wrong_parameters_error_see_comment_above cb_a2p_addr_map_fixed_table_9_high_check ( .error(1'b1) ); end if (CB_A2P_ADDR_MAP_FIXED_TABLE_9_LOW != 32'b00000000000000000000000000000000) begin initial begin $display("Generated module instantiated with wrong parameters"); $stop; end instantiated_with_wrong_parameters_error_see_comment_above cb_a2p_addr_map_fixed_table_9_low_check ( .error(1'b1) ); end if (CB_A2P_ADDR_MAP_FIXED_TABLE_10_HIGH != 32'b00000000000000000000000000000000) begin initial begin $display("Generated module instantiated with wrong parameters"); $stop; end instantiated_with_wrong_parameters_error_see_comment_above cb_a2p_addr_map_fixed_table_10_high_check ( .error(1'b1) ); end if (CB_A2P_ADDR_MAP_FIXED_TABLE_10_LOW != 32'b00000000000000000000000000000000) begin initial begin $display("Generated module instantiated with wrong parameters"); $stop; end instantiated_with_wrong_parameters_error_see_comment_above cb_a2p_addr_map_fixed_table_10_low_check ( .error(1'b1) ); end if (CB_A2P_ADDR_MAP_FIXED_TABLE_11_HIGH != 32'b00000000000000000000000000000000) begin initial begin $display("Generated module instantiated with wrong parameters"); $stop; end instantiated_with_wrong_parameters_error_see_comment_above cb_a2p_addr_map_fixed_table_11_high_check ( .error(1'b1) ); end if (CB_A2P_ADDR_MAP_FIXED_TABLE_11_LOW != 32'b00000000000000000000000000000000) begin initial begin $display("Generated module instantiated with wrong parameters"); $stop; end instantiated_with_wrong_parameters_error_see_comment_above cb_a2p_addr_map_fixed_table_11_low_check ( .error(1'b1) ); end if (CB_A2P_ADDR_MAP_FIXED_TABLE_12_HIGH != 32'b00000000000000000000000000000000) begin initial begin $display("Generated module instantiated with wrong parameters"); $stop; end instantiated_with_wrong_parameters_error_see_comment_above cb_a2p_addr_map_fixed_table_12_high_check ( .error(1'b1) ); end if (CB_A2P_ADDR_MAP_FIXED_TABLE_12_LOW != 32'b00000000000000000000000000000000) begin initial begin $display("Generated module instantiated with wrong parameters"); $stop; end instantiated_with_wrong_parameters_error_see_comment_above cb_a2p_addr_map_fixed_table_12_low_check ( .error(1'b1) ); end if (CB_A2P_ADDR_MAP_FIXED_TABLE_13_HIGH != 32'b00000000000000000000000000000000) begin initial begin $display("Generated module instantiated with wrong parameters"); $stop; end instantiated_with_wrong_parameters_error_see_comment_above cb_a2p_addr_map_fixed_table_13_high_check ( .error(1'b1) ); end if (CB_A2P_ADDR_MAP_FIXED_TABLE_13_LOW != 32'b00000000000000000000000000000000) begin initial begin $display("Generated module instantiated with wrong parameters"); $stop; end instantiated_with_wrong_parameters_error_see_comment_above cb_a2p_addr_map_fixed_table_13_low_check ( .error(1'b1) ); end if (CB_A2P_ADDR_MAP_FIXED_TABLE_14_HIGH != 32'b00000000000000000000000000000000) begin initial begin $display("Generated module instantiated with wrong parameters"); $stop; end instantiated_with_wrong_parameters_error_see_comment_above cb_a2p_addr_map_fixed_table_14_high_check ( .error(1'b1) ); end if (CB_A2P_ADDR_MAP_FIXED_TABLE_14_LOW != 32'b00000000000000000000000000000000) begin initial begin $display("Generated module instantiated with wrong parameters"); $stop; end instantiated_with_wrong_parameters_error_see_comment_above cb_a2p_addr_map_fixed_table_14_low_check ( .error(1'b1) ); end if (CB_A2P_ADDR_MAP_FIXED_TABLE_15_HIGH != 32'b00000000000000000000000000000000) begin initial begin $display("Generated module instantiated with wrong parameters"); $stop; end instantiated_with_wrong_parameters_error_see_comment_above cb_a2p_addr_map_fixed_table_15_high_check ( .error(1'b1) ); end if (CB_A2P_ADDR_MAP_FIXED_TABLE_15_LOW != 32'b00000000000000000000000000000000) begin initial begin $display("Generated module instantiated with wrong parameters"); $stop; end instantiated_with_wrong_parameters_error_see_comment_above cb_a2p_addr_map_fixed_table_15_low_check ( .error(1'b1) ); end if (RXM_DATA_WIDTH != 64) begin initial begin $display("Generated module instantiated with wrong parameters"); $stop; end instantiated_with_wrong_parameters_error_see_comment_above rxm_data_width_check ( .error(1'b1) ); end if (RXM_BEN_WIDTH != 8) begin initial begin $display("Generated module instantiated with wrong parameters"); $stop; end instantiated_with_wrong_parameters_error_see_comment_above rxm_ben_width_check ( .error(1'b1) ); end if (TL_SELECTION != 1) begin initial begin $display("Generated module instantiated with wrong parameters"); $stop; end instantiated_with_wrong_parameters_error_see_comment_above tl_selection_check ( .error(1'b1) ); end if (pcie_mode != "SHARED_MODE") begin initial begin $display("Generated module instantiated with wrong parameters"); $stop; end instantiated_with_wrong_parameters_error_see_comment_above pcie_mode_check ( .error(1'b1) ); end if (single_rx_detect != 1) begin initial begin $display("Generated module instantiated with wrong parameters"); $stop; end instantiated_with_wrong_parameters_error_see_comment_above single_rx_detect_check ( .error(1'b1) ); end if (enable_coreclk_out_half_rate != "false") begin initial begin $display("Generated module instantiated with wrong parameters"); $stop; end instantiated_with_wrong_parameters_error_see_comment_above enable_coreclk_out_half_rate_check ( .error(1'b1) ); end if (low_priority_vc != 0) begin initial begin $display("Generated module instantiated with wrong parameters"); $stop; end instantiated_with_wrong_parameters_error_see_comment_above low_priority_vc_check ( .error(1'b1) ); end if (link_width != 1) begin initial begin $display("Generated module instantiated with wrong parameters"); $stop; end instantiated_with_wrong_parameters_error_see_comment_above link_width_check ( .error(1'b1) ); end if (cyclone4 != 1) begin initial begin $display("Generated module instantiated with wrong parameters"); $stop; end instantiated_with_wrong_parameters_error_see_comment_above cyclone4_check ( .error(1'b1) ); end endgenerate altpcie_hip_pipen1b_qsys #( .INTENDED_DEVICE_FAMILY ("Cyclone IV GX"), .pcie_qsys (1), .p_pcie_hip_type ("2"), .lane_mask (8'b11111110), .max_link_width (1), .millisecond_cycle_count ("125000"), .enable_gen2_core ("false"), .gen2_lane_rate_mode ("false"), .no_soft_reset ("false"), .core_clk_divider (2), .enable_ch0_pclk_out ("true"), .core_clk_source ("pclk"), .CB_P2A_AVALON_ADDR_B0 (0), .bar0_size_mask (9), .bar0_io_space ("false"), .bar0_64bit_mem_space ("true"), .bar0_prefetchable ("true"), .CB_P2A_AVALON_ADDR_B1 (0), .bar1_size_mask (0), .bar1_io_space ("false"), .bar1_64bit_mem_space ("true"), .bar1_prefetchable ("false"), .CB_P2A_AVALON_ADDR_B2 (0), .bar2_size_mask (15), .bar2_io_space ("false"), .bar2_64bit_mem_space ("false"), .bar2_prefetchable ("false"), .CB_P2A_AVALON_ADDR_B3 (0), .bar3_size_mask (0), .bar3_io_space ("false"), .bar3_64bit_mem_space ("false"), .bar3_prefetchable ("false"), .CB_P2A_AVALON_ADDR_B4 (0), .bar4_size_mask (0), .bar4_io_space ("false"), .bar4_64bit_mem_space ("false"), .bar4_prefetchable ("false"), .CB_P2A_AVALON_ADDR_B5 (0), .bar5_size_mask (0), .bar5_io_space ("false"), .bar5_64bit_mem_space ("false"), .bar5_prefetchable ("false"), .vendor_id (4466), .device_id (57345), .revision_id (1), .class_code (0), .subsystem_vendor_id (4466), .subsystem_device_id (4), .port_link_number (1), .msi_function_count (0), .enable_msi_64bit_addressing ("true"), .enable_function_msix_support ("false"), .eie_before_nfts_count (4), .enable_completion_timeout_disable ("false"), .completion_timeout ("NONE"), .enable_adapter_half_rate_mode ("false"), .msix_pba_bir (0), .msix_pba_offset (0), .msix_table_bir (0), .msix_table_offset (0), .msix_table_size (0), .use_crc_forwarding ("false"), .surprise_down_error_support ("false"), .dll_active_report_support ("false"), .bar_io_window_size ("32BIT"), .bar_prefetchable (32), .hot_plug_support (7'b0000000), .no_command_completed ("true"), .slot_power_limit (0), .slot_power_scale (0), .slot_number (0), .enable_slot_register ("false"), .advanced_errors ("false"), .enable_ecrc_check ("false"), .enable_ecrc_gen ("false"), .max_payload_size (0), .retry_buffer_last_active_address (255), .credit_buffer_allocation_aux ("BALANCED"), .vc0_rx_flow_ctrl_posted_header (28), .vc0_rx_flow_ctrl_posted_data (198), .vc0_rx_flow_ctrl_nonposted_header (30), .vc0_rx_flow_ctrl_nonposted_data (0), .vc0_rx_flow_ctrl_compl_header (48), .vc0_rx_flow_ctrl_compl_data (256), .RX_BUF (10), .RH_NUM (7), .G_TAG_NUM0 (32), .endpoint_l0_latency (0), .endpoint_l1_latency (0), .enable_l1_aspm ("false"), .l01_entry_latency (31), .diffclock_nfts_count (255), .sameclock_nfts_count (255), .l1_exit_latency_sameclock (7), .l1_exit_latency_diffclock (7), .l0_exit_latency_sameclock (7), .l0_exit_latency_diffclock (7), .gen2_diffclock_nfts_count (255), .gen2_sameclock_nfts_count (255), .CG_COMMON_CLOCK_MODE (1), .CB_PCIE_MODE (0), .AST_LITE (0), .CB_PCIE_RX_LITE (0), .CG_RXM_IRQ_NUM (16), .CG_AVALON_S_ADDR_WIDTH (31), .bypass_tl ("false"), .CG_IMPL_CRA_AV_SLAVE_PORT (1), .CG_NO_CPL_REORDERING (0), .CG_ENABLE_A2P_INTERRUPT (0), .CG_IRQ_BIT_ENA (65535), .CB_A2P_ADDR_MAP_IS_FIXED (1), .CB_A2P_ADDR_MAP_NUM_ENTRIES (1), .CB_A2P_ADDR_MAP_PASS_THRU_BITS (31), .CB_A2P_ADDR_MAP_FIXED_TABLE_0_HIGH (32'b00000000000000000000000000000000), .CB_A2P_ADDR_MAP_FIXED_TABLE_0_LOW (32'b00000000000000000000000000000000), .CB_A2P_ADDR_MAP_FIXED_TABLE_1_HIGH (32'b00000000000000000000000000000000), .CB_A2P_ADDR_MAP_FIXED_TABLE_1_LOW (32'b00000000000000000000000000000000), .CB_A2P_ADDR_MAP_FIXED_TABLE_2_HIGH (32'b00000000000000000000000000000000), .CB_A2P_ADDR_MAP_FIXED_TABLE_2_LOW (32'b00000000000000000000000000000000), .CB_A2P_ADDR_MAP_FIXED_TABLE_3_HIGH (32'b00000000000000000000000000000000), .CB_A2P_ADDR_MAP_FIXED_TABLE_3_LOW (32'b00000000000000000000000000000000), .CB_A2P_ADDR_MAP_FIXED_TABLE_4_HIGH (32'b00000000000000000000000000000000), .CB_A2P_ADDR_MAP_FIXED_TABLE_4_LOW (32'b00000000000000000000000000000000), .CB_A2P_ADDR_MAP_FIXED_TABLE_5_HIGH (32'b00000000000000000000000000000000), .CB_A2P_ADDR_MAP_FIXED_TABLE_5_LOW (32'b00000000000000000000000000000000), .CB_A2P_ADDR_MAP_FIXED_TABLE_6_HIGH (32'b00000000000000000000000000000000), .CB_A2P_ADDR_MAP_FIXED_TABLE_6_LOW (32'b00000000000000000000000000000000), .CB_A2P_ADDR_MAP_FIXED_TABLE_7_HIGH (32'b00000000000000000000000000000000), .CB_A2P_ADDR_MAP_FIXED_TABLE_7_LOW (32'b00000000000000000000000000000000), .CB_A2P_ADDR_MAP_FIXED_TABLE_8_HIGH (32'b00000000000000000000000000000000), .CB_A2P_ADDR_MAP_FIXED_TABLE_8_LOW (32'b00000000000000000000000000000000), .CB_A2P_ADDR_MAP_FIXED_TABLE_9_HIGH (32'b00000000000000000000000000000000), .CB_A2P_ADDR_MAP_FIXED_TABLE_9_LOW (32'b00000000000000000000000000000000), .CB_A2P_ADDR_MAP_FIXED_TABLE_10_HIGH (32'b00000000000000000000000000000000), .CB_A2P_ADDR_MAP_FIXED_TABLE_10_LOW (32'b00000000000000000000000000000000), .CB_A2P_ADDR_MAP_FIXED_TABLE_11_HIGH (32'b00000000000000000000000000000000), .CB_A2P_ADDR_MAP_FIXED_TABLE_11_LOW (32'b00000000000000000000000000000000), .CB_A2P_ADDR_MAP_FIXED_TABLE_12_HIGH (32'b00000000000000000000000000000000), .CB_A2P_ADDR_MAP_FIXED_TABLE_12_LOW (32'b00000000000000000000000000000000), .CB_A2P_ADDR_MAP_FIXED_TABLE_13_HIGH (32'b00000000000000000000000000000000), .CB_A2P_ADDR_MAP_FIXED_TABLE_13_LOW (32'b00000000000000000000000000000000), .CB_A2P_ADDR_MAP_FIXED_TABLE_14_HIGH (32'b00000000000000000000000000000000), .CB_A2P_ADDR_MAP_FIXED_TABLE_14_LOW (32'b00000000000000000000000000000000), .CB_A2P_ADDR_MAP_FIXED_TABLE_15_HIGH (32'b00000000000000000000000000000000), .CB_A2P_ADDR_MAP_FIXED_TABLE_15_LOW (32'b00000000000000000000000000000000), .RXM_DATA_WIDTH (64), .RXM_BEN_WIDTH (8), .TL_SELECTION (1), .pcie_mode ("SHARED_MODE"), .single_rx_detect (1), .enable_coreclk_out_half_rate ("false"), .low_priority_vc (0) ) pcie_internal_hip ( .npor (pcie_rstn_export), // npor.interconect .dl_ltssm (pcie_internal_hip_dl_ltssm), // dl_ltssm_int.interconect .dlup_exit (pcie_internal_hip_dlup_exit_interconect), // dlup_exit.interconect .hotrst_exit (pcie_internal_hip_hotrst_exit_interconect), // hotrst_exit.interconect .l2_exit (pcie_internal_hip_l2_exit_interconect), // l2_exit.interconect .powerdown0_ext (pcie_internal_hip_powerdown0_ext_interconect), // powerdown0_ext.interconect .rate_ext (pcie_internal_hip_rate_ext_interconect), // rate_ext.interconect .rc_rx_analogreset (), // rc_rx_analogreset.interconect .rc_rx_digitalreset (), // rc_rx_digitalreset.interconect .rxpolarity0_ext (pcie_internal_hip_rxpolarity0_ext_interconect), // rxpolarity0_ext.interconect .txcompl0_ext (pcie_internal_hip_txcompl0_ext_interconect), // txcompl0_ext.interconect .txdata0_ext (pcie_internal_hip_txdata0_ext_interconect), // txdata0_ext.interconect .txdatak0_ext (pcie_internal_hip_txdatak0_ext_interconect), // txdatak0_ext.interconect .txdetectrx0_ext (pcie_internal_hip_txdetectrx0_ext_interconect), // txdetectrx0_ext.interconect .txelecidle0_ext (pcie_internal_hip_txelecidle0_ext_interconect), // txelecidle0_ext.interconect .crst (reset_controller_internal_crst_interconect), // crst.interconect .pclk_central (pipe_interface_internal_pclk_central_hip_interconect), // pclk_central.interconect .pclk_ch0 (pipe_interface_internal_pclk_ch0_hip_interconect), // pclk_ch0.interconect .pld_clk (pcie_core_clk_clk), // pld_clk.clk .pll_fixed_clk (pipe_interface_internal_pll_fixed_clk_hip_interconect), // pll_fixed_clk.interconect .rc_areset (pipe_interface_internal_rc_areset_interconect), // rc_areset.interconect .srst (reset_controller_internal_srst_interconect), // srst.interconect .test_in (test_in_test_in), // test_in.interconect .AvlClk_i (pcie_core_clk_clk), // avalon_clk.clk .Rstn_i (~rst_controller_reset_out_reset), // avalon_reset.reset_n .TxsAddress_i (txs_address), // Txs.address .TxsChipSelect_i (txs_chipselect), // .chipselect .TxsByteEnable_i (txs_byteenable), // .byteenable .TxsReadData_o (txs_readdata), // .readdata .TxsWriteData_i (txs_writedata), // .writedata .TxsRead_i (txs_read), // .read .TxsWrite_i (txs_write), // .write .TxsBurstCount_i (txs_burstcount), // .burstcount .TxsReadDataValid_o (txs_readdatavalid), // .readdatavalid .TxsWaitRequest_o (txs_waitrequest), // .waitrequest .CraChipSelect_i (cra_chipselect), // Cra.chipselect .CraAddress_i (cra_address), // .address .CraByteEnable_i (cra_byteenable), // .byteenable .CraRead (cra_read), // .read .CraReadData_o (cra_readdata), // .readdata .CraWrite (cra_write), // .write .CraWriteData_i (cra_writedata), // .writedata .CraWaitRequest_o (cra_waitrequest), // .waitrequest .CraIrq_o (cra_irq_irq), // CraIrq.irq .core_clk_out (pcie_core_clk_clk), // pcie_core_clk.clk .eidle_infer_sel (pcie_internal_hip_eidle_infer_sel), // eidle_infer_sel_0.interconect .tx_deemph_0 (), // tx_deemph_0.interconect .tx_margin_0 (), // tx_margin_0.interconect .phystatus0_ext (pipe_interface_internal_phystatus_hip_0_interconect), // phystatus0_ext.interconect .rxdata0_ext (pipe_interface_internal_rxdata_hip_0_interconect), // rxdata0_ext.interconect .rxdatak0_ext (pipe_interface_internal_rxdatak_hip_0_interconect), // rxdatak0_ext.interconect .rxelecidle0_ext (pipe_interface_internal_rxelecidle_hip_0_interconect), // rxelecidle0_ext.interconect .rxstatus0_ext (pipe_interface_internal_rxstatus_hip_0_interconect), // rxstatus0_ext.interconect .rxvalid0_ext (pipe_interface_internal_rxvalid_hip_0_interconect), // rxvalid0_ext.interconect .RxmAddress_0_o (bar1_0_address), // Rxm_BAR0.address .RxmRead_0_o (bar1_0_read), // .read .RxmWaitRequest_0_i (bar1_0_waitrequest), // .waitrequest .RxmWrite_0_o (bar1_0_write), // .write .RxmReadDataValid_0_i (bar1_0_readdatavalid), // .readdatavalid .RxmReadData_0_i (bar1_0_readdata), // .readdata .RxmWriteData_0_o (bar1_0_writedata), // .writedata .RxmBurstCount_0_o (bar1_0_burstcount), // .burstcount .RxmByteEnable_0_o (bar1_0_byteenable), // .byteenable .RxmAddress_2_o (bar2_address), // Rxm_BAR2.address .RxmRead_2_o (bar2_read), // .read .RxmWaitRequest_2_i (bar2_waitrequest), // .waitrequest .RxmWrite_2_o (bar2_write), // .write .RxmReadDataValid_2_i (bar2_readdatavalid), // .readdatavalid .RxmReadData_2_i (bar2_readdata), // .readdata .RxmWriteData_2_o (bar2_writedata), // .writedata .RxmBurstCount_2_o (bar2_burstcount), // .burstcount .RxmByteEnable_2_o (bar2_byteenable), // .byteenable .RxmIrq_i (rxm_irq_irq), // RxmIrq.irq .app_int_ack (), // (terminated) .app_msi_ack (), // (terminated) .avs_pcie_reconfig_readdata (), // (terminated) .avs_pcie_reconfig_readdatavalid (), // (terminated) .avs_pcie_reconfig_waitrequest (), // (terminated) .derr_cor_ext_rcv0 (), // (terminated) .derr_cor_ext_rcv1 (), // (terminated) .derr_cor_ext_rpl (), // (terminated) .derr_rpl (), // (terminated) .ev_128ns (), // (terminated) .ev_1us (), // (terminated) .hip_extraclkout (), // (terminated) .int_status (), // (terminated) .lmi_ack (), // (terminated) .lmi_dout (), // (terminated) .npd_alloc_1cred_vc0 (), // (terminated) .npd_alloc_1cred_vc1 (), // (terminated) .npd_cred_vio_vc0 (), // (terminated) .npd_cred_vio_vc1 (), // (terminated) .nph_alloc_1cred_vc0 (), // (terminated) .nph_alloc_1cred_vc1 (), // (terminated) .nph_cred_vio_vc0 (), // (terminated) .nph_cred_vio_vc1 (), // (terminated) .pme_to_sr (), // (terminated) .powerdown1_ext (), // (terminated) .powerdown2_ext (), // (terminated) .powerdown3_ext (), // (terminated) .powerdown4_ext (), // (terminated) .powerdown5_ext (), // (terminated) .powerdown6_ext (), // (terminated) .powerdown7_ext (), // (terminated) .r2c_err0 (), // (terminated) .r2c_err1 (), // (terminated) .rc_gxb_powerdown (), // (terminated) .rc_tx_digitalreset (), // (terminated) .reset_status (), // (terminated) .rx_fifo_empty0 (), // (terminated) .rx_fifo_empty1 (), // (terminated) .rx_fifo_full0 (), // (terminated) .rx_fifo_full1 (), // (terminated) .rx_st_bardec0 (), // (terminated) .rx_st_bardec1 (), // (terminated) .rx_st_be0 (), // (terminated) .rx_st_be0_p1 (), // (terminated) .rx_st_be1 (), // (terminated) .rx_st_be1_p1 (), // (terminated) .rx_st_data0 (), // (terminated) .rx_st_data0_p1 (), // (terminated) .rx_st_data1 (), // (terminated) .rx_st_data1_p1 (), // (terminated) .rx_st_eop0 (), // (terminated) .rx_st_eop0_p1 (), // (terminated) .rx_st_eop1 (), // (terminated) .rx_st_eop1_p1 (), // (terminated) .rx_st_err0 (), // (terminated) .rx_st_err1 (), // (terminated) .rx_st_sop0 (), // (terminated) .rx_st_sop0_p1 (), // (terminated) .rx_st_sop1 (), // (terminated) .rx_st_sop1_p1 (), // (terminated) .rx_st_valid0 (), // (terminated) .rx_st_valid1 (), // (terminated) .rxpolarity1_ext (), // (terminated) .rxpolarity2_ext (), // (terminated) .rxpolarity3_ext (), // (terminated) .rxpolarity4_ext (), // (terminated) .rxpolarity5_ext (), // (terminated) .rxpolarity6_ext (), // (terminated) .rxpolarity7_ext (), // (terminated) .serr_out (), // (terminated) .suc_spd_neg (), // (terminated) .swdn_wake (), // (terminated) .swup_hotrst (), // (terminated) .tl_cfg_add (), // (terminated) .tl_cfg_ctl (), // (terminated) .tl_cfg_ctl_wr (), // (terminated) .tl_cfg_sts (), // (terminated) .tl_cfg_sts_wr (), // (terminated) .tlbp_dl_ack_phypm (), // (terminated) .tlbp_dl_ack_requpfc (), // (terminated) .tlbp_dl_ack_sndupfc (), // (terminated) .tlbp_dl_current_deemp (), // (terminated) .tlbp_dl_currentspeed (), // (terminated) .tlbp_dl_dll_req (), // (terminated) .tlbp_dl_err_dll (), // (terminated) .tlbp_dl_errphy (), // (terminated) .tlbp_dl_link_autobdw_status (), // (terminated) .tlbp_dl_link_bdwmng_status (), // (terminated) .tlbp_dl_rpbuf_emp (), // (terminated) .tlbp_dl_rst_enter_comp_bit (), // (terminated) .tlbp_dl_rst_tx_margin_field (), // (terminated) .tlbp_dl_rx_typ_pm (), // (terminated) .tlbp_dl_rx_valpm (), // (terminated) .tlbp_dl_tx_ackpm (), // (terminated) .tlbp_dl_up (), // (terminated) .tlbp_dl_vc_status (), // (terminated) .tlbp_link_up (), // (terminated) .tx_cred0 (), // (terminated) .tx_cred1 (), // (terminated) .tx_fifo_empty0 (), // (terminated) .tx_fifo_empty1 (), // (terminated) .tx_fifo_full0 (), // (terminated) .tx_fifo_full1 (), // (terminated) .tx_fifo_rdptr0 (), // (terminated) .tx_fifo_rdptr1 (), // (terminated) .tx_fifo_wrptr0 (), // (terminated) .tx_fifo_wrptr1 (), // (terminated) .tx_st_ready0 (), // (terminated) .tx_st_ready1 (), // (terminated) .txcompl1_ext (), // (terminated) .txcompl2_ext (), // (terminated) .txcompl3_ext (), // (terminated) .txcompl4_ext (), // (terminated) .txcompl5_ext (), // (terminated) .txcompl6_ext (), // (terminated) .txcompl7_ext (), // (terminated) .txdata1_ext (), // (terminated) .txdata2_ext (), // (terminated) .txdata3_ext (), // (terminated) .txdata4_ext (), // (terminated) .txdata5_ext (), // (terminated) .txdata6_ext (), // (terminated) .txdata7_ext (), // (terminated) .txdatak1_ext (), // (terminated) .txdatak2_ext (), // (terminated) .txdatak3_ext (), // (terminated) .txdatak4_ext (), // (terminated) .txdatak5_ext (), // (terminated) .txdatak6_ext (), // (terminated) .txdatak7_ext (), // (terminated) .txdetectrx1_ext (), // (terminated) .txdetectrx2_ext (), // (terminated) .txdetectrx3_ext (), // (terminated) .txdetectrx4_ext (), // (terminated) .txdetectrx5_ext (), // (terminated) .txdetectrx6_ext (), // (terminated) .txdetectrx7_ext (), // (terminated) .txelecidle1_ext (), // (terminated) .txelecidle2_ext (), // (terminated) .txelecidle3_ext (), // (terminated) .txelecidle4_ext (), // (terminated) .txelecidle5_ext (), // (terminated) .txelecidle6_ext (), // (terminated) .txelecidle7_ext (), // (terminated) .use_pcie_reconfig (), // (terminated) .wake_oen (), // (terminated) .aer_msi_num (5'b00000), // (terminated) .app_int_sts (1'b0), // (terminated) .app_msi_num (5'b00000), // (terminated) .app_msi_req (1'b0), // (terminated) .app_msi_tc (3'b000), // (terminated) .avs_pcie_reconfig_address (8'b00000000), // (terminated) .avs_pcie_reconfig_chipselect (1'b0), // (terminated) .avs_pcie_reconfig_clk (1'b0), // (terminated) .avs_pcie_reconfig_read (1'b0), // (terminated) .avs_pcie_reconfig_rstn (1'b0), // (terminated) .avs_pcie_reconfig_write (1'b0), // (terminated) .avs_pcie_reconfig_writedata (16'b0000000000000000), // (terminated) .core_clk_in (1'b0), // (terminated) .cpl_err (7'b0000000), // (terminated) .cpl_pending (1'b0), // (terminated) .dbg_pipex1_rx (15'b000000000000000), // (terminated) .hpg_ctrler (5'b00000), // (terminated) .lmi_addr (12'b000000000000), // (terminated) .lmi_din (32'b00000000000000000000000000000000), // (terminated) .lmi_rden (1'b0), // (terminated) .lmi_wren (1'b0), // (terminated) .mode (2'b00), // (terminated) .pex_msi_num (5'b00000), // (terminated) .pm_auxpwr (1'b0), // (terminated) .pm_data (10'b0000000000), // (terminated) .pm_event (1'b0), // (terminated) .pme_to_cr (1'b0), // (terminated) .rc_inclk_eq_125mhz (1'b0), // (terminated) .rc_pll_locked (1'b1), // (terminated) .rc_rx_pll_locked_one (1'b1), // (terminated) .rx_st_mask0 (1'b0), // (terminated) .rx_st_mask1 (1'b0), // (terminated) .rx_st_ready0 (1'b0), // (terminated) .rx_st_ready1 (1'b0), // (terminated) .swdn_in (3'b000), // (terminated) .swup_in (7'b0000000), // (terminated) .tl_slotclk_cfg (1'b1), // (terminated) .tlbp_dl_aspm_cr0 (1'b0), // (terminated) .tlbp_dl_comclk_reg (1'b0), // (terminated) .tlbp_dl_ctrl_link2 (13'b0000000000000), // (terminated) .tlbp_dl_data_upfc (12'b000000000000), // (terminated) .tlbp_dl_hdr_upfc (8'b00000000), // (terminated) .tlbp_dl_inh_dllp (1'b0), // (terminated) .tlbp_dl_maxpload_dcr (3'b000), // (terminated) .tlbp_dl_req_phycfg (4'b0000), // (terminated) .tlbp_dl_req_phypm (4'b0000), // (terminated) .tlbp_dl_req_upfc (1'b0), // (terminated) .tlbp_dl_req_wake (1'b0), // (terminated) .tlbp_dl_rx_ecrcchk (1'b0), // (terminated) .tlbp_dl_snd_upfc (1'b0), // (terminated) .tlbp_dl_tx_reqpm (1'b0), // (terminated) .tlbp_dl_tx_typpm (3'b000), // (terminated) .tlbp_dl_txcfg_extsy (1'b0), // (terminated) .tlbp_dl_typ_upfc (2'b00), // (terminated) .tlbp_dl_vc_ctrl (8'b00000000), // (terminated) .tlbp_dl_vcid_map (24'b000000000000000000000000), // (terminated) .tlbp_dl_vcid_upfc (3'b000), // (terminated) .tx_st_data0 (64'b0000000000000000000000000000000000000000000000000000000000000000), // (terminated) .tx_st_data0_p1 (64'b0000000000000000000000000000000000000000000000000000000000000000), // (terminated) .tx_st_data1 (64'b0000000000000000000000000000000000000000000000000000000000000000), // (terminated) .tx_st_data1_p1 (64'b0000000000000000000000000000000000000000000000000000000000000000), // (terminated) .tx_st_eop0 (1'b0), // (terminated) .tx_st_eop0_p1 (1'b0), // (terminated) .tx_st_eop1 (1'b0), // (terminated) .tx_st_eop1_p1 (1'b0), // (terminated) .tx_st_err0 (1'b0), // (terminated) .tx_st_err1 (1'b0), // (terminated) .tx_st_sop0 (1'b0), // (terminated) .tx_st_sop0_p1 (1'b0), // (terminated) .tx_st_sop1 (1'b0), // (terminated) .tx_st_sop1_p1 (1'b0), // (terminated) .tx_st_valid0 (1'b0), // (terminated) .tx_st_valid1 (1'b0), // (terminated) .phystatus1_ext (1'b0), // (terminated) .rxdata1_ext (8'b00000000), // (terminated) .rxdatak1_ext (1'b0), // (terminated) .rxelecidle1_ext (1'b0), // (terminated) .rxstatus1_ext (3'b000), // (terminated) .rxvalid1_ext (1'b0), // (terminated) .phystatus2_ext (1'b0), // (terminated) .rxdata2_ext (8'b00000000), // (terminated) .rxdatak2_ext (1'b0), // (terminated) .rxelecidle2_ext (1'b0), // (terminated) .rxstatus2_ext (3'b000), // (terminated) .rxvalid2_ext (1'b0), // (terminated) .phystatus3_ext (1'b0), // (terminated) .rxdata3_ext (8'b00000000), // (terminated) .rxdatak3_ext (1'b0), // (terminated) .rxelecidle3_ext (1'b0), // (terminated) .rxstatus3_ext (3'b000), // (terminated) .rxvalid3_ext (1'b0), // (terminated) .phystatus4_ext (1'b0), // (terminated) .rxdata4_ext (8'b00000000), // (terminated) .rxdatak4_ext (1'b0), // (terminated) .rxelecidle4_ext (1'b0), // (terminated) .rxstatus4_ext (3'b000), // (terminated) .rxvalid4_ext (1'b0), // (terminated) .phystatus5_ext (1'b0), // (terminated) .rxdata5_ext (8'b00000000), // (terminated) .rxdatak5_ext (1'b0), // (terminated) .rxelecidle5_ext (1'b0), // (terminated) .rxstatus5_ext (3'b000), // (terminated) .rxvalid5_ext (1'b0), // (terminated) .phystatus6_ext (1'b0), // (terminated) .rxdata6_ext (8'b00000000), // (terminated) .rxdatak6_ext (1'b0), // (terminated) .rxelecidle6_ext (1'b0), // (terminated) .rxstatus6_ext (3'b000), // (terminated) .rxvalid6_ext (1'b0), // (terminated) .phystatus7_ext (1'b0), // (terminated) .rxdata7_ext (8'b00000000), // (terminated) .rxdatak7_ext (1'b0), // (terminated) .rxelecidle7_ext (1'b0), // (terminated) .rxstatus7_ext (3'b000), // (terminated) .rxvalid7_ext (1'b0) // (terminated) ); amm_master_qsys_with_pcie_pcie_ip_altgx_internal altgx_internal ( .cal_blk_clk (cal_blk_clk_clk), // cal_blk_clk.clk .gxb_powerdown (pipe_interface_internal_gxb_powerdown_pcs_interconect), // gxb_powerdown.interconect .pipe8b10binvpolarity (pipe_interface_internal_rxpolarity_pcs_interconect), // pipe8b10binvpolarity.interconect .pll_inclk (refclk_export), // pll_inclk.interconect .powerdn (pipe_interface_internal_powerdown_pcs_interconect), // powerdn.interconect .rx_analogreset (reset_controller_internal_rxanalogreset_interconect), // rx_analogreset.interconect .fixedclk (fixedclk_clk), // fixedclk_export.clk .reconfig_togxb (reconfig_togxb_data), // togxb_export.data .reconfig_fromgxb (reconfig_fromgxb_0_data), // fromgxb_export_0.data .reconfig_clk (reconfig_gxbclk_clk), // reconfig_clk_export.clk .rx_dataout (altgx_internal_rx_dataout_interconect), // rx_dataout.interconect .rx_digitalreset (reset_controller_internal_rx_digitalreset_serdes_interconect), // rx_digitalreset.interconect .rx_elecidleinfersel_0 (pcie_internal_hip_eidle_infer_sel_0_interconect), // rx_elecidleinfersel_0.interconect .tx_ctrlenable (pipe_interface_internal_txdatak_pcs_interconect), // tx_ctrlenable.interconect .tx_datain (pipe_interface_internal_txdata_pcs_interconect), // tx_datain.interconect .tx_detectrxloop (pipe_interface_internal_txdetectrx_pcs_interconect), // tx_detectrxloop.interconect .tx_forcedispcompliance (pipe_interface_internal_txcompl_pcs_interconect), // tx_forcedispcompliance.interconect .tx_forceelecidle (pipe_interface_internal_txelecidle_pcs_interconect), // tx_forceelecidle.interconect .hip_tx_clkout_0 (altgx_internal_hip_tx_clkout_0_interconect), // hip_tx_clkout_0.interconect .pipedatavalid (altgx_internal_pipedatavalid_interconect), // pipedatavalid.interconect .pipephydonestatus (altgx_internal_pipephydonestatus_interconect), // pipephydonestatus.interconect .pipeelecidle (altgx_internal_pipeelecidle_interconect), // pipeelecidle.interconect .pipestatus (altgx_internal_pipestatus_interconect), // pipestatus.interconect .pll_locked (altgx_internal_pll_locked_interconect), // pll_locked.interconect .rx_ctrldetect (altgx_internal_rx_ctrldetect_interconect), // rx_ctrldetect.interconect .rx_freqlocked (altgx_internal_rx_freqlocked_interconect), // rx_freqlocked.interconect .tx_digitalreset (reset_controller_internal_txdigitalreset_interconect), // tx_digitalreset.interconect .rx_datain_0 (rx_in_rx_datain_0), // rx_in_export.rx_datain_0 .tx_dataout_0 (tx_out_tx_dataout_0) // tx_out_export.tx_dataout_0 ); altera_pcie_hard_ip_reset_controller #( .link_width (1), .cyclone4 (1) ) reset_controller_internal ( .clk250_export (clocks_sim_clk250_export), // reset_controller_export.clk250_export .clk500_export (clocks_sim_clk500_export), // .clk500_export .clk125_export (clocks_sim_clk125_export), // .clk125_export .busy_altgxb_reconfig (reconfig_busy_busy_altgxb_reconfig), // reconfig_busy_export.busy_altgxb_reconfig .pld_clk (pcie_core_clk_clk), // pld_clk.clk .reset_n_out (pcie_core_reset_reset_n), // reset_n_out.reset_n .pcie_rstn (pcie_rstn_export), // pcie_rstn.interconect .refclk (refclk_export), // refclk.interconect .l2_exit (pcie_internal_hip_l2_exit_interconect), // l2_exit.interconect .hotrst_exit (pcie_internal_hip_hotrst_exit_interconect), // hotrst_exit.interconect .dlup_exit (pcie_internal_hip_dlup_exit_interconect), // dlup_exit.interconect .ltssm (pcie_internal_hip_dl_ltssm_int_interconect), // ltssm.interconect .pll_locked (pipe_interface_internal_rc_pll_locked_interconect), // pll_locked.interconect .rx_freqlocked (altgx_internal_rx_freqlocked_interconect), // rx_freqlocked.interconect .test_in (test_in_test_in), // test_in.interconect .srst (reset_controller_internal_srst_interconect), // srst.interconect .crst (reset_controller_internal_crst_interconect), // crst.interconect .rx_digitalreset_serdes (reset_controller_internal_rx_digitalreset_serdes_interconect), // rx_digitalreset_serdes.interconect .txdigitalreset (reset_controller_internal_txdigitalreset_interconect), // txdigitalreset.interconect .rxanalogreset (reset_controller_internal_rxanalogreset_interconect), // rxanalogreset.interconect .clk250_out (reset_controller_internal_clk250_out_interconect), // clk250_out.interconect .clk500_out (reset_controller_internal_clk500_out_interconect), // clk500_out.interconect .rc_inclk_eq_125mhz (1'b1), // (terminated) .rx_pll_locked (1'b0), // (terminated) .rx_signaldetect (1'b0) // (terminated) ); altpcie_pipe_interface #( .max_link_width (1), .gen2_lane_rate_mode ("false"), .p_pcie_hip_type ("2") ) pipe_interface_internal ( .pipe_mode (pipe_ext_pipe_mode), // pipe_interface_export.pipe_mode .phystatus_ext (pipe_ext_phystatus_ext), // .phystatus_ext .rate_ext (pipe_ext_rate_ext), // .rate_ext .powerdown_ext (pipe_ext_powerdown_ext), // .powerdown_ext .txdetectrx_ext (pipe_ext_txdetectrx_ext), // .txdetectrx_ext .rxelecidle0_ext (pipe_ext_rxelecidle0_ext), // .rxelecidle0_ext .rxdata0_ext (pipe_ext_rxdata0_ext), // .rxdata0_ext .rxstatus0_ext (pipe_ext_rxstatus0_ext), // .rxstatus0_ext .rxvalid0_ext (pipe_ext_rxvalid0_ext), // .rxvalid0_ext .rxdatak0_ext (pipe_ext_rxdatak0_ext), // .rxdatak0_ext .txdata0_ext (pipe_ext_txdata0_ext), // .txdata0_ext .txdatak0_ext (pipe_ext_txdatak0_ext), // .txdatak0_ext .rxpolarity0_ext (pipe_ext_rxpolarity0_ext), // .rxpolarity0_ext .txcompl0_ext (pipe_ext_txcompl0_ext), // .txcompl0_ext .txelecidle0_ext (pipe_ext_txelecidle0_ext), // .txelecidle0_ext .pll_powerdown (powerdown_pll_powerdown), // powerdown_export.pll_powerdown .gxb_powerdown (powerdown_gxb_powerdown), // .gxb_powerdown .pll_locked_pcs (altgx_internal_pll_locked_interconect), // pll_locked_pcs.interconect .hip_tx_clkout_pcs (altgx_internal_hip_tx_clkout_0_interconect), // hip_tx_clkout_pcs.interconect .rate_hip (pcie_internal_hip_rate_ext_interconect), // rate_hip.interconect .clk500_out (reset_controller_internal_clk500_out_interconect), // clk500_out.interconect .clk250_out (reset_controller_internal_clk250_out_interconect), // clk250_out.interconect .core_clk_out (pcie_core_clk_clk), // core_clk_out.clk .rc_pll_locked (pipe_interface_internal_rc_pll_locked_interconect), // rc_pll_locked.interconect .gxb_powerdown_pcs (pipe_interface_internal_gxb_powerdown_pcs_interconect), // gxb_powerdown_pcs.interconect .pll_powerdown_pcs (), // pll_powerdown_pcs.interconect .pclk_central_hip (pipe_interface_internal_pclk_central_hip_interconect), // pclk_central_hip.interconect .pclk_ch0_hip (pipe_interface_internal_pclk_ch0_hip_interconect), // pclk_ch0_hip.interconect .rateswitch_pcs (), // rateswitch_pcs.interconect .pll_fixed_clk_hip (pipe_interface_internal_pll_fixed_clk_hip_interconect), // pll_fixed_clk_hip.interconect .pcie_rstn (pcie_rstn_export), // pcie_rstn.interconect .rc_areset (pipe_interface_internal_rc_areset_interconect), // rc_areset.interconect .txdata0_hip (pcie_internal_hip_txdata0_ext_interconect), // txdata0_hip.interconect .txdatak0_hip (pcie_internal_hip_txdatak0_ext_interconect), // txdatak0_hip.interconect .powerdown0_hip (pcie_internal_hip_powerdown0_ext_interconect), // powerdown0_hip.interconect .rxpolarity0_hip (pcie_internal_hip_rxpolarity0_ext_interconect), // rxpolarity0_hip.interconect .txcompl0_hip (pcie_internal_hip_txcompl0_ext_interconect), // txcompl0_hip.interconect .txdetectrx0_hip (pcie_internal_hip_txdetectrx0_ext_interconect), // txdetectrx0_hip.interconect .txelecidle0_hip (pcie_internal_hip_txelecidle0_ext_interconect), // txelecidle0_hip.interconect .rxdata_hip (pipe_interface_internal_rxdata_hip), // rxdata_hip_0.interconect .rxdatak_hip (pipe_interface_internal_rxdatak_hip), // rxdatak_hip_0.interconect .rxstatus_hip (pipe_interface_internal_rxstatus_hip), // rxstatus_hip_0.interconect .powerdown_pcs (pipe_interface_internal_powerdown_pcs_interconect), // powerdown_pcs.interconect .rxdata_pcs (altgx_internal_rx_dataout_interconect), // rxdata_pcs.interconect .phystatus_pcs (altgx_internal_pipephydonestatus_interconect), // phystatus_pcs.interconect .rxelecidle_pcs (altgx_internal_pipeelecidle_interconect), // rxelecidle_pcs.interconect .rxvalid_pcs (altgx_internal_pipedatavalid_interconect), // rxvalid_pcs.interconect .rxdatak_pcs (altgx_internal_rx_ctrldetect_interconect), // rxdatak_pcs.interconect .rxstatus_pcs (altgx_internal_pipestatus_interconect), // rxstatus_pcs.interconect .txdata_pcs (pipe_interface_internal_txdata_pcs_interconect), // txdata_pcs.interconect .rxpolarity_pcs (pipe_interface_internal_rxpolarity_pcs_interconect), // rxpolarity_pcs.interconect .txcompl_pcs (pipe_interface_internal_txcompl_pcs_interconect), // txcompl_pcs.interconect .txdatak_pcs (pipe_interface_internal_txdatak_pcs_interconect), // txdatak_pcs.interconect .txdetectrx_pcs (pipe_interface_internal_txdetectrx_pcs_interconect), // txdetectrx_pcs.interconect .txelecidle_pcs (pipe_interface_internal_txelecidle_pcs_interconect), // txelecidle_pcs.interconect .phystatus_hip (pipe_interface_internal_phystatus_hip), // phystatus_hip_0.interconect .rxelecidle_hip (pipe_interface_internal_rxelecidle_hip), // rxelecidle_hip_0.interconect .rxvalid_hip (pipe_interface_internal_rxvalid_hip), // rxvalid_hip_0.interconect .rateswitchbaseclock_pcs () // rateswitchbaseclock_pcs.interconect ); altera_reset_controller #( .NUM_RESET_INPUTS (1), .OUTPUT_RESET_SYNC_EDGES ("both"), .SYNC_DEPTH (2), .RESET_REQUEST_PRESENT (0) ) rst_controller ( .reset_in0 (~pcie_core_reset_reset_n), // reset_in0.reset .clk (pcie_core_clk_clk), // clk.clk .reset_out (rst_controller_reset_out_reset), // reset_out.reset .reset_req (), // (terminated) .reset_in1 (1'b0), // (terminated) .reset_in2 (1'b0), // (terminated) .reset_in3 (1'b0), // (terminated) .reset_in4 (1'b0), // (terminated) .reset_in5 (1'b0), // (terminated) .reset_in6 (1'b0), // (terminated) .reset_in7 (1'b0), // (terminated) .reset_in8 (1'b0), // (terminated) .reset_in9 (1'b0), // (terminated) .reset_in10 (1'b0), // (terminated) .reset_in11 (1'b0), // (terminated) .reset_in12 (1'b0), // (terminated) .reset_in13 (1'b0), // (terminated) .reset_in14 (1'b0), // (terminated) .reset_in15 (1'b0) // (terminated) ); assign pcie_internal_hip_dl_ltssm_int_interconect = { pcie_internal_hip_dl_ltssm[4:0] }; assign pipe_interface_internal_rxdatak_hip_0_interconect = { pipe_interface_internal_rxdatak_hip[0] }; assign pcie_internal_hip_eidle_infer_sel_0_interconect = { pcie_internal_hip_eidle_infer_sel[2:0] }; assign pipe_interface_internal_rxdata_hip_0_interconect = { pipe_interface_internal_rxdata_hip[7:0] }; assign pipe_interface_internal_rxvalid_hip_0_interconect = { pipe_interface_internal_rxvalid_hip[0] }; assign pipe_interface_internal_rxelecidle_hip_0_interconect = { pipe_interface_internal_rxelecidle_hip[0] }; assign pipe_interface_internal_phystatus_hip_0_interconect = { pipe_interface_internal_phystatus_hip[0] }; assign pipe_interface_internal_rxstatus_hip_0_interconect = { pipe_interface_internal_rxstatus_hip[2:0] }; endmodule
Coq
require 'class' MaxSources=20 NoiseModuleTree=class(function(a,declaration) a.moduletable={} a.libraries={} a.seedablemodules={} if declaration~=nil then a:parseDeclaration(declaration) end end) function NoiseModuleTree:getFunction(name) return self.moduletable[name] end -- Functions to parse module parameters -- Function to verify the existence and type a numeric parameter, with a warning and a default function NoiseModuleTree:verifyNumberWarn(module, name, default) local v=module[name] if v==nil or type(v)~="number" then print("Warning: Parameter "..name.." of module "..module.name.." not correctly specified. Defaulting to "..default) return default end print("Parameter "..name.." of module "..module.name..": "..v) return v end -- Function to verify the existence and type of a numeric parameter, with an error function NoiseModuleTree:verifyNumberError(module,name) local v=module[name] if v==nil or type(v)~="number" then print("Error: Parameter "..name.." of module "..module.name.." not specified.") return false end print("Parameter "..name.." of module "..module.name..": "..v) return v end function NoiseModuleTree:verifyNumber(module,name,default) if default==nil then return self:verifyNumberError(module,name) else return self:verifyNumberWarn(module,name,default) end end -- Function to verify a boolean parameter, with warn and default function NoiseModuleTree:verifyBoolean(module,name,default) local v=module[name] if v~=true and v~=false then print("Warning: Boolean parameter "..name.." of module "..module.name.." not specified. Defaulting to "..tostring(default)) return(default) end print("Parameter "..name.." of module "..module.name..": "..tostring(v)) return v end -- Function to verify a string parameter function NoiseModuleTree:verifyStringError(module, name) local v=module[name] if v==nil or type(v)~="string" then print("Error: String parameter "..name.." of module "..module.name.." not specified.") return false end print("Parameter "..name.." of module "..module.name..": "..v) return v end function NoiseModuleTree:verifyStringWarn(module,name,default) local v=module[name] if v==nil or type(v)~="string" then print("Warning: String parameter "..name.." of module "..module.name.." not specified. Defaulting to "..default) return default end print("Parameter "..name.." of module "..module.name..": "..v) return v end function NoiseModuleTree:verifyString(module,name,default) if default==nil then return self:verifyStringError(module,name) else return self:verifyStringWarn(module,name,default) end end function NoiseModuleTree:verifyScalarParameter(module,name) local v=module[name] if v==nil then print("ScalarParameter "..name.." not specified, defaulting to built-in default.") return nil end if type(v)=='number' then return v end if type(v)=='string' then local m=self.moduletable[v] if m==nil then print("Error: module "..v.." (set as scalar parameter) does not exist.") return nil end return m end print("ScalarParameter "..name.." not specified, defaulting to built-in default.") return nil end function NoiseModuleTree:verifyRGBAParameter(module,name) local v=module[name] if v==nil then print("RGBAParameter "..name.." not specified, defaulting to built-in default.") return nil end if type(v)=='table' then if v[1]==nil or v[2]==nil or v[3]==nil or v[4]==nil then print("Warning: RGBA constant in RGBAParameter "..name.." malformed; defaulting to built-in default.") return nil end return v end if type(v)=='string' then local m=self.moduletable[v] if m==nil then print("Warning: module "..v.." set as RGBAParameter does not exist.") return nil end return m end print("RGBAParameter "..name.." not specified. Defaulting to built-in default.") return nil end -- Function to verify a source module function NoiseModuleTree:verifyModuleError(module, name) local v=module[name] if v==nil or type(v)~="string" then print("Error: Module parameter "..name.." of module "..module.name.." not specified.") return false end local m=self.moduletable[v] if m==nil then print("Error: Module parameter "..v.." specified for module "..module.name.." does not exist.") return false end print("Parameter "..name.." of module "..module.name..": "..v) return m end function NoiseModuleTree:verifyModule(module, name) local v=module[name] if v==nil then return nil end local m=self.moduletable[v] return m end function NoiseModuleTree:parseDeclaration(declaration) local i for i=1,#declaration,1 do if self:parseModule(declaration[i])==false then -- Error condition print("Aborting") return end end print("Declaration parsed. "..(#declaration).." modules.") end function NoiseModuleTree:setSeedFunction(name,seed) local f=self:getFunction(name) if f then f:setSeed(seed) end end function NoiseModuleTree:setSeedAll(startseed) local i,j local k=0 for i,j in pairs(self.moduletable) do print("Seeding "..i) j:setSeed(startseed+k*10) k=k+1 end end function NoiseModuleTree:parseModule(module) if module==nil then print("Error: nil module table passed to parseModule") return false end -- Check name if module.name==nil then print("Error: module name not specified") return false end if self.moduletable[module.name] ~= nil then print("Error: Module "..module.name.." already exists.") return false end -- Check type if module.type==nil then print("Error: module type not specified.") return false end -- The name of the module type directly references the name of a function to parse the module if self[module.type]==nil then print("Error: module type "..module.type.." unsupported.") return false end return self[module.type](self,module) end function NoiseModuleTree:gatherMultipleSources(module,func) -- Parse the source_n entries of module, check and obtain the modules and set the sources for i=0,MaxSources-1,1 do local s="source_"..i if module[s]~=nil then if self.moduletable[module[s]]==nil then print("Error: Module "..module[s].." specified as source to module "..module.name.." does not exist.") return false end if module[s]==module.name then print("Error: Module "..module.name.." specified as source for itself; will result in infinite loop condition.") return false end func:setSource(i,self.moduletable[module[s]]) print("Module "..module[s].."set as source "..i.." of module "..module.name) end end end function NoiseModuleTree:gatherMultipleSourcesFractal(module,func) -- Parse the source_n entries of module, check and obtain the modules and set the sources for i=0,MaxSources-1,1 do local s="source_"..i if module[s]~=nil then if self.moduletable[module[s]]==nil then print("Error: Module "..module[s].." specified as source to module "..module.name.." does not exist.") return false end if module[s]==module.name then print("Error: Module "..module.name.." specified as source for itself; will result in infinite loop condition.") return false end func:overrideSource(i,self.moduletable[module[s]]) print("Module "..module[s].."set as source "..i.." of module "..module.name) end end end -- Module parsers -- Library function function NoiseModuleTree:library(module) -- Library loads a file specified by a path. The file is loaded line by line, and each line is parsed using parseModule() local pathname=self:verifyStringError(module, "path") if pathname==nil then return nil end -- Load the file given by path/name local infile=io.open(pathname..module.libraryname..".lua") if infile==nil then print("Error: Library file "..pathname..module.libraryname.." does not exist.") return nil end local l local lib=NoiseModuleTree() for l in infile:lines() do local t=table.load(l) --self:parseModule(t) if lib:parseModule(t)==nil then print("Error: Malformed module declaration in library "..pathname..module.libraryname) infile:close() return nil end end infile:close() self.libraries[module.libraryname]=lib self.moduletable[module.name]=lib:getFunction(module.libraryname) end -- AutoCorrect function NoiseModuleTree:autocorrect(module) -- Parameters: -- source: module -- low,high: double local source=self:verifyModuleError(module,"source") if source==false then return nil end local low=self:verifyNumber(module, "low", -1.0) local high=self:verifyNumber(module, "high", 1.0) local f=anl.CImplicitAutoCorrect() f:setRange(low,high) f:setSource(source) self.moduletable[module.name]=f return true end -- BasisFunction function NoiseModuleTree:basisfunction(module) -- Parameters -- basis, interp: int local basis=self:verifyNumber(module,"basis",anl.GRADIENT) local interp=self:verifyNumber(module,"interp",anl.QUINTIC) local f=anl.CImplicitBasisFunction(basis,interp) self.moduletable[module.name]=f return true end -- Bias function NoiseModuleTree:bias(module) -- Parameters: -- source: scalarparameter -- bias: scalarparameter local source=self:verifyScalarParameter(module,"source") local bias=self:verifyScalarParameter(module,"bias") local f=anl.CImplicitBias(0) if source then f:setSource(source) end if bias then f:setBias(bias) end self.moduletable[module.name]=f return true end -- Blend function NoiseModuleTree:blend(module) -- Parameters: -- source,low,high: scalarparameters local source=self:verifyScalarParameter(module,"control") local low=self:verifyScalarParameter(module,"low") local high=self:verifyScalarParameter(module,"high") local f=anl.CImplicitBlend() if source then f:setControlSource(source) end if low then f:setLowSource(low) end if high then f:setHighSource(high) end self.moduletable[module.name]=f return true end -- BrightContrast function NoiseModuleTree:brightcontrast(module) -- Parameters -- source, bright, threshold, factor: scalarparameters local source=self:verifyScalarParameter(module,"source") local bright=self:verifyScalarParameter(module,"brightness") local threshold=self:verifyScalarParameter(module,"contrast_threshold") local factor=self:verifyScalarParameter(module, "contrast_factor") local f=anl.CImplicitBrightContrast() if source then f:setSource(source) end if bright then f:setBrightness(bright) end if threshold then f:setContrastThreshold(threshold) end if factor then f:setContrastFactor(factor) end self.moduletable[module.name]=f return true end -- Cache function NoiseModuleTree:cache(module) -- Parameters -- source: module local source=self:verifyModuleError(module,"source") if source==nil then return false end local f=anl.CImplicitCache() f:setSource(source) self.moduletable[module.name]=f return true end -- Cellular generator. Not really a module, per se... function NoiseModuleTree:cellulargenerator(module) -- Parameters -- seed (optional): int local f=anl.CCellularGenerator() self.moduletable[module.name]=f if module.seed then f:setSeed(module.seed) end return true end -- Cellular function NoiseModuleTree:cellular(module) -- Parameters -- f1,f2,f3,f4: Coefficients -- source: CellularGenerator local source=self:verifyModuleError(module,"source") if source==nil then return false end local f1,f2,f3,f4=self:verifyNumber(module,"f1",0.0), self:verifyNumber(module,"f2",0.0), self:verifyNumber(module,"f3",0.0), self:verifyNumber(module,"f4",0.0) local f=anl.CImplicitCellular() f:setSource(source) f:setCoefficients(f1,f2,f3,f4) self.moduletable[module.name]=f return true end -- Clamp function NoiseModuleTree:clamp(module) -- Parameters -- source: module -- low,high: number local source=self:verifyModuleError(module,"source") if source==nil then return false end local low=self:verifyNumber(module,"low",-1.0) local high=self:verifyNumber(module,"high",1.0) local f=anl.CImplicitClamp(low,high) f:setSource(source) self.moduletable[module.name]=f return true end -- Combiner function NoiseModuleTree:combiner(module) local type=self:verifyNumber(module,"operation", anl.ADD) self.moduletable[module.name]=anl.CImplicitCombiner(type) self:gatherMultipleSources(module,self.moduletable[module.name]) print("Module "..module.name.."(combiner,"..type..") created.") return true end -- Constant function NoiseModuleTree:constant(module) local constant=self:verifyNumber(module,"constant",1.0) self.moduletable[module.name]=anl.CImplicitConstant(constant) print("Module "..module.name.."(constant,"..constant..") created.") return true end -- Cos function NoiseModuleTree:cos(module) local source=self:verifyScalarParameter(module, "source") local f=anl.CImplicitCos() if source then f:setSource(source) end self.moduletable[module.name]=f return true end -- Floor function NoiseModuleTree:floor(module) local source=self:verifyScalarParameter(module, "source") local f=anl.CImplicitFloor() if source then f:setSource(source) end self.moduletable[module.name]=f return true end -- RGBAExtractChannel function NoiseModuleTree:extractchannel(module) -- Parameters -- source: RGBAParameter -- channel: int local source=self:verifyRGBAParameter(module,"source") local channel=self:verifyNumber(module,"channel",anl.RED) local f=anl.CImplicitExtractRGBAChannel() f:setChannel(channel) if source~=nil and type(source)=='table' then f:setSource(source[1],source[2],source[3],source[4]) else f:setSource(source) end self.moduletable[module.name]=f return true end -- Fractal function NoiseModuleTree:fractal(module) local type=self:verifyNumber(module,"fractaltype",anl.FBM) local basis=self:verifyNumber(module,"basistype",anl.GRADIENT) local interp=self:verifyNumber(module,"interptype",anl.QUINTIC) local octaves=self:verifyNumber(module,"octaves", 8) local freq=self:verifyNumber(module,"frequency",1.0) -- TODO: Implement setters for Lacunarity, Offset, Gain, H local f=anl.CImplicitFractal(type,basis,interp) f:setNumOctaves(octaves) f:setFrequency(freq) -- Specify any overrides print("Module "..module.name..": Check for octave overrides...") self:gatherMultipleSourcesFractal(module,f) if module.seed then f:setSeed(module.seed) end self.moduletable[module.name]=f print("Module "..module.name.."(fractal) created.") return true end -- FunctionGradient function NoiseModuleTree:functiongradient(module) local source=self:verifyScalarParameter(module,"source") local axis=self:verifyNumber(module,"axis",anl.X_AXIS) local spacing=self:verifyNumber(module,"spacing",0.01) local f=anl.CImplicitFunctionGradient() if source then f:setSource(source) end f:setAxis(axis) f:setSpacing(spacing) self.moduletable[module.name]=f return true end -- Gain function NoiseModuleTree:gain(module) -- Parameters: -- source: scalarparameter -- bias: scalarparameter local source=self:verifyScalarParameter(module,"source") local bias=self:verifyScalarParameter(module,"gain") if bias==nil then bias=0 end local f=anl.CImplicitGain(0) if bias then f:setGain(bias) end if source then f:setSource(source) end self.moduletable[module.name]=f return true end -- Gradient function NoiseModuleTree:gradient(module) local x1,y1,z1,w1,u1,v1, x2,y2,z2,w2,u2,v2=0,0,0,0,0,0,0,0,0,0,0,0 if module.x1~=nil then x1=module.x1 end if module.x2~=nil then x2=module.x2 end if module.y1~=nil then y1=module.y1 end if module.y2~=nil then y2=module.y2 end if module.z1~=nil then z1=module.z1 end if module.z2~=nil then z2=module.z2 end if module.w1~=nil then w1=module.w1 end if module.w2~=nil then w2=module.w2 end if module.u1~=nil then u1=module.u1 end if module.u2~=nil then u2=module.u2 end if module.v1~=nil then v1=module.v1 end if module.v2~=nil then v2=module.v2 end self.moduletable[module.name]=anl.CImplicitGradient() self.moduletable[module.name]:setGradient(x1,x2,y1,y2,z1,z2,w1,w2,u1,u2,v1,v2) print("Module "..module.name.."(gradient) created.") return true end -- RGBADotProduct function NoiseModuleTree:rgbadotproduct(module) local s1=self:verifyRGBAParameter(module,"source1") local s2=self:verifyRGBAParameter(module,"source2") local f=anl.CImplicitRGBADotProduct() if s1 then if type(s1)=='table' then f:setSource1(s1[1],s1[2],s1[3],s1[4]) else f:setSource1(s1) end end if s2 then if type(s2)=='table' then f:setSource2(s2[1], s2[2], s2[3], s2[4]) else f:setSource2(s2) end end self.moduletable[module.name]=f return true end -- RotateDomain function NoiseModuleTree:rotatedomain(module) -- Parameters -- ax,ay,az,angle: scalarparameters -- source: scalarparameter local ax=self:verifyScalarParameter(module,"ax") local ay=self:verifyScalarParameter(module,"ay") local az=self:verifyScalarParameter(module,"az") local angle=self:verifyScalarParameter(module,"angle") local source=self:verifyModuleError(module,"source") if source==nil then return false end local f=anl.CImplicitRotateDomain(0,0,0,0) if ax then f:setAxisX(ax) end if ay then f:setAxisY(ay) end if az then f:setAxisZ(az) end if angle then f:setAngle(angle) end f:setSource(source) self.moduletable[module.name]=f return true end -- ScaleDomain function NoiseModuleTree:scaledomain(module) -- Parameters -- scalex,scaley,scalez,scalew,scaleu,scalev: scalarparameters -- source: module local source=self:verifyModuleError(module,"source") if source==nil then return false end local scalex=self:verifyScalarParameter(module,"scalex") local scaley=self:verifyScalarParameter(module,"scaley") local scalez=self:verifyScalarParameter(module,"scalez") local scalew=self:verifyScalarParameter(module,"scalew") local scaleu=self:verifyScalarParameter(module,"scaleu") local scalev=self:verifyScalarParameter(module,"scalev") local f=anl.CImplicitScaleDomain() f:setSource(source) if scalex then f:setXScale(scalex) end if scaley then f:setYScale(scaley) end if scalez then f:setZScale(scalez) end if scalew then f:setWScale(scalew) end if scaleu then f:setUScale(scaleu) end if scalev then f:setVScale(scalev) end self.moduletable[module.name]=f return true end -- ScaleOffset function NoiseModuleTree:scaleoffset(module) -- Parameters -- source: module -- scale,offset: scalarparameters local source=self:verifyModuleError(module,"source") if source==nil then return false end local scale=self:verifyScalarParameter(module,"scale") local offset=self:verifyScalarParameter(module,"offset") local f=anl.CImplicitScaleOffset(1,0) f:setSource(source) if scale then f:setScale(scale) end if offset then f:setOffset(offset) end self.moduletable[module.name]=f return true end -- Select function NoiseModuleTree:select(module) -- Parameters -- low,high,control,threshold,falloff: scalar parameters local low=self:verifyScalarParameter(module,"low") local high=self:verifyScalarParameter(module,"high") local control=self:verifyScalarParameter(module,"control") local threshold=self:verifyScalarParameter(module,"threshold") local falloff=self:verifyScalarParameter(module,"falloff") local f=anl.CImplicitSelect() if low then f:setLowSource(low) end if high then f:setHighSource(high) end if control then f:setControlSource(control) end if threshold then f:setThreshold(threshold) end if falloff then f:setFalloff(falloff) end self.moduletable[module.name]=f return true end function NoiseModuleTree:sin(module) local source=self:verifyScalarParameter(module,"source") local f=anl.CImplicitSin() if source then f:setSource(source) end self.moduletable[module.name]=f return true end -- Sphere function NoiseModuleTree:sphere(module) -- Parameters -- cx,cy,cz,cw,cu,cv,radius: scalarparameter local cx=self:verifyScalarParameter(module,"cx") local cy=self:verifyScalarParameter(module,"cy") local cz=self:verifyScalarParameter(module,"cz") local cw=self:verifyScalarParameter(module,"cw") local cu=self:verifyScalarParameter(module,"cu") local cv=self:verifyScalarParameter(module,"cv") local radius=self:verifyScalarParameter(module,"radius") local f=anl.CImplicitSphere() if cx then f:setCenterX(cx) end if cy then f:setCenterY(cy) end if cz then f:setCenterZ(cz) end if cw then f:setCenterW(cw) end if cu then f:setCenterU(cu) end if cv then f:setCenterV(cv) end if radius then f:setRadius(radius) end self.moduletable[module.name]=f return true end -- Sqrt function NoiseModuleTree:pow(module) local source=self:verifyScalarParameter(module,"source") local power=self:verifyScalarParameter(module,"power") local f=anl.CImplicitPow() if source then f:setSource(source) end if power then f:setPower(power) end self.moduletable[module.name]=f return true end -- Tiers function NoiseModuleTree:tiers(module) local source=self:verifyScalarParameter(module,"source") local numtiers=self:verifyNumber(module,"tiers",2) local smooth=self:verifyBoolean(module,"smooth", true) local f=anl.CImplicitTiers(numtiers, smooth) if source then f:setSource(source) end self.moduletable[module.name]=f return true end -- TranslateDomain function NoiseModuleTree:translatedomain(module) -- Parameters -- tx,ty,tz,tw,tu,tv: scalarparameter local tx=self:verifyScalarParameter(module,"tx") local ty=self:verifyScalarParameter(module,"ty") local tz=self:verifyScalarParameter(module,"tz") local tw=self:verifyScalarParameter(module,"tw") local tu=self:verifyScalarParameter(module,"tu") local tv=self:verifyScalarParameter(module,"tv") local source=self:verifyScalarParameter(module,"source") local f=anl.CImplicitTranslateDomain() if tx then f:setXAxisSource(tx) end if ty then f:setYAxisSource(ty) end if tz then f:setZAxisSource(tz) end if tw then f:setWAxisSource(tw) end if tu then f:setUAxisSource(tu) end if tv then f:setVAxisSource(tv) end if source then f:setSource(source) end self.moduletable[module.name]=f return true end -- RGBA Modules -- Blend function NoiseModuleTree:rgba_blend(module) -- Parameters -- low,high: RGBAParameter -- control: scalarparamter local low=self:verifyRGBAParameter(module,"low") local high=self:verifyRGBAParameter(module,"high") local control=self:verifyScalarParamter(module,"control") local f=anl.CRGBABlend() if low then if type(low)=='table' then f:setLowSource(low[1],low[2],low[3],low[4]) else f:setLowSource(low) end end if high then if type(high)=='table' then f:setHighSource(high[1],high[2],high[3],high[4]) else f:setHighSource(high) end end if control then f:setControlSource(control) end self.moduletable[module.name]=f return true end -- BlendOps function NoiseModuleTree:rgba_blendops(module) -- Parameters -- source1,source2: RGBAParameter -- blend1,blend2: int local source1=self:verifyRGBAParameter(module,"source1") local source2=self:verifyRGBAParameter(module,"source2") local blend1=self:verifyNumber(module,"blend1",anl.SRC1_ALPHA) local blend2=self:verifyNumber(module,"blend2",anl.ONE_MINUS_SRC1_ALPHA) local f=anl.CRGBABlendOps() if source1 then if type(source1)=='table' then f:setSource1(source1[1], source1[2], source1[3], source1[4]) else f:setSource1(source1) end end if source2 then if type(source2)=='table' then f:setSource2(source2[1],source2[2],source2[3],source2[4]) else f:setSource2(source2) end end f:setSrc1Mode(blend1) f:setSrc2Mode(blend2) self.moduletable[module.name]=f return true end -- ComposeChannels function NoiseModuleTree:rgba_composechannels(module) -- Parameters -- mode: int -- r,g,b,a,h,s,v: scalarparamter local mode=self:verifyNumber(module,"mode",anl.RGB) local r,g,b,a if mode==anl.HSV then r=self:verifyScalarParameter(module,"hue") g=self:verifyScalarParameter(module,"sat") b=self:verifyScalarParameter(module,"val") else r=self:verifyScalarParameter(module,"red") g=self:verifyScalarParameter(module,"green") b=self:verifyScalarParameter(module,"blue") end local a=self:verifyScalarParameter(module,"alpha") local f=anl.CRGBACompositeChannels() if r then f:setRedSource(r) end if g then f:setGreenSource(g) end if b then f:setBlueSource(b) end if a then f:setAlphaSource(a) end f:setMode(mode) self.moduletable[module.name]=f return true end -- HSVtoRGBA function NoiseModuleTree:rgba_hsvtorgba(module) -- Parameters -- source: RGBAParameter local source=self:verifyRGBAParameter(module,"source") local f=anl.CRGBAHSVToRGBA() if source then if type(source)=='table' then f:setSource(source[1],source[2],source[3],source[4]) else f:setSource(source) end end self.moduletable[module.name]=f return true end -- ImplicitGrayscale function NoiseModuleTree:rgba_implicitgrayscale(module) -- Parameters -- source:scalarparameter local source=self:verifyScalarParameter(module,"source") local f=anl.CRGBAImplicitGrayscale() if source then f:setSource(source) end self.moduletable[module.name]=f return true end -- Normalize function NoiseModuleTree:rgba_normalize(module) local s=self:verifyRGBAParameter(module,"source") local f=anl.CRGBANormalize() if s then if type(s)=='table' then f:setSource(s[1],s[2],s[3],s[4]) else f:setSource(s) end end self.moduletable[module.name]=f return true end -- RGBAtoHSV function NoiseModuleTree:rgba_rgbatohsv(module) -- Paramters -- source: RGBAParamter local s = self:verifyRGBAParameter(module,"source") local f=anl.CRGBARGBAToHSV() if s then if type(s)=='table' then f:setSource(s[1],s[2],s[3],s[4]) else f:setSource(s) end end self.moduletable[module.name]=f return true end -- RotateColor function NoiseModuleTree:rgba_rotatecolor(module) -- Parameters -- ax,ay,az,angle: scalarparamter -- source: rgbaparameter local ax=self:verifyScalarParameter(module,"ax") local ay=self:verifyScalarParameter(module,"ay") local az=self:verifyScalarParameter(module,"az") local angle=self:verifyScalarParameter(module,"angle") local s = self:verifyRGBAParameter(module,"source") local f=anl.CRGBARotateColor() if ax then f:setAxisX(ax) end if ay then f:setAxisY(ay) end if az then f:setAxisZ(az) end if angle then f:setAngle(angle) end if s then if type(s)=='table' then f:setSource(s[1],s[2],s[3],s[4]) else f:setSource(s) end end self.moduletable[module.name]=f return true end -- Select function NoiseModuleTree:rgba_select(module) -- Parameters -- control,falloff,threshold: scalar -- low,high: rgbaparam local low=self:verifyRGBAParameter(module,"low") local high=self:verifyRGBAParamter(module,"high") local control=self:verifyScalarParameter(module,"control") local threshold=self:verifyScalarParameter(module,"threshold") local falloff=self:verifyScalarParameter(module,"falloff") local f=anl.CRGBASelect() if low then if type(low)=='table' then f:setLowSource(low[1],low[2],low[3],low[4]) else f:setLowSource(low) end end if high then if type(high)=='table' then f:setHighSource(high[1],high[2],high[3],high[4]) else f:setHighSource(high) end end if control then f:setControlSource(control) end if threshold then f:setThreshold(threshold) end if falloff then f:setFalloff(falloff) end self.moduletable[module.name]=f return true end
Lua
(**************************************************************************) (* *) (* This file is part of Frama-C. *) (* *) (* Copyright (C) 2007-2019 *) (* CEA (Commissariat à l'énergie atomique et aux énergies *) (* alternatives) *) (* *) (* 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, version 2.1. *) (* *) (* It 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. *) (* *) (* See the GNU Lesser General Public License version 2.1 *) (* for more details (enclosed in the file licenses/LGPLv2.1). *) (* *) (**************************************************************************) (** Database in which static plugins are registered. @plugin development guide *) (** Modules providing general services: - {!Dynamic}: API for plug-ins linked dynamically - {!Journal}: journalisation - {!Log}: message outputs and printers - {!Plugin}: general services for plug-ins - {!Project} and associated files: {!Kind}, {!Datatype} and {!State_builder}. Other main kernel modules: - {!Ast}: the cil AST - {!Ast_info}: syntactic value directly computed from the Cil Ast - {!File}: Cil file initialization - {!Globals}: global variables, functions and annotations - {!Annotations}: annotations associated with a statement - {!Properties_status}: status of annotations - {!Kernel_function}: C functions as seen by Frama-C - {!Stmts_graph}: the statement graph - {!Loop}: (natural) loops - {!Visitor}: frama-c visitors - {!Kernel}: general parameters of Frama-C (mostly set from the command line) *) open Cil_types open Cil_datatype (* ************************************************************************* *) (** {2 Registering} *) (* ************************************************************************* *) (** How to journalize the given function. @since Beryllium-20090601-beta1 *) type 'a how_to_journalize = | Journalize of string * 'a Type.t (** Journalize the value with the given name and type. *) | Journalization_not_required (** Journalization of this value is not required (usually because it has no effect on the Frama-C global state). *) | Journalization_must_not_happen of string (** Journalization of this value should not happen (usually because it is a low-level function: this function is always called from a journalized function). The string is the function name which is used for displaying suitable error message. *) val register: 'a how_to_journalize -> 'a ref -> 'a -> unit (** Plugins must register values with this function. *) val register_compute: string -> State.t list -> (unit -> unit) ref -> (unit -> unit) -> State.t (** @modify Boron-20100401 now return the state of the computation. *) val register_guarded_compute: string -> (unit -> bool) -> (unit -> unit) ref -> (unit -> unit) -> unit (** Frama-C main interface. @since Lithium-20081201 @plugin development guide *) module Main: sig val extend : (unit -> unit) -> unit (** Register a function to be called by the Frama-C main entry point. @plugin development guide *) val play: (unit -> unit) ref (** Run all the Frama-C analyses. This function should be called only by toplevels. @since Beryllium-20090901 *) (**/**) val apply: unit -> unit (** Not for casual user. *) (**/**) end module Toplevel: sig val run: ((unit -> unit) -> unit) ref (** Run a Frama-C toplevel playing the game given in argument (in particular, applying the argument runs the analyses). @since Beryllium-20090901 *) end (* ************************************************************************* *) (** {2 Values} *) (* ************************************************************************* *) (** The Value analysis itself. @see <../value/index.html> internal documentation. *) module Value : sig type state = Cvalue.Model.t (** Internal state of the value analysis. *) type t = Cvalue.V.t (** Internal representation of a value. *) exception Aborted val emitter: Emitter.t ref (** Emitter used by Value to emit statuses *) val self : State.t (** Internal state of the value analysis from projects viewpoint. @plugin development guide *) val mark_as_computed: unit -> unit (** Indicate that the value analysis has been done already. *) val compute : (unit -> unit) ref (** Compute the value analysis using the entry point of the current project. You may set it with {!Globals.set_entry_point}. @raise Globals.No_such_entry_point if the entry point is incorrect @raise Db.Value.Incorrect_number_of_arguments if some arguments are specified for the entry point using {!Db.Value.fun_set_args}, and an incorrect number of them is given. @plugin development guide *) val is_computed: unit -> bool (** Return [true] iff the value analysis has been done. @plugin development guide *) module Table_By_Callstack: State_builder.Hashtbl with type key = stmt and type data = state Value_types.Callstack.Hashtbl.t (** Table containing the results of the value analysis, ie. the state before the evaluation of each reachable statement. *) module AfterTable_By_Callstack: State_builder.Hashtbl with type key = stmt and type data = state Value_types.Callstack.Hashtbl.t (** Table containing the state of the value analysis after the evaluation of each reachable and evaluable statement. Filled only if [Value_parameters.ResultsAfter] is set. *) val ignored_recursive_call: kernel_function -> bool (** This functions returns true if the value analysis found and ignored a recursive call to this function during the analysis. *) val condition_truth_value: stmt -> bool * bool (** Provided [stmt] is an 'if' construct, [fst (condition_truth_value stmt)] (resp. snd) is true if and only if the condition of the 'if' has been evaluated to true (resp. false) at least once during the analysis. *) (** {3 Parameterization} *) exception Outside_builtin_possibilities (** Type for a Value builtin function *) type builtin_sig = (** Memory state at the beginning of the function *) state -> (** Args for the function: the expressions corresponding to the formals of the functions at the call site, the actual value of those formals, and a more precise view of those formals using offsetmaps (for eg. structs) *) (Cil_types.exp * Cvalue.V.t * Cvalue.V_Offsetmap.t) list -> Value_types.call_result val register_builtin: (string -> ?replace:string -> builtin_sig -> unit) ref (** [!register_builtin name ?replace f] registers an abstract function [f] to use everytime a C function named [name] is called in the program. If [replace] is supplied and option [-val-builtins-auto] is active, calls to [replace] will also be substituted by the builtin. See also option [-val-builtin] *) val registered_builtins: (unit -> (string * builtin_sig) list) ref (** Returns a list of the pairs (name, builtin_sig) registered via [register_builtin]. @since Aluminium-20160501 *) val mem_builtin: (string -> bool) ref (** returns whether there is an abstract function registered by {!register_builtin} with the given name. *) val use_spec_instead_of_definition: (kernel_function -> bool) ref (** To be called by derived analyses to determine if they must use the body of the function (if available), or only its spec. Used for value builtins, and option -val-use-spec. *) (** {4 Arguments of the main function} *) (** The functions below are related to the arguments that are passed to the function that is analysed by the value analysis. Specific arguments are set by [fun_set_args]. Arguments reset to default values when [fun_use_default_args] is called, when the ast is changed, or if the options [-libentry] or [-main] are changed. *) (** Specify the arguments to use. This function is not journalized, and will generate an error when the journal is replayed *) val fun_set_args : t list -> unit val fun_use_default_args : unit -> unit (** For this function, the result [None] means that default values are used for the arguments. *) val fun_get_args : unit -> t list option exception Incorrect_number_of_arguments (** Raised by [Db.Compute] when the arguments set by [fun_set_args] are not coherent with the prototype of the function (if there are too few or too many of them) *) (** {4 Initial state of the analysis} *) (** The functions below are related to the value of the global variables when the value analysis is started. If [globals_set_initial_state] has not been called, the given state is used. A default state (which depends on the option [-libentry]) is used when [globals_use_default_initial_state] is called, or when the ast changes. *) (** Specify the initial state to use. This function is not journalized, and will generate an error when the journal is replayed *) val globals_set_initial_state : state -> unit val globals_use_default_initial_state : unit -> unit (** Initial state used by the analysis *) val globals_state : unit -> state (** @return [true] if the initial state for globals used by the value analysis has been supplied by the user (through [globals_set_initial_state]), or [false] if it is automatically computed by the value analysis *) val globals_use_supplied_state : unit -> bool (** {3 Getters} *) (** State of the analysis at various points *) val get_initial_state : kernel_function -> state val get_initial_state_callstack : kernel_function -> state Value_types.Callstack.Hashtbl.t option val get_state : ?after:bool -> kinstr -> state (** [after] is false by default. *) val get_stmt_state_callstack: after:bool -> stmt -> state Value_types.Callstack.Hashtbl.t option val get_stmt_state : ?after:bool -> stmt -> state (** [after] is false by default. @plugin development guide *) val fold_stmt_state_callstack : (state -> 'a -> 'a) -> 'a -> after:bool -> stmt -> 'a val fold_state_callstack : (state -> 'a -> 'a) -> 'a -> after:bool -> kinstr -> 'a val find : state -> Locations.location -> t (** {3 Evaluations} *) val eval_lval : (?with_alarms:CilE.warn_mode -> Locations.Zone.t option -> state -> lval -> Locations.Zone.t option * t) ref val eval_expr : (?with_alarms:CilE.warn_mode -> state -> exp -> t) ref val eval_expr_with_state : (?with_alarms:CilE.warn_mode -> state -> exp -> state * t) ref val reduce_by_cond: (state -> exp -> bool -> state) ref val find_lv_plus : (Cvalue.Model.t -> Cil_types.exp -> (Cil_types.lval * Ival.t) list) ref (** returns the list of all decompositions of [expr] into the sum an lvalue and an interval. *) (** {3 Values and kernel functions} *) val expr_to_kernel_function : (kinstr -> ?with_alarms:CilE.warn_mode -> deps:Locations.Zone.t option -> exp -> Locations.Zone.t * Kernel_function.Hptset.t) ref val expr_to_kernel_function_state : (state -> deps:Locations.Zone.t option -> exp -> Locations.Zone.t * Kernel_function.Hptset.t) ref exception Not_a_call val call_to_kernel_function : stmt -> Kernel_function.Hptset.t (** Return the functions that can be called from this call. @raise Not_a_call if the statement is not a call. *) val valid_behaviors: (kernel_function -> state -> funbehavior list) ref val add_formals_to_state: (state -> kernel_function -> exp list -> state) ref (** [add_formals_to_state state kf exps] evaluates [exps] in [state] and binds them to the formal arguments of [kf] in the resulting state *) (** {3 Reachability} *) val is_accessible : kinstr -> bool val is_reachable : state -> bool (** @plugin development guide *) val is_reachable_stmt : stmt -> bool (** {3 About kernel functions} *) exception Void_Function val find_return_loc : kernel_function -> Locations.location (** Return the location of the returned lvalue of the given function. @raise Void_Function if the function does not return any value. *) val is_called: (kernel_function -> bool) ref val callers: (kernel_function -> (kernel_function*stmt list) list) ref (** @return the list of callers with their call sites. Each function is present only once in the list. *) (** {3 State before a kinstr} *) val access : (kinstr -> lval -> t) ref val access_expr : (kinstr -> exp -> t) ref val access_location : (kinstr -> Locations.location -> t) ref (** {3 Locations of left values} *) val lval_to_loc : (kinstr -> ?with_alarms:CilE.warn_mode -> lval -> Locations.location) ref val lval_to_loc_with_deps : (kinstr -> ?with_alarms:CilE.warn_mode -> deps:Locations.Zone.t -> lval -> Locations.Zone.t * Locations.location) ref val lval_to_loc_with_deps_state : (state -> deps:Locations.Zone.t -> lval -> Locations.Zone.t * Locations.location) ref val lval_to_loc_state : (state -> lval -> Locations.location) ref val lval_to_offsetmap : ( kinstr -> ?with_alarms:CilE.warn_mode -> lval -> Cvalue.V_Offsetmap.t option) ref val lval_to_offsetmap_state : (state -> lval -> Cvalue.V_Offsetmap.t option) ref (** @since Carbon-20110201 *) val lval_to_zone : (kinstr -> ?with_alarms:CilE.warn_mode -> lval -> Locations.Zone.t) ref val lval_to_zone_state : (state -> lval -> Locations.Zone.t) ref (** Does not emit alarms. *) val lval_to_zone_with_deps_state: (state -> for_writing:bool -> deps:Locations.Zone.t option -> lval -> Locations.Zone.t * Locations.Zone.t * bool) ref (** [lval_to_zone_with_deps_state state ~for_writing ~deps lv] computes [res_deps, zone_lv, exact], where [res_deps] are the memory zones needed to evaluate [lv] in [state] joined with [deps]. [zone_lv] contains the valid memory zones that correspond to the location that [lv] evaluates to in [state]. If [for_writing] is true, [zone_lv] is restricted to memory zones that are writable. [exact] indicates that [lv] evaluates to a valid location of cardinal at most one. *) val lval_to_precise_loc_state: (?with_alarms:CilE.warn_mode -> state -> lval -> state * Precise_locs.precise_location * typ) ref val lval_to_precise_loc_with_deps_state: (state -> deps:Locations.Zone.t option -> lval -> Locations.Zone.t * Precise_locs.precise_location) ref (** Evaluation of the [\from] clause of an [assigns] clause.*) val assigns_inputs_to_zone : (state -> assigns -> Locations.Zone.t) ref (** Evaluation of the left part of [assigns] clause (without [\from]).*) val assigns_outputs_to_zone : (state -> result:varinfo option -> assigns -> Locations.Zone.t) ref (** Evaluation of the left part of [assigns] clause (without [\from]). Each assigns term results in one location. *) val assigns_outputs_to_locations : (state -> result:varinfo option -> assigns -> Locations.location list) ref (** For internal use only. Evaluate the [assigns] clause of the given function in the given prestate, compare it with the computed froms, return warning and set statuses. *) val verify_assigns_froms : (Kernel_function.t -> pre:state -> Function_Froms.t -> unit) ref (** {3 Evaluation of logic terms and predicates} *) module Logic : sig (** The APIs of this module are not stabilized yet, and are subject to change between Frama-C versions. *) val eval_predicate: (pre:state -> here:state -> predicate -> Property_status.emitted_status) ref (** Evaluate the given predicate in the given states for the Pre and Here ACSL labels. @since Neon-20140301 *) end (** {3 Callbacks} *) type callstack = Value_types.callstack (** Actions to perform at end of each function analysis. Not compatible with option [-memexec-all] *) module Record_Value_Callbacks: Hook.Iter_hook with type param = callstack * (state Stmt.Hashtbl.t) Lazy.t module Record_Value_Superposition_Callbacks: Hook.Iter_hook with type param = callstack * (state list Stmt.Hashtbl.t) Lazy.t module Record_Value_After_Callbacks: Hook.Iter_hook with type param = callstack * (state Stmt.Hashtbl.t) Lazy.t (**/**) (* Temporary API, do not use *) module Record_Value_Callbacks_New: Hook.Iter_hook with type param = callstack * ((state Stmt.Hashtbl.t) Lazy.t (* before states *) * (state Stmt.Hashtbl.t) Lazy.t) (* after states *) Value_types.callback_result (**/**) val no_results: (fundec -> bool) ref (** Returns [true] if the user has requested that no results should be recorded for this function. If possible, hooks registered on [Record_Value_Callbacks] and [Record_Value_Callbacks_New] should not force their lazy argument *) (** Actions to perform at each treatment of a "call" statement. [state] is the state before the call. @deprecated Use Call_Type_Value_Callbacks instead. *) module Call_Value_Callbacks: Hook.Iter_hook with type param = state * callstack (** Actions to perform at each treatment of a "call" statement. [state] is the state before the call. @since Aluminium-20160501 *) module Call_Type_Value_Callbacks: Hook.Iter_hook with type param = [`Builtin of Value_types.call_result | `Spec of funspec | `Def | `Memexec] * state * callstack (** Actions to perform whenever a statement is handled. *) module Compute_Statement_Callbacks: Hook.Iter_hook with type param = stmt * callstack * state list (* -remove-redundant-alarms feature, applied at the end of an Eva analysis, fulfilled by the Scope plugin that also depends on Eva. We thus use a reference here to avoid a cyclic dependency. *) val rm_asserts: (unit -> unit) ref (** {3 Pretty printing} *) val pretty : Format.formatter -> t -> unit val pretty_state : Format.formatter -> state -> unit val display : (Format.formatter -> kernel_function -> unit) ref (**/**) (** {3 Internal use only} *) val noassert_get_state : ?after:bool -> kinstr -> state (** To be used during the value analysis itself (instead of {!get_state}). [after] is false by default. *) val recursive_call_occurred: kernel_function -> unit val merge_conditions: int Cil_datatype.Stmt.Hashtbl.t -> unit val mask_then: int val mask_else: int val initial_state_only_globals : (unit -> state) ref val update_callstack_table: after:bool -> stmt -> callstack -> state -> unit (* Merge a new state in the table indexed by callstacks. *) val memoize : (kernel_function -> unit) ref (* val compute_call : (kernel_function -> call_kinstr:kinstr -> state -> (exp*t) list -> Cvalue.V_Offsetmap.t option (** returned value of [kernel_function] *) * state) ref *) val merge_initial_state : callstack -> state -> unit (** Store an additional possible initial state for the given callstack as well as its values for actuals. *) val initial_state_changed: (unit -> unit) ref end (** Functional dependencies between function inputs and function outputs. @see <../from/index.html> internal documentation. *) module From : sig (** exception raised by [find_deps_no_transitivity_*] if the given expression is not an lvalue. @since Aluminium-20160501 *) exception Not_lval val compute_all : (unit -> unit) ref val compute_all_calldeps : (unit -> unit) ref val compute : (kernel_function -> unit) ref val is_computed: (kernel_function -> bool) ref (** Check whether the from analysis has been performed for the given function. @return true iff the analysis has been performed *) val get : (kernel_function -> Function_Froms.t) ref val access : (Locations.Zone.t -> Function_Froms.Memory.t -> Locations.Zone.t) ref val find_deps_no_transitivity : (stmt -> exp -> Locations.Zone.t) ref val find_deps_no_transitivity_state : (Value.state -> exp -> Locations.Zone.t) ref (** @raise Not_lval if the given expression is not a C lvalue. *) val find_deps_term_no_transitivity_state : (Value.state -> term -> Value_types.logic_dependencies) ref val self: State.t ref (** {3 Pretty printing} *) val pretty : (Format.formatter -> kernel_function -> unit) ref val display : (Format.formatter -> unit) ref (** {3 Callback} *) module Record_From_Callbacks: Hook.Iter_hook with type param = Kernel_function.t Stack.t * Function_Froms.Memory.t Stmt.Hashtbl.t * (Kernel_function.t * Function_Froms.Memory.t) list Stmt.Hashtbl.t (** {3 Access to callwise-stored data} *) module Callwise : sig val iter : ((kinstr -> Function_Froms.t -> unit) -> unit) ref val find : (kinstr -> Function_Froms.t) ref end end (* ************************************************************************* *) (** {2 Properties} *) (* ************************************************************************* *) (** Dealing with logical properties. @plugin development guide *) module Properties : sig (** Interpretation of logic terms. *) module Interp : sig (** {3 Parsing logic terms and annotations} *) (** For the three functions below, [env] can be used to specify which logic labels are parsed. By default, only [Here] is accepted. All the C labels inside the function are also accepted, regardless of [env]. [loc] is used as the source for the beginning of the string. All three functions may raise {!Logic_interp.Error} or {!Parsing.Parse_error}. *) val term_lval : (kernel_function -> ?loc:location -> ?env:Logic_typing.Lenv.t -> string -> Cil_types.term_lval) ref val term : (kernel_function -> ?loc:location -> ?env:Logic_typing.Lenv.t -> string -> Cil_types.term) ref val predicate : (kernel_function -> ?loc:location -> ?env:Logic_typing.Lenv.t -> string -> Cil_types.predicate) ref val code_annot : (kernel_function -> stmt -> string -> code_annotation) ref (** {3 From logic terms to C terms} *) (** Exception raised by the functions below when their given argument cannot be interpreted in the C world. @since Aluminium-20160501 *) exception No_conversion val term_lval_to_lval: (result: Cil_types.varinfo option -> term_lval -> Cil_types.lval) ref (** @raise No_conversion if the argument is not a left value. @modify Aluminium-20160501 raises a custom exn instead of generic Invalid_arg *) val term_to_lval: (result: Cil_types.varinfo option -> term -> Cil_types.lval) ref (** @raise No_conversion if the argument is not a left value. @modify Aluminium-20160501 raises a custom exn instead of generic Invalid_arg *) val term_to_exp: (result: Cil_types.varinfo option -> term -> Cil_types.exp) ref (** @raise No_conversion if the argument is not a valid expression. @modify Aluminium-20160501 raises a custom exn instead of generic Invalid_arg *) val loc_to_exp: (result: Cil_types.varinfo option -> term -> Cil_types.exp list) ref (** @return a list of C expressions. @raise No_conversion if the argument is not a valid set of expressions. @modify Aluminium-20160501 raises a custom exn instead of generic Invalid_arg *) val loc_to_lval: (result: Cil_types.varinfo option -> term -> Cil_types.lval list) ref (** @return a list of C locations. @raise No_conversion if the argument is not a valid set of left values. @modify Aluminium-20160501 raises a custom exn instead of generic Invalid_arg *) val term_offset_to_offset: (result: Cil_types.varinfo option -> term_offset -> offset) ref (** @raise No_conversion if the argument is not a valid offset. @modify Aluminium-20160501 raises a custom exn instead of generic Invalid_arg *) val loc_to_offset: (result: Cil_types.varinfo option -> term -> Cil_types.offset list) ref (** @return a list of C offset provided the term denotes locations who have all the same base address. @raise No_conversion if the given term does not match the precondition @modify Aluminium-20160501 raises a custom exn instead of generic Invalid_arg *) (** {3 From logic terms to Locations.location} *) val loc_to_loc: (result: Cil_types.varinfo option -> Value.state -> term -> Locations.location) ref (** @raise No_conversion if the translation fails. @modify Aluminium-20160501 raises a custom exn instead of generic Invalid_arg *) val loc_to_loc_under_over: (result: Cil_types.varinfo option -> Value.state -> term -> Locations.location * Locations.location * Locations.Zone.t) ref (** Same as {!loc_to_loc}, except that we return simultaneously an under-approximation of the term (first location), and an over-approximation (second location). The under-approximation is particularly useful when evaluating Tsets. The zone returned is an over-approximation of locations that have been read during evaluation. Warning: This API is not stabilized, and may change in the future. @raise No_conversion if the translation fails. @modify Aluminium-20160501 raises a custom exn instead of generic Invalid_arg *) (** {3 From logic terms to Zone.t} *) module To_zone : sig type t_ctx = {state_opt:bool option; ki_opt:(stmt * bool) option; kf:Kernel_function.t} val mk_ctx_func_contrat: (kernel_function -> state_opt:bool option -> t_ctx) ref (** To build an interpretation context relative to function contracts. *) val mk_ctx_stmt_contrat: (kernel_function -> stmt -> state_opt:bool option -> t_ctx) ref (** To build an interpretation context relative to statement contracts. *) val mk_ctx_stmt_annot: (kernel_function -> stmt -> t_ctx) ref (** To build an interpretation context relative to statement annotations. *) type t = {before:bool ; ki:stmt ; zone:Locations.Zone.t} type t_zone_info = (t list) option (** list of zones at some program points. * None means that the computation has failed. *) type t_decl = {var: Varinfo.Set.t ; (* related to vars of the annot *) lbl: Logic_label.Set.t} (* related to labels of the annot *) type t_pragmas = {ctrl: Stmt.Set.t ; (* related to //@ slice pragma ctrl/expr *) stmt: Stmt.Set.t} (* related to statement assign and //@ slice pragma stmt *) val from_term: (term -> t_ctx -> t_zone_info * t_decl) ref (** Entry point to get zones needed to evaluate the [term] relative to the [ctx] of interpretation. *) val from_terms: (term list -> t_ctx -> t_zone_info * t_decl) ref (** Entry point to get zones needed to evaluate the list of [terms] relative to the [ctx] of interpretation. *) val from_pred: (predicate -> t_ctx -> t_zone_info * t_decl) ref (** Entry point to get zones needed to evaluate the [predicate] relative to the [ctx] of interpretation. *) val from_preds: (predicate list -> t_ctx -> t_zone_info * t_decl) ref (** Entry point to get zones needed to evaluate the list of [predicates] relative to the [ctx] of interpretation. *) val from_zone: (identified_term -> t_ctx -> t_zone_info * t_decl) ref (** Entry point to get zones needed to evaluate the [zone] relative to the [ctx] of interpretation. *) val from_stmt_annot: (code_annotation -> stmt * kernel_function -> (t_zone_info * t_decl) * t_pragmas) ref (** Entry point to get zones needed to evaluate an annotation on the given stmt. *) val from_stmt_annots: ((code_annotation -> bool) option -> stmt * kernel_function -> (t_zone_info * t_decl) * t_pragmas) ref (** Entry point to get zones needed to evaluate annotations of this [stmt]. *) val from_func_annots: (((stmt -> unit) -> kernel_function -> unit) -> (code_annotation -> bool) option -> kernel_function -> (t_zone_info * t_decl) * t_pragmas) ref (** Entry point to get zones needed to evaluate annotations of this [kf]. *) val code_annot_filter: (code_annotation -> threat:bool -> user_assert:bool -> slicing_pragma:bool -> loop_inv:bool -> loop_var:bool -> others:bool -> bool) ref (** To quickly build an annotation filter *) end (** Does the interpretation of the predicate rely on the interpretation of the term result? @since Carbon-20110201 *) val to_result_from_pred: (predicate -> bool) ref end (** {3 Assertions} *) val add_assert: Emitter.t -> kernel_function -> stmt -> string -> unit (** @deprecated since Oxygen-20120901 Ask for {ACSL_importer plug-in} if you need such functionality. @modify Boron-20100401 takes as additional argument the computation which adds the assert. @modify Oxygen-20120901 replaces the State.t list by an Emitter.t *) end (* ************************************************************************* *) (** {2 Plugins} *) (* ************************************************************************* *) (** Declarations common to the various postdominators-computing modules *) module PostdominatorsTypes: sig exception Top (** Used for postdominators-related functions, when the postdominators of a statement cannot be computed. It means that there is no path from this statement to the function return. *) module type Sig = sig val compute: (kernel_function -> unit) ref val stmt_postdominators: (kernel_function -> stmt -> Stmt.Hptset.t) ref (** @raise Top (see above) *) val is_postdominator: (kernel_function -> opening:stmt -> closing:stmt -> bool) ref val display: (unit -> unit) ref val print_dot : (string -> kernel_function -> unit) ref (** Print a representation of the postdominators in a dot file whose name is [basename.function_name.dot]. *) end end (** Syntactic postdominators plugin. @see <../postdominators/index.html> internal documentation. *) module Postdominators: PostdominatorsTypes.Sig (** Postdominators using value analysis results. @see <../postdominators/index.html> internal documentation. *) module PostdominatorsValue: PostdominatorsTypes.Sig (** Runtime Error Annotation Generation plugin. @see <../rte/index.html> internal documentation. *) module RteGen : sig (** Same result as having [-rte] on the command line*) val compute : (unit -> unit) ref (** Generates RTE for a single function. Uses the status of the various RTE options do decide which kinds of annotations must be generated. *) val annotate_kf : (kernel_function -> unit) ref (** Generates all possible RTE for a given function. *) val do_all_rte : (kernel_function -> unit) ref (** Generates all possible RTE except pre-conditions for a given function. *) val do_rte : (kernel_function -> unit) ref val self: State.t ref type status_accessor = string (* name *) * (kernel_function -> bool -> unit) (* for each kf and each kind of annotation, set/unset the fact that there has been generated *) * (kernel_function -> bool) (* is this kind of annotation generated in kf? *) val get_all_status : (unit -> status_accessor list) ref val get_divMod_status : (unit -> status_accessor) ref val get_initialized_status: (unit -> status_accessor) ref val get_memAccess_status : (unit -> status_accessor) ref val get_pointerCall_status: (unit -> status_accessor) ref val get_signedOv_status : (unit -> status_accessor) ref val get_signed_downCast_status : (unit -> status_accessor) ref val get_unsignedOv_status : (unit -> status_accessor) ref val get_unsignedDownCast_status : (unit -> status_accessor) ref val get_float_to_int_status : (unit -> status_accessor) ref val get_finite_float_status : (unit -> status_accessor) ref val get_bool_value_status : (unit -> status_accessor) ref end (** Security analysis. @see <../security/index.html> internal documentation. *) module Security : sig val run_whole_analysis: (unit -> unit) ref (** Run all the security analysis. *) val run_ai_analysis: (unit -> unit) ref (** Only run the analysis by abstract interpretation. *) val run_slicing_analysis: (unit -> Project.t) ref (** Only run the security slicing pre-analysis. *) val self: State.t ref end (** Program Dependence Graph. @see <../pdg/index.html> PDG internal documentation. *) module Pdg : sig exception Bottom (** Raised by most function when the PDG is Bottom because we can hardly do nothing with it. It happens when the function is unreachable because we have no information about it. *) exception Top (** Raised by most function when the PDG is Top because we can hardly do nothing with it. It happens when we didn't manage to compute it, for instance for a variadic function. *) type t = PdgTypes.Pdg.t (** PDG type *) type t_nodes_and_undef = ((PdgTypes.Node.t * Locations.Zone.t option) list * Locations.Zone.t option) (** type for the return value of many [find_xxx] functions when the answer can be a list of [(node, z_part)] and an [undef zone]. For each node, [z_part] can specify which part of the node is used in terms of zone ([None] means all). *) val self : State.t ref (** {3 Getters} *) val get : (kernel_function -> t) ref (** Get the PDG of a function. Build it if it doesn't exist yet. *) val node_key : (PdgTypes.Node.t -> PdgIndex.Key.t) ref val from_same_fun : t -> t -> bool (** {3 Finding PDG nodes} *) val find_decl_var_node : (t -> Cil_types.varinfo -> PdgTypes.Node.t) ref (** Get the node corresponding the declaration of a local variable or a formal parameter. @raise Not_found if the variable is not declared in this function. @raise Bottom if given PDG is bottom. @raise Top if the given pdg is top. *) val find_ret_output_node : (t -> PdgTypes.Node.t) ref (** Get the node corresponding return stmt. @raise Not_found if the output state in unreachable @raise Bottom if given PDG is bottom. @raise Top if the given pdg is top. *) val find_output_nodes : (t -> PdgIndex.Signature.out_key -> t_nodes_and_undef) ref (** Get the nodes corresponding to a call output key in the called pdg. @raise Not_found if the output state in unreachable @raise Bottom if given PDG is bottom. @raise Top if the given pdg is top. *) val find_input_node : (t -> int -> PdgTypes.Node.t) ref (** Get the node corresponding to a given input (parameter). @raise Not_found if the number is not an input number. @raise Bottom if given PDG is bottom. @raise Top if the given pdg is top. *) val find_all_inputs_nodes : (t -> PdgTypes.Node.t list) ref (** Get the nodes corresponding to all inputs. {!node_key} can be used to know their numbers. @raise Bottom if given PDG is bottom. @raise Top if the given pdg is top. *) val find_stmt_node : (t -> Cil_types.stmt -> PdgTypes.Node.t) ref (** Get the node corresponding to the statement. It shouldn't be a call statement. See also {!find_simple_stmt_nodes} or {!find_call_stmts}. @raise Not_found if the given statement is unreachable. @raise Bottom if given PDG is bottom. @raise Top if the given pdg is top. @raise PdgIndex.CallStatement if the given stmt is a function call. *) val find_simple_stmt_nodes : (t -> Cil_types.stmt -> PdgTypes.Node.t list) ref (** Get the nodes corresponding to the statement. It is usually composed of only one node (see {!find_stmt_node}), except for call statement. Be careful that for block statements, it only returns a node corresponding to the elementary stmt (see {!find_stmt_and_blocks_nodes} for more) @raise Not_found if the given statement is unreachable. @raise Bottom if given PDG is bottom. @raise Top if the given pdg is top. *) val find_label_node : (t -> Cil_types.stmt -> Cil_types.label -> PdgTypes.Node.t) ref (** Get the node corresponding to the label. @raise Not_found if the given label is not in the PDG. @raise Bottom if given PDG is bottom. @raise Top if the given pdg is top. *) val find_stmt_and_blocks_nodes : (t -> Cil_types.stmt -> PdgTypes.Node.t list) ref (** Get the nodes corresponding to the statement like * {!find_simple_stmt_nodes} but also add the nodes of the enclosed * statements if [stmt] contains blocks. @raise Not_found if the given statement is unreachable. @raise Bottom if given PDG is bottom. @raise Top if the given pdg is top. *) val find_top_input_node : (t -> PdgTypes.Node.t) ref (** @raise Not_found if there is no top input in the PDG. @raise Bottom if given PDG is bottom. @raise Top if the given pdg is top. *) val find_entry_point_node : (t -> PdgTypes.Node.t) ref (** Find the node that represent the entry point of the function, i.e. the higher level block. @raise Bottom if given PDG is bottom. @raise Top if the given pdg is top. *) val find_location_nodes_at_stmt : (t -> Cil_types.stmt -> before:bool -> Locations.Zone.t -> t_nodes_and_undef) ref (** Find the nodes that define the value of the location at the given program point. Also return a zone that might be undefined at that point. @raise Not_found if the given statement is unreachable. @raise Bottom if given PDG is bottom. @raise Top if the given pdg is top. *) val find_location_nodes_at_end : (t -> Locations.Zone.t -> t_nodes_and_undef) ref (** Same than {!find_location_nodes_at_stmt} for the program point located at the end of the function. @raise Not_found if the output state is unreachable. @raise Bottom if given PDG is bottom. @raise Top if the given pdg is top. *) val find_location_nodes_at_begin : (t -> Locations.Zone.t -> t_nodes_and_undef) ref (** Same than {!find_location_nodes_at_stmt} for the program point located at the beginning of the function. Notice that it can only find formal argument nodes. The remaining zone (implicit input) is returned as undef. @raise Not_found if the output state is unreachable. @raise Bottom if given PDG is bottom. @raise Top if the given pdg is top. *) val find_call_stmts: (kernel_function -> caller:kernel_function -> Cil_types.stmt list) ref (** Find the call statements to the function (can maybe be somewhere else). @raise Bottom if given PDG is bottom. @raise Top if the given pdg is top. *) val find_call_ctrl_node : (t -> Cil_types.stmt -> PdgTypes.Node.t) ref (** @raise Not_found if the call is unreachable. @raise Bottom if given PDG is bottom. @raise Top if the given pdg is top. *) val find_call_input_node : (t -> Cil_types.stmt -> int -> PdgTypes.Node.t) ref (** @raise Not_found if the call is unreachable or has no such input. @raise Bottom if given PDG is bottom. @raise Top if the given pdg is top. *) val find_call_output_node : (t -> Cil_types.stmt -> PdgTypes.Node.t) ref (** @raise Not_found if the call is unreachable or has no output node. @raise Bottom if given PDG is bottom. @raise Top if the given pdg is top. *) val find_code_annot_nodes : (t -> Cil_types.stmt -> Cil_types.code_annotation -> PdgTypes.Node.t list * PdgTypes.Node.t list * (t_nodes_and_undef option)) ref (** The result is composed of three parts : - the first part of the result are the control dependencies nodes of the annotation, - the second part is the list of declaration nodes of the variables used in the annotation; - the third part is similar to [find_location_nodes_at_stmt] result but for all the locations needed by the annotation. When the third part is globally [None], it means that we were not able to compute this information. @raise Not_found if the statement is unreachable. @raise Bottom if given PDG is bottom. @raise Top if the given pdg is top. *) val find_fun_precond_nodes : (t -> Cil_types.predicate -> PdgTypes.Node.t list * (t_nodes_and_undef option)) ref (** Similar to [find_code_annot_nodes] (no control dependencies nodes) *) val find_fun_postcond_nodes : (t -> Cil_types.predicate -> PdgTypes.Node.t list * (t_nodes_and_undef option)) ref (** Similar to [find_fun_precond_nodes] *) val find_fun_variant_nodes : (t -> Cil_types.term -> (PdgTypes.Node.t list * t_nodes_and_undef option)) ref (** Similar to [find_fun_precond_nodes] *) (** {3 Propagation} See also [Pdg.mli] for more function that cannot be here because they use polymorphic types. **) val find_call_out_nodes_to_select : (t -> PdgTypes.NodeSet.t -> t -> Cil_types.stmt -> PdgTypes.Node.t list) ref (** [find_call_out_nodes_to_select pdg_called called_selected_nodes pdg_caller call_stmt] @return the call outputs nodes [out] such that [find_output_nodes pdg_called out_key] intersects [called_selected_nodes]. *) val find_in_nodes_to_select_for_this_call : (t -> PdgTypes.NodeSet.t -> Cil_types.stmt -> t -> PdgTypes.Node.t list) ref (** [find_in_nodes_to_select_for_this_call pdg_caller caller_selected_nodes call_stmt pdg_called] @return the called input nodes such that the corresponding nodes in the caller intersect [caller_selected_nodes] @raise Not_found if the statement is unreachable. @raise Bottom if given PDG is bottom. @raise Top if the given pdg is top. *) (** {3 Dependencies} *) val direct_dpds : (t -> PdgTypes.Node.t -> PdgTypes.Node.t list) ref (** Get the nodes to which the given node directly depend on. @raise Bottom if given PDG is bottom. @raise Top if the given pdg is top. *) val direct_ctrl_dpds : (t -> PdgTypes.Node.t -> PdgTypes.Node.t list) ref (** Similar to {!direct_dpds}, but for control dependencies only. @raise Bottom if given PDG is bottom. @raise Top if the given pdg is top. *) val direct_data_dpds : (t -> PdgTypes.Node.t -> PdgTypes.Node.t list) ref (** Similar to {!direct_dpds}, but for data dependencies only. @raise Bottom if given PDG is bottom. @raise Top if the given pdg is top. *) val direct_addr_dpds : (t -> PdgTypes.Node.t -> PdgTypes.Node.t list) ref (** Similar to {!direct_dpds}, but for address dependencies only. @raise Bottom if given PDG is bottom. @raise Top if the given pdg is top. *) val all_dpds : (t -> PdgTypes.Node.t list -> PdgTypes.Node.t list) ref (** Transitive closure of {!direct_dpds} for all the given nodes. @raise Bottom if given PDG is bottom. @raise Top if the given pdg is top. *) val all_data_dpds : (t -> PdgTypes.Node.t list -> PdgTypes.Node.t list) ref (** Gives the data dependencies of the given nodes, and recursively, all the dependencies of those nodes (regardless to their kind). @raise Bottom if given PDG is bottom. @raise Top if the given pdg is top. *) val all_ctrl_dpds : (t -> PdgTypes.Node.t list -> PdgTypes.Node.t list) ref (** Similar to {!all_data_dpds} for control dependencies. @raise Bottom if given PDG is bottom. @raise Top if the given pdg is top. *) val all_addr_dpds : (t -> PdgTypes.Node.t list -> PdgTypes.Node.t list) ref (** Similar to {!all_data_dpds} for address dependencies. @raise Bottom if given PDG is bottom. @raise Top if the given pdg is top. *) val direct_uses : (t -> PdgTypes.Node.t -> PdgTypes.Node.t list) ref (** build a list of all the nodes that have direct dependencies on the given node. @raise Bottom if given PDG is bottom. @raise Top if the given pdg is top. *) val direct_ctrl_uses : (t -> PdgTypes.Node.t -> PdgTypes.Node.t list) ref (** Similar to {!direct_uses}, but for control dependencies only. @raise Bottom if given PDG is bottom. @raise Top if the given pdg is top. *) val direct_data_uses : (t -> PdgTypes.Node.t -> PdgTypes.Node.t list) ref (** Similar to {!direct_uses}, but for data dependencies only. @raise Bottom if given PDG is bottom. @raise Top if the given pdg is top. *) val direct_addr_uses : (t -> PdgTypes.Node.t -> PdgTypes.Node.t list) ref (** Similar to {!direct_uses}, but for address dependencies only. @raise Bottom if given PDG is bottom. @raise Top if the given pdg is top. *) val all_uses : (t -> PdgTypes.Node.t list -> PdgTypes.Node.t list) ref (** build a list of all the nodes that have dependencies (even indirect) on the given nodes. @raise Bottom if given PDG is bottom. @raise Top if the given pdg is top. *) val custom_related_nodes : ((PdgTypes.Node.t -> PdgTypes.Node.t list) -> PdgTypes.Node.t list -> PdgTypes.Node.t list) ref (** [custom_related_nodes get_dpds node_list] build a list, starting from the node in [node_list], and recursively add the nodes given by the function [get_dpds]. For this function to work well, it is important that [get_dpds n] returns a subset of the nodes directly related to [n], ie a subset of [direct_uses] U [direct_dpds]. @raise Bottom if given PDG is bottom. @raise Top if the given pdg is top. *) val iter_nodes : ((PdgTypes.Node.t -> unit) -> t -> unit) ref (** apply a given function to all the PDG nodes @raise Bottom if given PDG is bottom. @raise Top if the given pdg is top. *) (** {3 Pretty printing} *) val extract : (t -> string -> unit) ref (** Pretty print pdg into a dot file. @see <../pdg/index.html> PDG internal documentation. *) val pretty_node : (bool -> Format.formatter -> PdgTypes.Node.t -> unit) ref (** Pretty print information on a node : with [short=true], only the id of the node is printed.. *) val pretty_key : (Format.formatter -> PdgIndex.Key.t -> unit) ref (** Pretty print information on a node key *) val pretty : (?bw:bool -> Format.formatter -> t -> unit) ref (** For debugging... Pretty print pdg information. Print codependencies rather than dependencies if [bw=true]. *) end (** Signature common to some Inout plugin options. The results of the computations are available on a per function basis. *) module type INOUTKF = sig type t val self_internal: State.t ref val self_external: State.t ref val compute : (kernel_function -> unit) ref val get_internal : (kernel_function -> t) ref (** Inputs/Outputs with local and formal variables *) val get_external : (kernel_function -> t) ref (** Inputs/Outputs without either local or formal variables *) (** {3 Pretty printing} *) val display : (Format.formatter -> kernel_function -> unit) ref val pretty : Format.formatter -> t -> unit end (** Signature common to inputs and outputs computations. The results are also available on a per-statement basis. *) module type INOUT = sig include INOUTKF val statement : (stmt -> t) ref val kinstr : kinstr -> t option end (** State_builder.of read inputs. That is over-approximation of zones read by each function. @see <../inout/Inputs.html> internal documentation. *) module Inputs : sig include INOUT with type t = Locations.Zone.t val expr : (stmt -> exp -> t) ref val self_with_formals: State.t ref val get_with_formals : (kernel_function -> t) ref (** Inputs with formals and without local variables *) val display_with_formals: (Format.formatter -> kernel_function -> unit) ref end (** State_builder.of outputs. That is over-approximation of zones written by each function. @see <../inout/Outputs.html> internal documentation. *) module Outputs : sig include INOUT with type t = Locations.Zone.t val display_external : (Format.formatter -> kernel_function -> unit) ref end (** State_builder.of operational inputs. That is: - over-approximation of zones whose input values are read by each function, State_builder.of sure outputs - under-approximation of zones written by each function. @see <../inout/Context.html> internal documentation. *) module Operational_inputs : sig include INOUTKF with type t = Inout_type.t val get_internal_precise: (?stmt:stmt -> kernel_function -> Inout_type.t) ref (** More precise version of [get_internal] function. If [stmt] is specified, and is a possible call to the given kernel_function, returns the operational inputs for this call (if option -inout-callwise has been set). *) (**/**) (* Internal use *) module Record_Inout_Callbacks: Hook.Iter_hook with type param = Value_types.callstack * Inout_type.t (**/**) end (**/**) (** Do not use yet. @see <../inout/Derefs.html> internal documentation. *) module Derefs : INOUT with type t = Locations.Zone.t (**/**) (** {3 GUI} *) (** This function should be called from time to time by all analysers taking time. In GUI mode, this will make the interface reactive. @plugin development guide *) val progress: (unit -> unit) ref (** This exception may be raised by {!progress} to interrupt computations. *) exception Cancel (* Local Variables: compile-command: "make -C ../../.." End: *)
OCaml
use std::fs::File; use std::io::prelude::Read; fn main() { let mut file = File::open("./input").expect("Unable to open file"); let mut input = String::new(); file.read_to_string(&mut input).expect("Could not read file"); println!("Puzzle 1: {}", puzzle(&input)); println!("Puzzle 2: {}", puzzle2(&input)); } fn puzzle(s: &str) -> String { let mut output = String::new(); for line in &transpose(s) { output.push(most_common(line)); } output } fn puzzle2(s: &str) -> String { let mut output = String::new(); for line in &transpose(s) { output.push(least_common(line)); } output } /// Reads the string vertically and returns it horizontally. fn transpose(s: &str) -> Vec<String> { let length = s.lines() .map(|l| l.trim()) .next() .unwrap() .len(); let mut output = vec![String::new(); length]; for line in s.lines().map(|l| l.trim()) { for (n, c) in line.chars().enumerate() { output[n].push(c); } } output } /// Return most frequent char in the input string. Doesn't handle empty input. fn most_common(s: &str) -> char { use std::collections::HashMap; let mut char_map: HashMap<char, u64> = HashMap::new(); for c in s.chars() { *char_map.entry(c).or_insert(0) += 1; } let (c, _) = char_map.iter().fold((' ', 0), |max, (&c, &n)| if n > max.1 { (c, n) } else { max }); c } /// Return least frequent char in the input string. Doesn't handle empty input. fn least_common(s: &str) -> char { use std::collections::HashMap; let mut char_map: HashMap<char, u64> = HashMap::new(); for c in s.chars() { *char_map.entry(c).or_insert(0) += 1; } let (c, _) = char_map.iter().fold((' ', std::u64::MAX), |min, (&c, &n)| if n < min.1 { (c, n) } else { min }); c } #[cfg(test)] mod test { use super::*; #[test] fn test_transpose() { let input = "eedadn drvtee eandsr raavrd atevrs tsrnev sdttsa rasrtv nssdts ntnada svetve tesnvt vntsnd vrdear dvrsen enarar"; let expected = ["ederatsrnnstvvde", "eraatsdastvenrvn", "dvnaertssnestdra", "atdvvntrdatnsesr", "desrresttdvvnaea", "nerdsvavsaetdrnr"]; println!("Transposed: {:?}", transpose(input)); for (n, s) in transpose(input).iter().enumerate() { assert_eq!(s, expected[n]); } } #[test] fn test_most_common() { assert_eq!(most_common("hello"), 'l'); assert_eq!(most_common("hhhll"), 'h'); assert_eq!(most_common("hhlll"), 'l'); } }
RenderScript
2.938749999999999751e+00 -1.811500000000000055e-01 2.809649999999999537e+00 -1.230549999999999977e-01 2.709649999999999892e+00 1.456349999999999867e-01 2.837699999999999889e+00 2.580199999999999716e-01 2.763999999999999790e+00 1.393099999999999894e-01 2.763999999999999790e+00 1.393099999999999894e-01 2.605649999999999800e+00 5.046499999999999597e-02 2.276050000000000129e+00 -3.449899999999999495e-02 2.084449999999999914e+00 1.045399999999999940e-01 2.048299999999999788e+00 1.249050000000000021e-01 2.048299999999999788e+00 1.249050000000000021e-01 2.031949999999999701e+00 1.610399999999999887e-01 2.032049999999999912e+00 3.043600000000000194e-01 2.165249999999999897e+00 3.527150000000000007e-01 2.134799999999999809e+00 2.637499999999999845e-01 2.134799999999999809e+00 2.637499999999999845e-01 2.052849999999999842e+00 1.647900000000000198e-01 1.880399999999999849e+00 9.414999999999999758e-02 1.827999999999999847e+00 8.283999999999999697e-02 1.850400000000000045e+00 -7.184499999999999264e-04 1.850400000000000045e+00 -7.184499999999999264e-04 1.847949999999999982e+00 -7.907999999999999752e-02 1.823149999999999826e+00 -8.683000000000000440e-02 2.173699999999999743e+00 1.043599999999999910e-02 2.300449999999999662e+00 -4.351350000000000356e-02 2.300449999999999662e+00 -4.351350000000000356e-02 2.316549999999999887e+00 -1.140950000000000020e-01 2.264949999999999797e+00 -1.547749999999999959e-01 2.281149999999999789e+00 -1.345799999999999774e-01 2.276949999999999807e+00 -1.311449999999999838e-01 2.276949999999999807e+00 -1.311449999999999838e-01 2.250449999999999839e+00 -1.068149999999999933e-01 2.284949999999999815e+00 1.264299999999999868e-01 2.510899999999999910e+00 2.473249999999999615e-01 2.538850000000000051e+00 1.383299999999999808e-01 2.538850000000000051e+00 1.383299999999999808e-01 2.502049999999999663e+00 2.167799999999999588e-02 2.370000000000000107e+00 -7.761499999999998956e-02 2.367550000000000043e+00 1.365699999999999727e-02 2.410799999999999610e+00 9.374499999999999500e-02 2.410799999999999610e+00 9.374499999999999500e-02 2.383099999999999774e+00 1.313349999999999795e-01 2.365599999999999703e+00 1.014999999999999791e-01 2.706049999999999400e+00 1.526199999999999779e-01 2.771199999999999886e+00 3.060849999999999335e-02 2.771199999999999886e+00 3.060849999999999335e-02 2.747850000000000126e+00 -7.590999999999999137e-02 2.632099999999999884e+00 -8.724999999999999423e-02 2.525399999999999867e+00 -4.432350000000000179e-02 2.506199999999999761e+00 6.323999999999999760e-03 2.506199999999999761e+00 6.323999999999999760e-03 2.478099999999999525e+00 7.841000000000000747e-02 2.486600000000000144e+00 2.572149999999999714e-01 2.671600000000000197e+00 2.926399999999999557e-01 2.617699999999999694e+00 1.366050000000000042e-01 2.617699999999999694e+00 1.366050000000000042e-01 2.522950000000000248e+00 9.214499999999998733e-03 2.416149999999999576e+00 5.939999999999999100e-03 2.416599999999999859e+00 2.124650000000000150e-02 2.457949999999999857e+00 -5.512499999999998651e-02 2.457949999999999857e+00 -5.512499999999998651e-02 2.489100000000000090e+00 -1.351149999999999851e-01 2.539199999999999680e+00 -4.743049999999999350e-02 2.750449999999999839e+00 1.249149999999999844e-01 2.756250000000000089e+00 4.039549999999999391e-02 2.756250000000000089e+00 4.039549999999999391e-02 2.680849999999999511e+00 -4.535700000000000148e-02 2.476999999999999869e+00 -9.412999999999997758e-02 2.298499999999999766e+00 -1.071049999999999780e-02 2.268499999999999517e+00 2.042949999999999974e-02 2.268499999999999517e+00 2.042949999999999974e-02 2.208749999999999769e+00 -2.195200000000000016e-03 2.075999999999999623e+00 -6.199499999999999456e-02 2.250449999999999839e+00 -1.304999999999999737e-02 2.307499999999999662e+00 -1.176699999999999968e-01 2.307499999999999662e+00 -1.176699999999999968e-01 2.313549999999999773e+00 -2.233750000000000180e-01 2.303499999999999659e+00 -2.527849999999999819e-01 2.293299999999999894e+00 -2.173249999999999904e-01 2.314249999999999474e+00 -1.641849999999999699e-01 2.314249999999999474e+00 -1.641849999999999699e-01 2.296449999999999658e+00 -1.115899999999999809e-01 2.367749999999999577e+00 1.049349999999999866e-01 2.651549999999999851e+00 2.327299999999999647e-01 2.642149999999999554e+00 1.345899999999999874e-01 2.642149999999999554e+00 1.345899999999999874e-01 2.532599999999999518e+00 3.228550000000000170e-02 2.279699999999999616e+00 1.164399999999999810e-02 2.156849999999999934e+00 4.315950000000000342e-02 2.150599999999999845e+00 3.740699999999999581e-02 2.150599999999999845e+00 3.740699999999999581e-02 2.170999999999999819e+00 4.986849999999998923e-02 2.291349999999999554e+00 1.729199999999999904e-01 2.572749999999999648e+00 2.537099999999999356e-01 2.580899999999999750e+00 1.430299999999999905e-01 2.580899999999999750e+00 1.430299999999999905e-01 2.503750000000000142e+00 5.036000000000000199e-02 2.405800000000000161e+00 4.516900000000000082e-02 2.278049999999999908e+00 -7.874499999999999555e-02 2.243299999999999628e+00 -8.411500000000000921e-02 2.243299999999999628e+00 -8.411500000000000921e-02 2.213099999999999845e+00 -4.119149999999999895e-02 2.338749999999999662e+00 1.429699999999999860e-01 2.697699999999999765e+00 1.318549999999999722e-01 2.735049999999999759e+00 -2.498799999999999980e-02 2.735049999999999759e+00 -2.498799999999999980e-02 2.685299999999999354e+00 -1.519999999999999962e-01 2.543950000000000156e+00 -1.941599999999999993e-01 2.490349999999999397e+00 -1.327399999999999969e-01 2.510349999999999859e+00 -1.056099999999999955e-01 2.510349999999999859e+00 -1.056099999999999955e-01 2.516249999999999876e+00 -6.888500000000000179e-02 2.562999999999999723e+00 1.422899999999999998e-01 2.887449999999999850e+00 2.999200000000000199e-01 2.907849999999999824e+00 1.600600000000000078e-01 2.907849999999999824e+00 1.600600000000000078e-01 2.820049999999999724e+00 -2.067299999999999780e-03 2.661099999999999355e+00 -1.253349999999999742e-01 2.595949999999999758e+00 -6.192999999999999200e-02 2.577249999999999819e+00 -7.140499999999999625e-02 2.577249999999999819e+00 -7.140499999999999625e-02 2.529949999999999921e+00 -7.021499999999998576e-02 2.480199999999999960e+00 5.100499999999999479e-02 2.711249999999999716e+00 6.329499999999999016e-02 2.791049999999999809e+00 -6.525500000000000744e-02 2.791049999999999809e+00 -6.525500000000000744e-02 2.790299999999999780e+00 -2.001349999999999796e-01 2.751149999999999984e+00 -2.865449999999999942e-01 2.750899999999999679e+00 -2.705799999999999872e-01 2.746999999999999886e+00 -2.575949999999999629e-01 2.746999999999999886e+00 -2.575949999999999629e-01 2.722199999999999509e+00 -2.064199999999999924e-01 2.727749999999999897e+00 4.362499999999999711e-02 2.980999999999999428e+00 1.450299999999999923e-01 3.036999999999999922e+00 -2.544049999999999784e-02 3.036999999999999922e+00 -2.544049999999999784e-02 3.037199999999999900e+00 -2.010699999999999710e-01 3.031299999999999439e+00 -2.977299999999999947e-01 2.963000000000000078e+00 -2.109299999999999786e-01 2.893349999999999866e+00 -1.623699999999999588e-01 2.893349999999999866e+00 -1.623699999999999588e-01 2.789950000000000152e+00 -1.456599999999999839e-01 2.717549999999999688e+00 3.592699999999999366e-02 3.052349999999999675e+00 1.609849999999999892e-01 3.166149999999999576e+00 5.195999999999999230e-02 3.166149999999999576e+00 5.195999999999999230e-02 3.163899999999999491e+00 -6.783000000000000140e-02 3.057849999999999735e+00 -1.789349999999999830e-01 3.001499999999999613e+00 -1.935749999999999693e-01 2.938749999999999751e+00 -1.811500000000000055e-01
CSV
/* This file is part of JTFRAME. JTFRAME program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. JTFRAME 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 General Public License for more details. You should have received a copy of the GNU General Public License along with JTFRAME. If not, see <http://www.gnu.org/licenses/>. Author: Jose Tejada Gomez. Twitter: @topapate Version: 1.0 Date: 13-12-2019 */ module jtframe_ff #(parameter W=1 ) ( input clk, input rst, (*direct_enable*) input cen, input [W-1:0] din, output reg [W-1:0] q, output reg [W-1:0] qn, input [W-1:0] set, // active high input [W-1:0] clr, // active high input [W-1:0] sigedge // signal whose edge will trigger the FF ); reg [W-1:0] last_edge; generate genvar i; for (i=0; i < W; i=i+1) begin: flip_flop always @(posedge clk) begin if(rst) begin q[i] <= 0; qn[i] <= 1; last_edge[i] <= 0; end else begin last_edge[i] <= sigedge[i]; if( cen && clr[i] ) begin q[i] <= 1'b0; qn[i] <= 1'b1; end else if( cen && set[i] ) begin q[i] <= 1'b1; qn[i] <= 1'b0; end else if( sigedge[i] && !last_edge[i] ) begin q[i] <= din[i]; qn[i] <= ~din[i]; end end end end endgenerate endmodule
Coq
<?php /* Template Name: Builder */ get_header(); ?> <div id="primary" class="content-area"> <main id="main" class="site-main"> <?php while ( have_posts() ) : the_post(); ?> <?php the_content(); ?> <?php endwhile; ?> </main><!-- #main --> </div><!-- #primary --> <?php get_footer(); ?>
Hack
/* * Ext JS Library 2.2 * Copyright(c) 2006-2008, Ext JS, LLC. * licensing@extjs.com * * http://extjs.com/license */ .x-combo-list { border:1px solid #98c0f4; background:#ddecfe; zoom:1; overflow:hidden; } .x-combo-list-inner { overflow:auto; background:white; position:relative; /* for calculating scroll offsets */ zoom:1; overflow-x:hidden; } .x-combo-list-hd { font:bold 11px tahoma, arial, helvetica, sans-serif; color:#15428b; background-image: url(../images/default/layout/panel-title-light-bg.gif); border-bottom:1px solid #98c0f4; padding:3px; } .x-resizable-pinned .x-combo-list-inner { border-bottom:1px solid #98c0f4; } .x-combo-list-item { font:normal 12px tahoma, arial, helvetica, sans-serif; padding:2px; border:1px solid #fff; white-space: nowrap; overflow:hidden; text-overflow: ellipsis; } .x-combo-list .x-combo-selected{ border:1px dotted #a3bae9 !important; background:#DFE8F6; cursor:pointer; } .x-combo-noedit{ cursor:pointer; } .x-combo-list .x-toolbar { border-top:1px solid #98c0f4; border-bottom:0 none; } .x-combo-list-small .x-combo-list-item { font:normal 11px tahoma, arial, helvetica, sans-serif; }
CSS
!******************************************************************* !* TALLY VOXEL DOSE DISTRIBUTION * !* * !* Short description: * !* Tally routines for radiation transport calculations with * !* PENELOPE. * !* * !* Dose distribution in the volume elements (voxels) defined in * !* a PENVOX geometry file. * !* * !* Dependencies: * !* from PENELOPE: * !* -> common /TRACK/, /COMPOS/, /RSEED/ * !* from other penEasy files: * !* -> common /GEOQUAD/ * !* -> routine FINDUF * !* from PENVOX: * !* -> commons /GEOVOX/,/PARTVOX/ * !* -> routines LOCATEVOX * !* * !* Compatible with PENELOPE versions: * !* 2005,2006 * !* * !* Authors: * !* Andreu Badal & Josep Sempau * !* Universitat Politecnica de Catalunya, Barcelona, Spain * !* * !* SEE COPYRIGHT NOTICE IN README.txt under folder penEasy_Imaging * !******************************************************************* subroutine VDDtally(mode,arg) !******************************************************************* !* Input: * !* mode -> Identifies the state of the calling routine * !* arg -> energy loss (mode<0) or history no. (mode=1) * !* Comments: ** IMPORTANT** * !* -> Since this tally modifies the particle state variables * !* through LOCATEVOX, it is required to be the 1st tally * !* to be called by the main program. * !******************************************************************* implicit none integer mode real*8 arg integer*4 kpar,ibody,mat,ilb real*8 e,x,y,z,u,v,w,wght common/track/e,x,y,z,u,v,w,wght,kpar,ibody,mat,ilb(5) character*80 voxfilen logical isFullvol integer matvox,granul,maxGranul parameter (maxGranul=1000) integer*4 nx,ny,nz,nxy,maxvox,bodymask,matmask parameter (maxvox=10000000) ! Max no. of voxels real densvox,idensvox real*8 massvox,dx,dy,dz,idx,idy,idz,vbb common /geovox/ massvox(maxvox),densvox(maxvox),idensvox(maxvox), & matvox(maxvox),dx,dy,dz,idx,idy,idz,vbb(3),nx,ny,nz,nxy, & bodymask,matmask,granul,isFullvol,voxfilen integer*4 xvox,yvox,zvox,absvox real*8 uold,vold,ivx,ivy,ivz,sdx,sdy,sdz common /partvox/ uold,vold,ivx,ivy,ivz,sdx,sdy,sdz, & xvox,yvox,zvox,absvox logical active integer prtxyz,prtdens integer*4 xvoxmin,xvoxmax,yvoxmin,yvoxmax,zvoxmin,zvoxmax real*8 nlast,nhist,unclimit,edptmp,edep,edep2 common /scovdd/ edptmp(maxvox),edep(maxvox),edep2(maxvox), & nlast(maxvox),unclimit,nhist, & xvoxmin,xvoxmax,yvoxmin,yvoxmax,zvoxmin,zvoxmax, & prtxyz,prtdens,active integer*4 vox if (mode.eq.-99.and.ilb(1).ne.1) then ! Locate 2nd particle if (ibody.eq.bodymask) then call locatevox ! Check voxels else ! Inside quadrics absvox = 0 ! Mark as quadrics endif endif if (.not.active) return ! Voxel doses not tallied if (mode.le.0) then ! Deposit energy if (arg.eq.0.0d0) return ! Nothing to deposit if (absvox.eq.0) then ! Inside quadrics if (isFullvol) then ! Consider partial volume xvox = x*idx+1.0d0 ! Compute indices if(xvox.lt.xvoxmin.or.xvox.gt.xvoxmax) return ! Not in ROI yvox = y*idy+1.0d0 if(yvox.lt.yvoxmin.or.yvox.gt.yvoxmax) return ! Not in ROI zvox = z*idz+1.0d0 if(zvox.lt.zvoxmin.or.zvox.gt.zvoxmax) return ! Not in ROI vox = xvox+(yvox-1)*nx+(zvox-1)*nxy ! Absolute voxel index else ! Ignore partial volume return ! Nothing to do endif else ! Inside voxels vox = absvox ! Transfer abs voxel endif if (nhist.gt.nlast(vox)) then ! Visit of a new history edep(vox) = edep(vox) +edptmp(vox) ! Transfer partial scoring to totals edep2(vox) = edep2(vox)+edptmp(vox)**2 ! Score squared values for variance edptmp(vox)= arg*wght ! And update temporary counter nlast(vox) = nhist+0.5d0 ! Update NLAST (+0.5 avoids prec. problems) else edptmp(vox) = edptmp(vox)+arg*wght ! Same history: update temporary counter only endif else if (mode.eq.1.or.mode.eq.2) then ! New history or hist. modified nhist = arg ! Update NHIST endif end subroutine VDDreport(n,cputim,uncdone) !******************************************************************* !* Input: * !* n -> no. of histories simulated * !* cputim -> elapsed CPU time * !* Output: * !* uncdone -> 2 if uncert reached, 1 if not defined, 0 else * !******************************************************************* implicit none integer uncdone real*8 n,cputim integer*4 seed1,seed2 common/rseed/seed1,seed2 character*80 voxfilen logical isFullvol integer matvox,granul,maxGranul parameter (maxGranul=1000) integer*4 nx,ny,nz,nxy,maxvox,bodymask,matmask parameter (maxvox=10000000) ! Max no. of voxels real densvox,idensvox real*8 massvox,dx,dy,dz,idx,idy,idz,vbb common /geovox/ massvox(maxvox),densvox(maxvox),idensvox(maxvox), & matvox(maxvox),dx,dy,dz,idx,idy,idz,vbb(3),nx,ny,nz,nxy, & bodymask,matmask,granul,isFullvol,voxfilen logical active integer prtxyz,prtdens integer*4 xvoxmin,xvoxmax,yvoxmin,yvoxmax,zvoxmin,zvoxmax real*8 nlast,nhist,unclimit,edptmp,edep,edep2 common /scovdd/ edptmp(maxvox),edep(maxvox),edep2(maxvox), & nlast(maxvox),unclimit,nhist, & xvoxmin,xvoxmax,yvoxmin,yvoxmax,zvoxmin,zvoxmax, & prtxyz,prtdens,active logical isQuad common /geoquad/ isQuad character typevox(3) integer nchan,out,finduf,error integer*4 vox,i,j,k real*8 q,sigma,eff,avesig,maxq,fact,x,y,z,uncert real*8 xmiddle,ymiddle,zmiddle,invn uncdone = 1 if (.not.active) return invn = 1.0d0/n ! Prepare output files: out = finduf() open(out,file='tallyVoxelDoseDistrib.dat',iostat=error) if (error.ne.0) then write(*,*) write(*,'(a)') & '*********************************************' write(*,'(a)') & 'VDDreport:ERROR: cannot open output data file' write(*,'(a)') & '*********************************************' close(out) ! Just in case return endif ! Dump counters and obtain max score: avesig = 0.0d0 nchan = 0 maxq = 0.0d0 do k=zvoxmin,zvoxmax do j=yvoxmin,yvoxmax do i=xvoxmin,xvoxmax vox = i+(j-1)*nx+(k-1)*nxy ! Absolute voxel index if (nlast(vox).gt.0.5d0) then ! Do not update if nothing scored edep(vox) = edep(vox) +edptmp(vox) edep2(vox) = edep2(vox)+edptmp(vox)**2 edptmp(vox)= 0.0d0 nlast(vox) = 0.0d0 endif maxq = max(maxq,edep(vox)) end do end do end do maxq = 0.5d0*maxq ! 1/2 of the max score ! Write header: write(out,'(a)') &'#>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>' write(out,'(a)') '# [SECTION REPORT VOXEL DOSE DISTRIB]' write(out,'(a)') '# Deposited energy over voxel mass' if (isFullvol) then write(out,'(a)') '# (INCLUDING parts overlapped by quadrics)' else write(out,'(a)') '# (EXCLUDING parts overlapped by quadrics)' endif write(out,'(a)') '#' write(out,'(a)') '# Dose units are eV/g per primary history' write(out,'(a)') '# Number of voxels in x,y,z:' write(out,'(a,3(1x,i0))') '# ',nx,ny,nz write(out,'(a)') '# Voxels size dx,dy,dz (cm):' write(out,'(a,3(1x,es12.5))')'# ',dx,dy,dz if (isQuad) then write(out,'(a)') & '# The granularity used to compute the voxels mass was:' write(out,'(a,i0)') '# ',granul endif if (prtxyz.eq.1) then write(out,'(a)') '#' write(out,'(a)') & '# For plotting purposes, two values per voxel '// & 'coordinate are given, namely,' write(out,'(a)') & '# the low end and the middle point of each voxel' write(out,'(a)') '#' endif write(out,'(a,$)') '# ' if (prtxyz.eq.1) then write(out,'(a,$)') 'xLow(cm) : xMiddle(cm) : ' write(out,'(a,$)') 'yLow(cm) : yMiddle(cm) : ' write(out,'(a,$)') 'zLow(cm) : zMiddle(cm) : ' endif write(out,'(a,$)') 'dose (eV/g) : +-2sigma' if (prtdens.eq.1) write(out,'(a,$)') & ' : voxel mass (g) : Pure(+)/Overlapped(-)' typevox(1) = '-' typevox(3) = '+' write(out,'(a)') '' ! End of line ! Write data: do k=zvoxmin,zvoxmax z = dz*(k-1) zmiddle = z+dz*0.5d0 write(out,'(a,i0,$)') '# zVoxIndex=',k if (prtxyz.ne.1) & write(out,'(a,es12.5,$)') ' zMiddle(cm)=',zmiddle write(out,*) '' ! EOL do j=yvoxmin,yvoxmax y = dy*(j-1) ymiddle = y+dy*0.5d0 write(out,'(a,i0,$)') '# yVoxIndex=',j if (prtxyz.ne.1) & write(out,'(a,es12.5,$)') ' yMiddle(cm)=',ymiddle write(out,*) '' ! EOL do i=xvoxmin,xvoxmax vox = i+(j-1)*nx+(k-1)*nxy ! Absolute voxel index if (prtxyz.eq.1) then x = dx*(i-1) xmiddle = x+dx*0.5d0 write(out,'(6(1x,es12.5),$)') & x,xmiddle,y,ymiddle,z,zmiddle endif fact = 0.0d0 ! Voxel mass (may be null if partial vol.): if (massvox(vox).gt.0.0d0) fact = 1.0d0/massvox(vox) q = edep(vox)*invn sigma = sqrt(max((edep2(vox)*invn-q**2)*invn,0.0d0))*fact q = q*fact write(out,'(1x,es12.5,1x,es7.1,$)') q,2.0d0*sigma if (prtdens.eq.1) ! Print voxel partial mass & write(out,'(1x,es12.5,1x,a1,$)') massvox(vox), & typevox(2+sign(1,matvox(vox))) ! (1) or (3) write(out,*) '' ! End of line ! Evaluate average uncertainty for scores above 1/2 max score: if (edep(vox).gt.maxq.and.fact.gt.0.0d0) then avesig = avesig+(sigma/q)**2 nchan = nchan+1 endif enddo if (xvoxmax.gt.xvoxmin) write(out,*) '' ! Separate 2D data blocks enddo if (yvoxmax.gt.yvoxmin) write(out,*) '' ! Separate 3D data blocks enddo uncdone = 0 if (nchan.gt.0) then uncert = 200.0d0*sqrt(avesig/nchan) if (uncert.lt.unclimit) uncdone = 2 ! Uncertainty reached else uncert = 0.0d0 ! Uncertainty assumed not reached when score is nil endif ! Generic report: write(out,'(a)') ' ' write(out,'(a)') '# Performance report' write(out,'(a)') '# Random seeds:' write(out,'(a,i10)') '# ',seed1 write(out,'(a,i10)') '# ',seed2 write(out,'(a)') '# No. of histories simulated [N]:' write(out,'(a,f18.0)') '# ',n write(out,'(a)') '# CPU time [t] (s):' write(out,'(a,es12.5)') '# ',cputim if (cputim.gt.0.0d0) then write(out,'(a)') '# Speed (histories/s):' write(out,'(a,es12.5)') '# ',n/cputim endif write(out,'(a)') & '# Average uncertainty (above 1/2 max score) in % [uncert]:' write(out,'(a,es12.5)') '# ',uncert eff = n*uncert**2 if (eff.gt.0.0d0) then write(out,'(a)') '# Intrinsic efficiency [N*uncert^2]^-1:' write(out,'(a,es12.5)') '# ',1.0d0/eff endif eff = cputim*uncert**2 if (eff.gt.0.0d0) then write(out,'(a)') '# Absolute efficiency [t*uncert^2]^-1:' write(out,'(a,es12.5)') '# ',1.0d0/eff endif write(out,'(a)') '#' write(out,'(a)') '# Have a nice day.' close(out) end subroutine VDDinitally !******************************************************************* !* Initializes the Voxel Dose tally. To be called before TALLY. * !* The voxelized geometry must be active to use this tally. * !******************************************************************* implicit none integer*4 kpar,ibody,mat,ilb real*8 e,x,y,z,u,v,w,wght common/track/e,x,y,z,u,v,w,wght,kpar,ibody,mat,ilb(5) integer*4 iz,nelem,maxmat parameter (maxmat=10) real*8 stf,zt,at,rho,vmol common/compos/stf(maxmat,30),zt(maxmat),at(maxmat),rho(maxmat), & vmol(maxmat),iz(maxmat,30),nelem(maxmat) character*80 voxfilen logical isFullvol integer matvox,granul,maxGranul parameter (maxGranul=1000) integer*4 nx,ny,nz,nxy,maxvox,bodymask,matmask parameter (maxvox=10000000) ! Max no. of voxels real densvox,idensvox real*8 massvox,dx,dy,dz,idx,idy,idz,vbb common /geovox/ massvox(maxvox),densvox(maxvox),idensvox(maxvox), & matvox(maxvox),dx,dy,dz,idx,idy,idz,vbb(3),nx,ny,nz,nxy, & bodymask,matmask,granul,isFullvol,voxfilen logical isQuad common /geoquad/ isQuad logical active integer prtxyz,prtdens integer*4 xvoxmin,xvoxmax,yvoxmin,yvoxmax,zvoxmin,zvoxmax real*8 nlast,nhist,unclimit,edptmp,edep,edep2 common /scovdd/ edptmp(maxvox),edep(maxvox),edep2(maxvox), & nlast(maxvox),unclimit,nhist, & xvoxmin,xvoxmax,yvoxmin,yvoxmax,zvoxmin,zvoxmax, & prtxyz,prtdens,active character*(*) secid,eos parameter (secid= &'[SECTION TALLY VOXEL DOSE v.2008-06-01]') parameter (eos='[END OF VDD SECTION]') character*80 buffer integer error,answer integer*4 vox,dk,djk,i,j,k real*8 volvox write(*,*) write(*,'(a)') & '>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>' call getline(buffer) if (index(buffer,secid).eq.0) then write(*,'(a)') 'VDDinitally:ERROR: incorrect section header;' write(*,'(a,a)') ' expecting to find: ',secid write(*,'(a,a)') ' found instead: ',buffer stop endif write(*,'(a)') secid read(*,'(1x,a3)') buffer if (adjustl(buffer(1:3)).eq.'ON') then if (bodymask.ne.-1) then ! Voxel geometry is ON active = .true. else active = .false. write(*,'(a)') & 'Voxel Dose tally switch was ON but no voxels are defined' write(*,'(a)') & 'so the switch has been turned OFF automatically.' endif else if (buffer(1:3).eq.'OFF') then active = .false. else write(*,'(a)') & 'VDDinitally:ERROR: expecting to find ON or OFF' write(*,'(a)') 'found instead:' write(*,'(a)') buffer(1:3) stop endif if (active) then write(*,'(a)') 'Region Of Interest set to:' read(*,*) xvoxmin,xvoxmax xvoxmin = max(1,xvoxmin) xvoxmax = min(nx,xvoxmax) if (xvoxmax.eq.0) xvoxmax = nx write(*,'(a,2(2x,i0))') ' x-voxel interval: ',xvoxmin,xvoxmax read(*,*) yvoxmin,yvoxmax yvoxmin = max(1,yvoxmin) yvoxmax = min(ny,yvoxmax) if (yvoxmax.eq.0) yvoxmax = ny write(*,'(a,2(2x,i0))') ' y-voxel interval: ',yvoxmin,yvoxmax read(*,*) zvoxmin, zvoxmax zvoxmin = max(1,zvoxmin) zvoxmax = min(nz,zvoxmax) if (zvoxmax.eq.0) zvoxmax = nz write(*,'(a,2(2x,i0))') ' z-voxel interval: ',zvoxmin,zvoxmax write(*,'(a)') 'Partial volume policy:' read(*,*) answer select case(answer) case(0) isFullvol = .false. write(*,'(a)') & ' Voxels mass and doses EXCLUDE overlapping quadrics.' case(1) isFullvol = .true. write(*,'(a)') & ' Voxels mass and doses INCLUDE overlapping quadrics.' case default write(*,'(a)') 'VDDinitally:ERROR: expecting 0 or 1.' stop end select write(*,'(a)') 'Print voxels mass:' read(*,*) prtdens if (prtdens.eq.1) then write(*,'(a)') ' yes' else write(*,'(a)') ' no' endif write(*,'(a)') 'Print coordinates:' read(*,*) prtxyz if (prtxyz.eq.1) then write(*,'(a)') ' yes' else write(*,'(a)') ' no' endif write(*,'(a)') 'Relative uncertainty (%) requested:' read(*,*) unclimit write(*,'(es12.5)') unclimit ! Check section integrity: read(*,'(a80)') buffer if (index(buffer,eos).eq.0) then write(*,'(a)') 'inivox ERROR: End-Of-Section mark not found' write(*,'(a,a)') ' expecting to find: ',eos write(*,'(a,a)') ' found instead: ',buffer stop endif else ! Tally is inactive isFullvol = .false. ! (in case voxels mass are computed) endif ! Init counters, compute voxels mass and sign: ! (if tally is inactive, only voxels sign matter) if (bodymask.ne.-1) then ! Voxel geometry is ON write(*,'(a)') 'Computing voxels mass...' volvox = dx*dy*dz ! Voxels volume do k=1,nz ! For all voxels dk = (k-1)*nxy do j=1,ny djk = (j-1)*nx+dk do i=1,nx vox = i+djk ! Absolute voxel index edptmp(vox) = 0.0d0 ! Init deposited energy arrays edep(vox) = 0.0d0 edep2(vox) = 0.0d0 nlast(vox) = 0.0d0 if (isQuad) then ! Quadrics present, init mass to nil massvox(vox) = 0.0d0 else ! No quadrics, compute mass as vol*dens massvox(vox) = volvox*densvox(vox) endif enddo enddo enddo if (isQuad) then ! Quadrics present call setMassvox ! Compute mass and set (-) matvox's !! call writeMassvox ! Write voxels mass and sign to a file endif ! (reserved for future versions) ! Redefine voxels density, normalizing by nominal mat density: do k=1,nz ! For all voxels dk = (k-1)*nxy do j=1,ny djk = (j-1)*nx+dk do i=1,nx vox = i+djk densvox(vox) = densvox(vox)/rho(abs(matvox(vox))) idensvox(vox) = 1.0/densvox(vox) enddo enddo enddo write(*,'(a)') 'Done.' endif if (active) then write(*,'(a)') '>>>> VDD tally initialization finished >>>>' else write(*, '(a)') & '>>>> Tally Voxel Dose Distribution is OFF >>>>' do read(*,'(a80)',iostat=error) buffer if (error.ne.0) then write(*,'(a,a,a)') 'VDDinitally:ERROR: ', & 'Unable to find End-Of-Section mark: ',eos stop endif if (index(buffer,eos).ne.0) return enddo endif end subroutine setMassvox !******************************************************************* !* Computes the mass of all voxels by integrating density over * !* volume, taking into account whether the mode is fullvol or * !* not. It also sets the sign of the voxel material, depending * !* on whether the voxel is pure (+) or overlapped (-). * !******************************************************************* implicit none integer*4 kpar,ibody,mat,ilb real*8 e,x,y,z,u,v,w,wght common/track/e,x,y,z,u,v,w,wght,kpar,ibody,mat,ilb(5) integer*4 iz,nelem,maxmat parameter (maxmat=10) real*8 stf,zt,at,rho,vmol common/compos/stf(maxmat,30),zt(maxmat),at(maxmat),rho(maxmat), & vmol(maxmat),iz(maxmat,30),nelem(maxmat) character*80 voxfilen logical isFullvol integer matvox,granul,maxGranul parameter (maxGranul=1000) integer*4 nx,ny,nz,nxy,maxvox,bodymask,matmask parameter (maxvox=10000000) ! Max no. of voxels real densvox,idensvox real*8 massvox,dx,dy,dz,idx,idy,idz,vbb common /geovox/ massvox(maxvox),densvox(maxvox),idensvox(maxvox), & matvox(maxvox),dx,dy,dz,idx,idy,idz,vbb(3),nx,ny,nz,nxy, & bodymask,matmask,granul,isFullvol,voxfilen integer*4 xvox,yvox,zvox,i,j,vox integer*4 voxIni,zvoxIni,zvoxFin,ncross,matold real*8 da(maxGranul,maxGranul),xg(maxGranul),yg(maxGranul) real*8 darea,zinf,xIni,yIni,zIni,dist,dsef,shift,delta,eps,oneeps parameter (delta=0.01d0) ! A small fraction of unity parameter (eps=1.0d-10,oneeps=1.0d0+1.0d-12) ! From PENGEOM darea = dx*dy/(granul-1)**2 ! Area of cells in which voxels area subdivided ! Set grid points and weights to sweep a voxel according to GRANUL: do j=1,granul do i=1,granul da(i,j) = darea enddo enddo do i=1,granul xg(i) = (i-1)*dx/(granul-1) da(i,1) = da(i,1)*0.5d0 da(i,granul) = da(i,granul)*0.5d0 ! Halve weights enddo do j=1,granul yg(j) = (j-1)*dy/(granul-1) da(1,j) = da(1,j)*0.5d0 da(granul,j) = da(granul,j)*0.5d0 ! Halve weights enddo ! Shift sides: shift = delta*dx/(granul-1) xg(1) = shift xg(granul) = dx-shift shift = delta*dy/(granul-1) yg(1) = shift yg(granul) = dy-shift ! ...Note that corners are shifted both in x and y and their areas halved twice zinf = 1.01d0*nz*dz ! Practical infinity (>VBB in z) avoids overflows u = 0.0d0 v = 0.0d0 w = 1.0d0 ! Pointing upwards do yvox=1,ny ! For each voxel yIni = (yvox-1)*dy ! Coordinates of the voxel corner do xvox=1,nx xIni = (xvox-1)*dx voxIni = xvox+(yvox-1)*nx ! Absolute voxel index for this column do j=1,granul ! For each ray (i.e. each cell) in a voxel do i=1,granul darea = da(i,j) ! dArea to compute voxel mass x = xIni+xg(i) ! Coordinates of the {x,y} ray y = yIni+yg(j) z = 0.0d0 ! Initial z on the VBB call locate ! Set ibody and mat zvoxIni = 1 ! Initial z index for this ray vox = voxIni ! Init voxel index for this ray zIni = z ! First raystep position raystep: do ! For each step in a ray matold = mat ! Save current mat to compute vox mass z = zIni ! Set start of next step for STEP to work call step(zinf,dsef,ncross) ! Compute next step of current ray if (mat.eq.0) then ! Gone, last step if (matold.eq.0) then ! From vac to vac, no matter z = +zinf ! Set z to practical infinity else z = zIni+oneeps*dsef+eps ! Reposition in close vacuum endif else if (ncross.gt.1) then ! Matter after vaccum gap z = zIni+oneeps*dsef+eps ! Reposition inside vac gap endif zvoxFin = int(z*idz+1.0d0) ! Final voxel of the current step do zvox=max(1,zvoxIni),min(nz,zvoxFin) ! For each visited voxel along z ! Compute distance travelled inside this voxel: dist = dz ! For a whole voxel if (zvox.eq.zvoxIni) dist = dist-zIni+(zvox-1)*dz ! Correct start-of-step if (zvox.eq.zvoxFin) dist = dist+z-zvox*dz ! Correct end-of-step ! Compute mass and mark overlapped voxels: if (matold.eq.matmask) then ! Moved inside voxels massvox(vox) = massvox(vox)+darea*dist*densvox(vox) else ! Moved in quadric geometry matvox(vox) = -abs(matvox(vox)) ! Mark voxels as overlapped if (matold.gt.0.and.isFullvol) ! Protect vacuum and partial vol. & massvox(vox) = massvox(vox)+darea*dist*rho(matold) endif vox = vox+nxy ! Move one voxel up along z enddo vox = vox-nxy ! Move 'pointer' back to last voxel zIni = z ! Update next step initial position zvoxIni = zvoxFin ! Update next step initial index if (zvoxIni.gt.nz) exit raystep ! All voxels along this ray have been completed enddo raystep ! Cycle next step enddo enddo enddo enddo end subroutine writeMassvox !******************************************************************* !* Writes voxels mass and sign to an external file for reference* !* * !* Comments: * !* -> Currently unused, awaiting for future versions that would * !* allow to load the mass file instead of recalculating them.* !******************************************************************* implicit none character*80 voxfilen logical isFullvol integer matvox,granul,maxGranul parameter (maxGranul=1000) integer*4 nx,ny,nz,nxy,maxvox,bodymask,matmask parameter (maxvox=10000000) ! Max no. of voxels real densvox,idensvox real*8 massvox,dx,dy,dz,idx,idy,idz,vbb common /geovox/ massvox(maxvox),densvox(maxvox),idensvox(maxvox), & matvox(maxvox),dx,dy,dz,idx,idy,idz,vbb(3),nx,ny,nz,nxy, & bodymask,matmask,granul,isFullvol,voxfilen character*90 buffer integer ufile,finduf,error integer*4 vox,i,j,k,dk,djk buffer = trim(voxfilen)//'.mass' ufile = finduf() ! Find a valid unit file open(ufile,file=buffer,iostat=error) if (error.ne.0) then write(*,'(a,a)') 'writeMassvox:ERROR: unable to open file: ', & buffer stop endif write(ufile,'(a,a)') & '# This file was automatically created by penEasy from '// & 'the voxels file named: ',trim(voxfilen) write(ufile,'(a)') & '# It contains the list of voxels mass (in g) with sign,' write(ufile,'(a)') & '# (+) for pure voxels and (-) for voxels overlapped '// & 'by a quadric body.' if (isFullvol) then write(ufile,'(a)') & '# The voxels mass INCLUDES the volume covered by quadrics.' else write(ufile,'(a)') & '# The voxels mass EXCLUDES the volume covered by quadrics.' endif write(ufile,'(a)') & '# This file is for your information; '// & 'it can be deleted at any time.' write(ufile,'(a,i0)') & '# The granularity used to compute the mass was: ',granul write(ufile,'(a)') '#' ! Write data to file: do k=1,nz write(ufile,'(a,i0)') '# zVoxIndex=',k dk = (k-1)*nxy do j=1,ny write(ufile,'(a,i0)') '# yVoxIndex=',j djk = (j-1)*nx+dk do i=1,nx vox = i+djk write(ufile,'(es12.5)') sign(massvox(vox),dble(matvox(vox))) enddo if (nx.gt.1) write(ufile,*) '' ! Separate 2D data blocks enddo if (ny.gt.1) write(ufile,*) '' ! Separate 3D data blocks enddo close(ufile) end !>>>> End Of File >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
Fortran Free Form
import pyfits import numpy as np imgname = '../data/VCC1043_k_sig.fits' img = pyfits.getdata(imgname) h = pyfits.getheader(imgname) img2 = (1./img)**2 print len(img2) hdr = h.copy() filename = '../data/VCC1043_k_weight.fits' pyfits.writeto(filename, img2, hdr) pyfits.append(imgname, img2, hdr) #pyfits.update(filename, img2, hdr, ext)
Python
# Makefile for Sphinx documentation # # You can set these variables from the command line. SPHINXOPTS = SPHINXBUILD = sphinx-build PAPER = BUILDDIR = _build # User-friendly check for sphinx-build ifeq ($(shell which $(SPHINXBUILD) >/dev/null 2>&1; echo $$?), 1) $(error The '$(SPHINXBUILD)' command was not found. Make sure you have Sphinx installed, then set the SPHINXBUILD environment variable to point to the full path of the '$(SPHINXBUILD)' executable. Alternatively you can add the directory with the executable to your PATH. If you don't have Sphinx installed, grab it from http://sphinx-doc.org/) endif # Internal variables. PAPEROPT_a4 = -D latex_paper_size=a4 PAPEROPT_letter = -D latex_paper_size=letter ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . # the i18n builder cannot share the environment and doctrees with the others I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . .PHONY: help help: @echo "Please use \`make <target>' where <target> is one of" @echo " html to make standalone HTML files" @echo " dirhtml to make HTML files named index.html in directories" @echo " singlehtml to make a single large HTML file" @echo " pickle to make pickle files" @echo " json to make JSON files" @echo " htmlhelp to make HTML files and a HTML help project" @echo " qthelp to make HTML files and a qthelp project" @echo " applehelp to make an Apple Help Book" @echo " devhelp to make HTML files and a Devhelp project" @echo " epub to make an epub" @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" @echo " latexpdf to make LaTeX files and run them through pdflatex" @echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx" @echo " text to make text files" @echo " man to make manual pages" @echo " texinfo to make Texinfo files" @echo " info to make Texinfo files and run them through makeinfo" @echo " gettext to make PO message catalogs" @echo " changes to make an overview of all changed/added/deprecated items" @echo " xml to make Docutils-native XML files" @echo " pseudoxml to make pseudoxml-XML files for display purposes" @echo " linkcheck to check all external links for integrity" @echo " doctest to run all doctests embedded in the documentation (if enabled)" @echo " coverage to run coverage check of the documentation (if enabled)" .PHONY: clean clean: rm -rf $(BUILDDIR)/* .PHONY: html html: $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." .PHONY: dirhtml dirhtml: $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." .PHONY: singlehtml singlehtml: $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml @echo @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." .PHONY: pickle pickle: $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle @echo @echo "Build finished; now you can process the pickle files." .PHONY: json json: $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json @echo @echo "Build finished; now you can process the JSON files." .PHONY: htmlhelp htmlhelp: $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp @echo @echo "Build finished; now you can run HTML Help Workshop with the" \ ".hhp project file in $(BUILDDIR)/htmlhelp." .PHONY: qthelp qthelp: $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp @echo @echo "Build finished; now you can run "qcollectiongenerator" with the" \ ".qhcp project file in $(BUILDDIR)/qthelp, like this:" @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/ral_nlls.qhcp" @echo "To view the help file:" @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/ral_nlls.qhc" .PHONY: applehelp applehelp: $(SPHINXBUILD) -b applehelp $(ALLSPHINXOPTS) $(BUILDDIR)/applehelp @echo @echo "Build finished. The help book is in $(BUILDDIR)/applehelp." @echo "N.B. You won't be able to view it unless you put it in" \ "~/Library/Documentation/Help or install it in your application" \ "bundle." .PHONY: devhelp devhelp: $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp @echo @echo "Build finished." @echo "To view the help file:" @echo "# mkdir -p $$HOME/.local/share/devhelp/ral_nlls" @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/ral_nlls" @echo "# devhelp" .PHONY: epub epub: $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub @echo @echo "Build finished. The epub file is in $(BUILDDIR)/epub." .PHONY: latex latex: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." @echo "Run \`make' in that directory to run these through (pdf)latex" \ "(use \`make latexpdf' here to do that automatically)." .PHONY: latexpdf latexpdf: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo "Running LaTeX files through pdflatex..." $(MAKE) -C $(BUILDDIR)/latex all-pdf @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." .PHONY: latexpdfja latexpdfja: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo "Running LaTeX files through platex and dvipdfmx..." $(MAKE) -C $(BUILDDIR)/latex all-pdf-ja @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." .PHONY: text text: $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text @echo @echo "Build finished. The text files are in $(BUILDDIR)/text." .PHONY: man man: $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man @echo @echo "Build finished. The manual pages are in $(BUILDDIR)/man." .PHONY: texinfo texinfo: $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo @echo @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." @echo "Run \`make' in that directory to run these through makeinfo" \ "(use \`make info' here to do that automatically)." .PHONY: info info: $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo @echo "Running Texinfo files through makeinfo..." make -C $(BUILDDIR)/texinfo info @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." .PHONY: gettext gettext: $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale @echo @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." .PHONY: changes changes: $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes @echo @echo "The overview file is in $(BUILDDIR)/changes." .PHONY: linkcheck linkcheck: $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck @echo @echo "Link check complete; look for any errors in the above output " \ "or in $(BUILDDIR)/linkcheck/output.txt." .PHONY: doctest doctest: $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest @echo "Testing of doctests in the sources finished, look at the " \ "results in $(BUILDDIR)/doctest/output.txt." .PHONY: coverage coverage: $(SPHINXBUILD) -b coverage $(ALLSPHINXOPTS) $(BUILDDIR)/coverage @echo "Testing of coverage in the sources finished, look at the " \ "results in $(BUILDDIR)/coverage/python.txt." .PHONY: xml xml: $(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml @echo @echo "Build finished. The XML files are in $(BUILDDIR)/xml." .PHONY: pseudoxml pseudoxml: $(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml @echo @echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml."
Makefile
using Documenter, Feynman makedocs( modules = [Feynman], sitename = "Feynman.jl", pages = Any[ "Home" => "index.md", "API" => "api.md", ], ) deploydocs( repo = "github.com/bhgomes/Feynman.jl.git", target = "build", )
Julia
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Copyright by The HDF Group. * * Copyright by the Board of Trustees of the University of Illinois. * * All rights reserved. * * * * This file is part of HDF5. The full HDF5 copyright notice, including * * terms governing use, modification, and redistribution, is contained in * * the files COPYING and Copyright.html. COPYING can be found at the root * * of the source code distribution tree; Copyright.html can be found at the * * root level of an installed copy of the electronic HDF5 document set and * * is linked from the top-level documents page. It can also be found at * * http://hdfgroup.org/HDF5/doc/Copyright.html. If you do not have * * access to either file, you may request a copy from help@hdfgroup.org. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ #include <string> #include "H5Include.h" #include "H5Exception.h" #include "H5IdComponent.h" #include "H5PropList.h" #include "H5Object.h" #include "H5DcreatProp.h" #include "H5CommonFG.h" #include "H5DataType.h" #include "H5AtomType.h" #include "H5Library.h" #include "H5PredType.h" #ifndef H5_NO_NAMESPACE namespace H5 { #endif #ifndef DOXYGEN_SHOULD_SKIP_THIS //-------------------------------------------------------------------------- // Function: PredType overloaded constructor ///\brief Creates a PredType object using the id of an existing /// predefined datatype. ///\param predtype_id - IN: Id of a predefined datatype // Description // This constructor creates a PredType object by copying // the provided HDF5 predefined datatype. // Programmer Binh-Minh Ribler - 2000 //-------------------------------------------------------------------------- PredType::PredType( const hid_t predtype_id ) : AtomType( predtype_id ) { id = H5Tcopy(predtype_id); } //-------------------------------------------------------------------------- // Function: PredType default constructor ///\brief Default constructor: Creates a stub predefined datatype // Programmer Binh-Minh Ribler - 2000 //-------------------------------------------------------------------------- PredType::PredType() : AtomType() {} //-------------------------------------------------------------------------- // Function: PredType copy constructor ///\brief Copy constructor: makes a copy of the original PredType object. ///\param original - IN: PredType instance to copy // Programmer Binh-Minh Ribler - 2000 //-------------------------------------------------------------------------- PredType::PredType( const PredType& original ) : AtomType( original ) {} const PredType PredType::NotAtexit; // only for atexit/global dest. problem // Definition of pre-defined types const PredType PredType::C_S1( H5T_C_S1 ); const PredType PredType::FORTRAN_S1( H5T_FORTRAN_S1 ); const PredType PredType::STD_I8BE( H5T_STD_I8BE ); const PredType PredType::STD_I8LE( H5T_STD_I8LE ); const PredType PredType::STD_I16BE( H5T_STD_I16BE ); const PredType PredType::STD_I16LE( H5T_STD_I16LE ); const PredType PredType::STD_I32BE( H5T_STD_I32BE ); const PredType PredType::STD_I32LE( H5T_STD_I32LE ); const PredType PredType::STD_I64BE( H5T_STD_I64BE ); const PredType PredType::STD_I64LE( H5T_STD_I64LE ); const PredType PredType::STD_U8BE( H5T_STD_U8BE ); const PredType PredType::STD_U8LE( H5T_STD_U8LE ); const PredType PredType::STD_U16BE( H5T_STD_U16BE ); const PredType PredType::STD_U16LE( H5T_STD_U16LE ); const PredType PredType::STD_U32BE( H5T_STD_U32BE ); const PredType PredType::STD_U32LE( H5T_STD_U32LE ); const PredType PredType::STD_U64BE( H5T_STD_U64BE ); const PredType PredType::STD_U64LE( H5T_STD_U64LE ); const PredType PredType::STD_B8BE( H5T_STD_B8BE ); const PredType PredType::STD_B8LE( H5T_STD_B8LE ); const PredType PredType::STD_B16BE( H5T_STD_B16BE ); const PredType PredType::STD_B16LE( H5T_STD_B16LE ); const PredType PredType::STD_B32BE( H5T_STD_B32BE ); const PredType PredType::STD_B32LE( H5T_STD_B32LE ); const PredType PredType::STD_B64BE( H5T_STD_B64BE ); const PredType PredType::STD_B64LE( H5T_STD_B64LE ); const PredType PredType::STD_REF_OBJ( H5T_STD_REF_OBJ ); const PredType PredType::STD_REF_DSETREG( H5T_STD_REF_DSETREG ); const PredType PredType::IEEE_F32BE( H5T_IEEE_F32BE ); const PredType PredType::IEEE_F32LE( H5T_IEEE_F32LE ); const PredType PredType::IEEE_F64BE( H5T_IEEE_F64BE ); const PredType PredType::IEEE_F64LE( H5T_IEEE_F64LE ); const PredType PredType::UNIX_D32BE( H5T_UNIX_D32BE ); const PredType PredType::UNIX_D32LE( H5T_UNIX_D32LE ); const PredType PredType::UNIX_D64BE( H5T_UNIX_D64BE ); const PredType PredType::UNIX_D64LE( H5T_UNIX_D64LE ); const PredType PredType::INTEL_I8( H5T_INTEL_I8 ); const PredType PredType::INTEL_I16( H5T_INTEL_I16 ); const PredType PredType::INTEL_I32( H5T_INTEL_I32 ); const PredType PredType::INTEL_I64( H5T_INTEL_I64 ); const PredType PredType::INTEL_U8( H5T_INTEL_U8 ); const PredType PredType::INTEL_U16( H5T_INTEL_U16 ); const PredType PredType::INTEL_U32( H5T_INTEL_U32 ); const PredType PredType::INTEL_U64( H5T_INTEL_U64 ); const PredType PredType::INTEL_B8( H5T_INTEL_B8 ); const PredType PredType::INTEL_B16( H5T_INTEL_B16 ); const PredType PredType::INTEL_B32( H5T_INTEL_B32 ); const PredType PredType::INTEL_B64( H5T_INTEL_B64 ); const PredType PredType::INTEL_F32( H5T_INTEL_F32 ); const PredType PredType::INTEL_F64( H5T_INTEL_F64 ); const PredType PredType::ALPHA_I8( H5T_ALPHA_I8 ); const PredType PredType::ALPHA_I16( H5T_ALPHA_I16 ); const PredType PredType::ALPHA_I32( H5T_ALPHA_I32 ); const PredType PredType::ALPHA_I64( H5T_ALPHA_I64 ); const PredType PredType::ALPHA_U8( H5T_ALPHA_U8 ); const PredType PredType::ALPHA_U16( H5T_ALPHA_U16 ); const PredType PredType::ALPHA_U32( H5T_ALPHA_U32 ); const PredType PredType::ALPHA_U64( H5T_ALPHA_U64 ); const PredType PredType::ALPHA_B8( H5T_ALPHA_B8 ); const PredType PredType::ALPHA_B16( H5T_ALPHA_B16 ); const PredType PredType::ALPHA_B32( H5T_ALPHA_B32 ); const PredType PredType::ALPHA_B64( H5T_ALPHA_B64 ); const PredType PredType::ALPHA_F32( H5T_ALPHA_F32 ); const PredType PredType::ALPHA_F64( H5T_ALPHA_F64 ); const PredType PredType::MIPS_I8( H5T_MIPS_I8 ); const PredType PredType::MIPS_I16( H5T_MIPS_I16 ); const PredType PredType::MIPS_I32( H5T_MIPS_I32 ); const PredType PredType::MIPS_I64( H5T_MIPS_I64 ); const PredType PredType::MIPS_U8( H5T_MIPS_U8 ); const PredType PredType::MIPS_U16( H5T_MIPS_U16 ); const PredType PredType::MIPS_U32( H5T_MIPS_U32 ); const PredType PredType::MIPS_U64( H5T_MIPS_U64 ); const PredType PredType::MIPS_B8( H5T_MIPS_B8 ); const PredType PredType::MIPS_B16( H5T_MIPS_B16 ); const PredType PredType::MIPS_B32( H5T_MIPS_B32 ); const PredType PredType::MIPS_B64( H5T_MIPS_B64 ); const PredType PredType::MIPS_F32( H5T_MIPS_F32 ); const PredType PredType::MIPS_F64( H5T_MIPS_F64 ); const PredType PredType::NATIVE_CHAR( H5T_NATIVE_CHAR ); const PredType PredType::NATIVE_INT( H5T_NATIVE_INT ); const PredType PredType::NATIVE_FLOAT( H5T_NATIVE_FLOAT ); const PredType PredType::NATIVE_SCHAR( H5T_NATIVE_SCHAR ); const PredType PredType::NATIVE_UCHAR( H5T_NATIVE_UCHAR ); const PredType PredType::NATIVE_SHORT( H5T_NATIVE_SHORT ); const PredType PredType::NATIVE_USHORT( H5T_NATIVE_USHORT ); const PredType PredType::NATIVE_UINT( H5T_NATIVE_UINT ); const PredType PredType::NATIVE_LONG( H5T_NATIVE_LONG ); const PredType PredType::NATIVE_ULONG( H5T_NATIVE_ULONG ); const PredType PredType::NATIVE_LLONG( H5T_NATIVE_LLONG ); const PredType PredType::NATIVE_ULLONG( H5T_NATIVE_ULLONG ); const PredType PredType::NATIVE_DOUBLE( H5T_NATIVE_DOUBLE ); #if H5_SIZEOF_LONG_DOUBLE !=0 const PredType PredType::NATIVE_LDOUBLE( H5T_NATIVE_LDOUBLE ); #endif const PredType PredType::NATIVE_B8( H5T_NATIVE_B8 ); const PredType PredType::NATIVE_B16( H5T_NATIVE_B16 ); const PredType PredType::NATIVE_B32( H5T_NATIVE_B32 ); const PredType PredType::NATIVE_B64( H5T_NATIVE_B64 ); const PredType PredType::NATIVE_OPAQUE( H5T_NATIVE_OPAQUE ); const PredType PredType::NATIVE_HSIZE( H5T_NATIVE_HSIZE ); const PredType PredType::NATIVE_HSSIZE( H5T_NATIVE_HSSIZE ); const PredType PredType::NATIVE_HERR( H5T_NATIVE_HERR ); const PredType PredType::NATIVE_HBOOL( H5T_NATIVE_HBOOL ); const PredType PredType::NATIVE_INT8( H5T_NATIVE_INT8 ); const PredType PredType::NATIVE_UINT8( H5T_NATIVE_UINT8 ); const PredType PredType::NATIVE_INT16( H5T_NATIVE_INT16 ); const PredType PredType::NATIVE_UINT16( H5T_NATIVE_UINT16 ); const PredType PredType::NATIVE_INT32( H5T_NATIVE_INT32 ); const PredType PredType::NATIVE_UINT32( H5T_NATIVE_UINT32 ); const PredType PredType::NATIVE_INT64( H5T_NATIVE_INT64 ); const PredType PredType::NATIVE_UINT64( H5T_NATIVE_UINT64 ); // LEAST types #if H5_SIZEOF_INT_LEAST8_T != 0 const PredType PredType::NATIVE_INT_LEAST8( H5T_NATIVE_INT_LEAST8 ); #endif /* H5_SIZEOF_INT_LEAST8_T */ #if H5_SIZEOF_UINT_LEAST8_T != 0 const PredType PredType::NATIVE_UINT_LEAST8( H5T_NATIVE_UINT_LEAST8 ); #endif /* H5_SIZEOF_UINT_LEAST8_T */ #if H5_SIZEOF_INT_LEAST16_T != 0 const PredType PredType::NATIVE_INT_LEAST16( H5T_NATIVE_INT_LEAST16 ); #endif /* H5_SIZEOF_INT_LEAST16_T */ #if H5_SIZEOF_UINT_LEAST16_T != 0 const PredType PredType::NATIVE_UINT_LEAST16( H5T_NATIVE_UINT_LEAST16 ); #endif /* H5_SIZEOF_UINT_LEAST16_T */ #if H5_SIZEOF_INT_LEAST32_T != 0 const PredType PredType::NATIVE_INT_LEAST32( H5T_NATIVE_INT_LEAST32 ); #endif /* H5_SIZEOF_INT_LEAST32_T */ #if H5_SIZEOF_UINT_LEAST32_T != 0 const PredType PredType::NATIVE_UINT_LEAST32( H5T_NATIVE_UINT_LEAST32 ); #endif /* H5_SIZEOF_UINT_LEAST32_T */ #if H5_SIZEOF_INT_LEAST64_T != 0 const PredType PredType::NATIVE_INT_LEAST64( H5T_NATIVE_INT_LEAST64 ); #endif /* H5_SIZEOF_INT_LEAST64_T */ #if H5_SIZEOF_UINT_LEAST64_T != 0 const PredType PredType::NATIVE_UINT_LEAST64( H5T_NATIVE_UINT_LEAST64 ); #endif /* H5_SIZEOF_UINT_LEAST64_T */ // FAST types #if H5_SIZEOF_INT_FAST8_T != 0 const PredType PredType::NATIVE_INT_FAST8( H5T_NATIVE_INT_FAST8 ); #endif /* H5_SIZEOF_INT_FAST8_T */ #if H5_SIZEOF_UINT_FAST8_T != 0 const PredType PredType::NATIVE_UINT_FAST8( H5T_NATIVE_UINT_FAST8 ); #endif /* H5_SIZEOF_UINT_FAST8_T */ #if H5_SIZEOF_INT_FAST16_T != 0 const PredType PredType::NATIVE_INT_FAST16( H5T_NATIVE_INT_FAST16 ); #endif /* H5_SIZEOF_INT_FAST16_T */ #if H5_SIZEOF_UINT_FAST16_T != 0 const PredType PredType::NATIVE_UINT_FAST16( H5T_NATIVE_UINT_FAST16 ); #endif /* H5_SIZEOF_UINT_FAST16_T */ #if H5_SIZEOF_INT_FAST32_T != 0 const PredType PredType::NATIVE_INT_FAST32( H5T_NATIVE_INT_FAST32 ); #endif /* H5_SIZEOF_INT_FAST32_T */ #if H5_SIZEOF_UINT_FAST32_T != 0 const PredType PredType::NATIVE_UINT_FAST32( H5T_NATIVE_UINT_FAST32 ); #endif /* H5_SIZEOF_UINT_FAST32_T */ #if H5_SIZEOF_INT_FAST64_T != 0 const PredType PredType::NATIVE_INT_FAST64( H5T_NATIVE_INT_FAST64 ); #endif /* H5_SIZEOF_INT_FAST64_T */ #if H5_SIZEOF_UINT_FAST64_T != 0 const PredType PredType::NATIVE_UINT_FAST64( H5T_NATIVE_UINT_FAST64 ); #endif /* H5_SIZEOF_UINT_FAST64_T */ #endif // DOXYGEN_SHOULD_SKIP_THIS //-------------------------------------------------------------------------- // Function: PredType::operator= ///\brief Assignment operator. ///\param rhs - IN: Reference to the predefined datatype ///\return Reference to PredType instance ///\exception H5::DataTypeIException // Description // Makes a copy of the type on the right hand side and stores // the new id in the left hand side object. // Programmer Binh-Minh Ribler - 2000 //-------------------------------------------------------------------------- PredType& PredType::operator=( const PredType& rhs ) { if (this != &rhs) copy(rhs); return(*this); } #ifndef DOXYGEN_SHOULD_SKIP_THIS // These dummy functions do not inherit from DataType - they'll // throw an DataTypeIException if invoked. void PredType::commit( H5File& loc, const char* name ) { throw DataTypeIException("PredType::commit", "Error: Attempted to commit a predefined datatype. Invalid operation!" ); } void PredType::commit( H5File& loc, const H5std_string& name ) { commit( loc, name.c_str()); } void PredType::commit( H5Object& loc, const char* name ) { throw DataTypeIException("PredType::commit", "Error: Attempted to commit a predefined datatype. Invalid operation!" ); } void PredType::commit( H5Object& loc, const H5std_string& name ) { commit( loc, name.c_str()); } bool PredType::committed() { throw DataTypeIException("PredType::committed", "Error: Attempting to check for commit status on a predefined datatype." ); } #endif // DOXYGEN_SHOULD_SKIP_THIS // Default destructor //-------------------------------------------------------------------------- // Function: PredType destructor ///\brief Noop destructor. // Programmer Binh-Minh Ribler - 2000 //-------------------------------------------------------------------------- PredType::~PredType() {} #ifndef H5_NO_NAMESPACE } // end namespace #endif
C++
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * * Contains some contributions under the Thrift Software License. * Please see doc/old-thrift-license.txt in the Thrift distribution for * details. */ using System; using System.IO; namespace Thrift.Transport { public abstract class TTransport : IDisposable { public abstract bool IsOpen { get; } private byte[] _peekBuffer = new byte[1]; private bool _hasPeekByte; public bool Peek() { //If we already have a byte read but not consumed, do nothing. if (_hasPeekByte) return true; //If transport closed we can't peek. if (!IsOpen) return false; //Try to read one byte. If succeeds we will need to store it for the next read. try { int bytes = Read(_peekBuffer, 0, 1); if (bytes == 0) return false; } catch (IOException) { return false; } _hasPeekByte = true; return true; } public abstract void Open(); public abstract void Close(); protected static void ValidateBufferArgs(byte[] buf, int off, int len) { if (buf == null) throw new ArgumentNullException("buf"); if (off < 0) throw new ArgumentOutOfRangeException("Buffer offset is smaller than zero."); if (len < 0) throw new ArgumentOutOfRangeException("Buffer length is smaller than zero."); if (off + len > buf.Length) throw new ArgumentOutOfRangeException("Not enough data."); } public abstract int Read(byte[] buf, int off, int len); public int ReadAll(byte[] buf, int off, int len) { ValidateBufferArgs(buf, off, len); int got = 0; //If we previously peeked a byte, we need to use that first. if (_hasPeekByte) { buf[off + got++] = _peekBuffer[0]; _hasPeekByte = false; } while (got < len) { int ret = Read(buf, off + got, len - got); if (ret <= 0) { throw new TTransportException( TTransportException.ExceptionType.EndOfFile, "Cannot read, Remote side has closed"); } got += ret; } return got; } public virtual void Write(byte[] buf) { Write(buf, 0, buf.Length); } public abstract void Write(byte[] buf, int off, int len); public virtual void Flush() { } public virtual IAsyncResult BeginFlush(AsyncCallback callback, object state) { throw new TTransportException( TTransportException.ExceptionType.Unknown, "Asynchronous operations are not supported by this transport."); } public virtual void EndFlush(IAsyncResult asyncResult) { throw new TTransportException( TTransportException.ExceptionType.Unknown, "Asynchronous operations are not supported by this transport."); } #region " IDisposable Support " // IDisposable protected abstract void Dispose(bool disposing); public void Dispose() { // Do not change this code. Put cleanup code in Dispose(ByVal disposing As Boolean) above. Dispose(true); GC.SuppressFinalize(this); } #endregion } }
C#
/*========================================================================================= File Name: vertical-content-menu.scss Description: A vertical style content menu with expand and collops support. It support light & dark version, filpped layout, right side icons, native scroll and borders menu item seperation. ---------------------------------------------------------------------------------------- Item Name: Modern Admin - Clean Bootstrap 4 Dashboard HTML Template Version: 1.0 Author: PIXINVENT Author URL: http://www.themeforest.net/user/pixinvent ==========================================================================================*/ .vertical-content-menu.menu-expanded .navbar .navbar-header { float: left; width: 260px; } .vertical-content-menu.menu-expanded .navbar.navbar-brand-center .navbar-header { float: left; width: auto; } .vertical-content-menu.menu-expanded .navbar.navbar-brand-center .navbar-container { margin-left: 0; } .vertical-content-menu.menu-expanded .navbar .navbar-container { margin-left: 260px; } .vertical-content-menu.menu-expanded .main-menu { width: 260px; transition: 300ms ease all; backface-visibility: hidden; top: inherit; } .vertical-content-menu.menu-expanded .main-menu .navigation .navigation-header .ft-minus { display: none; } .vertical-content-menu.menu-expanded .main-menu .navigation > li > a > i { margin-right: 12px; float: left; } .vertical-content-menu.menu-expanded .main-menu .navigation > li > a > i:before { font-size: 1.4rem; } .vertical-content-menu.menu-expanded .main-menu .navigation > li > a > span { display: inline-block; } .vertical-content-menu.menu-expanded .main-menu .navigation > li > a > span.tag { position: absolute; right: 20px; } .vertical-content-menu.menu-expanded .main-menu .navigation li.has-sub > a:not(.mm-next):after { content: "\f112"; font-family: 'LineAwesome'; font-size: 1rem; display: inline-block; position: absolute; right: 20px; top: 14px; transform: rotate(0deg); transition: -webkit-transform 0.2s ease-in-out; } .vertical-content-menu.menu-expanded .main-menu .navigation li.has-sub .has-sub > a:not(.mm-next):after { top: 8px; } .vertical-content-menu.menu-expanded .main-menu .navigation li.open > a:not(.mm-next):after { transform: rotate(90deg); } .vertical-content-menu.menu-expanded .main-menu .main-menu-footer { width: 260px; } .vertical-content-menu.menu-expanded .content-body { margin-left: 288px; transition: 300ms ease all; } .vertical-content-menu.menu-expanded.menu-flipped .content-body { margin: 0; margin-right: 288px; transition: 300ms ease all; } @media (min-width: 576px) { .vertical-content-menu.menu-expanded.menu-flipped:not(.boxed-layout) .main-menu { right: 20px; } .vertical-content-menu.menu-expanded.menu-flipped.boxed-layout .main-menu { float: right; position: relative; } } .vertical-content-menu.menu-expanded.menu-flipped .navbar .navbar-header { float: right; } .vertical-content-menu.menu-expanded.menu-flipped .navbar .navbar-container { margin: 0; margin-right: 260px; } .vertical-content-menu.menu-collapsed .navbar .navbar-header { float: left; width: 260px; } .vertical-content-menu.menu-collapsed .navbar.navbar-brand-center .navbar-header { float: left; width: auto; } .vertical-content-menu.menu-collapsed .navbar.navbar-brand-center .navbar-container { margin-left: 0; } .vertical-content-menu.menu-collapsed .navbar .navbar-container { margin-left: 260px; } .vertical-content-menu.menu-collapsed .main-menu { width: 65px; transform: translateZ(-160px) translateX(-160px); transform: translate3d(0, 0, 0); transition: 300ms ease all; top: inherit; } .vertical-content-menu.menu-collapsed .main-menu .main-menu-header .user-content { padding: 20px 10px; } .vertical-content-menu.menu-collapsed .main-menu .main-menu-footer, .vertical-content-menu.menu-collapsed .main-menu .main-menu-header .media-body .media-heading, .vertical-content-menu.menu-collapsed .main-menu .main-menu-header .media-body .text-muted, .vertical-content-menu.menu-collapsed .main-menu .main-menu-header .media-right { display: none; } .vertical-content-menu.menu-collapsed .main-menu .main-menu-header .media-body { opacity: 0; } .vertical-content-menu.menu-collapsed .main-menu .main-menu-content > span.menu-title, .vertical-content-menu.menu-collapsed .main-menu .main-menu-content a.menu-title { right: -260px; width: 260px; font-weight: 600; color: #fff; text-transform: uppercase; text-align: left; background-color: #1E9FF2; border-color: #1E9FF2; padding: 14px 20px; } .vertical-content-menu.menu-collapsed .main-menu .main-menu-content > ul.menu-content { left: 65px; width: 260px; transition: visibility .25s,opacity .25s; box-shadow: 25px 5px 75px 2px rgba(64, 70, 74, 0.2); border-bottom: 1px solid rgba(0, 0, 0, 0.2); border-left: 1px solid rgba(0, 0, 0, 0.02); } .vertical-content-menu.menu-collapsed .main-menu .main-menu-content > ul.menu-content li { white-space: nowrap; position: relative; } .vertical-content-menu.menu-collapsed .main-menu .main-menu-content > ul.menu-content li a { display: block; padding: 8px 20px 8px 20px; transition: all 0.2s ease; } .vertical-content-menu.menu-collapsed .main-menu .main-menu-content > ul.menu-content li.has-sub > a:not(.mm-next):after { content: "\f112"; font-family: 'LineAwesome'; font-size: 1rem; display: inline-block; position: absolute; right: 20px; top: 14px; transform: rotate(0deg); transition: -webkit-transform 0.2s ease-in-out; } .vertical-content-menu.menu-collapsed .main-menu .main-menu-content > ul.menu-content li.has-sub .has-sub > a:not(.mm-next):after { top: 8px; } .vertical-content-menu.menu-collapsed .main-menu .main-menu-content > ul.menu-content li.open > a:not(.mm-next):after { transform: rotate(90deg); } .vertical-content-menu.menu-collapsed .main-menu .main-menu-content > ul.menu-content li:hover > a, .vertical-content-menu.menu-collapsed .main-menu .main-menu-content > ul.menu-content li.hover > a { transform: translateX(4px); } .vertical-content-menu.menu-collapsed .main-menu .main-menu-content > ul.menu-content li:hover > a > a, .vertical-content-menu.menu-collapsed .main-menu .main-menu-content > ul.menu-content li.hover > a > a { transform: translateX(-4px); } .vertical-content-menu.menu-collapsed .main-menu .navigation { overflow: visible; } .vertical-content-menu.menu-collapsed .main-menu .navigation > li.navigation-header { padding: 30px 20px 8px 20px; } .vertical-content-menu.menu-collapsed .main-menu .navigation > li.navigation-header .ft-minus { display: block; padding: 12px 0px; text-align: center; font-size: 1.6rem; } .vertical-content-menu.menu-collapsed .main-menu .navigation > li.navigation-header span { display: none; } .vertical-content-menu.menu-collapsed .main-menu .navigation > li > a { padding: 8px 20px; text-align: center; } .vertical-content-menu.menu-collapsed .main-menu .navigation > li > a > span { visibility: hidden; opacity: 0; position: absolute; top: 0; right: -260px; width: 260px; font-weight: 600; color: #fff; text-align: left; background-color: #666EE8; border-color: #666EE8; padding: 11px 20px; } .vertical-content-menu.menu-collapsed .main-menu .navigation > li > a > i { margin-right: 0; font-size: 1.4rem; visibility: visible; } .vertical-content-menu.menu-collapsed .main-menu .navigation > li > ul { display: none; } .vertical-content-menu.menu-collapsed .main-menu .navigation > li > a > span { display: none; } .vertical-content-menu.menu-collapsed .main-menu .mTSWrapper { overflow: visible; } .vertical-content-menu.menu-collapsed .content-body { margin-left: 90px; transition: 300ms ease all; } .vertical-content-menu.menu-collapsed.menu-flipped .content-body { margin-left: 0px; margin-right: 90px; transition: 300ms ease all; } @media (min-width: 576px) { .vertical-content-menu.menu-collapsed.menu-flipped:not(.boxed-layout) .main-menu { right: 1.5rem; } .vertical-content-menu.menu-collapsed.menu-flipped:not(.boxed-layout) .main-menu span.menu-title { right: 65px; } .vertical-content-menu.menu-collapsed.menu-flipped:not(.boxed-layout) .main-menu ul.menu-content { right: 65px; left: inherit; } .vertical-content-menu.menu-collapsed.menu-flipped.boxed-layout .main-menu { float: right; position: relative; } .vertical-content-menu.menu-collapsed.menu-flipped.boxed-layout span.menu-title { right: 65px; } .vertical-content-menu.menu-collapsed.menu-flipped.boxed-layout ul.menu-content { right: 65px; left: inherit; } } .vertical-content-menu.menu-collapsed.menu-flipped .navbar .navbar-header { float: right; } .vertical-content-menu.menu-collapsed.menu-flipped .navbar .navbar-container { margin: 0; margin-right: 260px; } .vertical-content-menu .navbar-brand-center .content, .vertical-content-menu .navbar-brand-center .footer { margin-left: 0; } .vertical-content-menu.boxed-layout.menu-flipped .main-men { float: right; position: relative; } [data-textdirection="rtl"] body.vertical-layout.vertical-content-menu.menu-collapsed .main-menu .navigation > li > a { padding: 12px 22px !important; } [data-textdirection="rtl"] body.vertical-layout.vertical-content-menu.menu-collapsed .main-menu .navigation > li.navigation-header .ft-minus { padding: 12px 0px; } @media (min-width: 992px) { body.vertical-content-menu .main-menu, body.vertical-content-menu .vertical-overlay-menu.menu-hide .main-menu, .vertical-overlay-menu.menu-hide body.vertical-content-menu .main-menu { width: 260px; } body.vertical-content-menu .navbar .navbar-header { width: 260px; } body.vertical-content-menu .content-body { margin-left: 288px; transition: 300ms ease all; } } @media (max-width: 991.98px) { body.vertical-content-menu .main-menu, body.vertical-content-menu .vertical-overlay-menu.menu-hide .main-menu, .vertical-overlay-menu.menu-hide body.vertical-content-menu .main-menu { width: 65px; } body.vertical-content-menu .navbar .navbar-header { width: 65px; } body.vertical-content-menu .content-body { margin-left: 90px; transition: 300ms ease all; } } @media (max-width: 767.98px) { body.vertical-content-menu .content-body { margin-left: 0; } } /*========================================================================================= File Name: vertical-overlay-menu.scss Description: A overlay style vertical menu with show and hide support. It support light & dark version, filpped layout, right side icons, native scroll and borders menu item seperation. ---------------------------------------------------------------------------------------- Item Name: Modern Admin - Clean Bootstrap 4 Dashboard HTML Template Version: 1.0 Author: PIXINVENT Author URL: http://www.themeforest.net/user/pixinvent ==========================================================================================*/ .vertical-overlay-menu .content { margin-left: 0; } .vertical-overlay-menu .navbar .navbar-header { float: left; width: 260px; } .vertical-overlay-menu .navbar.navbar-brand-center .navbar-container { margin-left: 0; } .vertical-overlay-menu .navbar.navbar-brand-center .navbar-header { float: left; width: auto; } .vertical-overlay-menu .main-menu, .vertical-overlay-menu.menu-hide .main-menu { opacity: 0; transform: translate3d(0, 0, 0); transition: width .25s,opacity .25s,transform .25s; width: 260px; left: -260px; } .vertical-overlay-menu .main-menu .navigation .navigation-header .ft-minus { display: none; } .vertical-overlay-menu .main-menu .navigation > li > a > i { font-size: 1.4rem; margin-right: 12px; float: left; } .vertical-overlay-menu .main-menu .navigation > li > a > i:before { transition: 200ms ease all; } .vertical-overlay-menu .main-menu .navigation li.has-sub > a:not(.mm-next):after, .vertical-overlay-menu.menu-hide .main-menu .navigation li.has-sub > a:not(.mm-next):after { content: "\f112"; font-family: 'LineAwesome'; font-size: 1rem; display: inline-block; position: absolute; right: 20px; top: 14px; transform: rotate(0deg); transition: -webkit-transform 0.2s ease-in-out; } .vertical-overlay-menu .main-menu .navigation li.has-sub .has-sub > a:not(.mm-next):after, .vertical-overlay-menu.menu-hide .main-menu .navigation li.has-sub .has-sub > a:not(.mm-next):after { top: 8px; } .vertical-overlay-menu .main-menu .navigation li.open > a:not(.mm-next):after, .vertical-overlay-menu.menu-hide .main-menu .navigation li.open > a:not(.mm-next):after { transform: rotate(90deg); } .vertical-overlay-menu .main-menu .main-menu-footer { bottom: 55px; } .vertical-overlay-menu .main-menu .main-menu-footer { width: 260px; } .vertical-overlay-menu.menu-open .main-menu { opacity: 1; transform: translate3d(260px, 0, 0); transition: width .25s,opacity .25s,transform .25s; } .vertical-overlay-menu.menu-flipped .main-menu { right: -260px; left: inherit; } .vertical-overlay-menu.menu-flipped .navbar .navbar-container { margin: 0; margin-right: 260px; } .vertical-overlay-menu.menu-flipped .navbar .navbar-header { float: right; } .vertical-overlay-menu.menu-flipped.menu-open .main-menu { transform: translate3d(-260px, 0, 0); } @media (max-width: 991.98px) { .vertical-overlay-menu .main-menu .main-menu-footer { bottom: 0px; } }
CSS
\input{tex/layout} \usepackage[chorded]{tex/songs} \usepackage[utf8]{inputenc} \usepackage[ngerman]{babel} \input{tex/font} \usepackage{pdfpages} \setlength{\songnumwidth}{4em} \songcolumns{1} \def\lmnumcols{1} \newindex{$(INH_NAME)}{$(INH_FILE)} \begin{document} \begin{songs}{$(INH_NAME)} \input{$(SONGS)} \end{songs} \showindex[2]{Inhaltsverzeichnis}{$(INH_NAME)} \end{document}
TeX
;;; spinner-autoloads.el --- automatically extracted autoloads ;; ;;; Code: (add-to-list 'load-path (or (file-name-directory #$) (car load-path))) ;;;### (autoloads nil "spinner" "spinner.el" (22368 29883 0 0)) ;;; Generated autoloads from spinner.el (autoload 'spinner-create "spinner" "\ Create a spinner of the given TYPE. The possible TYPEs are described in `spinner--type-to-frames'. FPS, if given, is the number of desired frames per second. Default is `spinner-frames-per-second'. If BUFFER-LOCAL is non-nil, the spinner will be automatically deactivated if the buffer is killed. If BUFFER-LOCAL is a buffer, use that instead of current buffer. When started, in order to function properly, the spinner runs a timer which periodically calls `force-mode-line-update' in the curent buffer. If BUFFER-LOCAL was set at creation time, then `force-mode-line-update' is called in that buffer instead. When the spinner is stopped, the timer is deactivated. DELAY, if given, is the number of seconds to wait after starting the spinner before actually displaying it. It is safe to cancel the spinner before this time, in which case it won't display at all. \(fn &optional TYPE BUFFER-LOCAL FPS DELAY)" nil nil) (autoload 'spinner-start "spinner" "\ Start a mode-line spinner of given TYPE-OR-OBJECT. If TYPE-OR-OBJECT is an object created with `make-spinner', simply activate it. This method is designed for minor modes, so they can use the spinner as part of their lighter by doing: '(:eval (spinner-print THE-SPINNER)) To stop this spinner, call `spinner-stop' on it. If TYPE-OR-OBJECT is anything else, a buffer-local spinner is created with this type, and it is displayed in the `mode-line-process' of the buffer it was created it. Both TYPE-OR-OBJECT and FPS are passed to `make-spinner' (which see). To stop this spinner, call `spinner-stop' in the same buffer. Either way, the return value is a function which can be called anywhere to stop this spinner. You can also call `spinner-stop' in the same buffer where the spinner was created. FPS, if given, is the number of desired frames per second. Default is `spinner-frames-per-second'. DELAY, if given, is the number of seconds to wait until actually displaying the spinner. It is safe to cancel the spinner before this time, in which case it won't display at all. \(fn &optional TYPE-OR-OBJECT FPS DELAY)" nil nil) ;;;*** ;; Local Variables: ;; version-control: never ;; no-byte-compile: t ;; no-update-autoloads: t ;; End: ;;; spinner-autoloads.el ends here
Common Lisp
/** * Autogenerated by Thrift Compiler (0.9.2) * * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING * @generated */ #include "SecondService.h" #include "thrift/async/TAsyncChannel.h" #include "SecondService.tcc" namespace thrift { namespace test { SecondService_blahBlah_args::~SecondService_blahBlah_args() throw() { } SecondService_blahBlah_pargs::~SecondService_blahBlah_pargs() throw() { } SecondService_blahBlah_result::~SecondService_blahBlah_result() throw() { } SecondService_blahBlah_presult::~SecondService_blahBlah_presult() throw() { } SecondService_secondtestString_args::~SecondService_secondtestString_args() throw() { } SecondService_secondtestString_pargs::~SecondService_secondtestString_pargs() throw() { } SecondService_secondtestString_result::~SecondService_secondtestString_result() throw() { } SecondService_secondtestString_presult::~SecondService_secondtestString_presult() throw() { } }} // namespace
C++
// Licensed to the Apache Software Foundation(ASF) under one // or more contributor license agreements.See the NOTICE file // distributed with this work for additional information // regarding copyright ownership.The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. using System; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Logging; using Thrift.Processor; using Thrift.Protocol; using Thrift.Transport.Client; namespace Thrift.Transport.Server { // ReSharper disable once InconsistentNaming public class THttpServerTransport { protected const string ContentType = "application/x-thrift"; private readonly ILogger _logger; private readonly RequestDelegate _next; protected Encoding Encoding = Encoding.UTF8; protected TProtocolFactory InputProtocolFactory; protected TProtocolFactory OutputProtocolFactory; protected TTransportFactory InputTransportFactory; protected TTransportFactory OutputTransportFactory; protected ITAsyncProcessor Processor; public THttpServerTransport(ITAsyncProcessor processor, RequestDelegate next = null, ILoggerFactory loggerFactory = null) : this(processor, new TBinaryProtocol.Factory(), null, next, loggerFactory) { } public THttpServerTransport( ITAsyncProcessor processor, TProtocolFactory protocolFactory, TTransportFactory transFactory = null, RequestDelegate next = null, ILoggerFactory loggerFactory = null) : this(processor, protocolFactory, protocolFactory, transFactory, transFactory, next, loggerFactory) { } public THttpServerTransport( ITAsyncProcessor processor, TProtocolFactory inputProtocolFactory, TProtocolFactory outputProtocolFactory, TTransportFactory inputTransFactory = null, TTransportFactory outputTransFactory = null, RequestDelegate next = null, ILoggerFactory loggerFactory = null) { // loggerFactory == null is not illegal anymore Processor = processor ?? throw new ArgumentNullException(nameof(processor)); InputProtocolFactory = inputProtocolFactory ?? throw new ArgumentNullException(nameof(inputProtocolFactory)); OutputProtocolFactory = outputProtocolFactory ?? throw new ArgumentNullException(nameof(outputProtocolFactory)); InputTransportFactory = inputTransFactory; OutputTransportFactory = outputTransFactory; _next = next; _logger = (loggerFactory != null) ? loggerFactory.CreateLogger<THttpServerTransport>() : new NullLogger<THttpServerTransport>(); } public async Task Invoke(HttpContext context) { context.Response.ContentType = ContentType; await ProcessRequestAsync(context, context.RequestAborted); //TODO: check for correct logic } public async Task ProcessRequestAsync(HttpContext context, CancellationToken cancellationToken) { var transport = new TStreamTransport(context.Request.Body, context.Response.Body); try { var intrans = (InputTransportFactory != null) ? InputTransportFactory.GetTransport(transport) : transport; var outtrans = (OutputTransportFactory != null) ? OutputTransportFactory.GetTransport(transport) : transport; var input = InputProtocolFactory.GetProtocol(intrans); var output = OutputProtocolFactory.GetProtocol(outtrans); while (await Processor.ProcessAsync(input, output, cancellationToken)) { if (!context.Response.HasStarted) // oneway method called await context.Response.Body.FlushAsync(cancellationToken); } } catch (TTransportException) { if (!context.Response.HasStarted) // if something goes bust, let the client know context.Response.StatusCode = 500; } finally { transport.Close(); } } } }
C#
This program updates the GFS surface conditions using external snow and sea ice analyses. It updates monthly climatological fields such as plant greenness fraction and albedo. Documentation may be found at https://ufs-community.github.io/UFS_UTILS
GCC Machine Description
// // ISRecommendController.m // iScrobbler // // Created by Brian Bergstrand on 1/8/2007. // Copyright 2007 Brian Bergstrand. // // Released under the GPL, license details available in res/gpl.txt // #import "ISRecommendController.h" #import "ProtocolManager.h" #import "ASXMLFile.h" @implementation ISRecommendController - (IBAction)ok:(id)sender { [[self window] endEditingFor:nil]; // force any editor to resign first-responder and commit send = YES; [self performSelector:@selector(performClose:) withObject:sender]; } - (NSString*)who { return (toUser ? toUser : @""); } - (NSString*)message { return (msg ? msg : @""); } - (ISTypeToRecommend_t)type { return (what); } - (void)setType:(ISTypeToRecommend_t)newtype { what = newtype; } - (BOOL)send { return (send); } - (id)representedObject { return (representedObj); } - (void)setRepresentedObject:(id)obj { if (obj != representedObj) { [representedObj release]; representedObj = [obj retain]; } } -(void)xmlFile:(ASXMLFile *)connection didFailWithError:(NSError *)reason { [conn autorelease]; conn = nil; [progress stopAnimation:nil]; } - (void)xmlFileDidFinishLoading:(ASXMLFile *)connection { NSXMLDocument *xml = [connection xml]; [conn autorelease]; conn = nil; @try { if ([[friends content] count]) [friends removeObjects:[friends content]]; NSArray *users = [[xml rootElement] elementsForName:@"user"]; NSEnumerator *en = [users objectEnumerator]; NSString *user; NSXMLElement *e; while ((e = [en nextObject])) { if ((user = [[[e attributeForName:@"username"] stringValue] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding])) { NSMutableDictionary *entry = [NSMutableDictionary dictionaryWithObjectsAndKeys: user, @"name", nil]; [friends addObject:entry]; } } } @catch (NSException *e) { ScrobLog(SCROB_LOG_ERR, @"Exception processing friends.xml: %@", e); } [progress stopAnimation:nil]; } - (void)tableViewSelectionDidChange:(NSNotification*)note { NSTableView *table = [note object]; if (100 != [table tag]) return; @try { NSArray *users = [friends selectedObjects]; if ([users count] > 0) { id user = [users objectAtIndex:0]; if ([user isKindOfClass:[NSDictionary class]]) { [self setValue:[user objectForKey:@"name"] forKey:@"toUser"]; } } } @catch (id e) {} } - (void)closeWindow { [[NSNotificationCenter defaultCenter] removeObserver:self name:NSTableViewSelectionDidChangeNotification object:nil]; if ([[self window] isSheet]) [NSApp endSheet:[self window]]; [[self window] close]; [[NSNotificationCenter defaultCenter] postNotificationName:ISRecommendDidEnd object:self]; } - (IBAction)performClose:(id)sender { [self closeWindow]; } - (IBAction)showWindow:(id)sender { [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(tableViewSelectionDidChange:) name:NSTableViewSelectionDidChangeNotification object:nil]; if (sender) [NSApp beginSheet:[self window] modalForWindow:sender modalDelegate:self didEndSelector:nil contextInfo:nil]; else [super showWindow:nil]; [progress startAnimation:nil]; // Get the friends list NSString *user = [[[ProtocolManager sharedInstance] userName] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; NSString *url = [[[NSUserDefaults standardUserDefaults] stringForKey:@"WS URL"] stringByAppendingFormat:@"user/%@/friends.xml", user]; conn = [[ASXMLFile xmlFileWithURL:[NSURL URLWithString:url] delegate:self cachedForSeconds:600] retain]; } - (void)windowDidLoad { [[self window] setAlphaValue:IS_UTIL_WINDOW_ALPHA]; } - (void)setArtistEnabled:(BOOL)enabled { artistEnabled = enabled; } - (void)setTrackEnabled:(BOOL)enabled { trackEnabled = enabled; } - (void)setAlbumEnabled:(BOOL)enabled { albumEnabled = enabled; } - (id)init { artistEnabled = trackEnabled = albumEnabled = YES; return ((self = [super initWithWindowNibName:@"Recommend"])); } - (void)dealloc { [conn cancel]; [conn release]; [toUser release]; [msg release]; [super dealloc]; } @end
Objective-C++
# Author: geekgit # Date: 21.06.2017 0:17 UTC # Last update: 21.06.2017 0:36 UTC Try { $whiteList=New-Object System.Collections.ArrayList($null); $whiteList.Add("content"); $whiteList.Add("config"); $whiteList.Add("intermediate"); $dirVar=(Get-ChildItem | ?{ $_.PSIsContainer}).Name; Write-Host "Dir in project folder: "; #just print info ForEach ($currDir in $dirVar) { $currDirLowercase=$currDir.ToLower(); $flag=$whiteList.contains($currDirLowercase); Write-Host "Directory $currDir [$currDirLowercase], whitelist? $flag" } #clean ForEach ($currDir in $dirVar) { $currDirLowercase=$currDir.ToLower(); $flag=$whiteList.contains($currDirLowercase); if(!$flag) { Write-Host "Delete $currDir..." Remove-Item .\$currDir -Force -Recurse } } } Catch { $Message=$_ Write-Host "Exception: $Message" } Read-Host -Prompt "Press Enter to exit..."
PowerShell
(***********************************************************************) (* *) (* Objective Caml *) (* *) (* Jerome Vouillon, projet Cristal, INRIA Rocquencourt *) (* *) (* Copyright 1996 Institut National de Recherche en Informatique et *) (* en Automatique. All rights reserved. This file is distributed *) (* under the terms of the Q Public License version 1.0. *) (* *) (***********************************************************************) (* $Id: typeclass.ml,v 1.78 2004/05/31 02:01:59 garrigue Exp $ *) open Misc open Parsetree open Asttypes open Path open Types open Typedtree open Typecore open Typetexp open Format type error = Unconsistent_constraint of (type_expr * type_expr) list | Method_type_mismatch of string * (type_expr * type_expr) list | Structure_expected of class_type | Cannot_apply of class_type | Apply_wrong_label of label | Pattern_type_clash of type_expr | Repeated_parameter | Unbound_class of Longident.t | Unbound_class_2 of Longident.t | Unbound_class_type of Longident.t | Unbound_class_type_2 of Longident.t | Abbrev_type_clash of type_expr * type_expr * type_expr | Constructor_type_mismatch of string * (type_expr * type_expr) list | Virtual_class of bool * string list | Parameter_arity_mismatch of Longident.t * int * int | Parameter_mismatch of (type_expr * type_expr) list | Bad_parameters of Ident.t * type_expr * type_expr | Class_match_failure of Ctype.class_match_failure list | Unbound_val of string | Unbound_type_var of (formatter -> unit) * Ctype.closed_class_failure | Make_nongen_seltype of type_expr | Non_generalizable_class of Ident.t * Types.class_declaration | Cannot_coerce_self of type_expr | Non_collapsable_conjunction of Ident.t * Types.class_declaration * (type_expr * type_expr) list | Final_self_clash of (type_expr * type_expr) list exception Error of Location.t * error (**********************) (* Useful constants *) (**********************) (* Self type have a dummy private method, thus preventing it to become closed. *) let dummy_method = Ctype.dummy_method (* Path associated to the temporary class type of a class being typed (its constructor is not available). *) let unbound_class = Path.Pident (Ident.create "") (************************************) (* Some operations on class types *) (************************************) (* Fully expand the head of a class type *) let rec scrape_class_type = function Tcty_constr (_, _, cty) -> scrape_class_type cty | cty -> cty (* Generalize a class type *) let rec generalize_class_type = function Tcty_constr (_, params, cty) -> List.iter Ctype.generalize params; generalize_class_type cty | Tcty_signature {cty_self = sty; cty_vars = vars; cty_inher = inher} -> Ctype.generalize sty; Vars.iter (fun _ (_, ty) -> Ctype.generalize ty) vars; List.iter (fun (_,tl) -> List.iter Ctype.generalize tl) inher | Tcty_fun (_, ty, cty) -> Ctype.generalize ty; generalize_class_type cty (* Return the virtual methods of a class type *) let virtual_methods sign = let (fields, _) = Ctype.flatten_fields (Ctype.object_fields sign.cty_self) in List.fold_left (fun virt (lab, _, _) -> if lab = dummy_method then virt else if Concr.mem lab sign.cty_concr then virt else lab::virt) [] fields (* Return the constructor type associated to a class type *) let rec constructor_type constr cty = match cty with Tcty_constr (_, _, cty) -> constructor_type constr cty | Tcty_signature sign -> constr | Tcty_fun (l, ty, cty) -> Ctype.newty (Tarrow (l, ty, constructor_type constr cty, Cok)) let rec class_body cty = match cty with Tcty_constr (_, _, cty') -> cty (* Only class bodies can be abbreviated *) | Tcty_signature sign -> cty | Tcty_fun (_, ty, cty) -> class_body cty let rec extract_constraints cty = let sign = Ctype.signature_of_class_type cty in (Vars.fold (fun lab _ vars -> lab :: vars) sign.cty_vars [], begin let (fields, _) = Ctype.flatten_fields (Ctype.object_fields sign.cty_self) in List.fold_left (fun meths (lab, _, _) -> if lab = dummy_method then meths else lab::meths) [] fields end, sign.cty_concr) let rec abbreviate_class_type path params cty = match cty with Tcty_constr (_, _, _) | Tcty_signature _ -> Tcty_constr (path, params, cty) | Tcty_fun (l, ty, cty) -> Tcty_fun (l, ty, abbreviate_class_type path params cty) let rec closed_class_type = function Tcty_constr (_, params, _) -> List.for_all Ctype.closed_schema params | Tcty_signature sign -> Ctype.closed_schema sign.cty_self && Vars.fold (fun _ (_, ty) cc -> Ctype.closed_schema ty && cc) sign.cty_vars true | Tcty_fun (_, ty, cty) -> Ctype.closed_schema ty && closed_class_type cty let closed_class cty = List.for_all Ctype.closed_schema cty.cty_params && closed_class_type cty.cty_type let rec limited_generalize rv = function Tcty_constr (path, params, cty) -> List.iter (Ctype.limited_generalize rv) params; limited_generalize rv cty | Tcty_signature sign -> Ctype.limited_generalize rv sign.cty_self; Vars.iter (fun _ (_, ty) -> Ctype.limited_generalize rv ty) sign.cty_vars; List.iter (fun (_, tl) -> List.iter (Ctype.limited_generalize rv) tl) sign.cty_inher | Tcty_fun (_, ty, cty) -> Ctype.limited_generalize rv ty; limited_generalize rv cty (* Record a class type *) let rc node = Stypes.record (Stypes.Ti_class node); node (***********************************) (* Primitives for typing classes *) (***********************************) (* Enter a value in the method environment only *) let enter_met_env lab kind ty val_env met_env par_env = let (id, val_env) = Env.enter_value lab {val_type = ty; val_kind = Val_unbound} val_env in (id, val_env, Env.add_value id {val_type = ty; val_kind = kind} met_env, Env.add_value id {val_type = ty; val_kind = Val_unbound} par_env) (* Enter an instance variable in the environment *) let enter_val cl_num vars lab mut ty val_env met_env par_env = let (id, val_env, met_env, par_env) as result = enter_met_env lab (Val_ivar (mut, cl_num)) ty val_env met_env par_env in vars := Vars.add lab (id, mut, ty) !vars; result let inheritance self_type env concr_meths warn_meths loc parent = match scrape_class_type parent with Tcty_signature cl_sig -> (* Methods *) begin try Ctype.unify env self_type cl_sig.cty_self with Ctype.Unify trace -> match trace with _::_::_::({desc = Tfield(n, _, _, _)}, _)::rem -> raise(Error(loc, Method_type_mismatch (n, rem))) | _ -> assert false end; let overridings = Concr.inter cl_sig.cty_concr warn_meths in if not (Concr.is_empty overridings) then begin Location.prerr_warning loc (Warnings.Method_override (Concr.elements overridings)) end; let concr_meths = Concr.union cl_sig.cty_concr concr_meths in let warn_meths = Concr.union cl_sig.cty_concr warn_meths in (cl_sig, concr_meths, warn_meths) | _ -> raise(Error(loc, Structure_expected parent)) let virtual_method val_env meths self_type lab priv sty loc = let (_, ty') = Ctype.filter_self_method val_env lab priv meths self_type in let ty = transl_simple_type val_env false sty in try Ctype.unify val_env ty ty' with Ctype.Unify trace -> raise(Error(loc, Method_type_mismatch (lab, trace))) let declare_method val_env meths self_type lab priv sty loc = let (_, ty') = Ctype.filter_self_method val_env lab priv meths self_type in let ty = match sty.ptyp_desc, priv with Ptyp_poly ([],sty), Public -> transl_simple_type_univars val_env sty | _ -> transl_simple_type val_env false sty in begin try Ctype.unify val_env ty ty' with Ctype.Unify trace -> raise(Error(loc, Method_type_mismatch (lab, trace))) end let type_constraint val_env sty sty' loc = let ty = transl_simple_type val_env false sty in let ty' = transl_simple_type val_env false sty' in try Ctype.unify val_env ty ty' with Ctype.Unify trace -> raise(Error(loc, Unconsistent_constraint trace)) let mkpat d = { ppat_desc = d; ppat_loc = Location.none } let make_method cl_num expr = { pexp_desc = Pexp_function ("", None, [mkpat (Ppat_alias (mkpat(Ppat_var "self-*"), "self-" ^ cl_num)), expr]); pexp_loc = expr.pexp_loc } (*******************************) let rec class_type_field env self_type meths (val_sig, concr_meths, inher) = function Pctf_inher sparent -> let parent = class_type env sparent in let inher = match parent with Tcty_constr (p, tl, _) -> (p, tl) :: inher | _ -> inher in let (cl_sig, concr_meths, _) = inheritance self_type env concr_meths Concr.empty sparent.pcty_loc parent in let val_sig = Vars.fold (fun lab (mut, ty) val_sig -> Vars.add lab (mut, ty) val_sig) cl_sig.cty_vars val_sig in (val_sig, concr_meths, inher) | Pctf_val (lab, mut, sty_opt, loc) -> let (mut, ty) = match sty_opt with None -> let (mut', ty) = try Vars.find lab val_sig with Not_found -> raise(Error(loc, Unbound_val lab)) in (if mut = Mutable then mut' else Immutable), ty | Some sty -> mut, transl_simple_type env false sty in (Vars.add lab (mut, ty) val_sig, concr_meths, inher) | Pctf_virt (lab, priv, sty, loc) -> declare_method env meths self_type lab priv sty loc; (val_sig, concr_meths, inher) | Pctf_meth (lab, priv, sty, loc) -> declare_method env meths self_type lab priv sty loc; (val_sig, Concr.add lab concr_meths, inher) | Pctf_cstr (sty, sty', loc) -> type_constraint env sty sty' loc; (val_sig, concr_meths, inher) and class_signature env sty sign = let meths = ref Meths.empty in let self_type = transl_simple_type env false sty in (* Check that the binder is a correct type, and introduce a dummy method preventing self type from being closed. *) begin try Ctype.unify env (Ctype.filter_method env dummy_method Private self_type) (Ctype.newty (Ttuple [])) with Ctype.Unify _ -> raise(Error(sty.ptyp_loc, Pattern_type_clash self_type)) end; (* Class type fields *) let (val_sig, concr_meths, inher) = List.fold_left (class_type_field env self_type meths) (Vars.empty, Concr.empty, []) sign in {cty_self = self_type; cty_vars = val_sig; cty_concr = concr_meths; cty_inher = inher} and class_type env scty = match scty.pcty_desc with Pcty_constr (lid, styl) -> let (path, decl) = try Env.lookup_cltype lid env with Not_found -> raise(Error(scty.pcty_loc, Unbound_class_type lid)) in if Path.same decl.clty_path unbound_class then raise(Error(scty.pcty_loc, Unbound_class_type_2 lid)); let (params, clty) = Ctype.instance_class decl.clty_params decl.clty_type in let sty = Ctype.self_type clty in if List.length params <> List.length styl then raise(Error(scty.pcty_loc, Parameter_arity_mismatch (lid, List.length params, List.length styl))); List.iter2 (fun sty ty -> let ty' = transl_simple_type env false sty in try Ctype.unify env ty' ty with Ctype.Unify trace -> raise(Error(sty.ptyp_loc, Parameter_mismatch trace))) styl params; Tcty_constr (path, params, clty) | Pcty_signature (sty, sign) -> Tcty_signature (class_signature env sty sign) | Pcty_fun (l, sty, scty) -> let ty = transl_simple_type env false sty in let cty = class_type env scty in Tcty_fun (l, ty, cty) (*******************************) module StringSet = Set.Make(struct type t = string let compare = compare end) let rec class_field cl_num self_type meths vars (val_env, met_env, par_env, fields, concr_meths, warn_meths, inh_vals, inher) = function Pcf_inher (sparent, super) -> let parent = class_expr cl_num val_env par_env sparent in let inher = match parent.cl_type with Tcty_constr (p, tl, _) -> (p, tl) :: inher | _ -> inher in let (cl_sig, concr_meths, warn_meths) = inheritance self_type val_env concr_meths warn_meths sparent.pcl_loc parent.cl_type in (* Variables *) let (val_env, met_env, par_env, inh_vars, inh_vals) = Vars.fold (fun lab (mut, ty) (val_env, met_env, par_env, inh_vars, inh_vals) -> let (id, val_env, met_env, par_env) = enter_val cl_num vars lab mut ty val_env met_env par_env in if StringSet.mem lab inh_vals then Location.prerr_warning sparent.pcl_loc (Warnings.Hide_instance_variable lab); (val_env, met_env, par_env, (lab, id) :: inh_vars, StringSet.add lab inh_vals)) cl_sig.cty_vars (val_env, met_env, par_env, [], inh_vals) in (* Inherited concrete methods *) let inh_meths = Concr.fold (fun lab rem -> (lab, Ident.create lab)::rem) cl_sig.cty_concr [] in (* Super *) let (val_env, met_env, par_env) = match super with None -> (val_env, met_env, par_env) | Some name -> let (id, val_env, met_env, par_env) = enter_met_env name (Val_anc (inh_meths, cl_num)) self_type val_env met_env par_env in (val_env, met_env, par_env) in (val_env, met_env, par_env, lazy(Cf_inher (parent, inh_vars, inh_meths))::fields, concr_meths, warn_meths, inh_vals, inher) | Pcf_val (lab, mut, sexp, loc) -> if StringSet.mem lab inh_vals then Location.prerr_warning loc (Warnings.Hide_instance_variable lab); if !Clflags.principal then Ctype.begin_def (); let exp = try type_exp val_env sexp with Ctype.Unify [(ty, _)] -> raise(Error(loc, Make_nongen_seltype ty)) in if !Clflags.principal then begin Ctype.end_def (); Ctype.generalize_structure exp.exp_type end; let (id, val_env, met_env, par_env) = enter_val cl_num vars lab mut exp.exp_type val_env met_env par_env in (val_env, met_env, par_env, lazy(Cf_val (lab, id, exp)) :: fields, concr_meths, warn_meths, inh_vals, inher) | Pcf_virt (lab, priv, sty, loc) -> virtual_method val_env meths self_type lab priv sty loc; let warn_meths = Concr.remove lab warn_meths in (val_env, met_env, par_env, fields, concr_meths, warn_meths, inh_vals, inher) | Pcf_meth (lab, priv, expr, loc) -> let (_, ty) = Ctype.filter_self_method val_env lab priv meths self_type in begin try match expr.pexp_desc with Pexp_poly (sbody, sty) -> begin match sty with None -> () | Some sty -> Ctype.unify val_env (Typetexp.transl_simple_type val_env false sty) ty end; begin match (Ctype.repr ty).desc with Tvar -> let ty' = Ctype.newvar () in Ctype.unify val_env (Ctype.newty (Tpoly (ty', []))) ty; Ctype.unify val_env (type_approx val_env sbody) ty' | Tpoly (ty1, tl) -> let _, ty1' = Ctype.instance_poly false tl ty1 in let ty2 = type_approx val_env sbody in Ctype.unify val_env ty2 ty1' | _ -> assert false end | _ -> assert false with Ctype.Unify trace -> raise(Error(loc, Method_type_mismatch (lab, trace))) end; let meth_expr = make_method cl_num expr in (* backup variables for Pexp_override *) let vars_local = !vars in let field = lazy begin let meth_type = Ctype.newty (Tarrow("", self_type, Ctype.instance ty, Cok)) in Ctype.raise_nongen_level (); vars := vars_local; let texp = type_expect met_env meth_expr meth_type in Ctype.end_def (); Cf_meth (lab, texp) end in (val_env, met_env, par_env, field::fields, Concr.add lab concr_meths, Concr.add lab warn_meths, inh_vals, inher) | Pcf_cstr (sty, sty', loc) -> type_constraint val_env sty sty' loc; (val_env, met_env, par_env, fields, concr_meths, warn_meths, inh_vals, inher) | Pcf_let (rec_flag, sdefs, loc) -> let (defs, val_env) = try Typecore.type_let val_env rec_flag sdefs with Ctype.Unify [(ty, _)] -> raise(Error(loc, Make_nongen_seltype ty)) in let (vals, met_env, par_env) = List.fold_right (fun id (vals, met_env, par_env) -> let expr = Typecore.type_exp val_env {pexp_desc = Pexp_ident (Longident.Lident (Ident.name id)); pexp_loc = Location.none} in let desc = {val_type = expr.exp_type; val_kind = Val_ivar (Immutable, cl_num)} in let id' = Ident.create (Ident.name id) in ((id', expr) :: vals, Env.add_value id' desc met_env, Env.add_value id' desc par_env)) (let_bound_idents defs) ([], met_env, par_env) in (val_env, met_env, par_env, lazy(Cf_let(rec_flag, defs, vals))::fields, concr_meths, warn_meths, inh_vals, inher) | Pcf_init expr -> let expr = make_method cl_num expr in let vars_local = !vars in let field = lazy begin Ctype.raise_nongen_level (); let meth_type = Ctype.newty (Tarrow ("", self_type, Ctype.instance Predef.type_unit, Cok)) in vars := vars_local; let texp = type_expect met_env expr meth_type in Ctype.end_def (); Cf_init texp end in (val_env, met_env, par_env, field::fields, concr_meths, warn_meths, inh_vals, inher) and class_structure cl_num final val_env met_env loc (spat, str) = (* Environment for substructures *) let par_env = met_env in (* Self type, with a dummy method preventing it from being closed/escaped. *) let self_type = Ctype.newvar () in Ctype.unify val_env (Ctype.filter_method val_env dummy_method Private self_type) (Ctype.newty (Ttuple [])); (* Private self is used for private method calls *) let private_self = if final then Ctype.newvar () else self_type in (* Self binder *) let (pat, meths, vars, val_env, meth_env, par_env) = type_self_pattern cl_num private_self val_env met_env par_env spat in let public_self = pat.pat_type in (* Check that the binder has a correct type *) let ty = if final then Ctype.newty (Tobject (Ctype.newvar(), ref None)) else self_type in begin try Ctype.unify val_env public_self ty with Ctype.Unify _ -> raise(Error(spat.ppat_loc, Pattern_type_clash public_self)) end; let get_methods ty = (fst (Ctype.flatten_fields (Ctype.object_fields (Ctype.expand_head val_env ty)))) in if final then begin (* Copy known information to still empty self_type *) List.iter (fun (lab,kind,ty) -> let k = if Btype.field_kind_repr kind = Fpresent then Public else Private in try Ctype.unify val_env ty (Ctype.filter_method val_env lab k self_type) with _ -> assert false) (get_methods public_self) end; (* Typing of class fields *) let (_, _, _, fields, concr_meths, _, _, inher) = List.fold_left (class_field cl_num self_type meths vars) (val_env, meth_env, par_env, [], Concr.empty, Concr.empty, StringSet.empty, []) str in Ctype.unify val_env self_type (Ctype.newvar ()); let sign = {cty_self = public_self; cty_vars = Vars.map (function (id, mut, ty) -> (mut, ty)) !vars; cty_concr = concr_meths; cty_inher = inher} in let methods = get_methods self_type in let priv_meths = List.filter (fun (_,kind,_) -> Btype.field_kind_repr kind <> Fpresent) methods in if final then begin (* Unify private_self and a copy of self_type. self_type will not be modified after this point *) Ctype.close_object self_type; let mets = virtual_methods {sign with cty_self = self_type} in if mets <> [] then raise(Error(loc, Virtual_class(true, mets))); let self_methods = List.fold_right (fun (lab,kind,ty) rem -> if lab = dummy_method then (* allow public self and private self to be unified *) match Btype.field_kind_repr kind with Fvar r -> Btype.set_kind r Fabsent; rem | _ -> rem else Ctype.newty(Tfield(lab, Btype.copy_kind kind, ty, rem))) methods (Ctype.newty Tnil) in begin try Ctype.unify val_env private_self (Ctype.newty (Tobject(self_methods, ref None))); Ctype.unify val_env public_self self_type with Ctype.Unify trace -> raise(Error(loc, Final_self_clash trace)) end; end; (* Typing of method bodies *) if !Clflags.principal then List.iter (fun (_,_,ty) -> Ctype.generalize_spine ty) methods; let fields = List.map Lazy.force (List.rev fields) in if !Clflags.principal then List.iter (fun (_,_,ty) -> Ctype.unify val_env ty (Ctype.newvar ())) methods; let meths = Meths.map (function (id, ty) -> id) !meths in (* Check for private methods made public *) let pub_meths' = List.filter (fun (_,kind,_) -> Btype.field_kind_repr kind = Fpresent) (get_methods public_self) in let names = List.map (fun (x,_,_) -> x) in let l1 = names priv_meths and l2 = names pub_meths' in let added = List.filter (fun x -> List.mem x l1) l2 in if added <> [] then Location.prerr_warning loc (Warnings.Other (String.concat " " ("the following private methods were made public implicitly:\n " :: added))); {cl_field = fields; cl_meths = meths}, sign and class_expr cl_num val_env met_env scl = match scl.pcl_desc with Pcl_constr (lid, styl) -> let (path, decl) = try Env.lookup_class lid val_env with Not_found -> raise(Error(scl.pcl_loc, Unbound_class lid)) in if Path.same decl.cty_path unbound_class then raise(Error(scl.pcl_loc, Unbound_class_2 lid)); let tyl = List.map (fun sty -> transl_simple_type val_env false sty, sty.ptyp_loc) styl in let (params, clty) = Ctype.instance_class decl.cty_params decl.cty_type in let clty' = abbreviate_class_type path params clty in if List.length params <> List.length tyl then raise(Error(scl.pcl_loc, Parameter_arity_mismatch (lid, List.length params, List.length tyl))); List.iter2 (fun (ty',loc) ty -> try Ctype.unify val_env ty' ty with Ctype.Unify trace -> raise(Error(loc, Parameter_mismatch trace))) tyl params; let cl = rc {cl_desc = Tclass_ident path; cl_loc = scl.pcl_loc; cl_type = clty'; cl_env = val_env} in let (vals, meths, concrs) = extract_constraints clty in rc {cl_desc = Tclass_constraint (cl, vals, meths, concrs); cl_loc = scl.pcl_loc; cl_type = clty'; cl_env = val_env} | Pcl_structure cl_str -> let (desc, ty) = class_structure cl_num false val_env met_env scl.pcl_loc cl_str in rc {cl_desc = Tclass_structure desc; cl_loc = scl.pcl_loc; cl_type = Tcty_signature ty; cl_env = val_env} | Pcl_fun (l, Some default, spat, sbody) -> let loc = default.pexp_loc in let scases = [{ppat_loc = loc; ppat_desc = Ppat_construct(Longident.Lident"Some", Some{ppat_loc = loc; ppat_desc = Ppat_var"*sth*"}, false)}, {pexp_loc = loc; pexp_desc = Pexp_ident(Longident.Lident"*sth*")}; {ppat_loc = loc; ppat_desc = Ppat_construct(Longident.Lident"None", None, false)}, default] in let smatch = {pexp_loc = loc; pexp_desc = Pexp_match({pexp_loc = loc; pexp_desc = Pexp_ident(Longident.Lident"*opt*")}, scases)} in let sfun = {pcl_loc = scl.pcl_loc; pcl_desc = Pcl_fun(l, None, {ppat_loc = loc; ppat_desc = Ppat_var"*opt*"}, {pcl_loc = scl.pcl_loc; pcl_desc = Pcl_let(Default, [spat, smatch], sbody)})} in class_expr cl_num val_env met_env sfun | Pcl_fun (l, None, spat, scl') -> if !Clflags.principal then Ctype.begin_def (); let (pat, pv, val_env, met_env) = Typecore.type_class_arg_pattern cl_num val_env met_env l spat in if !Clflags.principal then begin Ctype.end_def (); iter_pattern (fun {pat_type=ty} -> Ctype.generalize_structure ty) pat end; let pv = List.map (function (id, id', ty) -> (id, Typecore.type_exp val_env {pexp_desc = Pexp_ident (Longident.Lident (Ident.name id)); pexp_loc = Location.none})) pv in let rec all_labeled = function Tcty_fun ("", _, _) -> false | Tcty_fun (l, _, ty_fun) -> l.[0] <> '?' && all_labeled ty_fun | _ -> true in let partial = Parmatch.check_partial pat.pat_loc [pat, (* Dummy expression *) {exp_desc = Texp_constant (Asttypes.Const_int 1); exp_loc = Location.none; exp_type = Ctype.none; exp_env = Env.empty }] in Ctype.raise_nongen_level (); let cl = class_expr cl_num val_env met_env scl' in Ctype.end_def (); if Btype.is_optional l && all_labeled cl.cl_type then Location.prerr_warning pat.pat_loc (Warnings.Other "This optional argument cannot be erased"); rc {cl_desc = Tclass_fun (pat, pv, cl, partial); cl_loc = scl.pcl_loc; cl_type = Tcty_fun (l, Ctype.instance pat.pat_type, cl.cl_type); cl_env = val_env} | Pcl_apply (scl', sargs) -> let cl = class_expr cl_num val_env met_env scl' in let rec nonopt_labels ls ty_fun = match ty_fun with | Tcty_fun (l, _, ty_res) -> if Btype.is_optional l then nonopt_labels ls ty_res else nonopt_labels (l::ls) ty_res | _ -> ls in let ignore_labels = !Clflags.classic || let labels = nonopt_labels [] cl.cl_type in List.length labels = List.length sargs && List.for_all (fun (l,_) -> l = "") sargs && List.exists (fun l -> l <> "") labels && begin Location.prerr_warning cl.cl_loc Warnings.Labels_omitted; true end in let rec type_args args omitted ty_fun sargs more_sargs = match ty_fun with | Tcty_fun (l, ty, ty_fun) when sargs <> [] || more_sargs <> [] -> let name = Btype.label_name l and optional = if Btype.is_optional l then Optional else Required in let sargs, more_sargs, arg = if ignore_labels && not (Btype.is_optional l) then begin match sargs, more_sargs with (l', sarg0)::_, _ -> raise(Error(sarg0.pexp_loc, Apply_wrong_label(l'))) | _, (l', sarg0)::more_sargs -> if l <> l' && l' <> "" then raise(Error(sarg0.pexp_loc, Apply_wrong_label l')) else ([], more_sargs, Some(type_argument val_env sarg0 ty)) | _ -> assert false end else try let (l', sarg0, sargs, more_sargs) = try let (l', sarg0, sargs1, sargs2) = Btype.extract_label name sargs in (l', sarg0, sargs1 @ sargs2, more_sargs) with Not_found -> let (l', sarg0, sargs1, sargs2) = Btype.extract_label name more_sargs in (l', sarg0, sargs @ sargs1, sargs2) in sargs, more_sargs, if Btype.is_optional l' || not (Btype.is_optional l) then Some (type_argument val_env sarg0 ty) else let arg = type_argument val_env sarg0 (extract_option_type val_env ty) in Some (option_some arg) with Not_found -> sargs, more_sargs, if Btype.is_optional l && (List.mem_assoc "" sargs || List.mem_assoc "" more_sargs) then Some (option_none ty Location.none) else None in let omitted = if arg = None then (l,ty) :: omitted else omitted in type_args ((arg,optional)::args) omitted ty_fun sargs more_sargs | _ -> match sargs @ more_sargs with (l, sarg0)::_ -> if omitted <> [] then raise(Error(sarg0.pexp_loc, Apply_wrong_label l)) else raise(Error(cl.cl_loc, Cannot_apply cl.cl_type)) | [] -> (List.rev args, List.fold_left (fun ty_fun (l,ty) -> Tcty_fun(l,ty,ty_fun)) ty_fun omitted) in let (args, cty) = if ignore_labels then type_args [] [] cl.cl_type [] sargs else type_args [] [] cl.cl_type sargs [] in rc {cl_desc = Tclass_apply (cl, args); cl_loc = scl.pcl_loc; cl_type = cty; cl_env = val_env} | Pcl_let (rec_flag, sdefs, scl') -> let (defs, val_env) = try Typecore.type_let val_env rec_flag sdefs with Ctype.Unify [(ty, _)] -> raise(Error(scl.pcl_loc, Make_nongen_seltype ty)) in let (vals, met_env) = List.fold_right (fun id (vals, met_env) -> Ctype.begin_def (); let expr = Typecore.type_exp val_env {pexp_desc = Pexp_ident (Longident.Lident (Ident.name id)); pexp_loc = Location.none} in Ctype.end_def (); Ctype.generalize expr.exp_type; let desc = {val_type = expr.exp_type; val_kind = Val_ivar (Immutable, cl_num)} in let id' = Ident.create (Ident.name id) in ((id', expr) :: vals, Env.add_value id' desc met_env)) (let_bound_idents defs) ([], met_env) in let cl = class_expr cl_num val_env met_env scl' in rc {cl_desc = Tclass_let (rec_flag, defs, vals, cl); cl_loc = scl.pcl_loc; cl_type = cl.cl_type; cl_env = val_env} | Pcl_constraint (scl', scty) -> Ctype.begin_class_def (); let context = Typetexp.narrow () in let cl = class_expr cl_num val_env met_env scl' in Typetexp.widen context; let context = Typetexp.narrow () in let clty = class_type val_env scty in Typetexp.widen context; Ctype.end_def (); limited_generalize (Ctype.row_variable (Ctype.self_type cl.cl_type)) cl.cl_type; limited_generalize (Ctype.row_variable (Ctype.self_type clty)) clty; begin match Includeclass.class_types val_env cl.cl_type clty with [] -> () | error -> raise(Error(cl.cl_loc, Class_match_failure error)) end; let (vals, meths, concrs) = extract_constraints clty in rc {cl_desc = Tclass_constraint (cl, vals, meths, concrs); cl_loc = scl.pcl_loc; cl_type = snd (Ctype.instance_class [] clty); cl_env = val_env} (*******************************) (* Approximate the type of the constructor to allow recursive use *) (* of optional parameters *) let var_option = Predef.type_option (Btype.newgenvar ()) let rec approx_declaration cl = match cl.pcl_desc with Pcl_fun (l, _, _, cl) -> let arg = if Btype.is_optional l then Ctype.instance var_option else Ctype.newvar () in Ctype.newty (Tarrow (l, arg, approx_declaration cl, Cok)) | Pcl_let (_, _, cl) -> approx_declaration cl | Pcl_constraint (cl, _) -> approx_declaration cl | _ -> Ctype.newvar () let rec approx_description ct = match ct.pcty_desc with Pcty_fun (l, _, ct) -> let arg = if Btype.is_optional l then Ctype.instance var_option else Ctype.newvar () in Ctype.newty (Tarrow (l, arg, approx_description ct, Cok)) | _ -> Ctype.newvar () (*******************************) let temp_abbrev env id arity = let params = ref [] in for i = 1 to arity do params := Ctype.newvar () :: !params done; let ty = Ctype.newobj (Ctype.newvar ()) in let env = Env.add_type id {type_params = !params; type_arity = arity; type_kind = Type_abstract; type_manifest = Some ty; type_variance = List.map (fun _ -> true, true, true) !params} env in (!params, ty, env) let rec initial_env define_class approx (res, env) (cl, id, ty_id, obj_id, cl_id) = (* Temporary abbreviations *) let arity = List.length (fst cl.pci_params) in let (obj_params, obj_ty, env) = temp_abbrev env obj_id arity in let (cl_params, cl_ty, env) = temp_abbrev env cl_id arity in (* Temporary type for the class constructor *) let constr_type = approx cl.pci_expr in if !Clflags.principal then Ctype.generalize_spine constr_type; let dummy_cty = Tcty_signature { cty_self = Ctype.newvar (); cty_vars = Vars.empty; cty_concr = Concr.empty; cty_inher = [] } in let dummy_class = {cty_params = []; (* Dummy value *) cty_type = dummy_cty; (* Dummy value *) cty_path = unbound_class; cty_new = match cl.pci_virt with Virtual -> None | Concrete -> Some constr_type} in let env = Env.add_cltype ty_id {clty_params = []; (* Dummy value *) clty_type = dummy_cty; (* Dummy value *) clty_path = unbound_class} ( if define_class then Env.add_class id dummy_class env else env) in ((cl, id, ty_id, obj_id, obj_params, obj_ty, cl_id, cl_params, cl_ty, constr_type, dummy_class)::res, env) let class_infos define_class kind (cl, id, ty_id, obj_id, obj_params, obj_ty, cl_id, cl_params, cl_ty, constr_type, dummy_class) (res, env) = reset_type_variables (); Ctype.begin_class_def (); (* Introduce class parameters *) let params = try let params, loc = cl.pci_params in List.map (enter_type_variable true loc) params with Already_bound -> raise(Error(snd cl.pci_params, Repeated_parameter)) in (* Allow self coercions (only for class declarations) *) let coercion_locs = ref [] in (* Type the class expression *) let (expr, typ) = try Typecore.self_coercion := (Path.Pident obj_id, coercion_locs) :: !Typecore.self_coercion; let res = kind env cl.pci_expr in Typecore.self_coercion := List.tl !Typecore.self_coercion; res with exn -> Typecore.self_coercion := []; raise exn in Ctype.end_def (); let sty = Ctype.self_type typ in (* Generalize the row variable *) let rv = Ctype.row_variable sty in List.iter (Ctype.limited_generalize rv) params; limited_generalize rv typ; (* Check the abbreviation for the object type *) let (obj_params', obj_type) = Ctype.instance_class params typ in let constr = Ctype.newconstr (Path.Pident obj_id) obj_params in begin let ty = Ctype.self_type obj_type in Ctype.hide_private_methods ty; Ctype.close_object ty; begin try List.iter2 (Ctype.unify env) obj_params obj_params' with Ctype.Unify _ -> raise(Error(cl.pci_loc, Bad_parameters (obj_id, constr, Ctype.newconstr (Path.Pident obj_id) obj_params'))) end; begin try Ctype.unify env ty constr with Ctype.Unify _ -> raise(Error(cl.pci_loc, Abbrev_type_clash (constr, ty, Ctype.expand_head env constr))) end end; (* Check the other temporary abbreviation (#-type) *) begin let (cl_params', cl_type) = Ctype.instance_class params typ in let ty = Ctype.self_type cl_type in Ctype.hide_private_methods ty; Ctype.set_object_name obj_id (Ctype.row_variable ty) cl_params ty; begin try List.iter2 (Ctype.unify env) cl_params cl_params' with Ctype.Unify _ -> raise(Error(cl.pci_loc, Bad_parameters (cl_id, Ctype.newconstr (Path.Pident cl_id) cl_params, Ctype.newconstr (Path.Pident cl_id) cl_params'))) end; begin try Ctype.unify env ty cl_ty with Ctype.Unify _ -> let constr = Ctype.newconstr (Path.Pident cl_id) params in raise(Error(cl.pci_loc, Abbrev_type_clash (constr, ty, cl_ty))) end end; (* Type of the class constructor *) begin try Ctype.unify env (constructor_type constr obj_type) (Ctype.instance constr_type) with Ctype.Unify trace -> raise(Error(cl.pci_loc, Constructor_type_mismatch (cl.pci_name, trace))) end; (* Class and class type temporary definitions *) let cltydef = {clty_params = params; clty_type = class_body typ; clty_path = Path.Pident obj_id} and clty = {cty_params = params; cty_type = typ; cty_path = Path.Pident obj_id; cty_new = match cl.pci_virt with Virtual -> None | Concrete -> Some constr_type} in dummy_class.cty_type <- typ; let env = Env.add_cltype ty_id cltydef ( if define_class then Env.add_class id clty env else env) in if cl.pci_virt = Concrete then begin match virtual_methods (Ctype.signature_of_class_type typ) with [] -> () | mets -> raise(Error(cl.pci_loc, Virtual_class(define_class, mets))) end; (* Misc. *) let arity = Ctype.class_type_arity typ in let pub_meths = let (fields, _) = Ctype.flatten_fields (Ctype.object_fields (Ctype.expand_head env obj_ty)) in List.map (function (lab, _, _) -> lab) fields in (* Final definitions *) let (params', typ') = Ctype.instance_class params typ in let cltydef = {clty_params = params'; clty_type = class_body typ'; clty_path = Path.Pident obj_id} and clty = {cty_params = params'; cty_type = typ'; cty_path = Path.Pident obj_id; cty_new = match cl.pci_virt with Virtual -> None | Concrete -> Some (Ctype.instance constr_type)} in let obj_abbr = {type_params = obj_params; type_arity = List.length obj_params; type_kind = Type_abstract; type_manifest = Some obj_ty; type_variance = List.map (fun _ -> true, true, true) obj_params} in let (cl_params, cl_ty) = Ctype.instance_parameterized_type params (Ctype.self_type typ) in Ctype.hide_private_methods cl_ty; Ctype.set_object_name obj_id (Ctype.row_variable cl_ty) cl_params cl_ty; let cl_abbr = {type_params = cl_params; type_arity = List.length cl_params; type_kind = Type_abstract; type_manifest = Some cl_ty; type_variance = List.map (fun _ -> true, true, true) cl_params} in ((cl, id, clty, ty_id, cltydef, obj_id, obj_abbr, cl_id, cl_abbr, arity, pub_meths, List.rev !coercion_locs, expr) :: res, env) let final_decl env define_class (cl, id, clty, ty_id, cltydef, obj_id, obj_abbr, cl_id, cl_abbr, arity, pub_meths, coe, expr) = begin try Ctype.collapse_conj_params env clty.cty_params with Ctype.Unify trace -> raise(Error(cl.pci_loc, Non_collapsable_conjunction (id, clty, trace))) end; List.iter Ctype.generalize clty.cty_params; generalize_class_type clty.cty_type; begin match clty.cty_new with None -> () | Some ty -> Ctype.generalize ty end; List.iter Ctype.generalize obj_abbr.type_params; begin match obj_abbr.type_manifest with None -> () | Some ty -> Ctype.generalize ty end; List.iter Ctype.generalize cl_abbr.type_params; begin match cl_abbr.type_manifest with None -> () | Some ty -> Ctype.generalize ty end; if not (closed_class clty) then raise(Error(cl.pci_loc, Non_generalizable_class (id, clty))); begin match Ctype.closed_class clty.cty_params (Ctype.signature_of_class_type clty.cty_type) with None -> () | Some reason -> let printer = if define_class then function ppf -> Printtyp.class_declaration id ppf clty else function ppf -> Printtyp.cltype_declaration id ppf cltydef in raise(Error(cl.pci_loc, Unbound_type_var(printer, reason))) end; (id, clty, ty_id, cltydef, obj_id, obj_abbr, cl_id, cl_abbr, arity, pub_meths, coe, expr, (cl.pci_variance, cl.pci_loc)) let extract_type_decls (id, clty, ty_id, cltydef, obj_id, obj_abbr, cl_id, cl_abbr, arity, pub_meths, coe, expr, required) decls = ((obj_id, obj_abbr), required) :: ((cl_id, cl_abbr), required) :: decls let rec compact = function [] -> [] | a :: b :: l -> (a,b) :: compact l | _ -> fatal_error "Typeclass.compact" let merge_type_decls (id, clty, ty_id, cltydef, _obj_id, _obj_abbr, _cl_id, _cl_abbr, arity, pub_meths, coe, expr, req) ((obj_id, obj_abbr), (cl_id, cl_abbr)) = (id, clty, ty_id, cltydef, obj_id, obj_abbr, cl_id, cl_abbr, arity, pub_meths, coe, expr) let final_env define_class env (id, clty, ty_id, cltydef, obj_id, obj_abbr, cl_id, cl_abbr, arity, pub_meths, coe, expr) = (* Add definitions after cleaning them *) Env.add_type obj_id (Subst.type_declaration Subst.identity obj_abbr) ( Env.add_type cl_id (Subst.type_declaration Subst.identity cl_abbr) ( Env.add_cltype ty_id (Subst.cltype_declaration Subst.identity cltydef) ( if define_class then Env.add_class id (Subst.class_declaration Subst.identity clty) env else env))) (* Check that #c is coercible to c if there is a self-coercion *) let check_coercions env (id, clty, ty_id, cltydef, obj_id, obj_abbr, cl_id, cl_abbr, arity, pub_meths, coercion_locs, expr) = begin match coercion_locs with [] -> () | loc :: _ -> let cl_ty, obj_ty = match cl_abbr.type_manifest, obj_abbr.type_manifest with Some cl_ab, Some obj_ab -> let cl_params, cl_ty = Ctype.instance_parameterized_type cl_abbr.type_params cl_ab and obj_params, obj_ty = Ctype.instance_parameterized_type obj_abbr.type_params obj_ab in List.iter2 (Ctype.unify env) cl_params obj_params; cl_ty, obj_ty | _ -> assert false in begin try Ctype.subtype env cl_ty obj_ty () with Ctype.Subtype (tr1, tr2) -> raise(Typecore.Error(loc, Typecore.Not_subtype(tr1, tr2))) end; if not (Ctype.opened_object cl_ty) then raise(Error(loc, Cannot_coerce_self obj_ty)) end; (id, clty, ty_id, cltydef, obj_id, obj_abbr, cl_id, cl_abbr, arity, pub_meths, expr) (*******************************) let type_classes define_class approx kind env cls = let cls = List.map (function cl -> (cl, Ident.create cl.pci_name, Ident.create cl.pci_name, Ident.create cl.pci_name, Ident.create ("#" ^ cl.pci_name))) cls in Ctype.init_def (Ident.current_time ()); Ctype.begin_class_def (); let (res, env) = List.fold_left (initial_env define_class approx) ([], env) cls in let (res, env) = List.fold_right (class_infos define_class kind) res ([], env) in Ctype.end_def (); let res = List.rev_map (final_decl env define_class) res in let decls = List.fold_right extract_type_decls res [] in let decls = Typedecl.compute_variance_decls env decls in let res = List.map2 merge_type_decls res (compact decls) in let env = List.fold_left (final_env define_class) env res in let res = List.map (check_coercions env) res in (res, env) let class_num = ref 0 let class_declaration env sexpr = incr class_num; let expr = class_expr (string_of_int !class_num) env env sexpr in (expr, expr.cl_type) let class_description env sexpr = let expr = class_type env sexpr in (expr, expr) let class_declarations env cls = type_classes true approx_declaration class_declaration env cls let class_descriptions env cls = type_classes true approx_description class_description env cls let class_type_declarations env cls = let (decl, env) = type_classes false approx_description class_description env cls in (List.map (function (_, _, ty_id, cltydef, obj_id, obj_abbr, cl_id, cl_abbr, _, _, _) -> (ty_id, cltydef, obj_id, obj_abbr, cl_id, cl_abbr)) decl, env) let rec unify_parents env ty cl = match cl.cl_desc with Tclass_ident p -> begin try let decl = Env.find_class p env in let _, body = Ctype.find_cltype_for_path env decl.cty_path in Ctype.unify env ty (Ctype.instance body) with exn -> assert (exn = Not_found) end | Tclass_structure st -> unify_parents_struct env ty st | Tclass_fun (_, _, cl, _) | Tclass_apply (cl, _) | Tclass_let (_, _, _, cl) | Tclass_constraint (cl, _, _, _) -> unify_parents env ty cl and unify_parents_struct env ty st = List.iter (function Cf_inher (cl, _, _) -> unify_parents env ty cl | _ -> ()) st.cl_field let type_object env loc s = incr class_num; let (desc, sign) = class_structure (string_of_int !class_num) true env env loc s in let sty = Ctype.expand_head env sign.cty_self in Ctype.hide_private_methods sty; let (fields, _) = Ctype.flatten_fields (Ctype.object_fields sty) in let meths = List.map (fun (s,_,_) -> s) fields in unify_parents_struct env sign.cty_self desc; (desc, sign, meths) let () = Typecore.type_object := type_object (*******************************) (* Approximate the class declaration as class ['params] id = object end *) let approx_class sdecl = let self' = { ptyp_desc = Ptyp_any; ptyp_loc = Location.none } in let clty' = { pcty_desc = Pcty_signature(self', []); pcty_loc = sdecl.pci_expr.pcty_loc } in { sdecl with pci_expr = clty' } let approx_class_declarations env sdecls = fst (class_type_declarations env (List.map approx_class sdecls)) (*******************************) (* Error report *) open Format let report_error ppf = function | Repeated_parameter -> fprintf ppf "A type parameter occurs several times" | Unconsistent_constraint trace -> fprintf ppf "The class constraints are not consistent.@."; Printtyp.report_unification_error ppf trace (fun ppf -> fprintf ppf "Type") (fun ppf -> fprintf ppf "is not compatible with type") | Method_type_mismatch (m, trace) -> Printtyp.report_unification_error ppf trace (function ppf -> fprintf ppf "The method %s@ has type" m) (function ppf -> fprintf ppf "but is expected to have type") | Structure_expected clty -> fprintf ppf "@[This class expression is not a class structure; it has type@ %a@]" Printtyp.class_type clty | Cannot_apply clty -> fprintf ppf "This class expression is not a class function, it cannot be applied" | Apply_wrong_label l -> let mark_label = function | "" -> "out label" | l -> sprintf " label ~%s" l in fprintf ppf "This argument cannot be applied with%s" (mark_label l) | Pattern_type_clash ty -> (* XXX Trace *) (* XXX Revoir message d'erreur *) fprintf ppf "@[This pattern cannot match self: \ it only matches values of type@ %a@]" Printtyp.type_expr ty | Unbound_class cl -> fprintf ppf "Unbound class@ %a" Printtyp.longident cl | Unbound_class_2 cl -> fprintf ppf "The class@ %a@ is not yet completely defined" Printtyp.longident cl | Unbound_class_type cl -> fprintf ppf "Unbound class type@ %a" Printtyp.longident cl | Unbound_class_type_2 cl -> fprintf ppf "The class type@ %a@ is not yet completely defined" Printtyp.longident cl | Abbrev_type_clash (abbrev, actual, expected) -> (* XXX Afficher une trace ? *) Printtyp.reset_and_mark_loops_list [abbrev; actual; expected]; fprintf ppf "@[The abbreviation@ %a@ expands to type@ %a@ \ but is used with type@ %a@]" Printtyp.type_expr abbrev Printtyp.type_expr actual Printtyp.type_expr expected | Constructor_type_mismatch (c, trace) -> Printtyp.report_unification_error ppf trace (function ppf -> fprintf ppf "The expression \"new %s\" has type" c) (function ppf -> fprintf ppf "but is used with type") | Virtual_class (cl, mets) -> let print_mets ppf mets = List.iter (function met -> fprintf ppf "@ %s" met) mets in let cl_mark = if cl then "" else " type" in fprintf ppf "@[This class%s should be virtual@ \ @[<2>The following methods are undefined :%a@] @]" cl_mark print_mets mets | Parameter_arity_mismatch(lid, expected, provided) -> fprintf ppf "@[The class constructor %a@ expects %i type argument(s),@ \ but is here applied to %i type argument(s)@]" Printtyp.longident lid expected provided | Parameter_mismatch trace -> Printtyp.report_unification_error ppf trace (function ppf -> fprintf ppf "The type parameter") (function ppf -> fprintf ppf "does not meet its constraint: it should be") | Bad_parameters (id, params, cstrs) -> Printtyp.reset_and_mark_loops_list [params; cstrs]; fprintf ppf "@[The abbreviation %a@ is used with parameters@ %a@ \ wich are incompatible with constraints@ %a@]" Printtyp.ident id Printtyp.type_expr params Printtyp.type_expr cstrs | Class_match_failure error -> Includeclass.report_error ppf error | Unbound_val lab -> fprintf ppf "Unbound instance variable %s" lab | Unbound_type_var (printer, reason) -> let print_common ppf kind ty0 real lab ty = let ty1 = if real then ty0 else Btype.newgenty(Tobject(ty0, ref None)) in Printtyp.reset_and_mark_loops_list [ty; ty1]; fprintf ppf "The %s %s@ has type@;<1 2>%a@ where@ %a@ is unbound" kind lab Printtyp.type_expr ty Printtyp.type_expr ty0 in let print_reason ppf = function | Ctype.CC_Method (ty0, real, lab, ty) -> print_common ppf "method" ty0 real lab ty | Ctype.CC_Value (ty0, real, lab, ty) -> print_common ppf "instance variable" ty0 real lab ty in Printtyp.reset (); fprintf ppf "@[<v>@[Some type variables are unbound in this type:@;<1 2>%t@]@ \ @[%a@]@]" printer print_reason reason | Make_nongen_seltype ty -> fprintf ppf "@[<v>@[Self type should not occur in the non-generic type@;<1 2>\ %a@]@,\ It would escape the scope of its class@]" Printtyp.type_scheme ty | Non_generalizable_class (id, clty) -> fprintf ppf "@[The type of this class,@ %a,@ \ contains type variables that cannot be generalized@]" (Printtyp.class_declaration id) clty | Cannot_coerce_self ty -> fprintf ppf "@[The type of self cannot be coerced to@ \ the type of the current class:@ %a.@.\ Some occurences are contravariant@]" Printtyp.type_scheme ty | Non_collapsable_conjunction (id, clty, trace) -> fprintf ppf "@[The type of this class,@ %a,@ \ contains non-collapsable conjunctive types in constraints@]" (Printtyp.class_declaration id) clty; Printtyp.report_unification_error ppf trace (fun ppf -> fprintf ppf "Type") (fun ppf -> fprintf ppf "is not compatible with type") | Final_self_clash trace -> Printtyp.report_unification_error ppf trace (function ppf -> fprintf ppf "This object is expected to have type") (function ppf -> fprintf ppf "but has actually type")
OCaml
%%%------------------------------------------------------------------- %%% @author Lukasz Opiola %%% @copyright (C) 2022 ACK CYFRONET AGH %%% This software is released under the MIT license %%% cited in 'LICENSE.txt'. %%% @end %%%------------------------------------------------------------------- %%% @doc %%% Record expressing store content update options specialization for %%% range store used in automation machinery. %%% @end %%%------------------------------------------------------------------- -module(atm_range_store_content_update_options). -author("Lukasz Opiola"). -behaviour(jsonable_record). -behaviour(persistent_record). -include("automation/automation.hrl"). %% jsonable_record callbacks -export([to_json/1, from_json/1]). %% persistent_record callbacks -export([version/0, db_encode/2, db_decode/2]). -type start_num() :: integer(). -type end_num() :: integer(). -type step() :: integer(). -export_type([start_num/0, end_num/0, step/0]). -type record() :: #atm_range_store_content_update_options{}. -export_type([record/0]). -define(DEFAULT_START_NUM, 0). -define(DEFAULT_STEP, 1). %%%=================================================================== %%% jsonable_record callbacks %%%=================================================================== -spec to_json(record()) -> json_utils:json_term(). to_json(_Record) -> #{}. -spec from_json(json_utils:json_term()) -> record(). from_json(_RecordJson) -> #atm_range_store_content_update_options{}. %%%=================================================================== %%% persistent_record callbacks %%%=================================================================== -spec version() -> persistent_record:record_version(). version() -> 1. -spec db_encode(record(), persistent_record:nested_record_encoder()) -> json_utils:json_term(). db_encode(Record, _NestedRecordEncoder) -> to_json(Record). -spec db_decode(json_utils:json_term(), persistent_record:nested_record_decoder()) -> record(). db_decode(RecordJson, _NestedRecordDecoder) -> from_json(RecordJson).
Erlang
module ip_top_sva_nbor1u_1r1w_nocam ( clk, rst, ready, sr_en, sr_key, sr_dout, sr_vld, sr_match, sr_mhe, up_en, up_key, up_din, up_del, up_bp, up_mhe, t1_readB, t1_addrB, t1_doutB, t1_writeA, t1_addrA, t1_dinA, select_key, select_bit ); parameter NUMSEPT = 1; parameter KYWIDTH = 32; parameter DTWIDTH = 32; parameter LG_DTWIDTH = 5; parameter NUMVROW = 1024; parameter BITVROW = 10; parameter NUMVBNK = 8; parameter BITVBNK = 3; parameter MEM_DELAY = 2; parameter FLOPCRC = 0; parameter QSIZE=2; parameter PHWIDTH = KYWIDTH+DTWIDTH+1; parameter PLINE_DELAY = MEM_DELAY + FLOPCRC; parameter UP_DELAY = PLINE_DELAY; input clk, rst; input ready; input [NUMSEPT-1:0] sr_en; input [NUMSEPT*KYWIDTH-1:0] sr_key; input [NUMSEPT*DTWIDTH-1:0] sr_dout; input [NUMSEPT-1:0] sr_vld; input [NUMSEPT-1:0] sr_match; input [NUMSEPT-1:0] sr_mhe; input up_en; input [KYWIDTH-1:0] up_key; input [DTWIDTH-1:0] up_din; input up_del; input up_bp; input up_mhe; input [NUMVBNK-1:0] t1_readB; input [NUMVBNK*BITVROW-1:0] t1_addrB; input [NUMVBNK*PHWIDTH-1:0] t1_doutB; input [NUMVBNK-1:0] t1_writeA; input [NUMVBNK*BITVROW-1:0] t1_addrA; input [NUMVBNK*PHWIDTH-1:0] t1_dinA; input [KYWIDTH-1:0] select_key; input [LG_DTWIDTH-1:0] select_bit; reg t1_writeA_wire [0:NUMVBNK-1]; reg [BITVROW-1:0] t1_addrA_wire [0:NUMVBNK-1]; reg [PHWIDTH-1:0] t1_dinA_wire [0:NUMVBNK-1]; reg t1_readB_wire [0:NUMVBNK-1]; reg [BITVROW-1:0] t1_addrB_wire [0:NUMVBNK-1]; reg [PHWIDTH-1:0] t1_doutB_wire [0:NUMVBNK-1]; integer t1_int; always_comb for (t1_int=0; t1_int<NUMVBNK; t1_int=t1_int+1) begin t1_writeA_wire[t1_int] = t1_writeA >> t1_int; t1_addrA_wire[t1_int] = t1_addrA >> (t1_int*BITVROW); t1_dinA_wire[t1_int] = t1_dinA >> (t1_int*PHWIDTH); t1_readB_wire[t1_int] = t1_readB >> t1_int; t1_addrB_wire[t1_int] = t1_addrB >> (t1_int*BITVROW); t1_doutB_wire[t1_int] = t1_doutB >> (t1_int*PHWIDTH); end reg [BITVBNK-1:0] t1vld; reg [BITVBNK-1:0] t1bnk; reg [WIDTH-1:0] t1dat; integer t1_int; always @(posedge clk) if (!ready) begin t1vld <= 1'b0; t1bnk <= 0; end else for (t1_int=0; t1_int<NUMVBNK; t1_int=t1_int+1) if (t1_writeA_wire[t1_int] && (t1_addrA_wire[t1_int]==select_t1row[t1_int])) if (t1vld && (t1bnk==t1_int)) begin t1vld <= (t1_dinA_wire[t1_int] != {1'b1,select_key}); end else && (t1bnk==t1_int)) begin t1bnk <= t1_int; end wire [BITVROW-1:0] select_t1row [0:NUMVBNK-1]; genvar t1_var; generate for(t1_var=0; t1_var<NUMVBNK; t1_var=t1_var+1) begin: tdout_loop assert_select_row_check: assert property (@(posedge clk) disable iff (!ready) ($stable(select_t1row[t1_gen]))); // assert_update_row_check: assert property (@(posedge clk) disable iff(!ready) (core.up_q_en && core.hash_zero_key == select_key)|-> ##FLOPCRC (core.up_hash[t1_gen] == select_t1row[t1_gen])); // assert_search_row_check: assert property (@(posedge clk) disable iff(!ready) (sr_en[0] && sr_key == select_key)|-> ##FLOPCRC (core.sr_hash[0][t1_gen] == select_t1row[t1_gen])); //TODO: We dont check for t1mem_inv here, as all assertions are used after //ready signal is high. So we must already assume mem = 0; assert_tdout_check: assert property (@(posedge clk) disable iff (!ready) (t1_readB_wire[t1_var] && t1vld && (t1_var==t1bnk) && (t1_addrB_wire[t1_var] == select_t1row[t1_var])) |-> ##MEM_DELAY (t1_doutB_wire[t1_var]== {$past(t1vld,MEM_DELAY),select_key})); end endgenerate wire fakekey; assert search_key_check: assert property (@(posedge clk) disable iff (!ready) genvar fwd_var; generate for (fwd_var=0; fwd_var<NUMVBNK; fwd_var=fwd_var+1) begin: fwd_loop assert_tdout_fwd_check: assert property (@(posedge clk) disable iff (!ready) (t1_readB_wire[fwd_var] && (t1_addrB_wire[fwd_var]==select_t1row[fwd_var])) |-> ##MEM_DELAY (!(t1vld && (t1bnk==fwd_var)) || (t1_doutB_wire[fwd_var]=={1'b1,select_key}))); reg data_vld; reg data_mem; always @(posedge clk) if(!ready) begin data_vld <= 0; data_mem <= 0; end else if (up_en && (up_key == select_key)) begin data_vld <= !up_del; data_mem <= up_din[select_bit]; end assert_sr_vld_check: assert property (@(posedge clk) disable iff (!ready) ( (sr_en) |-> ##PLINE_DELAY (sr_vld) )); assert_sr_mhe_check: assert property (@(posedge clk) disable iff (!ready) ( (sr_en && sr_key == select_key) |-> ##PLINE_DELAY (!sr_mhe) )); assert_sr_match_check: assert property (@(posedge clk) disable iff (!ready) ( (data_vld && sr_en && sr_key == select_key) |-> ##PLINE_DELAY (sr_match)) ); assert_sr_nomatch_check: assert property (@(posedge clk) disable iff (!ready) ( (!data_vld && sr_en && sr_key == select_key) |-> ##PLINE_DELAY (!sr_match)) ); assert_sr_dout_check: assert property (@(posedge clk) disable iff (!ready) ( (data_vld && sr_en && sr_key == select_key) |-> ##PLINE_DELAY (sr_dout[select_bit] == $past(data_mem, PLINE_DELAY)) )); assert_up_mhe_check: assert property(@(posedge clk) disable iff(!ready) ( (up_en) |-> ##PLINE_DELAY (!up_mhe))); /*reg up_en_dly[0:UP_DELAY-1]; reg [KYWIDTH-1:0] up_key_dly[0:UP_DELAY-1]; reg [DTWIDTH-1:0] up_din_dly[0:UP_DELAY-1]; reg up_del_dly[0:UP_DELAY-1]; integer updel_int; always @(posedge clk) for(updel_int=0; updel_int<UP_DELAY; updel_int = updel_int+1) begin if(!ready) begin up_en_dly[updel_int] <= 0; up_key_dly[updel_int] <=0; up_din_dly[updel_int] <= 0; up_del_dly[updel_int] <= 0; end else begin up_en_dly[updel_int] <= (updel_int ==0 ? up_en : up_en_dly[updel_int-1]); up_key_dly[updel_int] <= (updel_int ==0 ? up_key : up_key_dly[updel_int-1]); up_din_dly[updel_int] <= (updel_int ==0 ? up_din : up_din_dly[updel_int-1]); up_del_dly[updel_int] <= (updel_int ==0 ? up_del : up_del_dly[updel_int-1]); end end reg data_vld; reg data_mem; always @(posedge clk) if(!ready) begin data_vld <= 0; data_mem <= 0; end else if (up_en_dly[UP_DELAY-1] && (up_key_dly[UP_DELAY-1] == select_key) && !up_fail) begin data_vld <= !up_del_dly[UP_DELAY-1]; data_mem <= up_din_dly[UP_DELAY-1][select_bit]; end assert_sr_vld_check: assert property (@(posedge clk) disable iff (!ready) ( (sr_en && sr_key == select_key) |-> ##PLINE_DELAY (sr_vld && !sr_mhe) )); assert_sr_match_check: assert property (@(posedge clk) disable iff (!ready) ( (data_vld && sr_en && sr_key == select_key) |-> ##PLINE_DELAY (sr_match)) ); assert_sr_nomatch_check: assert property (@(posedge clk) disable iff (!ready) ( (!data_vld && sr_en && sr_key == select_key) |-> ##PLINE_DELAY (!sr_match)) ); //assert_sr_dout_check: assert property (@(posedge clk) disable iff (!ready) ( (data_vld && sr_en && sr_key == select_key) |-> ##PLINE_DELAY (sr_dout[select_bit] == $past(data_mem, PLINE_DELAY)) )); assert_up_mhe_check: assert property(@(posedge clk) disable iff(!ready) ( (up_en && up_key == select_key) |-> ##PLINE_DELAY (!up_mhe))); */ endmodule
Coq
--- layout: "flexibleengine" page_title: "FlexibleEngine: flexibleengine_compute_bms_server_v2" sidebar_current: "docs-flexibleengine-resource-compute-bms-server-v2" description: |- Manages a BMS server resource within FlexibleEngine. --- # flexibleengine_compute_bms_server_v2 Manages a BMS Server resource within FlexibleEngine. ## Example Usage ### Basic Instance ```hcl variable "image_id" {} variable "flavor_id" {} variable "keypair_name" {} variable "network_id" {} variable "availability_zone" {} resource "flexibleengine_compute_bms_server_v2" "basic" { name = "basic" image_id = "${var.image_id}" flavor_id = "${var.flavor_id}" key_pair = "${var.keypair_name}" security_groups = ["default"] availability_zone = "${var.availability_zone}" metadata = { this = "that" } network { uuid = "${var.network_id}" } } ``` ## Argument Reference The following arguments are supported: * `region` - (Optional) The region in which to create the bms server instance. If omitted, the `region` argument of the provider is used. Changing this creates a new bms server. * `name` - (Required) The name of the BMS. * `image_id` - (Optional; Required if `image_name` is empty.) Changing this creates a new bms server. * `image_name` - (Optional; Required if `image_id` is empty.) The name of the desired image for the bms server. Changing this creates a new bms server. * `flavor_id` - (Optional; Required if `flavor_name` is empty) The flavor ID of the desired flavor for the bms server. Changing this resizes the existing bms server. * `flavor_name` - (Optional; Required if `flavor_id` is empty) The name of the desired flavor for the bms server. Changing this resizes the existing bms server. * `user_data` - (Optional) The user data to provide when launching the instance. Changing this creates a new bms server. * `security_groups` - (Optional) An array of one or more security group names to associate with the bms server. Changing this results in adding/removing security groups from the existing bms server. * `availability_zone` - (Required) The availability zone in which to create the bms server. * `network` - (Optional) An array of one or more networks to attach to the bms instance. Changing this creates a new bms server. * `metadata` - (Optional) Metadata key/value pairs to make available from within the instance. Changing this updates the existing bms server metadata. * `admin_pass` - (Optional) The administrative password to assign to the bms server. Changing this changes the root password on the existing server. * `key_pair` - (Optional) The name of a key pair to put on the bms server. The key pair must already be created and associated with the tenant's account. Changing this creates a new bms server. * `stop_before_destroy` - (Optional) Whether to try stop instance gracefully before destroying it, thus giving chance for guest OS daemons to stop correctly. If instance doesn't stop within timeout, it will be destroyed anyway. The `network` block supports: * `uuid` - (Required unless `port` or `name` is provided) The network UUID to attach to the bms server. Changing this creates a new bms server. * `name` - (Required unless `uuid` or `port` is provided) The human-readable name of the network. Changing this creates a new bms server. * `port` - (Required unless `uuid` or `name` is provided) The port UUID of a network to attach to the bms server. Changing this creates a new server. * `fixed_ip_v4` - (Optional) Specifies a fixed IPv4 address to be used on this network. Changing this creates a new bms server. * `fixed_ip_v6` - (Optional) Specifies a fixed IPv6 address to be used on this network. Changing this creates a new bms server. * `access_network` - (Optional) Specifies if this network should be used for provisioning access. Accepts true or false. Defaults to false. # Attributes Reference In addition to all arguments above, the following attributes are exported: * `id` - The id of the bms server. * `config_drive` - Whether to use the config_drive feature to configure the instance. * `kernel_id` - The UUID of the kernel image when the AMI image is used. * `user_id` - The ID of the user to which the BMS belongs. * `host_status` - The nova-compute status: **UP, UNKNOWN, DOWN, MAINTENANCE** and **Null**.
GCC Machine Description
!-----------------------------------------------------------------------------! ! CP2K: A general program to perform molecular dynamics simulations ! ! Copyright (C) 2000 - 2015 CP2K developers group ! !-----------------------------------------------------------------------------! ! ***************************************************************************** !> \brief performs geometry optimization !> \par History !> none ! ***************************************************************************** MODULE geo_opt USE bfgs_optimizer, ONLY: geoopt_bfgs USE cg_optimizer, ONLY: geoopt_cg USE cp_lbfgs_geo, ONLY: geoopt_lbfgs USE cp_output_handling, ONLY: cp_add_iter_level,& cp_iterate,& cp_rm_iter_level USE force_env_types, ONLY: force_env_type USE global_types, ONLY: global_environment_type USE gopt_f_methods, ONLY: gopt_f_create_x0 USE gopt_f_types, ONLY: gopt_f_create,& gopt_f_release,& gopt_f_type USE gopt_param_types, ONLY: gopt_param_read,& gopt_param_release,& gopt_param_type USE input_constants, ONLY: default_bfgs_method_id,& default_cg_method_id,& default_lbfgs_method_id USE input_section_types, ONLY: section_vals_get_subs_vals,& section_vals_type,& section_vals_val_get,& section_vals_val_set USE kinds, ONLY: dp #include "../common/cp_common_uses.f90" #include "../base/base_uses.f90" IMPLICIT NONE PRIVATE CHARACTER(len=*), PARAMETER, PRIVATE :: moduleN = 'geo_opt' PUBLIC :: cp_geo_opt, cp_rot_opt CONTAINS ! ***************************************************************************** !> \brief Main driver to perform geometry optimization !> \param force_env ... !> \param globenv ... !> \param eval_opt_geo ... !> \param rm_restart_info ... ! ***************************************************************************** RECURSIVE SUBROUTINE cp_geo_opt(force_env, globenv, eval_opt_geo, rm_restart_info) TYPE(force_env_type), POINTER :: force_env TYPE(global_environment_type), POINTER :: globenv LOGICAL, INTENT(IN), OPTIONAL :: eval_opt_geo, rm_restart_info CHARACTER(len=*), PARAMETER :: routineN = 'cp_geo_opt', & routineP = moduleN//':'//routineN INTEGER :: handle, step_start_val LOGICAL :: my_rm_restart_info REAL(KIND=dp), DIMENSION(:), POINTER :: x0 TYPE(cp_logger_type), POINTER :: logger TYPE(gopt_f_type), POINTER :: gopt_env TYPE(gopt_param_type), POINTER :: gopt_param TYPE(section_vals_type), POINTER :: force_env_section, & geo_section, root_section CALL timeset(routineN,handle) logger => cp_get_default_logger() CPASSERT(ASSOCIATED(force_env)) CPASSERT(ASSOCIATED(globenv)) NULLIFY (gopt_param,force_env_section,gopt_env,x0) root_section => force_env%root_section force_env_section => force_env%force_env_section geo_section => section_vals_get_subs_vals(root_section,"MOTION%GEO_OPT") CALL gopt_param_read(gopt_param, geo_section) CALL gopt_f_create(gopt_env, gopt_param, force_env=force_env, globenv=globenv,& geo_opt_section=geo_section, eval_opt_geo=eval_opt_geo) CALL gopt_f_create_x0(gopt_env, x0) CALL section_vals_val_get(geo_section,"STEP_START_VAL",i_val=step_start_val) CALL cp_add_iter_level(logger%iter_info,"GEO_OPT") CALL cp_iterate(logger%iter_info,iter_nr=step_start_val) CALL cp_geo_opt_low(force_env, globenv, gopt_param, gopt_env,& force_env_section, geo_section, x0) CALL cp_rm_iter_level(logger%iter_info,"GEO_OPT") ! Reset counter for next iteration, unless rm_restart_info==.FALSE. my_rm_restart_info = .TRUE. IF(PRESENT(rm_restart_info)) my_rm_restart_info = rm_restart_info IF(my_rm_restart_info) & CALL section_vals_val_set(geo_section,"STEP_START_VAL",i_val=0) DEALLOCATE (x0) CALL gopt_f_release(gopt_env) CALL gopt_param_release(gopt_param) CALL timestop(handle) END SUBROUTINE cp_geo_opt ! ***************************************************************************** !> \brief Main driver to perform rotation optimization for Dimer !> \param gopt_env ... !> \param x0 ... !> \param gopt_param ... !> \param geo_section ... ! ***************************************************************************** SUBROUTINE cp_rot_opt(gopt_env, x0, gopt_param, geo_section) TYPE(gopt_f_type), POINTER :: gopt_env REAL(KIND=dp), DIMENSION(:), POINTER :: x0 TYPE(gopt_param_type), POINTER :: gopt_param TYPE(section_vals_type), POINTER :: geo_section CHARACTER(len=*), PARAMETER :: routineN = 'cp_rot_opt', & routineP = moduleN//':'//routineN INTEGER :: handle, step_start_val TYPE(cp_logger_type), POINTER :: logger TYPE(section_vals_type), POINTER :: force_env_section CALL timeset(routineN,handle) NULLIFY (force_env_section) logger => cp_get_default_logger() CPASSERT(ASSOCIATED(gopt_env)) CPASSERT(ASSOCIATED(gopt_env%force_env)) CPASSERT(ASSOCIATED(gopt_env%globenv)) force_env_section => gopt_env%force_env%force_env_section CALL section_vals_val_get(geo_section,"STEP_START_VAL",i_val=step_start_val) CALL cp_add_iter_level(logger%iter_info,"ROT_OPT") CALL cp_iterate(logger%iter_info,iter_nr=step_start_val) CALL cp_geo_opt_low(gopt_env%force_env, gopt_env%globenv, gopt_param, gopt_env,& force_env_section, geo_section, x0) CALL cp_rm_iter_level(logger%iter_info,"ROT_OPT") ! Reset counter for next iteration CALL section_vals_val_set(geo_section,"STEP_START_VAL",i_val=0) CALL timestop(handle) END SUBROUTINE cp_rot_opt ! ***************************************************************************** !> \brief call to low level geometry optimizers !> \param force_env ... !> \param globenv ... !> \param gopt_param ... !> \param gopt_env ... !> \param force_env_section ... !> \param geo_section ... !> \param x0 ... ! ***************************************************************************** RECURSIVE SUBROUTINE cp_geo_opt_low(force_env, globenv, gopt_param, gopt_env, force_env_section,& geo_section, x0) TYPE(force_env_type), POINTER :: force_env TYPE(global_environment_type), POINTER :: globenv TYPE(gopt_param_type), POINTER :: gopt_param TYPE(gopt_f_type), POINTER :: gopt_env TYPE(section_vals_type), POINTER :: force_env_section, geo_section REAL(KIND=dp), DIMENSION(:), POINTER :: x0 CHARACTER(len=*), PARAMETER :: routineN = 'cp_geo_opt_low', & routineP = moduleN//':'//routineN CPASSERT(ASSOCIATED(force_env)) CPASSERT(ASSOCIATED(globenv)) CPASSERT(ASSOCIATED(gopt_param)) CPASSERT(ASSOCIATED(gopt_env)) CPASSERT(ASSOCIATED(x0)) CPASSERT(ASSOCIATED(force_env_section)) CPASSERT(ASSOCIATED(geo_section)) SELECT CASE (gopt_param%method_id) CASE (default_bfgs_method_id) CALL geoopt_bfgs(force_env,gopt_param,globenv,& geo_section, gopt_env, x0) CASE (default_lbfgs_method_id) CALL geoopt_lbfgs(force_env,gopt_param,globenv,& geo_section, gopt_env, x0) CASE (default_cg_method_id) CALL geoopt_cg(force_env,gopt_param,globenv,& geo_section, gopt_env, x0) CASE DEFAULT CPABORT("") END SELECT END SUBROUTINE cp_geo_opt_low END MODULE geo_opt
Fortran Free Form
<?php /** * PHPExcel * * Copyright (c) 2006 - 2010 PHPExcel * * 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 * * @category PHPExcel * @package PHPExcel_Shared_Best_Fit * @copyright Copyright (c) 2006 - 2010 PHPExcel (http://www.codeplex.com/PHPExcel) * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL * @version 1.7.5, 2010-12-10 */ /** * PHPExcel_Best_Fit * * @category PHPExcel * @package PHPExcel_Shared_Best_Fit * @copyright Copyright (c) 2006 - 2010 PHPExcel (http://www.codeplex.com/PHPExcel) */ class PHPExcel_Best_Fit { protected $_error = False; protected $_bestFitType = 'undetermined'; protected $_valueCount = 0; protected $_xValues = array(); protected $_yValues = array(); protected $_adjustToZero = False; protected $_yBestFitValues = array(); protected $_goodnessOfFit = 1; protected $_stdevOfResiduals = 0; protected $_covariance = 0; protected $_correlation = 0; protected $_SSRegression = 0; protected $_SSResiduals = 0; protected $_DFResiduals = 0; protected $_F = 0; protected $_slope = 0; protected $_slopeSE = 0; protected $_intersect = 0; protected $_intersectSE = 0; protected $_Xoffset = 0; protected $_Yoffset = 0; public function getError() { return $this->_error; } // function getBestFitType() public function getBestFitType() { return $this->_bestFitType; } // function getBestFitType() public function getValueOfYForX($xValue) { return False; } // function getValueOfYForX() public function getValueOfXForY($yValue) { return False; } // function getValueOfXForY() public function getXValues() { return $this->_xValues; } // function getValueOfXForY() public function getEquation($dp=0) { return False; } // function getEquation() public function getSlope($dp=0) { if ($dp != 0) { return round($this->_slope,$dp); } return $this->_slope; } // function getSlope() public function getSlopeSE($dp=0) { if ($dp != 0) { return round($this->_slopeSE,$dp); } return $this->_slopeSE; } // function getSlopeSE() public function getIntersect($dp=0) { if ($dp != 0) { return round($this->_intersect,$dp); } return $this->_intersect; } // function getIntersect() public function getIntersectSE($dp=0) { if ($dp != 0) { return round($this->_intersectSE,$dp); } return $this->_intersectSE; } // function getIntersectSE() public function getGoodnessOfFit($dp=0) { if ($dp != 0) { return round($this->_goodnessOfFit,$dp); } return $this->_goodnessOfFit; } // function getGoodnessOfFit() public function getGoodnessOfFitPercent($dp=0) { if ($dp != 0) { return round($this->_goodnessOfFit * 100,$dp); } return $this->_goodnessOfFit * 100; } // function getGoodnessOfFitPercent() public function getStdevOfResiduals($dp=0) { if ($dp != 0) { return round($this->_stdevOfResiduals,$dp); } return $this->_stdevOfResiduals; } // function getStdevOfResiduals() public function getSSRegression($dp=0) { if ($dp != 0) { return round($this->_SSRegression,$dp); } return $this->_SSRegression; } // function getSSRegression() public function getSSResiduals($dp=0) { if ($dp != 0) { return round($this->_SSResiduals,$dp); } return $this->_SSResiduals; } // function getSSResiduals() public function getDFResiduals($dp=0) { if ($dp != 0) { return round($this->_DFResiduals,$dp); } return $this->_DFResiduals; } // function getDFResiduals() public function getF($dp=0) { if ($dp != 0) { return round($this->_F,$dp); } return $this->_F; } // function getF() public function getCovariance($dp=0) { if ($dp != 0) { return round($this->_covariance,$dp); } return $this->_covariance; } // function getCovariance() public function getCorrelation($dp=0) { if ($dp != 0) { return round($this->_correlation,$dp); } return $this->_correlation; } // function getCorrelation() public function getYBestFitValues() { return $this->_yBestFitValues; } // function getYBestFitValues() protected function _calculateGoodnessOfFit($sumX,$sumY,$sumX2,$sumY2,$sumXY,$meanX,$meanY, $const) { $SSres = $SScov = $SScor = $SStot = $SSsex = 0.0; foreach($this->_xValues as $xKey => $xValue) { $bestFitY = $this->_yBestFitValues[$xKey] = $this->getValueOfYForX($xValue); $SSres += ($this->_yValues[$xKey] - $bestFitY) * ($this->_yValues[$xKey] - $bestFitY); if ($const) { $SStot += ($this->_yValues[$xKey] - $meanY) * ($this->_yValues[$xKey] - $meanY); } else { $SStot += $this->_yValues[$xKey] * $this->_yValues[$xKey]; } $SScov += ($this->_xValues[$xKey] - $meanX) * ($this->_yValues[$xKey] - $meanY); if ($const) { $SSsex += ($this->_xValues[$xKey] - $meanX) * ($this->_xValues[$xKey] - $meanX); } else { $SSsex += $this->_xValues[$xKey] * $this->_xValues[$xKey]; } } $this->_SSResiduals = $SSres; $this->_DFResiduals = $this->_valueCount - 1 - $const; if ($this->_DFResiduals == 0.0) { $this->_stdevOfResiduals = 0.0; } else { $this->_stdevOfResiduals = sqrt($SSres / $this->_DFResiduals); } if (($SStot == 0.0) || ($SSres == $SStot)) { $this->_goodnessOfFit = 1; } else { $this->_goodnessOfFit = 1 - ($SSres / $SStot); } $this->_SSRegression = $this->_goodnessOfFit * $SStot; $this->_covariance = $SScov / $this->_valueCount; $this->_correlation = ($this->_valueCount * $sumXY - $sumX * $sumY) / sqrt(($this->_valueCount * $sumX2 - pow($sumX,2)) * ($this->_valueCount * $sumY2 - pow($sumY,2))); $this->_slopeSE = $this->_stdevOfResiduals / sqrt($SSsex); $this->_intersectSE = $this->_stdevOfResiduals * sqrt(1 / ($this->_valueCount - ($sumX * $sumX) / $sumX2)); if ($this->_SSResiduals != 0.0) { if ($this->_DFResiduals == 0.0) { $this->_F = 0.0; } else { $this->_F = $this->_SSRegression / ($this->_SSResiduals / $this->_DFResiduals); } } else { if ($this->_DFResiduals == 0.0) { $this->_F = 0.0; } else { $this->_F = $this->_SSRegression / $this->_DFResiduals; } } } // function _calculateGoodnessOfFit() protected function _leastSquareFit($yValues, $xValues, $const) { // calculate sums $x_sum = array_sum($xValues); $y_sum = array_sum($yValues); $meanX = $x_sum / $this->_valueCount; $meanY = $y_sum / $this->_valueCount; $mBase = $mDivisor = $xx_sum = $xy_sum = $yy_sum = 0.0; for($i = 0; $i < $this->_valueCount; ++$i) { $xy_sum += $xValues[$i] * $yValues[$i]; $xx_sum += $xValues[$i] * $xValues[$i]; $yy_sum += $yValues[$i] * $yValues[$i]; if ($const) { $mBase += ($xValues[$i] - $meanX) * ($yValues[$i] - $meanY); $mDivisor += ($xValues[$i] - $meanX) * ($xValues[$i] - $meanX); } else { $mBase += $xValues[$i] * $yValues[$i]; $mDivisor += $xValues[$i] * $xValues[$i]; } } // calculate slope // $this->_slope = (($this->_valueCount * $xy_sum) - ($x_sum * $y_sum)) / (($this->_valueCount * $xx_sum) - ($x_sum * $x_sum)); $this->_slope = $mBase / $mDivisor; // calculate intersect // $this->_intersect = ($y_sum - ($this->_slope * $x_sum)) / $this->_valueCount; if ($const) { $this->_intersect = $meanY - ($this->_slope * $meanX); } else { $this->_intersect = 0; } $this->_calculateGoodnessOfFit($x_sum,$y_sum,$xx_sum,$yy_sum,$xy_sum,$meanX,$meanY,$const); } // function _leastSquareFit() function __construct($yValues, $xValues=array(), $const=True) { // Calculate number of points $nY = count($yValues); $nX = count($xValues); // Define X Values if necessary if ($nX == 0) { $xValues = range(1,$nY); $nX = $nY; } elseif ($nY != $nX) { // Ensure both arrays of points are the same size $this->_error = True; return False; } $this->_valueCount = $nY; $this->_xValues = $xValues; $this->_yValues = $yValues; } // function __construct() } // class bestFit
Hack
package com.twitter.finagle.zipkin.thrift import com.twitter.finagle.zipkin.{core, host => Host} /** * Receives the Finagle generated traces and sends a sample of them off to Zipkin via Scribe */ class ScribeZipkinTracer(tracer: ScribeRawZipkinTracer, sampler: core.Sampler) extends core.SamplingTracer(tracer, sampler) { /** * Default constructor for the service loader */ private[finagle] def this() = this( ScribeRawZipkinTracer( scribeHost = Host().getHostName, scribePort = Host().getPort ), core.DefaultSampler ) }
Scala
package model import scalikejdbc.TypeBinder case class CompanyId(value: Long) { override def toString = value.toString } object CompanyId { implicit val companyIdTypeBinder: TypeBinder[CompanyId] = TypeBinder.long.map(CompanyId.apply) }
Scala
\section{View Handler} Das View Handler Design-Pattern hilft alle Views welches ein Softwaresystem bereitstellt zu verwalten. Eine View-Handler Komponente erlaubt es Clients Views zu öffnen, zu verändern und zu entsorgen. Es koordiniert zudem die Abhängigkeiten zwischen Views und kümmert sich um ihre Aktualisierung. \subsection*{Example} Ein Multidokument-Editor erlaubt es an mehreren Dokumenten gleichzeitig zu arbeiten. Jedes Dokument wird in seinem eigenen Fenster (Moderner: Tab) angezeigt. Um solche Editoren effizient zu benutzen benötigen Benutzer hilfe beim Verwalten der Fenster. Zum Beispiel möchten sie ein Fenster klonen um mit mehreren unabhängigen Ansichten auf das selbe Dokument arbeiten zu können. Oft schliessen Benutzer nicht alle Fenster bevor sie die Anwendung beenden. Es ist die Aufgabe des Systems alle offenen Dokumente zu überwachen und sie vorsichtig zu schliessen. Änderungen in einem Fenster können auch andere Fenster betreffen. Deshalb benötigen wir einen effizienten Update-Mechansimus um die Änderungen zwischen Fenstern zu propagieren. \subsection*{Context} Ein Software-System stellt verschiedene Views von applikationsspezifischen Daten zur Verfügung order unterstützt das Arbeiten mit mehreren Dokumenten. \subsection*{Problem} Software-System welche mehrere Views unterstützen brauchen oft zusätzliche Funktioanlität um die Views zu verwalten. Der Benutzer will bequem Views öffnen, verändern oder entsorgen. Ein Update einer View soll autoamtisch an die entsprechenden anderen Views weitergegeben werden. \subsubsection*{Forces} \begin{itemize} \item Mehrere Views sollen durch den Benutzer wie auch durch interne Komponenten des Systems einfach verwaltet werden können. \item Die Implementierung der Views darf nicht von anderen Views abhängig sein oder mit dem Code gemsicht werden welcher zur Verwaltung der Views dient. \item Die Implementierung der Views kann varieren und weitere Arten von Views können während der Lebenszeit des Systems hinzugefügt werden. \end{itemize} \subsection*{Solution} Trenne die Verwaltung von Views vom Code welcher die spezifischen Views repräsentiert oder kontrolliert. Eine View Handler Komponente verwaltet alle Views welche das Software-System bereitstellt. Es bietet die notwendige Funktionalität an um Views zu öffnen, zu koordinieren und zu schliessen, und zudem um die Views zu bedienen. Zum Beispiel ein Kommando um alle Views in einer gekachelten Ansicht zu arrangieren. Spezfische Views werden in separaten View-Komponenten gekapselt, zusammen mit der Funktionalität sie darzustellen und zu kontrollieren. Suppliers versorgen die Views mit den Daten welche sie anzeigen sollen. Das View Handler Pattern adaptiert die Idee die Präsentatiion von der Funktionalität zu trennen, wie beim Model-View-Controller Pattern. Es stellt nicht die Struktur des gesammten Software-Systems zur Verfügung, sondern entfernt jediglich die Verantwortung die Gesamtheit der Views zu verwalten von den Model- und View-Komponenten. Das Pattern überträgt diese Verantwortung an die View Handler Komponente. Die View Handler Komponente lässt ich auch als Abstract Factory (GOF) oder als Mediator betrachten. Sie ist eine Abstract Factory, da die Clients unabhängig davon sind wie eine spezifische View erstellt wird. Sie ist ein Mediator weil die Clients unabhängig davon sind wie die Views koordiniert sind. \subsection*{Structure} \begin{figure}[H] \centering \includegraphics[width=0.7\textwidth]{content/posa1/images/view-handler-classes.png} \caption{View Handler Klassendiagramm} \end{figure} Der View Handler stellt auch Funktionen bereit um die Views zu schliessen, sowohl einzelne Views als auch alle Views auf einmal. Die Hauptverantwortung des View Handler ist es jedoch die Views zu verwalten. Zum Beispiel um eine View in den Vordergrund zu holen, alle Views zu kacheln , eine einzelne Views in mehrere Teile zu teilen, alle Views zu aktualisieren und um Views zu klonen. Eine Abstract View Komponente definiert eine gemeinsame Schnittstelle (Interface) für alle Views. Der View Handler benutzt diese Schnittstelle um die Views zu erzeugen, zu koordinieren und zu schliessen. Die dem System zu grunde liegende Plattform benutzt die Schnittstelle um Benutzerereignisse auszuführen, wie zum Beispiel das vergrössern eines Fensters. Spezifische View-Komponenten leiten von der Abstract View ab und implementieren die Schnittstelle. Jeder View implementiert seine eigene "display" Funktion. Diese empfängt Daten von Suppliers der View, bereitet diese Daten zur Anzeige vor und präsentiert sie dem Benutzer. Die "display" Funktion wird aufgerufen beim Öffnen oder Aktualsieren der View. Supplier Komponenten stellen die Daten, welche durch View-Komponenten angezeigt werden, zur Verfügung. Sie stellen eine Schnittstelle zur Verfügung welche es Clients - wie zum Beispiel Views - erlaubt Daten zu empfangen oder zu ändern. Sie benachrichtigen abhängige Komponenten über Änderungen an ihrem internen Zustand. Solche abhängige Komponenten können Views oder falls der View Handler Aktualisierungen durchführt der View Handler selbst sein. \subsection*{Dynamics} \begin{figure}[H] \centering \includegraphics[width=0.7\textwidth]{content/posa1/images/view-handler-classes.png} \caption{View Handler Klassendiagramm} \end{figure} \subsubsection*{Szenario 1: Ein View Handler erzeugt eine neue View} \begin{enumerate} \item Ein Client weist den View Handler an eine neue View zu öffnen. \item Der View Handler instanziert und initialisiert die entsprechende View. Die View registriert sich beim Change-Propagation Mechanismus seines Supplieres, entsprechend dem Publisher-Subscriber Pattern. \item Der View Handler fügt die View zur internen Liste von geöffneten View hinzu. \item Der View Handler weist die View an sicht selbst anzuzeigen. Die View öffnet ein neues Fenster, empfängt Daten von seinem Supplier, bereitet die Daten zur Anzeige vor und präsentiert sie dem Benutzer. \end{enumerate} \subsubsection*{Szenario 2: Ein View Handler kachelt die Views } \begin{enumerate} \item Der User führt das Kommando aus um alle offenen Fenster zu kacheln. Der View Handler empfängt die Aufforderung. \item Für jedes offene Fenster berechnet der View Handler eine neue Grösse und Position und ruft die entsprechende Resize und Move Prozeduren auf. \item Jede View ändert seine Position und Grösse und stellt die entsprechende Clipping-Fläche ein. Sie aktualisiert das Bild und zeigt es dem Benutzer an. Wir nehmen an, dass die Views die Daten welche sie anzeigen in einem Cache halten. Ist das nicht der Fall müssen die Views die Daten von ihren Supplieren neu beziehen. \end{enumerate} \subsection*{Implementation} \begin{enumerate} \item Identifiziere die Views \item Spezifiere eine gemeinsame Schnittstelle für die Views \item Implementiere die Views. \item Definiere einen View Handler. Implementiere die Funktionen um neue Views zu erzeugen als Factory Methods (GOF). \end{enumerate} \subsection*{Variants} View Handler with Command objects. Diese Variante benutzt Command Objects um ViewHandler unabhängiger von der Implementation der Views zu machen. Statt die View-Funktionalität direkt aufzurufen, erstellt der View-Handler ein entsprechendes Command und führt dieses aus. Eine weitere Möglichkeit wäre es, Commands zu erstellen und diese einem Command Prozessor (POSA1, nicht behandelt) zu übergeben. Dies erlaubt zusätzliche Funktionalität wie das Rückgängigmachen eines ausgeführten Commands. \subsection*{Known Uses} \begin{itemize} \item Macintosh Window Manager \item Microsoft Word \end{itemize} \subsection*{Consequences} \subsubsection*{Benefits} \begin{itemize} \item Einheitliches Handhaben der Views (-> gemeinsame Schnittstelle), alle Komponenten können über ein Interface auf die Views zugreifen, unabhängig von deren Inhalt \item Erweiterbarkeit und Austauschbarkeit der Views \item Applikationsspezifische View-Koordination, da Views von einer zentralen Instanz verwaltet werden, können spezifische Koordinationsstrategien verwendet werden. Koordinationsstrategien können auch benutzt werden, um die Applikation auf verschiedene Displaytypen anzupassen (z.B. kleine Smartphones vs Desktopbildschirm) \end{itemize} \subsubsection*{Liablities} \begin{itemize} \item Beschränkte Anwendbarkeit. ViewHandler lohnen sich nur, falls viele unterschiedliche Views, Views mit logischen Abhängigkeiten zwischeneinander oder unterschiedliche Koordinationsstrategien unterstützt werden müssen. Andernfalls erhöht ein View Handler bloss den Implementationsaufwand und die Komplexität der Software. \item Effizienz. Da zusätzliche Zwischenschicht. Meist nicht wirklich ausschlaggebend. \end{itemize} \subsection*{See also} \begin{itemize} \item Model View Controller \item Presentation-Abstraction-Control \end{itemize}
TeX
# inline text of content. philosophy: quotes: text: "書体 (typography) デザインというのは、文字の骨格がまずあり、それが確定すると、次にそれに明朝体やゴシック体のコスチュームを hello 着せていく。ウロコや始筆の形というのは、たとえていえば、ワイシャツの襟であり、袖口の形なのです。同じモデルがいろいろなコスチュームを着ることで、同じコンセプトの様々な書体をファミリーとしてつることができるというわけです。" by: — 小塚 昌彦 p: タイポグラフィの知識を深めるにつれて、その世界の大きさに毎日驚かされています。上記もそのうちの1つで、「新ゴ」で有名な小塚昌彦さんの著書「僕のつくった書体の話」でこの一文に出会いました。ちょうど、ウェブの機能的なデザイン方法について考えていた時だったので、「モデルにコスチュームを着せる」という発想にとても共感しました。同じたとえでは味気ないので、大好きな寿司になぞらえてフレームワークをつくってみました。手塩をかけてつくりこんだシャリを、手早く、力みなく、無駄な動きなしで、いろんな視点から仕入れた最適なネタを合わせて、握る。そんなイメージでつくっています。 details: composition: <code>neta</code>
YAML
package com.databricks.spark.sql.perf.mllib.clustering import org.apache.spark.ml import org.apache.spark.ml.{PipelineStage} import org.apache.spark.sql._ import com.databricks.spark.sql.perf.mllib.OptionImplicits._ import com.databricks.spark.sql.perf.mllib.data.DataGenerator import com.databricks.spark.sql.perf.mllib.{BenchmarkAlgorithm, MLBenchContext, TestFromTraining} object KMeans extends BenchmarkAlgorithm with TestFromTraining { override def trainingDataSet(ctx: MLBenchContext): DataFrame = { import ctx.params._ DataGenerator.generateGaussianMixtureData(ctx.sqlContext, k, numExamples, ctx.seed(), numPartitions, numFeatures) } override def getPipelineStage(ctx: MLBenchContext): PipelineStage = { import ctx.params._ new ml.clustering.KMeans() .setK(k) .setSeed(randomSeed.toLong) .setMaxIter(maxIter) .setTol(tol) } // TODO(?) add a scoring method here. }
Scala
<component name="libraryTable"> <library name="Gradle: org.springframework.boot:spring-boot-test-autoconfigure:1.4.1.RELEASE"> <CLASSES> <root url="jar://$USER_HOME$/.gradle/caches/modules-2/files-2.1/org.springframework.boot/spring-boot-test-autoconfigure/1.4.1.RELEASE/5061da3fdebd260fc20689561f5fb82e190df8a5/spring-boot-test-autoconfigure-1.4.1.RELEASE.jar!/" /> </CLASSES> <JAVADOC /> <SOURCES> <root url="jar://$USER_HOME$/.gradle/caches/modules-2/files-2.1/org.springframework.boot/spring-boot-test-autoconfigure/1.4.1.RELEASE/1f5e291e77674ec909562cbefa6486d223c857fd/spring-boot-test-autoconfigure-1.4.1.RELEASE-sources.jar!/" /> </SOURCES> </library> </component>
XML
// // main.swift // SimpleCalc // // Created by Xinyue Chen on 10/6/17. // Copyright © 2017 Xinyue Chen. All rights reserved. // import Foundation print("Enter an expression separated by returns:") let response = readLine(strippingNewline: true)!.trimmingCharacters(in: .whitespacesAndNewlines) let responseArr = response.components(separatedBy: " ") // determine it's three-line calculation or one-line if responseArr.count == 1 { let operand1 = Double(response)! // trim the whitespaces in input let op = readLine()!.trimmingCharacters(in: .whitespacesAndNewlines) let thirdLine = readLine()!.trimmingCharacters(in: .whitespacesAndNewlines) let operand2 = Double(thirdLine)! var result:Double = 0 // do the corresponding calculation according to the operator switch op { case "+": result = operand1 + operand2 case "-": result = operand1 - operand2 case "*": result = operand1 * operand2 case "/": result = operand1 / operand2 case "%": result = operand1.truncatingRemainder(dividingBy: operand2) default: print("Result: \(operand1) \(op) \(operand2)") } if result == Double(Int(result)) { print("Result: \(Int(result))") } else { print("Result: \(result)") } } else { let op = responseArr[responseArr.count - 1] let count = responseArr.count - 1 switch op { case "count": print(count) case "avg": var sum:Double = 0 for var i in 0..<count { sum += Double(responseArr[i])! i += 1 } let avg = sum / Double(count) if avg == Double(Int(avg)) { print(Int(avg)) } else { print(avg) } case "fact": let num = Double(responseArr[0])! if num != Double(Int(num)) { print("Please enter an integer for factorial calculation") } else { var fact = 1 if num < 0 { print("Bad input") } else if num == 0 { print("1") } else { for var i in 1...Int(num) { fact = fact * i i += 1 } print(fact) } } default: print("Non-standard operation command") } }
Swift
(************************************************************************) (* v * The Coq Proof Assistant / The Coq Development Team *) (* <O___,, * CNRS-Ecole Polytechnique-INRIA Futurs-Universite Paris Sud *) (* \VV/ **************************************************************) (* // * This file is distributed under the terms of the *) (* * GNU Lesser General Public License Version 2.1 *) (************************************************************************) (*i $Id: subtac_classes.ml 12187 2009-06-13 19:36:59Z msozeau $ i*) open Pretyping open Evd open Environ open Term open Rawterm open Topconstr open Names open Libnames open Pp open Vernacexpr open Constrintern open Subtac_command open Typeclasses open Typeclasses_errors open Termops open Decl_kinds open Entries open Util module SPretyping = Subtac_pretyping.Pretyping let interp_binder_evars evdref env na t = let t = Constrintern.intern_gen true (Evd.evars_of !evdref) env t in SPretyping.understand_tcc_evars evdref env IsType t let interp_binders_evars isevars env avoid l = List.fold_left (fun (env, ids, params) ((loc, i), t) -> let n = Name i in let t' = interp_binder_evars isevars env n t in let d = (i,None,t') in (push_named d env, i :: ids, d::params)) (env, avoid, []) l let interp_typeclass_context_evars isevars env avoid l = List.fold_left (fun (env, ids, params) (iid, bk, cl) -> let t' = interp_binder_evars isevars env (snd iid) cl in let i = match snd iid with | Anonymous -> Nameops.next_name_away (Termops.named_hd env t' Anonymous) ids | Name id -> id in let d = (i,None,t') in (push_named d env, i :: ids, d::params)) (env, avoid, []) l let interp_constrs_evars isevars env avoid l = List.fold_left (fun (env, ids, params) t -> let t' = interp_binder_evars isevars env Anonymous t in let id = Nameops.next_name_away (Termops.named_hd env t' Anonymous) ids in let d = (id,None,t') in (push_named d env, id :: ids, d::params)) (env, avoid, []) l let interp_constr_evars_gen evdref env ?(impls=([],[])) kind c = SPretyping.understand_tcc_evars evdref env kind (intern_gen (kind=IsType) ~impls (Evd.evars_of !evdref) env c) let interp_casted_constr_evars evdref env ?(impls=([],[])) c typ = interp_constr_evars_gen evdref env ~impls (OfType (Some typ)) c let type_ctx_instance isevars env ctx inst subst = List.fold_left2 (fun (subst, instctx) (na, _, t) ce -> let t' = substl subst t in let c = interp_casted_constr_evars isevars env ce t' in isevars := resolve_typeclasses ~onlyargs:true ~fail:true env !isevars; let d = na, Some c, t' in c :: subst, d :: instctx) (subst, []) (List.rev ctx) inst let type_class_instance_params isevars env id n ctx inst subst = List.fold_left2 (fun (subst, instctx) (na, _, t) ce -> let t' = replace_vars subst t in let c = interp_casted_constr_evars isevars env ce t' in let d = na, Some c, t' in (na, c) :: subst, d :: instctx) (subst, []) (List.rev ctx) inst let substitution_of_constrs ctx cstrs = List.fold_right2 (fun c (na, _, _) acc -> (na, c) :: acc) cstrs ctx [] let new_instance ?(global=false) ctx (instid, bk, cl) props ?(generalize=true) pri = let env = Global.env() in let isevars = ref (Evd.create_evar_defs Evd.empty) in let tclass = match bk with | Implicit -> Implicit_quantifiers.implicit_application Idset.empty (* need no avoid *) ~allow_partial:false (fun avoid (clname, (id, _, t)) -> match clname with | Some (cl, b) -> let t = if b then let _k = class_info cl in CHole (Util.dummy_loc, Some Evd.InternalHole) else CHole (Util.dummy_loc, None) in t, avoid | None -> failwith ("new instance: under-applied typeclass")) cl | Explicit -> cl in let tclass = if generalize then CGeneralization (dummy_loc, Implicit, Some AbsPi, tclass) else tclass in let k, ctx', imps, subst = let c = Command.generalize_constr_expr tclass ctx in let c', imps = interp_type_evars_impls ~evdref:isevars env c in let ctx, c = Sign.decompose_prod_assum c' in let cl, args = Typeclasses.dest_class_app (push_rel_context ctx env) c in cl, ctx, imps, (List.rev args) in let id = match snd instid with | Name id -> let sp = Lib.make_path id in if Nametab.exists_cci sp then errorlabstrm "new_instance" (Nameops.pr_id id ++ Pp.str " already exists"); id | Anonymous -> let i = Nameops.add_suffix (Classes.id_of_class k) "_instance_0" in Termops.next_global_ident_away false i (Termops.ids_of_context env) in let env' = push_rel_context ctx' env in isevars := Evarutil.nf_evar_defs !isevars; isevars := resolve_typeclasses ~onlyargs:false ~fail:true env' !isevars; let sigma = Evd.evars_of !isevars in let subst = List.map (Evarutil.nf_evar sigma) subst in let subst = let props = match props with | CRecord (loc, _, fs) -> if List.length fs > List.length k.cl_props then Classes.mismatched_props env' (List.map snd fs) k.cl_props; fs | _ -> if List.length k.cl_props <> 1 then errorlabstrm "new_instance" (Pp.str "Expected a definition for the instance body") else [(dummy_loc, Nameops.out_name (pi1 (List.hd k.cl_props))), props] in match k.cl_props with | [(na,b,ty)] -> let term = match props with [] -> CHole (Util.dummy_loc, None) | [(_,f)] -> f | _ -> assert false in let ty' = substl subst ty in let c = interp_casted_constr_evars isevars env' term ty' in c :: subst | _ -> let props, rest = List.fold_left (fun (props, rest) (id,_,_) -> try let ((loc, mid), c) = List.find (fun ((_,id'), c) -> Name id' = id) rest in let rest' = List.filter (fun ((_,id'), c) -> Name id' <> id) rest in Option.iter (fun x -> Dumpglob.add_glob loc (ConstRef x)) (List.assoc mid k.cl_projs); c :: props, rest' with Not_found -> (CHole (Util.dummy_loc, None) :: props), rest) ([], props) k.cl_props in if rest <> [] then unbound_method env' k.cl_impl (fst (List.hd rest)) else fst (type_ctx_instance isevars env' k.cl_props props subst) in let subst = List.fold_left2 (fun subst' s (_, b, _) -> if b = None then s :: subst' else subst') [] subst (k.cl_props @ snd k.cl_context) in let inst_constr, ty_constr = instance_constructor k subst in isevars := Evarutil.nf_evar_defs !isevars; let term = Evarutil.nf_isevar !isevars (it_mkLambda_or_LetIn inst_constr ctx') and termtype = Evarutil.nf_isevar !isevars (it_mkProd_or_LetIn ty_constr ctx') in isevars := undefined_evars !isevars; Evarutil.check_evars env Evd.empty !isevars termtype; let hook vis gr = let cst = match gr with ConstRef kn -> kn | _ -> assert false in let inst = Typeclasses.new_instance k pri global cst in Impargs.declare_manual_implicits false gr ~enriching:false imps; Typeclasses.add_instance inst in let evm = Subtac_utils.evars_of_term (Evd.evars_of !isevars) Evd.empty term in let obls, constr, typ = Eterm.eterm_obligations env id !isevars evm 0 term termtype in id, Subtac_obligations.add_definition id constr typ ~kind:(Global,false,Instance) ~hook obls
OCaml
#!/usr/bin/env bash # Copyright 2009 The Go Authors. All rights reserved. # Use of this source code is governed by a BSD-style # license that can be found in the LICENSE file. # Generate Go code listing errors and other #defined constant # values (ENAMETOOLONG etc.), by asking the preprocessor # about the definitions. unset LANG export LC_ALL=C export LC_CTYPE=C if test -z "$GOARCH" -o -z "$GOOS"; then echo 1>&2 "GOARCH or GOOS not defined in environment" exit 1 fi # Check that we are using the new build system if we should if [[ "$GOOS" = "linux" ]] && [[ "$GOLANG_SYS_BUILD" != "docker" ]]; then echo 1>&2 "In the Docker based build system, mkerrors should not be called directly." echo 1>&2 "See README.md" exit 1 fi if [[ "$GOOS" = "aix" ]]; then CC=${CC:-gcc} else CC=${CC:-cc} fi if [[ "$GOOS" = "solaris" ]]; then # Assumes GNU versions of utilities in PATH. export PATH=/usr/gnu/bin:$PATH fi uname=$(uname) includes_AIX=' #include <net/if.h> #include <net/netopt.h> #include <netinet/ip_mroute.h> #include <sys/protosw.h> #include <sys/stropts.h> #include <sys/mman.h> #include <sys/poll.h> #include <sys/select.h> #include <sys/termio.h> #include <termios.h> #include <fcntl.h> #define AF_LOCAL AF_UNIX ' includes_Darwin=' #define _DARWIN_C_SOURCE #define KERNEL #define _DARWIN_USE_64_BIT_INODE #define __APPLE_USE_RFC_3542 #include <stdint.h> #include <sys/attr.h> #include <sys/clonefile.h> #include <sys/kern_control.h> #include <sys/types.h> #include <sys/event.h> #include <sys/ptrace.h> #include <sys/select.h> #include <sys/socket.h> #include <sys/un.h> #include <sys/sockio.h> #include <sys/sys_domain.h> #include <sys/sysctl.h> #include <sys/mman.h> #include <sys/mount.h> #include <sys/utsname.h> #include <sys/wait.h> #include <sys/xattr.h> #include <net/bpf.h> #include <net/if.h> #include <net/if_types.h> #include <net/route.h> #include <netinet/in.h> #include <netinet/ip.h> #include <termios.h> ' includes_DragonFly=' #include <sys/types.h> #include <sys/event.h> #include <sys/select.h> #include <sys/socket.h> #include <sys/sockio.h> #include <sys/stat.h> #include <sys/sysctl.h> #include <sys/mman.h> #include <sys/mount.h> #include <sys/wait.h> #include <sys/ioctl.h> #include <net/bpf.h> #include <net/if.h> #include <net/if_clone.h> #include <net/if_types.h> #include <net/route.h> #include <netinet/in.h> #include <termios.h> #include <netinet/ip.h> #include <net/ip_mroute/ip_mroute.h> ' includes_FreeBSD=' #include <sys/capsicum.h> #include <sys/param.h> #include <sys/types.h> #include <sys/disk.h> #include <sys/event.h> #include <sys/sched.h> #include <sys/select.h> #include <sys/socket.h> #include <sys/un.h> #include <sys/sockio.h> #include <sys/stat.h> #include <sys/sysctl.h> #include <sys/mman.h> #include <sys/mount.h> #include <sys/wait.h> #include <sys/ioctl.h> #include <net/bpf.h> #include <net/if.h> #include <net/if_types.h> #include <net/route.h> #include <netinet/in.h> #include <termios.h> #include <netinet/ip.h> #include <netinet/ip_mroute.h> #include <sys/extattr.h> #if __FreeBSD__ >= 10 #define IFT_CARP 0xf8 // IFT_CARP is deprecated in FreeBSD 10 #undef SIOCAIFADDR #define SIOCAIFADDR _IOW(105, 26, struct oifaliasreq) // ifaliasreq contains if_data #undef SIOCSIFPHYADDR #define SIOCSIFPHYADDR _IOW(105, 70, struct oifaliasreq) // ifaliasreq contains if_data #endif ' includes_Linux=' #define _LARGEFILE_SOURCE #define _LARGEFILE64_SOURCE #ifndef __LP64__ #define _FILE_OFFSET_BITS 64 #endif #define _GNU_SOURCE // <sys/ioctl.h> is broken on powerpc64, as it fails to include definitions of // these structures. We just include them copied from <bits/termios.h>. #if defined(__powerpc__) struct sgttyb { char sg_ispeed; char sg_ospeed; char sg_erase; char sg_kill; short sg_flags; }; struct tchars { char t_intrc; char t_quitc; char t_startc; char t_stopc; char t_eofc; char t_brkc; }; struct ltchars { char t_suspc; char t_dsuspc; char t_rprntc; char t_flushc; char t_werasc; char t_lnextc; }; #endif #include <bits/sockaddr.h> #include <sys/epoll.h> #include <sys/eventfd.h> #include <sys/inotify.h> #include <sys/ioctl.h> #include <sys/mman.h> #include <sys/mount.h> #include <sys/prctl.h> #include <sys/stat.h> #include <sys/types.h> #include <sys/time.h> #include <sys/select.h> #include <sys/signalfd.h> #include <sys/socket.h> #include <sys/timerfd.h> #include <sys/uio.h> #include <sys/xattr.h> #include <linux/bpf.h> #include <linux/can.h> #include <linux/can/error.h> #include <linux/can/raw.h> #include <linux/capability.h> #include <linux/cryptouser.h> #include <linux/devlink.h> #include <linux/dm-ioctl.h> #include <linux/errqueue.h> #include <linux/ethtool_netlink.h> #include <linux/falloc.h> #include <linux/fanotify.h> #include <linux/filter.h> #include <linux/fs.h> #include <linux/fscrypt.h> #include <linux/fsverity.h> #include <linux/genetlink.h> #include <linux/hdreg.h> #include <linux/hidraw.h> #include <linux/icmp.h> #include <linux/icmpv6.h> #include <linux/if.h> #include <linux/if_addr.h> #include <linux/if_alg.h> #include <linux/if_arp.h> #include <linux/if_ether.h> #include <linux/if_ppp.h> #include <linux/if_tun.h> #include <linux/if_packet.h> #include <linux/if_xdp.h> #include <linux/input.h> #include <linux/kexec.h> #include <linux/keyctl.h> #include <linux/loop.h> #include <linux/lwtunnel.h> #include <linux/magic.h> #include <linux/memfd.h> #include <linux/module.h> #include <linux/netfilter/nfnetlink.h> #include <linux/netlink.h> #include <linux/net_namespace.h> #include <linux/nfc.h> #include <linux/nsfs.h> #include <linux/perf_event.h> #include <linux/pps.h> #include <linux/ptrace.h> #include <linux/random.h> #include <linux/reboot.h> #include <linux/rtc.h> #include <linux/rtnetlink.h> #include <linux/sched.h> #include <linux/seccomp.h> #include <linux/serial.h> #include <linux/sockios.h> #include <linux/taskstats.h> #include <linux/tipc.h> #include <linux/vm_sockets.h> #include <linux/wait.h> #include <linux/watchdog.h> #include <mtd/ubi-user.h> #include <mtd/mtd-user.h> #include <net/route.h> #if defined(__sparc__) // On sparc{,64}, the kernel defines struct termios2 itself which clashes with the // definition in glibc. As only the error constants are needed here, include the // generic termibits.h (which is included by termbits.h on sparc). #include <asm-generic/termbits.h> #else #include <asm/termbits.h> #endif #ifndef MSG_FASTOPEN #define MSG_FASTOPEN 0x20000000 #endif #ifndef PTRACE_GETREGS #define PTRACE_GETREGS 0xc #endif #ifndef PTRACE_SETREGS #define PTRACE_SETREGS 0xd #endif #ifndef SOL_NETLINK #define SOL_NETLINK 270 #endif #ifdef SOL_BLUETOOTH // SPARC includes this in /usr/include/sparc64-linux-gnu/bits/socket.h // but it is already in bluetooth_linux.go #undef SOL_BLUETOOTH #endif // Certain constants are missing from the fs/crypto UAPI #define FS_KEY_DESC_PREFIX "fscrypt:" #define FS_KEY_DESC_PREFIX_SIZE 8 #define FS_MAX_KEY_SIZE 64 // The code generator produces -0x1 for (~0), but an unsigned value is necessary // for the tipc_subscr timeout __u32 field. #undef TIPC_WAIT_FOREVER #define TIPC_WAIT_FOREVER 0xffffffff // Copied from linux/l2tp.h // Including linux/l2tp.h here causes conflicts between linux/in.h // and netinet/in.h included via net/route.h above. #define IPPROTO_L2TP 115 // Copied from linux/hid.h. // Keep in sync with the size of the referenced fields. #define _HIDIOCGRAWNAME_LEN 128 // sizeof_field(struct hid_device, name) #define _HIDIOCGRAWPHYS_LEN 64 // sizeof_field(struct hid_device, phys) #define _HIDIOCGRAWUNIQ_LEN 64 // sizeof_field(struct hid_device, uniq) #define _HIDIOCGRAWNAME HIDIOCGRAWNAME(_HIDIOCGRAWNAME_LEN) #define _HIDIOCGRAWPHYS HIDIOCGRAWPHYS(_HIDIOCGRAWPHYS_LEN) #define _HIDIOCGRAWUNIQ HIDIOCGRAWUNIQ(_HIDIOCGRAWUNIQ_LEN) ' includes_NetBSD=' #include <sys/types.h> #include <sys/param.h> #include <sys/event.h> #include <sys/extattr.h> #include <sys/mman.h> #include <sys/mount.h> #include <sys/sched.h> #include <sys/select.h> #include <sys/socket.h> #include <sys/sockio.h> #include <sys/sysctl.h> #include <sys/termios.h> #include <sys/ttycom.h> #include <sys/wait.h> #include <net/bpf.h> #include <net/if.h> #include <net/if_types.h> #include <net/route.h> #include <netinet/in.h> #include <netinet/in_systm.h> #include <netinet/ip.h> #include <netinet/ip_mroute.h> #include <netinet/if_ether.h> // Needed since <sys/param.h> refers to it... #define schedppq 1 ' includes_OpenBSD=' #include <sys/types.h> #include <sys/param.h> #include <sys/event.h> #include <sys/mman.h> #include <sys/mount.h> #include <sys/select.h> #include <sys/sched.h> #include <sys/socket.h> #include <sys/sockio.h> #include <sys/stat.h> #include <sys/sysctl.h> #include <sys/termios.h> #include <sys/ttycom.h> #include <sys/unistd.h> #include <sys/wait.h> #include <net/bpf.h> #include <net/if.h> #include <net/if_types.h> #include <net/if_var.h> #include <net/route.h> #include <netinet/in.h> #include <netinet/in_systm.h> #include <netinet/ip.h> #include <netinet/ip_mroute.h> #include <netinet/if_ether.h> #include <net/if_bridge.h> // We keep some constants not supported in OpenBSD 5.5 and beyond for // the promise of compatibility. #define EMUL_ENABLED 0x1 #define EMUL_NATIVE 0x2 #define IPV6_FAITH 0x1d #define IPV6_OPTIONS 0x1 #define IPV6_RTHDR_STRICT 0x1 #define IPV6_SOCKOPT_RESERVED1 0x3 #define SIOCGIFGENERIC 0xc020693a #define SIOCSIFGENERIC 0x80206939 #define WALTSIG 0x4 ' includes_SunOS=' #include <limits.h> #include <sys/types.h> #include <sys/select.h> #include <sys/socket.h> #include <sys/sockio.h> #include <sys/stat.h> #include <sys/stream.h> #include <sys/mman.h> #include <sys/wait.h> #include <sys/ioctl.h> #include <sys/mkdev.h> #include <net/bpf.h> #include <net/if.h> #include <net/if_arp.h> #include <net/if_types.h> #include <net/route.h> #include <netinet/icmp6.h> #include <netinet/in.h> #include <netinet/ip.h> #include <netinet/ip_mroute.h> #include <termios.h> ' includes=' #include <sys/types.h> #include <sys/file.h> #include <fcntl.h> #include <dirent.h> #include <sys/socket.h> #include <netinet/in.h> #include <netinet/ip.h> #include <netinet/ip6.h> #include <netinet/tcp.h> #include <errno.h> #include <sys/signal.h> #include <signal.h> #include <sys/resource.h> #include <time.h> ' ccflags="$@" # Write go tool cgo -godefs input. ( echo package unix echo echo '/*' indirect="includes_$(uname)" echo "${!indirect} $includes" echo '*/' echo 'import "C"' echo 'import "syscall"' echo echo 'const (' # The gcc command line prints all the #defines # it encounters while processing the input echo "${!indirect} $includes" | $CC -x c - -E -dM $ccflags | awk ' $1 != "#define" || $2 ~ /\(/ || $3 == "" {next} $2 ~ /^E([ABCD]X|[BIS]P|[SD]I|S|FL)$/ {next} # 386 registers $2 ~ /^(SIGEV_|SIGSTKSZ|SIGRT(MIN|MAX))/ {next} $2 ~ /^(SCM_SRCRT)$/ {next} $2 ~ /^(MAP_FAILED)$/ {next} $2 ~ /^ELF_.*$/ {next}# <asm/elf.h> contains ELF_ARCH, etc. $2 ~ /^EXTATTR_NAMESPACE_NAMES/ || $2 ~ /^EXTATTR_NAMESPACE_[A-Z]+_STRING/ {next} $2 !~ /^ECCAPBITS/ && $2 !~ /^ETH_/ && $2 !~ /^EPROC_/ && $2 !~ /^EQUIV_/ && $2 !~ /^EXPR_/ && $2 !~ /^EVIOC/ && $2 !~ /^EV_/ && $2 ~ /^E[A-Z0-9_]+$/ || $2 ~ /^B[0-9_]+$/ || $2 ~ /^(OLD|NEW)DEV$/ || $2 == "BOTHER" || $2 ~ /^CI?BAUD(EX)?$/ || $2 == "IBSHIFT" || $2 ~ /^V[A-Z0-9]+$/ || $2 ~ /^CS[A-Z0-9]/ || $2 ~ /^I(SIG|CANON|CRNL|UCLC|EXTEN|MAXBEL|STRIP|UTF8)$/ || $2 ~ /^IGN/ || $2 ~ /^IX(ON|ANY|OFF)$/ || $2 ~ /^IN(LCR|PCK)$/ || $2 !~ "X86_CR3_PCID_NOFLUSH" && $2 ~ /(^FLU?SH)|(FLU?SH$)/ || $2 ~ /^C(LOCAL|READ|MSPAR|RTSCTS)$/ || $2 == "BRKINT" || $2 == "HUPCL" || $2 == "PENDIN" || $2 == "TOSTOP" || $2 == "XCASE" || $2 == "ALTWERASE" || $2 == "NOKERNINFO" || $2 == "NFDBITS" || $2 ~ /^PAR/ || $2 ~ /^SIG[^_]/ || $2 ~ /^O[CNPFPL][A-Z]+[^_][A-Z]+$/ || $2 ~ /^(NL|CR|TAB|BS|VT|FF)DLY$/ || $2 ~ /^(NL|CR|TAB|BS|VT|FF)[0-9]$/ || $2 ~ /^O?XTABS$/ || $2 ~ /^TC[IO](ON|OFF)$/ || $2 ~ /^IN_/ || $2 ~ /^LOCK_(SH|EX|NB|UN)$/ || $2 ~ /^LO_(KEY|NAME)_SIZE$/ || $2 ~ /^LOOP_(CLR|CTL|GET|SET)_/ || $2 ~ /^(AF|SOCK|SO|SOL|IPPROTO|IP|IPV6|TCP|MCAST|EVFILT|NOTE|SHUT|PROT|MAP|MFD|T?PACKET|MSG|SCM|MCL|DT|MADV|PR|LOCAL)_/ || $2 ~ /^NFC_(GENL|PROTO|COMM|RF|SE|DIRECTION|LLCP|SOCKPROTO)_/ || $2 ~ /^NFC_.*_(MAX)?SIZE$/ || $2 ~ /^RAW_PAYLOAD_/ || $2 ~ /^TP_STATUS_/ || $2 ~ /^FALLOC_/ || $2 ~ /^ICMPV?6?_(FILTER|SEC)/ || $2 == "SOMAXCONN" || $2 == "NAME_MAX" || $2 == "IFNAMSIZ" || $2 ~ /^CTL_(HW|KERN|MAXNAME|NET|QUERY)$/ || $2 ~ /^KERN_(HOSTNAME|OS(RELEASE|TYPE)|VERSION)$/ || $2 ~ /^HW_MACHINE$/ || $2 ~ /^SYSCTL_VERS/ || $2 !~ "MNT_BITS" && $2 ~ /^(MS|MNT|UMOUNT)_/ || $2 ~ /^NS_GET_/ || $2 ~ /^TUN(SET|GET|ATTACH|DETACH)/ || $2 ~ /^(O|F|[ES]?FD|NAME|S|PTRACE|PT|TFD)_/ || $2 ~ /^KEXEC_/ || $2 ~ /^LINUX_REBOOT_CMD_/ || $2 ~ /^LINUX_REBOOT_MAGIC[12]$/ || $2 ~ /^MODULE_INIT_/ || $2 !~ "NLA_TYPE_MASK" && $2 !~ /^RTC_VL_(ACCURACY|BACKUP|DATA)/ && $2 ~ /^(NETLINK|NLM|NLMSG|NLA|IFA|IFAN|RT|RTC|RTCF|RTN|RTPROT|RTNH|ARPHRD|ETH_P|NETNSA)_/ || $2 ~ /^FIORDCHK$/ || $2 ~ /^SIOC/ || $2 ~ /^TIOC/ || $2 ~ /^TCGET/ || $2 ~ /^TCSET/ || $2 ~ /^TC(FLSH|SBRKP?|XONC)$/ || $2 !~ "RTF_BITS" && $2 ~ /^(IFF|IFT|NET_RT|RTM(GRP)?|RTF|RTV|RTA|RTAX)_/ || $2 ~ /^BIOC/ || $2 ~ /^DIOC/ || $2 ~ /^RUSAGE_(SELF|CHILDREN|THREAD)/ || $2 ~ /^RLIMIT_(AS|CORE|CPU|DATA|FSIZE|LOCKS|MEMLOCK|MSGQUEUE|NICE|NOFILE|NPROC|RSS|RTPRIO|RTTIME|SIGPENDING|STACK)|RLIM_INFINITY/ || $2 ~ /^PRIO_(PROCESS|PGRP|USER)/ || $2 ~ /^CLONE_[A-Z_]+/ || $2 !~ /^(BPF_TIMEVAL|BPF_FIB_LOOKUP_[A-Z]+)$/ && $2 ~ /^(BPF|DLT)_/ || $2 ~ /^(CLOCK|TIMER)_/ || $2 ~ /^CAN_/ || $2 ~ /^CAP_/ || $2 ~ /^CP_/ || $2 ~ /^CPUSTATES$/ || $2 ~ /^CTLIOCGINFO$/ || $2 ~ /^ALG_/ || $2 ~ /^FI(CLONE|DEDUPERANGE)/ || $2 ~ /^FS_(POLICY_FLAGS|KEY_DESC|ENCRYPTION_MODE|[A-Z0-9_]+_KEY_SIZE)/ || $2 ~ /^FS_IOC_.*(ENCRYPTION|VERITY|[GS]ETFLAGS)/ || $2 ~ /^FS_VERITY_/ || $2 ~ /^FSCRYPT_/ || $2 ~ /^DM_/ || $2 ~ /^GRND_/ || $2 ~ /^RND/ || $2 ~ /^KEY_(SPEC|REQKEY_DEFL)_/ || $2 ~ /^KEYCTL_/ || $2 ~ /^PERF_/ || $2 ~ /^SECCOMP_MODE_/ || $2 ~ /^SPLICE_/ || $2 ~ /^SYNC_FILE_RANGE_/ || $2 !~ /^AUDIT_RECORD_MAGIC/ && $2 !~ /IOC_MAGIC/ && $2 ~ /^[A-Z][A-Z0-9_]+_MAGIC2?$/ || $2 ~ /^(VM|VMADDR)_/ || $2 ~ /^IOCTL_VM_SOCKETS_/ || $2 ~ /^(TASKSTATS|TS)_/ || $2 ~ /^CGROUPSTATS_/ || $2 ~ /^GENL_/ || $2 ~ /^STATX_/ || $2 ~ /^RENAME/ || $2 ~ /^UBI_IOC[A-Z]/ || $2 ~ /^UTIME_/ || $2 ~ /^XATTR_(CREATE|REPLACE|NO(DEFAULT|FOLLOW|SECURITY)|SHOWCOMPRESSION)/ || $2 ~ /^ATTR_(BIT_MAP_COUNT|(CMN|VOL|FILE)_)/ || $2 ~ /^FSOPT_/ || $2 ~ /^WDIO[CFS]_/ || $2 ~ /^NFN/ || $2 ~ /^XDP_/ || $2 ~ /^RWF_/ || $2 ~ /^(HDIO|WIN|SMART)_/ || $2 ~ /^CRYPTO_/ || $2 ~ /^TIPC_/ || $2 !~ "DEVLINK_RELOAD_LIMITS_VALID_MASK" && $2 ~ /^DEVLINK_/ || $2 ~ /^ETHTOOL_/ || $2 ~ /^LWTUNNEL_IP/ || $2 !~ "WMESGLEN" && $2 ~ /^W[A-Z0-9]+$/ || $2 ~/^PPPIOC/ || $2 ~ /^FAN_|FANOTIFY_/ || $2 == "HID_MAX_DESCRIPTOR_SIZE" || $2 ~ /^_?HIDIOC/ || $2 ~ /^BUS_(USB|HIL|BLUETOOTH|VIRTUAL)$/ || $2 ~ /^MTD/ || $2 ~ /^OTP/ || $2 ~ /^MEM/ || $2 ~ /^BLK[A-Z]*(GET$|SET$|BUF$|PART$|SIZE)/ {printf("\t%s = C.%s\n", $2, $2)} $2 ~ /^__WCOREFLAG$/ {next} $2 ~ /^__W[A-Z0-9]+$/ {printf("\t%s = C.%s\n", substr($2,3), $2)} {next} ' | sort echo ')' ) >_const.go # Pull out the error names for later. errors=$( echo '#include <errno.h>' | $CC -x c - -E -dM $ccflags | awk '$1=="#define" && $2 ~ /^E[A-Z0-9_]+$/ { print $2 }' | sort ) # Pull out the signal names for later. signals=$( echo '#include <signal.h>' | $CC -x c - -E -dM $ccflags | awk '$1=="#define" && $2 ~ /^SIG[A-Z0-9]+$/ { print $2 }' | egrep -v '(SIGSTKSIZE|SIGSTKSZ|SIGRT|SIGMAX64)' | sort ) # Again, writing regexps to a file. echo '#include <errno.h>' | $CC -x c - -E -dM $ccflags | awk '$1=="#define" && $2 ~ /^E[A-Z0-9_]+$/ { print "^\t" $2 "[ \t]*=" }' | sort >_error.grep echo '#include <signal.h>' | $CC -x c - -E -dM $ccflags | awk '$1=="#define" && $2 ~ /^SIG[A-Z0-9]+$/ { print "^\t" $2 "[ \t]*=" }' | egrep -v '(SIGSTKSIZE|SIGSTKSZ|SIGRT|SIGMAX64)' | sort >_signal.grep echo '// mkerrors.sh' "$@" echo '// Code generated by the command above; see README.md. DO NOT EDIT.' echo echo "//go:build ${GOARCH} && ${GOOS}" echo "// +build ${GOARCH},${GOOS}" echo go tool cgo -godefs -- "$@" _const.go >_error.out cat _error.out | grep -vf _error.grep | grep -vf _signal.grep echo echo '// Errors' echo 'const (' cat _error.out | grep -f _error.grep | sed 's/=\(.*\)/= syscall.Errno(\1)/' echo ')' echo echo '// Signals' echo 'const (' cat _error.out | grep -f _signal.grep | sed 's/=\(.*\)/= syscall.Signal(\1)/' echo ')' # Run C program to print error and syscall strings. ( echo -E " #include <stdio.h> #include <stdlib.h> #include <errno.h> #include <ctype.h> #include <string.h> #include <signal.h> #define nelem(x) (sizeof(x)/sizeof((x)[0])) enum { A = 'A', Z = 'Z', a = 'a', z = 'z' }; // avoid need for single quotes below struct tuple { int num; const char *name; }; struct tuple errors[] = { " for i in $errors do echo -E ' {'$i', "'$i'" },' done echo -E " }; struct tuple signals[] = { " for i in $signals do echo -E ' {'$i', "'$i'" },' done # Use -E because on some systems bash builtin interprets \n itself. echo -E ' }; static int tuplecmp(const void *a, const void *b) { return ((struct tuple *)a)->num - ((struct tuple *)b)->num; } int main(void) { int i, e; char buf[1024], *p; printf("\n\n// Error table\n"); printf("var errorList = [...]struct {\n"); printf("\tnum syscall.Errno\n"); printf("\tname string\n"); printf("\tdesc string\n"); printf("} {\n"); qsort(errors, nelem(errors), sizeof errors[0], tuplecmp); for(i=0; i<nelem(errors); i++) { e = errors[i].num; if(i > 0 && errors[i-1].num == e) continue; strcpy(buf, strerror(e)); // lowercase first letter: Bad -> bad, but STREAM -> STREAM. if(A <= buf[0] && buf[0] <= Z && a <= buf[1] && buf[1] <= z) buf[0] += a - A; printf("\t{ %d, \"%s\", \"%s\" },\n", e, errors[i].name, buf); } printf("}\n\n"); printf("\n\n// Signal table\n"); printf("var signalList = [...]struct {\n"); printf("\tnum syscall.Signal\n"); printf("\tname string\n"); printf("\tdesc string\n"); printf("} {\n"); qsort(signals, nelem(signals), sizeof signals[0], tuplecmp); for(i=0; i<nelem(signals); i++) { e = signals[i].num; if(i > 0 && signals[i-1].num == e) continue; strcpy(buf, strsignal(e)); // lowercase first letter: Bad -> bad, but STREAM -> STREAM. if(A <= buf[0] && buf[0] <= Z && a <= buf[1] && buf[1] <= z) buf[0] += a - A; // cut trailing : number. p = strrchr(buf, ":"[0]); if(p) *p = '\0'; printf("\t{ %d, \"%s\", \"%s\" },\n", e, signals[i].name, buf); } printf("}\n\n"); return 0; } ' ) >_errors.c $CC $ccflags -o _errors _errors.c && $GORUN ./_errors && rm -f _errors.c _errors _const.go _error.grep _signal.grep _error.out
Shell
;;; subatomic-theme.el --- Low contrast bluish color theme ;; Copyright (C) 2012, 2013, 2014, 2015, 2016 John Olsson ;; Author: John Olsson <john@cryon.se> ;; Maintainer: John Olsson <john@cryon.se> ;; URL: https://github.com/cryon/subatomic ;; Created: 25th December 2012 ;; Version: 1.8.2 ;; Keywords: color-theme, blue, low contrast ;; This file is free software: you can redistribute it and/or modify ;; it under the terms of the GNU General Public License as published ;; by the Free Software Foundation, either version 3 of the License, ;; or (at your option) any later version. ;; This file 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 ;; General Public License for more details. ;; You should have received a copy of the GNU General Public License ;; along with this file. If not, see <http://www.gnu.org/licenses/>. ;;; Commentary: ;; A low contrast bluish color theme. A high contrast mode can be toggled in the ;; "subatomic" customization group. ;;; Code: (deftheme subatomic "subatomic emacs theme") (defgroup subatomic nil "Subatomic theme options. The theme has to be reloaded after changing anything in this group." :group 'faces) (defcustom subatomic-high-contrast nil "Makes the general contrast higher by setting the background as black." :type 'boolean :group 'subatomic) (defcustom subatomic-more-visible-comment-delimiters nil "Makes the comment delimiter characters the same color as the rest of the comment" :type 'boolean :group 'subatomic) (let ((midnight (if subatomic-high-contrast "#000000" "#303347")) (midnight-1 "#2e3043") (midnight-2 "#2a2c3e") (midnight-3 "#232533") (midnight-red "#421d17") (mystic-blue "#696e92") (victory-blue "#8aa6bc") (victory-blue+1 "#9dbbd3") (jungle-green "#a9dc69") (undergrowth-green "#81a257") (contrast-green "#22aa22") (deep-gold "#f9b529") (bright-gold "#ffd700") (axiomatic-purple "#9c71a5") (brick-red "#ea8673") (contrast-red "#aa2222") (piggy-pink "#feccd4") (relaxed-white "#e5e5e5") (cold-mud "#cebca5") (full-white "#ffffff") (full-black "#000000") (full-red "#ff0000") (full-green "#00ff00") (full-blue "#0000ff") (full-yellow "#ffff00") (full-magenta "#ff00ff") (full-cyan "#00ffff")) (custom-theme-set-faces 'subatomic ;; default stuff `(default ((t (:background ,midnight :foreground ,relaxed-white)))) `(fringe ((t (:background ,midnight)))) `(linum ((t (:background ,midnight :foreground ,mystic-blue)))) `(vertical-border ((t (:foreground ,midnight-2)))) `(region ((t (:background ,mystic-blue :foreground ,full-white)))) `(show-paren-match-face ((t (:foreground ,full-green :bold t)))) `(show-paren-mismatch-face ((t (:foreground ,full-red :bold t)))) `(isearch ((t (:background ,midnight-2 :foreground ,full-green :bold t)))) `(lazy-highlight ((t (:background ,midnight-2 :foreground ,deep-gold :bold t)))) `(query-replace ((t (:inherit lazy-highlight)))) `(trailing-whitespace ((t (:inherit show-paren-mismatch-face :underline t)))) `(mode-line ((t (:background ,midnight-3 :foreground ,full-white :weight bold :box (:line-width 1 :style released-button))))) `(powerline-active1 ((t (:background ,midnight-2)))) `(powerline-active2 ((t (:background ,midnight-1)))) `(mode-line-inactive ((t (:background ,midnight-2 :foreground ,mystic-blue)))) `(powerline-inactive1 ((t (:background ,midnight-2)))) `(powerline-inactive2 ((t (:background ,midnight-1)))) `(header-line ((t (:background ,midnight-3 :foreground ,full-white :weight bold)))) `(hl-line ((t (:background ,(if subatomic-high-contrast midnight-3 midnight-1))))) `(highlight-current-line-face ((t (:inherit hl-line)))) `(minibuffer-prompt ((t (:foreground ,axiomatic-purple :weight bold)))) `(escape-glyph ((t (:foreground ,cold-mud :weight bold)))) `(link ((t (:foreground ,victory-blue+1 :weight bold :underline t)))) ;; font lock `(font-lock-keyword-face ((t (:foreground ,deep-gold :weight bold)))) `(font-lock-function-name-face ((t (:foreground ,victory-blue)))) `(font-lock-warning-face ((t (:foreground ,brick-red)))) `(font-lock-builtin-face ((t (:foreground ,deep-gold)))) `(font-lock-variable-name-face ((t (:foreground ,victory-blue)))) `(font-lock-constant-face ((t (:foreground ,full-white, :weight bold :italic t)))) `(font-lock-type-face ((t (:foreground ,victory-blue+1 :weight bold)))) `(font-lock-negation-char-face ((t (:foreground ,brick-red :weight bold)))) `(font-lock-preprocessor-face ((t (:foreground ,cold-mud)))) `(font-lock-comment-face ((t (:foreground ,mystic-blue)))) `(font-lock-string-face ((t (:foreground ,jungle-green)))) `(font-lock-comment-delimiter-face ((t (:foreground ,(if subatomic-more-visible-comment-delimiters mystic-blue midnight-3))))) `(font-lock-doc-face ((t (:foreground ,axiomatic-purple :italic t)))) ;; flymake `(flymake-errline ((t (:underline ,full-red)))) `(flymake-warnline ((t (:underline ,full-yellow)))) ;; eshell `(eshell-ls-clutter ((t (:inherit font-lock-comment-face)))) `(eshell-ls-executable ((t (:foreground ,jungle-green)))) `(eshell-ls-directory ((t (:foreground ,victory-blue :bold t)))) `(eshell-ls-archive ((t (:foreground ,deep-gold)))) `(eshell-ls-backup ((t (:inherit font-lock-comment-face)))) `(eshell-ls-missing ((t (:inherit font-lock-warning-face)))) `(eshell-ls-unreadable ((t (:inherit font-lock-warning-face)))) `(eshell-ls-symlink ((t (:inherit font-lock-builtin-face)))) `(eshell-prompt ((t (:inherit minibuffer-prompt)))) `(eshell-ls-backup ((t (:foreground ,brick-red :slant italic)))) `(eshell-ls-product ((t (:inherit default :weight bold)))) `(eshell-ls-readonly ((t (:inherit font-lock-comment)))) `(eshell-ls-special ((t (:foreground ,cold-mud)))) ;; calendar `(calendar-today-face ((t (:foreground ,jungle-green :bold t)))) `(holiday-face ((t (:foreground ,brick-red)))) `(diary-face ((t (:foreground ,axiomatic-purple)))) ;; ido-mode `(ido-subdir ((t (:inherit eshell-ls-directory)))) `(ido-only-match ((t (:foreground ,jungle-green :bold t)))) `(ido-first-match ((t (:foreground ,deep-gold :bold t)))) `(ido-virtual ((t (:inherit font-lock-comment-face)))) ;; Can't really figure out what these are for... ;; `(ido-indicator ;; ((t (:foreground ,brick-red :bold t)))) ;; ;; `(ido-inclomplete-regexp ;; ((t (:foreground ,piggy-pink)))) ;; jabber `(jabber-roster-user-online ((t (:foreground ,jungle-green)))) `(jabber-roster-user-offline ((t (:foreground ,mystic-blue)))) `(jabber-roster-user-dnd ((t (:foreground ,brick-red)))) `(jabber-roster-user-away ((t (:foreground ,cold-mud)))) `(jabber-roster-user-chatty ((t (:foreground ,victory-blue+1 :bold t)))) `(jabber-roster-user-xa ((t (:foreground ,brick-red)))) `(jabber-roster-user-error ((t (:foreground ,full-red)))) `(jabber-chat-prompt-local ((t (:foreground ,victory-blue+1)))) `(jabber-chat-prompt-foreign ((t (:foreground ,cold-mud)))) `(jabber-chat-text-local ((t (:foreground ,relaxed-white)))) `(jabber-chat-text-foreign ((t (:foreground ,relaxed-white)))) `(jabber-rare-time-face ((t (:foreground ,mystic-blue :bold t)))) `(jabber-activity-face ((t (:foreground ,deep-gold :bold t)))) `(jabber-activity-personal-face ((t (:foreground ,cold-mud :bold t)))) `(jabber-chat-error ((t (:foreground ,full-red)))) `(jabber-chat-prompt-system ((t (:foreground ,full-red)))) `(jabber-title-large ((t (:foreground ,deep-gold :height 1.3 :bold t)))) `(jabber-title-medium ((t (:foreground ,deep-gold :bold t)))) `(jabber-title-small ((t (:foreground ,deep-gold)))) ;; erc `(erc-default-face ((t (:inherit default)))) `(erc-current-nick-face ((t (:inherit font-lock-keyword-face)))) `(erc-action-face ((t (:foreground ,cold-mud)))) `(erc-dangerous-host-face ((t (:inherit font-lock-warning-face)))) `(erc-highlight-face ((t (:weight bold)))) `(erc-direct-msg-face ((t (:foreground ,jungle-green)))) `(erc-nick-msg-face ((t (:foreground ,victory-blue+1 :weight bold)))) `(erc-fool-face ((t (:inherit font-lock-comment-face)))) `(erc-input-face ((t (:inherit default :weight bold)))) `(erc-error-face ((t (:inherit font-lock-warning-face)))) `(erc-keyword-face ((t (:inherit font-lock-keyword-face)))) `(erc-nick-default-face ((t (:inherit default)))) `(erc-prompt-face ((t (:inherit eshell-prompt)))) `(erc-notice-face ((t (:foreground ,axiomatic-purple)))) `(erc-timestamp-face ((t (:inherit font-lock-comment-face)))) `(erc-pal-face ((t (:foreground ,jungle-green)))) ;; highlight-symbol `(highlight-symbol-face ((t (:background ,midnight-3)))) ;; diff `(diff-file-header ((t (:background ,midnight :foreground ,relaxed-white :weight bold)))) `(diff-header ((t (:inherit default :foreground ,mystic-blue)))) `(diff-indicator-changed ((t (:foreground ,full-yellow :weight bold)))) `(diff-changed ((t (:foreground ,deep-gold)))) `(diff-indicator-removed ((t (:foreground ,full-red :weight bold)))) `(diff-removed ((t (:foreground ,brick-red)))) `(diff-indicator-added ((t (:foreground ,full-green :weight bold)))) `(diff-added ((t (:foreground ,jungle-green)))) `(diff-hunk-header ((t (:foreground ,axiomatic-purple)))) `(diff-refine-removed ((t (:background ,contrast-red :foreground ,relaxed-white :weight bold)))) `(diff-refine-added ((t (:background ,contrast-green :foreground ,relaxed-white :weight bold)))) `(diff-refine-change ((t (:background ,deep-gold :foreground ,relaxed-white :weight bold)))) ;; magit (new faces since 2.1.0) ;; there may be some duplication with the older magit faces. ;; they should be merged over time. `(magit-bisect-bad ((t (:foreground ,brick-red)))) `(magit-bisect-good ((t (:foreground ,jungle-green)))) `(magit-bisect-skip ((t (:inherit default)))) `(magit-blame-date ((t (:foreground ,cold-mud :background ,midnight-3)))) `(magit-blame-hash ((t (:foreground ,mystic-blue :background ,midnight-3)))) `(magit-blame-heading ((t (:background ,midnight-3)))) `(magit-blame-name ((t (:foreground ,jungle-green :background ,midnight-3 :bold t)))) `(magit-blame-summary ((t (:foreground ,relaxed-white :background ,midnight-3 :bold t)))) `(magit-branch-current ((t (:foreground ,jungle-green :weight bold :underline t)))) `(magit-branch-local ((t (:foreground ,jungle-green)))) `(magit-branch-remote ((t (:foreground ,cold-mud)))) ;;`(magit-cherry-equivalent ((t (:inherit default)))) ;;`(magit-cherry-unmatched ((t (:inherit default)))) `(magit-diff-added ((t (:inherit diff-added)))) `(magit-diff-added-highlight ((t (:inherit magit-diff-added :background ,(if subatomic-high-contrast midnight-3 midnight-1))))) ;;`(magit-diff-base ((t (:inherit default)))) ;;`(magit-diff-base-highlight ((t (:inherit default)))) ;;`(magit-diff-conflict-heading ((t (:inherit default)))) `(magit-diff-context ((t (:inherit default)))) `(magit-diff-context-highlight ((t (:inherit magit-diff-context :background ,(if subatomic-high-contrast midnight-3 midnight-1))))) `(magit-diff-file-heading ((t (:inherit diff-file-header)))) ;;`(magit-diff-file-heading-highlight ((t (:inherit default)))) `(magit-diff-file-heading-selection ((t (:inherit default)))) `(magit-diff-hunk-heading ((t (:inherit diff-hunk-header)))) `(magit-diff-hunk-heading-highlight ((t (:inherit hunk-heading-highlight :background ,(if subatomic-high-contrast midnight-3 midnight-1))))) `(magit-diff-hunk-heading-selection ((t (:inherit magit-diff-hunk-heading-highlight)))) `(magit-diff-lines-boundary ((t (:inherit region)))) `(magit-diff-lines-heading ((t (:inherit magit-diff-hunk-heading-highlight)))) ;;`(magit-diff-our ((t (:inherit default)))) ;;`(magit-diff-our-highlight ((t (:inherit default)))) `(magit-diff-removed ((t (:inherit diff-removed)))) `(magit-diff-removed-highlight ((t (:inherit magit-diff-removed :background ,(if subatomic-high-contrast midnight-3 midnight-1))))) ;;`(magit-diff-their ((t (:inherit default)))) ;;`(magit-diff-their-highlight ((t (:inherit default)))) `(magit-diff-whitespace-warning ((t (:inherit trailing-whitespace)))) `(magit-diffstat-added ((t (:foreground ,jungle-green)))) `(magit-diffstat-removed ((t (:foreground ,brick-red)))) `(magit-dimmed ((t (:inherit font-lock-comment-face)))) ;;`(magit-filename ((t (:inherit default)))) `(magit-hash ((t (:foreground ,victory-blue :weight bold)))) ;;`(magit-head ((t (:inherit default)))) ;;`(magit-header-line ((t (:inherit default)))) ;;`(magit-log-author ((t (:inherit default)))) ;;`(magit-log-date ((t (:inherit default)))) ;;`(magit-log-graph ((t (:inherit default)))) `(magit-process-ng ((t (:foreground ,brick-red)))) `(magit-process-ok ((t (:foreground ,jungle-green)))) `(magit-reflog-amend ((t (:foreground ,victory-blue)))) `(magit-reflog-checkout ((t (:foreground ,victory-blue)))) `(magit-reflog-cherry-pick ((t :foreground ,victory-blue))) `(magit-reflog-commit ((t (:foreground ,victory-blue)))) `(magit-reflog-merge ((t (:foreground ,victory-blue)))) `(magit-reflog-other ((t (:foreground ,victory-blue)))) `(magit-reflog-rebase ((t (:foreground ,victory-blue)))) `(magit-reflog-remote ((t (:foreground ,victory-blue)))) `(magit-reflog-reset ((t (:foreground ,victory-blue)))) `(magit-section-heading ((t (:foreground ,deep-gold :bold t)))) ;;`(magit-section-heading-selection ((t (:inherit default)))) `(magit-section-highlight ((t (:inherit hl-line)))) ;;`(magit-sequence-done ((t (:inherit default)))) ;;`(magit-sequence-drop ((t (:inherit default)))) ;;`(magit-sequence-head ((t (:inherit default)))) ;;`(magit-sequence-onto ((t (:inherit default)))) ;;`(magit-sequence-part ((t (:inherit default)))) ;;`(magit-sequence-pick ((t (:inherit default)))) ;;`(magit-sequence-stop ((t (:inherit default)))) ;;`(magit-signature-bad ((t (:inherit default)))) ;;`(magit-signature-good ((t (:inherit default)))) ;;`(magit-signature-untrusted ((t (:inherit default)))) ;;`(magit-tag ((t (:inherit default)))) ;;`(magit-valid-signature ((t (:inherit default)))) ;; magit `(magit-branch ((t (:foreground ,jungle-green :weight bold)))) `(magit-diff-add ((t (:inherit diff-added)))) `(magit-diff-del ((t (:inherit diff-removed)))) `(magit-diff-file-header ((t (:inherit diff-file-header)))) `(magit-diff-hunk-header ((t (:inherit diff-hunk-header)))) `(magit-diff-none ((t (:inherit default)))) `(magit-header ((t (:inherit diff-header)))) `(magit-item-highlight ((t (:background ,midnight-2)))) `(magit-item-mark ((t (:background ,midnight-2)))) `(magit-log-graph ((t (:foreground ,victory-blue)))) `(magit-log-head-label-head ((t (:foreground ,cold-mud :weight bold)))) `(magit-log-head-label-bisect-bad ((t (:foreground ,brick-red)))) `(magit-log-head-label-bisect-good ((t (:foreground ,jungle-green)))) `(magit-log-head-label-default ((t (:foreground ,axiomatic-purple :weight bold)))) `(magit-log-head-label-local ((t (:inherit magit-log-head-label-default :foreground ,jungle-green)))) `(magit-log-head-label-patches ((t (:inherit magit-log-head-label-default)))) `(magit-log-head-label-remote ((t (:inherit magit-log-head-label-default :foreground ,deep-gold)))) `(magit-log-head-label-tags ((t (:inherit magit-log-head-label-default)))) `(magit-log-message ((t (:inherit default)))) `(magit-log-sha1 ((t (:foreground ,victory-blue :weight bold)))) `(magit-log-author ((t (:foreground ,jungle-green :weight normal)))) `(magit-log-date ((t (:inherit font-lock-comment-face :weight normal)))) `(magit-section-title ((t (:inherit header-line)))) `(magit-whitespace-warning-face ((t (:inherit font-lock-warning)))) `(magit-blame-header ((t (:background ,midnight-3)))) `(magit-blame-sha1 ((t (:foreground ,mystic-blue :background ,midnight-3)))) `(magit-blame-culprit ((t (:foreground ,jungle-green :background ,midnight-3 :bold t)))) `(magit-blame-time ((t (:foreground ,cold-mud :background ,midnight-3)))) `(magit-blame-subject ((t (:foreground ,relaxed-white :background ,midnight-3 :bold t)))) ;; compilation `(compilation-info ((t (:inherit default)))) `(compilation-warning ((t (:inherit font-lock-warning)))) ;; twittering-mode `(twittering-username-face ((t (:inherit font-lock-keyword-face)))) `(twittering-uri-face ((t (:inherit link)))) `(twittering-timeline-header-face ((t (:foreground ,cold-mud :weight bold)))) `(twittering-timeline-footer-face ((t (:inherit twittering-timeline-header-face)))) ;; outline `(outline-1 ((t (:foreground ,deep-gold :weight bold)))) `(outline-2 ((t (:foreground ,victory-blue+1 :weight bold)))) `(outline-3 ((t (:foreground ,jungle-green :weight bold)))) `(outline-4 ((t (:foreground ,brick-red :weight bold)))) `(outline-5 ((t (:foreground ,axiomatic-purple :weight bold)))) `(outline-6 ((t (:foreground ,undergrowth-green :weight bold)))) `(outline-7 ((t (:foreground ,mystic-blue :weight bold)))) `(outline-8 ((t (:foreground ,mystic-blue :weight bold)))) ;; org-mode `(org-level-1 ((t (:inherit outline-1)))) `(org-level-2 ((t (:inherit outline-2)))) `(org-level-3 ((t (:inherit outline-3)))) `(org-level-4 ((t (:inherit outline-4)))) `(org-level-5 ((t (:inherit outline-5)))) `(org-level-6 ((t (:inherit outline-6)))) `(org-level-7 ((t (:inherit outline-7)))) `(org-level-8 ((t (:inherit outline-8)))) `(org-hide ((t (:foreground ,midnight)))) `(org-link ((t (:inherit link)))) `(org-checkbox ((t (:background ,midnight :foreground ,full-white :weight bold :box (:line-width 1 :style released-button))))) `(org-done ((t (:foreground ,jungle-green :weight bold)))) `(org-todo ((t (:foreground ,piggy-pink :weight bold)))) `(org-table ((t (:foreground ,cold-mud)))) `(org-date ((t (:foreground ,piggy-pink :weight bold)))) `(org-document-info-keyword ((t (:foreground ,mystic-blue)))) `(org-document-info ((t (:foreground ,cold-mud :weight bold :slant italic)))) `(org-block-begin-line ((t (:background ,midnight-2 :foreground ,mystic-blue :weight bold)))) `(org-block-background ((t (:background ,midnight-1)))) `(org-block-end-line ((t (:inherit org-block-begin-line)))) `(org-agenda-date-today ((t (:foreground ,jungle-green :background ,midnight-2 :weight bold)))) `(org-agenda-date ((t (:foreground ,victory-blue+1)))) `(org-agenda-date-weekend ((t (:foreground ,piggy-pink)))) `(org-agenda-structure ((t (:inherit header-line)))) `(org-warning ((t (:inherit font-lock-warning-face)))) `(org-agenda-clocking ((t (:inherit org-date)))) `(org-deadline-announce ((t (:inherit font-lock-warning-face)))) `(org-formula ((t (:inherit font-lock-doc-face)))) `(org-special-keyword ((t (:inherit font-lock-keyword)))) ;; dired+ `(diredp-compressed-file-suffix ((t (:foreground ,deep-gold :weight bold)))) `(diredp-date-time ((t (:foreground ,mystic-blue)))) `(diredp-deletion ((t (:foreground ,brick-red :weight bold :slant italic)))) `(diredp-deletion-file-name ((t (:foreground ,brick-red :underline t)))) `(diredp-symlink ((t (:foreground ,deep-gold)))) `(diredp-dir-heading ((t (:inherit minibuffer-prompt)))) `(diredp-display-msg ((t (:inherit default)))) `(diredp-exec-priv ((t (:foreground ,jungle-green)))) `(diredp-write-priv ((t (:foreground ,brick-red)))) `(diredp-read-priv ((t (:foreground ,deep-gold)))) `(diredp-dir-priv ((t (:foreground ,victory-blue+1 :weight bold)))) `(diredp-link-priv ((t (:foreground ,deep-gold)))) `(diredp-other-priv ((t (:foreground ,deep-gold :weight bold)))) `(diredp-rare-priv ((t (:foreground ,brick-red :weight bold)))) `(diredp-no-priv ((t (:foreground ,mystic-blue)))) `(diredp-file-name ((t (:foreground ,relaxed-white)))) `(diredp-file-suffix ((t (:inherit dired-file-name)))) `(diredp-number ((t (:foreground ,victory-blue)))) `(diredp-executable-tag ((t (:foreground ,jungle-green :weight bold)))) `(diredp-flag-mark ((t (:bareground ,brick-red :weight bold)))) `(diredp-flag-mark-line ((t (:background ,midnight-2)))) `(diredp-mode-line-marked ((t (:foreground ,brick-red)))) `(diredp-mode-line-flagged ((t (:foreground ,deep-gold)))) `(diredp-ignored-file-name ((t (:foreground ,mystic-blue)))) ;; nXML `(nxml-cdata-section-CDATA ((t (:foreground ,deep-gold)))) `(nxml-cdata-section-content ((t (:foreground ,cold-mud)))) `(nxml-attribute-local-name ((t (:foreground ,relaxed-white)))) `(nxml-element-local-name ((t (:foreground ,victory-blue)))) `(nxml-element-prefix ((t (:foreground ,deep-gold)))) ;; git-gutter `(git-gutter:modified ((t (:background ,bright-gold :foreground ,bright-gold)))) `(git-gutter:added ((t (:background ,jungle-green :foreground ,jungle-green)))) `(git-gutter:deleted ((t (:background ,brick-red :foreground ,brick-red)))) `(git-gutter:separator ((t (:background ,midnight-2 :foreground ,midnight-2)))) `(git-gutter:unchanged ((t (:background ,midnight-3 :foreground ,midnight-3)))) ;; git-gutter-fringe `(git-gutter-fr:modified ((t (:background ,bright-gold :foreground ,bright-gold)))) `(git-gutter-fr:added ((t (:background ,jungle-green :foreground ,jungle-green)))) `(git-gutter-fr:deleted ((t (:background ,brick-red :foreground ,brick-red)))) ;; company-mode ;; TODO ;; company-tooltip-search - Face used for the search string in the tooltip ;; company-tooltip-mouse - Face used for the tooltip item under the mouse ;; company-preview-search - Face used for the search string in the completion preview ;; company-echo - Face used for completions in the echo area ;; company-echo-common - Face used for the common part of completions in the echo area `(company-tooltip ((t (:background ,midnight-2 :foreground ,relaxed-white)))) `(company-tooltip-selection ((t (:background ,midnight-3 :foreground ,full-white :weight bold)))) `(company-tooltip-common ((t (:background ,midnight-2 :foreground ,jungle-green :weight bold)))) `(company-tooltip-annotation ((t (:background ,midnight-2 :foreground ,mystic-blue)))) `(company-preview ((t (:background ,midnight :foreground ,bright-gold)))) `(company-preview-common ((t (:background ,midnight :foreground ,bright-gold)))) `(company-tooltip-common-selection ((t (:background ,midnight-3 :foreground ,jungle-green :weight bold)))) `(company-scrollbar-bg ((t (:background ,midnight-3 :foreground ,midnight-2)))) `(company-scrollbar-fg ((t (:background ,mystic-blue)))) ;; helm `(helm-header ((t (:inherit header-line :height 1.3 :bold t)))) `(helm-source-header ((t (:background ,midnight-1 :foreground ,axiomatic-purple :weight bold :height 1.1)))) `(helm-selection ((t (:background ,midnight-2 :weight bold)))) `(helm-candidate-number ((t (:foreground ,jungle-green)))) `(helm-match ((t (:foreground ,jungle-green :weight bold :underline t)))) `(helm-M-x-key ((t (:foreground ,victory-blue)))) `(helm-prefarg ((t (:foreground ,deep-gold)))) `(helm-selection-line ((t (:background ,midnight-2 :weight bold)))) `(helm-match-item ((t (:inherit match)))) `(helm-buffer-saved-out ((t (:foreground ,cold-mud)))) `(helm-buffer-not-saved ((t (:foreground ,piggy-pink)))) `(helm-buffer-size ((t (:foreground ,mystic-blue)))) `(helm-buffer-file ((t (:inherit default)))) `(helm-buffer-directory ((t (:foreground ,victory-blue)))) `(helm-buffer-process ((t (:inherit helm-buffer-directory)))) `(helm-grep-match ((t (:inherit helm-match)))) `(helm-grep-file ((t (:foreground ,victory-blue)))) `(helm-moccur-buffer ((t (:inherit helm-grep-file)))) `(helm-grep-lineno ((t (:foreground ,mystic-blue)))) `(helm-ff-file ((t (:inherit default)))) `(helm-ff-directory ((t (:inherit eshell-ls-directory)))) `(helm-ff-executable ((t (:inherit eshell-ls-executable)))) `(helm-ff-invalid-symlink ((t (:inherit eshell-ls-missing)))) `(helm-ff-symlink ((t (:inherit eshell-ls-symlink)))) `(helm-ff-prefix ((t (:inherit default :foreground ,mystic-blue)))) ;; TODO ;; helm-top-columns - Face for helm help string in minibuffer. ;; helm-visible-mark - Face for visible mark. ;; helm-separator - Face for multiline source separator. ;; helm-action - Face for action lines in the helm action buffer. ;; helm-header-line-left-margin - Face used to highlight helm-header sign in left-margin. ;; helm-moccur-buffer - Face used to highlight moccur buffer names. ;; helm-grep-finish - Face used in mode line when grep is finish. ;; helm-grep-cmd-line - Face used to highlight grep command line when no results. ;; helm-resume-need-update - Face used to flash moccur buffer when it needs update. ;; helm-locate-finish - Face used in mode line when locate process is finish. ;; helm-helper - Face for helm help string in minibuffer. ;; helm-ff-dotted-directory - Face used for dotted directories in `helm-find-files'. ;; helm-ff-dotted-symlink-directory - Face used for dotted symlinked directories in `helm-find-files'. ;; helm-history-deleted - Face used for deleted files in `file-name-history'. ;; helm-history-remote - Face used for remote files in `file-name-history'. ;; structured-haskell-mode `(shm-current-face ((t (:background ,midnight-2)))) `(shm-quarantine-face ((t (:background ,midnight-red)))) ;; fill-column-indicator `(fci-rule-color ((t (:background ,mystic-blue)))) ;; basic auctex support `(font-latex-sectioning-0-face ((t (:inherit outline-1 :height 1.1)))) `(font-latex-sectioning-1-face ((t (:inherit outline-2 :height 1.1)))) `(font-latex-sectioning-2-face ((t (:inherit outline-3 :height 1.1)))) `(font-latex-sectioning-3-face ((t (:inherit outline-4 :height 1.1)))) `(font-latex-sectioning-4-face ((t (:inherit outline-5 :height 1.1)))) `(font-latex-sectioning-5-face ((t (:inherit outline-6 :height 1.1)))) `(font-latex-bold-face ((t (:inherit bold :foreground ,relaxed-white)))) `(font-latex-italic-face ((t (:inherit italic :foreground ,relaxed-white)))) `(font-latex-math-face ((t (:foreground ,axiomatic-purple)))) `(font-latex-slide-title-face ((t (:inherit font-lock-type-face :weight bold :height 1.2)))) `(font-latex-string-face ((t (:inherit font-lock-string-face)))) `(font-latex-subscript-face ((t (:height 0.8)))) `(font-latex-superscript-face ((t (:height 0.8)))) `(font-latex-warning-face ((t (:inherit font-lock-warning-face)))) `(font-latex-doctex-documentation-face ((t (:background unspecified)))) `(font-latex-doctex-preprocessor-face ((t (:inherit (font-latex-doctex-documentation-face font-lock-builtin-face font-lock-preprocessor-face))))) )) ;;;###autoload (when load-file-name (add-to-list 'custom-theme-load-path (file-name-as-directory (file-name-directory load-file-name)))) (provide-theme 'subatomic) ;;; subatomic-theme.el ends here
Common Lisp
module AS.Views.Selectable def initialize: -> @events ?= {} @events["click"] = "activateSelf" @_super.apply(this, arguments) def activateSelf: (event) -> if event return unless @el.is(event.currentTarget) @navigableSelection().select @model
CoffeeScript
%% ------------------------------------------------------------------- %% %% Copyright (c) 2016 Carlos Gonzalez Florido. All Rights Reserved. %% %% This file is provided 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. %% %% ------------------------------------------------------------------- %% @doc Room Plugin -module(nkcollab_room). -author('Carlos Gonzalez <carlosj.gf@gmail.com>'). -behaviour(gen_server). -export([start/2, stop/1, stop/2]). -export([get_room/1, get_publishers/1, get_listeners/1]). -export([add_publish_session/4, add_listen_session/5, remove_session/2]). -export([remove_user_sessions/2, remove_user_all_sessions/2]). -export([get_user_sessions/2, get_user_all_sessions/2]). -export([update_publish_session/3]). -export([send_info/2, send_msg/3, get_all_msgs/1]). -export([add_timelog/2, get_timelog/1]). -export([register/2, unregister/2, get_all/0]). -export([media_session_event/3, media_room_event/2]). -export([find/1, do_call/2, do_call/3, do_cast/2]). -export([init/1, terminate/2, code_change/3, handle_call/3, handle_cast/2, handle_info/2]). -export_type([id/0, room/0, event/0]). % To debug, set debug => [nkcollab_room] -define(DEBUG(Txt, Args, State), case erlang:get(nkcollab_room_debug) of true -> ?LLOG(debug, Txt, Args, State); _ -> ok end). -define(LLOG(Type, Txt, Args, State), lager:Type( [ {room_id, State#state.id} ], "NkCOLLAB Room '~s' "++Txt, [State#state.id | Args])). -include("nkcollab_room.hrl"). -include_lib("nkservice/include/nkservice.hrl"). %% =================================================================== %% Types %% =================================================================== -type id() :: binary(). -type session_id() :: nkmedia_session:id(). -type user_id() :: binary(). -type conn_id() :: binary(). -type meta() :: map(). -type config() :: #{ backend => atom(), audio_codec => opus | isac32 | isac16 | pcmu | pcma, video_codec => vp8 | vp9 | h264, bitrate => integer(), room_meta => meta(), register => nklib:link() }. -type room() :: config() | #{ room_id => id(), srv_id => nkservice:id(), users => #{user_id() => [conn_id()]}, conns => #{conn_id() => conn_data()}, publish => #{session_id() => session_data()}, listen => #{session_id() => session_data()}, start_time => nklib_util:timestamp(), stop_time => nklib_util:timestamp(), status => map() }. -type session_config() :: #{ offer => nkmedia:offer(), no_offer_trickle_ice => boolean(), % Buffer candidates and insert in SDP no_answer_trickle_ice => boolean(), trickle_ice_timeout => integer(), sdp_type => webrtc | rtp, register => nklib:link(), mute_audio => boolean(), mute_video => boolean(), mute_data => boolean(), bitrate => integer(), class => binary(), device => binary(), meta => map(), session_events => [nkservice_events:type()], session_events_body => map() }. -type conn_data() :: #{ user_id => user_id(), sessions => [session_id()], room_events => [nkservice_events:type()], room_events_body => map() }. -type session_data() :: #{ type => publish | listen, device => atom() | binary(), bitrate => integer(), started_time => nklib_util:l_timestamp(), stopped_time => nklib_util:l_timestamp(), session_meta => map(), announce => map(), user_id => user_id(), conn_id => conn_id(), publisher_id => session_id() }. -type event() :: created | {started_publisher, session_data()} | {stopped_publisher, session_data()} | {updated_publisher, session_data()} | {started_listener, session_data()} | {stopped_listener, session_data()} | {room_info, map()} | {room_msg, msg()} | {stopped, nkservice:error()} | {record, [map()]} | destroyed. -type msg_id() :: integer(). -type msg() :: #{ msg_id => msg_id(), user_id => binary(), session_id => binary(), timestamp => nklib_util:l_timestamp(), body => map() }. %% =================================================================== %% Public %% =================================================================== %% @doc Creates a new room -spec start(nkservice:id(), config()) -> {ok, id(), pid()} | {error, term()}. start(Srv, Config) -> {RoomId, Config2} = nkmedia_util:add_id(room_id, Config, room), case find(RoomId) of {ok, _} -> {error, room_already_exists}; not_found -> case nkmedia_room:start(Srv, Config2#{class=>sfu}) of {ok, RoomId, RoomPid} -> {ok, BaseRoom} = nkmedia_room:get_room(RoomPid), BaseRoom2 = maps:with(room_opts(), BaseRoom), Config3 = maps:merge(Config2, BaseRoom2), {ok, Pid} = gen_server:start(?MODULE, [Config3, RoomPid], []), {ok, RoomId, Pid}; {error, Error} -> {error, Error} end end. %% @doc -spec stop(id()) -> ok | {error, term()}. stop(Id) -> stop(Id, user_stop). %% @doc -spec stop(id(), nkservice:error()) -> ok | {error, term()}. stop(Id, Reason) -> do_cast(Id, {stop, Reason}). %% @doc -spec get_room(id()) -> {ok, room()} | {error, term()}. get_room(Id) -> do_call(Id, get_room). %% @doc -spec get_publishers(id()) -> {ok, [session_data()]} | {error, term()}. get_publishers(Id) -> do_call(Id, get_publishers). %% @doc -spec get_listeners(id()) -> {ok, [session_data()]} | {error, term()}. get_listeners(Id) -> do_call(Id, get_listeners). %% @private -spec get_user_sessions(id(), conn_id()) -> {ok, [session_data()]} | {error, term()}. get_user_sessions(Id, ConnId) -> do_call(Id, {get_user_sessions, ConnId}). %% @private -spec get_user_all_sessions(id(), user_id()) -> {ok, [session_data()]} | {error, term()}. get_user_all_sessions(Id, UserId) -> do_call(Id, {get_user_all_sessions, UserId}). %% @doc -spec add_publish_session(id(), user_id(), conn_id(), session_config()) -> {ok, session_id(), pid()} | {error, term()}. add_publish_session(Id, UserId, ConnId, SessConfig) -> do_call(Id, {add_session, publish, UserId, ConnId, SessConfig}). %% @doc -spec add_listen_session(id(), user_id(), conn_id(), session_id(), session_config()) -> {ok, session_id(), pid()} | {error, term()}. add_listen_session(Id, UserId, ConnId, SessId, SessConfig) -> SessConfig2 = SessConfig#{publisher_id=>SessId}, do_call(Id, {add_session, listen, UserId, ConnId, SessConfig2}). %% Changes presenter's sessions and updates all viewers -spec update_publish_session(id(), session_id(), session_config()) -> {ok, session_id()} | {error, term()}. update_publish_session(Id, SessId, SessConfig) -> do_call(Id, {update_publish_session, SessId, SessConfig}). %% Removes a session -spec remove_session(id(), session_id()) -> ok | {error, term()}. remove_session(Id, SessId) -> do_cast(Id, {remove_session, SessId}). %% @doc -spec remove_user_sessions(id(), conn_id()) -> ok | {error, term()}. remove_user_sessions(Id, ConnId) -> do_cast(Id, {remove_user_sessions, ConnId}). %% @doc -spec remove_user_all_sessions(id(), user_id()) -> ok | {error, term()}. remove_user_all_sessions(Id, UserId) -> do_cast(Id, {remove_user_all_sessions, UserId}). %% @private -spec send_msg(id(), user_id(), msg()) -> {ok, msg_id()} | {error, term()}. send_msg(Id, UserId, Msg) when is_map(Msg) -> do_call(Id, {send_msg, UserId, Msg}). %% @private -spec send_info(id(), map()) -> ok | {error, term()}. send_info(Id, Data) when is_map(Data) -> do_cast(Id, {send_info, Data}). %% @doc Sends an info to the sesison -spec add_timelog(id(), map()) -> ok | {error, nkservice:error()}. add_timelog(RoomId, #{msg:=_}=Data) -> do_cast(RoomId, {add_timelog, Data}). %% @private -spec get_all_msgs(id()) -> {ok, [msg()]} | {error, term()}. get_all_msgs(Id) -> do_call(Id, get_all_msgs). %% @doc Registers a process with the room -spec register(id(), nklib:link()) -> {ok, pid()} | {error, nkservice:error()}. register(RoomId, Link) -> case find(RoomId) of {ok, Pid} -> do_cast(RoomId, {register, Link}), {ok, Pid}; not_found -> {error, room_not_found} end. %% @doc Registers a process with the call -spec unregister(id(), nklib:link()) -> ok | {error, nkservice:error()}. unregister(RoomId, Link) -> do_cast(RoomId, {unregister, Link}). %% @doc Gets currents timelog -spec get_timelog(id()) -> {ok, [map()]} | {error, nkservice:error()}. get_timelog(RoomId) -> do_call(RoomId, get_timelog). %% @doc Gets all started rooms -spec get_all() -> [{id(), pid()}]. get_all() -> [{RoomId, Meta, Pid} || {{RoomId, Meta}, Pid} <- nklib_proc:values(?MODULE)]. %% @private Called from nkcollab_room_callbacks for session events -spec media_session_event(id(), session_id(), nkmedia_session:event()) -> ok | {error, nkservice:error()}. media_session_event(RoomId, SessId, {stopped, _Reason}) -> remove_session(RoomId, SessId); media_session_event(RoomId, SessId, {status, Status}) -> do_cast(RoomId, {session_status, SessId, Status}); media_session_event(_RoomId, _SessId, _Event) -> ok. %% @private Called from nkcollab_room_callbacks for base room's events -spec media_room_event(id(), nkmedia_room:event()) -> ok | {error, nkservice:error()}. media_room_event(RoomId, {status, Class, Data}) -> lager:error("ROOM INFO: ~p, ~p", [Class, Data]), send_info(RoomId, Data#{class=>Class}); media_room_event(RoomId, {stopped, Reason}) -> stop(RoomId, Reason); media_room_event(_RoomId, _Event) -> ok. % =================================================================== %% gen_server behaviour %% =================================================================== -record(state, { id :: id(), srv_id :: nkservice:id(), backend :: nkcollab:backend(), stop_reason = false :: false | nkservice:error(), links :: nklib_links:links(), msg_pos = 1 :: integer(), msgs :: orddict:orddict(), room :: room(), started :: nklib_util:l_timestamp(), timelog = [] :: [{integer(), map()}] }). %% @private -spec init(term()) -> {ok, tuple()}. init([#{room_id:=RoomId, srv_id:=SrvId, backend:=Backend}=Room, BasePid]) -> true = nklib_proc:reg({?MODULE, RoomId}), Meta = maps:get(room_meta, Room, #{}), nklib_proc:put(?MODULE, {RoomId, Meta}), {ok, BasePid} = nkmedia_room:register(RoomId, {nkcollab_room, BasePid, self()}), Room1 = Room#{ users => #{}, conns => #{}, publish => #{}, listen => #{}, start_time => nklib_util:timestamp() }, State1 = #state{ id = RoomId, srv_id = SrvId, backend = Backend, links = nklib_links:new(), msgs = orddict:new(), room = Room1, started = nklib_util:l_timestamp() }, State2 = links_add(nkmedia_room, none, BasePid, State1), State3 = case Room of #{register:=Link} -> links_add(Link, reg, State2); _ -> State2 end, set_log(State3), nkservice_util:register_for_changes(SrvId), ?LLOG(info, "started", [], State3), State4 = do_event(created, State3), {ok, State4}. %% @private -spec handle_call(term(), {pid(), term()}, #state{}) -> {noreply, #state{}} | {reply, term(), #state{}} | {stop, Reason::term(), #state{}} | {stop, Reason::term(), Reply::term(), #state{}}. handle_call({add_session, Type, UserId, ConnId, Config}, _From, State) -> restart_timer(State), case add_session(Type, UserId, ConnId, Config, State) of {ok, SessId, State2} -> State3 = case Config of #{register:=Link} -> links_add(Link, {conn_id, UserId, ConnId}, State2); _ -> State2 end, {reply, {ok, SessId, self()}, State3}; {error, Error} -> {reply, {error, Error}, State} end; handle_call({get_user_sessions, ConnId}, _From, State) -> case do_get_conn(ConnId, State) of #{user_id:=UserId, sessions:=SessionIds} -> Sessions = [do_get_session(Id, State) || Id<-SessionIds], {reply, {ok, UserId, Sessions}, State}; not_found -> {reply, {error, user_not_found}, State} end; handle_call({get_user_all_sessions, UserId}, _From, State) -> case do_get_user_conns(UserId, State) of ConnIds when is_list(ConnIds) -> Sessions = lists:foldl( fun(ConnId, Acc) -> #{sessions:=SessionIds} = do_get_conn(ConnId, State), Acc ++ [do_get_session(Id, State) || Id<-SessionIds] end, [], ConnIds), {reply, {ok, Sessions}, State}; not_found -> {reply, {error, user_not_found}, State} end; % handle_call({update_publisher, UserId, Config}, _From, State) -> % restart_timer(State), % case get_info(UserId, State) of % {ok, Info} -> % OldSessId = maps:get(publish_session_id, Info, undefined), % case add_session(publish, UserId, Config, Info, State) of % {ok, SessId, _Info2, State2} -> % Self = self(), % spawn_link( % fun() -> % timer:sleep(500), % gen_server:cast(Self, % {switch_all_listeners, UserId, OldSessId}) % end), % {reply, {ok, SessId}, State2}; % {error, Error} -> % {reply, {error, Error}, State} % end; % not_found -> % {reply, {error, user_not_found}, State} % end; % handle_cast({switch_all_listeners, UserId, OldSessId}, State) -> % case get_info(UserId, State) of % {ok, #{publish_session_id:=NewSessId}} -> % State2 = switch_all_listeners(UserId, NewSessId, State), % State3 = case OldSessId of % undefined -> % State2; % _ -> % % stop_sessions(UserId, [OldSessId], State2); % State2 % end, % {noreply, State3}; % _ -> % ?LLOG(warning, "received switch_all_listeners for invalid publisher", % [], State), % {noreply, State} % end; handle_call(get_room, _From, #state{room=Room}=State) -> {reply, {ok, Room}, State}; handle_call(get_timelog, _From, #state{timelog=Log}=State) -> {reply, {ok, lists:reverse(Log)}, State}; handle_call(get_publishers, _From, #state{room=Room}=State) -> #{publish:=Publish} = Room, {reply, {ok, maps:values(Publish)}, State}; handle_call(get_listeners, _From, #state{room=Room}=State) -> #{listen:=Listen} = Room, {reply, {ok, maps:values(Listen)}, State}; handle_call({send_msg, UserId, Msg}, _From, #state{msg_pos=Pos, msgs=Msgs}=State) -> restart_timer(State), Msg2 = Msg#{msg_id => Pos, user_id=>UserId}, State2 = State#state{ msg_pos = Pos+1, msgs = orddict:store(Pos, Msg2, Msgs) }, State3 = do_event({room_msg, Msg2}, State2), {reply, {ok, Pos}, State3}; handle_call(get_all_msgs, _From, #state{msgs=Msgs}=State) -> restart_timer(State), Reply = [Msg || {_Id, Msg} <- orddict:to_list(Msgs)], {reply, {ok, Reply}, State}; handle_call(get_state, _From, State) -> {reply, State, State}; handle_call(Msg, From, State) -> handle(nkcollab_room_handle_call, [Msg, From], State). %% @private -spec handle_cast(term(), #state{}) -> {noreply, #state{}} | {stop, term(), #state{}}. %% @private handle_cast({remove_session, SessId}, State) -> restart_timer(State), State2 = remove_sessions([SessId], State), {noreply, State2}; handle_cast({remove_user_sessions, ConnId}, State) -> restart_timer(State), {noreply, do_remove_user_sessions(ConnId, State)}; handle_cast({remove_user_all_sessions, UserId}, State) -> restart_timer(State), case do_get_user_conns(UserId, State) of ConnIds when is_list(ConnIds) -> State2 = lists:foldl( fun(ConnId, Acc) -> case do_get_conn(ConnId, State) of #{sessions:=SessIds} -> remove_sessions(SessIds, Acc); not_found -> lager:error("REMOVING ~s, ~p", [ConnId, lager:pr(State, ?MODULE)]), Acc end end, State, ConnIds), {noreply, State2}; not_found -> {noreply, State} end; handle_cast({send_info, Data}, State) -> restart_timer(State), {noreply, do_event({room_info, Data}, State)}; handle_cast({add_timelog, Data}, State) -> restart_timer(State), {noreply, do_add_timelog(Data, State)}; handle_cast({register, Link}, State) -> ?DEBUG("proc registered (~p)", [Link], State), State2 = links_add(Link, reg, State), {noreply, State2}; handle_cast({unregister, Link}, State) -> ?DEBUG("proc unregistered (~p)", [Link], State), {noreply, links_remove(Link, State)}; handle_cast({session_status, SessId, Data}, State) -> case do_get_session(SessId, State) of #{type:=Type, status:=Status}=Session -> Session2 = Session#{status:=maps:merge(Status, Data)}, State2 = do_update_session(SessId, Session2, State), Data2 = Data#{session_id=>SessId}, State3 = do_add_timelog(Data2#{msg=>session_updated_status}, State2), ?DEBUG("updated status: ~p", [Data2], State3), State4 = case Type of publish -> do_event({updated_publisher, Data2}, State3); listen -> State3 end, {noreply, State4}; not_found -> {noreply, State} end; handle_cast({stop, Reason}, State) -> ?DEBUG("external stop: ~p", [Reason], State), do_stop(Reason, State); handle_cast(Msg, State) -> handle(nkcollab_room_handle_cast, [Msg], State). %% @private -spec handle_info(term(), #state{}) -> {noreply, #state{}} | {stop, term(), #state{}}. handle_info({'DOWN', Ref, process, _Pid, Reason}=Msg, State) -> #state{stop_reason=Stop} = State, case links_down(Ref, State) of {ok, _, _, State2} when Stop /= false -> {noreply, State2}; {ok, nkmedia_room, _, State2} -> ?LLOG(notice, "media room down", [], State2), do_stop(media_room_down, State2); {ok, _Link, {conn_id, UserId, ConnId}, State2} -> ?DEBUG("connection ~s is down (user ~s)", [ConnId, UserId], State), {noreply, do_remove_conn(ConnId, State2)}; {ok, SessId, session, State2} -> case do_get_session(SessId, State2) of #{user_id:=UserId} -> ?DEBUG("session ~s down (~p)", [SessId, UserId], State2), State3 = remove_sessions([SessId], State2), {noreply, State3}; not_found -> {noreply, State2} end; {ok, Link, reg, State2} -> #state{id=Id} = State2, case handle(nkcollab_room_reg_down, [Id, Link, Reason], State2) of {ok, State3} -> {noreply, State3}; {stop, normal, State3} -> ?DEBUG("stopping because of reg '~p' down", [Link], State2), do_stop(reg_down, State3); {stop, Reason2, State3} -> ?LLOG(notice, "stopping because of reg '~p' down (~p)", [Link, Reason2], State2), do_stop(Reason2, State3) end; not_found -> handle(nkcollab_room_handle_info, [Msg], State) end; handle_info(destroy, State) -> {stop, normal, State}; handle_info({nkservice_updated, _SrvId}, State) -> {noreply, set_log(State)}; handle_info(Msg, #state{}=State) -> handle(nkcollab_room_handle_info, [Msg], State). %% @private -spec code_change(term(), #state{}, term()) -> {ok, #state{}}. code_change(_OldVsn, State, _Extra) -> {ok, State}. %% @private -spec terminate(term(), #state{}) -> ok. terminate(Reason, #state{stop_reason=Stop, timelog=Log}=State) -> case Stop of false -> {noreply, State2} = do_stop({terminate, Reason}, State); _ -> State2 = State end, State3 = do_event({record, lists:reverse(Log)}, State2), State4 = do_event(destroyed, State3), {ok, _State5} = handle(nkcollab_room_terminate, [Reason], State4), ok. % =================================================================== %% Internal %% =================================================================== %% @private set_log(#state{srv_id=SrvId}=State) -> Debug = case nkservice_util:get_debug_info(SrvId, ?MODULE) of {true, _} -> true; _ -> false end, put(nkcollab_room_debug, Debug), State. %% @private find(Pid) when is_pid(Pid) -> {ok, Pid}; find(#{room_id:=RoomId}) -> find(RoomId); find(Id) -> Id2 = nklib_util:to_binary(Id), case nklib_proc:values({?MODULE, Id2}) of [{_, Pid}] -> {ok, Pid}; [] -> not_found end. %% @private do_call(Id, Msg) -> do_call(Id, Msg, 5000). %% @private do_call(Id, Msg, Timeout) -> case find(Id) of {ok, Pid} -> nkservice_util:call(Pid, Msg, Timeout); not_found -> {error, room_not_found} end. %% @private do_cast(Id, Msg) -> case find(Id) of {ok, Pid} -> gen_server:cast(Pid, Msg); not_found -> {error, room_not_found} end. %% @private -spec add_session(publish|{listen, session_id()}, user_id(), conn_id(), map(), #state{}) -> {ok, session_id(), #state{}} | {error, nkservice:error()}. add_session(Type, UserId, ConnId, Config, State) -> #state{srv_id=SrvId, id=RoomId, backend=Backend} = State, SessConfig1 = maps:with(session_opts(), Config), SessMeta1 = maps:get(session_meta, SessConfig1, #{}), % Fields session_events and session_events_body wil be included SessConfig2 = SessConfig1#{ backend => Backend, room_id => RoomId, register => {nkcollab_room, RoomId, self()}, session_meta => SessMeta1#{nkcollab_room=>true}, user_id => UserId, user_session => ConnId }, case nkmedia_session:start(SrvId, Type, SessConfig2) of {ok, SessId, Pid} -> SessData1 = maps:with(session_data_keys(), Config), SessData2 = SessData1#{ session_id => SessId, type => Type, started_time => nklib_util:l_timestamp(), user_id => UserId, conn_id => ConnId, status => #{} }, State2 = links_add(SessId, session, Pid, State), State3 = case Type of publish -> do_event({started_publisher, SessData2}, State2); listen -> do_event({started_listener, SessData2}, State2) end, State4 = do_update_session(SessId, SessData2, State3), State5 = do_conn_add_session(UserId, ConnId, SessId, Config, State4), Log = #{msg=>started_session, session=>SessData2}, State6 = do_add_timelog(Log, State5), {ok, SessId, State6}; {error, Error} -> {error, Error} end. %% @private remove_sessions([], State) -> State; remove_sessions([SessId|Rest], State) -> State2 = case do_get_session(SessId, State) of #{}=Session -> do_remove_session(SessId, Session, State); not_found -> State end, remove_sessions(Rest, State2). %% @private do_remove_session(SessId, Session, State) -> #{type:=Type, conn_id:=ConnId} = Session, State2 = links_remove(SessId, State), Session2 = Session#{stopped_time=>nklib_util:l_timestamp()}, State3 = do_update_session(SessId, Session2, State2), State4 = case Type of publish -> do_event({stopped_publisher, Session2}, State3); listen -> do_event({stopped_listener, Session2}, State3) end, nkmedia_session:stop(SessId, user_stop), ?DEBUG("removed session ~s", [SessId], State), State5 = do_conn_remove_session(ConnId, SessId, State4), do_add_timelog(#{msg=>stopped_session, session_id=>SessId}, State5). %% @private do_remove_user_sessions(ConnId, State) -> case do_get_conn(ConnId, State) of #{sessions:=SessIds} -> remove_sessions(SessIds, State); not_found -> State end. %% @private do_remove_conn(ConnId, #state{room=Room}=State) -> State2 = do_remove_user_sessions(ConnId, State), #{conns:=Conns} = Room, add_to_room(conns, maps:remove(ConnId, Conns), State2). % %% @private % switch_all_listeners([], _PresenterId, _PublishId, State) -> % State; % switch_all_listeners([{_UserId, Info}|Rest], PresenterId, PublishId, State) -> % State2 = case has_this_presenter(Info, PresenterId) of % {true, SessId} -> % switch_listener(SessId, PublishId), % State; % false -> % State % end, % switch_all_listeners(Rest, PresenterId, PublishId, State2). %% @private do_stop(Reason, #state{stop_reason=false, srv_id=SrvId, id=Id, room=Room}=State) -> ?LLOG(info, "stopped: ~p", [Reason], State), #{listen:=Listen} = Room, #{publish:=Publish} = Room, State2 = remove_sessions(maps:keys(Listen), State), State3 = remove_sessions(maps:keys(Publish), State2), case nkmedia_room:stop(Id) of ok -> ok; Other -> ?LLOG(notice, "error stopping base room: ~p", [Other], State) end, % Give time for possible registrations to success and capture stop event State4 = add_to_room(stop_time, nklib_util:timestamp(), State3), timer:sleep(100), State5 = do_event({stopped, Reason}, State4), {ok, State6} = handle(nkcollab_room_stop, [Reason], State5), {_Code, Txt} = nkservice_util:error_code(SrvId, Reason), State7 = do_add_timelog(#{msg=>stopped, reason=>Txt}, State6), erlang:send_after(?SRV_DELAYED_DESTROY, self(), destroy), {noreply, State7#state{stop_reason=Reason}}; do_stop(_Reason, State) -> % destroy already sent {noreply, State}. %% @private do_event(Event, #state{id=Id}=State) -> ?DEBUG("sending 'event': ~p", [Event], State), State2 = links_fold( fun(Link, AccState) -> {ok, AccState2} = handle(nkcollab_room_reg_event, [Id, Link, Event], AccState), AccState2 end, State, State), {ok, State3} = handle(nkcollab_room_event, [Id, Event], State2), State3. %% @private do_get_user_conns(UserId, #state{room=#{users:=Users}}) -> case maps:find(UserId, Users) of {ok, ConnIds} -> ConnIds; error -> not_found end. %% @private do_get_conn(ConnId, #state{room=#{conns:=Conns}}) -> case maps:find(ConnId, Conns) of {ok, Conn} -> Conn; error -> not_found end. %% @private do_conn_add_session(UserId, ConnId, SessId, Config, #state{room=Room}=State) -> #{users:=AllUsers1, conns:=AllConns1} = Room, UserConnIds1 = maps:get(UserId, AllUsers1, []), UserConnIds2 = nklib_util:store_value(ConnId, UserConnIds1), AllUsers2 = maps:put(UserId, UserConnIds2, AllUsers1), case maps:find(ConnId, AllConns1) of {ok, #{user_id:=UserId}=Conn1} -> ok; error -> Conn1 = #{} end, Sessions = maps:get(sessions, Conn1, []), Conn2 = Conn1#{ user_id => UserId, sessions => [SessId|Sessions], room_events => maps:get(room_events, Config, []), room_events_body => maps:get(room_events_body, Config, #{}) }, AllConns2 = maps:put(ConnId, Conn2, AllConns1), State#state{room=?ROOM(#{users=>AllUsers2, conns=>AllConns2}, Room)}. %% @private do_conn_remove_session(ConnId, SessId, #state{room=Room}=State) -> AllConns1 = maps:get(conns, Room), case maps:find(ConnId, AllConns1) of {ok, #{sessions:=Sessions}=Conn1} -> Conn2 = Conn1#{sessions:=Sessions--[SessId]}, AllConns2 = maps:put(ConnId, Conn2, AllConns1), add_to_room(conns, AllConns2, State); error -> State end. %% @private do_get_session(SessId, #state{room=Room}) -> Publish = maps:get(publish, Room), case maps:find(SessId, Publish) of {ok, Session} -> Session; error -> Listen = maps:get(listen, Room), case maps:find(SessId, Listen) of {ok, Sessions} -> Sessions; error -> not_found end end. %% @private do_update_session(SessId, #{stopped_time:=_}=Session, #state{room=Room}=State) -> case Session of #{type:=publish} -> Publish1 = maps:get(publish, Room), Publish2 = maps:remove(SessId, Publish1), add_to_room(publish, Publish2, State); #{type:=listen} -> Listen1 = maps:get(listen, Room), Listen2 = maps:remove(SessId, Listen1), add_to_room(listen, Listen2, State) end; do_update_session(SessId, Session, #state{room=Room}=State) -> case Session of #{type:=publish} -> Publish1 = maps:get(publish, Room), Publish2 = maps:put(SessId, Session, Publish1), add_to_room(publish, Publish2, State); #{type:=listen} -> Listen1 = maps:get(listen, Room), Listen2 = maps:put(SessId, Session, Listen1), add_to_room(listen, Listen2, State) end. %% @private add_to_room(Key, Val, #state{room=Room}=State) -> State#state{room=maps:put(Key, Val, Room)}. %% @private do_add_timelog(Msg, State) when is_atom(Msg); is_binary(Msg) -> do_add_timelog(#{msg=>Msg}, State); do_add_timelog(#{msg:=_}=Data, #state{started=Started, timelog=Log}=State) -> Time = (nklib_util:l_timestamp() - Started) div 1000, State#state{timelog=[{Time, Data}|Log]}. %% @private handle(Fun, Args, State) -> nklib_gen_server:handle_any(Fun, Args, State, #state.srv_id, #state.room). %% @private links_add(Id, Data, State) -> Pid = nklib_links:get_pid(Id), links_add(Id, Data, Pid, State). %% @private links_add(Id, Data, Pid, #state{links=Links}=State) -> State#state{links=nklib_links:add(Id, Data, Pid, Links)}. % %% @private % links_get(Link, #state{links=Links}) -> % nklib_links:get_value(Link, Links). %% @private links_remove(Id, #state{links=Links}=State) -> State#state{links=nklib_links:remove(Id, Links)}. %% @private links_down(Ref, #state{links=Links}=State) -> case nklib_links:down(Ref, Links) of {ok, Link, Data, Links2} -> {ok, Link, Data, State#state{links=Links2}}; not_found -> not_found end. %% @private links_fold(Fun, Acc, #state{links=Links}) -> nklib_links:fold(Fun, Acc, Links). %% @private restart_timer(#state{id=RoomId}) -> nkmedia_room:restart_timeout(RoomId). room_opts() -> [ srv_id, backend, timeout, audio_codec, video_codec, room_meta ]. %% @private session_opts() -> [ offer, no_offer_trickle_ice, no_answer_trickle_ice, trickle_ice_timeout, sdp_type, publisher_id, mute_audio, mute_video, mute_data, bitrate, session_meta, session_events, session_events_body ]. %% @private session_data_keys() -> [ type, device, bitrate, session_meta, announce, publisher_id ].
Erlang
package skinny.test.scalatest import org.scalatest.{ BeforeAndAfter, Suite } import scalikejdbc.{ ConnectionPool, ThreadLocalDB } /** * ThreadLocalDB auto rollback SUPPORT */ trait ThreadLocalDBAutoRollback extends BeforeAndAfter { self: Suite => before { Option(ThreadLocalDB.load()) .getOrElse { ThreadLocalDB.create(ConnectionPool.borrow()) } .beginIfNotYet() } after { ThreadLocalDB.load().rollbackIfActive() } }
Scala
unit DemoCounterForm; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Redux; type TEnumAction= (INIT, INCREMENT, DECREMENT); TFormDemoCounter = class(TForm) ButtonInc: TButton; ButtonDec: TButton; LabelCounter: TLabel; procedure ButtonIncClick(Sender: TObject); procedure ButtonDecClick(Sender: TObject); procedure FormShow(Sender: TObject); private FStore : IStore<Integer, TEnumAction>; end; var FormDemoCounter: TFormDemoCounter; implementation {$R *.dfm} procedure TFormDemoCounter.ButtonIncClick(Sender: TObject); begin FStore.dispatch(INCREMENT); end; procedure TFormDemoCounter.ButtonDecClick(Sender: TObject); begin FStore.dispatch(DECREMENT); end; procedure TFormDemoCounter.FormShow(Sender: TObject); var FReducer : TReducer<Integer,TEnumAction>; begin FReducer := function(State: Integer; Action: TEnumAction): Integer begin case Action of INCREMENT: Result := State + 1; DECREMENT: Result := State - 1; else Result := State; end; end; FStore := TStore<Integer, TEnumAction>.Create(FReducer, 0); FStore.subscribe( procedure (State: Integer) begin LabelCounter.Caption := IntToStr(State); end ); FStore.dispatch(INIT); end; end.
Pascal
ORIGIN 0 SEGMENT CODE: MULT1: LEA R0, DATA LDR R1, R0, ONE LDR R2, R0, TEN LDR R7, R0, ONE ADDLOOP: ADD R3, R3, R1 ADD R2, R2, -1 BRp ADDLOOP MULT2: AND R3, R3, 0 LDR R1, R0, OVERFLOW LDR R2, R0, FOUR LDR R7, R0, TWO ADDLOOP2: ADD R3, R3, R1 ADD R2, R2, -1 BRp ADDLOOP2 MULT3: AND R3, R3, 0 LDR R1, R0, NEG1 LDR R2, R0, NEG2 NOT R1, R1 ADD R1, R1, 1 NOT R2, R2 ADD R2, R2, 1 ADDLOOP3: ADD R3, R3, R1 ADD R2, R2, -1 BRp ADDLOOP3 HALT: BRnzp HALT SEGMENT DATA: ONE: DATA2 4x0001 TWO: DATA2 4x0002 THREE: DATA2 4x0003 FOUR: DATA2 4X0004 TEN: DATA2 4x000A OVERFLOW: DATA2 4xABCD NEG1: DATA2 4xFFFF NEG2: DATA2 4xFFFE
Assembly
[PHP] ;;;;;;;;;;;;;;;;;;; ; About php.ini ; ;;;;;;;;;;;;;;;;;;; ; PHP's initialization file, generally called php.ini, is responsible for ; configuring many of the aspects of PHP's behavior. ; PHP attempts to find and load this configuration from a number of locations. ; The following is a summary of its search order: ; 1. SAPI module specific location. ; 2. The PHPRC environment variable. (As of PHP 5.2.0) ; 3. A number of predefined registry keys on Windows (As of PHP 5.2.0) ; 4. Current working directory (except CLI) ; 5. The web server's directory (for SAPI modules), or directory of PHP ; (otherwise in Windows) ; 6. The directory from the --with-config-file-path compile time option, or the ; Windows directory (C:\windows or C:\winnt) ; See the PHP docs for more specific information. ; http://php.net/configuration.file ; The syntax of the file is extremely simple. Whitespace and lines ; beginning with a semicolon are silently ignored (as you probably guessed). ; Section headers (e.g. [Foo]) are also silently ignored, even though ; they might mean something in the future. ; Directives following the section heading [PATH=/www/mysite] only ; apply to PHP files in the /www/mysite directory. Directives ; following the section heading [HOST=www.example.com] only apply to ; PHP files served from www.example.com. Directives set in these ; special sections cannot be overridden by user-defined INI files or ; at runtime. Currently, [PATH=] and [HOST=] sections only work under ; CGI/FastCGI. ; http://php.net/ini.sections ; Directives are specified using the following syntax: ; directive = value ; Directive names are *case sensitive* - foo=bar is different from FOO=bar. ; Directives are variables used to configure PHP or PHP extensions. ; There is no name validation. If PHP can't find an expected ; directive because it is not set or is mistyped, a default value will be used. ; The value can be a string, a number, a PHP constant (e.g. E_ALL or M_PI), one ; of the INI constants (On, Off, True, False, Yes, No and None) or an expression ; (e.g. E_ALL & ~E_NOTICE), a quoted string ("bar"), or a reference to a ; previously set variable or directive (e.g. ${foo}) ; Expressions in the INI file are limited to bitwise operators and parentheses: ; | bitwise OR ; ^ bitwise XOR ; & bitwise AND ; ~ bitwise NOT ; ! boolean NOT ; Boolean flags can be turned on using the values 1, On, True or Yes. ; They can be turned off using the values 0, Off, False or No. ; An empty string can be denoted by simply not writing anything after the equal ; sign, or by using the None keyword: ; foo = ; sets foo to an empty string ; foo = None ; sets foo to an empty string ; foo = "None" ; sets foo to the string 'None' ; If you use constants in your value, and these constants belong to a ; dynamically loaded extension (either a PHP extension or a Zend extension), ; you may only use these constants *after* the line that loads the extension. ;;;;;;;;;;;;;;;;;;; ; About this file ; ;;;;;;;;;;;;;;;;;;; ; PHP comes packaged with two INI files. One that is recommended to be used ; in production environments and one that is recommended to be used in ; development environments. ; php.ini-production contains settings which hold security, performance and ; best practices at its core. But please be aware, these settings may break ; compatibility with older or less security conscience applications. We ; recommending using the production ini in production and testing environments. ; php.ini-development is very similar to its production variant, except it is ; much more verbose when it comes to errors. We recommend using the ; development version only in development environments, as errors shown to ; application users can inadvertently leak otherwise secure information. ; This is php.ini-development INI file. ;;;;;;;;;;;;;;;;;;; ; Quick Reference ; ;;;;;;;;;;;;;;;;;;; ; The following are all the settings which are different in either the production ; or development versions of the INIs with respect to PHP's default behavior. ; Please see the actual settings later in the document for more details as to why ; we recommend these changes in PHP's behavior. ; display_errors ; Default Value: On ; Development Value: On ; Production Value: Off ; display_startup_errors ; Default Value: Off ; Development Value: On ; Production Value: Off ; error_reporting ; Default Value: E_ALL & ~E_NOTICE & ~E_STRICT & ~E_DEPRECATED ; Development Value: E_ALL ; Production Value: E_ALL & ~E_DEPRECATED & ~E_STRICT ; html_errors ; Default Value: On ; Development Value: On ; Production value: On ; log_errors ; Default Value: Off ; Development Value: On ; Production Value: On ; max_input_time ; Default Value: -1 (Unlimited) ; Development Value: 60 (60 seconds) ; Production Value: 60 (60 seconds) ; output_buffering ; Default Value: Off ; Development Value: 4096 ; Production Value: 4096 ; register_argc_argv ; Default Value: On ; Development Value: Off ; Production Value: Off ; request_order ; Default Value: None ; Development Value: "GP" ; Production Value: "GP" ; session.gc_divisor ; Default Value: 100 ; Development Value: 1000 ; Production Value: 1000 ; session.sid_bits_per_character ; Default Value: 4 ; Development Value: 5 ; Production Value: 5 ; short_open_tag ; Default Value: On ; Development Value: Off ; Production Value: Off ; track_errors ; Default Value: Off ; Development Value: On ; Production Value: Off ; variables_order ; Default Value: "EGPCS" ; Development Value: "GPCS" ; Production Value: "GPCS" ;;;;;;;;;;;;;;;;;;;; ; php.ini Options ; ;;;;;;;;;;;;;;;;;;;; ; Name for user-defined php.ini (.htaccess) files. Default is ".user.ini" ;user_ini.filename = ".user.ini" ; To disable this feature set this option to empty value ;user_ini.filename = ; TTL for user-defined php.ini files (time-to-live) in seconds. Default is 300 seconds (5 minutes) ;user_ini.cache_ttl = 300 ;;;;;;;;;;;;;;;;;;;; ; Language Options ; ;;;;;;;;;;;;;;;;;;;; ; Enable the PHP scripting language engine under Apache. ; http://php.net/engine engine = On ; This directive determines whether or not PHP will recognize code between ; <? and ?> tags as PHP source which should be processed as such. It is ; generally recommended that <?php and ?> should be used and that this feature ; should be disabled, as enabling it may result in issues when generating XML ; documents, however this remains supported for backward compatibility reasons. ; Note that this directive does not control the <?= shorthand tag, which can be ; used regardless of this directive. ; Default Value: On ; Development Value: Off ; Production Value: Off ; http://php.net/short-open-tag short_open_tag = Off ; The number of significant digits displayed in floating point numbers. ; http://php.net/precision precision = 14 ; Output buffering is a mechanism for controlling how much output data ; (excluding headers and cookies) PHP should keep internally before pushing that ; data to the client. If your application's output exceeds this setting, PHP ; will send that data in chunks of roughly the size you specify. ; Turning on this setting and managing its maximum buffer size can yield some ; interesting side-effects depending on your application and web server. ; You may be able to send headers and cookies after you've already sent output ; through print or echo. You also may see performance benefits if your server is ; emitting less packets due to buffered output versus PHP streaming the output ; as it gets it. On production servers, 4096 bytes is a good setting for performance ; reasons. ; Note: Output buffering can also be controlled via Output Buffering Control ; functions. ; Possible Values: ; On = Enabled and buffer is unlimited. (Use with caution) ; Off = Disabled ; Integer = Enables the buffer and sets its maximum size in bytes. ; Note: This directive is hardcoded to Off for the CLI SAPI ; Default Value: Off ; Development Value: 4096 ; Production Value: 4096 ; http://php.net/output-buffering output_buffering = 4096 ; You can redirect all of the output of your scripts to a function. For ; example, if you set output_handler to "mb_output_handler", character ; encoding will be transparently converted to the specified encoding. ; Setting any output handler automatically turns on output buffering. ; Note: People who wrote portable scripts should not depend on this ini ; directive. Instead, explicitly set the output handler using ob_start(). ; Using this ini directive may cause problems unless you know what script ; is doing. ; Note: You cannot use both "mb_output_handler" with "ob_iconv_handler" ; and you cannot use both "ob_gzhandler" and "zlib.output_compression". ; Note: output_handler must be empty if this is set 'On' !!!! ; Instead you must use zlib.output_handler. ; http://php.net/output-handler ;output_handler = ; URL rewriter function rewrites URL on the fly by using ; output buffer. You can set target tags by this configuration. ; "form" tag is special tag. It will add hidden input tag to pass values. ; Refer to session.trans_sid_tags for usage. ; Default Value: "form=" ; Development Value: "form=" ; Production Value: "form=" ;url_rewriter.tags ; URL rewriter will not rewrites absolute URL nor form by default. To enable ; absolute URL rewrite, allowed hosts must be defined at RUNTIME. ; Refer to session.trans_sid_hosts for more details. ; Default Value: "" ; Development Value: "" ; Production Value: "" ;url_rewriter.hosts ; Transparent output compression using the zlib library ; Valid values for this option are 'off', 'on', or a specific buffer size ; to be used for compression (default is 4KB) ; Note: Resulting chunk size may vary due to nature of compression. PHP ; outputs chunks that are few hundreds bytes each as a result of ; compression. If you prefer a larger chunk size for better ; performance, enable output_buffering in addition. ; Note: You need to use zlib.output_handler instead of the standard ; output_handler, or otherwise the output will be corrupted. ; http://php.net/zlib.output-compression zlib.output_compression = Off ; http://php.net/zlib.output-compression-level ;zlib.output_compression_level = -1 ; You cannot specify additional output handlers if zlib.output_compression ; is activated here. This setting does the same as output_handler but in ; a different order. ; http://php.net/zlib.output-handler ;zlib.output_handler = ; Implicit flush tells PHP to tell the output layer to flush itself ; automatically after every output block. This is equivalent to calling the ; PHP function flush() after each and every call to print() or echo() and each ; and every HTML block. Turning this option on has serious performance ; implications and is generally recommended for debugging purposes only. ; http://php.net/implicit-flush ; Note: This directive is hardcoded to On for the CLI SAPI implicit_flush = Off ; The unserialize callback function will be called (with the undefined class' ; name as parameter), if the unserializer finds an undefined class ; which should be instantiated. A warning appears if the specified function is ; not defined, or if the function doesn't include/implement the missing class. ; So only set this entry, if you really want to implement such a ; callback-function. unserialize_callback_func = ; When floats & doubles are serialized store serialize_precision significant ; digits after the floating point. The default value ensures that when floats ; are decoded with unserialize, the data will remain the same. ; The value is also used for json_encode when encoding double values. ; If -1 is used, then dtoa mode 0 is used which automatically select the best ; precision. serialize_precision = -1 ; open_basedir, if set, limits all file operations to the defined directory ; and below. This directive makes most sense if used in a per-directory ; or per-virtualhost web server configuration file. ; http://php.net/open-basedir ;open_basedir = ; This directive allows you to disable certain functions for security reasons. ; It receives a comma-delimited list of function names. ; http://php.net/disable-functions disable_functions = ; This directive allows you to disable certain classes for security reasons. ; It receives a comma-delimited list of class names. ; http://php.net/disable-classes disable_classes = ; Colors for Syntax Highlighting mode. Anything that's acceptable in ; <span style="color: ???????"> would work. ; http://php.net/syntax-highlighting ;highlight.string = #DD0000 ;highlight.comment = #FF9900 ;highlight.keyword = #007700 ;highlight.default = #0000BB ;highlight.html = #000000 ; If enabled, the request will be allowed to complete even if the user aborts ; the request. Consider enabling it if executing long requests, which may end up ; being interrupted by the user or a browser timing out. PHP's default behavior ; is to disable this feature. ; http://php.net/ignore-user-abort ;ignore_user_abort = On ; Determines the size of the realpath cache to be used by PHP. This value should ; be increased on systems where PHP opens many files to reflect the quantity of ; the file operations performed. ; http://php.net/realpath-cache-size ;realpath_cache_size = 4096k ; Duration of time, in seconds for which to cache realpath information for a given ; file or directory. For systems with rarely changing files, consider increasing this ; value. ; http://php.net/realpath-cache-ttl ;realpath_cache_ttl = 120 ; Enables or disables the circular reference collector. ; http://php.net/zend.enable-gc zend.enable_gc = On ; If enabled, scripts may be written in encodings that are incompatible with ; the scanner. CP936, Big5, CP949 and Shift_JIS are the examples of such ; encodings. To use this feature, mbstring extension must be enabled. ; Default: Off ;zend.multibyte = Off ; Allows to set the default encoding for the scripts. This value will be used ; unless "declare(encoding=...)" directive appears at the top of the script. ; Only affects if zend.multibyte is set. ; Default: "" ;zend.script_encoding = ;;;;;;;;;;;;;;;;; ; Miscellaneous ; ;;;;;;;;;;;;;;;;; ; Decides whether PHP may expose the fact that it is installed on the server ; (e.g. by adding its signature to the Web server header). It is no security ; threat in any way, but it makes it possible to determine whether you use PHP ; on your server or not. ; http://php.net/expose-php expose_php = On ;;;;;;;;;;;;;;;;;;; ; Resource Limits ; ;;;;;;;;;;;;;;;;;;; ; Maximum execution time of each script, in seconds ; http://php.net/max-execution-time ; Note: This directive is hardcoded to 0 for the CLI SAPI max_execution_time = 30 ; Maximum amount of time each script may spend parsing request data. It's a good ; idea to limit this time on productions servers in order to eliminate unexpectedly ; long running scripts. ; Note: This directive is hardcoded to -1 for the CLI SAPI ; Default Value: -1 (Unlimited) ; Development Value: 60 (60 seconds) ; Production Value: 60 (60 seconds) ; http://php.net/max-input-time max_input_time = 60 ; Maximum input variable nesting level ; http://php.net/max-input-nesting-level ;max_input_nesting_level = 64 ; How many GET/POST/COOKIE input variables may be accepted ; max_input_vars = 1000 ; Maximum amount of memory a script may consume (128MB) ; http://php.net/memory-limit memory_limit = 128M ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; Error handling and logging ; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; This directive informs PHP of which errors, warnings and notices you would like ; it to take action for. The recommended way of setting values for this ; directive is through the use of the error level constants and bitwise ; operators. The error level constants are below here for convenience as well as ; some common settings and their meanings. ; By default, PHP is set to take action on all errors, notices and warnings EXCEPT ; those related to E_NOTICE and E_STRICT, which together cover best practices and ; recommended coding standards in PHP. For performance reasons, this is the ; recommend error reporting setting. Your production server shouldn't be wasting ; resources complaining about best practices and coding standards. That's what ; development servers and development settings are for. ; Note: The php.ini-development file has this setting as E_ALL. This ; means it pretty much reports everything which is exactly what you want during ; development and early testing. ; ; Error Level Constants: ; E_ALL - All errors and warnings (includes E_STRICT as of PHP 5.4.0) ; E_ERROR - fatal run-time errors ; E_RECOVERABLE_ERROR - almost fatal run-time errors ; E_WARNING - run-time warnings (non-fatal errors) ; E_PARSE - compile-time parse errors ; E_NOTICE - run-time notices (these are warnings which often result ; from a bug in your code, but it's possible that it was ; intentional (e.g., using an uninitialized variable and ; relying on the fact it is automatically initialized to an ; empty string) ; E_STRICT - run-time notices, enable to have PHP suggest changes ; to your code which will ensure the best interoperability ; and forward compatibility of your code ; E_CORE_ERROR - fatal errors that occur during PHP's initial startup ; E_CORE_WARNING - warnings (non-fatal errors) that occur during PHP's ; initial startup ; E_COMPILE_ERROR - fatal compile-time errors ; E_COMPILE_WARNING - compile-time warnings (non-fatal errors) ; E_USER_ERROR - user-generated error message ; E_USER_WARNING - user-generated warning message ; E_USER_NOTICE - user-generated notice message ; E_DEPRECATED - warn about code that will not work in future versions ; of PHP ; E_USER_DEPRECATED - user-generated deprecation warnings ; ; Common Values: ; E_ALL (Show all errors, warnings and notices including coding standards.) ; E_ALL & ~E_NOTICE (Show all errors, except for notices) ; E_ALL & ~E_NOTICE & ~E_STRICT (Show all errors, except for notices and coding standards warnings.) ; E_COMPILE_ERROR|E_RECOVERABLE_ERROR|E_ERROR|E_CORE_ERROR (Show only errors) ; Default Value: E_ALL & ~E_NOTICE & ~E_STRICT & ~E_DEPRECATED ; Development Value: E_ALL ; Production Value: E_ALL & ~E_DEPRECATED & ~E_STRICT ; http://php.net/error-reporting error_reporting = E_ALL ; This directive controls whether or not and where PHP will output errors, ; notices and warnings too. Error output is very useful during development, but ; it could be very dangerous in production environments. Depending on the code ; which is triggering the error, sensitive information could potentially leak ; out of your application such as database usernames and passwords or worse. ; For production environments, we recommend logging errors rather than ; sending them to STDOUT. ; Possible Values: ; Off = Do not display any errors ; stderr = Display errors to STDERR (affects only CGI/CLI binaries!) ; On or stdout = Display errors to STDOUT ; Default Value: On ; Development Value: On ; Production Value: Off ; http://php.net/display-errors display_errors = On ; The display of errors which occur during PHP's startup sequence are handled ; separately from display_errors. PHP's default behavior is to suppress those ; errors from clients. Turning the display of startup errors on can be useful in ; debugging configuration problems. We strongly recommend you ; set this to 'off' for production servers. ; Default Value: Off ; Development Value: On ; Production Value: Off ; http://php.net/display-startup-errors display_startup_errors = On ; Besides displaying errors, PHP can also log errors to locations such as a ; server-specific log, STDERR, or a location specified by the error_log ; directive found below. While errors should not be displayed on productions ; servers they should still be monitored and logging is a great way to do that. ; Default Value: Off ; Development Value: On ; Production Value: On ; http://php.net/log-errors log_errors = On ; Set maximum length of log_errors. In error_log information about the source is ; added. The default is 1024 and 0 allows to not apply any maximum length at all. ; http://php.net/log-errors-max-len log_errors_max_len = 1024 ; Do not log repeated messages. Repeated errors must occur in same file on same ; line unless ignore_repeated_source is set true. ; http://php.net/ignore-repeated-errors ignore_repeated_errors = Off ; Ignore source of message when ignoring repeated messages. When this setting ; is On you will not log errors with repeated messages from different files or ; source lines. ; http://php.net/ignore-repeated-source ignore_repeated_source = Off ; If this parameter is set to Off, then memory leaks will not be shown (on ; stdout or in the log). This has only effect in a debug compile, and if ; error reporting includes E_WARNING in the allowed list ; http://php.net/report-memleaks report_memleaks = On ; This setting is on by default. ;report_zend_debug = 0 ; Store the last error/warning message in $php_errormsg (boolean). Setting this value ; to On can assist in debugging and is appropriate for development servers. It should ; however be disabled on production servers. ; Default Value: Off ; Development Value: On ; Production Value: Off ; http://php.net/track-errors track_errors = Off ; Turn off normal error reporting and emit XML-RPC error XML ; http://php.net/xmlrpc-errors ;xmlrpc_errors = 0 ; An XML-RPC faultCode ;xmlrpc_error_number = 0 ; When PHP displays or logs an error, it has the capability of formatting the ; error message as HTML for easier reading. This directive controls whether ; the error message is formatted as HTML or not. ; Note: This directive is hardcoded to Off for the CLI SAPI ; Default Value: On ; Development Value: On ; Production value: On ; http://php.net/html-errors html_errors = On ; If html_errors is set to On *and* docref_root is not empty, then PHP ; produces clickable error messages that direct to a page describing the error ; or function causing the error in detail. ; You can download a copy of the PHP manual from http://php.net/docs ; and change docref_root to the base URL of your local copy including the ; leading '/'. You must also specify the file extension being used including ; the dot. PHP's default behavior is to leave these settings empty, in which ; case no links to documentation are generated. ; Note: Never use this feature for production boxes. ; http://php.net/docref-root ; Examples ;docref_root = "/phpmanual/" ; http://php.net/docref-ext ;docref_ext = .html ; String to output before an error message. PHP's default behavior is to leave ; this setting blank. ; http://php.net/error-prepend-string ; Example: ;error_prepend_string = "<span style='color: #ff0000'>" ; String to output after an error message. PHP's default behavior is to leave ; this setting blank. ; http://php.net/error-append-string ; Example: ;error_append_string = "</span>" ; Log errors to specified file. PHP's default behavior is to leave this value ; empty. ; http://php.net/error-log ; Example: error_log = /var/log/php_errors.log ; Log errors to syslog (Event Log on Windows). ;error_log = syslog ;windows.show_crt_warning ; Default value: 0 ; Development value: 0 ; Production value: 0 ;;;;;;;;;;;;;;;;; ; Data Handling ; ;;;;;;;;;;;;;;;;; ; The separator used in PHP generated URLs to separate arguments. ; PHP's default setting is "&". ; http://php.net/arg-separator.output ; Example: ;arg_separator.output = "&amp;" ; List of separator(s) used by PHP to parse input URLs into variables. ; PHP's default setting is "&". ; NOTE: Every character in this directive is considered as separator! ; http://php.net/arg-separator.input ; Example: ;arg_separator.input = ";&" ; This directive determines which super global arrays are registered when PHP ; starts up. G,P,C,E & S are abbreviations for the following respective super ; globals: GET, POST, COOKIE, ENV and SERVER. There is a performance penalty ; paid for the registration of these arrays and because ENV is not as commonly ; used as the others, ENV is not recommended on productions servers. You ; can still get access to the environment variables through getenv() should you ; need to. ; Default Value: "EGPCS" ; Development Value: "GPCS" ; Production Value: "GPCS"; ; http://php.net/variables-order variables_order = "GPCS" ; This directive determines which super global data (G,P & C) should be ; registered into the super global array REQUEST. If so, it also determines ; the order in which that data is registered. The values for this directive ; are specified in the same manner as the variables_order directive, ; EXCEPT one. Leaving this value empty will cause PHP to use the value set ; in the variables_order directive. It does not mean it will leave the super ; globals array REQUEST empty. ; Default Value: None ; Development Value: "GP" ; Production Value: "GP" ; http://php.net/request-order request_order = "GP" ; This directive determines whether PHP registers $argv & $argc each time it ; runs. $argv contains an array of all the arguments passed to PHP when a script ; is invoked. $argc contains an integer representing the number of arguments ; that were passed when the script was invoked. These arrays are extremely ; useful when running scripts from the command line. When this directive is ; enabled, registering these variables consumes CPU cycles and memory each time ; a script is executed. For performance reasons, this feature should be disabled ; on production servers. ; Note: This directive is hardcoded to On for the CLI SAPI ; Default Value: On ; Development Value: Off ; Production Value: Off ; http://php.net/register-argc-argv register_argc_argv = Off ; When enabled, the ENV, REQUEST and SERVER variables are created when they're ; first used (Just In Time) instead of when the script starts. If these ; variables are not used within a script, having this directive on will result ; in a performance gain. The PHP directive register_argc_argv must be disabled ; for this directive to have any affect. ; http://php.net/auto-globals-jit auto_globals_jit = On ; Whether PHP will read the POST data. ; This option is enabled by default. ; Most likely, you won't want to disable this option globally. It causes $_POST ; and $_FILES to always be empty; the only way you will be able to read the ; POST data will be through the php://input stream wrapper. This can be useful ; to proxy requests or to process the POST data in a memory efficient fashion. ; http://php.net/enable-post-data-reading ;enable_post_data_reading = Off ; Maximum size of POST data that PHP will accept. ; Its value may be 0 to disable the limit. It is ignored if POST data reading ; is disabled through enable_post_data_reading. ; http://php.net/post-max-size post_max_size = 8M ; Automatically add files before PHP document. ; http://php.net/auto-prepend-file auto_prepend_file = ; Automatically add files after PHP document. ; http://php.net/auto-append-file auto_append_file = ; By default, PHP will output a media type using the Content-Type header. To ; disable this, simply set it to be empty. ; ; PHP's built-in default media type is set to text/html. ; http://php.net/default-mimetype default_mimetype = "text/html" ; PHP's default character set is set to UTF-8. ; http://php.net/default-charset default_charset = "UTF-8" ; PHP internal character encoding is set to empty. ; If empty, default_charset is used. ; http://php.net/internal-encoding ;internal_encoding = ; PHP input character encoding is set to empty. ; If empty, default_charset is used. ; http://php.net/input-encoding ;input_encoding = ; PHP output character encoding is set to empty. ; If empty, default_charset is used. ; See also output_buffer. ; http://php.net/output-encoding ;output_encoding = ;;;;;;;;;;;;;;;;;;;;;;;;; ; Paths and Directories ; ;;;;;;;;;;;;;;;;;;;;;;;;; ; UNIX: "/path1:/path2" ;include_path = ".:/php/includes" ; ; Windows: "\path1;\path2" ;include_path = ".;c:\php\includes" ; ; PHP's default setting for include_path is ".;/path/to/php/pear" ; http://php.net/include-path ; The root of the PHP pages, used only if nonempty. ; if PHP was not compiled with FORCE_REDIRECT, you SHOULD set doc_root ; if you are running php as a CGI under any web server (other than IIS) ; see documentation for security issues. The alternate is to use the ; cgi.force_redirect configuration below ; http://php.net/doc-root doc_root = ; The directory under which PHP opens the script using /~username used only ; if nonempty. ; http://php.net/user-dir user_dir = ; Directory in which the loadable extensions (modules) reside. ; http://php.net/extension-dir ; extension_dir = "./" ; On windows: ; extension_dir = "ext" ; Directory where the temporary files should be placed. ; Defaults to the system default (see sys_get_temp_dir) ; sys_temp_dir = "/tmp" ; Whether or not to enable the dl() function. The dl() function does NOT work ; properly in multithreaded servers, such as IIS or Zeus, and is automatically ; disabled on them. ; http://php.net/enable-dl enable_dl = Off ; cgi.force_redirect is necessary to provide security running PHP as a CGI under ; most web servers. Left undefined, PHP turns this on by default. You can ; turn it off here AT YOUR OWN RISK ; **You CAN safely turn this off for IIS, in fact, you MUST.** ; http://php.net/cgi.force-redirect ;cgi.force_redirect = 1 ; if cgi.nph is enabled it will force cgi to always sent Status: 200 with ; every request. PHP's default behavior is to disable this feature. ;cgi.nph = 1 ; if cgi.force_redirect is turned on, and you are not running under Apache or Netscape ; (iPlanet) web servers, you MAY need to set an environment variable name that PHP ; will look for to know it is OK to continue execution. Setting this variable MAY ; cause security issues, KNOW WHAT YOU ARE DOING FIRST. ; http://php.net/cgi.redirect-status-env ;cgi.redirect_status_env = ; cgi.fix_pathinfo provides *real* PATH_INFO/PATH_TRANSLATED support for CGI. PHP's ; previous behaviour was to set PATH_TRANSLATED to SCRIPT_FILENAME, and to not grok ; what PATH_INFO is. For more information on PATH_INFO, see the cgi specs. Setting ; this to 1 will cause PHP CGI to fix its paths to conform to the spec. A setting ; of zero causes PHP to behave as before. Default is 1. You should fix your scripts ; to use SCRIPT_FILENAME rather than PATH_TRANSLATED. ; http://php.net/cgi.fix-pathinfo ;cgi.fix_pathinfo=1 ; if cgi.discard_path is enabled, the PHP CGI binary can safely be placed outside ; of the web tree and people will not be able to circumvent .htaccess security. ; http://php.net/cgi.dicard-path ;cgi.discard_path=1 ; FastCGI under IIS (on WINNT based OS) supports the ability to impersonate ; security tokens of the calling client. This allows IIS to define the ; security context that the request runs under. mod_fastcgi under Apache ; does not currently support this feature (03/17/2002) ; Set to 1 if running under IIS. Default is zero. ; http://php.net/fastcgi.impersonate ;fastcgi.impersonate = 1 ; Disable logging through FastCGI connection. PHP's default behavior is to enable ; this feature. ;fastcgi.logging = 0 ; cgi.rfc2616_headers configuration option tells PHP what type of headers to ; use when sending HTTP response code. If set to 0, PHP sends Status: header that ; is supported by Apache. When this option is set to 1, PHP will send ; RFC2616 compliant header. ; Default is zero. ; http://php.net/cgi.rfc2616-headers ;cgi.rfc2616_headers = 0 ; cgi.check_shebang_line controls whether CGI PHP checks for line starting with #! ; (shebang) at the top of the running script. This line might be needed if the ; script support running both as stand-alone script and via PHP CGI<. PHP in CGI ; mode skips this line and ignores its content if this directive is turned on. ; http://php.net/cgi.check-shebang-line ;cgi.check_shebang_line=1 ;;;;;;;;;;;;;;;; ; File Uploads ; ;;;;;;;;;;;;;;;; ; Whether to allow HTTP file uploads. ; http://php.net/file-uploads file_uploads = On ; Temporary directory for HTTP uploaded files (will use system default if not ; specified). ; http://php.net/upload-tmp-dir ;upload_tmp_dir = ; Maximum allowed size for uploaded files. ; http://php.net/upload-max-filesize upload_max_filesize = 2M ; Maximum number of files that can be uploaded via a single request max_file_uploads = 20 ;;;;;;;;;;;;;;;;;; ; Fopen wrappers ; ;;;;;;;;;;;;;;;;;; ; Whether to allow the treatment of URLs (like http:// or ftp://) as files. ; http://php.net/allow-url-fopen allow_url_fopen = On ; Whether to allow include/require to open URLs (like http:// or ftp://) as files. ; http://php.net/allow-url-include allow_url_include = Off ; Define the anonymous ftp password (your email address). PHP's default setting ; for this is empty. ; http://php.net/from ;from="john@doe.com" ; Define the User-Agent string. PHP's default setting for this is empty. ; http://php.net/user-agent ;user_agent="PHP" ; Default timeout for socket based streams (seconds) ; http://php.net/default-socket-timeout default_socket_timeout = 60 ; If your scripts have to deal with files from Macintosh systems, ; or you are running on a Mac and need to deal with files from ; unix or win32 systems, setting this flag will cause PHP to ; automatically detect the EOL character in those files so that ; fgets() and file() will work regardless of the source of the file. ; http://php.net/auto-detect-line-endings ;auto_detect_line_endings = Off ;;;;;;;;;;;;;;;;;;;;;; ; Dynamic Extensions ; ;;;;;;;;;;;;;;;;;;;;;; ; If you wish to have an extension loaded automatically, use the following ; syntax: ; ; extension=modulename.extension ; ; For example, on Windows: ; ; extension=msql.dll ; ; ... or under UNIX: ; ; extension=msql.so ; ; ... or with a path: ; ; extension=/path/to/extension/msql.so ; ; If you only provide the name of the extension, PHP will look for it in its ; default extension directory. ; ; Windows Extensions ; Note that ODBC support is built in, so no dll is needed for it. ; Note that many DLL files are located in the extensions/ (PHP 4) ext/ (PHP 5+) ; extension folders as well as the separate PECL DLL download (PHP 5+). ; Be sure to appropriately set the extension_dir directive. ; ;extension=php_bz2.dll ;extension=php_curl.dll ;extension=php_fileinfo.dll ;extension=php_ftp.dll ;extension=php_gd2.dll ;extension=php_gettext.dll ;extension=php_gmp.dll ;extension=php_intl.dll ;extension=php_imap.dll ;extension=php_interbase.dll ;extension=php_ldap.dll ;extension=php_mbstring.dll ;extension=php_exif.dll ; Must be after mbstring as it depends on it ;extension=php_mysqli.dll ;extension=php_oci8_12c.dll ; Use with Oracle Database 12c Instant Client ;extension=php_openssl.dll ;extension=php_pdo_firebird.dll ;extension=php_pdo_mysql.dll ;extension=php_pdo_oci.dll ;extension=php_pdo_odbc.dll ;extension=php_pdo_pgsql.dll ;extension=php_pdo_sqlite.dll ;extension=php_pgsql.dll ;extension=php_shmop.dll ; The MIBS data available in the PHP distribution must be installed. ; See http://www.php.net/manual/en/snmp.installation.php ;extension=php_snmp.dll ;extension=php_soap.dll ;extension=php_sockets.dll ;extension=php_sqlite3.dll ;extension=php_tidy.dll ;extension=php_xmlrpc.dll ;extension=php_xsl.dll ;;;;;;;;;;;;;;;;;;; ; Module Settings ; ;;;;;;;;;;;;;;;;;;; [CLI Server] ; Whether the CLI web server uses ANSI color coding in its terminal output. cli_server.color = On [Date] ; Defines the default timezone used by the date functions ; http://php.net/date.timezone date.timezone = Asia/Shanghai ; http://php.net/date.default-latitude ;date.default_latitude = 31.7667 ; http://php.net/date.default-longitude ;date.default_longitude = 35.2333 ; http://php.net/date.sunrise-zenith ;date.sunrise_zenith = 90.583333 ; http://php.net/date.sunset-zenith ;date.sunset_zenith = 90.583333 [filter] ; http://php.net/filter.default ;filter.default = unsafe_raw ; http://php.net/filter.default-flags ;filter.default_flags = [iconv] ; Use of this INI entry is deprecated, use global input_encoding instead. ; If empty, default_charset or input_encoding or iconv.input_encoding is used. ; The precedence is: default_charset < intput_encoding < iconv.input_encoding ;iconv.input_encoding = ; Use of this INI entry is deprecated, use global internal_encoding instead. ; If empty, default_charset or internal_encoding or iconv.internal_encoding is used. ; The precedence is: default_charset < internal_encoding < iconv.internal_encoding ;iconv.internal_encoding = ; Use of this INI entry is deprecated, use global output_encoding instead. ; If empty, default_charset or output_encoding or iconv.output_encoding is used. ; The precedence is: default_charset < output_encoding < iconv.output_encoding ; To use an output encoding conversion, iconv's output handler must be set ; otherwise output encoding conversion cannot be performed. ;iconv.output_encoding = [intl] ;intl.default_locale = ; This directive allows you to produce PHP errors when some error ; happens within intl functions. The value is the level of the error produced. ; Default is 0, which does not produce any errors. ;intl.error_level = E_WARNING ;intl.use_exceptions = 0 [sqlite3] ;sqlite3.extension_dir = [Pcre] ;PCRE library backtracking limit. ; http://php.net/pcre.backtrack-limit ;pcre.backtrack_limit=100000 ;PCRE library recursion limit. ;Please note that if you set this value to a high number you may consume all ;the available process stack and eventually crash PHP (due to reaching the ;stack size limit imposed by the Operating System). ; http://php.net/pcre.recursion-limit ;pcre.recursion_limit=100000 ;Enables or disables JIT compilation of patterns. This requires the PCRE ;library to be compiled with JIT support. ;pcre.jit=1 [Pdo] ; Whether to pool ODBC connections. Can be one of "strict", "relaxed" or "off" ; http://php.net/pdo-odbc.connection-pooling ;pdo_odbc.connection_pooling=strict ;pdo_odbc.db2_instance_name [Pdo_mysql] ; If mysqlnd is used: Number of cache slots for the internal result set cache ; http://php.net/pdo_mysql.cache_size pdo_mysql.cache_size = 2000 ; Default socket name for local MySQL connects. If empty, uses the built-in ; MySQL defaults. ; http://php.net/pdo_mysql.default-socket pdo_mysql.default_socket= [Phar] ; http://php.net/phar.readonly ;phar.readonly = On ; http://php.net/phar.require-hash ;phar.require_hash = On ;phar.cache_list = [mail function] ; For Win32 only. ; http://php.net/smtp SMTP = localhost ; http://php.net/smtp-port smtp_port = 25 ; For Win32 only. ; http://php.net/sendmail-from ;sendmail_from = me@example.com ; For Unix only. You may supply arguments as well (default: "sendmail -t -i"). ; http://php.net/sendmail-path ;sendmail_path = ; Force the addition of the specified parameters to be passed as extra parameters ; to the sendmail binary. These parameters will always replace the value of ; the 5th parameter to mail(). ;mail.force_extra_parameters = ; Add X-PHP-Originating-Script: that will include uid of the script followed by the filename mail.add_x_header = On ; The path to a log file that will log all mail() calls. Log entries include ; the full path of the script, line number, To address and headers. ;mail.log = ; Log mail to syslog (Event Log on Windows). ;mail.log = syslog [SQL] ; http://php.net/sql.safe-mode sql.safe_mode = Off [ODBC] ; http://php.net/odbc.default-db ;odbc.default_db = Not yet implemented ; http://php.net/odbc.default-user ;odbc.default_user = Not yet implemented ; http://php.net/odbc.default-pw ;odbc.default_pw = Not yet implemented ; Controls the ODBC cursor model. ; Default: SQL_CURSOR_STATIC (default). ;odbc.default_cursortype ; Allow or prevent persistent links. ; http://php.net/odbc.allow-persistent odbc.allow_persistent = On ; Check that a connection is still valid before reuse. ; http://php.net/odbc.check-persistent odbc.check_persistent = On ; Maximum number of persistent links. -1 means no limit. ; http://php.net/odbc.max-persistent odbc.max_persistent = -1 ; Maximum number of links (persistent + non-persistent). -1 means no limit. ; http://php.net/odbc.max-links odbc.max_links = -1 ; Handling of LONG fields. Returns number of bytes to variables. 0 means ; passthru. ; http://php.net/odbc.defaultlrl odbc.defaultlrl = 4096 ; Handling of binary data. 0 means passthru, 1 return as is, 2 convert to char. ; See the documentation on odbc_binmode and odbc_longreadlen for an explanation ; of odbc.defaultlrl and odbc.defaultbinmode ; http://php.net/odbc.defaultbinmode odbc.defaultbinmode = 1 ;birdstep.max_links = -1 [Interbase] ; Allow or prevent persistent links. ibase.allow_persistent = 1 ; Maximum number of persistent links. -1 means no limit. ibase.max_persistent = -1 ; Maximum number of links (persistent + non-persistent). -1 means no limit. ibase.max_links = -1 ; Default database name for ibase_connect(). ;ibase.default_db = ; Default username for ibase_connect(). ;ibase.default_user = ; Default password for ibase_connect(). ;ibase.default_password = ; Default charset for ibase_connect(). ;ibase.default_charset = ; Default timestamp format. ibase.timestampformat = "%Y-%m-%d %H:%M:%S" ; Default date format. ibase.dateformat = "%Y-%m-%d" ; Default time format. ibase.timeformat = "%H:%M:%S" [MySQLi] ; Maximum number of persistent links. -1 means no limit. ; http://php.net/mysqli.max-persistent mysqli.max_persistent = -1 ; Allow accessing, from PHP's perspective, local files with LOAD DATA statements ; http://php.net/mysqli.allow_local_infile ;mysqli.allow_local_infile = On ; Allow or prevent persistent links. ; http://php.net/mysqli.allow-persistent mysqli.allow_persistent = On ; Maximum number of links. -1 means no limit. ; http://php.net/mysqli.max-links mysqli.max_links = -1 ; If mysqlnd is used: Number of cache slots for the internal result set cache ; http://php.net/mysqli.cache_size mysqli.cache_size = 2000 ; Default port number for mysqli_connect(). If unset, mysqli_connect() will use ; the $MYSQL_TCP_PORT or the mysql-tcp entry in /etc/services or the ; compile-time value defined MYSQL_PORT (in that order). Win32 will only look ; at MYSQL_PORT. ; http://php.net/mysqli.default-port mysqli.default_port = 3306 ; Default socket name for local MySQL connects. If empty, uses the built-in ; MySQL defaults. ; http://php.net/mysqli.default-socket mysqli.default_socket = ; Default host for mysql_connect() (doesn't apply in safe mode). ; http://php.net/mysqli.default-host mysqli.default_host = ; Default user for mysql_connect() (doesn't apply in safe mode). ; http://php.net/mysqli.default-user mysqli.default_user = ; Default password for mysqli_connect() (doesn't apply in safe mode). ; Note that this is generally a *bad* idea to store passwords in this file. ; *Any* user with PHP access can run 'echo get_cfg_var("mysqli.default_pw") ; and reveal this password! And of course, any users with read access to this ; file will be able to reveal the password as well. ; http://php.net/mysqli.default-pw mysqli.default_pw = ; Allow or prevent reconnect mysqli.reconnect = Off [mysqlnd] ; Enable / Disable collection of general statistics by mysqlnd which can be ; used to tune and monitor MySQL operations. ; http://php.net/mysqlnd.collect_statistics mysqlnd.collect_statistics = On ; Enable / Disable collection of memory usage statistics by mysqlnd which can be ; used to tune and monitor MySQL operations. ; http://php.net/mysqlnd.collect_memory_statistics mysqlnd.collect_memory_statistics = On ; Records communication from all extensions using mysqlnd to the specified log ; file. ; http://php.net/mysqlnd.debug ;mysqlnd.debug = ; Defines which queries will be logged. ; http://php.net/mysqlnd.log_mask ;mysqlnd.log_mask = 0 ; Default size of the mysqlnd memory pool, which is used by result sets. ; http://php.net/mysqlnd.mempool_default_size ;mysqlnd.mempool_default_size = 16000 ; Size of a pre-allocated buffer used when sending commands to MySQL in bytes. ; http://php.net/mysqlnd.net_cmd_buffer_size ;mysqlnd.net_cmd_buffer_size = 2048 ; Size of a pre-allocated buffer used for reading data sent by the server in ; bytes. ; http://php.net/mysqlnd.net_read_buffer_size ;mysqlnd.net_read_buffer_size = 32768 ; Timeout for network requests in seconds. ; http://php.net/mysqlnd.net_read_timeout ;mysqlnd.net_read_timeout = 31536000 ; SHA-256 Authentication Plugin related. File with the MySQL server public RSA ; key. ; http://php.net/mysqlnd.sha256_server_public_key ;mysqlnd.sha256_server_public_key = [OCI8] ; Connection: Enables privileged connections using external ; credentials (OCI_SYSOPER, OCI_SYSDBA) ; http://php.net/oci8.privileged-connect ;oci8.privileged_connect = Off ; Connection: The maximum number of persistent OCI8 connections per ; process. Using -1 means no limit. ; http://php.net/oci8.max-persistent ;oci8.max_persistent = -1 ; Connection: The maximum number of seconds a process is allowed to ; maintain an idle persistent connection. Using -1 means idle ; persistent connections will be maintained forever. ; http://php.net/oci8.persistent-timeout ;oci8.persistent_timeout = -1 ; Connection: The number of seconds that must pass before issuing a ; ping during oci_pconnect() to check the connection validity. When ; set to 0, each oci_pconnect() will cause a ping. Using -1 disables ; pings completely. ; http://php.net/oci8.ping-interval ;oci8.ping_interval = 60 ; Connection: Set this to a user chosen connection class to be used ; for all pooled server requests with Oracle 11g Database Resident ; Connection Pooling (DRCP). To use DRCP, this value should be set to ; the same string for all web servers running the same application, ; the database pool must be configured, and the connection string must ; specify to use a pooled server. ;oci8.connection_class = ; High Availability: Using On lets PHP receive Fast Application ; Notification (FAN) events generated when a database node fails. The ; database must also be configured to post FAN events. ;oci8.events = Off ; Tuning: This option enables statement caching, and specifies how ; many statements to cache. Using 0 disables statement caching. ; http://php.net/oci8.statement-cache-size ;oci8.statement_cache_size = 20 ; Tuning: Enables statement prefetching and sets the default number of ; rows that will be fetched automatically after statement execution. ; http://php.net/oci8.default-prefetch ;oci8.default_prefetch = 100 ; Compatibility. Using On means oci_close() will not close ; oci_connect() and oci_new_connect() connections. ; http://php.net/oci8.old-oci-close-semantics ;oci8.old_oci_close_semantics = Off [PostgreSQL] ; Allow or prevent persistent links. ; http://php.net/pgsql.allow-persistent pgsql.allow_persistent = On ; Detect broken persistent links always with pg_pconnect(). ; Auto reset feature requires a little overheads. ; http://php.net/pgsql.auto-reset-persistent pgsql.auto_reset_persistent = Off ; Maximum number of persistent links. -1 means no limit. ; http://php.net/pgsql.max-persistent pgsql.max_persistent = -1 ; Maximum number of links (persistent+non persistent). -1 means no limit. ; http://php.net/pgsql.max-links pgsql.max_links = -1 ; Ignore PostgreSQL backends Notice message or not. ; Notice message logging require a little overheads. ; http://php.net/pgsql.ignore-notice pgsql.ignore_notice = 0 ; Log PostgreSQL backends Notice message or not. ; Unless pgsql.ignore_notice=0, module cannot log notice message. ; http://php.net/pgsql.log-notice pgsql.log_notice = 0 [bcmath] ; Number of decimal digits for all bcmath functions. ; http://php.net/bcmath.scale bcmath.scale = 0 [browscap] ; http://php.net/browscap ;browscap = extra/browscap.ini [Session] ; Handler used to store/retrieve data. ; http://php.net/session.save-handler session.save_handler = files ; Argument passed to save_handler. In the case of files, this is the path ; where data files are stored. Note: Windows users have to change this ; variable in order to use PHP's session functions. ; ; The path can be defined as: ; ; session.save_path = "N;/path" ; ; where N is an integer. Instead of storing all the session files in ; /path, what this will do is use subdirectories N-levels deep, and ; store the session data in those directories. This is useful if ; your OS has problems with many files in one directory, and is ; a more efficient layout for servers that handle many sessions. ; ; NOTE 1: PHP will not create this directory structure automatically. ; You can use the script in the ext/session dir for that purpose. ; NOTE 2: See the section on garbage collection below if you choose to ; use subdirectories for session storage ; ; The file storage module creates files using mode 600 by default. ; You can change that by using ; ; session.save_path = "N;MODE;/path" ; ; where MODE is the octal representation of the mode. Note that this ; does not overwrite the process's umask. ; http://php.net/session.save-path ;session.save_path = "/tmp" ; Whether to use strict session mode. ; Strict session mode does not accept uninitialized session ID and regenerate ; session ID if browser sends uninitialized session ID. Strict mode protects ; applications from session fixation via session adoption vulnerability. It is ; disabled by default for maximum compatibility, but enabling it is encouraged. ; https://wiki.php.net/rfc/strict_sessions session.use_strict_mode = 0 ; Whether to use cookies. ; http://php.net/session.use-cookies session.use_cookies = 1 ; http://php.net/session.cookie-secure ;session.cookie_secure = ; This option forces PHP to fetch and use a cookie for storing and maintaining ; the session id. We encourage this operation as it's very helpful in combating ; session hijacking when not specifying and managing your own session id. It is ; not the be-all and end-all of session hijacking defense, but it's a good start. ; http://php.net/session.use-only-cookies session.use_only_cookies = 1 ; Name of the session (used as cookie name). ; http://php.net/session.name session.name = PHPSESSID ; Initialize session on request startup. ; http://php.net/session.auto-start session.auto_start = 0 ; Lifetime in seconds of cookie or, if 0, until browser is restarted. ; http://php.net/session.cookie-lifetime session.cookie_lifetime = 0 ; The path for which the cookie is valid. ; http://php.net/session.cookie-path session.cookie_path = / ; The domain for which the cookie is valid. ; http://php.net/session.cookie-domain session.cookie_domain = ; Whether or not to add the httpOnly flag to the cookie, which makes it inaccessible to browser scripting languages such as JavaScript. ; http://php.net/session.cookie-httponly session.cookie_httponly = ; Handler used to serialize data. php is the standard serializer of PHP. ; http://php.net/session.serialize-handler session.serialize_handler = php ; Defines the probability that the 'garbage collection' process is started ; on every session initialization. The probability is calculated by using ; gc_probability/gc_divisor. Where session.gc_probability is the numerator ; and gc_divisor is the denominator in the equation. Setting this value to 1 ; when the session.gc_divisor value is 100 will give you approximately a 1% chance ; the gc will run on any give request. ; Default Value: 1 ; Development Value: 1 ; Production Value: 1 ; http://php.net/session.gc-probability session.gc_probability = 1 ; Defines the probability that the 'garbage collection' process is started on every ; session initialization. The probability is calculated by using the following equation: ; gc_probability/gc_divisor. Where session.gc_probability is the numerator and ; session.gc_divisor is the denominator in the equation. Setting this value to 1 ; when the session.gc_divisor value is 100 will give you approximately a 1% chance ; the gc will run on any give request. Increasing this value to 1000 will give you ; a 0.1% chance the gc will run on any give request. For high volume production servers, ; this is a more efficient approach. ; Default Value: 100 ; Development Value: 1000 ; Production Value: 1000 ; http://php.net/session.gc-divisor session.gc_divisor = 1000 ; After this number of seconds, stored data will be seen as 'garbage' and ; cleaned up by the garbage collection process. ; http://php.net/session.gc-maxlifetime session.gc_maxlifetime = 1440 ; NOTE: If you are using the subdirectory option for storing session files ; (see session.save_path above), then garbage collection does *not* ; happen automatically. You will need to do your own garbage ; collection through a shell script, cron entry, or some other method. ; For example, the following script would is the equivalent of ; setting session.gc_maxlifetime to 1440 (1440 seconds = 24 minutes): ; find /path/to/sessions -cmin +24 -type f | xargs rm ; Check HTTP Referer to invalidate externally stored URLs containing ids. ; HTTP_REFERER has to contain this substring for the session to be ; considered as valid. ; http://php.net/session.referer-check session.referer_check = ; Set to {nocache,private,public,} to determine HTTP caching aspects ; or leave this empty to avoid sending anti-caching headers. ; http://php.net/session.cache-limiter session.cache_limiter = nocache ; Document expires after n minutes. ; http://php.net/session.cache-expire session.cache_expire = 180 ; trans sid support is disabled by default. ; Use of trans sid may risk your users' security. ; Use this option with caution. ; - User may send URL contains active session ID ; to other person via. email/irc/etc. ; - URL that contains active session ID may be stored ; in publicly accessible computer. ; - User may access your site with the same session ID ; always using URL stored in browser's history or bookmarks. ; http://php.net/session.use-trans-sid session.use_trans_sid = 0 ; Set session ID character length. This value could be between 22 to 256. ; Shorter length than default is supported only for compatibility reason. ; Users should use 32 or more chars. ; http://php.net/session.sid-length ; Default Value: 32 ; Development Value: 26 ; Production Value: 26 session.sid_length = 26 ; The URL rewriter will look for URLs in a defined set of HTML tags. ; <form> is special; if you include them here, the rewriter will ; add a hidden <input> field with the info which is otherwise appended ; to URLs. <form> tag's action attribute URL will not be modified ; unless it is specified. ; Note that all valid entries require a "=", even if no value follows. ; Default Value: "a=href,area=href,frame=src,form=" ; Development Value: "a=href,area=href,frame=src,form=" ; Production Value: "a=href,area=href,frame=src,form=" ; http://php.net/url-rewriter.tags session.trans_sid_tags = "a=href,area=href,frame=src,form=" ; URL rewriter does not rewrite absolute URLs by default. ; To enable rewrites for absolute pathes, target hosts must be specified ; at RUNTIME. i.e. use ini_set() ; <form> tags is special. PHP will check action attribute's URL regardless ; of session.trans_sid_tags setting. ; If no host is defined, HTTP_HOST will be used for allowed host. ; Example value: php.net,www.php.net,wiki.php.net ; Use "," for multiple hosts. No spaces are allowed. ; Default Value: "" ; Development Value: "" ; Production Value: "" ;session.trans_sid_hosts="" ; Define how many bits are stored in each character when converting ; the binary hash data to something readable. ; Possible values: ; 4 (4 bits: 0-9, a-f) ; 5 (5 bits: 0-9, a-v) ; 6 (6 bits: 0-9, a-z, A-Z, "-", ",") ; Default Value: 4 ; Development Value: 5 ; Production Value: 5 ; http://php.net/session.hash-bits-per-character session.sid_bits_per_character = 5 ; Enable upload progress tracking in $_SESSION ; Default Value: On ; Development Value: On ; Production Value: On ; http://php.net/session.upload-progress.enabled ;session.upload_progress.enabled = On ; Cleanup the progress information as soon as all POST data has been read ; (i.e. upload completed). ; Default Value: On ; Development Value: On ; Production Value: On ; http://php.net/session.upload-progress.cleanup ;session.upload_progress.cleanup = On ; A prefix used for the upload progress key in $_SESSION ; Default Value: "upload_progress_" ; Development Value: "upload_progress_" ; Production Value: "upload_progress_" ; http://php.net/session.upload-progress.prefix ;session.upload_progress.prefix = "upload_progress_" ; The index name (concatenated with the prefix) in $_SESSION ; containing the upload progress information ; Default Value: "PHP_SESSION_UPLOAD_PROGRESS" ; Development Value: "PHP_SESSION_UPLOAD_PROGRESS" ; Production Value: "PHP_SESSION_UPLOAD_PROGRESS" ; http://php.net/session.upload-progress.name ;session.upload_progress.name = "PHP_SESSION_UPLOAD_PROGRESS" ; How frequently the upload progress should be updated. ; Given either in percentages (per-file), or in bytes ; Default Value: "1%" ; Development Value: "1%" ; Production Value: "1%" ; http://php.net/session.upload-progress.freq ;session.upload_progress.freq = "1%" ; The minimum delay between updates, in seconds ; Default Value: 1 ; Development Value: 1 ; Production Value: 1 ; http://php.net/session.upload-progress.min-freq ;session.upload_progress.min_freq = "1" ; Only write session data when session data is changed. Enabled by default. ; http://php.net/session.lazy-write ;session.lazy_write = On [Assertion] ; Switch whether to compile assertions at all (to have no overhead at run-time) ; -1: Do not compile at all ; 0: Jump over assertion at run-time ; 1: Execute assertions ; Changing from or to a negative value is only possible in php.ini! (For turning assertions on and off at run-time, see assert.active, when zend.assertions = 1) ; Default Value: 1 ; Development Value: 1 ; Production Value: -1 ; http://php.net/zend.assertions zend.assertions = 1 ; Assert(expr); active by default. ; http://php.net/assert.active ;assert.active = On ; Throw an AssertationException on failed assertions ; http://php.net/assert.exception ;assert.exception = On ; Issue a PHP warning for each failed assertion. (Overridden by assert.exception if active) ; http://php.net/assert.warning ;assert.warning = On ; Don't bail out by default. ; http://php.net/assert.bail ;assert.bail = Off ; User-function to be called if an assertion fails. ; http://php.net/assert.callback ;assert.callback = 0 ; Eval the expression with current error_reporting(). Set to true if you want ; error_reporting(0) around the eval(). ; http://php.net/assert.quiet-eval ;assert.quiet_eval = 0 [COM] ; path to a file containing GUIDs, IIDs or filenames of files with TypeLibs ; http://php.net/com.typelib-file ;com.typelib_file = ; allow Distributed-COM calls ; http://php.net/com.allow-dcom ;com.allow_dcom = true ; autoregister constants of a components typlib on com_load() ; http://php.net/com.autoregister-typelib ;com.autoregister_typelib = true ; register constants casesensitive ; http://php.net/com.autoregister-casesensitive ;com.autoregister_casesensitive = false ; show warnings on duplicate constant registrations ; http://php.net/com.autoregister-verbose ;com.autoregister_verbose = true ; The default character set code-page to use when passing strings to and from COM objects. ; Default: system ANSI code page ;com.code_page= [mbstring] ; language for internal character representation. ; This affects mb_send_mail() and mbstring.detect_order. ; http://php.net/mbstring.language ;mbstring.language = Japanese ; Use of this INI entry is deprecated, use global internal_encoding instead. ; internal/script encoding. ; Some encoding cannot work as internal encoding. (e.g. SJIS, BIG5, ISO-2022-*) ; If empty, default_charset or internal_encoding or iconv.internal_encoding is used. ; The precedence is: default_charset < internal_encoding < iconv.internal_encoding ;mbstring.internal_encoding = ; Use of this INI entry is deprecated, use global input_encoding instead. ; http input encoding. ; mbstring.encoding_traslation = On is needed to use this setting. ; If empty, default_charset or input_encoding or mbstring.input is used. ; The precedence is: default_charset < intput_encoding < mbsting.http_input ; http://php.net/mbstring.http-input ;mbstring.http_input = ; Use of this INI entry is deprecated, use global output_encoding instead. ; http output encoding. ; mb_output_handler must be registered as output buffer to function. ; If empty, default_charset or output_encoding or mbstring.http_output is used. ; The precedence is: default_charset < output_encoding < mbstring.http_output ; To use an output encoding conversion, mbstring's output handler must be set ; otherwise output encoding conversion cannot be performed. ; http://php.net/mbstring.http-output ;mbstring.http_output = ; enable automatic encoding translation according to ; mbstring.internal_encoding setting. Input chars are ; converted to internal encoding by setting this to On. ; Note: Do _not_ use automatic encoding translation for ; portable libs/applications. ; http://php.net/mbstring.encoding-translation ;mbstring.encoding_translation = Off ; automatic encoding detection order. ; "auto" detect order is changed according to mbstring.language ; http://php.net/mbstring.detect-order ;mbstring.detect_order = auto ; substitute_character used when character cannot be converted ; one from another ; http://php.net/mbstring.substitute-character ;mbstring.substitute_character = none ; overload(replace) single byte functions by mbstring functions. ; mail(), ereg(), etc are overloaded by mb_send_mail(), mb_ereg(), ; etc. Possible values are 0,1,2,4 or combination of them. ; For example, 7 for overload everything. ; 0: No overload ; 1: Overload mail() function ; 2: Overload str*() functions ; 4: Overload ereg*() functions ; http://php.net/mbstring.func-overload ;mbstring.func_overload = 0 ; enable strict encoding detection. ; Default: Off ;mbstring.strict_detection = On ; This directive specifies the regex pattern of content types for which mb_output_handler() ; is activated. ; Default: mbstring.http_output_conv_mimetype=^(text/|application/xhtml\+xml) ;mbstring.http_output_conv_mimetype= [gd] ; Tell the jpeg decode to ignore warnings and try to create ; a gd image. The warning will then be displayed as notices ; disabled by default ; http://php.net/gd.jpeg-ignore-warning ;gd.jpeg_ignore_warning = 1 [exif] ; Exif UNICODE user comments are handled as UCS-2BE/UCS-2LE and JIS as JIS. ; With mbstring support this will automatically be converted into the encoding ; given by corresponding encode setting. When empty mbstring.internal_encoding ; is used. For the decode settings you can distinguish between motorola and ; intel byte order. A decode setting cannot be empty. ; http://php.net/exif.encode-unicode ;exif.encode_unicode = ISO-8859-15 ; http://php.net/exif.decode-unicode-motorola ;exif.decode_unicode_motorola = UCS-2BE ; http://php.net/exif.decode-unicode-intel ;exif.decode_unicode_intel = UCS-2LE ; http://php.net/exif.encode-jis ;exif.encode_jis = ; http://php.net/exif.decode-jis-motorola ;exif.decode_jis_motorola = JIS ; http://php.net/exif.decode-jis-intel ;exif.decode_jis_intel = JIS [Tidy] ; The path to a default tidy configuration file to use when using tidy ; http://php.net/tidy.default-config ;tidy.default_config = /usr/local/lib/php/default.tcfg ; Should tidy clean and repair output automatically? ; WARNING: Do not use this option if you are generating non-html content ; such as dynamic images ; http://php.net/tidy.clean-output tidy.clean_output = Off [soap] ; Enables or disables WSDL caching feature. ; http://php.net/soap.wsdl-cache-enabled soap.wsdl_cache_enabled=1 ; Sets the directory name where SOAP extension will put cache files. ; http://php.net/soap.wsdl-cache-dir soap.wsdl_cache_dir="/tmp" ; (time to live) Sets the number of second while cached file will be used ; instead of original one. ; http://php.net/soap.wsdl-cache-ttl soap.wsdl_cache_ttl=86400 ; Sets the size of the cache limit. (Max. number of WSDL files to cache) soap.wsdl_cache_limit = 5 [sysvshm] ; A default size of the shared memory segment ;sysvshm.init_mem = 10000 [ldap] ; Sets the maximum number of open links or -1 for unlimited. ldap.max_links = -1 [mcrypt] ; For more information about mcrypt settings see http://php.net/mcrypt-module-open ; Directory where to load mcrypt algorithms ; Default: Compiled in into libmcrypt (usually /usr/local/lib/libmcrypt) ;mcrypt.algorithms_dir= ; Directory where to load mcrypt modes ; Default: Compiled in into libmcrypt (usually /usr/local/lib/libmcrypt) ;mcrypt.modes_dir= [dba] ;dba.default_handler= [opcache] ; Determines if Zend OPCache is enabled opcache.enable=1 ; Determines if Zend OPCache is enabled for the CLI version of PHP opcache.enable_cli=0 ; The OPcache shared memory storage size. ;opcache.memory_consumption=128 ; The amount of memory for interned strings in Mbytes. ;opcache.interned_strings_buffer=8 ; The maximum number of keys (scripts) in the OPcache hash table. ; Only numbers between 200 and 1000000 are allowed. ;opcache.max_accelerated_files=10000 ; The maximum percentage of "wasted" memory until a restart is scheduled. ;opcache.max_wasted_percentage=5 ; When this directive is enabled, the OPcache appends the current working ; directory to the script key, thus eliminating possible collisions between ; files with the same name (basename). Disabling the directive improves ; performance, but may break existing applications. ;opcache.use_cwd=1 ; When disabled, you must reset the OPcache manually or restart the ; webserver for changes to the filesystem to take effect. opcache.validate_timestamps=1 ; How often (in seconds) to check file timestamps for changes to the shared ; memory storage allocation. ("1" means validate once per second, but only ; once per request. "0" means always validate) opcache.revalidate_freq=2 ; Enables or disables file search in include_path optimization ;opcache.revalidate_path=0 ; If disabled, all PHPDoc comments are dropped from the code to reduce the ; size of the optimized code. ;opcache.save_comments=1 ; If enabled, a fast shutdown sequence is used for the accelerated code ; Depending on the used Memory Manager this may cause some incompatibilities. opcache.fast_shutdown=1 ; Allow file existence override (file_exists, etc.) performance feature. ;opcache.enable_file_override=0 ; A bitmask, where each bit enables or disables the appropriate OPcache ; passes ;opcache.optimization_level=0xffffffff ;opcache.inherited_hack=1 ;opcache.dups_fix=0 ; The location of the OPcache blacklist file (wildcards allowed). ; Each OPcache blacklist file is a text file that holds the names of files ; that should not be accelerated. The file format is to add each filename ; to a new line. The filename may be a full path or just a file prefix ; (i.e., /var/www/x blacklists all the files and directories in /var/www ; that start with 'x'). Line starting with a ; are ignored (comments). ;opcache.blacklist_filename= ; Allows exclusion of large files from being cached. By default all files ; are cached. ;opcache.max_file_size=0 ; Check the cache checksum each N requests. ; The default value of "0" means that the checks are disabled. ;opcache.consistency_checks=0 ; How long to wait (in seconds) for a scheduled restart to begin if the cache ; is not being accessed. ;opcache.force_restart_timeout=180 ; OPcache error_log file name. Empty string assumes "stderr". ;opcache.error_log= ; All OPcache errors go to the Web server log. ; By default, only fatal errors (level 0) or errors (level 1) are logged. ; You can also enable warnings (level 2), info messages (level 3) or ; debug messages (level 4). ;opcache.log_verbosity_level=1 ; Preferred Shared Memory back-end. Leave empty and let the system decide. ;opcache.preferred_memory_model= ; Protect the shared memory from unexpected writing during script execution. ; Useful for internal debugging only. ;opcache.protect_memory=0 ; Allows calling OPcache API functions only from PHP scripts which path is ; started from specified string. The default "" means no restriction ;opcache.restrict_api= ; Mapping base of shared memory segments (for Windows only). All the PHP ; processes have to map shared memory into the same address space. This ; directive allows to manually fix the "Unable to reattach to base address" ; errors. ;opcache.mmap_base= ; Enables and sets the second level cache directory. ; It should improve performance when SHM memory is full, at server restart or ; SHM reset. The default "" disables file based caching. ;opcache.file_cache= ; Enables or disables opcode caching in shared memory. ;opcache.file_cache_only=0 ; Enables or disables checksum validation when script loaded from file cache. ;opcache.file_cache_consistency_checks=1 ; Implies opcache.file_cache_only=1 for a certain process that failed to ; reattach to the shared memory (for Windows only). Explicitly enabled file ; cache is required. ;opcache.file_cache_fallback=1 ; Enables or disables copying of PHP code (text segment) into HUGE PAGES. ; This should improve performance, but requires appropriate OS configuration. ;opcache.huge_code_pages=0 ; Validate cached file permissions. ;opcache.validate_permission=0 ; Prevent name collisions in chroot'ed environment. ;opcache.validate_root=0 [curl] ; A default value for the CURLOPT_CAINFO option. This is required to be an ; absolute path. ;curl.cainfo = [openssl] ; The location of a Certificate Authority (CA) file on the local filesystem ; to use when verifying the identity of SSL/TLS peers. Most users should ; not specify a value for this directive as PHP will attempt to use the ; OS-managed cert stores in its absence. If specified, this value may still ; be overridden on a per-stream basis via the "cafile" SSL stream context ; option. ;openssl.cafile= ; If openssl.cafile is not specified or if the CA file is not found, the ; directory pointed to by openssl.capath is searched for a suitable ; certificate. This value must be a correctly hashed certificate directory. ; Most users should not specify a value for this directive as PHP will ; attempt to use the OS-managed cert stores in its absence. If specified, ; this value may still be overridden on a per-stream basis via the "capath" ; SSL stream context option. ;openssl.capath= ; Local Variables: ; tab-width: 4 ; End:
INI
package redis_test import ( "bytes" "net" "testing" "time" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" "github.com/ainoya/fune/Godeps/_workspace/src/gopkg.in/redis.v3" ) var _ = Describe("Client", func() { var client *redis.Client BeforeEach(func() { client = redis.NewClient(&redis.Options{ Addr: redisAddr, }) }) AfterEach(func() { client.Close() }) It("should Stringer", func() { Expect(client.String()).To(Equal("Redis<:6380 db:0>")) }) It("should ping", func() { val, err := client.Ping().Result() Expect(err).NotTo(HaveOccurred()) Expect(val).To(Equal("PONG")) }) It("should support custom dialers", func() { custom := redis.NewClient(&redis.Options{ Dialer: func() (net.Conn, error) { return net.Dial("tcp", redisAddr) }, }) val, err := custom.Ping().Result() Expect(err).NotTo(HaveOccurred()) Expect(val).To(Equal("PONG")) Expect(custom.Close()).NotTo(HaveOccurred()) }) It("should close", func() { Expect(client.Close()).NotTo(HaveOccurred()) err := client.Ping().Err() Expect(err).To(HaveOccurred()) Expect(err).To(MatchError("redis: client is closed")) }) It("should close pubsub without closing the connection", func() { pubsub := client.PubSub() Expect(pubsub.Close()).NotTo(HaveOccurred()) _, err := pubsub.Receive() Expect(err).To(HaveOccurred()) Expect(err).To(MatchError("redis: client is closed")) Expect(client.Ping().Err()).NotTo(HaveOccurred()) }) It("should close multi without closing the connection", func() { multi := client.Multi() Expect(multi.Close()).NotTo(HaveOccurred()) _, err := multi.Exec(func() error { multi.Ping() return nil }) Expect(err).To(HaveOccurred()) Expect(err).To(MatchError("redis: client is closed")) Expect(client.Ping().Err()).NotTo(HaveOccurred()) }) It("should close pipeline without closing the connection", func() { pipeline := client.Pipeline() Expect(pipeline.Close()).NotTo(HaveOccurred()) pipeline.Ping() _, err := pipeline.Exec() Expect(err).To(HaveOccurred()) Expect(err).To(MatchError("redis: client is closed")) Expect(client.Ping().Err()).NotTo(HaveOccurred()) }) It("should close pubsub when client is closed", func() { pubsub := client.PubSub() Expect(client.Close()).NotTo(HaveOccurred()) Expect(pubsub.Close()).NotTo(HaveOccurred()) }) It("should close multi when client is closed", func() { multi := client.Multi() Expect(client.Close()).NotTo(HaveOccurred()) Expect(multi.Close()).NotTo(HaveOccurred()) }) It("should close pipeline when client is closed", func() { pipeline := client.Pipeline() Expect(client.Close()).NotTo(HaveOccurred()) Expect(pipeline.Close()).NotTo(HaveOccurred()) }) It("should support idle-timeouts", func() { idle := redis.NewClient(&redis.Options{ Addr: redisAddr, IdleTimeout: 100 * time.Microsecond, }) defer idle.Close() Expect(idle.Ping().Err()).NotTo(HaveOccurred()) time.Sleep(time.Millisecond) Expect(idle.Ping().Err()).NotTo(HaveOccurred()) }) It("should support DB selection", func() { db1 := redis.NewClient(&redis.Options{ Addr: redisAddr, DB: 1, }) defer db1.Close() Expect(db1.Get("key").Err()).To(Equal(redis.Nil)) Expect(db1.Set("key", "value", 0).Err()).NotTo(HaveOccurred()) Expect(client.Get("key").Err()).To(Equal(redis.Nil)) Expect(db1.Get("key").Val()).To(Equal("value")) Expect(db1.FlushDb().Err()).NotTo(HaveOccurred()) }) It("should support DB selection with read timeout (issue #135)", func() { for i := 0; i < 100; i++ { db1 := redis.NewClient(&redis.Options{ Addr: redisAddr, DB: 1, ReadTimeout: time.Nanosecond, }) err := db1.Ping().Err() Expect(err).To(HaveOccurred()) Expect(err.(net.Error).Timeout()).To(BeTrue()) } }) It("should retry command on network error", func() { Expect(client.Close()).NotTo(HaveOccurred()) client = redis.NewClient(&redis.Options{ Addr: redisAddr, MaxRetries: 1, }) // Put bad connection in the pool. cn, err := client.Pool().Get() Expect(err).NotTo(HaveOccurred()) cn.SetNetConn(newBadNetConn()) Expect(client.Pool().Put(cn)).NotTo(HaveOccurred()) err = client.Ping().Err() Expect(err).NotTo(HaveOccurred()) }) }) //------------------------------------------------------------------------------ func benchRedisClient() *redis.Client { client := redis.NewClient(&redis.Options{ Addr: ":6379", }) if err := client.FlushDb().Err(); err != nil { panic(err) } return client } func BenchmarkRedisPing(b *testing.B) { client := benchRedisClient() defer client.Close() b.ResetTimer() b.RunParallel(func(pb *testing.PB) { for pb.Next() { if err := client.Ping().Err(); err != nil { b.Fatal(err) } } }) } func BenchmarkRedisSet(b *testing.B) { client := benchRedisClient() defer client.Close() value := string(bytes.Repeat([]byte{'1'}, 10000)) b.ResetTimer() b.RunParallel(func(pb *testing.PB) { for pb.Next() { if err := client.Set("key", value, 0).Err(); err != nil { b.Fatal(err) } } }) } func BenchmarkRedisGetNil(b *testing.B) { client := benchRedisClient() defer client.Close() b.ResetTimer() b.RunParallel(func(pb *testing.PB) { for pb.Next() { if err := client.Get("key").Err(); err != redis.Nil { b.Fatal(err) } } }) } func benchmarkRedisSetGet(b *testing.B, size int) { client := benchRedisClient() defer client.Close() value := string(bytes.Repeat([]byte{'1'}, size)) b.ResetTimer() b.RunParallel(func(pb *testing.PB) { for pb.Next() { if err := client.Set("key", value, 0).Err(); err != nil { b.Fatal(err) } got, err := client.Get("key").Result() if err != nil { b.Fatal(err) } if got != value { b.Fatalf("got != value") } } }) } func BenchmarkRedisSetGet64Bytes(b *testing.B) { benchmarkRedisSetGet(b, 64) } func BenchmarkRedisSetGet1KB(b *testing.B) { benchmarkRedisSetGet(b, 1024) } func BenchmarkRedisSetGet10KB(b *testing.B) { benchmarkRedisSetGet(b, 10*1024) } func BenchmarkRedisSetGet1MB(b *testing.B) { benchmarkRedisSetGet(b, 1024*1024) } func BenchmarkRedisSetGetBytes(b *testing.B) { client := benchRedisClient() defer client.Close() value := bytes.Repeat([]byte{'1'}, 10000) b.ResetTimer() b.RunParallel(func(pb *testing.PB) { for pb.Next() { if err := client.Set("key", value, 0).Err(); err != nil { b.Fatal(err) } got, err := client.Get("key").Bytes() if err != nil { b.Fatal(err) } if !bytes.Equal(got, value) { b.Fatalf("got != value") } } }) } func BenchmarkRedisMGet(b *testing.B) { client := benchRedisClient() defer client.Close() if err := client.MSet("key1", "hello1", "key2", "hello2").Err(); err != nil { b.Fatal(err) } b.ResetTimer() b.RunParallel(func(pb *testing.PB) { for pb.Next() { if err := client.MGet("key1", "key2").Err(); err != nil { b.Fatal(err) } } }) } func BenchmarkSetExpire(b *testing.B) { client := benchRedisClient() defer client.Close() b.ResetTimer() b.RunParallel(func(pb *testing.PB) { for pb.Next() { if err := client.Set("key", "hello", 0).Err(); err != nil { b.Fatal(err) } if err := client.Expire("key", time.Second).Err(); err != nil { b.Fatal(err) } } }) } func BenchmarkPipeline(b *testing.B) { client := benchRedisClient() defer client.Close() b.ResetTimer() b.RunParallel(func(pb *testing.PB) { for pb.Next() { _, err := client.Pipelined(func(pipe *redis.Pipeline) error { pipe.Set("key", "hello", 0) pipe.Expire("key", time.Second) return nil }) if err != nil { b.Fatal(err) } } }) } func BenchmarkZAdd(b *testing.B) { client := benchRedisClient() defer client.Close() b.ResetTimer() b.RunParallel(func(pb *testing.PB) { for pb.Next() { if err := client.ZAdd("key", redis.Z{float64(1), "hello"}).Err(); err != nil { b.Fatal(err) } } }) }
Go
ghc -isrc src\Main.hs --make -o app
Batchfile
# Tools for initial digits stuff char2digit(c::Char) = c - '0' function first_digit(x::Real, alert::Bool = false) if x == 0 if alert warn("Received 0, returning 0") end return 0 end x = abs(x) # make sure it's positive while x < 1 x *= 10 end c = first(string(x)) return char2digit(c) end function first_counts(x::Array{T,1}) where {T<:Real} digs = map(first_digit, x) n = length(digs) counts = zeros(Int, 9) for d in digs if d != 0 counts[d] += 1 end end return counts end function first_hists(x::Array{T,1}) where {T<:Real} counts = first_counts(x) hist = zeros(9) S = sum(counts) for k = 1:9 hist[k] = counts[k] / S end return counts, hist end function report(x::Array{T,1}) where {T<:Real} counts, hist = first_hists(x) for k = 1:9 println( k, "\t", counts[k], "\t", round(hist[k] * 100, digits = 1), "%\t", log(10, k + 1) - log(10, k), ) end end function report_array(x::Array{T,1}) where {T<:Real} counts, hist = first_hists(x) A = Array(Any, (9, 3)) for k = 1:9 A[k, 1] = k A[k, 2] = counts[k] A[k, 3] = round(hist[k] * 100, digits = 2) end return A end function experiment() n = 1000 x = rand(n) println("Initial distribution") report(x) println("\n\n") sleep(1) count = 0 while count <= 1000 m = minimum(x) count += 1 if m < 1 x *= 100.0 end x = x .* rand(n) if count % 25 == 0 println("step = ", count) report(x) println("-------------------------------") sleep(0.1) end end end function digit_split(n::Int) map(char2digit, collect(string(n))) end # create a 9^d multiplication table function mult_table_old(d::Int) vals = Int[] for n = 10^(d-1):10^d-1 digs = digit_split(n) v = prod(digs) # println(digs, " --> ", v) if v != 0 push!(vals, v) end end return vals end function mult_table(d::Int) tic() counts = zeros(Int, 9) for n = 10^(d-1):10^d-1 digs = digit_split(n) v = prod(digs) if v != 0 d = first_digit(v) counts[d] += 1 end end toc() return counts end mult_report_old(d::Int) = report(mult_table(d)) function mult_report(d::Int) counts = mult_table(d) N = sum(counts) A = Array(Any, (9, 3)) for k = 1:9 A[k, 1] = k A[k, 2] = counts[k] A[k, 3] = round(100 * counts[k] / N, 2) end return A end
Julia